1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Translate the completed AST to the LLVM IR.
13 //! Some functions here, such as trans_block and trans_expr, return a value --
14 //! the result of the translation to LLVM -- while others, such as trans_fn
15 //! and trans_item, are called only for the side effect of adding a
16 //! particular definition to the LLVM IR output we're producing.
18 //! Hopefully useful general knowledge about trans:
20 //! * There's no way to find out the Ty type of a ValueRef. Doing so
21 //! would be "trying to get the eggs out of an omelette" (credit:
22 //! pcwalton). You can, instead, find out its TypeRef by calling val_ty,
23 //! but one TypeRef corresponds to many `Ty`s; for instance, tup(int, int,
24 //! int) and rec(x=int, y=int, z=int) will have the same TypeRef.
26 use super::ModuleLlvm;
27 use super::ModuleSource;
28 use super::ModuleTranslation;
29 use super::ModuleKind;
31 use assert_module_sources;
33 use back::linker::LinkerInfo;
34 use back::symbol_export::{self, ExportedSymbols};
35 use back::write::{self, OngoingCrateTranslation};
36 use llvm::{ContextRef, Linkage, ModuleRef, ValueRef, Vector, get_param};
39 use rustc::hir::def_id::LOCAL_CRATE;
40 use rustc::middle::lang_items::StartFnLangItem;
41 use rustc::middle::cstore::EncodedMetadata;
42 use rustc::ty::{self, Ty, TyCtxt};
43 use rustc::dep_graph::AssertDepGraphSafe;
44 use rustc::middle::cstore::LinkMeta;
45 use rustc::hir::map as hir_map;
46 use rustc::util::common::time;
47 use rustc::session::config::{self, NoDebugInfo, OutputFilenames, OutputType};
48 use rustc::session::Session;
49 use rustc_incremental::{self, IncrementalHashesMap};
52 use mir::lvalue::LvalueRef;
56 use common::{C_bool, C_bytes_in_context, C_i32, C_uint};
57 use collector::{self, TransItemCollectionMode};
58 use common::{C_struct_in_context, C_u64, C_undef, C_array};
59 use common::CrateContext;
60 use common::{type_is_zero_size, val_ty};
63 use context::{self, LocalCrateContext, SharedCrateContext, Stats};
69 use monomorphize::{self, Instance};
70 use partitioning::{self, PartitioningStrategy, CodegenUnit};
71 use symbol_names_test;
72 use trans_item::{TransItem, DefPathBasedNames};
76 use rustc::util::nodemap::{NodeSet, FxHashMap, FxHashSet};
79 use std::ffi::{CStr, CString};
88 use mir::lvalue::Alignment;
90 pub struct StatRecorder<'a, 'tcx: 'a> {
91 ccx: &'a CrateContext<'a, 'tcx>,
96 impl<'a, 'tcx> StatRecorder<'a, 'tcx> {
97 pub fn new(ccx: &'a CrateContext<'a, 'tcx>, name: String) -> StatRecorder<'a, 'tcx> {
98 let istart = ccx.stats().n_llvm_insns.get();
107 impl<'a, 'tcx> Drop for StatRecorder<'a, 'tcx> {
109 if self.ccx.sess().trans_stats() {
110 let iend = self.ccx.stats().n_llvm_insns.get();
111 self.ccx.stats().fn_stats.borrow_mut()
112 .push((self.name.take().unwrap(), iend - self.istart));
113 self.ccx.stats().n_fns.set(self.ccx.stats().n_fns.get() + 1);
114 // Reset LLVM insn count to avoid compound costs.
115 self.ccx.stats().n_llvm_insns.set(self.istart);
120 pub fn get_meta(bcx: &Builder, fat_ptr: ValueRef) -> ValueRef {
121 bcx.struct_gep(fat_ptr, abi::FAT_PTR_EXTRA)
124 pub fn get_dataptr(bcx: &Builder, fat_ptr: ValueRef) -> ValueRef {
125 bcx.struct_gep(fat_ptr, abi::FAT_PTR_ADDR)
128 pub fn bin_op_to_icmp_predicate(op: hir::BinOp_,
130 -> llvm::IntPredicate {
132 hir::BiEq => llvm::IntEQ,
133 hir::BiNe => llvm::IntNE,
134 hir::BiLt => if signed { llvm::IntSLT } else { llvm::IntULT },
135 hir::BiLe => if signed { llvm::IntSLE } else { llvm::IntULE },
136 hir::BiGt => if signed { llvm::IntSGT } else { llvm::IntUGT },
137 hir::BiGe => if signed { llvm::IntSGE } else { llvm::IntUGE },
139 bug!("comparison_op_to_icmp_predicate: expected comparison operator, \
146 pub fn bin_op_to_fcmp_predicate(op: hir::BinOp_) -> llvm::RealPredicate {
148 hir::BiEq => llvm::RealOEQ,
149 hir::BiNe => llvm::RealUNE,
150 hir::BiLt => llvm::RealOLT,
151 hir::BiLe => llvm::RealOLE,
152 hir::BiGt => llvm::RealOGT,
153 hir::BiGe => llvm::RealOGE,
155 bug!("comparison_op_to_fcmp_predicate: expected comparison operator, \
162 pub fn compare_simd_types<'a, 'tcx>(
163 bcx: &Builder<'a, 'tcx>,
170 let signed = match t.sty {
172 let cmp = bin_op_to_fcmp_predicate(op);
173 return bcx.sext(bcx.fcmp(cmp, lhs, rhs), ret_ty);
175 ty::TyUint(_) => false,
176 ty::TyInt(_) => true,
177 _ => bug!("compare_simd_types: invalid SIMD type"),
180 let cmp = bin_op_to_icmp_predicate(op, signed);
181 // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
182 // to get the correctly sized type. This will compile to a single instruction
183 // once the IR is converted to assembly if the SIMD instruction is supported
184 // by the target architecture.
185 bcx.sext(bcx.icmp(cmp, lhs, rhs), ret_ty)
188 /// Retrieve the information we are losing (making dynamic) in an unsizing
191 /// The `old_info` argument is a bit funny. It is intended for use
192 /// in an upcast, where the new vtable for an object will be drived
193 /// from the old one.
194 pub fn unsized_info<'ccx, 'tcx>(ccx: &CrateContext<'ccx, 'tcx>,
197 old_info: Option<ValueRef>)
199 let (source, target) = ccx.tcx().struct_lockstep_tails(source, target);
200 match (&source.sty, &target.sty) {
201 (&ty::TyArray(_, len), &ty::TySlice(_)) => C_uint(ccx, len),
202 (&ty::TyDynamic(..), &ty::TyDynamic(..)) => {
203 // For now, upcasts are limited to changes in marker
204 // traits, and hence never actually require an actual
205 // change to the vtable.
206 old_info.expect("unsized_info: missing old info for trait upcast")
208 (_, &ty::TyDynamic(ref data, ..)) => {
209 consts::ptrcast(meth::get_vtable(ccx, source, data.principal()),
210 Type::vtable_ptr(ccx))
212 _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}",
218 /// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer.
219 pub fn unsize_thin_ptr<'a, 'tcx>(
220 bcx: &Builder<'a, 'tcx>,
224 ) -> (ValueRef, ValueRef) {
225 debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
226 match (&src_ty.sty, &dst_ty.sty) {
227 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
228 &ty::TyRef(_, ty::TypeAndMut { ty: b, .. })) |
229 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
230 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) |
231 (&ty::TyRawPtr(ty::TypeAndMut { ty: a, .. }),
232 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) => {
233 assert!(bcx.ccx.shared().type_is_sized(a));
234 let ptr_ty = type_of::in_memory_type_of(bcx.ccx, b).ptr_to();
235 (bcx.pointercast(src, ptr_ty), unsized_info(bcx.ccx, a, b, None))
237 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
238 let (a, b) = (src_ty.boxed_ty(), dst_ty.boxed_ty());
239 assert!(bcx.ccx.shared().type_is_sized(a));
240 let ptr_ty = type_of::in_memory_type_of(bcx.ccx, b).ptr_to();
241 (bcx.pointercast(src, ptr_ty), unsized_info(bcx.ccx, a, b, None))
243 _ => bug!("unsize_thin_ptr: called on bad types"),
247 /// Coerce `src`, which is a reference to a value of type `src_ty`,
248 /// to a value of type `dst_ty` and store the result in `dst`
249 pub fn coerce_unsized_into<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
250 src: &LvalueRef<'tcx>,
251 dst: &LvalueRef<'tcx>) {
252 let src_ty = src.ty.to_ty(bcx.tcx());
253 let dst_ty = dst.ty.to_ty(bcx.tcx());
254 let coerce_ptr = || {
255 let (base, info) = if common::type_is_fat_ptr(bcx.ccx, src_ty) {
256 // fat-ptr to fat-ptr unsize preserves the vtable
257 // i.e. &'a fmt::Debug+Send => &'a fmt::Debug
258 // So we need to pointercast the base to ensure
259 // the types match up.
260 let (base, info) = load_fat_ptr(bcx, src.llval, src.alignment, src_ty);
261 let llcast_ty = type_of::fat_ptr_base_ty(bcx.ccx, dst_ty);
262 let base = bcx.pointercast(base, llcast_ty);
265 let base = load_ty(bcx, src.llval, src.alignment, src_ty);
266 unsize_thin_ptr(bcx, base, src_ty, dst_ty)
268 store_fat_ptr(bcx, base, info, dst.llval, dst.alignment, dst_ty);
270 match (&src_ty.sty, &dst_ty.sty) {
271 (&ty::TyRef(..), &ty::TyRef(..)) |
272 (&ty::TyRef(..), &ty::TyRawPtr(..)) |
273 (&ty::TyRawPtr(..), &ty::TyRawPtr(..)) => {
276 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
280 (&ty::TyAdt(def_a, substs_a), &ty::TyAdt(def_b, substs_b)) => {
281 assert_eq!(def_a, def_b);
283 let src_fields = def_a.variants[0].fields.iter().map(|f| {
284 monomorphize::field_ty(bcx.tcx(), substs_a, f)
286 let dst_fields = def_b.variants[0].fields.iter().map(|f| {
287 monomorphize::field_ty(bcx.tcx(), substs_b, f)
290 let iter = src_fields.zip(dst_fields).enumerate();
291 for (i, (src_fty, dst_fty)) in iter {
292 if type_is_zero_size(bcx.ccx, dst_fty) {
296 let (src_f, src_f_align) = src.trans_field_ptr(bcx, i);
297 let (dst_f, dst_f_align) = dst.trans_field_ptr(bcx, i);
298 if src_fty == dst_fty {
299 memcpy_ty(bcx, dst_f, src_f, src_fty, None);
303 &LvalueRef::new_sized_ty(src_f, src_fty, src_f_align),
304 &LvalueRef::new_sized_ty(dst_f, dst_fty, dst_f_align)
309 _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}",
315 pub fn cast_shift_expr_rhs(
316 cx: &Builder, op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef
318 cast_shift_rhs(op, lhs, rhs, |a, b| cx.trunc(a, b), |a, b| cx.zext(a, b))
321 pub fn cast_shift_const_rhs(op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
325 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
326 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
329 fn cast_shift_rhs<F, G>(op: hir::BinOp_,
335 where F: FnOnce(ValueRef, Type) -> ValueRef,
336 G: FnOnce(ValueRef, Type) -> ValueRef
338 // Shifts may have any size int on the rhs
340 let mut rhs_llty = val_ty(rhs);
341 let mut lhs_llty = val_ty(lhs);
342 if rhs_llty.kind() == Vector {
343 rhs_llty = rhs_llty.element_type()
345 if lhs_llty.kind() == Vector {
346 lhs_llty = lhs_llty.element_type()
348 let rhs_sz = rhs_llty.int_width();
349 let lhs_sz = lhs_llty.int_width();
352 } else if lhs_sz > rhs_sz {
353 // FIXME (#1877: If shifting by negative
354 // values becomes not undefined then this is wrong.
364 /// Returns whether this session's target will use SEH-based unwinding.
366 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
367 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
368 /// 64-bit MinGW) instead of "full SEH".
369 pub fn wants_msvc_seh(sess: &Session) -> bool {
370 sess.target.target.options.is_like_msvc
373 pub fn call_assume<'a, 'tcx>(b: &Builder<'a, 'tcx>, val: ValueRef) {
374 let assume_intrinsic = b.ccx.get_intrinsic("llvm.assume");
375 b.call(assume_intrinsic, &[val], None);
378 /// Helper for loading values from memory. Does the necessary conversion if the in-memory type
379 /// differs from the type used for SSA values. Also handles various special cases where the type
380 /// gives us better information about what we are loading.
381 pub fn load_ty<'a, 'tcx>(b: &Builder<'a, 'tcx>, ptr: ValueRef,
382 alignment: Alignment, t: Ty<'tcx>) -> ValueRef {
384 if type_is_zero_size(ccx, t) {
385 return C_undef(type_of::type_of(ccx, t));
389 let global = llvm::LLVMIsAGlobalVariable(ptr);
390 if !global.is_null() && llvm::LLVMIsGlobalConstant(global) == llvm::True {
391 let val = llvm::LLVMGetInitializer(global);
394 return llvm::LLVMConstTrunc(val, Type::i1(ccx).to_ref());
402 b.trunc(b.load_range_assert(ptr, 0, 2, llvm::False, alignment.to_align()),
404 } else if t.is_char() {
405 // a char is a Unicode codepoint, and so takes values from 0
406 // to 0x10FFFF inclusive only.
407 b.load_range_assert(ptr, 0, 0x10FFFF + 1, llvm::False, alignment.to_align())
408 } else if (t.is_region_ptr() || t.is_box() || t.is_fn())
409 && !common::type_is_fat_ptr(ccx, t)
411 b.load_nonnull(ptr, alignment.to_align())
413 b.load(ptr, alignment.to_align())
417 /// Helper for storing values in memory. Does the necessary conversion if the in-memory type
418 /// differs from the type used for SSA values.
419 pub fn store_ty<'a, 'tcx>(cx: &Builder<'a, 'tcx>, v: ValueRef, dst: ValueRef,
420 dst_align: Alignment, t: Ty<'tcx>) {
421 debug!("store_ty: {:?} : {:?} <- {:?}", Value(dst), t, Value(v));
423 if common::type_is_fat_ptr(cx.ccx, t) {
424 let lladdr = cx.extract_value(v, abi::FAT_PTR_ADDR);
425 let llextra = cx.extract_value(v, abi::FAT_PTR_EXTRA);
426 store_fat_ptr(cx, lladdr, llextra, dst, dst_align, t);
428 cx.store(from_immediate(cx, v), dst, dst_align.to_align());
432 pub fn store_fat_ptr<'a, 'tcx>(cx: &Builder<'a, 'tcx>,
436 dst_align: Alignment,
438 // FIXME: emit metadata
439 cx.store(data, get_dataptr(cx, dst), dst_align.to_align());
440 cx.store(extra, get_meta(cx, dst), dst_align.to_align());
443 pub fn load_fat_ptr<'a, 'tcx>(
444 b: &Builder<'a, 'tcx>, src: ValueRef, alignment: Alignment, t: Ty<'tcx>
445 ) -> (ValueRef, ValueRef) {
446 let ptr = get_dataptr(b, src);
447 let ptr = if t.is_region_ptr() || t.is_box() {
448 b.load_nonnull(ptr, alignment.to_align())
450 b.load(ptr, alignment.to_align())
453 let meta = get_meta(b, src);
454 let meta_ty = val_ty(meta);
455 // If the 'meta' field is a pointer, it's a vtable, so use load_nonnull
457 let meta = if meta_ty.element_type().kind() == llvm::TypeKind::Pointer {
458 b.load_nonnull(meta, None)
466 pub fn from_immediate(bcx: &Builder, val: ValueRef) -> ValueRef {
467 if val_ty(val) == Type::i1(bcx.ccx) {
468 bcx.zext(val, Type::i8(bcx.ccx))
474 pub fn to_immediate(bcx: &Builder, val: ValueRef, ty: Ty) -> ValueRef {
476 bcx.trunc(val, Type::i1(bcx.ccx))
482 pub enum Lifetime { Start, End }
485 // If LLVM lifetime intrinsic support is enabled (i.e. optimizations
486 // on), and `ptr` is nonzero-sized, then extracts the size of `ptr`
487 // and the intrinsic for `lt` and passes them to `emit`, which is in
488 // charge of generating code to call the passed intrinsic on whatever
489 // block of generated code is targetted for the intrinsic.
491 // If LLVM lifetime intrinsic support is disabled (i.e. optimizations
492 // off) or `ptr` is zero-sized, then no-op (does not call `emit`).
493 pub fn call(self, b: &Builder, ptr: ValueRef) {
494 if b.ccx.sess().opts.optimize == config::OptLevel::No {
498 let size = machine::llsize_of_alloc(b.ccx, val_ty(ptr).element_type());
503 let lifetime_intrinsic = b.ccx.get_intrinsic(match self {
504 Lifetime::Start => "llvm.lifetime.start",
505 Lifetime::End => "llvm.lifetime.end"
508 let ptr = b.pointercast(ptr, Type::i8p(b.ccx));
509 b.call(lifetime_intrinsic, &[C_u64(b.ccx, size), ptr], None);
513 pub fn call_memcpy<'a, 'tcx>(b: &Builder<'a, 'tcx>,
519 let ptr_width = &ccx.sess().target.target.target_pointer_width;
520 let key = format!("llvm.memcpy.p0i8.p0i8.i{}", ptr_width);
521 let memcpy = ccx.get_intrinsic(&key);
522 let src_ptr = b.pointercast(src, Type::i8p(ccx));
523 let dst_ptr = b.pointercast(dst, Type::i8p(ccx));
524 let size = b.intcast(n_bytes, ccx.int_type(), false);
525 let align = C_i32(ccx, align as i32);
526 let volatile = C_bool(ccx, false);
527 b.call(memcpy, &[dst_ptr, src_ptr, size, align, volatile], None);
530 pub fn memcpy_ty<'a, 'tcx>(
531 bcx: &Builder<'a, 'tcx>,
539 let size = ccx.size_of(t);
544 let align = align.unwrap_or_else(|| ccx.align_of(t));
545 call_memcpy(bcx, dst, src, C_uint(ccx, size), align);
548 pub fn call_memset<'a, 'tcx>(b: &Builder<'a, 'tcx>,
553 volatile: bool) -> ValueRef {
554 let ptr_width = &b.ccx.sess().target.target.target_pointer_width;
555 let intrinsic_key = format!("llvm.memset.p0i8.i{}", ptr_width);
556 let llintrinsicfn = b.ccx.get_intrinsic(&intrinsic_key);
557 let volatile = C_bool(b.ccx, volatile);
558 b.call(llintrinsicfn, &[ptr, fill_byte, size, align, volatile], None)
561 pub fn trans_instance<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, instance: Instance<'tcx>) {
562 let _s = if ccx.sess().trans_stats() {
563 let mut instance_name = String::new();
564 DefPathBasedNames::new(ccx.tcx(), true, true)
565 .push_def_path(instance.def_id(), &mut instance_name);
566 Some(StatRecorder::new(ccx, instance_name))
571 // this is an info! to allow collecting monomorphization statistics
572 // and to allow finding the last function before LLVM aborts from
574 info!("trans_instance({})", instance);
576 let fn_ty = common::instance_ty(ccx.shared(), &instance);
577 let sig = common::ty_fn_sig(ccx, fn_ty);
578 let sig = ccx.tcx().erase_late_bound_regions_and_normalize(&sig);
580 let lldecl = match ccx.instances().borrow().get(&instance) {
582 None => bug!("Instance `{:?}` not already declared", instance)
585 ccx.stats().n_closures.set(ccx.stats().n_closures.get() + 1);
587 // The `uwtable` attribute according to LLVM is:
589 // This attribute indicates that the ABI being targeted requires that an
590 // unwind table entry be produced for this function even if we can show
591 // that no exceptions passes by it. This is normally the case for the
592 // ELF x86-64 abi, but it can be disabled for some compilation units.
594 // Typically when we're compiling with `-C panic=abort` (which implies this
595 // `no_landing_pads` check) we don't need `uwtable` because we can't
596 // generate any exceptions! On Windows, however, exceptions include other
597 // events such as illegal instructions, segfaults, etc. This means that on
598 // Windows we end up still needing the `uwtable` attribute even if the `-C
599 // panic=abort` flag is passed.
601 // You can also find more info on why Windows is whitelisted here in:
602 // https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
603 if !ccx.sess().no_landing_pads() ||
604 ccx.sess().target.target.options.is_like_windows {
605 attributes::emit_uwtable(lldecl, true);
608 let mir = ccx.tcx().instance_mir(instance.def);
609 mir::trans_mir(ccx, lldecl, &mir, instance, sig);
612 pub fn llvm_linkage_by_name(name: &str) -> Option<Linkage> {
613 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
614 // applicable to variable declarations and may not really make sense for
615 // Rust code in the first place but whitelist them anyway and trust that
616 // the user knows what s/he's doing. Who knows, unanticipated use cases
617 // may pop up in the future.
619 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
620 // and don't have to be, LLVM treats them as no-ops.
622 "appending" => Some(llvm::Linkage::AppendingLinkage),
623 "available_externally" => Some(llvm::Linkage::AvailableExternallyLinkage),
624 "common" => Some(llvm::Linkage::CommonLinkage),
625 "extern_weak" => Some(llvm::Linkage::ExternalWeakLinkage),
626 "external" => Some(llvm::Linkage::ExternalLinkage),
627 "internal" => Some(llvm::Linkage::InternalLinkage),
628 "linkonce" => Some(llvm::Linkage::LinkOnceAnyLinkage),
629 "linkonce_odr" => Some(llvm::Linkage::LinkOnceODRLinkage),
630 "private" => Some(llvm::Linkage::PrivateLinkage),
631 "weak" => Some(llvm::Linkage::WeakAnyLinkage),
632 "weak_odr" => Some(llvm::Linkage::WeakODRLinkage),
637 pub fn set_link_section(ccx: &CrateContext,
639 attrs: &[ast::Attribute]) {
640 if let Some(sect) = attr::first_attr_value_str_by_name(attrs, "link_section") {
641 if contains_null(§.as_str()) {
642 ccx.sess().fatal(&format!("Illegal null byte in link_section value: `{}`", §));
645 let buf = CString::new(sect.as_str().as_bytes()).unwrap();
646 llvm::LLVMSetSection(llval, buf.as_ptr());
651 /// Create the `main` function which will initialise the rust runtime and call
652 /// users main function.
653 pub fn maybe_create_entry_wrapper(ccx: &CrateContext) {
654 let (main_def_id, span) = match *ccx.sess().entry_fn.borrow() {
655 Some((id, span)) => {
656 (ccx.tcx().hir.local_def_id(id), span)
661 // check for the #[rustc_error] annotation, which forces an
662 // error in trans. This is used to write compile-fail tests
663 // that actually test that compilation succeeds without
664 // reporting an error.
665 if ccx.tcx().has_attr(main_def_id, "rustc_error") {
666 ccx.tcx().sess.span_fatal(span, "compilation successful");
669 let instance = Instance::mono(ccx.tcx(), main_def_id);
671 if !ccx.codegen_unit().contains_item(&TransItem::Fn(instance)) {
672 // We want to create the wrapper in the same codegen unit as Rust's main
677 let main_llfn = callee::get_fn(ccx, instance);
679 let et = ccx.sess().entry_type.get().unwrap();
681 config::EntryMain => create_entry_fn(ccx, span, main_llfn, true),
682 config::EntryStart => create_entry_fn(ccx, span, main_llfn, false),
683 config::EntryNone => {} // Do nothing.
686 fn create_entry_fn(ccx: &CrateContext,
689 use_start_lang_item: bool) {
690 let llfty = Type::func(&[ccx.int_type(), Type::i8p(ccx).ptr_to()], &ccx.int_type());
692 if declare::get_defined_value(ccx, "main").is_some() {
693 // FIXME: We should be smart and show a better diagnostic here.
694 ccx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
695 .help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
697 ccx.sess().abort_if_errors();
700 let llfn = declare::declare_cfn(ccx, "main", llfty);
702 // `main` should respect same config for frame pointer elimination as rest of code
703 attributes::set_frame_pointer_elimination(ccx, llfn);
705 let bld = Builder::new_block(ccx, llfn, "top");
707 debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(ccx, &bld);
709 let (start_fn, args) = if use_start_lang_item {
710 let start_def_id = ccx.tcx().require_lang_item(StartFnLangItem);
711 let start_instance = Instance::mono(ccx.tcx(), start_def_id);
712 let start_fn = callee::get_fn(ccx, start_instance);
713 (start_fn, vec![bld.pointercast(rust_main, Type::i8p(ccx).ptr_to()), get_param(llfn, 0),
716 debug!("using user-defined start fn");
717 (rust_main, vec![get_param(llfn, 0 as c_uint), get_param(llfn, 1 as c_uint)])
720 let result = bld.call(start_fn, &args, None);
725 fn contains_null(s: &str) -> bool {
726 s.bytes().any(|b| b == 0)
729 fn write_metadata<'a, 'gcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
730 link_meta: &LinkMeta,
731 exported_symbols: &NodeSet)
732 -> (ContextRef, ModuleRef, EncodedMetadata) {
734 use flate2::Compression;
735 use flate2::write::DeflateEncoder;
737 let (metadata_llcx, metadata_llmod) = unsafe {
738 context::create_context_and_module(tcx.sess, "metadata")
741 #[derive(PartialEq, Eq, PartialOrd, Ord)]
748 let kind = tcx.sess.crate_types.borrow().iter().map(|ty| {
750 config::CrateTypeExecutable |
751 config::CrateTypeStaticlib |
752 config::CrateTypeCdylib => MetadataKind::None,
754 config::CrateTypeRlib => MetadataKind::Uncompressed,
756 config::CrateTypeDylib |
757 config::CrateTypeProcMacro => MetadataKind::Compressed,
761 if kind == MetadataKind::None {
762 return (metadata_llcx, metadata_llmod, EncodedMetadata::new());
765 let cstore = &tcx.sess.cstore;
766 let metadata = cstore.encode_metadata(tcx,
769 if kind == MetadataKind::Uncompressed {
770 return (metadata_llcx, metadata_llmod, metadata);
773 assert!(kind == MetadataKind::Compressed);
774 let mut compressed = cstore.metadata_encoding_version().to_vec();
775 DeflateEncoder::new(&mut compressed, Compression::Fast)
776 .write_all(&metadata.raw_data).unwrap();
778 let llmeta = C_bytes_in_context(metadata_llcx, &compressed);
779 let llconst = C_struct_in_context(metadata_llcx, &[llmeta], false);
780 let name = symbol_export::metadata_symbol_name(tcx);
781 let buf = CString::new(name).unwrap();
782 let llglobal = unsafe {
783 llvm::LLVMAddGlobal(metadata_llmod, val_ty(llconst).to_ref(), buf.as_ptr())
786 llvm::LLVMSetInitializer(llglobal, llconst);
787 let section_name = metadata::metadata_section_name(&tcx.sess.target.target);
788 let name = CString::new(section_name).unwrap();
789 llvm::LLVMSetSection(llglobal, name.as_ptr());
791 // Also generate a .section directive to force no
792 // flags, at least for ELF outputs, so that the
793 // metadata doesn't get loaded into memory.
794 let directive = format!(".section {}", section_name);
795 let directive = CString::new(directive).unwrap();
796 llvm::LLVMSetModuleInlineAsm(metadata_llmod, directive.as_ptr())
798 return (metadata_llcx, metadata_llmod, metadata);
801 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
802 // This is required to satisfy `dllimport` references to static data in .rlibs
803 // when using MSVC linker. We do this only for data, as linker can fix up
804 // code references on its own.
805 // See #26591, #27438
806 fn create_imps(sess: &Session,
807 llvm_module: &ModuleLlvm) {
808 // The x86 ABI seems to require that leading underscores are added to symbol
809 // names, so we need an extra underscore on 32-bit. There's also a leading
810 // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
811 // underscores added in front).
812 let prefix = if sess.target.target.target_pointer_width == "32" {
818 let exported: Vec<_> = iter_globals(llvm_module.llmod)
820 llvm::LLVMRustGetLinkage(val) ==
821 llvm::Linkage::ExternalLinkage &&
822 llvm::LLVMIsDeclaration(val) == 0
826 let i8p_ty = Type::i8p_llcx(llvm_module.llcx);
827 for val in exported {
828 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
829 let mut imp_name = prefix.as_bytes().to_vec();
830 imp_name.extend(name.to_bytes());
831 let imp_name = CString::new(imp_name).unwrap();
832 let imp = llvm::LLVMAddGlobal(llvm_module.llmod,
834 imp_name.as_ptr() as *const _);
835 let init = llvm::LLVMConstBitCast(val, i8p_ty.to_ref());
836 llvm::LLVMSetInitializer(imp, init);
837 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);
844 step: unsafe extern "C" fn(ValueRef) -> ValueRef,
847 impl Iterator for ValueIter {
848 type Item = ValueRef;
850 fn next(&mut self) -> Option<ValueRef> {
853 self.cur = unsafe { (self.step)(old) };
861 fn iter_globals(llmod: llvm::ModuleRef) -> ValueIter {
864 cur: llvm::LLVMGetFirstGlobal(llmod),
865 step: llvm::LLVMGetNextGlobal,
870 /// The context provided lists a set of reachable ids as calculated by
871 /// middle::reachable, but this contains far more ids and symbols than we're
872 /// actually exposing from the object file. This function will filter the set in
873 /// the context to the set of ids which correspond to symbols that are exposed
874 /// from the object file being generated.
876 /// This list is later used by linkers to determine the set of symbols needed to
877 /// be exposed from a dynamic library and it's also encoded into the metadata.
878 pub fn find_exported_symbols(tcx: TyCtxt, reachable: &NodeSet) -> NodeSet {
879 reachable.iter().cloned().filter(|&id| {
880 // Next, we want to ignore some FFI functions that are not exposed from
881 // this crate. Reachable FFI functions can be lumped into two
884 // 1. Those that are included statically via a static library
885 // 2. Those included otherwise (e.g. dynamically or via a framework)
887 // Although our LLVM module is not literally emitting code for the
888 // statically included symbols, it's an export of our library which
889 // needs to be passed on to the linker and encoded in the metadata.
891 // As a result, if this id is an FFI item (foreign item) then we only
892 // let it through if it's included statically.
893 match tcx.hir.get(id) {
894 hir_map::NodeForeignItem(..) => {
895 let def_id = tcx.hir.local_def_id(id);
896 tcx.sess.cstore.is_statically_included_foreign_item(def_id)
899 // Only consider nodes that actually have exported symbols.
900 hir_map::NodeItem(&hir::Item {
901 node: hir::ItemStatic(..), .. }) |
902 hir_map::NodeItem(&hir::Item {
903 node: hir::ItemFn(..), .. }) |
904 hir_map::NodeImplItem(&hir::ImplItem {
905 node: hir::ImplItemKind::Method(..), .. }) => {
906 let def_id = tcx.hir.local_def_id(id);
907 let generics = tcx.generics_of(def_id);
908 let attributes = tcx.get_attrs(def_id);
909 (generics.parent_types == 0 && generics.types.is_empty()) &&
910 // Functions marked with #[inline] are only ever translated
911 // with "internal" linkage and are never exported.
912 !attr::requests_inline(&attributes)
920 pub fn trans_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
921 analysis: ty::CrateAnalysis,
922 incremental_hashes_map: &IncrementalHashesMap,
923 output_filenames: &OutputFilenames)
924 -> OngoingCrateTranslation {
925 // Be careful with this krate: obviously it gives access to the
926 // entire contents of the krate. So if you push any subtasks of
927 // `TransCrate`, you need to be careful to register "reads" of the
928 // particular items that will be processed.
929 let krate = tcx.hir.krate();
931 let ty::CrateAnalysis { reachable, .. } = analysis;
933 let check_overflow = tcx.sess.overflow_checks();
935 let link_meta = link::build_link_meta(incremental_hashes_map);
937 let exported_symbol_node_ids = find_exported_symbols(tcx, &reachable);
938 let shared_ccx = SharedCrateContext::new(tcx,
941 // Translate the metadata.
942 let (metadata_llcx, metadata_llmod, metadata) =
943 time(tcx.sess.time_passes(), "write metadata", || {
944 write_metadata(tcx, &link_meta, &exported_symbol_node_ids)
947 let metadata_module = ModuleTranslation {
948 name: link::METADATA_MODULE_NAME.to_string(),
949 symbol_name_hash: 0, // we always rebuild metadata, at least for now
950 source: ModuleSource::Translated(ModuleLlvm {
952 llmod: metadata_llmod,
954 kind: ModuleKind::Metadata,
957 let no_builtins = attr::contains_name(&krate.attrs, "no_builtins");
959 // Skip crate items and just output metadata in -Z no-trans mode.
960 if tcx.sess.opts.debugging_opts.no_trans ||
961 !tcx.sess.opts.output_types.should_trans() {
962 let empty_exported_symbols = ExportedSymbols::empty();
963 let linker_info = LinkerInfo::new(&shared_ccx, &empty_exported_symbols);
964 let ongoing_translation = write::run_passes(
967 tcx.crate_name(LOCAL_CRATE),
970 Arc::new(empty_exported_symbols),
976 ongoing_translation.submit_translated_module_to_llvm(tcx.sess, metadata_module);
977 ongoing_translation.signal_translation_done();
979 return ongoing_translation;
982 let exported_symbols = Arc::new(ExportedSymbols::compute(tcx,
983 &exported_symbol_node_ids));
985 // Run the translation item collector and partition the collected items into
987 let (translation_items, codegen_units) =
988 collect_and_partition_translation_items(&shared_ccx, &exported_symbols);
990 assert!(codegen_units.len() <= 1 || !tcx.sess.lto());
992 let translation_items = Arc::new(translation_items);
994 let mut all_stats = Stats::default();
995 let modules: Vec<ModuleTranslation> = codegen_units
998 let dep_node = cgu.work_product_dep_node();
999 let ((stats, module), _) =
1000 tcx.dep_graph.with_task(dep_node,
1001 AssertDepGraphSafe(&shared_ccx),
1002 AssertDepGraphSafe((cgu,
1003 translation_items.clone(),
1004 exported_symbols.clone())),
1005 module_translation);
1006 all_stats.extend(stats);
1011 fn module_translation<'a, 'tcx>(
1012 scx: AssertDepGraphSafe<&SharedCrateContext<'a, 'tcx>>,
1013 args: AssertDepGraphSafe<(CodegenUnit<'tcx>,
1014 Arc<FxHashSet<TransItem<'tcx>>>,
1015 Arc<ExportedSymbols>)>)
1016 -> (Stats, ModuleTranslation)
1018 // FIXME(#40304): We ought to be using the id as a key and some queries, I think.
1019 let AssertDepGraphSafe(scx) = scx;
1020 let AssertDepGraphSafe((cgu, crate_trans_items, exported_symbols)) = args;
1022 let cgu_name = String::from(cgu.name());
1023 let cgu_id = cgu.work_product_id();
1024 let symbol_name_hash = cgu.compute_symbol_name_hash(scx, &exported_symbols);
1026 // Check whether there is a previous work-product we can
1027 // re-use. Not only must the file exist, and the inputs not
1028 // be dirty, but the hash of the symbols we will generate must
1030 let previous_work_product =
1031 scx.dep_graph().previous_work_product(&cgu_id).and_then(|work_product| {
1032 if work_product.input_hash == symbol_name_hash {
1033 debug!("trans_reuse_previous_work_products: reusing {:?}", work_product);
1036 if scx.sess().opts.debugging_opts.incremental_info {
1037 eprintln!("incremental: CGU `{}` invalidated because of \
1038 changed partitioning hash.",
1041 debug!("trans_reuse_previous_work_products: \
1042 not reusing {:?} because hash changed to {:?}",
1043 work_product, symbol_name_hash);
1048 if let Some(buf) = previous_work_product {
1049 // Don't need to translate this module.
1050 let module = ModuleTranslation {
1053 source: ModuleSource::Preexisting(buf.clone()),
1054 kind: ModuleKind::Regular,
1056 return (Stats::default(), module);
1059 // Instantiate translation items without filling out definitions yet...
1060 let lcx = LocalCrateContext::new(scx, cgu, crate_trans_items, exported_symbols);
1062 let ccx = CrateContext::new(scx, &lcx);
1063 let trans_items = ccx.codegen_unit()
1064 .items_in_deterministic_order(ccx.tcx());
1065 for &(trans_item, (linkage, visibility)) in &trans_items {
1066 trans_item.predefine(&ccx, linkage, visibility);
1069 // ... and now that we have everything pre-defined, fill out those definitions.
1070 for &(trans_item, _) in &trans_items {
1071 trans_item.define(&ccx);
1074 // If this codegen unit contains the main function, also create the
1076 maybe_create_entry_wrapper(&ccx);
1078 // Run replace-all-uses-with for statics that need it
1079 for &(old_g, new_g) in ccx.statics_to_rauw().borrow().iter() {
1081 let bitcast = llvm::LLVMConstPointerCast(new_g, llvm::LLVMTypeOf(old_g));
1082 llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
1083 llvm::LLVMDeleteGlobal(old_g);
1087 // Create the llvm.used variable
1088 // This variable has type [N x i8*] and is stored in the llvm.metadata section
1089 if !ccx.used_statics().borrow().is_empty() {
1090 let name = CString::new("llvm.used").unwrap();
1091 let section = CString::new("llvm.metadata").unwrap();
1092 let array = C_array(Type::i8(&ccx).ptr_to(), &*ccx.used_statics().borrow());
1095 let g = llvm::LLVMAddGlobal(ccx.llmod(),
1096 val_ty(array).to_ref(),
1098 llvm::LLVMSetInitializer(g, array);
1099 llvm::LLVMRustSetLinkage(g, llvm::Linkage::AppendingLinkage);
1100 llvm::LLVMSetSection(g, section.as_ptr());
1104 // Finalize debuginfo
1105 if ccx.sess().opts.debuginfo != NoDebugInfo {
1106 debuginfo::finalize(&ccx);
1109 let llvm_module = ModuleLlvm {
1114 // In LTO mode we inject the allocator shim into the existing
1116 if ccx.sess().lto() {
1117 if let Some(kind) = ccx.sess().allocator_kind.get() {
1118 time(ccx.sess().time_passes(), "write allocator module", || {
1120 allocator::trans(ccx.tcx(), &llvm_module, kind);
1126 // Adjust exported symbols for MSVC dllimport
1127 if ccx.sess().target.target.options.is_like_msvc &&
1128 ccx.sess().crate_types.borrow().iter().any(|ct| *ct == config::CrateTypeRlib) {
1129 create_imps(ccx.sess(), &llvm_module);
1135 source: ModuleSource::Translated(llvm_module),
1136 kind: ModuleKind::Regular,
1140 (lcx.into_stats(), module)
1143 assert_module_sources::assert_module_sources(tcx, &modules);
1145 symbol_names_test::report_symbol_names(tcx);
1147 if shared_ccx.sess().trans_stats() {
1148 println!("--- trans stats ---");
1149 println!("n_glues_created: {}", all_stats.n_glues_created.get());
1150 println!("n_null_glues: {}", all_stats.n_null_glues.get());
1151 println!("n_real_glues: {}", all_stats.n_real_glues.get());
1153 println!("n_fns: {}", all_stats.n_fns.get());
1154 println!("n_inlines: {}", all_stats.n_inlines.get());
1155 println!("n_closures: {}", all_stats.n_closures.get());
1156 println!("fn stats:");
1157 all_stats.fn_stats.borrow_mut().sort_by(|&(_, insns_a), &(_, insns_b)| {
1158 insns_b.cmp(&insns_a)
1160 for tuple in all_stats.fn_stats.borrow().iter() {
1162 (ref name, insns) => {
1163 println!("{} insns, {}", insns, *name);
1169 if shared_ccx.sess().count_llvm_insns() {
1170 for (k, v) in all_stats.llvm_insns.borrow().iter() {
1171 println!("{:7} {}", *v, *k);
1175 let sess = shared_ccx.sess();
1177 // Translate an allocator shim, if any
1179 // If LTO is enabled and we've got some previous LLVM module we translated
1180 // above, then we can just translate directly into that LLVM module. If not,
1181 // however, we need to create a separate module and trans into that. Note
1182 // that the separate translation is critical for the standard library where
1183 // the rlib's object file doesn't have allocator functions but the dylib
1184 // links in an object file that has allocator functions. When we're
1185 // compiling a final LTO artifact, though, there's no need to worry about
1186 // this as we're not working with this dual "rlib/dylib" functionality.
1187 let allocator_module = if tcx.sess.lto() {
1189 } else if let Some(kind) = tcx.sess.allocator_kind.get() {
1192 context::create_context_and_module(tcx.sess, "allocator");
1193 let modules = ModuleLlvm {
1197 time(tcx.sess.time_passes(), "write allocator module", || {
1198 allocator::trans(tcx, &modules, kind)
1201 Some(ModuleTranslation {
1202 name: link::ALLOCATOR_MODULE_NAME.to_string(),
1203 symbol_name_hash: 0, // we always rebuild allocator shims
1204 source: ModuleSource::Translated(modules),
1205 kind: ModuleKind::Allocator,
1212 let linker_info = LinkerInfo::new(&shared_ccx, &exported_symbols);
1214 let subsystem = attr::first_attr_value_str_by_name(&krate.attrs,
1215 "windows_subsystem");
1216 let windows_subsystem = subsystem.map(|subsystem| {
1217 if subsystem != "windows" && subsystem != "console" {
1218 tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
1219 `windows` and `console` are allowed",
1222 subsystem.to_string()
1225 let outputs = output_filenames;
1227 let no_integrated_as = sess.opts.cg.no_integrated_as ||
1228 (sess.target.target.options.no_integrated_as &&
1229 (outputs.outputs.contains_key(&OutputType::Object) ||
1230 outputs.outputs.contains_key(&OutputType::Exe)));
1232 time(sess.time_passes(),
1234 || rustc_incremental::assert_dep_graph(tcx));
1236 time(sess.time_passes(),
1237 "serialize dep graph",
1238 || rustc_incremental::save_dep_graph(tcx,
1239 incremental_hashes_map,
1241 link_meta.crate_hash));
1243 let ongoing_translation = write::run_passes(
1246 tcx.crate_name(LOCAL_CRATE),
1255 ongoing_translation.submit_translated_module_to_llvm(sess, metadata_module);
1257 for mtrans in modules {
1258 ongoing_translation.submit_translated_module_to_llvm(sess, mtrans);
1261 if let Some(allocator_module) = allocator_module {
1262 ongoing_translation.submit_translated_module_to_llvm(sess, allocator_module);
1265 ongoing_translation.signal_translation_done();
1270 #[inline(never)] // give this a place in the profiler
1271 fn assert_symbols_are_distinct<'a, 'tcx, I>(tcx: TyCtxt<'a, 'tcx, 'tcx>, trans_items: I)
1272 where I: Iterator<Item=&'a TransItem<'tcx>>
1274 let mut symbols: Vec<_> = trans_items.map(|trans_item| {
1275 (trans_item, trans_item.symbol_name(tcx))
1278 (&mut symbols[..]).sort_by(|&(_, ref sym1), &(_, ref sym2)|{
1282 for pair in (&symbols[..]).windows(2) {
1283 let sym1 = &pair[0].1;
1284 let sym2 = &pair[1].1;
1287 let trans_item1 = pair[0].0;
1288 let trans_item2 = pair[1].0;
1290 let span1 = trans_item1.local_span(tcx);
1291 let span2 = trans_item2.local_span(tcx);
1293 // Deterministically select one of the spans for error reporting
1294 let span = match (span1, span2) {
1295 (Some(span1), Some(span2)) => {
1296 Some(if span1.lo.0 > span2.lo.0 {
1302 (Some(span), None) |
1303 (None, Some(span)) => Some(span),
1307 let error_message = format!("symbol `{}` is already defined", sym1);
1309 if let Some(span) = span {
1310 tcx.sess.span_fatal(span, &error_message)
1312 tcx.sess.fatal(&error_message)
1318 fn collect_and_partition_translation_items<'a, 'tcx>(scx: &SharedCrateContext<'a, 'tcx>,
1319 exported_symbols: &ExportedSymbols)
1320 -> (FxHashSet<TransItem<'tcx>>,
1321 Vec<CodegenUnit<'tcx>>) {
1322 let time_passes = scx.sess().time_passes();
1324 let collection_mode = match scx.sess().opts.debugging_opts.print_trans_items {
1326 let mode_string = s.to_lowercase();
1327 let mode_string = mode_string.trim();
1328 if mode_string == "eager" {
1329 TransItemCollectionMode::Eager
1331 if mode_string != "lazy" {
1332 let message = format!("Unknown codegen-item collection mode '{}'. \
1333 Falling back to 'lazy' mode.",
1335 scx.sess().warn(&message);
1338 TransItemCollectionMode::Lazy
1341 None => TransItemCollectionMode::Lazy
1344 let (items, inlining_map) =
1345 time(time_passes, "translation item collection", || {
1346 collector::collect_crate_translation_items(&scx,
1351 assert_symbols_are_distinct(scx.tcx(), items.iter());
1353 let strategy = if scx.sess().opts.debugging_opts.incremental.is_some() {
1354 PartitioningStrategy::PerModule
1356 PartitioningStrategy::FixedUnitCount(scx.sess().opts.cg.codegen_units)
1359 let codegen_units = time(time_passes, "codegen unit partitioning", || {
1360 partitioning::partition(scx,
1361 items.iter().cloned(),
1367 assert!(scx.tcx().sess.opts.cg.codegen_units == codegen_units.len() ||
1368 scx.tcx().sess.opts.debugging_opts.incremental.is_some());
1370 let translation_items: FxHashSet<TransItem<'tcx>> = items.iter().cloned().collect();
1372 if scx.sess().opts.debugging_opts.print_trans_items.is_some() {
1373 let mut item_to_cgus = FxHashMap();
1375 for cgu in &codegen_units {
1376 for (&trans_item, &linkage) in cgu.items() {
1377 item_to_cgus.entry(trans_item)
1378 .or_insert(Vec::new())
1379 .push((cgu.name().clone(), linkage));
1383 let mut item_keys: Vec<_> = items
1386 let mut output = i.to_string(scx.tcx());
1387 output.push_str(" @@");
1388 let mut empty = Vec::new();
1389 let mut cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);
1390 cgus.as_mut_slice().sort_by_key(|&(ref name, _)| name.clone());
1392 for &(ref cgu_name, (linkage, _)) in cgus.iter() {
1393 output.push_str(" ");
1394 output.push_str(&cgu_name);
1396 let linkage_abbrev = match linkage {
1397 llvm::Linkage::ExternalLinkage => "External",
1398 llvm::Linkage::AvailableExternallyLinkage => "Available",
1399 llvm::Linkage::LinkOnceAnyLinkage => "OnceAny",
1400 llvm::Linkage::LinkOnceODRLinkage => "OnceODR",
1401 llvm::Linkage::WeakAnyLinkage => "WeakAny",
1402 llvm::Linkage::WeakODRLinkage => "WeakODR",
1403 llvm::Linkage::AppendingLinkage => "Appending",
1404 llvm::Linkage::InternalLinkage => "Internal",
1405 llvm::Linkage::PrivateLinkage => "Private",
1406 llvm::Linkage::ExternalWeakLinkage => "ExternalWeak",
1407 llvm::Linkage::CommonLinkage => "Common",
1410 output.push_str("[");
1411 output.push_str(linkage_abbrev);
1412 output.push_str("]");
1420 for item in item_keys {
1421 println!("TRANS_ITEM {}", item);
1425 (translation_items, codegen_units)