Skip to content

Commit b8b4150

Browse files
committed
Auto merge of #54911 - ljedrz:cleanup_codegen_llvm_top, r=michaelwoerister
Cleanup top-level codegen_llvm - improve allocations - improve common patterns - remove explicit returns - fix spelling & grammatical errors - whitespace & formatting improvements
2 parents a534216 + a0fc2e6 commit b8b4150

18 files changed

+189
-216
lines changed

src/librustc_codegen_llvm/abi.rs

+10-13
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ impl LlvmType for CastTarget {
150150
// Create list of fields in the main structure
151151
let mut args: Vec<_> =
152152
self.prefix.iter().flat_map(|option_kind| option_kind.map(
153-
|kind| Reg { kind: kind, size: self.prefix_chunk }.llvm_type(cx)))
153+
|kind| Reg { kind: kind, size: self.prefix_chunk }.llvm_type(cx)))
154154
.chain((0..rest_count).map(|_| rest_ll_unit))
155155
.collect();
156156

@@ -259,8 +259,7 @@ impl ArgTypeExt<'ll, 'tcx> for ArgType<'tcx, Ty<'tcx>> {
259259
}
260260

261261
pub trait FnTypeExt<'tcx> {
262-
fn of_instance(cx: &CodegenCx<'ll, 'tcx>, instance: &ty::Instance<'tcx>)
263-
-> Self;
262+
fn of_instance(cx: &CodegenCx<'ll, 'tcx>, instance: &ty::Instance<'tcx>) -> Self;
264263
fn new(cx: &CodegenCx<'ll, 'tcx>,
265264
sig: ty::FnSig<'tcx>,
266265
extra_args: &[Ty<'tcx>]) -> Self;
@@ -283,25 +282,24 @@ pub trait FnTypeExt<'tcx> {
283282
}
284283

285284
impl<'tcx> FnTypeExt<'tcx> for FnType<'tcx, Ty<'tcx>> {
286-
fn of_instance(cx: &CodegenCx<'ll, 'tcx>, instance: &ty::Instance<'tcx>)
287-
-> Self {
285+
fn of_instance(cx: &CodegenCx<'ll, 'tcx>, instance: &ty::Instance<'tcx>) -> Self {
288286
let fn_ty = instance.ty(cx.tcx);
289287
let sig = ty_fn_sig(cx, fn_ty);
290288
let sig = cx.tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
291289
FnType::new(cx, sig, &[])
292290
}
293291

294292
fn new(cx: &CodegenCx<'ll, 'tcx>,
295-
sig: ty::FnSig<'tcx>,
296-
extra_args: &[Ty<'tcx>]) -> Self {
293+
sig: ty::FnSig<'tcx>,
294+
extra_args: &[Ty<'tcx>]) -> Self {
297295
FnType::new_internal(cx, sig, extra_args, |ty, _| {
298296
ArgType::new(cx.layout_of(ty))
299297
})
300298
}
301299

302300
fn new_vtable(cx: &CodegenCx<'ll, 'tcx>,
303-
sig: ty::FnSig<'tcx>,
304-
extra_args: &[Ty<'tcx>]) -> Self {
301+
sig: ty::FnSig<'tcx>,
302+
extra_args: &[Ty<'tcx>]) -> Self {
305303
FnType::new_internal(cx, sig, extra_args, |ty, arg_idx| {
306304
let mut layout = cx.layout_of(ty);
307305
// Don't pass the vtable, it's not an argument of the virtual fn.
@@ -338,7 +336,7 @@ impl<'tcx> FnTypeExt<'tcx> for FnType<'tcx, Ty<'tcx>> {
338336
RustIntrinsic | PlatformIntrinsic |
339337
Rust | RustCall => Conv::C,
340338

341-
// It's the ABI's job to select this, not us.
339+
// It's the ABI's job to select this, not ours.
342340
System => bug!("system abi should be selected elsewhere"),
343341

344342
Stdcall => Conv::X86Stdcall,
@@ -697,14 +695,13 @@ impl<'tcx> FnTypeExt<'tcx> for FnType<'tcx, Ty<'tcx>> {
697695
// If the value is a boolean, the range is 0..2 and that ultimately
698696
// become 0..0 when the type becomes i1, which would be rejected
699697
// by the LLVM verifier.
700-
match scalar.value {
701-
layout::Int(..) if !scalar.is_bool() => {
698+
if let layout::Int(..) = scalar.value {
699+
if !scalar.is_bool() {
702700
let range = scalar.valid_range_exclusive(bx.cx);
703701
if range.start != range.end {
704702
bx.range_metadata(callsite, range);
705703
}
706704
}
707-
_ => {}
708705
}
709706
}
710707
for arg in &self.args {

src/librustc_codegen_llvm/allocator.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ pub(crate) unsafe fn codegen(tcx: TyCtxt, mods: &ModuleLlvm, kind: AllocatorKind
3333
let void = llvm::LLVMVoidTypeInContext(llcx);
3434

3535
for method in ALLOCATOR_METHODS {
36-
let mut args = Vec::new();
36+
let mut args = Vec::with_capacity(method.inputs.len());
3737
for ty in method.inputs.iter() {
3838
match *ty {
3939
AllocatorTy::Layout => {

src/librustc_codegen_llvm/attributes.rs

+11-10
Original file line numberDiff line numberDiff line change
@@ -94,9 +94,8 @@ pub fn set_probestack(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
9494
// Currently stack probes seem somewhat incompatible with the address
9595
// sanitizer. With asan we're already protected from stack overflow anyway
9696
// so we don't really need stack probes regardless.
97-
match cx.sess().opts.debugging_opts.sanitizer {
98-
Some(Sanitizer::Address) => return,
99-
_ => {}
97+
if let Some(Sanitizer::Address) = cx.sess().opts.debugging_opts.sanitizer {
98+
return
10099
}
101100

102101
// probestack doesn't play nice either with pgo-gen.
@@ -280,12 +279,14 @@ pub fn provide_extern(providers: &mut Providers) {
280279
// `NativeLibrary` internally contains information about
281280
// `#[link(wasm_import_module = "...")]` for example.
282281
let native_libs = tcx.native_libraries(cnum);
283-
let mut def_id_to_native_lib = FxHashMap();
284-
for lib in native_libs.iter() {
282+
283+
let def_id_to_native_lib = native_libs.iter().filter_map(|lib|
285284
if let Some(id) = lib.foreign_module {
286-
def_id_to_native_lib.insert(id, lib);
285+
Some((id, lib))
286+
} else {
287+
None
287288
}
288-
}
289+
).collect::<FxHashMap<_, _>>();
289290

290291
let mut ret = FxHashMap();
291292
for lib in tcx.foreign_modules(cnum).iter() {
@@ -296,10 +297,10 @@ pub fn provide_extern(providers: &mut Providers) {
296297
Some(s) => s,
297298
None => continue,
298299
};
299-
for id in lib.foreign_items.iter() {
300+
ret.extend(lib.foreign_items.iter().map(|id| {
300301
assert_eq!(id.krate, cnum);
301-
ret.insert(*id, module.to_string());
302-
}
302+
(*id, module.to_string())
303+
}));
303304
}
304305

305306
Lrc::new(ret)

src/librustc_codegen_llvm/base.rs

+32-31
Original file line numberDiff line numberDiff line change
@@ -213,8 +213,8 @@ pub fn unsized_info(
213213
vtable_ptr.llvm_type(cx))
214214
}
215215
_ => bug!("unsized_info: invalid unsizing {:?} -> {:?}",
216-
source,
217-
target),
216+
source,
217+
target),
218218
}
219219
}
220220

@@ -340,11 +340,11 @@ pub fn cast_shift_expr_rhs(
340340
}
341341

342342
fn cast_shift_rhs<'ll, F, G>(op: hir::BinOpKind,
343-
lhs: &'ll Value,
344-
rhs: &'ll Value,
345-
trunc: F,
346-
zext: G)
347-
-> &'ll Value
343+
lhs: &'ll Value,
344+
rhs: &'ll Value,
345+
trunc: F,
346+
zext: G)
347+
-> &'ll Value
348348
where F: FnOnce(&'ll Value, &'ll Type) -> &'ll Value,
349349
G: FnOnce(&'ll Value, &'ll Type) -> &'ll Value
350350
{
@@ -363,8 +363,8 @@ fn cast_shift_rhs<'ll, F, G>(op: hir::BinOpKind,
363363
if lhs_sz < rhs_sz {
364364
trunc(rhs, lhs_llty)
365365
} else if lhs_sz > rhs_sz {
366-
// FIXME (#1877: If shifting by negative
367-
// values becomes not undefined then this is wrong.
366+
// FIXME (#1877: If in the future shifting by negative
367+
// values is no longer undefined then this is wrong.
368368
zext(rhs, lhs_llty)
369369
} else {
370370
rhs
@@ -495,10 +495,8 @@ pub fn codegen_instance<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>, instance: Instance<'
495495
let sig = common::ty_fn_sig(cx, fn_ty);
496496
let sig = cx.tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
497497

498-
let lldecl = match cx.instances.borrow().get(&instance) {
499-
Some(&val) => val,
500-
None => bug!("Instance `{:?}` not already declared", instance)
501-
};
498+
let lldecl = cx.instances.borrow().get(&instance).cloned().unwrap_or_else(||
499+
bug!("Instance `{:?}` not already declared", instance));
502500

503501
cx.stats.borrow_mut().n_closures += 1;
504502

@@ -566,8 +564,8 @@ fn maybe_create_entry_wrapper(cx: &CodegenCx) {
566564
if declare::get_defined_value(cx, "main").is_some() {
567565
// FIXME: We should be smart and show a better diagnostic here.
568566
cx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
569-
.help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
570-
.emit();
567+
.help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
568+
.emit();
571569
cx.sess().abort_if_errors();
572570
bug!();
573571
}
@@ -736,9 +734,9 @@ fn determine_cgu_reuse<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
736734
}
737735

738736
pub fn codegen_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
739-
rx: mpsc::Receiver<Box<dyn Any + Send>>)
740-
-> OngoingCodegen {
741-
737+
rx: mpsc::Receiver<Box<dyn Any + Send>>)
738+
-> OngoingCodegen
739+
{
742740
check_for_rustc_errors_attr(tcx);
743741

744742
if let Some(true) = tcx.sess.opts.debugging_opts.thinlto {
@@ -803,8 +801,7 @@ pub fn codegen_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
803801

804802
// Run the monomorphization collector and partition the collected items into
805803
// codegen units.
806-
let codegen_units =
807-
tcx.collect_and_partition_mono_items(LOCAL_CRATE).1;
804+
let codegen_units = tcx.collect_and_partition_mono_items(LOCAL_CRATE).1;
808805
let codegen_units = (*codegen_units).clone();
809806

810807
// Force all codegen_unit queries so they are already either red or green
@@ -837,12 +834,7 @@ pub fn codegen_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
837834
.iter()
838835
.any(|(_, list)| {
839836
use rustc::middle::dependency_format::Linkage;
840-
list.iter().any(|linkage| {
841-
match linkage {
842-
Linkage::Dynamic => true,
843-
_ => false,
844-
}
845-
})
837+
list.iter().any(|&linkage| linkage == Linkage::Dynamic)
846838
});
847839
let allocator_module = if any_dynamic_crate {
848840
None
@@ -988,7 +980,7 @@ fn collect_and_partition_mono_items<'a, 'tcx>(
988980
if mode_string != "lazy" {
989981
let message = format!("Unknown codegen-item collection mode '{}'. \
990982
Falling back to 'lazy' mode.",
991-
mode_string);
983+
mode_string);
992984
tcx.sess.warn(&message);
993985
}
994986

@@ -1123,7 +1115,15 @@ impl CrateInfo {
11231115
info.load_wasm_imports(tcx, LOCAL_CRATE);
11241116
}
11251117

1126-
for &cnum in tcx.crates().iter() {
1118+
let crates = tcx.crates();
1119+
1120+
let n_crates = crates.len();
1121+
info.native_libraries.reserve(n_crates);
1122+
info.crate_name.reserve(n_crates);
1123+
info.used_crate_source.reserve(n_crates);
1124+
info.missing_lang_items.reserve(n_crates);
1125+
1126+
for &cnum in crates.iter() {
11271127
info.native_libraries.insert(cnum, tcx.native_libraries(cnum));
11281128
info.crate_name.insert(cnum, tcx.crate_name(cnum).to_string());
11291129
info.used_crate_source.insert(cnum, tcx.used_crate_source(cnum));
@@ -1165,11 +1165,12 @@ impl CrateInfo {
11651165
}
11661166

11671167
fn load_wasm_imports(&mut self, tcx: TyCtxt, cnum: CrateNum) {
1168-
for (&id, module) in tcx.wasm_import_module_map(cnum).iter() {
1168+
self.wasm_imports.extend(tcx.wasm_import_module_map(cnum).iter().map(|(&id, module)| {
11691169
let instance = Instance::mono(tcx, id);
11701170
let import_name = tcx.symbol_name(instance);
1171-
self.wasm_imports.insert(import_name.to_string(), module.clone());
1172-
}
1171+
1172+
(import_name.to_string(), module.clone())
1173+
}));
11731174
}
11741175
}
11751176

src/librustc_codegen_llvm/builder.rs

+9-9
Original file line numberDiff line numberDiff line change
@@ -110,10 +110,10 @@ impl Builder<'a, 'll, 'tcx> {
110110
}
111111
if self.cx.sess().count_llvm_insns() {
112112
*self.cx.stats
113-
.borrow_mut()
114-
.llvm_insns
115-
.entry(category.to_string())
116-
.or_insert(0) += 1;
113+
.borrow_mut()
114+
.llvm_insns
115+
.entry(category.to_string())
116+
.or_insert(0) += 1;
117117
}
118118
}
119119

@@ -735,9 +735,9 @@ impl Builder<'a, 'll, 'tcx> {
735735
}
736736

737737
pub fn inline_asm_call(&self, asm: *const c_char, cons: *const c_char,
738-
inputs: &[&'ll Value], output: &'ll Type,
739-
volatile: bool, alignstack: bool,
740-
dia: AsmDialect) -> Option<&'ll Value> {
738+
inputs: &[&'ll Value], output: &'ll Type,
739+
volatile: bool, alignstack: bool,
740+
dia: AsmDialect) -> Option<&'ll Value> {
741741
self.count_insn("inlineasm");
742742

743743
let volatile = if volatile { llvm::True }
@@ -1093,7 +1093,7 @@ impl Builder<'a, 'll, 'tcx> {
10931093
) -> &'ll Value {
10941094
unsafe {
10951095
llvm::LLVMRustBuildAtomicCmpXchg(self.llbuilder, dst, cmp, src,
1096-
order, failure_order, weak)
1096+
order, failure_order, weak)
10971097
}
10981098
}
10991099
pub fn atomic_rmw(
@@ -1194,7 +1194,7 @@ impl Builder<'a, 'll, 'tcx> {
11941194
})
11951195
.collect();
11961196

1197-
return Cow::Owned(casted_args);
1197+
Cow::Owned(casted_args)
11981198
}
11991199

12001200
pub fn lifetime_start(&self, ptr: &'ll Value, size: Size) {

src/librustc_codegen_llvm/common.rs

+6-9
Original file line numberDiff line numberDiff line change
@@ -336,16 +336,13 @@ pub fn langcall(tcx: TyCtxt,
336336
msg: &str,
337337
li: LangItem)
338338
-> DefId {
339-
match tcx.lang_items().require(li) {
340-
Ok(id) => id,
341-
Err(s) => {
342-
let msg = format!("{} {}", msg, s);
343-
match span {
344-
Some(span) => tcx.sess.span_fatal(span, &msg[..]),
345-
None => tcx.sess.fatal(&msg[..]),
346-
}
339+
tcx.lang_items().require(li).unwrap_or_else(|s| {
340+
let msg = format!("{} {}", msg, s);
341+
match span {
342+
Some(span) => tcx.sess.span_fatal(span, &msg[..]),
343+
None => tcx.sess.fatal(&msg[..]),
347344
}
348-
}
345+
})
349346
}
350347

351348
// To avoid UB from LLVM, these two functions mask RHS with an

src/librustc_codegen_llvm/consts.rs

+10-11
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ pub fn get_static(cx: &CodegenCx<'ll, '_>, def_id: DefId) -> &'ll Value {
124124
assert!(!defined_in_current_codegen_unit,
125125
"consts::get_static() should always hit the cache for \
126126
statics defined in the same CGU, but did not for `{:?}`",
127-
def_id);
127+
def_id);
128128

129129
let ty = instance.ty(cx.tcx);
130130
let sym = cx.tcx.symbol_name(instance).as_str();
@@ -249,14 +249,13 @@ fn check_and_apply_linkage(
249249
// extern "C" fn() from being non-null, so we can't just declare a
250250
// static and call it a day. Some linkages (like weak) will make it such
251251
// that the static actually has a null value.
252-
let llty2 = match ty.sty {
253-
ty::RawPtr(ref mt) => cx.layout_of(mt.ty).llvm_type(cx),
254-
_ => {
255-
if span.is_some() {
256-
cx.sess().span_fatal(span.unwrap(), "must have type `*const T` or `*mut T`")
257-
} else {
258-
bug!("must have type `*const T` or `*mut T`")
259-
}
252+
let llty2 = if let ty::RawPtr(ref mt) = ty.sty {
253+
cx.layout_of(mt.ty).llvm_type(cx)
254+
} else {
255+
if let Some(span) = span {
256+
cx.sess().span_fatal(span, "must have type `*const T` or `*mut T`")
257+
} else {
258+
bug!("must have type `*const T` or `*mut T`")
260259
}
261260
};
262261
unsafe {
@@ -273,9 +272,9 @@ fn check_and_apply_linkage(
273272
let mut real_name = "_rust_extern_with_linkage_".to_string();
274273
real_name.push_str(&sym);
275274
let g2 = declare::define_global(cx, &real_name, llty).unwrap_or_else(||{
276-
if span.is_some() {
275+
if let Some(span) = span {
277276
cx.sess().span_fatal(
278-
span.unwrap(),
277+
span,
279278
&format!("symbol `{}` is already defined", &sym)
280279
)
281280
} else {

0 commit comments

Comments
 (0)