Skip to content

Commit

Permalink
Auto merge of #54911 - ljedrz:cleanup_codegen_llvm_top, r=michaelwoer…
Browse files Browse the repository at this point in the history
…ister

Cleanup top-level codegen_llvm

- improve allocations
- improve common patterns
- remove explicit returns
- fix spelling & grammatical errors
- whitespace & formatting improvements
  • Loading branch information
bors committed Oct 11, 2018
2 parents a534216 + a0fc2e6 commit b8b4150
Show file tree
Hide file tree
Showing 18 changed files with 189 additions and 216 deletions.
23 changes: 10 additions & 13 deletions src/librustc_codegen_llvm/abi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ impl LlvmType for CastTarget {
// Create list of fields in the main structure
let mut args: Vec<_> =
self.prefix.iter().flat_map(|option_kind| option_kind.map(
|kind| Reg { kind: kind, size: self.prefix_chunk }.llvm_type(cx)))
|kind| Reg { kind: kind, size: self.prefix_chunk }.llvm_type(cx)))
.chain((0..rest_count).map(|_| rest_ll_unit))
.collect();

Expand Down Expand Up @@ -259,8 +259,7 @@ impl ArgTypeExt<'ll, 'tcx> for ArgType<'tcx, Ty<'tcx>> {
}

pub trait FnTypeExt<'tcx> {
fn of_instance(cx: &CodegenCx<'ll, 'tcx>, instance: &ty::Instance<'tcx>)
-> Self;
fn of_instance(cx: &CodegenCx<'ll, 'tcx>, instance: &ty::Instance<'tcx>) -> Self;
fn new(cx: &CodegenCx<'ll, 'tcx>,
sig: ty::FnSig<'tcx>,
extra_args: &[Ty<'tcx>]) -> Self;
Expand All @@ -283,25 +282,24 @@ pub trait FnTypeExt<'tcx> {
}

impl<'tcx> FnTypeExt<'tcx> for FnType<'tcx, Ty<'tcx>> {
fn of_instance(cx: &CodegenCx<'ll, 'tcx>, instance: &ty::Instance<'tcx>)
-> Self {
fn of_instance(cx: &CodegenCx<'ll, 'tcx>, instance: &ty::Instance<'tcx>) -> Self {
let fn_ty = instance.ty(cx.tcx);
let sig = ty_fn_sig(cx, fn_ty);
let sig = cx.tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
FnType::new(cx, sig, &[])
}

fn new(cx: &CodegenCx<'ll, 'tcx>,
sig: ty::FnSig<'tcx>,
extra_args: &[Ty<'tcx>]) -> Self {
sig: ty::FnSig<'tcx>,
extra_args: &[Ty<'tcx>]) -> Self {
FnType::new_internal(cx, sig, extra_args, |ty, _| {
ArgType::new(cx.layout_of(ty))
})
}

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

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

Stdcall => Conv::X86Stdcall,
Expand Down Expand Up @@ -697,14 +695,13 @@ impl<'tcx> FnTypeExt<'tcx> for FnType<'tcx, Ty<'tcx>> {
// If the value is a boolean, the range is 0..2 and that ultimately
// become 0..0 when the type becomes i1, which would be rejected
// by the LLVM verifier.
match scalar.value {
layout::Int(..) if !scalar.is_bool() => {
if let layout::Int(..) = scalar.value {
if !scalar.is_bool() {
let range = scalar.valid_range_exclusive(bx.cx);
if range.start != range.end {
bx.range_metadata(callsite, range);
}
}
_ => {}
}
}
for arg in &self.args {
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_codegen_llvm/allocator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ pub(crate) unsafe fn codegen(tcx: TyCtxt, mods: &ModuleLlvm, kind: AllocatorKind
let void = llvm::LLVMVoidTypeInContext(llcx);

for method in ALLOCATOR_METHODS {
let mut args = Vec::new();
let mut args = Vec::with_capacity(method.inputs.len());
for ty in method.inputs.iter() {
match *ty {
AllocatorTy::Layout => {
Expand Down
21 changes: 11 additions & 10 deletions src/librustc_codegen_llvm/attributes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,8 @@ pub fn set_probestack(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
// Currently stack probes seem somewhat incompatible with the address
// sanitizer. With asan we're already protected from stack overflow anyway
// so we don't really need stack probes regardless.
match cx.sess().opts.debugging_opts.sanitizer {
Some(Sanitizer::Address) => return,
_ => {}
if let Some(Sanitizer::Address) = cx.sess().opts.debugging_opts.sanitizer {
return
}

// probestack doesn't play nice either with pgo-gen.
Expand Down Expand Up @@ -280,12 +279,14 @@ pub fn provide_extern(providers: &mut Providers) {
// `NativeLibrary` internally contains information about
// `#[link(wasm_import_module = "...")]` for example.
let native_libs = tcx.native_libraries(cnum);
let mut def_id_to_native_lib = FxHashMap();
for lib in native_libs.iter() {

let def_id_to_native_lib = native_libs.iter().filter_map(|lib|
if let Some(id) = lib.foreign_module {
def_id_to_native_lib.insert(id, lib);
Some((id, lib))
} else {
None
}
}
).collect::<FxHashMap<_, _>>();

let mut ret = FxHashMap();
for lib in tcx.foreign_modules(cnum).iter() {
Expand All @@ -296,10 +297,10 @@ pub fn provide_extern(providers: &mut Providers) {
Some(s) => s,
None => continue,
};
for id in lib.foreign_items.iter() {
ret.extend(lib.foreign_items.iter().map(|id| {
assert_eq!(id.krate, cnum);
ret.insert(*id, module.to_string());
}
(*id, module.to_string())
}));
}

Lrc::new(ret)
Expand Down
63 changes: 32 additions & 31 deletions src/librustc_codegen_llvm/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -213,8 +213,8 @@ pub fn unsized_info(
vtable_ptr.llvm_type(cx))
}
_ => bug!("unsized_info: invalid unsizing {:?} -> {:?}",
source,
target),
source,
target),
}
}

Expand Down Expand Up @@ -340,11 +340,11 @@ pub fn cast_shift_expr_rhs(
}

fn cast_shift_rhs<'ll, F, G>(op: hir::BinOpKind,
lhs: &'ll Value,
rhs: &'ll Value,
trunc: F,
zext: G)
-> &'ll Value
lhs: &'ll Value,
rhs: &'ll Value,
trunc: F,
zext: G)
-> &'ll Value
where F: FnOnce(&'ll Value, &'ll Type) -> &'ll Value,
G: FnOnce(&'ll Value, &'ll Type) -> &'ll Value
{
Expand All @@ -363,8 +363,8 @@ fn cast_shift_rhs<'ll, F, G>(op: hir::BinOpKind,
if lhs_sz < rhs_sz {
trunc(rhs, lhs_llty)
} else if lhs_sz > rhs_sz {
// FIXME (#1877: If shifting by negative
// values becomes not undefined then this is wrong.
// FIXME (#1877: If in the future shifting by negative
// values is no longer undefined then this is wrong.
zext(rhs, lhs_llty)
} else {
rhs
Expand Down Expand Up @@ -495,10 +495,8 @@ pub fn codegen_instance<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>, instance: Instance<'
let sig = common::ty_fn_sig(cx, fn_ty);
let sig = cx.tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);

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

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

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

pub fn codegen_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
rx: mpsc::Receiver<Box<dyn Any + Send>>)
-> OngoingCodegen {

rx: mpsc::Receiver<Box<dyn Any + Send>>)
-> OngoingCodegen
{
check_for_rustc_errors_attr(tcx);

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

// Run the monomorphization collector and partition the collected items into
// codegen units.
let codegen_units =
tcx.collect_and_partition_mono_items(LOCAL_CRATE).1;
let codegen_units = tcx.collect_and_partition_mono_items(LOCAL_CRATE).1;
let codegen_units = (*codegen_units).clone();

// Force all codegen_unit queries so they are already either red or green
Expand Down Expand Up @@ -837,12 +834,7 @@ pub fn codegen_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
.iter()
.any(|(_, list)| {
use rustc::middle::dependency_format::Linkage;
list.iter().any(|linkage| {
match linkage {
Linkage::Dynamic => true,
_ => false,
}
})
list.iter().any(|&linkage| linkage == Linkage::Dynamic)
});
let allocator_module = if any_dynamic_crate {
None
Expand Down Expand Up @@ -988,7 +980,7 @@ fn collect_and_partition_mono_items<'a, 'tcx>(
if mode_string != "lazy" {
let message = format!("Unknown codegen-item collection mode '{}'. \
Falling back to 'lazy' mode.",
mode_string);
mode_string);
tcx.sess.warn(&message);
}

Expand Down Expand Up @@ -1123,7 +1115,15 @@ impl CrateInfo {
info.load_wasm_imports(tcx, LOCAL_CRATE);
}

for &cnum in tcx.crates().iter() {
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));
Expand Down Expand Up @@ -1165,11 +1165,12 @@ impl CrateInfo {
}

fn load_wasm_imports(&mut self, tcx: TyCtxt, cnum: CrateNum) {
for (&id, module) in tcx.wasm_import_module_map(cnum).iter() {
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);
self.wasm_imports.insert(import_name.to_string(), module.clone());
}

(import_name.to_string(), module.clone())
}));
}
}

Expand Down
18 changes: 9 additions & 9 deletions src/librustc_codegen_llvm/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,10 +110,10 @@ impl Builder<'a, 'll, 'tcx> {
}
if self.cx.sess().count_llvm_insns() {
*self.cx.stats
.borrow_mut()
.llvm_insns
.entry(category.to_string())
.or_insert(0) += 1;
.borrow_mut()
.llvm_insns
.entry(category.to_string())
.or_insert(0) += 1;
}
}

Expand Down Expand Up @@ -735,9 +735,9 @@ impl Builder<'a, 'll, 'tcx> {
}

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

let volatile = if volatile { llvm::True }
Expand Down Expand Up @@ -1093,7 +1093,7 @@ impl Builder<'a, 'll, 'tcx> {
) -> &'ll Value {
unsafe {
llvm::LLVMRustBuildAtomicCmpXchg(self.llbuilder, dst, cmp, src,
order, failure_order, weak)
order, failure_order, weak)
}
}
pub fn atomic_rmw(
Expand Down Expand Up @@ -1194,7 +1194,7 @@ impl Builder<'a, 'll, 'tcx> {
})
.collect();

return Cow::Owned(casted_args);
Cow::Owned(casted_args)
}

pub fn lifetime_start(&self, ptr: &'ll Value, size: Size) {
Expand Down
15 changes: 6 additions & 9 deletions src/librustc_codegen_llvm/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -336,16 +336,13 @@ pub fn langcall(tcx: TyCtxt,
msg: &str,
li: LangItem)
-> DefId {
match tcx.lang_items().require(li) {
Ok(id) => id,
Err(s) => {
let msg = format!("{} {}", msg, s);
match span {
Some(span) => tcx.sess.span_fatal(span, &msg[..]),
None => tcx.sess.fatal(&msg[..]),
}
tcx.lang_items().require(li).unwrap_or_else(|s| {
let msg = format!("{} {}", msg, s);
match span {
Some(span) => tcx.sess.span_fatal(span, &msg[..]),
None => tcx.sess.fatal(&msg[..]),
}
}
})
}

// To avoid UB from LLVM, these two functions mask RHS with an
Expand Down
21 changes: 10 additions & 11 deletions src/librustc_codegen_llvm/consts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ pub fn get_static(cx: &CodegenCx<'ll, '_>, def_id: DefId) -> &'ll Value {
assert!(!defined_in_current_codegen_unit,
"consts::get_static() should always hit the cache for \
statics defined in the same CGU, but did not for `{:?}`",
def_id);
def_id);

let ty = instance.ty(cx.tcx);
let sym = cx.tcx.symbol_name(instance).as_str();
Expand Down Expand Up @@ -249,14 +249,13 @@ fn check_and_apply_linkage(
// extern "C" fn() from being non-null, so we can't just declare a
// static and call it a day. Some linkages (like weak) will make it such
// that the static actually has a null value.
let llty2 = match ty.sty {
ty::RawPtr(ref mt) => cx.layout_of(mt.ty).llvm_type(cx),
_ => {
if span.is_some() {
cx.sess().span_fatal(span.unwrap(), "must have type `*const T` or `*mut T`")
} else {
bug!("must have type `*const T` or `*mut T`")
}
let llty2 = if let ty::RawPtr(ref mt) = ty.sty {
cx.layout_of(mt.ty).llvm_type(cx)
} else {
if let Some(span) = span {
cx.sess().span_fatal(span, "must have type `*const T` or `*mut T`")
} else {
bug!("must have type `*const T` or `*mut T`")
}
};
unsafe {
Expand All @@ -273,9 +272,9 @@ fn check_and_apply_linkage(
let mut real_name = "_rust_extern_with_linkage_".to_string();
real_name.push_str(&sym);
let g2 = declare::define_global(cx, &real_name, llty).unwrap_or_else(||{
if span.is_some() {
if let Some(span) = span {
cx.sess().span_fatal(
span.unwrap(),
span,
&format!("symbol `{}` is already defined", &sym)
)
} else {
Expand Down
Loading

0 comments on commit b8b4150

Please sign in to comment.