Skip to content

Commit 6408162

Browse files
committed
Auto merge of #54864 - ljedrz:cleanup_codegen_llvm_back, r=Mark-Simulacrum
Cleanup codegen_llvm/back - improve allocations - use `Cow<'static, str>` where applicable - use `to_owned` instead of `to_string` with string literals - remove a redundant `continue` - possible minor speedup in logic - use `mem::replace` instead of `swap` where more concise - remove `'static` from consts - improve common patterns - remove explicit `return`s - whitespace & formatting fixes
2 parents 6e9b842 + 2f99d09 commit 6408162

File tree

9 files changed

+133
-175
lines changed

9 files changed

+133
-175
lines changed

Diff for: src/librustc_codegen_llvm/back/archive.rs

+14-19
Original file line numberDiff line numberDiff line change
@@ -83,15 +83,16 @@ impl<'a> ArchiveBuilder<'a> {
8383
if self.src_archive().is_none() {
8484
return Vec::new()
8585
}
86+
8687
let archive = self.src_archive.as_ref().unwrap().as_ref().unwrap();
87-
let ret = archive.iter()
88-
.filter_map(|child| child.ok())
89-
.filter(is_relevant_child)
90-
.filter_map(|child| child.name())
91-
.filter(|name| !self.removals.iter().any(|x| x == name))
92-
.map(|name| name.to_string())
93-
.collect();
94-
return ret;
88+
89+
archive.iter()
90+
.filter_map(|child| child.ok())
91+
.filter(is_relevant_child)
92+
.filter_map(|child| child.name())
93+
.filter(|name| !self.removals.iter().any(|x| x == name))
94+
.map(|name| name.to_owned())
95+
.collect()
9596
}
9697

9798
fn src_archive(&mut self) -> Option<&ArchiveRO> {
@@ -171,7 +172,7 @@ impl<'a> ArchiveBuilder<'a> {
171172
let name = file.file_name().unwrap().to_str().unwrap();
172173
self.additions.push(Addition::File {
173174
path: file.to_path_buf(),
174-
name_in_archive: name.to_string(),
175+
name_in_archive: name.to_owned(),
175176
});
176177
}
177178

@@ -184,13 +185,8 @@ impl<'a> ArchiveBuilder<'a> {
184185
/// Combine the provided files, rlibs, and native libraries into a single
185186
/// `Archive`.
186187
pub fn build(&mut self) {
187-
let kind = match self.llvm_archive_kind() {
188-
Ok(kind) => kind,
189-
Err(kind) => {
190-
self.config.sess.fatal(&format!("Don't know how to build archive of type: {}",
191-
kind));
192-
}
193-
};
188+
let kind = self.llvm_archive_kind().unwrap_or_else(|kind|
189+
self.config.sess.fatal(&format!("Don't know how to build archive of type: {}", kind)));
194190

195191
if let Err(e) = self.build_with_llvm(kind) {
196192
self.config.sess.fatal(&format!("failed to build archive: {}", e));
@@ -281,10 +277,9 @@ impl<'a> ArchiveBuilder<'a> {
281277
let ret = if r.into_result().is_err() {
282278
let err = llvm::LLVMRustGetLastError();
283279
let msg = if err.is_null() {
284-
"failed to write archive".to_string()
280+
"failed to write archive".into()
285281
} else {
286282
String::from_utf8_lossy(CStr::from_ptr(err).to_bytes())
287-
.into_owned()
288283
};
289284
Err(io::Error::new(io::ErrorKind::Other, msg))
290285
} else {
@@ -293,7 +288,7 @@ impl<'a> ArchiveBuilder<'a> {
293288
for member in members {
294289
llvm::LLVMRustArchiveMemberFree(member);
295290
}
296-
return ret
291+
ret
297292
}
298293
}
299294
}

Diff for: src/librustc_codegen_llvm/back/bytecode.rs

+9-9
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ use flate2::write::DeflateEncoder;
4242

4343
// This is the "magic number" expected at the beginning of a LLVM bytecode
4444
// object in an rlib.
45-
pub const RLIB_BYTECODE_OBJECT_MAGIC: &'static [u8] = b"RUST_OBJECT";
45+
pub const RLIB_BYTECODE_OBJECT_MAGIC: &[u8] = b"RUST_OBJECT";
4646

4747
// The version number this compiler will write to bytecode objects in rlibs
4848
pub const RLIB_BYTECODE_OBJECT_VERSION: u8 = 2;
@@ -106,39 +106,39 @@ pub struct DecodedBytecode<'a> {
106106
}
107107

108108
impl<'a> DecodedBytecode<'a> {
109-
pub fn new(data: &'a [u8]) -> Result<DecodedBytecode<'a>, String> {
109+
pub fn new(data: &'a [u8]) -> Result<DecodedBytecode<'a>, &'static str> {
110110
if !data.starts_with(RLIB_BYTECODE_OBJECT_MAGIC) {
111-
return Err("magic bytecode prefix not found".to_string())
111+
return Err("magic bytecode prefix not found")
112112
}
113113
let data = &data[RLIB_BYTECODE_OBJECT_MAGIC.len()..];
114114
if !data.starts_with(&[RLIB_BYTECODE_OBJECT_VERSION, 0, 0, 0]) {
115-
return Err("wrong version prefix found in bytecode".to_string())
115+
return Err("wrong version prefix found in bytecode")
116116
}
117117
let data = &data[4..];
118118
if data.len() < 4 {
119-
return Err("bytecode corrupted".to_string())
119+
return Err("bytecode corrupted")
120120
}
121121
let identifier_len = unsafe {
122122
u32::from_le(ptr::read_unaligned(data.as_ptr() as *const u32)) as usize
123123
};
124124
let data = &data[4..];
125125
if data.len() < identifier_len {
126-
return Err("bytecode corrupted".to_string())
126+
return Err("bytecode corrupted")
127127
}
128128
let identifier = match str::from_utf8(&data[..identifier_len]) {
129129
Ok(s) => s,
130-
Err(_) => return Err("bytecode corrupted".to_string())
130+
Err(_) => return Err("bytecode corrupted")
131131
};
132132
let data = &data[identifier_len..];
133133
if data.len() < 8 {
134-
return Err("bytecode corrupted".to_string())
134+
return Err("bytecode corrupted")
135135
}
136136
let bytecode_len = unsafe {
137137
u64::from_le(ptr::read_unaligned(data.as_ptr() as *const u64)) as usize
138138
};
139139
let data = &data[8..];
140140
if data.len() < bytecode_len {
141-
return Err("bytecode corrupted".to_string())
141+
return Err("bytecode corrupted")
142142
}
143143
let encoded_bytecode = &data[..bytecode_len];
144144

Diff for: src/librustc_codegen_llvm/back/link.rs

+20-32
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,8 @@ use std::str;
4747
use syntax::attr;
4848

4949
pub use rustc_codegen_utils::link::{find_crate_name, filename_for_input, default_output_for_target,
50-
invalid_output_for_target, out_filename, check_file_is_writeable,
51-
filename_for_metadata};
50+
invalid_output_for_target, filename_for_metadata,
51+
out_filename, check_file_is_writeable};
5252

5353
// The third parameter is for env vars, used on windows to set up the
5454
// path for MSVC to find its DLLs, and gcc to find its bundled
@@ -107,13 +107,10 @@ pub fn get_linker(sess: &Session, linker: &Path, flavor: LinkerFlavor) -> (PathB
107107
}
108108

109109
pub fn remove(sess: &Session, path: &Path) {
110-
match fs::remove_file(path) {
111-
Ok(..) => {}
112-
Err(e) => {
113-
sess.err(&format!("failed to remove {}: {}",
114-
path.display(),
115-
e));
116-
}
110+
if let Err(e) = fs::remove_file(path) {
111+
sess.err(&format!("failed to remove {}: {}",
112+
path.display(),
113+
e));
117114
}
118115
}
119116

@@ -147,9 +144,7 @@ pub(crate) fn link_binary(sess: &Session,
147144

148145
// Remove the temporary object file and metadata if we aren't saving temps
149146
if !sess.opts.cg.save_temps {
150-
if sess.opts.output_types.should_codegen() &&
151-
!preserve_objects_for_their_debuginfo(sess)
152-
{
147+
if sess.opts.output_types.should_codegen() && !preserve_objects_for_their_debuginfo(sess) {
153148
for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
154149
remove(sess, obj);
155150
}
@@ -186,7 +181,7 @@ fn preserve_objects_for_their_debuginfo(sess: &Session) -> bool {
186181
// the objects as they're losslessly contained inside the archives.
187182
let output_linked = sess.crate_types.borrow()
188183
.iter()
189-
.any(|x| *x != config::CrateType::Rlib && *x != config::CrateType::Staticlib);
184+
.any(|&x| x != config::CrateType::Rlib && x != config::CrateType::Staticlib);
190185
if !output_linked {
191186
return false
192187
}
@@ -270,7 +265,7 @@ pub(crate) fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum)
270265
// crates providing these functions don't participate in LTO (e.g.
271266
// no_builtins or compiler builtins crates).
272267
!sess.target.target.options.no_builtins &&
273-
(info.is_no_builtins.contains(&cnum) || info.compiler_builtins == Some(cnum))
268+
(info.compiler_builtins == Some(cnum) || info.is_no_builtins.contains(&cnum))
274269
}
275270

276271
fn link_binary_output(sess: &Session,
@@ -291,24 +286,19 @@ fn link_binary_output(sess: &Session,
291286
// final destination, with a `fs::rename` call. In order for the rename to
292287
// always succeed, the temporary file needs to be on the same filesystem,
293288
// which is why we create it inside the output directory specifically.
294-
let metadata_tmpdir = match TempFileBuilder::new()
289+
let metadata_tmpdir = TempFileBuilder::new()
295290
.prefix("rmeta")
296291
.tempdir_in(out_filename.parent().unwrap())
297-
{
298-
Ok(tmpdir) => tmpdir,
299-
Err(err) => sess.fatal(&format!("couldn't create a temp dir: {}", err)),
300-
};
292+
.unwrap_or_else(|err| sess.fatal(&format!("couldn't create a temp dir: {}", err)));
301293
let metadata = emit_metadata(sess, codegen_results, &metadata_tmpdir);
302294
if let Err(e) = fs::rename(metadata, &out_filename) {
303295
sess.fatal(&format!("failed to write {}: {}", out_filename.display(), e));
304296
}
305297
out_filenames.push(out_filename);
306298
}
307299

308-
let tmpdir = match TempFileBuilder::new().prefix("rustc").tempdir() {
309-
Ok(tmpdir) => tmpdir,
310-
Err(err) => sess.fatal(&format!("couldn't create a temp dir: {}", err)),
311-
};
300+
let tmpdir = TempFileBuilder::new().prefix("rustc").tempdir().unwrap_or_else(|err|
301+
sess.fatal(&format!("couldn't create a temp dir: {}", err)));
312302

313303
if outputs.outputs.should_codegen() {
314304
let out_filename = out_filename(sess, crate_type, outputs, crate_name);
@@ -342,7 +332,8 @@ fn archive_search_paths(sess: &Session) -> Vec<PathBuf> {
342332
sess.target_filesearch(PathKind::Native).for_each_lib_search_path(|path, _| {
343333
search.push(path.to_path_buf());
344334
});
345-
return search;
335+
336+
search
346337
}
347338

348339
fn archive_config<'a>(sess: &'a Session,
@@ -814,8 +805,8 @@ fn link_natively(sess: &Session,
814805
.unwrap_or_else(|_| {
815806
let mut x = "Non-UTF-8 output: ".to_string();
816807
x.extend(s.iter()
817-
.flat_map(|&b| ascii::escape_default(b))
818-
.map(|b| char::from_u32(b as u32).unwrap()));
808+
.flat_map(|&b| ascii::escape_default(b))
809+
.map(char::from));
819810
x
820811
})
821812
}
@@ -870,9 +861,8 @@ fn link_natively(sess: &Session,
870861
sess.opts.debuginfo != DebugInfo::None &&
871862
!preserve_objects_for_their_debuginfo(sess)
872863
{
873-
match Command::new("dsymutil").arg(out_filename).output() {
874-
Ok(..) => {}
875-
Err(e) => sess.fatal(&format!("failed to run dsymutil: {}", e)),
864+
if let Err(e) = Command::new("dsymutil").arg(out_filename).output() {
865+
sess.fatal(&format!("failed to run dsymutil: {}", e))
876866
}
877867
}
878868

@@ -1012,8 +1002,7 @@ fn exec_linker(sess: &Session, cmd: &mut Command, out_filename: &Path, tmpdir: &
10121002
// ensure the line is interpreted as one whole argument.
10131003
for c in self.arg.chars() {
10141004
match c {
1015-
'\\' |
1016-
' ' => write!(f, "\\{}", c)?,
1005+
'\\' | ' ' => write!(f, "\\{}", c)?,
10171006
c => write!(f, "{}", c)?,
10181007
}
10191008
}
@@ -1426,7 +1415,6 @@ fn add_upstream_rust_crates(cmd: &mut dyn Linker,
14261415
for f in archive.src_files() {
14271416
if f.ends_with(RLIB_BYTECODE_EXTENSION) || f == METADATA_FILENAME {
14281417
archive.remove_file(&f);
1429-
continue
14301418
}
14311419
}
14321420

Diff for: src/librustc_codegen_llvm/back/lto.rs

+19-26
Original file line numberDiff line numberDiff line change
@@ -205,11 +205,11 @@ pub(crate) fn run(cgcx: &CodegenContext,
205205
Lto::Fat => {
206206
assert!(cached_modules.is_empty());
207207
let opt_jobs = fat_lto(cgcx,
208-
&diag_handler,
209-
modules,
210-
upstream_modules,
211-
&symbol_white_list,
212-
timeline);
208+
&diag_handler,
209+
modules,
210+
upstream_modules,
211+
&symbol_white_list,
212+
timeline);
213213
opt_jobs.map(|opt_jobs| (opt_jobs, vec![]))
214214
}
215215
Lto::Thin |
@@ -296,7 +296,7 @@ fn fat_lto(cgcx: &CodegenContext,
296296
let data = bc_decoded.data();
297297
linker.add(&data).map_err(|()| {
298298
let msg = format!("failed to load bc of {:?}", name);
299-
write::llvm_err(&diag_handler, msg)
299+
write::llvm_err(&diag_handler, &msg)
300300
})
301301
})?;
302302
timeline.record(&format!("link {:?}", name));
@@ -310,8 +310,8 @@ fn fat_lto(cgcx: &CodegenContext,
310310
unsafe {
311311
let ptr = symbol_white_list.as_ptr();
312312
llvm::LLVMRustRunRestrictionPass(llmod,
313-
ptr as *const *const libc::c_char,
314-
symbol_white_list.len() as libc::size_t);
313+
ptr as *const *const libc::c_char,
314+
symbol_white_list.len() as libc::size_t);
315315
cgcx.save_temp_bitcode(&module, "lto.after-restriction");
316316
}
317317

@@ -490,7 +490,7 @@ fn thin_lto(cgcx: &CodegenContext,
490490
symbol_white_list.as_ptr(),
491491
symbol_white_list.len() as u32,
492492
).ok_or_else(|| {
493-
write::llvm_err(&diag_handler, "failed to prepare thin LTO context".to_string())
493+
write::llvm_err(&diag_handler, "failed to prepare thin LTO context")
494494
})?;
495495

496496
info!("thin LTO data created");
@@ -617,8 +617,7 @@ fn run_pass_manager(cgcx: &CodegenContext,
617617
llvm::LLVMRustAddPass(pm, pass.unwrap());
618618
}
619619

620-
time_ext(cgcx.time_passes, None, "LTO passes", ||
621-
llvm::LLVMRunPassManager(pm, llmod));
620+
time_ext(cgcx.time_passes, None, "LTO passes", || llvm::LLVMRunPassManager(pm, llmod));
622621

623622
llvm::LLVMDisposePassManager(pm);
624623
}
@@ -747,7 +746,7 @@ impl ThinModule {
747746
{
748747
let diag_handler = cgcx.create_diag_handler();
749748
let tm = (cgcx.tm_factory)().map_err(|e| {
750-
write::llvm_err(&diag_handler, e)
749+
write::llvm_err(&diag_handler, &e)
751750
})?;
752751

753752
// Right now the implementation we've got only works over serialized
@@ -762,7 +761,7 @@ impl ThinModule {
762761
self.data().len(),
763762
self.shared.module_names[self.idx].as_ptr(),
764763
).ok_or_else(|| {
765-
let msg = "failed to parse bitcode for thin LTO module".to_string();
764+
let msg = "failed to parse bitcode for thin LTO module";
766765
write::llvm_err(&diag_handler, msg)
767766
})? as *const _;
768767
let module = ModuleCodegen {
@@ -786,7 +785,7 @@ impl ThinModule {
786785
let mut cu2 = ptr::null_mut();
787786
llvm::LLVMRustThinLTOGetDICompileUnit(llmod, &mut cu1, &mut cu2);
788787
if !cu2.is_null() {
789-
let msg = "multiple source DICompileUnits found".to_string();
788+
let msg = "multiple source DICompileUnits found";
790789
return Err(write::llvm_err(&diag_handler, msg))
791790
}
792791

@@ -807,25 +806,25 @@ impl ThinModule {
807806
// You can find some more comments about these functions in the LLVM
808807
// bindings we've got (currently `PassWrapper.cpp`)
809808
if !llvm::LLVMRustPrepareThinLTORename(self.shared.data.0, llmod) {
810-
let msg = "failed to prepare thin LTO module".to_string();
809+
let msg = "failed to prepare thin LTO module";
811810
return Err(write::llvm_err(&diag_handler, msg))
812811
}
813812
cgcx.save_temp_bitcode(&module, "thin-lto-after-rename");
814813
timeline.record("rename");
815814
if !llvm::LLVMRustPrepareThinLTOResolveWeak(self.shared.data.0, llmod) {
816-
let msg = "failed to prepare thin LTO module".to_string();
815+
let msg = "failed to prepare thin LTO module";
817816
return Err(write::llvm_err(&diag_handler, msg))
818817
}
819818
cgcx.save_temp_bitcode(&module, "thin-lto-after-resolve");
820819
timeline.record("resolve");
821820
if !llvm::LLVMRustPrepareThinLTOInternalize(self.shared.data.0, llmod) {
822-
let msg = "failed to prepare thin LTO module".to_string();
821+
let msg = "failed to prepare thin LTO module";
823822
return Err(write::llvm_err(&diag_handler, msg))
824823
}
825824
cgcx.save_temp_bitcode(&module, "thin-lto-after-internalize");
826825
timeline.record("internalize");
827826
if !llvm::LLVMRustPrepareThinLTOImport(self.shared.data.0, llmod) {
828-
let msg = "failed to prepare thin LTO module".to_string();
827+
let msg = "failed to prepare thin LTO module";
829828
return Err(write::llvm_err(&diag_handler, msg))
830829
}
831830
cgcx.save_temp_bitcode(&module, "thin-lto-after-import");
@@ -920,12 +919,6 @@ impl ThinLTOImports {
920919
}
921920

922921
fn module_name_to_str(c_str: &CStr) -> &str {
923-
match c_str.to_str() {
924-
Ok(s) => s,
925-
Err(e) => {
926-
bug!("Encountered non-utf8 LLVM module name `{}`: {}",
927-
c_str.to_string_lossy(),
928-
e)
929-
}
930-
}
922+
c_str.to_str().unwrap_or_else(|e|
923+
bug!("Encountered non-utf8 LLVM module name `{}`: {}", c_str.to_string_lossy(), e))
931924
}

0 commit comments

Comments
 (0)