]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/base.rs
Auto merge of #35162 - canndrew:bang_type_coerced, r=nikomatsakis
[rust.git] / src / librustc_trans / base.rs
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.
4 //
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.
10
11 //! Translate the completed AST to the LLVM IR.
12 //!
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.
17 //!
18 //! Hopefully useful general knowledge about trans:
19 //!
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.
25
26 #![allow(non_camel_case_types)]
27
28 use super::CrateTranslation;
29 use super::ModuleLlvm;
30 use super::ModuleSource;
31 use super::ModuleTranslation;
32
33 use assert_module_sources;
34 use back::link;
35 use back::linker::LinkerInfo;
36 use llvm::{BasicBlockRef, Linkage, ValueRef, Vector, get_param};
37 use llvm;
38 use rustc::cfg;
39 use rustc::hir::def_id::DefId;
40 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
41 use rustc::hir::pat_util::simple_name;
42 use rustc::ty::subst::{self, Substs};
43 use rustc::traits;
44 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
45 use rustc::ty::adjustment::CustomCoerceUnsized;
46 use rustc::dep_graph::{DepNode, WorkProduct};
47 use rustc::hir::map as hir_map;
48 use rustc::util::common::time;
49 use rustc::mir::mir_map::MirMap;
50 use rustc_data_structures::graph::OUTGOING;
51 use session::config::{self, NoDebugInfo, FullDebugInfo};
52 use session::Session;
53 use _match;
54 use abi::{self, Abi, FnType};
55 use adt;
56 use attributes;
57 use build::*;
58 use builder::{Builder, noname};
59 use callee::{Callee, CallArgs, ArgExprs, ArgVals};
60 use cleanup::{self, CleanupMethods, DropHint};
61 use closure;
62 use common::{Block, C_bool, C_bytes_in_context, C_i32, C_int, C_uint, C_integral};
63 use collector::{self, TransItemCollectionMode};
64 use common::{C_null, C_struct_in_context, C_u64, C_u8, C_undef};
65 use common::{CrateContext, DropFlagHintsMap, Field, FunctionContext};
66 use common::{Result, NodeIdAndSpan, VariantInfo};
67 use common::{node_id_type, fulfill_obligation};
68 use common::{type_is_immediate, type_is_zero_size, val_ty};
69 use common;
70 use consts;
71 use context::{SharedCrateContext, CrateContextList};
72 use controlflow;
73 use datum;
74 use debuginfo::{self, DebugLoc, ToDebugLoc};
75 use declare;
76 use expr;
77 use glue;
78 use inline;
79 use machine;
80 use machine::{llalign_of_min, llsize_of};
81 use meth;
82 use mir;
83 use monomorphize::{self, Instance};
84 use partitioning::{self, PartitioningStrategy, CodegenUnit};
85 use symbol_map::SymbolMap;
86 use symbol_names_test;
87 use trans_item::TransItem;
88 use tvec;
89 use type_::Type;
90 use type_of;
91 use value::Value;
92 use Disr;
93 use util::common::indenter;
94 use util::sha2::Sha256;
95 use util::nodemap::{NodeMap, NodeSet, FnvHashSet};
96
97 use arena::TypedArena;
98 use libc::c_uint;
99 use std::ffi::{CStr, CString};
100 use std::borrow::Cow;
101 use std::cell::{Cell, RefCell};
102 use std::collections::HashMap;
103 use std::ptr;
104 use std::rc::Rc;
105 use std::str;
106 use std::{i8, i16, i32, i64};
107 use syntax_pos::{Span, DUMMY_SP};
108 use syntax::parse::token::InternedString;
109 use syntax::attr::AttrMetaMethods;
110 use syntax::attr;
111 use rustc::hir::intravisit::{self, Visitor};
112 use rustc::hir;
113 use syntax::ast;
114
115 thread_local! {
116     static TASK_LOCAL_INSN_KEY: RefCell<Option<Vec<&'static str>>> = {
117         RefCell::new(None)
118     }
119 }
120
121 pub fn with_insn_ctxt<F>(blk: F)
122     where F: FnOnce(&[&'static str])
123 {
124     TASK_LOCAL_INSN_KEY.with(move |slot| {
125         slot.borrow().as_ref().map(move |s| blk(s));
126     })
127 }
128
129 pub fn init_insn_ctxt() {
130     TASK_LOCAL_INSN_KEY.with(|slot| {
131         *slot.borrow_mut() = Some(Vec::new());
132     });
133 }
134
135 pub struct _InsnCtxt {
136     _cannot_construct_outside_of_this_module: (),
137 }
138
139 impl Drop for _InsnCtxt {
140     fn drop(&mut self) {
141         TASK_LOCAL_INSN_KEY.with(|slot| {
142             if let Some(ctx) = slot.borrow_mut().as_mut() {
143                 ctx.pop();
144             }
145         })
146     }
147 }
148
149 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
150     debug!("new InsnCtxt: {}", s);
151     TASK_LOCAL_INSN_KEY.with(|slot| {
152         if let Some(ctx) = slot.borrow_mut().as_mut() {
153             ctx.push(s)
154         }
155     });
156     _InsnCtxt {
157         _cannot_construct_outside_of_this_module: (),
158     }
159 }
160
161 pub struct StatRecorder<'a, 'tcx: 'a> {
162     ccx: &'a CrateContext<'a, 'tcx>,
163     name: Option<String>,
164     istart: usize,
165 }
166
167 impl<'a, 'tcx> StatRecorder<'a, 'tcx> {
168     pub fn new(ccx: &'a CrateContext<'a, 'tcx>, name: String) -> StatRecorder<'a, 'tcx> {
169         let istart = ccx.stats().n_llvm_insns.get();
170         StatRecorder {
171             ccx: ccx,
172             name: Some(name),
173             istart: istart,
174         }
175     }
176 }
177
178 impl<'a, 'tcx> Drop for StatRecorder<'a, 'tcx> {
179     fn drop(&mut self) {
180         if self.ccx.sess().trans_stats() {
181             let iend = self.ccx.stats().n_llvm_insns.get();
182             self.ccx
183                 .stats()
184                 .fn_stats
185                 .borrow_mut()
186                 .push((self.name.take().unwrap(), iend - self.istart));
187             self.ccx.stats().n_fns.set(self.ccx.stats().n_fns.get() + 1);
188             // Reset LLVM insn count to avoid compound costs.
189             self.ccx.stats().n_llvm_insns.set(self.istart);
190         }
191     }
192 }
193
194 pub fn kind_for_closure(ccx: &CrateContext, closure_id: DefId) -> ty::ClosureKind {
195     *ccx.tcx().tables.borrow().closure_kinds.get(&closure_id).unwrap()
196 }
197
198 fn require_alloc_fn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, info_ty: Ty<'tcx>, it: LangItem) -> DefId {
199     match bcx.tcx().lang_items.require(it) {
200         Ok(id) => id,
201         Err(s) => {
202             bcx.sess().fatal(&format!("allocation of `{}` {}", info_ty, s));
203         }
204     }
205 }
206
207 // The following malloc_raw_dyn* functions allocate a box to contain
208 // a given type, but with a potentially dynamic size.
209
210 pub fn malloc_raw_dyn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
211                                   llty_ptr: Type,
212                                   info_ty: Ty<'tcx>,
213                                   size: ValueRef,
214                                   align: ValueRef,
215                                   debug_loc: DebugLoc)
216                                   -> Result<'blk, 'tcx> {
217     let _icx = push_ctxt("malloc_raw_exchange");
218
219     // Allocate space:
220     let def_id = require_alloc_fn(bcx, info_ty, ExchangeMallocFnLangItem);
221     let r = Callee::def(bcx.ccx(), def_id, bcx.tcx().mk_substs(Substs::empty()))
222         .call(bcx, debug_loc, ArgVals(&[size, align]), None);
223
224     Result::new(r.bcx, PointerCast(r.bcx, r.val, llty_ptr))
225 }
226
227
228 pub fn bin_op_to_icmp_predicate(op: hir::BinOp_,
229                                 signed: bool)
230                                 -> llvm::IntPredicate {
231     match op {
232         hir::BiEq => llvm::IntEQ,
233         hir::BiNe => llvm::IntNE,
234         hir::BiLt => if signed { llvm::IntSLT } else { llvm::IntULT },
235         hir::BiLe => if signed { llvm::IntSLE } else { llvm::IntULE },
236         hir::BiGt => if signed { llvm::IntSGT } else { llvm::IntUGT },
237         hir::BiGe => if signed { llvm::IntSGE } else { llvm::IntUGE },
238         op => {
239             bug!("comparison_op_to_icmp_predicate: expected comparison operator, \
240                   found {:?}",
241                  op)
242         }
243     }
244 }
245
246 pub fn bin_op_to_fcmp_predicate(op: hir::BinOp_) -> llvm::RealPredicate {
247     match op {
248         hir::BiEq => llvm::RealOEQ,
249         hir::BiNe => llvm::RealUNE,
250         hir::BiLt => llvm::RealOLT,
251         hir::BiLe => llvm::RealOLE,
252         hir::BiGt => llvm::RealOGT,
253         hir::BiGe => llvm::RealOGE,
254         op => {
255             bug!("comparison_op_to_fcmp_predicate: expected comparison operator, \
256                   found {:?}",
257                  op);
258         }
259     }
260 }
261
262 pub fn compare_fat_ptrs<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
263                                     lhs_addr: ValueRef,
264                                     lhs_extra: ValueRef,
265                                     rhs_addr: ValueRef,
266                                     rhs_extra: ValueRef,
267                                     _t: Ty<'tcx>,
268                                     op: hir::BinOp_,
269                                     debug_loc: DebugLoc)
270                                     -> ValueRef {
271     match op {
272         hir::BiEq => {
273             let addr_eq = ICmp(bcx, llvm::IntEQ, lhs_addr, rhs_addr, debug_loc);
274             let extra_eq = ICmp(bcx, llvm::IntEQ, lhs_extra, rhs_extra, debug_loc);
275             And(bcx, addr_eq, extra_eq, debug_loc)
276         }
277         hir::BiNe => {
278             let addr_eq = ICmp(bcx, llvm::IntNE, lhs_addr, rhs_addr, debug_loc);
279             let extra_eq = ICmp(bcx, llvm::IntNE, lhs_extra, rhs_extra, debug_loc);
280             Or(bcx, addr_eq, extra_eq, debug_loc)
281         }
282         hir::BiLe | hir::BiLt | hir::BiGe | hir::BiGt => {
283             // a OP b ~ a.0 STRICT(OP) b.0 | (a.0 == b.0 && a.1 OP a.1)
284             let (op, strict_op) = match op {
285                 hir::BiLt => (llvm::IntULT, llvm::IntULT),
286                 hir::BiLe => (llvm::IntULE, llvm::IntULT),
287                 hir::BiGt => (llvm::IntUGT, llvm::IntUGT),
288                 hir::BiGe => (llvm::IntUGE, llvm::IntUGT),
289                 _ => bug!(),
290             };
291
292             let addr_eq = ICmp(bcx, llvm::IntEQ, lhs_addr, rhs_addr, debug_loc);
293             let extra_op = ICmp(bcx, op, lhs_extra, rhs_extra, debug_loc);
294             let addr_eq_extra_op = And(bcx, addr_eq, extra_op, debug_loc);
295
296             let addr_strict = ICmp(bcx, strict_op, lhs_addr, rhs_addr, debug_loc);
297             Or(bcx, addr_strict, addr_eq_extra_op, debug_loc)
298         }
299         _ => {
300             bug!("unexpected fat ptr binop");
301         }
302     }
303 }
304
305 pub fn compare_scalar_types<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
306                                         lhs: ValueRef,
307                                         rhs: ValueRef,
308                                         t: Ty<'tcx>,
309                                         op: hir::BinOp_,
310                                         debug_loc: DebugLoc)
311                                         -> ValueRef {
312     match t.sty {
313         ty::TyTuple(ref tys) if tys.is_empty() => {
314             // We don't need to do actual comparisons for nil.
315             // () == () holds but () < () does not.
316             match op {
317                 hir::BiEq | hir::BiLe | hir::BiGe => return C_bool(bcx.ccx(), true),
318                 hir::BiNe | hir::BiLt | hir::BiGt => return C_bool(bcx.ccx(), false),
319                 // refinements would be nice
320                 _ => bug!("compare_scalar_types: must be a comparison operator"),
321             }
322         }
323         ty::TyFnDef(..) | ty::TyFnPtr(_) | ty::TyBool | ty::TyUint(_) | ty::TyChar => {
324             ICmp(bcx,
325                  bin_op_to_icmp_predicate(op, false),
326                  lhs,
327                  rhs,
328                  debug_loc)
329         }
330         ty::TyRawPtr(mt) if common::type_is_sized(bcx.tcx(), mt.ty) => {
331             ICmp(bcx,
332                  bin_op_to_icmp_predicate(op, false),
333                  lhs,
334                  rhs,
335                  debug_loc)
336         }
337         ty::TyRawPtr(_) => {
338             let lhs_addr = Load(bcx, GEPi(bcx, lhs, &[0, abi::FAT_PTR_ADDR]));
339             let lhs_extra = Load(bcx, GEPi(bcx, lhs, &[0, abi::FAT_PTR_EXTRA]));
340
341             let rhs_addr = Load(bcx, GEPi(bcx, rhs, &[0, abi::FAT_PTR_ADDR]));
342             let rhs_extra = Load(bcx, GEPi(bcx, rhs, &[0, abi::FAT_PTR_EXTRA]));
343             compare_fat_ptrs(bcx,
344                              lhs_addr,
345                              lhs_extra,
346                              rhs_addr,
347                              rhs_extra,
348                              t,
349                              op,
350                              debug_loc)
351         }
352         ty::TyInt(_) => {
353             ICmp(bcx,
354                  bin_op_to_icmp_predicate(op, true),
355                  lhs,
356                  rhs,
357                  debug_loc)
358         }
359         ty::TyFloat(_) => {
360             FCmp(bcx,
361                  bin_op_to_fcmp_predicate(op),
362                  lhs,
363                  rhs,
364                  debug_loc)
365         }
366         // Should never get here, because t is scalar.
367         _ => bug!("non-scalar type passed to compare_scalar_types"),
368     }
369 }
370
371 pub fn compare_simd_types<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
372                                       lhs: ValueRef,
373                                       rhs: ValueRef,
374                                       t: Ty<'tcx>,
375                                       ret_ty: Type,
376                                       op: hir::BinOp_,
377                                       debug_loc: DebugLoc)
378                                       -> ValueRef {
379     let signed = match t.sty {
380         ty::TyFloat(_) => {
381             let cmp = bin_op_to_fcmp_predicate(op);
382             return SExt(bcx, FCmp(bcx, cmp, lhs, rhs, debug_loc), ret_ty);
383         },
384         ty::TyUint(_) => false,
385         ty::TyInt(_) => true,
386         _ => bug!("compare_simd_types: invalid SIMD type"),
387     };
388
389     let cmp = bin_op_to_icmp_predicate(op, signed);
390     // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
391     // to get the correctly sized type. This will compile to a single instruction
392     // once the IR is converted to assembly if the SIMD instruction is supported
393     // by the target architecture.
394     SExt(bcx, ICmp(bcx, cmp, lhs, rhs, debug_loc), ret_ty)
395 }
396
397 // Iterates through the elements of a structural type.
398 pub fn iter_structural_ty<'blk, 'tcx, F>(cx: Block<'blk, 'tcx>,
399                                          av: ValueRef,
400                                          t: Ty<'tcx>,
401                                          mut f: F)
402                                          -> Block<'blk, 'tcx>
403     where F: FnMut(Block<'blk, 'tcx>, ValueRef, Ty<'tcx>) -> Block<'blk, 'tcx>
404 {
405     let _icx = push_ctxt("iter_structural_ty");
406
407     fn iter_variant<'blk, 'tcx, F>(cx: Block<'blk, 'tcx>,
408                                    repr: &adt::Repr<'tcx>,
409                                    av: adt::MaybeSizedValue,
410                                    variant: ty::VariantDef<'tcx>,
411                                    substs: &Substs<'tcx>,
412                                    f: &mut F)
413                                    -> Block<'blk, 'tcx>
414         where F: FnMut(Block<'blk, 'tcx>, ValueRef, Ty<'tcx>) -> Block<'blk, 'tcx>
415     {
416         let _icx = push_ctxt("iter_variant");
417         let tcx = cx.tcx();
418         let mut cx = cx;
419
420         for (i, field) in variant.fields.iter().enumerate() {
421             let arg = monomorphize::field_ty(tcx, substs, field);
422             cx = f(cx,
423                    adt::trans_field_ptr(cx, repr, av, Disr::from(variant.disr_val), i),
424                    arg);
425         }
426         return cx;
427     }
428
429     let value = if common::type_is_sized(cx.tcx(), t) {
430         adt::MaybeSizedValue::sized(av)
431     } else {
432         let data = Load(cx, expr::get_dataptr(cx, av));
433         let info = Load(cx, expr::get_meta(cx, av));
434         adt::MaybeSizedValue::unsized_(data, info)
435     };
436
437     let mut cx = cx;
438     match t.sty {
439         ty::TyStruct(..) => {
440             let repr = adt::represent_type(cx.ccx(), t);
441             let VariantInfo { fields, discr } = VariantInfo::from_ty(cx.tcx(), t, None);
442             for (i, &Field(_, field_ty)) in fields.iter().enumerate() {
443                 let llfld_a = adt::trans_field_ptr(cx, &repr, value, Disr::from(discr), i);
444
445                 let val = if common::type_is_sized(cx.tcx(), field_ty) {
446                     llfld_a
447                 } else {
448                     let scratch = datum::rvalue_scratch_datum(cx, field_ty, "__fat_ptr_iter");
449                     Store(cx, llfld_a, expr::get_dataptr(cx, scratch.val));
450                     Store(cx, value.meta, expr::get_meta(cx, scratch.val));
451                     scratch.val
452                 };
453                 cx = f(cx, val, field_ty);
454             }
455         }
456         ty::TyClosure(_, ref substs) => {
457             let repr = adt::represent_type(cx.ccx(), t);
458             for (i, upvar_ty) in substs.upvar_tys.iter().enumerate() {
459                 let llupvar = adt::trans_field_ptr(cx, &repr, value, Disr(0), i);
460                 cx = f(cx, llupvar, upvar_ty);
461             }
462         }
463         ty::TyArray(_, n) => {
464             let (base, len) = tvec::get_fixed_base_and_len(cx, value.value, n);
465             let unit_ty = t.sequence_element_type(cx.tcx());
466             cx = tvec::iter_vec_raw(cx, base, unit_ty, len, f);
467         }
468         ty::TySlice(_) | ty::TyStr => {
469             let unit_ty = t.sequence_element_type(cx.tcx());
470             cx = tvec::iter_vec_raw(cx, value.value, unit_ty, value.meta, f);
471         }
472         ty::TyTuple(ref args) => {
473             let repr = adt::represent_type(cx.ccx(), t);
474             for (i, arg) in args.iter().enumerate() {
475                 let llfld_a = adt::trans_field_ptr(cx, &repr, value, Disr(0), i);
476                 cx = f(cx, llfld_a, *arg);
477             }
478         }
479         ty::TyEnum(en, substs) => {
480             let fcx = cx.fcx;
481             let ccx = fcx.ccx;
482
483             let repr = adt::represent_type(ccx, t);
484             let n_variants = en.variants.len();
485
486             // NB: we must hit the discriminant first so that structural
487             // comparison know not to proceed when the discriminants differ.
488
489             match adt::trans_switch(cx, &repr, av, false) {
490                 (_match::Single, None) => {
491                     if n_variants != 0 {
492                         assert!(n_variants == 1);
493                         cx = iter_variant(cx, &repr, adt::MaybeSizedValue::sized(av),
494                                           &en.variants[0], substs, &mut f);
495                     }
496                 }
497                 (_match::Switch, Some(lldiscrim_a)) => {
498                     cx = f(cx, lldiscrim_a, cx.tcx().types.isize);
499
500                     // Create a fall-through basic block for the "else" case of
501                     // the switch instruction we're about to generate. Note that
502                     // we do **not** use an Unreachable instruction here, even
503                     // though most of the time this basic block will never be hit.
504                     //
505                     // When an enum is dropped it's contents are currently
506                     // overwritten to DTOR_DONE, which means the discriminant
507                     // could have changed value to something not within the actual
508                     // range of the discriminant. Currently this function is only
509                     // used for drop glue so in this case we just return quickly
510                     // from the outer function, and any other use case will only
511                     // call this for an already-valid enum in which case the `ret
512                     // void` will never be hit.
513                     let ret_void_cx = fcx.new_temp_block("enum-iter-ret-void");
514                     RetVoid(ret_void_cx, DebugLoc::None);
515                     let llswitch = Switch(cx, lldiscrim_a, ret_void_cx.llbb, n_variants);
516                     let next_cx = fcx.new_temp_block("enum-iter-next");
517
518                     for variant in &en.variants {
519                         let variant_cx = fcx.new_temp_block(&format!("enum-iter-variant-{}",
520                                                                      &variant.disr_val
521                                                                              .to_string()));
522                         let case_val = adt::trans_case(cx, &repr, Disr::from(variant.disr_val));
523                         AddCase(llswitch, case_val, variant_cx.llbb);
524                         let variant_cx = iter_variant(variant_cx,
525                                                       &repr,
526                                                       value,
527                                                       variant,
528                                                       substs,
529                                                       &mut f);
530                         Br(variant_cx, next_cx.llbb, DebugLoc::None);
531                     }
532                     cx = next_cx;
533                 }
534                 _ => ccx.sess().unimpl("value from adt::trans_switch in iter_structural_ty"),
535             }
536         }
537         _ => {
538             cx.sess().unimpl(&format!("type in iter_structural_ty: {}", t))
539         }
540     }
541     return cx;
542 }
543
544
545 /// Retrieve the information we are losing (making dynamic) in an unsizing
546 /// adjustment.
547 ///
548 /// The `old_info` argument is a bit funny. It is intended for use
549 /// in an upcast, where the new vtable for an object will be drived
550 /// from the old one.
551 pub fn unsized_info<'ccx, 'tcx>(ccx: &CrateContext<'ccx, 'tcx>,
552                                 source: Ty<'tcx>,
553                                 target: Ty<'tcx>,
554                                 old_info: Option<ValueRef>)
555                                 -> ValueRef {
556     let (source, target) = ccx.tcx().struct_lockstep_tails(source, target);
557     match (&source.sty, &target.sty) {
558         (&ty::TyArray(_, len), &ty::TySlice(_)) => C_uint(ccx, len),
559         (&ty::TyTrait(_), &ty::TyTrait(_)) => {
560             // For now, upcasts are limited to changes in marker
561             // traits, and hence never actually require an actual
562             // change to the vtable.
563             old_info.expect("unsized_info: missing old info for trait upcast")
564         }
565         (_, &ty::TyTrait(box ty::TraitTy { ref principal, .. })) => {
566             // Note that we preserve binding levels here:
567             let substs = principal.0.substs.with_self_ty(source).erase_regions();
568             let substs = ccx.tcx().mk_substs(substs);
569             let trait_ref = ty::Binder(ty::TraitRef {
570                 def_id: principal.def_id(),
571                 substs: substs,
572             });
573             consts::ptrcast(meth::get_vtable(ccx, trait_ref),
574                             Type::vtable_ptr(ccx))
575         }
576         _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}",
577                                      source,
578                                      target),
579     }
580 }
581
582 /// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer.
583 pub fn unsize_thin_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
584                                    src: ValueRef,
585                                    src_ty: Ty<'tcx>,
586                                    dst_ty: Ty<'tcx>)
587                                    -> (ValueRef, ValueRef) {
588     debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
589     match (&src_ty.sty, &dst_ty.sty) {
590         (&ty::TyBox(a), &ty::TyBox(b)) |
591         (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
592          &ty::TyRef(_, ty::TypeAndMut { ty: b, .. })) |
593         (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
594          &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) |
595         (&ty::TyRawPtr(ty::TypeAndMut { ty: a, .. }),
596          &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) => {
597             assert!(common::type_is_sized(bcx.tcx(), a));
598             let ptr_ty = type_of::in_memory_type_of(bcx.ccx(), b).ptr_to();
599             (PointerCast(bcx, src, ptr_ty),
600              unsized_info(bcx.ccx(), a, b, None))
601         }
602         _ => bug!("unsize_thin_ptr: called on bad types"),
603     }
604 }
605
606 /// Coerce `src`, which is a reference to a value of type `src_ty`,
607 /// to a value of type `dst_ty` and store the result in `dst`
608 pub fn coerce_unsized_into<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
609                                        src: ValueRef,
610                                        src_ty: Ty<'tcx>,
611                                        dst: ValueRef,
612                                        dst_ty: Ty<'tcx>) {
613     match (&src_ty.sty, &dst_ty.sty) {
614         (&ty::TyBox(..), &ty::TyBox(..)) |
615         (&ty::TyRef(..), &ty::TyRef(..)) |
616         (&ty::TyRef(..), &ty::TyRawPtr(..)) |
617         (&ty::TyRawPtr(..), &ty::TyRawPtr(..)) => {
618             let (base, info) = if common::type_is_fat_ptr(bcx.tcx(), src_ty) {
619                 // fat-ptr to fat-ptr unsize preserves the vtable
620                 // i.e. &'a fmt::Debug+Send => &'a fmt::Debug
621                 // So we need to pointercast the base to ensure
622                 // the types match up.
623                 let (base, info) = load_fat_ptr(bcx, src, src_ty);
624                 let llcast_ty = type_of::fat_ptr_base_ty(bcx.ccx(), dst_ty);
625                 let base = PointerCast(bcx, base, llcast_ty);
626                 (base, info)
627             } else {
628                 let base = load_ty(bcx, src, src_ty);
629                 unsize_thin_ptr(bcx, base, src_ty, dst_ty)
630             };
631             store_fat_ptr(bcx, base, info, dst, dst_ty);
632         }
633
634         // This can be extended to enums and tuples in the future.
635         // (&ty::TyEnum(def_id_a, _), &ty::TyEnum(def_id_b, _)) |
636         (&ty::TyStruct(def_a, _), &ty::TyStruct(def_b, _)) => {
637             assert_eq!(def_a, def_b);
638
639             let src_repr = adt::represent_type(bcx.ccx(), src_ty);
640             let src_fields = match &*src_repr {
641                 &adt::Repr::Univariant(ref s, _) => &s.fields,
642                 _ => bug!("struct has non-univariant repr"),
643             };
644             let dst_repr = adt::represent_type(bcx.ccx(), dst_ty);
645             let dst_fields = match &*dst_repr {
646                 &adt::Repr::Univariant(ref s, _) => &s.fields,
647                 _ => bug!("struct has non-univariant repr"),
648             };
649
650             let src = adt::MaybeSizedValue::sized(src);
651             let dst = adt::MaybeSizedValue::sized(dst);
652
653             let iter = src_fields.iter().zip(dst_fields).enumerate();
654             for (i, (src_fty, dst_fty)) in iter {
655                 if type_is_zero_size(bcx.ccx(), dst_fty) {
656                     continue;
657                 }
658
659                 let src_f = adt::trans_field_ptr(bcx, &src_repr, src, Disr(0), i);
660                 let dst_f = adt::trans_field_ptr(bcx, &dst_repr, dst, Disr(0), i);
661                 if src_fty == dst_fty {
662                     memcpy_ty(bcx, dst_f, src_f, src_fty);
663                 } else {
664                     coerce_unsized_into(bcx, src_f, src_fty, dst_f, dst_fty);
665                 }
666             }
667         }
668         _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}",
669                   src_ty,
670                   dst_ty),
671     }
672 }
673
674 pub fn custom_coerce_unsize_info<'scx, 'tcx>(scx: &SharedCrateContext<'scx, 'tcx>,
675                                              source_ty: Ty<'tcx>,
676                                              target_ty: Ty<'tcx>)
677                                              -> CustomCoerceUnsized {
678     let trait_substs = Substs::new(subst::VecPerParamSpace::new(vec![target_ty],
679                                                                 vec![source_ty],
680                                                                 Vec::new()),
681                                    subst::VecPerParamSpace::empty());
682
683     let trait_ref = ty::Binder(ty::TraitRef {
684         def_id: scx.tcx().lang_items.coerce_unsized_trait().unwrap(),
685         substs: scx.tcx().mk_substs(trait_substs)
686     });
687
688     match fulfill_obligation(scx, DUMMY_SP, trait_ref) {
689         traits::VtableImpl(traits::VtableImplData { impl_def_id, .. }) => {
690             scx.tcx().custom_coerce_unsized_kind(impl_def_id)
691         }
692         vtable => {
693             bug!("invalid CoerceUnsized vtable: {:?}", vtable);
694         }
695     }
696 }
697
698 pub fn cast_shift_expr_rhs(cx: Block, op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
699     cast_shift_rhs(op, lhs, rhs, |a, b| Trunc(cx, a, b), |a, b| ZExt(cx, a, b))
700 }
701
702 pub fn cast_shift_const_rhs(op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
703     cast_shift_rhs(op,
704                    lhs,
705                    rhs,
706                    |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
707                    |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
708 }
709
710 fn cast_shift_rhs<F, G>(op: hir::BinOp_,
711                         lhs: ValueRef,
712                         rhs: ValueRef,
713                         trunc: F,
714                         zext: G)
715                         -> ValueRef
716     where F: FnOnce(ValueRef, Type) -> ValueRef,
717           G: FnOnce(ValueRef, Type) -> ValueRef
718 {
719     // Shifts may have any size int on the rhs
720     if op.is_shift() {
721         let mut rhs_llty = val_ty(rhs);
722         let mut lhs_llty = val_ty(lhs);
723         if rhs_llty.kind() == Vector {
724             rhs_llty = rhs_llty.element_type()
725         }
726         if lhs_llty.kind() == Vector {
727             lhs_llty = lhs_llty.element_type()
728         }
729         let rhs_sz = rhs_llty.int_width();
730         let lhs_sz = lhs_llty.int_width();
731         if lhs_sz < rhs_sz {
732             trunc(rhs, lhs_llty)
733         } else if lhs_sz > rhs_sz {
734             // FIXME (#1877: If shifting by negative
735             // values becomes not undefined then this is wrong.
736             zext(rhs, lhs_llty)
737         } else {
738             rhs
739         }
740     } else {
741         rhs
742     }
743 }
744
745 pub fn llty_and_min_for_signed_ty<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
746                                               val_t: Ty<'tcx>)
747                                               -> (Type, u64) {
748     match val_t.sty {
749         ty::TyInt(t) => {
750             let llty = Type::int_from_ty(cx.ccx(), t);
751             let min = match t {
752                 ast::IntTy::Is if llty == Type::i32(cx.ccx()) => i32::MIN as u64,
753                 ast::IntTy::Is => i64::MIN as u64,
754                 ast::IntTy::I8 => i8::MIN as u64,
755                 ast::IntTy::I16 => i16::MIN as u64,
756                 ast::IntTy::I32 => i32::MIN as u64,
757                 ast::IntTy::I64 => i64::MIN as u64,
758             };
759             (llty, min)
760         }
761         _ => bug!(),
762     }
763 }
764
765 pub fn fail_if_zero_or_overflows<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
766                                              call_info: NodeIdAndSpan,
767                                              divrem: hir::BinOp,
768                                              lhs: ValueRef,
769                                              rhs: ValueRef,
770                                              rhs_t: Ty<'tcx>)
771                                              -> Block<'blk, 'tcx> {
772     use rustc_const_math::{ConstMathErr, Op};
773
774     let (zero_err, overflow_err) = if divrem.node == hir::BiDiv {
775         (ConstMathErr::DivisionByZero, ConstMathErr::Overflow(Op::Div))
776     } else {
777         (ConstMathErr::RemainderByZero, ConstMathErr::Overflow(Op::Rem))
778     };
779     let debug_loc = call_info.debug_loc();
780
781     let (is_zero, is_signed) = match rhs_t.sty {
782         ty::TyInt(t) => {
783             let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0, false);
784             (ICmp(cx, llvm::IntEQ, rhs, zero, debug_loc), true)
785         }
786         ty::TyUint(t) => {
787             let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0, false);
788             (ICmp(cx, llvm::IntEQ, rhs, zero, debug_loc), false)
789         }
790         ty::TyStruct(def, _) if def.is_simd() => {
791             let mut res = C_bool(cx.ccx(), false);
792             for i in 0..rhs_t.simd_size(cx.tcx()) {
793                 res = Or(cx,
794                          res,
795                          IsNull(cx, ExtractElement(cx, rhs, C_int(cx.ccx(), i as i64))),
796                          debug_loc);
797             }
798             (res, false)
799         }
800         _ => {
801             bug!("fail-if-zero on unexpected type: {}", rhs_t);
802         }
803     };
804     let bcx = with_cond(cx, is_zero, |bcx| {
805         controlflow::trans_fail(bcx, call_info, InternedString::new(zero_err.description()))
806     });
807
808     // To quote LLVM's documentation for the sdiv instruction:
809     //
810     //      Division by zero leads to undefined behavior. Overflow also leads
811     //      to undefined behavior; this is a rare case, but can occur, for
812     //      example, by doing a 32-bit division of -2147483648 by -1.
813     //
814     // In order to avoid undefined behavior, we perform runtime checks for
815     // signed division/remainder which would trigger overflow. For unsigned
816     // integers, no action beyond checking for zero need be taken.
817     if is_signed {
818         let (llty, min) = llty_and_min_for_signed_ty(cx, rhs_t);
819         let minus_one = ICmp(bcx,
820                              llvm::IntEQ,
821                              rhs,
822                              C_integral(llty, !0, false),
823                              debug_loc);
824         with_cond(bcx, minus_one, |bcx| {
825             let is_min = ICmp(bcx,
826                               llvm::IntEQ,
827                               lhs,
828                               C_integral(llty, min, true),
829                               debug_loc);
830             with_cond(bcx, is_min, |bcx| {
831                 controlflow::trans_fail(bcx, call_info,
832                                         InternedString::new(overflow_err.description()))
833             })
834         })
835     } else {
836         bcx
837     }
838 }
839
840 pub fn invoke<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
841                           llfn: ValueRef,
842                           llargs: &[ValueRef],
843                           debug_loc: DebugLoc)
844                           -> (ValueRef, Block<'blk, 'tcx>) {
845     let _icx = push_ctxt("invoke_");
846     if bcx.unreachable.get() {
847         return (C_null(Type::i8(bcx.ccx())), bcx);
848     }
849
850     match bcx.opt_node_id {
851         None => {
852             debug!("invoke at ???");
853         }
854         Some(id) => {
855             debug!("invoke at {}", bcx.tcx().map.node_to_string(id));
856         }
857     }
858
859     if need_invoke(bcx) {
860         debug!("invoking {:?} at {:?}", Value(llfn), bcx.llbb);
861         for &llarg in llargs {
862             debug!("arg: {:?}", Value(llarg));
863         }
864         let normal_bcx = bcx.fcx.new_temp_block("normal-return");
865         let landing_pad = bcx.fcx.get_landing_pad();
866
867         let llresult = Invoke(bcx,
868                               llfn,
869                               &llargs[..],
870                               normal_bcx.llbb,
871                               landing_pad,
872                               debug_loc);
873         return (llresult, normal_bcx);
874     } else {
875         debug!("calling {:?} at {:?}", Value(llfn), bcx.llbb);
876         for &llarg in llargs {
877             debug!("arg: {:?}", Value(llarg));
878         }
879
880         let llresult = Call(bcx, llfn, &llargs[..], debug_loc);
881         return (llresult, bcx);
882     }
883 }
884
885 /// Returns whether this session's target will use SEH-based unwinding.
886 ///
887 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
888 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
889 /// 64-bit MinGW) instead of "full SEH".
890 pub fn wants_msvc_seh(sess: &Session) -> bool {
891     sess.target.target.options.is_like_msvc
892 }
893
894 pub fn avoid_invoke(bcx: Block) -> bool {
895     bcx.sess().no_landing_pads() || bcx.lpad().is_some()
896 }
897
898 pub fn need_invoke(bcx: Block) -> bool {
899     if avoid_invoke(bcx) {
900         false
901     } else {
902         bcx.fcx.needs_invoke()
903     }
904 }
905
906 pub fn load_if_immediate<'blk, 'tcx>(cx: Block<'blk, 'tcx>, v: ValueRef, t: Ty<'tcx>) -> ValueRef {
907     let _icx = push_ctxt("load_if_immediate");
908     if type_is_immediate(cx.ccx(), t) {
909         return load_ty(cx, v, t);
910     }
911     return v;
912 }
913
914 /// Helper for loading values from memory. Does the necessary conversion if the in-memory type
915 /// differs from the type used for SSA values. Also handles various special cases where the type
916 /// gives us better information about what we are loading.
917 pub fn load_ty<'blk, 'tcx>(cx: Block<'blk, 'tcx>, ptr: ValueRef, t: Ty<'tcx>) -> ValueRef {
918     if cx.unreachable.get() {
919         return C_undef(type_of::type_of(cx.ccx(), t));
920     }
921     load_ty_builder(&B(cx), ptr, t)
922 }
923
924 pub fn load_ty_builder<'a, 'tcx>(b: &Builder<'a, 'tcx>, ptr: ValueRef, t: Ty<'tcx>) -> ValueRef {
925     let ccx = b.ccx;
926     if type_is_zero_size(ccx, t) {
927         return C_undef(type_of::type_of(ccx, t));
928     }
929
930     unsafe {
931         let global = llvm::LLVMIsAGlobalVariable(ptr);
932         if !global.is_null() && llvm::LLVMIsGlobalConstant(global) == llvm::True {
933             let val = llvm::LLVMGetInitializer(global);
934             if !val.is_null() {
935                 if t.is_bool() {
936                     return llvm::LLVMConstTrunc(val, Type::i1(ccx).to_ref());
937                 }
938                 return val;
939             }
940         }
941     }
942
943     if t.is_bool() {
944         b.trunc(b.load_range_assert(ptr, 0, 2, llvm::False), Type::i1(ccx))
945     } else if t.is_char() {
946         // a char is a Unicode codepoint, and so takes values from 0
947         // to 0x10FFFF inclusive only.
948         b.load_range_assert(ptr, 0, 0x10FFFF + 1, llvm::False)
949     } else if (t.is_region_ptr() || t.is_unique()) &&
950               !common::type_is_fat_ptr(ccx.tcx(), t) {
951         b.load_nonnull(ptr)
952     } else {
953         b.load(ptr)
954     }
955 }
956
957 /// Helper for storing values in memory. Does the necessary conversion if the in-memory type
958 /// differs from the type used for SSA values.
959 pub fn store_ty<'blk, 'tcx>(cx: Block<'blk, 'tcx>, v: ValueRef, dst: ValueRef, t: Ty<'tcx>) {
960     if cx.unreachable.get() {
961         return;
962     }
963
964     debug!("store_ty: {:?} : {:?} <- {:?}", Value(dst), t, Value(v));
965
966     if common::type_is_fat_ptr(cx.tcx(), t) {
967         Store(cx,
968               ExtractValue(cx, v, abi::FAT_PTR_ADDR),
969               expr::get_dataptr(cx, dst));
970         Store(cx,
971               ExtractValue(cx, v, abi::FAT_PTR_EXTRA),
972               expr::get_meta(cx, dst));
973     } else {
974         Store(cx, from_immediate(cx, v), dst);
975     }
976 }
977
978 pub fn store_fat_ptr<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
979                                  data: ValueRef,
980                                  extra: ValueRef,
981                                  dst: ValueRef,
982                                  _ty: Ty<'tcx>) {
983     // FIXME: emit metadata
984     Store(cx, data, expr::get_dataptr(cx, dst));
985     Store(cx, extra, expr::get_meta(cx, dst));
986 }
987
988 pub fn load_fat_ptr<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
989                                 src: ValueRef,
990                                 _ty: Ty<'tcx>)
991                                 -> (ValueRef, ValueRef) {
992     // FIXME: emit metadata
993     (Load(cx, expr::get_dataptr(cx, src)),
994      Load(cx, expr::get_meta(cx, src)))
995 }
996
997 pub fn from_immediate(bcx: Block, val: ValueRef) -> ValueRef {
998     if val_ty(val) == Type::i1(bcx.ccx()) {
999         ZExt(bcx, val, Type::i8(bcx.ccx()))
1000     } else {
1001         val
1002     }
1003 }
1004
1005 pub fn to_immediate(bcx: Block, val: ValueRef, ty: Ty) -> ValueRef {
1006     if ty.is_bool() {
1007         Trunc(bcx, val, Type::i1(bcx.ccx()))
1008     } else {
1009         val
1010     }
1011 }
1012
1013 pub fn init_local<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, local: &hir::Local) -> Block<'blk, 'tcx> {
1014     debug!("init_local(bcx={}, local.id={})", bcx.to_str(), local.id);
1015     let _indenter = indenter();
1016     let _icx = push_ctxt("init_local");
1017     _match::store_local(bcx, local)
1018 }
1019
1020 pub fn raw_block<'blk, 'tcx>(fcx: &'blk FunctionContext<'blk, 'tcx>,
1021                              llbb: BasicBlockRef)
1022                              -> Block<'blk, 'tcx> {
1023     common::BlockS::new(llbb, None, fcx)
1024 }
1025
1026 pub fn with_cond<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>, val: ValueRef, f: F) -> Block<'blk, 'tcx>
1027     where F: FnOnce(Block<'blk, 'tcx>) -> Block<'blk, 'tcx>
1028 {
1029     let _icx = push_ctxt("with_cond");
1030
1031     if bcx.unreachable.get() || common::const_to_opt_uint(val) == Some(0) {
1032         return bcx;
1033     }
1034
1035     let fcx = bcx.fcx;
1036     let next_cx = fcx.new_temp_block("next");
1037     let cond_cx = fcx.new_temp_block("cond");
1038     CondBr(bcx, val, cond_cx.llbb, next_cx.llbb, DebugLoc::None);
1039     let after_cx = f(cond_cx);
1040     if !after_cx.terminated.get() {
1041         Br(after_cx, next_cx.llbb, DebugLoc::None);
1042     }
1043     next_cx
1044 }
1045
1046 pub enum Lifetime { Start, End }
1047
1048 // If LLVM lifetime intrinsic support is enabled (i.e. optimizations
1049 // on), and `ptr` is nonzero-sized, then extracts the size of `ptr`
1050 // and the intrinsic for `lt` and passes them to `emit`, which is in
1051 // charge of generating code to call the passed intrinsic on whatever
1052 // block of generated code is targetted for the intrinsic.
1053 //
1054 // If LLVM lifetime intrinsic support is disabled (i.e.  optimizations
1055 // off) or `ptr` is zero-sized, then no-op (does not call `emit`).
1056 fn core_lifetime_emit<'blk, 'tcx, F>(ccx: &'blk CrateContext<'blk, 'tcx>,
1057                                      ptr: ValueRef,
1058                                      lt: Lifetime,
1059                                      emit: F)
1060     where F: FnOnce(&'blk CrateContext<'blk, 'tcx>, machine::llsize, ValueRef)
1061 {
1062     if ccx.sess().opts.optimize == config::OptLevel::No {
1063         return;
1064     }
1065
1066     let _icx = push_ctxt(match lt {
1067         Lifetime::Start => "lifetime_start",
1068         Lifetime::End => "lifetime_end"
1069     });
1070
1071     let size = machine::llsize_of_alloc(ccx, val_ty(ptr).element_type());
1072     if size == 0 {
1073         return;
1074     }
1075
1076     let lifetime_intrinsic = ccx.get_intrinsic(match lt {
1077         Lifetime::Start => "llvm.lifetime.start",
1078         Lifetime::End => "llvm.lifetime.end"
1079     });
1080     emit(ccx, size, lifetime_intrinsic)
1081 }
1082
1083 impl Lifetime {
1084     pub fn call(self, b: &Builder, ptr: ValueRef) {
1085         core_lifetime_emit(b.ccx, ptr, self, |ccx, size, lifetime_intrinsic| {
1086             let ptr = b.pointercast(ptr, Type::i8p(ccx));
1087             b.call(lifetime_intrinsic, &[C_u64(ccx, size), ptr], None);
1088         });
1089     }
1090 }
1091
1092 pub fn call_lifetime_start(bcx: Block, ptr: ValueRef) {
1093     if !bcx.unreachable.get() {
1094         Lifetime::Start.call(&bcx.build(), ptr);
1095     }
1096 }
1097
1098 pub fn call_lifetime_end(bcx: Block, ptr: ValueRef) {
1099     if !bcx.unreachable.get() {
1100         Lifetime::End.call(&bcx.build(), ptr);
1101     }
1102 }
1103
1104 // Generates code for resumption of unwind at the end of a landing pad.
1105 pub fn trans_unwind_resume(bcx: Block, lpval: ValueRef) {
1106     if !bcx.sess().target.target.options.custom_unwind_resume {
1107         Resume(bcx, lpval);
1108     } else {
1109         let exc_ptr = ExtractValue(bcx, lpval, 0);
1110         bcx.fcx.eh_unwind_resume()
1111             .call(bcx, DebugLoc::None, ArgVals(&[exc_ptr]), None);
1112     }
1113 }
1114
1115 pub fn call_memcpy<'bcx, 'tcx>(b: &Builder<'bcx, 'tcx>,
1116                                dst: ValueRef,
1117                                src: ValueRef,
1118                                n_bytes: ValueRef,
1119                                align: u32) {
1120     let _icx = push_ctxt("call_memcpy");
1121     let ccx = b.ccx;
1122     let ptr_width = &ccx.sess().target.target.target_pointer_width[..];
1123     let key = format!("llvm.memcpy.p0i8.p0i8.i{}", ptr_width);
1124     let memcpy = ccx.get_intrinsic(&key);
1125     let src_ptr = b.pointercast(src, Type::i8p(ccx));
1126     let dst_ptr = b.pointercast(dst, Type::i8p(ccx));
1127     let size = b.intcast(n_bytes, ccx.int_type());
1128     let align = C_i32(ccx, align as i32);
1129     let volatile = C_bool(ccx, false);
1130     b.call(memcpy, &[dst_ptr, src_ptr, size, align, volatile], None);
1131 }
1132
1133 pub fn memcpy_ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, dst: ValueRef, src: ValueRef, t: Ty<'tcx>) {
1134     let _icx = push_ctxt("memcpy_ty");
1135     let ccx = bcx.ccx();
1136
1137     if type_is_zero_size(ccx, t) || bcx.unreachable.get() {
1138         return;
1139     }
1140
1141     if t.is_structural() {
1142         let llty = type_of::type_of(ccx, t);
1143         let llsz = llsize_of(ccx, llty);
1144         let llalign = type_of::align_of(ccx, t);
1145         call_memcpy(&B(bcx), dst, src, llsz, llalign as u32);
1146     } else if common::type_is_fat_ptr(bcx.tcx(), t) {
1147         let (data, extra) = load_fat_ptr(bcx, src, t);
1148         store_fat_ptr(bcx, data, extra, dst, t);
1149     } else {
1150         store_ty(bcx, load_ty(bcx, src, t), dst, t);
1151     }
1152 }
1153
1154 pub fn drop_done_fill_mem<'blk, 'tcx>(cx: Block<'blk, 'tcx>, llptr: ValueRef, t: Ty<'tcx>) {
1155     if cx.unreachable.get() {
1156         return;
1157     }
1158     let _icx = push_ctxt("drop_done_fill_mem");
1159     let bcx = cx;
1160     memfill(&B(bcx), llptr, t, adt::DTOR_DONE);
1161 }
1162
1163 pub fn init_zero_mem<'blk, 'tcx>(cx: Block<'blk, 'tcx>, llptr: ValueRef, t: Ty<'tcx>) {
1164     if cx.unreachable.get() {
1165         return;
1166     }
1167     let _icx = push_ctxt("init_zero_mem");
1168     let bcx = cx;
1169     memfill(&B(bcx), llptr, t, 0);
1170 }
1171
1172 // Always use this function instead of storing a constant byte to the memory
1173 // in question. e.g. if you store a zero constant, LLVM will drown in vreg
1174 // allocation for large data structures, and the generated code will be
1175 // awful. (A telltale sign of this is large quantities of
1176 // `mov [byte ptr foo],0` in the generated code.)
1177 fn memfill<'a, 'tcx>(b: &Builder<'a, 'tcx>, llptr: ValueRef, ty: Ty<'tcx>, byte: u8) {
1178     let _icx = push_ctxt("memfill");
1179     let ccx = b.ccx;
1180     let llty = type_of::type_of(ccx, ty);
1181     let llptr = b.pointercast(llptr, Type::i8(ccx).ptr_to());
1182     let llzeroval = C_u8(ccx, byte);
1183     let size = machine::llsize_of(ccx, llty);
1184     let align = C_i32(ccx, type_of::align_of(ccx, ty) as i32);
1185     call_memset(b, llptr, llzeroval, size, align, false);
1186 }
1187
1188 pub fn call_memset<'bcx, 'tcx>(b: &Builder<'bcx, 'tcx>,
1189                                ptr: ValueRef,
1190                                fill_byte: ValueRef,
1191                                size: ValueRef,
1192                                align: ValueRef,
1193                                volatile: bool) {
1194     let ccx = b.ccx;
1195     let ptr_width = &ccx.sess().target.target.target_pointer_width[..];
1196     let intrinsic_key = format!("llvm.memset.p0i8.i{}", ptr_width);
1197     let llintrinsicfn = ccx.get_intrinsic(&intrinsic_key);
1198     let volatile = C_bool(ccx, volatile);
1199     b.call(llintrinsicfn, &[ptr, fill_byte, size, align, volatile], None);
1200 }
1201
1202
1203 /// In general, when we create an scratch value in an alloca, the
1204 /// creator may not know if the block (that initializes the scratch
1205 /// with the desired value) actually dominates the cleanup associated
1206 /// with the scratch value.
1207 ///
1208 /// To deal with this, when we do an alloca (at the *start* of whole
1209 /// function body), we optionally can also set the associated
1210 /// dropped-flag state of the alloca to "dropped."
1211 #[derive(Copy, Clone, Debug)]
1212 pub enum InitAlloca {
1213     /// Indicates that the state should have its associated drop flag
1214     /// set to "dropped" at the point of allocation.
1215     Dropped,
1216     /// Indicates the value of the associated drop flag is irrelevant.
1217     /// The embedded string literal is a programmer provided argument
1218     /// for why. This is a safeguard forcing compiler devs to
1219     /// document; it might be a good idea to also emit this as a
1220     /// comment with the alloca itself when emitting LLVM output.ll.
1221     Uninit(&'static str),
1222 }
1223
1224
1225 pub fn alloc_ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1226                             t: Ty<'tcx>,
1227                             name: &str) -> ValueRef {
1228     // pnkfelix: I do not know why alloc_ty meets the assumptions for
1229     // passing Uninit, but it was never needed (even back when we had
1230     // the original boolean `zero` flag on `lvalue_scratch_datum`).
1231     alloc_ty_init(bcx, t, InitAlloca::Uninit("all alloc_ty are uninit"), name)
1232 }
1233
1234 /// This variant of `fn alloc_ty` does not necessarily assume that the
1235 /// alloca should be created with no initial value. Instead the caller
1236 /// controls that assumption via the `init` flag.
1237 ///
1238 /// Note that if the alloca *is* initialized via `init`, then we will
1239 /// also inject an `llvm.lifetime.start` before that initialization
1240 /// occurs, and thus callers should not call_lifetime_start
1241 /// themselves.  But if `init` says "uninitialized", then callers are
1242 /// in charge of choosing where to call_lifetime_start and
1243 /// subsequently populate the alloca.
1244 ///
1245 /// (See related discussion on PR #30823.)
1246 pub fn alloc_ty_init<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1247                              t: Ty<'tcx>,
1248                              init: InitAlloca,
1249                              name: &str) -> ValueRef {
1250     let _icx = push_ctxt("alloc_ty");
1251     let ccx = bcx.ccx();
1252     let ty = type_of::type_of(ccx, t);
1253     assert!(!t.has_param_types());
1254     match init {
1255         InitAlloca::Dropped => alloca_dropped(bcx, t, name),
1256         InitAlloca::Uninit(_) => alloca(bcx, ty, name),
1257     }
1258 }
1259
1260 pub fn alloca_dropped<'blk, 'tcx>(cx: Block<'blk, 'tcx>, ty: Ty<'tcx>, name: &str) -> ValueRef {
1261     let _icx = push_ctxt("alloca_dropped");
1262     let llty = type_of::type_of(cx.ccx(), ty);
1263     if cx.unreachable.get() {
1264         unsafe { return llvm::LLVMGetUndef(llty.ptr_to().to_ref()); }
1265     }
1266     let p = alloca(cx, llty, name);
1267     let b = cx.fcx.ccx.builder();
1268     b.position_before(cx.fcx.alloca_insert_pt.get().unwrap());
1269
1270     // This is just like `call_lifetime_start` (but latter expects a
1271     // Block, which we do not have for `alloca_insert_pt`).
1272     core_lifetime_emit(cx.ccx(), p, Lifetime::Start, |ccx, size, lifetime_start| {
1273         let ptr = b.pointercast(p, Type::i8p(ccx));
1274         b.call(lifetime_start, &[C_u64(ccx, size), ptr], None);
1275     });
1276     memfill(&b, p, ty, adt::DTOR_DONE);
1277     p
1278 }
1279
1280 pub fn alloca(cx: Block, ty: Type, name: &str) -> ValueRef {
1281     let _icx = push_ctxt("alloca");
1282     if cx.unreachable.get() {
1283         unsafe {
1284             return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1285         }
1286     }
1287     DebugLoc::None.apply(cx.fcx);
1288     Alloca(cx, ty, name)
1289 }
1290
1291 pub fn set_value_name(val: ValueRef, name: &str) {
1292     unsafe {
1293         let name = CString::new(name).unwrap();
1294         llvm::LLVMSetValueName(val, name.as_ptr());
1295     }
1296 }
1297
1298 struct FindNestedReturn {
1299     found: bool,
1300 }
1301
1302 impl FindNestedReturn {
1303     fn new() -> FindNestedReturn {
1304         FindNestedReturn {
1305             found: false,
1306         }
1307     }
1308 }
1309
1310 impl<'v> Visitor<'v> for FindNestedReturn {
1311     fn visit_expr(&mut self, e: &hir::Expr) {
1312         match e.node {
1313             hir::ExprRet(..) => {
1314                 self.found = true;
1315             }
1316             _ => intravisit::walk_expr(self, e),
1317         }
1318     }
1319 }
1320
1321 fn build_cfg<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1322                        id: ast::NodeId)
1323                        -> (ast::NodeId, Option<cfg::CFG>) {
1324     let blk = match tcx.map.find(id) {
1325         Some(hir_map::NodeItem(i)) => {
1326             match i.node {
1327                 hir::ItemFn(_, _, _, _, _, ref blk) => {
1328                     blk
1329                 }
1330                 _ => bug!("unexpected item variant in has_nested_returns"),
1331             }
1332         }
1333         Some(hir_map::NodeTraitItem(trait_item)) => {
1334             match trait_item.node {
1335                 hir::MethodTraitItem(_, Some(ref body)) => body,
1336                 _ => {
1337                     bug!("unexpected variant: trait item other than a provided method in \
1338                           has_nested_returns")
1339                 }
1340             }
1341         }
1342         Some(hir_map::NodeImplItem(impl_item)) => {
1343             match impl_item.node {
1344                 hir::ImplItemKind::Method(_, ref body) => body,
1345                 _ => {
1346                     bug!("unexpected variant: non-method impl item in has_nested_returns")
1347                 }
1348             }
1349         }
1350         Some(hir_map::NodeExpr(e)) => {
1351             match e.node {
1352                 hir::ExprClosure(_, _, ref blk, _) => blk,
1353                 _ => bug!("unexpected expr variant in has_nested_returns"),
1354             }
1355         }
1356         Some(hir_map::NodeVariant(..)) |
1357         Some(hir_map::NodeStructCtor(..)) => return (ast::DUMMY_NODE_ID, None),
1358
1359         // glue, shims, etc
1360         None if id == ast::DUMMY_NODE_ID => return (ast::DUMMY_NODE_ID, None),
1361
1362         _ => bug!("unexpected variant in has_nested_returns: {}",
1363                   tcx.node_path_str(id)),
1364     };
1365
1366     (blk.id, Some(cfg::CFG::new(tcx, blk)))
1367 }
1368
1369 // Checks for the presence of "nested returns" in a function.
1370 // Nested returns are when the inner expression of a return expression
1371 // (the 'expr' in 'return expr') contains a return expression. Only cases
1372 // where the outer return is actually reachable are considered. Implicit
1373 // returns from the end of blocks are considered as well.
1374 //
1375 // This check is needed to handle the case where the inner expression is
1376 // part of a larger expression that may have already partially-filled the
1377 // return slot alloca. This can cause errors related to clean-up due to
1378 // the clobbering of the existing value in the return slot.
1379 fn has_nested_returns(tcx: TyCtxt, cfg: &cfg::CFG, blk_id: ast::NodeId) -> bool {
1380     for index in cfg.graph.depth_traverse(cfg.entry, OUTGOING) {
1381         let n = cfg.graph.node_data(index);
1382         match tcx.map.find(n.id()) {
1383             Some(hir_map::NodeExpr(ex)) => {
1384                 if let hir::ExprRet(Some(ref ret_expr)) = ex.node {
1385                     let mut visitor = FindNestedReturn::new();
1386                     intravisit::walk_expr(&mut visitor, &ret_expr);
1387                     if visitor.found {
1388                         return true;
1389                     }
1390                 }
1391             }
1392             Some(hir_map::NodeBlock(blk)) if blk.id == blk_id => {
1393                 let mut visitor = FindNestedReturn::new();
1394                 walk_list!(&mut visitor, visit_expr, &blk.expr);
1395                 if visitor.found {
1396                     return true;
1397                 }
1398             }
1399             _ => {}
1400         }
1401     }
1402
1403     return false;
1404 }
1405
1406 impl<'blk, 'tcx> FunctionContext<'blk, 'tcx> {
1407     /// Create a function context for the given function.
1408     /// Beware that you must call `fcx.init` or `fcx.bind_args`
1409     /// before doing anything with the returned function context.
1410     pub fn new(ccx: &'blk CrateContext<'blk, 'tcx>,
1411                llfndecl: ValueRef,
1412                fn_ty: FnType,
1413                definition: Option<(Instance<'tcx>, &ty::FnSig<'tcx>, Abi, ast::NodeId)>,
1414                block_arena: &'blk TypedArena<common::BlockS<'blk, 'tcx>>)
1415                -> FunctionContext<'blk, 'tcx> {
1416         let (param_substs, def_id, inlined_id) = match definition {
1417             Some((instance, _, _, inlined_id)) => {
1418                 common::validate_substs(instance.substs);
1419                 (instance.substs, Some(instance.def), Some(inlined_id))
1420             }
1421             None => (ccx.tcx().mk_substs(Substs::empty()), None, None)
1422         };
1423
1424         let local_id = def_id.and_then(|id| ccx.tcx().map.as_local_node_id(id));
1425
1426         debug!("FunctionContext::new({})",
1427                definition.map_or(String::new(), |d| d.0.to_string()));
1428
1429         let cfg = inlined_id.map(|id| build_cfg(ccx.tcx(), id));
1430         let nested_returns = if let Some((blk_id, Some(ref cfg))) = cfg {
1431             has_nested_returns(ccx.tcx(), cfg, blk_id)
1432         } else {
1433             false
1434         };
1435
1436         let check_attrs = |attrs: &[ast::Attribute]| {
1437             let default_to_mir = ccx.sess().opts.debugging_opts.orbit;
1438             let invert = if default_to_mir { "rustc_no_mir" } else { "rustc_mir" };
1439             (default_to_mir ^ attrs.iter().any(|item| item.check_name(invert)),
1440              attrs.iter().any(|item| item.check_name("no_debug")))
1441         };
1442
1443         let (use_mir, no_debug) = if let Some(id) = local_id {
1444             check_attrs(ccx.tcx().map.attrs(id))
1445         } else if let Some(def_id) = def_id {
1446             check_attrs(&ccx.sess().cstore.item_attrs(def_id))
1447         } else {
1448             check_attrs(&[])
1449         };
1450
1451         let mir = if use_mir {
1452             def_id.and_then(|id| ccx.get_mir(id))
1453         } else {
1454             None
1455         };
1456
1457         let debug_context = if let (false, Some(definition)) = (no_debug, definition) {
1458             let (instance, sig, abi, _) = definition;
1459             debuginfo::create_function_debug_context(ccx, instance, sig, abi, llfndecl)
1460         } else {
1461             debuginfo::empty_function_debug_context(ccx)
1462         };
1463
1464         FunctionContext {
1465             needs_ret_allocas: nested_returns && mir.is_none(),
1466             mir: mir,
1467             llfn: llfndecl,
1468             llretslotptr: Cell::new(None),
1469             param_env: ccx.tcx().empty_parameter_environment(),
1470             alloca_insert_pt: Cell::new(None),
1471             llreturn: Cell::new(None),
1472             landingpad_alloca: Cell::new(None),
1473             lllocals: RefCell::new(NodeMap()),
1474             llupvars: RefCell::new(NodeMap()),
1475             lldropflag_hints: RefCell::new(DropFlagHintsMap::new()),
1476             fn_ty: fn_ty,
1477             param_substs: param_substs,
1478             span: inlined_id.and_then(|id| ccx.tcx().map.opt_span(id)),
1479             block_arena: block_arena,
1480             lpad_arena: TypedArena::new(),
1481             ccx: ccx,
1482             debug_context: debug_context,
1483             scopes: RefCell::new(Vec::new()),
1484             cfg: cfg.and_then(|(_, cfg)| cfg)
1485         }
1486     }
1487
1488     /// Performs setup on a newly created function, creating the entry
1489     /// scope block and allocating space for the return pointer.
1490     pub fn init(&'blk self, skip_retptr: bool, fn_did: Option<DefId>)
1491                 -> Block<'blk, 'tcx> {
1492         let entry_bcx = self.new_temp_block("entry-block");
1493
1494         // Use a dummy instruction as the insertion point for all allocas.
1495         // This is later removed in FunctionContext::cleanup.
1496         self.alloca_insert_pt.set(Some(unsafe {
1497             Load(entry_bcx, C_null(Type::i8p(self.ccx)));
1498             llvm::LLVMGetFirstInstruction(entry_bcx.llbb)
1499         }));
1500
1501         if !self.fn_ty.ret.is_ignore() && !skip_retptr {
1502             // We normally allocate the llretslotptr, unless we
1503             // have been instructed to skip it for immediate return
1504             // values, or there is nothing to return at all.
1505
1506             // We create an alloca to hold a pointer of type `ret.original_ty`
1507             // which will hold the pointer to the right alloca which has the
1508             // final ret value
1509             let llty = self.fn_ty.ret.memory_ty(self.ccx);
1510             let slot = if self.needs_ret_allocas {
1511                 // Let's create the stack slot
1512                 let slot = AllocaFcx(self, llty.ptr_to(), "llretslotptr");
1513
1514                 // and if we're using an out pointer, then store that in our newly made slot
1515                 if self.fn_ty.ret.is_indirect() {
1516                     let outptr = get_param(self.llfn, 0);
1517
1518                     let b = self.ccx.builder();
1519                     b.position_before(self.alloca_insert_pt.get().unwrap());
1520                     b.store(outptr, slot);
1521                 }
1522
1523                 slot
1524             } else {
1525                 // But if there are no nested returns, we skip the indirection
1526                 // and have a single retslot
1527                 if self.fn_ty.ret.is_indirect() {
1528                     get_param(self.llfn, 0)
1529                 } else {
1530                     AllocaFcx(self, llty, "sret_slot")
1531                 }
1532             };
1533
1534             self.llretslotptr.set(Some(slot));
1535         }
1536
1537         // Create the drop-flag hints for every unfragmented path in the function.
1538         let tcx = self.ccx.tcx();
1539         let tables = tcx.tables.borrow();
1540         let mut hints = self.lldropflag_hints.borrow_mut();
1541         let fragment_infos = tcx.fragment_infos.borrow();
1542
1543         // Intern table for drop-flag hint datums.
1544         let mut seen = HashMap::new();
1545
1546         let fragment_infos = fn_did.and_then(|did| fragment_infos.get(&did));
1547         if let Some(fragment_infos) = fragment_infos {
1548             for &info in fragment_infos {
1549
1550                 let make_datum = |id| {
1551                     let init_val = C_u8(self.ccx, adt::DTOR_NEEDED_HINT);
1552                     let llname = &format!("dropflag_hint_{}", id);
1553                     debug!("adding hint {}", llname);
1554                     let ty = tcx.types.u8;
1555                     let ptr = alloc_ty(entry_bcx, ty, llname);
1556                     Store(entry_bcx, init_val, ptr);
1557                     let flag = datum::Lvalue::new_dropflag_hint("FunctionContext::init");
1558                     datum::Datum::new(ptr, ty, flag)
1559                 };
1560
1561                 let (var, datum) = match info {
1562                     ty::FragmentInfo::Moved { var, .. } |
1563                     ty::FragmentInfo::Assigned { var, .. } => {
1564                         let opt_datum = seen.get(&var).cloned().unwrap_or_else(|| {
1565                             let ty = tables.node_types[&var];
1566                             if self.type_needs_drop(ty) {
1567                                 let datum = make_datum(var);
1568                                 seen.insert(var, Some(datum.clone()));
1569                                 Some(datum)
1570                             } else {
1571                                 // No drop call needed, so we don't need a dropflag hint
1572                                 None
1573                             }
1574                         });
1575                         if let Some(datum) = opt_datum {
1576                             (var, datum)
1577                         } else {
1578                             continue
1579                         }
1580                     }
1581                 };
1582                 match info {
1583                     ty::FragmentInfo::Moved { move_expr: expr_id, .. } => {
1584                         debug!("FragmentInfo::Moved insert drop hint for {}", expr_id);
1585                         hints.insert(expr_id, DropHint::new(var, datum));
1586                     }
1587                     ty::FragmentInfo::Assigned { assignee_id: expr_id, .. } => {
1588                         debug!("FragmentInfo::Assigned insert drop hint for {}", expr_id);
1589                         hints.insert(expr_id, DropHint::new(var, datum));
1590                     }
1591                 }
1592             }
1593         }
1594
1595         entry_bcx
1596     }
1597
1598     /// Creates lvalue datums for each of the incoming function arguments,
1599     /// matches all argument patterns against them to produce bindings,
1600     /// and returns the entry block (see FunctionContext::init).
1601     fn bind_args(&'blk self,
1602                  args: &[hir::Arg],
1603                  abi: Abi,
1604                  id: ast::NodeId,
1605                  closure_env: closure::ClosureEnv,
1606                  arg_scope: cleanup::CustomScopeIndex)
1607                  -> Block<'blk, 'tcx> {
1608         let _icx = push_ctxt("FunctionContext::bind_args");
1609         let fn_did = self.ccx.tcx().map.local_def_id(id);
1610         let mut bcx = self.init(false, Some(fn_did));
1611         let arg_scope_id = cleanup::CustomScope(arg_scope);
1612
1613         let mut idx = 0;
1614         let mut llarg_idx = self.fn_ty.ret.is_indirect() as usize;
1615
1616         let has_tupled_arg = match closure_env {
1617             closure::ClosureEnv::NotClosure => abi == Abi::RustCall,
1618             closure::ClosureEnv::Closure(..) => {
1619                 closure_env.load(bcx, arg_scope_id);
1620                 let env_arg = &self.fn_ty.args[idx];
1621                 idx += 1;
1622                 if env_arg.pad.is_some() {
1623                     llarg_idx += 1;
1624                 }
1625                 if !env_arg.is_ignore() {
1626                     llarg_idx += 1;
1627                 }
1628                 false
1629             }
1630         };
1631         let tupled_arg_id = if has_tupled_arg {
1632             args[args.len() - 1].id
1633         } else {
1634             ast::DUMMY_NODE_ID
1635         };
1636
1637         // Return an array wrapping the ValueRefs that we get from `get_param` for
1638         // each argument into datums.
1639         //
1640         // For certain mode/type combinations, the raw llarg values are passed
1641         // by value.  However, within the fn body itself, we want to always
1642         // have all locals and arguments be by-ref so that we can cancel the
1643         // cleanup and for better interaction with LLVM's debug info.  So, if
1644         // the argument would be passed by value, we store it into an alloca.
1645         // This alloca should be optimized away by LLVM's mem-to-reg pass in
1646         // the event it's not truly needed.
1647         let uninit_reason = InitAlloca::Uninit("fn_arg populate dominates dtor");
1648         for hir_arg in args {
1649             let arg_ty = node_id_type(bcx, hir_arg.id);
1650             let arg_datum = if hir_arg.id != tupled_arg_id {
1651                 let arg = &self.fn_ty.args[idx];
1652                 idx += 1;
1653                 if arg.is_indirect() && bcx.sess().opts.debuginfo != FullDebugInfo {
1654                     // Don't copy an indirect argument to an alloca, the caller
1655                     // already put it in a temporary alloca and gave it up, unless
1656                     // we emit extra-debug-info, which requires local allocas :(.
1657                     let llarg = get_param(self.llfn, llarg_idx as c_uint);
1658                     llarg_idx += 1;
1659                     self.schedule_lifetime_end(arg_scope_id, llarg);
1660                     self.schedule_drop_mem(arg_scope_id, llarg, arg_ty, None);
1661
1662                     datum::Datum::new(llarg,
1663                                       arg_ty,
1664                                       datum::Lvalue::new("FunctionContext::bind_args"))
1665                 } else {
1666                     unpack_datum!(bcx, datum::lvalue_scratch_datum(bcx, arg_ty, "",
1667                                                                    uninit_reason,
1668                                                                    arg_scope_id, |bcx, dst| {
1669                         debug!("FunctionContext::bind_args: {:?}: {:?}", hir_arg, arg_ty);
1670                         let b = &bcx.build();
1671                         if common::type_is_fat_ptr(bcx.tcx(), arg_ty) {
1672                             let meta = &self.fn_ty.args[idx];
1673                             idx += 1;
1674                             arg.store_fn_arg(b, &mut llarg_idx, expr::get_dataptr(bcx, dst));
1675                             meta.store_fn_arg(b, &mut llarg_idx, expr::get_meta(bcx, dst));
1676                         } else {
1677                             arg.store_fn_arg(b, &mut llarg_idx, dst);
1678                         }
1679                         bcx
1680                     }))
1681                 }
1682             } else {
1683                 // FIXME(pcwalton): Reduce the amount of code bloat this is responsible for.
1684                 let tupled_arg_tys = match arg_ty.sty {
1685                     ty::TyTuple(ref tys) => tys,
1686                     _ => bug!("last argument of `rust-call` fn isn't a tuple?!")
1687                 };
1688
1689                 unpack_datum!(bcx, datum::lvalue_scratch_datum(bcx,
1690                                                             arg_ty,
1691                                                             "tupled_args",
1692                                                             uninit_reason,
1693                                                             arg_scope_id,
1694                                                             |bcx, llval| {
1695                     debug!("FunctionContext::bind_args: tupled {:?}: {:?}", hir_arg, arg_ty);
1696                     for (j, &tupled_arg_ty) in tupled_arg_tys.iter().enumerate() {
1697                         let dst = StructGEP(bcx, llval, j);
1698                         let arg = &self.fn_ty.args[idx];
1699                         idx += 1;
1700                         let b = &bcx.build();
1701                         if common::type_is_fat_ptr(bcx.tcx(), tupled_arg_ty) {
1702                             let meta = &self.fn_ty.args[idx];
1703                             idx += 1;
1704                             arg.store_fn_arg(b, &mut llarg_idx, expr::get_dataptr(bcx, dst));
1705                             meta.store_fn_arg(b, &mut llarg_idx, expr::get_meta(bcx, dst));
1706                         } else {
1707                             arg.store_fn_arg(b, &mut llarg_idx, dst);
1708                         }
1709                     }
1710                     bcx
1711                 }))
1712             };
1713
1714             let pat = &hir_arg.pat;
1715             bcx = if let Some(name) = simple_name(pat) {
1716                 // Generate nicer LLVM for the common case of fn a pattern
1717                 // like `x: T`
1718                 set_value_name(arg_datum.val, &bcx.name(name));
1719                 self.lllocals.borrow_mut().insert(pat.id, arg_datum);
1720                 bcx
1721             } else {
1722                 // General path. Copy out the values that are used in the
1723                 // pattern.
1724                 _match::bind_irrefutable_pat(bcx, pat, arg_datum.match_input(), arg_scope_id)
1725             };
1726             debuginfo::create_argument_metadata(bcx, hir_arg);
1727         }
1728
1729         bcx
1730     }
1731
1732     /// Ties up the llstaticallocas -> llloadenv -> lltop edges,
1733     /// and builds the return block.
1734     pub fn finish(&'blk self, last_bcx: Block<'blk, 'tcx>,
1735                   ret_debug_loc: DebugLoc) {
1736         let _icx = push_ctxt("FunctionContext::finish");
1737
1738         let ret_cx = match self.llreturn.get() {
1739             Some(llreturn) => {
1740                 if !last_bcx.terminated.get() {
1741                     Br(last_bcx, llreturn, DebugLoc::None);
1742                 }
1743                 raw_block(self, llreturn)
1744             }
1745             None => last_bcx,
1746         };
1747
1748         self.build_return_block(ret_cx, ret_debug_loc);
1749
1750         DebugLoc::None.apply(self);
1751         self.cleanup();
1752     }
1753
1754     // Builds the return block for a function.
1755     pub fn build_return_block(&self, ret_cx: Block<'blk, 'tcx>,
1756                               ret_debug_location: DebugLoc) {
1757         if self.llretslotptr.get().is_none() ||
1758            ret_cx.unreachable.get() ||
1759            (!self.needs_ret_allocas && self.fn_ty.ret.is_indirect()) {
1760             return RetVoid(ret_cx, ret_debug_location);
1761         }
1762
1763         let retslot = if self.needs_ret_allocas {
1764             Load(ret_cx, self.llretslotptr.get().unwrap())
1765         } else {
1766             self.llretslotptr.get().unwrap()
1767         };
1768         let retptr = Value(retslot);
1769         let llty = self.fn_ty.ret.original_ty;
1770         match (retptr.get_dominating_store(ret_cx), self.fn_ty.ret.cast) {
1771             // If there's only a single store to the ret slot, we can directly return
1772             // the value that was stored and omit the store and the alloca.
1773             // However, we only want to do this when there is no cast needed.
1774             (Some(s), None) => {
1775                 let mut retval = s.get_operand(0).unwrap().get();
1776                 s.erase_from_parent();
1777
1778                 if retptr.has_no_uses() {
1779                     retptr.erase_from_parent();
1780                 }
1781
1782                 if self.fn_ty.ret.is_indirect() {
1783                     Store(ret_cx, retval, get_param(self.llfn, 0));
1784                     RetVoid(ret_cx, ret_debug_location)
1785                 } else {
1786                     if llty == Type::i1(self.ccx) {
1787                         retval = Trunc(ret_cx, retval, llty);
1788                     }
1789                     Ret(ret_cx, retval, ret_debug_location)
1790                 }
1791             }
1792             (_, cast_ty) if self.fn_ty.ret.is_indirect() => {
1793                 // Otherwise, copy the return value to the ret slot.
1794                 assert_eq!(cast_ty, None);
1795                 let llsz = llsize_of(self.ccx, self.fn_ty.ret.ty);
1796                 let llalign = llalign_of_min(self.ccx, self.fn_ty.ret.ty);
1797                 call_memcpy(&B(ret_cx), get_param(self.llfn, 0),
1798                             retslot, llsz, llalign as u32);
1799                 RetVoid(ret_cx, ret_debug_location)
1800             }
1801             (_, Some(cast_ty)) => {
1802                 let load = Load(ret_cx, PointerCast(ret_cx, retslot, cast_ty.ptr_to()));
1803                 let llalign = llalign_of_min(self.ccx, self.fn_ty.ret.ty);
1804                 unsafe {
1805                     llvm::LLVMSetAlignment(load, llalign);
1806                 }
1807                 Ret(ret_cx, load, ret_debug_location)
1808             }
1809             (_, None) => {
1810                 let retval = if llty == Type::i1(self.ccx) {
1811                     let val = LoadRangeAssert(ret_cx, retslot, 0, 2, llvm::False);
1812                     Trunc(ret_cx, val, llty)
1813                 } else {
1814                     Load(ret_cx, retslot)
1815                 };
1816                 Ret(ret_cx, retval, ret_debug_location)
1817             }
1818         }
1819     }
1820 }
1821
1822 /// Builds an LLVM function out of a source function.
1823 ///
1824 /// If the function closes over its environment a closure will be returned.
1825 pub fn trans_closure<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1826                                decl: &hir::FnDecl,
1827                                body: &hir::Block,
1828                                llfndecl: ValueRef,
1829                                instance: Instance<'tcx>,
1830                                inlined_id: ast::NodeId,
1831                                sig: &ty::FnSig<'tcx>,
1832                                abi: Abi,
1833                                closure_env: closure::ClosureEnv) {
1834     ccx.stats().n_closures.set(ccx.stats().n_closures.get() + 1);
1835
1836     let _icx = push_ctxt("trans_closure");
1837     if !ccx.sess().no_landing_pads() {
1838         attributes::emit_uwtable(llfndecl, true);
1839     }
1840
1841     // this is an info! to allow collecting monomorphization statistics
1842     // and to allow finding the last function before LLVM aborts from
1843     // release builds.
1844     info!("trans_closure(..., {})", instance);
1845
1846     let fn_ty = FnType::new(ccx, abi, sig, &[]);
1847
1848     let (arena, fcx): (TypedArena<_>, FunctionContext);
1849     arena = TypedArena::new();
1850     fcx = FunctionContext::new(ccx,
1851                                llfndecl,
1852                                fn_ty,
1853                                Some((instance, sig, abi, inlined_id)),
1854                                &arena);
1855
1856     if fcx.mir.is_some() {
1857         return mir::trans_mir(&fcx);
1858     }
1859
1860     debuginfo::fill_scope_map_for_function(&fcx, decl, body, inlined_id);
1861
1862     // cleanup scope for the incoming arguments
1863     let fn_cleanup_debug_loc = debuginfo::get_cleanup_debug_loc_for_ast_node(
1864         ccx, inlined_id, body.span, true);
1865     let arg_scope = fcx.push_custom_cleanup_scope_with_debug_loc(fn_cleanup_debug_loc);
1866
1867     // Set up arguments to the function.
1868     debug!("trans_closure: function: {:?}", Value(fcx.llfn));
1869     let bcx = fcx.bind_args(&decl.inputs, abi, inlined_id, closure_env, arg_scope);
1870
1871     // Up until here, IR instructions for this function have explicitly not been annotated with
1872     // source code location, so we don't step into call setup code. From here on, source location
1873     // emitting should be enabled.
1874     debuginfo::start_emitting_source_locations(&fcx);
1875
1876     let dest = if fcx.fn_ty.ret.is_ignore() {
1877         expr::Ignore
1878     } else {
1879         expr::SaveIn(fcx.get_ret_slot(bcx, "iret_slot"))
1880     };
1881
1882     // This call to trans_block is the place where we bridge between
1883     // translation calls that don't have a return value (trans_crate,
1884     // trans_mod, trans_item, et cetera) and those that do
1885     // (trans_block, trans_expr, et cetera).
1886     let mut bcx = controlflow::trans_block(bcx, body, dest);
1887
1888     match dest {
1889         expr::SaveIn(slot) if fcx.needs_ret_allocas => {
1890             Store(bcx, slot, fcx.llretslotptr.get().unwrap());
1891         }
1892         _ => {}
1893     }
1894
1895     match fcx.llreturn.get() {
1896         Some(_) => {
1897             Br(bcx, fcx.return_exit_block(), DebugLoc::None);
1898             fcx.pop_custom_cleanup_scope(arg_scope);
1899         }
1900         None => {
1901             // Microoptimization writ large: avoid creating a separate
1902             // llreturn basic block
1903             bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
1904         }
1905     };
1906
1907     // Put return block after all other blocks.
1908     // This somewhat improves single-stepping experience in debugger.
1909     unsafe {
1910         let llreturn = fcx.llreturn.get();
1911         if let Some(llreturn) = llreturn {
1912             llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1913         }
1914     }
1915
1916     // Insert the mandatory first few basic blocks before lltop.
1917     fcx.finish(bcx, fn_cleanup_debug_loc.debug_loc());
1918 }
1919
1920 pub fn trans_instance<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, instance: Instance<'tcx>) {
1921     let local_instance = inline::maybe_inline_instance(ccx, instance);
1922
1923     let fn_node_id = ccx.tcx().map.as_local_node_id(local_instance.def).unwrap();
1924
1925     let _s = StatRecorder::new(ccx, ccx.tcx().node_path_str(fn_node_id));
1926     debug!("trans_instance(instance={:?})", instance);
1927     let _icx = push_ctxt("trans_instance");
1928
1929     let item = ccx.tcx().map.find(fn_node_id).unwrap();
1930
1931     let fn_ty = ccx.tcx().lookup_item_type(instance.def).ty;
1932     let fn_ty = ccx.tcx().erase_regions(&fn_ty);
1933     let fn_ty = monomorphize::apply_param_substs(ccx.tcx(), instance.substs, &fn_ty);
1934
1935     let sig = ccx.tcx().erase_late_bound_regions(fn_ty.fn_sig());
1936     let sig = ccx.tcx().normalize_associated_type(&sig);
1937     let abi = fn_ty.fn_abi();
1938
1939     let lldecl = match ccx.instances().borrow().get(&local_instance) {
1940         Some(&val) => val,
1941         None => bug!("Instance `{:?}` not already declared", instance)
1942     };
1943
1944     match item {
1945         hir_map::NodeItem(&hir::Item {
1946             node: hir::ItemFn(ref decl, _, _, _, _, ref body), ..
1947         }) |
1948         hir_map::NodeTraitItem(&hir::TraitItem {
1949             node: hir::MethodTraitItem(
1950                 hir::MethodSig { ref decl, .. }, Some(ref body)), ..
1951         }) |
1952         hir_map::NodeImplItem(&hir::ImplItem {
1953             node: hir::ImplItemKind::Method(
1954                 hir::MethodSig { ref decl, .. }, ref body), ..
1955         }) => {
1956             trans_closure(ccx, decl, body, lldecl, instance,
1957                           fn_node_id, &sig, abi, closure::ClosureEnv::NotClosure);
1958         }
1959         _ => bug!("Instance is a {:?}?", item)
1960     }
1961 }
1962
1963 pub fn trans_named_tuple_constructor<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1964                                                  ctor_ty: Ty<'tcx>,
1965                                                  disr: Disr,
1966                                                  args: CallArgs,
1967                                                  dest: expr::Dest,
1968                                                  debug_loc: DebugLoc)
1969                                                  -> Result<'blk, 'tcx> {
1970
1971     let ccx = bcx.fcx.ccx;
1972
1973     let sig = ccx.tcx().erase_late_bound_regions(&ctor_ty.fn_sig());
1974     let sig = ccx.tcx().normalize_associated_type(&sig);
1975     let result_ty = sig.output;
1976
1977     // Get location to store the result. If the user does not care about
1978     // the result, just make a stack slot
1979     let llresult = match dest {
1980         expr::SaveIn(d) => d,
1981         expr::Ignore => {
1982             if !type_is_zero_size(ccx, result_ty) {
1983                 let llresult = alloc_ty(bcx, result_ty, "constructor_result");
1984                 call_lifetime_start(bcx, llresult);
1985                 llresult
1986             } else {
1987                 C_undef(type_of::type_of(ccx, result_ty).ptr_to())
1988             }
1989         }
1990     };
1991
1992     if !type_is_zero_size(ccx, result_ty) {
1993         match args {
1994             ArgExprs(exprs) => {
1995                 let fields = exprs.iter().map(|x| &**x).enumerate().collect::<Vec<_>>();
1996                 bcx = expr::trans_adt(bcx,
1997                                       result_ty,
1998                                       disr,
1999                                       &fields[..],
2000                                       None,
2001                                       expr::SaveIn(llresult),
2002                                       debug_loc);
2003             }
2004             _ => bug!("expected expr as arguments for variant/struct tuple constructor"),
2005         }
2006     } else {
2007         // Just eval all the expressions (if any). Since expressions in Rust can have arbitrary
2008         // contents, there could be side-effects we need from them.
2009         match args {
2010             ArgExprs(exprs) => {
2011                 for expr in exprs {
2012                     bcx = expr::trans_into(bcx, expr, expr::Ignore);
2013                 }
2014             }
2015             _ => (),
2016         }
2017     }
2018
2019     // If the caller doesn't care about the result
2020     // drop the temporary we made
2021     let bcx = match dest {
2022         expr::SaveIn(_) => bcx,
2023         expr::Ignore => {
2024             let bcx = glue::drop_ty(bcx, llresult, result_ty, debug_loc);
2025             if !type_is_zero_size(ccx, result_ty) {
2026                 call_lifetime_end(bcx, llresult);
2027             }
2028             bcx
2029         }
2030     };
2031
2032     Result::new(bcx, llresult)
2033 }
2034
2035 pub fn trans_ctor_shim<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
2036                                  ctor_id: ast::NodeId,
2037                                  disr: Disr,
2038                                  param_substs: &'tcx Substs<'tcx>,
2039                                  llfndecl: ValueRef) {
2040     let ctor_ty = ccx.tcx().node_id_to_type(ctor_id);
2041     let ctor_ty = monomorphize::apply_param_substs(ccx.tcx(), param_substs, &ctor_ty);
2042
2043     let sig = ccx.tcx().erase_late_bound_regions(&ctor_ty.fn_sig());
2044     let sig = ccx.tcx().normalize_associated_type(&sig);
2045     let fn_ty = FnType::new(ccx, Abi::Rust, &sig, &[]);
2046
2047     let (arena, fcx): (TypedArena<_>, FunctionContext);
2048     arena = TypedArena::new();
2049     fcx = FunctionContext::new(ccx, llfndecl, fn_ty, None, &arena);
2050     let bcx = fcx.init(false, None);
2051
2052     assert!(!fcx.needs_ret_allocas);
2053
2054     if !fcx.fn_ty.ret.is_ignore() {
2055         let dest = fcx.get_ret_slot(bcx, "eret_slot");
2056         let dest_val = adt::MaybeSizedValue::sized(dest); // Can return unsized value
2057         let repr = adt::represent_type(ccx, sig.output);
2058         let mut llarg_idx = fcx.fn_ty.ret.is_indirect() as usize;
2059         let mut arg_idx = 0;
2060         for (i, arg_ty) in sig.inputs.into_iter().enumerate() {
2061             let lldestptr = adt::trans_field_ptr(bcx, &repr, dest_val, Disr::from(disr), i);
2062             let arg = &fcx.fn_ty.args[arg_idx];
2063             arg_idx += 1;
2064             let b = &bcx.build();
2065             if common::type_is_fat_ptr(bcx.tcx(), arg_ty) {
2066                 let meta = &fcx.fn_ty.args[arg_idx];
2067                 arg_idx += 1;
2068                 arg.store_fn_arg(b, &mut llarg_idx, expr::get_dataptr(bcx, lldestptr));
2069                 meta.store_fn_arg(b, &mut llarg_idx, expr::get_meta(bcx, lldestptr));
2070             } else {
2071                 arg.store_fn_arg(b, &mut llarg_idx, lldestptr);
2072             }
2073         }
2074         adt::trans_set_discr(bcx, &repr, dest, disr);
2075     }
2076
2077     fcx.finish(bcx, DebugLoc::None);
2078 }
2079
2080 pub fn llvm_linkage_by_name(name: &str) -> Option<Linkage> {
2081     // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
2082     // applicable to variable declarations and may not really make sense for
2083     // Rust code in the first place but whitelist them anyway and trust that
2084     // the user knows what s/he's doing. Who knows, unanticipated use cases
2085     // may pop up in the future.
2086     //
2087     // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
2088     // and don't have to be, LLVM treats them as no-ops.
2089     match name {
2090         "appending" => Some(llvm::AppendingLinkage),
2091         "available_externally" => Some(llvm::AvailableExternallyLinkage),
2092         "common" => Some(llvm::CommonLinkage),
2093         "extern_weak" => Some(llvm::ExternalWeakLinkage),
2094         "external" => Some(llvm::ExternalLinkage),
2095         "internal" => Some(llvm::InternalLinkage),
2096         "linkonce" => Some(llvm::LinkOnceAnyLinkage),
2097         "linkonce_odr" => Some(llvm::LinkOnceODRLinkage),
2098         "private" => Some(llvm::PrivateLinkage),
2099         "weak" => Some(llvm::WeakAnyLinkage),
2100         "weak_odr" => Some(llvm::WeakODRLinkage),
2101         _ => None,
2102     }
2103 }
2104
2105 pub fn set_link_section(ccx: &CrateContext,
2106                         llval: ValueRef,
2107                         attrs: &[ast::Attribute]) {
2108     if let Some(sect) = attr::first_attr_value_str_by_name(attrs, "link_section") {
2109         if contains_null(&sect) {
2110             ccx.sess().fatal(&format!("Illegal null byte in link_section value: `{}`", &sect));
2111         }
2112         unsafe {
2113             let buf = CString::new(sect.as_bytes()).unwrap();
2114             llvm::LLVMSetSection(llval, buf.as_ptr());
2115         }
2116     }
2117 }
2118
2119 /// Create the `main` function which will initialise the rust runtime and call
2120 /// users’ main function.
2121 pub fn maybe_create_entry_wrapper(ccx: &CrateContext) {
2122     let (main_def_id, span) = match *ccx.sess().entry_fn.borrow() {
2123         Some((id, span)) => {
2124             (ccx.tcx().map.local_def_id(id), span)
2125         }
2126         None => return,
2127     };
2128
2129     // check for the #[rustc_error] annotation, which forces an
2130     // error in trans. This is used to write compile-fail tests
2131     // that actually test that compilation succeeds without
2132     // reporting an error.
2133     if ccx.tcx().has_attr(main_def_id, "rustc_error") {
2134         ccx.tcx().sess.span_fatal(span, "compilation successful");
2135     }
2136
2137     let instance = Instance::mono(ccx.shared(), main_def_id);
2138
2139     if !ccx.codegen_unit().contains_item(&TransItem::Fn(instance)) {
2140         // We want to create the wrapper in the same codegen unit as Rust's main
2141         // function.
2142         return;
2143     }
2144
2145     let main_llfn = Callee::def(ccx, main_def_id, instance.substs).reify(ccx).val;
2146
2147     let et = ccx.sess().entry_type.get().unwrap();
2148     match et {
2149         config::EntryMain => {
2150             create_entry_fn(ccx, span, main_llfn, true);
2151         }
2152         config::EntryStart => create_entry_fn(ccx, span, main_llfn, false),
2153         config::EntryNone => {}    // Do nothing.
2154     }
2155
2156     fn create_entry_fn(ccx: &CrateContext,
2157                        sp: Span,
2158                        rust_main: ValueRef,
2159                        use_start_lang_item: bool) {
2160         let llfty = Type::func(&[ccx.int_type(), Type::i8p(ccx).ptr_to()], &ccx.int_type());
2161
2162         if declare::get_defined_value(ccx, "main").is_some() {
2163             // FIXME: We should be smart and show a better diagnostic here.
2164             ccx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
2165                       .help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
2166                       .emit();
2167             ccx.sess().abort_if_errors();
2168             bug!();
2169         }
2170         let llfn = declare::declare_cfn(ccx, "main", llfty);
2171
2172         let llbb = unsafe {
2173             llvm::LLVMAppendBasicBlockInContext(ccx.llcx(), llfn, "top\0".as_ptr() as *const _)
2174         };
2175         let bld = ccx.raw_builder();
2176         unsafe {
2177             llvm::LLVMPositionBuilderAtEnd(bld, llbb);
2178
2179             debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(ccx);
2180
2181             let (start_fn, args) = if use_start_lang_item {
2182                 let start_def_id = match ccx.tcx().lang_items.require(StartFnLangItem) {
2183                     Ok(id) => id,
2184                     Err(s) => ccx.sess().fatal(&s)
2185                 };
2186                 let empty_substs = ccx.tcx().mk_substs(Substs::empty());
2187                 let start_fn = Callee::def(ccx, start_def_id, empty_substs).reify(ccx).val;
2188                 let args = {
2189                     let opaque_rust_main =
2190                         llvm::LLVMBuildPointerCast(bld,
2191                                                    rust_main,
2192                                                    Type::i8p(ccx).to_ref(),
2193                                                    "rust_main\0".as_ptr() as *const _);
2194
2195                     vec![opaque_rust_main, get_param(llfn, 0), get_param(llfn, 1)]
2196                 };
2197                 (start_fn, args)
2198             } else {
2199                 debug!("using user-defined start fn");
2200                 let args = vec![get_param(llfn, 0 as c_uint), get_param(llfn, 1 as c_uint)];
2201
2202                 (rust_main, args)
2203             };
2204
2205             let result = llvm::LLVMRustBuildCall(bld,
2206                                                  start_fn,
2207                                                  args.as_ptr(),
2208                                                  args.len() as c_uint,
2209                                                  ptr::null_mut(),
2210                                                  noname());
2211
2212             llvm::LLVMBuildRet(bld, result);
2213         }
2214     }
2215 }
2216
2217 fn contains_null(s: &str) -> bool {
2218     s.bytes().any(|b| b == 0)
2219 }
2220
2221 fn write_metadata(cx: &SharedCrateContext,
2222                   reachable_ids: &NodeSet) -> Vec<u8> {
2223     use flate;
2224
2225     let any_library = cx.sess()
2226                         .crate_types
2227                         .borrow()
2228                         .iter()
2229                         .any(|ty| *ty != config::CrateTypeExecutable);
2230     if !any_library {
2231         return Vec::new();
2232     }
2233
2234     let cstore = &cx.tcx().sess.cstore;
2235     let metadata = cstore.encode_metadata(cx.tcx(),
2236                                           cx.export_map(),
2237                                           cx.link_meta(),
2238                                           reachable_ids,
2239                                           cx.mir_map(),
2240                                           cx.tcx().map.krate());
2241     let mut compressed = cstore.metadata_encoding_version().to_vec();
2242     compressed.extend_from_slice(&flate::deflate_bytes(&metadata));
2243
2244     let llmeta = C_bytes_in_context(cx.metadata_llcx(), &compressed[..]);
2245     let llconst = C_struct_in_context(cx.metadata_llcx(), &[llmeta], false);
2246     let name = cx.metadata_symbol_name();
2247     let buf = CString::new(name).unwrap();
2248     let llglobal = unsafe {
2249         llvm::LLVMAddGlobal(cx.metadata_llmod(), val_ty(llconst).to_ref(), buf.as_ptr())
2250     };
2251     unsafe {
2252         llvm::LLVMSetInitializer(llglobal, llconst);
2253         let section_name =
2254             cx.tcx().sess.cstore.metadata_section_name(&cx.sess().target.target);
2255         let name = CString::new(section_name).unwrap();
2256         llvm::LLVMSetSection(llglobal, name.as_ptr());
2257
2258         // Also generate a .section directive to force no
2259         // flags, at least for ELF outputs, so that the
2260         // metadata doesn't get loaded into memory.
2261         let directive = format!(".section {}", section_name);
2262         let directive = CString::new(directive).unwrap();
2263         llvm::LLVMSetModuleInlineAsm(cx.metadata_llmod(), directive.as_ptr())
2264     }
2265     return metadata;
2266 }
2267
2268 /// Find any symbols that are defined in one compilation unit, but not declared
2269 /// in any other compilation unit.  Give these symbols internal linkage.
2270 fn internalize_symbols<'a, 'tcx>(sess: &Session,
2271                                  ccxs: &CrateContextList<'a, 'tcx>,
2272                                  symbol_map: &SymbolMap<'tcx>,
2273                                  reachable: &FnvHashSet<&str>) {
2274     let scx = ccxs.shared();
2275     let tcx = scx.tcx();
2276
2277     // In incr. comp. mode, we can't necessarily see all refs since we
2278     // don't generate LLVM IR for reused modules, so skip this
2279     // step. Later we should get smarter.
2280     if sess.opts.debugging_opts.incremental.is_some() {
2281         return;
2282     }
2283
2284     // 'unsafe' because we are holding on to CStr's from the LLVM module within
2285     // this block.
2286     unsafe {
2287         let mut referenced_somewhere = FnvHashSet();
2288
2289         // Collect all symbols that need to stay externally visible because they
2290         // are referenced via a declaration in some other codegen unit.
2291         for ccx in ccxs.iter_need_trans() {
2292             for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
2293                 let linkage = llvm::LLVMGetLinkage(val);
2294                 // We only care about external declarations (not definitions)
2295                 // and available_externally definitions.
2296                 let is_available_externally = linkage == llvm::AvailableExternallyLinkage as c_uint;
2297                 let is_decl = llvm::LLVMIsDeclaration(val) != 0;
2298
2299                 if is_decl || is_available_externally {
2300                     let symbol_name = CStr::from_ptr(llvm::LLVMGetValueName(val));
2301                     referenced_somewhere.insert(symbol_name);
2302                 }
2303             }
2304         }
2305
2306         // Also collect all symbols for which we cannot adjust linkage, because
2307         // it is fixed by some directive in the source code (e.g. #[no_mangle]).
2308         let linkage_fixed_explicitly: FnvHashSet<_> = scx
2309             .translation_items()
2310             .borrow()
2311             .iter()
2312             .cloned()
2313             .filter(|trans_item|{
2314                 let def_id = match *trans_item {
2315                     TransItem::DropGlue(..) => {
2316                         return false
2317                     },
2318                     TransItem::Fn(ref instance) => {
2319                         instance.def
2320                     }
2321                     TransItem::Static(node_id) => {
2322                         tcx.map.local_def_id(node_id)
2323                     }
2324                 };
2325
2326                 trans_item.explicit_linkage(tcx).is_some() ||
2327                 attr::contains_extern_indicator(tcx.sess.diagnostic(),
2328                                                 &tcx.get_attrs(def_id))
2329             })
2330             .map(|trans_item| symbol_map.get_or_compute(scx, trans_item))
2331             .collect();
2332
2333         // Examine each external definition.  If the definition is not used in
2334         // any other compilation unit, and is not reachable from other crates,
2335         // then give it internal linkage.
2336         for ccx in ccxs.iter_need_trans() {
2337             for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
2338                 let linkage = llvm::LLVMGetLinkage(val);
2339
2340                 let is_externally_visible = (linkage == llvm::ExternalLinkage as c_uint) ||
2341                                             (linkage == llvm::LinkOnceODRLinkage as c_uint) ||
2342                                             (linkage == llvm::WeakODRLinkage as c_uint);
2343                 let is_definition = llvm::LLVMIsDeclaration(val) == 0;
2344
2345                 // If this is a definition (as opposed to just a declaration)
2346                 // and externally visible, check if we can internalize it
2347                 if is_definition && is_externally_visible {
2348                     let name_cstr = CStr::from_ptr(llvm::LLVMGetValueName(val));
2349                     let name_str = name_cstr.to_str().unwrap();
2350                     let name_cow = Cow::Borrowed(name_str);
2351
2352                     let is_referenced_somewhere = referenced_somewhere.contains(&name_cstr);
2353                     let is_reachable = reachable.contains(&name_str);
2354                     let has_fixed_linkage = linkage_fixed_explicitly.contains(&name_cow);
2355
2356                     if !is_referenced_somewhere && !is_reachable && !has_fixed_linkage {
2357                         llvm::LLVMSetLinkage(val, llvm::InternalLinkage);
2358                         llvm::LLVMSetDLLStorageClass(val,
2359                                                      llvm::DLLStorageClass::Default);
2360                         llvm::UnsetComdat(val);
2361                     }
2362                 }
2363             }
2364         }
2365     }
2366 }
2367
2368 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
2369 // This is required to satisfy `dllimport` references to static data in .rlibs
2370 // when using MSVC linker.  We do this only for data, as linker can fix up
2371 // code references on its own.
2372 // See #26591, #27438
2373 fn create_imps(cx: &CrateContextList) {
2374     // The x86 ABI seems to require that leading underscores are added to symbol
2375     // names, so we need an extra underscore on 32-bit. There's also a leading
2376     // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
2377     // underscores added in front).
2378     let prefix = if cx.shared().sess().target.target.target_pointer_width == "32" {
2379         "\x01__imp__"
2380     } else {
2381         "\x01__imp_"
2382     };
2383     unsafe {
2384         for ccx in cx.iter_need_trans() {
2385             let exported: Vec<_> = iter_globals(ccx.llmod())
2386                                        .filter(|&val| {
2387                                            llvm::LLVMGetLinkage(val) ==
2388                                            llvm::ExternalLinkage as c_uint &&
2389                                            llvm::LLVMIsDeclaration(val) == 0
2390                                        })
2391                                        .collect();
2392
2393             let i8p_ty = Type::i8p(&ccx);
2394             for val in exported {
2395                 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
2396                 let mut imp_name = prefix.as_bytes().to_vec();
2397                 imp_name.extend(name.to_bytes());
2398                 let imp_name = CString::new(imp_name).unwrap();
2399                 let imp = llvm::LLVMAddGlobal(ccx.llmod(),
2400                                               i8p_ty.to_ref(),
2401                                               imp_name.as_ptr() as *const _);
2402                 let init = llvm::LLVMConstBitCast(val, i8p_ty.to_ref());
2403                 llvm::LLVMSetInitializer(imp, init);
2404                 llvm::LLVMSetLinkage(imp, llvm::ExternalLinkage);
2405             }
2406         }
2407     }
2408 }
2409
2410 struct ValueIter {
2411     cur: ValueRef,
2412     step: unsafe extern "C" fn(ValueRef) -> ValueRef,
2413 }
2414
2415 impl Iterator for ValueIter {
2416     type Item = ValueRef;
2417
2418     fn next(&mut self) -> Option<ValueRef> {
2419         let old = self.cur;
2420         if !old.is_null() {
2421             self.cur = unsafe { (self.step)(old) };
2422             Some(old)
2423         } else {
2424             None
2425         }
2426     }
2427 }
2428
2429 fn iter_globals(llmod: llvm::ModuleRef) -> ValueIter {
2430     unsafe {
2431         ValueIter {
2432             cur: llvm::LLVMGetFirstGlobal(llmod),
2433             step: llvm::LLVMGetNextGlobal,
2434         }
2435     }
2436 }
2437
2438 fn iter_functions(llmod: llvm::ModuleRef) -> ValueIter {
2439     unsafe {
2440         ValueIter {
2441             cur: llvm::LLVMGetFirstFunction(llmod),
2442             step: llvm::LLVMGetNextFunction,
2443         }
2444     }
2445 }
2446
2447 /// The context provided lists a set of reachable ids as calculated by
2448 /// middle::reachable, but this contains far more ids and symbols than we're
2449 /// actually exposing from the object file. This function will filter the set in
2450 /// the context to the set of ids which correspond to symbols that are exposed
2451 /// from the object file being generated.
2452 ///
2453 /// This list is later used by linkers to determine the set of symbols needed to
2454 /// be exposed from a dynamic library and it's also encoded into the metadata.
2455 pub fn filter_reachable_ids(tcx: TyCtxt, reachable: NodeSet) -> NodeSet {
2456     reachable.into_iter().filter(|&id| {
2457         // Next, we want to ignore some FFI functions that are not exposed from
2458         // this crate. Reachable FFI functions can be lumped into two
2459         // categories:
2460         //
2461         // 1. Those that are included statically via a static library
2462         // 2. Those included otherwise (e.g. dynamically or via a framework)
2463         //
2464         // Although our LLVM module is not literally emitting code for the
2465         // statically included symbols, it's an export of our library which
2466         // needs to be passed on to the linker and encoded in the metadata.
2467         //
2468         // As a result, if this id is an FFI item (foreign item) then we only
2469         // let it through if it's included statically.
2470         match tcx.map.get(id) {
2471             hir_map::NodeForeignItem(..) => {
2472                 tcx.sess.cstore.is_statically_included_foreign_item(id)
2473             }
2474
2475             // Only consider nodes that actually have exported symbols.
2476             hir_map::NodeItem(&hir::Item {
2477                 node: hir::ItemStatic(..), .. }) |
2478             hir_map::NodeItem(&hir::Item {
2479                 node: hir::ItemFn(..), .. }) |
2480             hir_map::NodeImplItem(&hir::ImplItem {
2481                 node: hir::ImplItemKind::Method(..), .. }) => {
2482                 let def_id = tcx.map.local_def_id(id);
2483                 let scheme = tcx.lookup_item_type(def_id);
2484                 scheme.generics.types.is_empty()
2485             }
2486
2487             _ => false
2488         }
2489     }).collect()
2490 }
2491
2492 pub fn trans_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2493                              mir_map: &MirMap<'tcx>,
2494                              analysis: ty::CrateAnalysis)
2495                              -> CrateTranslation {
2496     let _task = tcx.dep_graph.in_task(DepNode::TransCrate);
2497
2498     // Be careful with this krate: obviously it gives access to the
2499     // entire contents of the krate. So if you push any subtasks of
2500     // `TransCrate`, you need to be careful to register "reads" of the
2501     // particular items that will be processed.
2502     let krate = tcx.map.krate();
2503
2504     let ty::CrateAnalysis { export_map, reachable, name, .. } = analysis;
2505     let reachable = filter_reachable_ids(tcx, reachable);
2506
2507     let check_overflow = if let Some(v) = tcx.sess.opts.debugging_opts.force_overflow_checks {
2508         v
2509     } else {
2510         tcx.sess.opts.debug_assertions
2511     };
2512
2513     let check_dropflag = if let Some(v) = tcx.sess.opts.debugging_opts.force_dropflag_checks {
2514         v
2515     } else {
2516         tcx.sess.opts.debug_assertions
2517     };
2518
2519     let link_meta = link::build_link_meta(tcx, name);
2520
2521     let shared_ccx = SharedCrateContext::new(tcx,
2522                                              &mir_map,
2523                                              export_map,
2524                                              Sha256::new(),
2525                                              link_meta.clone(),
2526                                              reachable,
2527                                              check_overflow,
2528                                              check_dropflag);
2529     // Translate the metadata.
2530     let metadata = time(tcx.sess.time_passes(), "write metadata", || {
2531         write_metadata(&shared_ccx, shared_ccx.reachable())
2532     });
2533
2534     let metadata_module = ModuleTranslation {
2535         name: "metadata".to_string(),
2536         symbol_name_hash: 0, // we always rebuild metadata, at least for now
2537         source: ModuleSource::Translated(ModuleLlvm {
2538             llcx: shared_ccx.metadata_llcx(),
2539             llmod: shared_ccx.metadata_llmod(),
2540         }),
2541     };
2542     let no_builtins = attr::contains_name(&krate.attrs, "no_builtins");
2543
2544     // Run the translation item collector and partition the collected items into
2545     // codegen units.
2546     let (codegen_units, symbol_map) = collect_and_partition_translation_items(&shared_ccx);
2547
2548     let symbol_map = Rc::new(symbol_map);
2549
2550     let previous_work_products = trans_reuse_previous_work_products(tcx,
2551                                                                     &codegen_units,
2552                                                                     &symbol_map);
2553
2554     let crate_context_list = CrateContextList::new(&shared_ccx,
2555                                                    codegen_units,
2556                                                    previous_work_products,
2557                                                    symbol_map.clone());
2558     let modules: Vec<_> = crate_context_list.iter_all()
2559         .map(|ccx| {
2560             let source = match ccx.previous_work_product() {
2561                 Some(buf) => ModuleSource::Preexisting(buf.clone()),
2562                 None => ModuleSource::Translated(ModuleLlvm {
2563                     llcx: ccx.llcx(),
2564                     llmod: ccx.llmod(),
2565                 }),
2566             };
2567
2568             ModuleTranslation {
2569                 name: String::from(ccx.codegen_unit().name()),
2570                 symbol_name_hash: ccx.codegen_unit().compute_symbol_name_hash(tcx, &symbol_map),
2571                 source: source,
2572             }
2573         })
2574         .collect();
2575
2576     assert_module_sources::assert_module_sources(tcx, &modules);
2577
2578     // Skip crate items and just output metadata in -Z no-trans mode.
2579     if tcx.sess.opts.debugging_opts.no_trans {
2580         let linker_info = LinkerInfo::new(&shared_ccx, &[]);
2581         return CrateTranslation {
2582             modules: modules,
2583             metadata_module: metadata_module,
2584             link: link_meta,
2585             metadata: metadata,
2586             reachable: vec![],
2587             no_builtins: no_builtins,
2588             linker_info: linker_info
2589         };
2590     }
2591
2592     // Instantiate translation items without filling out definitions yet...
2593     for ccx in crate_context_list.iter_need_trans() {
2594         let cgu = ccx.codegen_unit();
2595         let trans_items = cgu.items_in_deterministic_order(tcx, &symbol_map);
2596
2597         tcx.dep_graph.with_task(cgu.work_product_dep_node(), || {
2598             for (trans_item, linkage) in trans_items {
2599                 trans_item.predefine(&ccx, linkage);
2600             }
2601         });
2602     }
2603
2604     // ... and now that we have everything pre-defined, fill out those definitions.
2605     for ccx in crate_context_list.iter_need_trans() {
2606         let cgu = ccx.codegen_unit();
2607         let trans_items = cgu.items_in_deterministic_order(tcx, &symbol_map);
2608         tcx.dep_graph.with_task(cgu.work_product_dep_node(), || {
2609             for (trans_item, _) in trans_items {
2610                 trans_item.define(&ccx);
2611             }
2612
2613             // If this codegen unit contains the main function, also create the
2614             // wrapper here
2615             maybe_create_entry_wrapper(&ccx);
2616
2617             // Run replace-all-uses-with for statics that need it
2618             for &(old_g, new_g) in ccx.statics_to_rauw().borrow().iter() {
2619                 unsafe {
2620                     let bitcast = llvm::LLVMConstPointerCast(new_g, llvm::LLVMTypeOf(old_g));
2621                     llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
2622                     llvm::LLVMDeleteGlobal(old_g);
2623                 }
2624             }
2625
2626             // Finalize debuginfo
2627             if ccx.sess().opts.debuginfo != NoDebugInfo {
2628                 debuginfo::finalize(&ccx);
2629             }
2630         });
2631     }
2632
2633     symbol_names_test::report_symbol_names(&shared_ccx);
2634
2635     if shared_ccx.sess().trans_stats() {
2636         let stats = shared_ccx.stats();
2637         println!("--- trans stats ---");
2638         println!("n_glues_created: {}", stats.n_glues_created.get());
2639         println!("n_null_glues: {}", stats.n_null_glues.get());
2640         println!("n_real_glues: {}", stats.n_real_glues.get());
2641
2642         println!("n_fallback_instantiations: {}", stats.n_fallback_instantiations.get());
2643
2644         println!("n_fns: {}", stats.n_fns.get());
2645         println!("n_monos: {}", stats.n_monos.get());
2646         println!("n_inlines: {}", stats.n_inlines.get());
2647         println!("n_closures: {}", stats.n_closures.get());
2648         println!("fn stats:");
2649         stats.fn_stats.borrow_mut().sort_by(|&(_, insns_a), &(_, insns_b)| {
2650             insns_b.cmp(&insns_a)
2651         });
2652         for tuple in stats.fn_stats.borrow().iter() {
2653             match *tuple {
2654                 (ref name, insns) => {
2655                     println!("{} insns, {}", insns, *name);
2656                 }
2657             }
2658         }
2659     }
2660
2661     if shared_ccx.sess().count_llvm_insns() {
2662         for (k, v) in shared_ccx.stats().llvm_insns.borrow().iter() {
2663             println!("{:7} {}", *v, *k);
2664         }
2665     }
2666
2667     let sess = shared_ccx.sess();
2668     let mut reachable_symbols = shared_ccx.reachable().iter().map(|&id| {
2669         let def_id = shared_ccx.tcx().map.local_def_id(id);
2670         symbol_for_def_id(def_id, &shared_ccx, &symbol_map)
2671     }).collect::<Vec<_>>();
2672
2673     if sess.entry_fn.borrow().is_some() {
2674         reachable_symbols.push("main".to_string());
2675     }
2676
2677     if sess.crate_types.borrow().contains(&config::CrateTypeDylib) {
2678         reachable_symbols.push(shared_ccx.metadata_symbol_name());
2679     }
2680
2681     // For the purposes of LTO or when creating a cdylib, we add to the
2682     // reachable set all of the upstream reachable extern fns. These functions
2683     // are all part of the public ABI of the final product, so we need to
2684     // preserve them.
2685     //
2686     // Note that this happens even if LTO isn't requested or we're not creating
2687     // a cdylib. In those cases, though, we're not even reading the
2688     // `reachable_symbols` list later on so it should be ok.
2689     for cnum in sess.cstore.crates() {
2690         let syms = sess.cstore.reachable_ids(cnum);
2691         reachable_symbols.extend(syms.into_iter().filter(|did| {
2692             sess.cstore.is_extern_item(shared_ccx.tcx(), *did)
2693         }).map(|did| {
2694             symbol_for_def_id(did, &shared_ccx, &symbol_map)
2695         }));
2696     }
2697
2698     time(shared_ccx.sess().time_passes(), "internalize symbols", || {
2699         internalize_symbols(sess,
2700                             &crate_context_list,
2701                             &symbol_map,
2702                             &reachable_symbols.iter()
2703                                               .map(|s| &s[..])
2704                                               .collect())
2705     });
2706
2707     if sess.target.target.options.is_like_msvc &&
2708        sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateTypeRlib) {
2709         create_imps(&crate_context_list);
2710     }
2711
2712     let linker_info = LinkerInfo::new(&shared_ccx, &reachable_symbols);
2713
2714     CrateTranslation {
2715         modules: modules,
2716         metadata_module: metadata_module,
2717         link: link_meta,
2718         metadata: metadata,
2719         reachable: reachable_symbols,
2720         no_builtins: no_builtins,
2721         linker_info: linker_info
2722     }
2723 }
2724
2725 /// For each CGU, identify if we can reuse an existing object file (or
2726 /// maybe other context).
2727 fn trans_reuse_previous_work_products(tcx: TyCtxt,
2728                                       codegen_units: &[CodegenUnit],
2729                                       symbol_map: &SymbolMap)
2730                                       -> Vec<Option<WorkProduct>> {
2731     debug!("trans_reuse_previous_work_products()");
2732     codegen_units
2733         .iter()
2734         .map(|cgu| {
2735             let id = cgu.work_product_id();
2736
2737             let hash = cgu.compute_symbol_name_hash(tcx, symbol_map);
2738
2739             debug!("trans_reuse_previous_work_products: id={:?} hash={}", id, hash);
2740
2741             if let Some(work_product) = tcx.dep_graph.previous_work_product(&id) {
2742                 if work_product.input_hash == hash {
2743                     debug!("trans_reuse_previous_work_products: reusing {:?}", work_product);
2744                     return Some(work_product);
2745                 } else {
2746                     debug!("trans_reuse_previous_work_products: \
2747                             not reusing {:?} because hash changed to {:?}",
2748                            work_product, hash);
2749                 }
2750             }
2751
2752             None
2753         })
2754         .collect()
2755 }
2756
2757 fn collect_and_partition_translation_items<'a, 'tcx>(scx: &SharedCrateContext<'a, 'tcx>)
2758                                                      -> (Vec<CodegenUnit<'tcx>>, SymbolMap<'tcx>) {
2759     let time_passes = scx.sess().time_passes();
2760
2761     let collection_mode = match scx.sess().opts.debugging_opts.print_trans_items {
2762         Some(ref s) => {
2763             let mode_string = s.to_lowercase();
2764             let mode_string = mode_string.trim();
2765             if mode_string == "eager" {
2766                 TransItemCollectionMode::Eager
2767             } else {
2768                 if mode_string != "lazy" {
2769                     let message = format!("Unknown codegen-item collection mode '{}'. \
2770                                            Falling back to 'lazy' mode.",
2771                                            mode_string);
2772                     scx.sess().warn(&message);
2773                 }
2774
2775                 TransItemCollectionMode::Lazy
2776             }
2777         }
2778         None => TransItemCollectionMode::Lazy
2779     };
2780
2781     let (items, inlining_map) =
2782         time(time_passes, "translation item collection", || {
2783             collector::collect_crate_translation_items(&scx, collection_mode)
2784     });
2785
2786     let symbol_map = SymbolMap::build(scx, items.iter().cloned());
2787
2788     let strategy = if scx.sess().opts.debugging_opts.incremental.is_some() {
2789         PartitioningStrategy::PerModule
2790     } else {
2791         PartitioningStrategy::FixedUnitCount(scx.sess().opts.cg.codegen_units)
2792     };
2793
2794     let codegen_units = time(time_passes, "codegen unit partitioning", || {
2795         partitioning::partition(scx.tcx(),
2796                                 items.iter().cloned(),
2797                                 strategy,
2798                                 &inlining_map,
2799                                 scx.reachable())
2800     });
2801
2802     assert!(scx.tcx().sess.opts.cg.codegen_units == codegen_units.len() ||
2803             scx.tcx().sess.opts.debugging_opts.incremental.is_some());
2804
2805     {
2806         let mut ccx_map = scx.translation_items().borrow_mut();
2807
2808         for trans_item in items.iter().cloned() {
2809             ccx_map.insert(trans_item);
2810         }
2811     }
2812
2813     if scx.sess().opts.debugging_opts.print_trans_items.is_some() {
2814         let mut item_to_cgus = HashMap::new();
2815
2816         for cgu in &codegen_units {
2817             for (&trans_item, &linkage) in cgu.items() {
2818                 item_to_cgus.entry(trans_item)
2819                             .or_insert(Vec::new())
2820                             .push((cgu.name().clone(), linkage));
2821             }
2822         }
2823
2824         let mut item_keys: Vec<_> = items
2825             .iter()
2826             .map(|i| {
2827                 let mut output = i.to_string(scx.tcx());
2828                 output.push_str(" @@");
2829                 let mut empty = Vec::new();
2830                 let mut cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);
2831                 cgus.as_mut_slice().sort_by_key(|&(ref name, _)| name.clone());
2832                 cgus.dedup();
2833                 for &(ref cgu_name, linkage) in cgus.iter() {
2834                     output.push_str(" ");
2835                     output.push_str(&cgu_name[..]);
2836
2837                     let linkage_abbrev = match linkage {
2838                         llvm::ExternalLinkage => "External",
2839                         llvm::AvailableExternallyLinkage => "Available",
2840                         llvm::LinkOnceAnyLinkage => "OnceAny",
2841                         llvm::LinkOnceODRLinkage => "OnceODR",
2842                         llvm::WeakAnyLinkage => "WeakAny",
2843                         llvm::WeakODRLinkage => "WeakODR",
2844                         llvm::AppendingLinkage => "Appending",
2845                         llvm::InternalLinkage => "Internal",
2846                         llvm::PrivateLinkage => "Private",
2847                         llvm::ExternalWeakLinkage => "ExternalWeak",
2848                         llvm::CommonLinkage => "Common",
2849                     };
2850
2851                     output.push_str("[");
2852                     output.push_str(linkage_abbrev);
2853                     output.push_str("]");
2854                 }
2855                 output
2856             })
2857             .collect();
2858
2859         item_keys.sort();
2860
2861         for item in item_keys {
2862             println!("TRANS_ITEM {}", item);
2863         }
2864     }
2865
2866     (codegen_units, symbol_map)
2867 }
2868
2869 fn symbol_for_def_id<'a, 'tcx>(def_id: DefId,
2870                                scx: &SharedCrateContext<'a, 'tcx>,
2871                                symbol_map: &SymbolMap<'tcx>)
2872                                -> String {
2873     // Just try to look things up in the symbol map. If nothing's there, we
2874     // recompute.
2875     if let Some(node_id) = scx.tcx().map.as_local_node_id(def_id) {
2876         if let Some(sym) = symbol_map.get(TransItem::Static(node_id)) {
2877             return sym.to_owned();
2878         }
2879     }
2880
2881     let instance = Instance::mono(scx, def_id);
2882
2883     symbol_map.get(TransItem::Fn(instance))
2884               .map(str::to_owned)
2885               .unwrap_or_else(|| instance.symbol_name(scx))
2886 }