]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/context.rs
Replace all uses of SHA-256 with BLAKE2b.
[rust.git] / src / librustc_trans / context.rs
1 // Copyright 2013 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 use llvm;
12 use llvm::{ContextRef, ModuleRef, ValueRef, BuilderRef};
13 use rustc::dep_graph::{DepNode, DepTrackingMap, DepTrackingMapConfig, WorkProduct};
14 use middle::cstore::LinkMeta;
15 use rustc::hir::def::ExportMap;
16 use rustc::hir::def_id::DefId;
17 use rustc::traits;
18 use base;
19 use builder::Builder;
20 use common::BuilderRef_res;
21 use debuginfo;
22 use declare;
23 use glue::DropGlueKind;
24 use monomorphize::Instance;
25
26 use partitioning::CodegenUnit;
27 use trans_item::TransItem;
28 use type_::{Type, TypeNames};
29 use rustc::ty::subst::Substs;
30 use rustc::ty::{self, Ty, TyCtxt};
31 use session::config::NoDebugInfo;
32 use session::Session;
33 use session::config;
34 use symbol_map::SymbolMap;
35 use util::nodemap::{NodeSet, DefIdMap, FnvHashMap, FnvHashSet};
36
37 use std::ffi::{CStr, CString};
38 use std::cell::{Cell, RefCell};
39 use std::marker::PhantomData;
40 use std::ptr;
41 use std::rc::Rc;
42 use std::str;
43 use syntax::ast;
44 use syntax::parse::token::InternedString;
45 use abi::FnType;
46
47 pub struct Stats {
48     pub n_glues_created: Cell<usize>,
49     pub n_null_glues: Cell<usize>,
50     pub n_real_glues: Cell<usize>,
51     pub n_fns: Cell<usize>,
52     pub n_inlines: Cell<usize>,
53     pub n_closures: Cell<usize>,
54     pub n_llvm_insns: Cell<usize>,
55     pub llvm_insns: RefCell<FnvHashMap<String, usize>>,
56     // (ident, llvm-instructions)
57     pub fn_stats: RefCell<Vec<(String, usize)> >,
58 }
59
60 /// The shared portion of a `CrateContext`.  There is one `SharedCrateContext`
61 /// per crate.  The data here is shared between all compilation units of the
62 /// crate, so it must not contain references to any LLVM data structures
63 /// (aside from metadata-related ones).
64 pub struct SharedCrateContext<'a, 'tcx: 'a> {
65     metadata_llmod: ModuleRef,
66     metadata_llcx: ContextRef,
67
68     export_map: ExportMap,
69     reachable: NodeSet,
70     link_meta: LinkMeta,
71     tcx: TyCtxt<'a, 'tcx, 'tcx>,
72     stats: Stats,
73     check_overflow: bool,
74
75     use_dll_storage_attrs: bool,
76
77     translation_items: RefCell<FnvHashSet<TransItem<'tcx>>>,
78     trait_cache: RefCell<DepTrackingMap<TraitSelectionCache<'tcx>>>,
79     project_cache: RefCell<DepTrackingMap<ProjectionCache<'tcx>>>,
80 }
81
82 /// The local portion of a `CrateContext`.  There is one `LocalCrateContext`
83 /// per compilation unit.  Each one has its own LLVM `ContextRef` so that
84 /// several compilation units may be optimized in parallel.  All other LLVM
85 /// data structures in the `LocalCrateContext` are tied to that `ContextRef`.
86 pub struct LocalCrateContext<'tcx> {
87     llmod: ModuleRef,
88     llcx: ContextRef,
89     previous_work_product: Option<WorkProduct>,
90     tn: TypeNames, // FIXME: This seems to be largely unused.
91     codegen_unit: CodegenUnit<'tcx>,
92     needs_unwind_cleanup_cache: RefCell<FnvHashMap<Ty<'tcx>, bool>>,
93     fn_pointer_shims: RefCell<FnvHashMap<Ty<'tcx>, ValueRef>>,
94     drop_glues: RefCell<FnvHashMap<DropGlueKind<'tcx>, (ValueRef, FnType)>>,
95     /// Cache instances of monomorphic and polymorphic items
96     instances: RefCell<FnvHashMap<Instance<'tcx>, ValueRef>>,
97     /// Cache generated vtables
98     vtables: RefCell<FnvHashMap<ty::PolyTraitRef<'tcx>, ValueRef>>,
99     /// Cache of constant strings,
100     const_cstr_cache: RefCell<FnvHashMap<InternedString, ValueRef>>,
101
102     /// Reverse-direction for const ptrs cast from globals.
103     /// Key is a ValueRef holding a *T,
104     /// Val is a ValueRef holding a *[T].
105     ///
106     /// Needed because LLVM loses pointer->pointee association
107     /// when we ptrcast, and we have to ptrcast during translation
108     /// of a [T] const because we form a slice, a (*T,usize) pair, not
109     /// a pointer to an LLVM array type. Similar for trait objects.
110     const_unsized: RefCell<FnvHashMap<ValueRef, ValueRef>>,
111
112     /// Cache of emitted const globals (value -> global)
113     const_globals: RefCell<FnvHashMap<ValueRef, ValueRef>>,
114
115     /// Cache of emitted const values
116     const_values: RefCell<FnvHashMap<(ast::NodeId, &'tcx Substs<'tcx>), ValueRef>>,
117
118     /// Cache of external const values
119     extern_const_values: RefCell<DefIdMap<ValueRef>>,
120
121     /// Mapping from static definitions to their DefId's.
122     statics: RefCell<FnvHashMap<ValueRef, DefId>>,
123
124     impl_method_cache: RefCell<FnvHashMap<(DefId, ast::Name), DefId>>,
125
126     /// Cache of closure wrappers for bare fn's.
127     closure_bare_wrapper_cache: RefCell<FnvHashMap<ValueRef, ValueRef>>,
128
129     /// List of globals for static variables which need to be passed to the
130     /// LLVM function ReplaceAllUsesWith (RAUW) when translation is complete.
131     /// (We have to make sure we don't invalidate any ValueRefs referring
132     /// to constants.)
133     statics_to_rauw: RefCell<Vec<(ValueRef, ValueRef)>>,
134
135     lltypes: RefCell<FnvHashMap<Ty<'tcx>, Type>>,
136     llsizingtypes: RefCell<FnvHashMap<Ty<'tcx>, Type>>,
137     type_hashcodes: RefCell<FnvHashMap<Ty<'tcx>, String>>,
138     int_type: Type,
139     opaque_vec_type: Type,
140     builder: BuilderRef_res,
141
142     /// Holds the LLVM values for closure IDs.
143     closure_vals: RefCell<FnvHashMap<Instance<'tcx>, ValueRef>>,
144
145     dbg_cx: Option<debuginfo::CrateDebugContext<'tcx>>,
146
147     eh_personality: Cell<Option<ValueRef>>,
148     eh_unwind_resume: Cell<Option<ValueRef>>,
149     rust_try_fn: Cell<Option<ValueRef>>,
150
151     intrinsics: RefCell<FnvHashMap<&'static str, ValueRef>>,
152
153     /// Number of LLVM instructions translated into this `LocalCrateContext`.
154     /// This is used to perform some basic load-balancing to keep all LLVM
155     /// contexts around the same size.
156     n_llvm_insns: Cell<usize>,
157
158     /// Depth of the current type-of computation - used to bail out
159     type_of_depth: Cell<usize>,
160
161     symbol_map: Rc<SymbolMap<'tcx>>,
162
163     /// A counter that is used for generating local symbol names
164     local_gen_sym_counter: Cell<usize>,
165 }
166
167 // Implement DepTrackingMapConfig for `trait_cache`
168 pub struct TraitSelectionCache<'tcx> {
169     data: PhantomData<&'tcx ()>
170 }
171
172 impl<'tcx> DepTrackingMapConfig for TraitSelectionCache<'tcx> {
173     type Key = ty::PolyTraitRef<'tcx>;
174     type Value = traits::Vtable<'tcx, ()>;
175     fn to_dep_node(key: &ty::PolyTraitRef<'tcx>) -> DepNode<DefId> {
176         key.to_poly_trait_predicate().dep_node()
177     }
178 }
179
180 // # Global Cache
181
182 pub struct ProjectionCache<'gcx> {
183     data: PhantomData<&'gcx ()>
184 }
185
186 impl<'gcx> DepTrackingMapConfig for ProjectionCache<'gcx> {
187     type Key = Ty<'gcx>;
188     type Value = Ty<'gcx>;
189     fn to_dep_node(key: &Self::Key) -> DepNode<DefId> {
190         // Ideally, we'd just put `key` into the dep-node, but we
191         // can't put full types in there. So just collect up all the
192         // def-ids of structs/enums as well as any traits that we
193         // project out of. It doesn't matter so much what we do here,
194         // except that if we are too coarse, we'll create overly
195         // coarse edges between impls and the trans. For example, if
196         // we just used the def-id of things we are projecting out of,
197         // then the key for `<Foo as SomeTrait>::T` and `<Bar as
198         // SomeTrait>::T` would both share a dep-node
199         // (`TraitSelect(SomeTrait)`), and hence the impls for both
200         // `Foo` and `Bar` would be considered inputs. So a change to
201         // `Bar` would affect things that just normalized `Foo`.
202         // Anyway, this heuristic is not ideal, but better than
203         // nothing.
204         let def_ids: Vec<DefId> =
205             key.walk()
206                .filter_map(|t| match t.sty {
207                    ty::TyAdt(adt_def, _) => Some(adt_def.did),
208                    ty::TyProjection(ref proj) => Some(proj.trait_ref.def_id),
209                    _ => None,
210                })
211                .collect();
212         DepNode::TraitSelect(def_ids)
213     }
214 }
215
216 /// This list owns a number of LocalCrateContexts and binds them to their common
217 /// SharedCrateContext. This type just exists as a convenience, something to
218 /// pass around all LocalCrateContexts with and get an iterator over them.
219 pub struct CrateContextList<'a, 'tcx: 'a> {
220     shared: &'a SharedCrateContext<'a, 'tcx>,
221     local_ccxs: Vec<LocalCrateContext<'tcx>>,
222 }
223
224 impl<'a, 'tcx: 'a> CrateContextList<'a, 'tcx> {
225     pub fn new(shared_ccx: &'a SharedCrateContext<'a, 'tcx>,
226                codegen_units: Vec<CodegenUnit<'tcx>>,
227                previous_work_products: Vec<Option<WorkProduct>>,
228                symbol_map: Rc<SymbolMap<'tcx>>)
229                -> CrateContextList<'a, 'tcx> {
230         CrateContextList {
231             shared: shared_ccx,
232             local_ccxs: codegen_units.into_iter().zip(previous_work_products).map(|(cgu, wp)| {
233                 LocalCrateContext::new(shared_ccx, cgu, wp, symbol_map.clone())
234             }).collect()
235         }
236     }
237
238     /// Iterate over all crate contexts, whether or not they need
239     /// translation.  That is, whether or not a `.o` file is available
240     /// for re-use from a previous incr. comp.).
241     pub fn iter_all<'b>(&'b self) -> CrateContextIterator<'b, 'tcx> {
242         CrateContextIterator {
243             shared: self.shared,
244             index: 0,
245             local_ccxs: &self.local_ccxs[..],
246             filter_to_previous_work_product_unavail: false,
247         }
248     }
249
250     /// Iterator over all CCX that need translation (cannot reuse results from
251     /// previous incr. comp.).
252     pub fn iter_need_trans<'b>(&'b self) -> CrateContextIterator<'b, 'tcx> {
253         CrateContextIterator {
254             shared: self.shared,
255             index: 0,
256             local_ccxs: &self.local_ccxs[..],
257             filter_to_previous_work_product_unavail: true,
258         }
259     }
260
261     pub fn shared(&self) -> &'a SharedCrateContext<'a, 'tcx> {
262         self.shared
263     }
264 }
265
266 /// A CrateContext value binds together one LocalCrateContext with the
267 /// SharedCrateContext. It exists as a convenience wrapper, so we don't have to
268 /// pass around (SharedCrateContext, LocalCrateContext) tuples all over trans.
269 pub struct CrateContext<'a, 'tcx: 'a> {
270     shared: &'a SharedCrateContext<'a, 'tcx>,
271     local_ccxs: &'a [LocalCrateContext<'tcx>],
272     /// The index of `local` in `local_ccxs`.  This is used in
273     /// `maybe_iter(true)` to identify the original `LocalCrateContext`.
274     index: usize,
275 }
276
277 pub struct CrateContextIterator<'a, 'tcx: 'a> {
278     shared: &'a SharedCrateContext<'a, 'tcx>,
279     local_ccxs: &'a [LocalCrateContext<'tcx>],
280     index: usize,
281
282     /// if true, only return results where `previous_work_product` is none
283     filter_to_previous_work_product_unavail: bool,
284 }
285
286 impl<'a, 'tcx> Iterator for CrateContextIterator<'a,'tcx> {
287     type Item = CrateContext<'a, 'tcx>;
288
289     fn next(&mut self) -> Option<CrateContext<'a, 'tcx>> {
290         loop {
291             if self.index >= self.local_ccxs.len() {
292                 return None;
293             }
294
295             let index = self.index;
296             self.index += 1;
297
298             let ccx = CrateContext {
299                 shared: self.shared,
300                 index: index,
301                 local_ccxs: self.local_ccxs,
302             };
303
304             if
305                 self.filter_to_previous_work_product_unavail &&
306                 ccx.previous_work_product().is_some()
307             {
308                 continue;
309             }
310
311             return Some(ccx);
312         }
313     }
314 }
315
316 /// The iterator produced by `CrateContext::maybe_iter`.
317 pub struct CrateContextMaybeIterator<'a, 'tcx: 'a> {
318     shared: &'a SharedCrateContext<'a, 'tcx>,
319     local_ccxs: &'a [LocalCrateContext<'tcx>],
320     index: usize,
321     single: bool,
322     origin: usize,
323 }
324
325 impl<'a, 'tcx> Iterator for CrateContextMaybeIterator<'a, 'tcx> {
326     type Item = (CrateContext<'a, 'tcx>, bool);
327
328     fn next(&mut self) -> Option<(CrateContext<'a, 'tcx>, bool)> {
329         if self.index >= self.local_ccxs.len() {
330             return None;
331         }
332
333         let index = self.index;
334         self.index += 1;
335         if self.single {
336             self.index = self.local_ccxs.len();
337         }
338
339         let ccx = CrateContext {
340             shared: self.shared,
341             index: index,
342             local_ccxs: self.local_ccxs
343         };
344         Some((ccx, index == self.origin))
345     }
346 }
347
348 pub fn get_reloc_model(sess: &Session) -> llvm::RelocMode {
349     let reloc_model_arg = match sess.opts.cg.relocation_model {
350         Some(ref s) => &s[..],
351         None => &sess.target.target.options.relocation_model[..],
352     };
353
354     match ::back::write::RELOC_MODEL_ARGS.iter().find(
355         |&&arg| arg.0 == reloc_model_arg) {
356         Some(x) => x.1,
357         _ => {
358             sess.err(&format!("{:?} is not a valid relocation mode",
359                              sess.opts
360                                  .cg
361                                  .code_model));
362             sess.abort_if_errors();
363             bug!();
364         }
365     }
366 }
367
368 fn is_any_library(sess: &Session) -> bool {
369     sess.crate_types.borrow().iter().any(|ty| {
370         *ty != config::CrateTypeExecutable
371     })
372 }
373
374 pub fn is_pie_binary(sess: &Session) -> bool {
375     !is_any_library(sess) && get_reloc_model(sess) == llvm::RelocMode::PIC
376 }
377
378 unsafe fn create_context_and_module(sess: &Session, mod_name: &str) -> (ContextRef, ModuleRef) {
379     let llcx = llvm::LLVMContextCreate();
380     let mod_name = CString::new(mod_name).unwrap();
381     let llmod = llvm::LLVMModuleCreateWithNameInContext(mod_name.as_ptr(), llcx);
382
383     // Ensure the data-layout values hardcoded remain the defaults.
384     if sess.target.target.options.is_builtin {
385         let tm = ::back::write::create_target_machine(sess);
386         llvm::LLVMRustSetDataLayoutFromTargetMachine(llmod, tm);
387         llvm::LLVMRustDisposeTargetMachine(tm);
388
389         let data_layout = llvm::LLVMGetDataLayout(llmod);
390         let data_layout = str::from_utf8(CStr::from_ptr(data_layout).to_bytes())
391             .ok().expect("got a non-UTF8 data-layout from LLVM");
392
393         // Unfortunately LLVM target specs change over time, and right now we
394         // don't have proper support to work with any more than one
395         // `data_layout` than the one that is in the rust-lang/rust repo. If
396         // this compiler is configured against a custom LLVM, we may have a
397         // differing data layout, even though we should update our own to use
398         // that one.
399         //
400         // As an interim hack, if CFG_LLVM_ROOT is not an empty string then we
401         // disable this check entirely as we may be configured with something
402         // that has a different target layout.
403         //
404         // Unsure if this will actually cause breakage when rustc is configured
405         // as such.
406         //
407         // FIXME(#34960)
408         let cfg_llvm_root = option_env!("CFG_LLVM_ROOT").unwrap_or("");
409         let custom_llvm_used = cfg_llvm_root.trim() != "";
410
411         if !custom_llvm_used && sess.target.target.data_layout != data_layout {
412             bug!("data-layout for builtin `{}` target, `{}`, \
413                   differs from LLVM default, `{}`",
414                  sess.target.target.llvm_target,
415                  sess.target.target.data_layout,
416                  data_layout);
417         }
418     }
419
420     let data_layout = CString::new(&sess.target.target.data_layout[..]).unwrap();
421     llvm::LLVMSetDataLayout(llmod, data_layout.as_ptr());
422
423     let llvm_target = sess.target.target.llvm_target.as_bytes();
424     let llvm_target = CString::new(llvm_target).unwrap();
425     llvm::LLVMRustSetNormalizedTarget(llmod, llvm_target.as_ptr());
426
427     if is_pie_binary(sess) {
428         llvm::LLVMRustSetModulePIELevel(llmod);
429     }
430
431     (llcx, llmod)
432 }
433
434 impl<'b, 'tcx> SharedCrateContext<'b, 'tcx> {
435     pub fn new(tcx: TyCtxt<'b, 'tcx, 'tcx>,
436                export_map: ExportMap,
437                link_meta: LinkMeta,
438                reachable: NodeSet,
439                check_overflow: bool)
440                -> SharedCrateContext<'b, 'tcx> {
441         let (metadata_llcx, metadata_llmod) = unsafe {
442             create_context_and_module(&tcx.sess, "metadata")
443         };
444
445         // An interesting part of Windows which MSVC forces our hand on (and
446         // apparently MinGW didn't) is the usage of `dllimport` and `dllexport`
447         // attributes in LLVM IR as well as native dependencies (in C these
448         // correspond to `__declspec(dllimport)`).
449         //
450         // Whenever a dynamic library is built by MSVC it must have its public
451         // interface specified by functions tagged with `dllexport` or otherwise
452         // they're not available to be linked against. This poses a few problems
453         // for the compiler, some of which are somewhat fundamental, but we use
454         // the `use_dll_storage_attrs` variable below to attach the `dllexport`
455         // attribute to all LLVM functions that are reachable (e.g. they're
456         // already tagged with external linkage). This is suboptimal for a few
457         // reasons:
458         //
459         // * If an object file will never be included in a dynamic library,
460         //   there's no need to attach the dllexport attribute. Most object
461         //   files in Rust are not destined to become part of a dll as binaries
462         //   are statically linked by default.
463         // * If the compiler is emitting both an rlib and a dylib, the same
464         //   source object file is currently used but with MSVC this may be less
465         //   feasible. The compiler may be able to get around this, but it may
466         //   involve some invasive changes to deal with this.
467         //
468         // The flipside of this situation is that whenever you link to a dll and
469         // you import a function from it, the import should be tagged with
470         // `dllimport`. At this time, however, the compiler does not emit
471         // `dllimport` for any declarations other than constants (where it is
472         // required), which is again suboptimal for even more reasons!
473         //
474         // * Calling a function imported from another dll without using
475         //   `dllimport` causes the linker/compiler to have extra overhead (one
476         //   `jmp` instruction on x86) when calling the function.
477         // * The same object file may be used in different circumstances, so a
478         //   function may be imported from a dll if the object is linked into a
479         //   dll, but it may be just linked against if linked into an rlib.
480         // * The compiler has no knowledge about whether native functions should
481         //   be tagged dllimport or not.
482         //
483         // For now the compiler takes the perf hit (I do not have any numbers to
484         // this effect) by marking very little as `dllimport` and praying the
485         // linker will take care of everything. Fixing this problem will likely
486         // require adding a few attributes to Rust itself (feature gated at the
487         // start) and then strongly recommending static linkage on MSVC!
488         let use_dll_storage_attrs = tcx.sess.target.target.options.is_like_msvc;
489
490         SharedCrateContext {
491             metadata_llmod: metadata_llmod,
492             metadata_llcx: metadata_llcx,
493             export_map: export_map,
494             reachable: reachable,
495             link_meta: link_meta,
496             tcx: tcx,
497             stats: Stats {
498                 n_glues_created: Cell::new(0),
499                 n_null_glues: Cell::new(0),
500                 n_real_glues: Cell::new(0),
501                 n_fns: Cell::new(0),
502                 n_inlines: Cell::new(0),
503                 n_closures: Cell::new(0),
504                 n_llvm_insns: Cell::new(0),
505                 llvm_insns: RefCell::new(FnvHashMap()),
506                 fn_stats: RefCell::new(Vec::new()),
507             },
508             check_overflow: check_overflow,
509             use_dll_storage_attrs: use_dll_storage_attrs,
510             translation_items: RefCell::new(FnvHashSet()),
511             trait_cache: RefCell::new(DepTrackingMap::new(tcx.dep_graph.clone())),
512             project_cache: RefCell::new(DepTrackingMap::new(tcx.dep_graph.clone())),
513         }
514     }
515
516     pub fn metadata_llmod(&self) -> ModuleRef {
517         self.metadata_llmod
518     }
519
520     pub fn metadata_llcx(&self) -> ContextRef {
521         self.metadata_llcx
522     }
523
524     pub fn export_map<'a>(&'a self) -> &'a ExportMap {
525         &self.export_map
526     }
527
528     pub fn reachable<'a>(&'a self) -> &'a NodeSet {
529         &self.reachable
530     }
531
532     pub fn trait_cache(&self) -> &RefCell<DepTrackingMap<TraitSelectionCache<'tcx>>> {
533         &self.trait_cache
534     }
535
536     pub fn project_cache(&self) -> &RefCell<DepTrackingMap<ProjectionCache<'tcx>>> {
537         &self.project_cache
538     }
539
540     pub fn link_meta<'a>(&'a self) -> &'a LinkMeta {
541         &self.link_meta
542     }
543
544     pub fn tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> {
545         self.tcx
546     }
547
548     pub fn sess<'a>(&'a self) -> &'a Session {
549         &self.tcx.sess
550     }
551
552     pub fn stats<'a>(&'a self) -> &'a Stats {
553         &self.stats
554     }
555
556     pub fn use_dll_storage_attrs(&self) -> bool {
557         self.use_dll_storage_attrs
558     }
559
560     pub fn translation_items(&self) -> &RefCell<FnvHashSet<TransItem<'tcx>>> {
561         &self.translation_items
562     }
563
564     /// Given the def-id of some item that has no type parameters, make
565     /// a suitable "empty substs" for it.
566     pub fn empty_substs_for_def_id(&self, item_def_id: DefId) -> &'tcx Substs<'tcx> {
567         Substs::for_item(self.tcx(), item_def_id,
568                          |_, _| self.tcx().mk_region(ty::ReErased),
569                          |_, _| {
570             bug!("empty_substs_for_def_id: {:?} has type parameters", item_def_id)
571         })
572     }
573
574     pub fn metadata_symbol_name(&self) -> String {
575         format!("rust_metadata_{}_{}",
576                 self.link_meta().crate_name,
577                 self.link_meta().crate_hash)
578     }
579 }
580
581 impl<'tcx> LocalCrateContext<'tcx> {
582     fn new<'a>(shared: &SharedCrateContext<'a, 'tcx>,
583                codegen_unit: CodegenUnit<'tcx>,
584                previous_work_product: Option<WorkProduct>,
585                symbol_map: Rc<SymbolMap<'tcx>>)
586            -> LocalCrateContext<'tcx> {
587         unsafe {
588             // Append ".rs" to LLVM module identifier.
589             //
590             // LLVM code generator emits a ".file filename" directive
591             // for ELF backends. Value of the "filename" is set as the
592             // LLVM module identifier.  Due to a LLVM MC bug[1], LLVM
593             // crashes if the module identifier is same as other symbols
594             // such as a function name in the module.
595             // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
596             let llmod_id = format!("{}.rs", codegen_unit.name());
597
598             let (llcx, llmod) = create_context_and_module(&shared.tcx.sess,
599                                                           &llmod_id[..]);
600
601             let dbg_cx = if shared.tcx.sess.opts.debuginfo != NoDebugInfo {
602                 let dctx = debuginfo::CrateDebugContext::new(llmod);
603                 debuginfo::metadata::compile_unit_metadata(shared, &dctx, shared.tcx.sess);
604                 Some(dctx)
605             } else {
606                 None
607             };
608
609             let local_ccx = LocalCrateContext {
610                 llmod: llmod,
611                 llcx: llcx,
612                 previous_work_product: previous_work_product,
613                 codegen_unit: codegen_unit,
614                 tn: TypeNames::new(),
615                 needs_unwind_cleanup_cache: RefCell::new(FnvHashMap()),
616                 fn_pointer_shims: RefCell::new(FnvHashMap()),
617                 drop_glues: RefCell::new(FnvHashMap()),
618                 instances: RefCell::new(FnvHashMap()),
619                 vtables: RefCell::new(FnvHashMap()),
620                 const_cstr_cache: RefCell::new(FnvHashMap()),
621                 const_unsized: RefCell::new(FnvHashMap()),
622                 const_globals: RefCell::new(FnvHashMap()),
623                 const_values: RefCell::new(FnvHashMap()),
624                 extern_const_values: RefCell::new(DefIdMap()),
625                 statics: RefCell::new(FnvHashMap()),
626                 impl_method_cache: RefCell::new(FnvHashMap()),
627                 closure_bare_wrapper_cache: RefCell::new(FnvHashMap()),
628                 statics_to_rauw: RefCell::new(Vec::new()),
629                 lltypes: RefCell::new(FnvHashMap()),
630                 llsizingtypes: RefCell::new(FnvHashMap()),
631                 type_hashcodes: RefCell::new(FnvHashMap()),
632                 int_type: Type::from_ref(ptr::null_mut()),
633                 opaque_vec_type: Type::from_ref(ptr::null_mut()),
634                 builder: BuilderRef_res(llvm::LLVMCreateBuilderInContext(llcx)),
635                 closure_vals: RefCell::new(FnvHashMap()),
636                 dbg_cx: dbg_cx,
637                 eh_personality: Cell::new(None),
638                 eh_unwind_resume: Cell::new(None),
639                 rust_try_fn: Cell::new(None),
640                 intrinsics: RefCell::new(FnvHashMap()),
641                 n_llvm_insns: Cell::new(0),
642                 type_of_depth: Cell::new(0),
643                 symbol_map: symbol_map,
644                 local_gen_sym_counter: Cell::new(0),
645             };
646
647             let (int_type, opaque_vec_type, str_slice_ty, mut local_ccx) = {
648                 // Do a little dance to create a dummy CrateContext, so we can
649                 // create some things in the LLVM module of this codegen unit
650                 let mut local_ccxs = vec![local_ccx];
651                 let (int_type, opaque_vec_type, str_slice_ty) = {
652                     let dummy_ccx = LocalCrateContext::dummy_ccx(shared,
653                                                                  local_ccxs.as_mut_slice());
654                     let mut str_slice_ty = Type::named_struct(&dummy_ccx, "str_slice");
655                     str_slice_ty.set_struct_body(&[Type::i8p(&dummy_ccx),
656                                                    Type::int(&dummy_ccx)],
657                                                  false);
658                     (Type::int(&dummy_ccx), Type::opaque_vec(&dummy_ccx), str_slice_ty)
659                 };
660                 (int_type, opaque_vec_type, str_slice_ty, local_ccxs.pop().unwrap())
661             };
662
663             local_ccx.int_type = int_type;
664             local_ccx.opaque_vec_type = opaque_vec_type;
665             local_ccx.tn.associate_type("str_slice", &str_slice_ty);
666
667             if shared.tcx.sess.count_llvm_insns() {
668                 base::init_insn_ctxt()
669             }
670
671             local_ccx
672         }
673     }
674
675     /// Create a dummy `CrateContext` from `self` and  the provided
676     /// `SharedCrateContext`.  This is somewhat dangerous because `self` may
677     /// not be fully initialized.
678     ///
679     /// This is used in the `LocalCrateContext` constructor to allow calling
680     /// functions that expect a complete `CrateContext`, even before the local
681     /// portion is fully initialized and attached to the `SharedCrateContext`.
682     fn dummy_ccx<'a>(shared: &'a SharedCrateContext<'a, 'tcx>,
683                      local_ccxs: &'a [LocalCrateContext<'tcx>])
684                      -> CrateContext<'a, 'tcx> {
685         assert!(local_ccxs.len() == 1);
686         CrateContext {
687             shared: shared,
688             index: 0,
689             local_ccxs: local_ccxs
690         }
691     }
692 }
693
694 impl<'b, 'tcx> CrateContext<'b, 'tcx> {
695     pub fn shared(&self) -> &'b SharedCrateContext<'b, 'tcx> {
696         self.shared
697     }
698
699     pub fn local(&self) -> &'b LocalCrateContext<'tcx> {
700         &self.local_ccxs[self.index]
701     }
702
703     /// Get a (possibly) different `CrateContext` from the same
704     /// `SharedCrateContext`.
705     pub fn rotate(&'b self) -> CrateContext<'b, 'tcx> {
706         let (_, index) =
707             self.local_ccxs
708                 .iter()
709                 .zip(0..self.local_ccxs.len())
710                 .min_by_key(|&(local_ccx, _idx)| local_ccx.n_llvm_insns.get())
711                 .unwrap();
712         CrateContext {
713             shared: self.shared,
714             index: index,
715             local_ccxs: &self.local_ccxs[..],
716         }
717     }
718
719     /// Either iterate over only `self`, or iterate over all `CrateContext`s in
720     /// the `SharedCrateContext`.  The iterator produces `(ccx, is_origin)`
721     /// pairs, where `is_origin` is `true` if `ccx` is `self` and `false`
722     /// otherwise.  This method is useful for avoiding code duplication in
723     /// cases where it may or may not be necessary to translate code into every
724     /// context.
725     pub fn maybe_iter(&self, iter_all: bool) -> CrateContextMaybeIterator<'b, 'tcx> {
726         CrateContextMaybeIterator {
727             shared: self.shared,
728             index: if iter_all { 0 } else { self.index },
729             single: !iter_all,
730             origin: self.index,
731             local_ccxs: self.local_ccxs,
732         }
733     }
734
735     pub fn tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> {
736         self.shared.tcx
737     }
738
739     pub fn sess<'a>(&'a self) -> &'a Session {
740         &self.shared.tcx.sess
741     }
742
743     pub fn builder<'a>(&'a self) -> Builder<'a, 'tcx> {
744         Builder::new(self)
745     }
746
747     pub fn raw_builder<'a>(&'a self) -> BuilderRef {
748         self.local().builder.b
749     }
750
751     pub fn get_intrinsic(&self, key: &str) -> ValueRef {
752         if let Some(v) = self.intrinsics().borrow().get(key).cloned() {
753             return v;
754         }
755         match declare_intrinsic(self, key) {
756             Some(v) => return v,
757             None => bug!("unknown intrinsic '{}'", key)
758         }
759     }
760
761     pub fn llmod(&self) -> ModuleRef {
762         self.local().llmod
763     }
764
765     pub fn llcx(&self) -> ContextRef {
766         self.local().llcx
767     }
768
769     pub fn previous_work_product(&self) -> Option<&WorkProduct> {
770         self.local().previous_work_product.as_ref()
771     }
772
773     pub fn codegen_unit(&self) -> &CodegenUnit<'tcx> {
774         &self.local().codegen_unit
775     }
776
777     pub fn td(&self) -> llvm::TargetDataRef {
778         unsafe { llvm::LLVMRustGetModuleDataLayout(self.llmod()) }
779     }
780
781     pub fn tn<'a>(&'a self) -> &'a TypeNames {
782         &self.local().tn
783     }
784
785     pub fn export_map<'a>(&'a self) -> &'a ExportMap {
786         &self.shared.export_map
787     }
788
789     pub fn reachable<'a>(&'a self) -> &'a NodeSet {
790         &self.shared.reachable
791     }
792
793     pub fn link_meta<'a>(&'a self) -> &'a LinkMeta {
794         &self.shared.link_meta
795     }
796
797     pub fn needs_unwind_cleanup_cache(&self) -> &RefCell<FnvHashMap<Ty<'tcx>, bool>> {
798         &self.local().needs_unwind_cleanup_cache
799     }
800
801     pub fn fn_pointer_shims(&self) -> &RefCell<FnvHashMap<Ty<'tcx>, ValueRef>> {
802         &self.local().fn_pointer_shims
803     }
804
805     pub fn drop_glues<'a>(&'a self)
806                           -> &'a RefCell<FnvHashMap<DropGlueKind<'tcx>, (ValueRef, FnType)>> {
807         &self.local().drop_glues
808     }
809
810     pub fn local_node_for_inlined_defid<'a>(&'a self, def_id: DefId) -> Option<ast::NodeId> {
811         self.sess().cstore.local_node_for_inlined_defid(def_id)
812     }
813
814     pub fn defid_for_inlined_node<'a>(&'a self, node_id: ast::NodeId) -> Option<DefId> {
815         self.sess().cstore.defid_for_inlined_node(node_id)
816     }
817
818     pub fn instances<'a>(&'a self) -> &'a RefCell<FnvHashMap<Instance<'tcx>, ValueRef>> {
819         &self.local().instances
820     }
821
822     pub fn vtables<'a>(&'a self) -> &'a RefCell<FnvHashMap<ty::PolyTraitRef<'tcx>, ValueRef>> {
823         &self.local().vtables
824     }
825
826     pub fn const_cstr_cache<'a>(&'a self) -> &'a RefCell<FnvHashMap<InternedString, ValueRef>> {
827         &self.local().const_cstr_cache
828     }
829
830     pub fn const_unsized<'a>(&'a self) -> &'a RefCell<FnvHashMap<ValueRef, ValueRef>> {
831         &self.local().const_unsized
832     }
833
834     pub fn const_globals<'a>(&'a self) -> &'a RefCell<FnvHashMap<ValueRef, ValueRef>> {
835         &self.local().const_globals
836     }
837
838     pub fn const_values<'a>(&'a self) -> &'a RefCell<FnvHashMap<(ast::NodeId, &'tcx Substs<'tcx>),
839                                                                 ValueRef>> {
840         &self.local().const_values
841     }
842
843     pub fn extern_const_values<'a>(&'a self) -> &'a RefCell<DefIdMap<ValueRef>> {
844         &self.local().extern_const_values
845     }
846
847     pub fn statics<'a>(&'a self) -> &'a RefCell<FnvHashMap<ValueRef, DefId>> {
848         &self.local().statics
849     }
850
851     pub fn impl_method_cache<'a>(&'a self)
852             -> &'a RefCell<FnvHashMap<(DefId, ast::Name), DefId>> {
853         &self.local().impl_method_cache
854     }
855
856     pub fn closure_bare_wrapper_cache<'a>(&'a self) -> &'a RefCell<FnvHashMap<ValueRef, ValueRef>> {
857         &self.local().closure_bare_wrapper_cache
858     }
859
860     pub fn statics_to_rauw<'a>(&'a self) -> &'a RefCell<Vec<(ValueRef, ValueRef)>> {
861         &self.local().statics_to_rauw
862     }
863
864     pub fn lltypes<'a>(&'a self) -> &'a RefCell<FnvHashMap<Ty<'tcx>, Type>> {
865         &self.local().lltypes
866     }
867
868     pub fn llsizingtypes<'a>(&'a self) -> &'a RefCell<FnvHashMap<Ty<'tcx>, Type>> {
869         &self.local().llsizingtypes
870     }
871
872     pub fn type_hashcodes<'a>(&'a self) -> &'a RefCell<FnvHashMap<Ty<'tcx>, String>> {
873         &self.local().type_hashcodes
874     }
875
876     pub fn stats<'a>(&'a self) -> &'a Stats {
877         &self.shared.stats
878     }
879
880     pub fn int_type(&self) -> Type {
881         self.local().int_type
882     }
883
884     pub fn opaque_vec_type(&self) -> Type {
885         self.local().opaque_vec_type
886     }
887
888     pub fn closure_vals<'a>(&'a self) -> &'a RefCell<FnvHashMap<Instance<'tcx>, ValueRef>> {
889         &self.local().closure_vals
890     }
891
892     pub fn dbg_cx<'a>(&'a self) -> &'a Option<debuginfo::CrateDebugContext<'tcx>> {
893         &self.local().dbg_cx
894     }
895
896     pub fn eh_personality<'a>(&'a self) -> &'a Cell<Option<ValueRef>> {
897         &self.local().eh_personality
898     }
899
900     pub fn eh_unwind_resume<'a>(&'a self) -> &'a Cell<Option<ValueRef>> {
901         &self.local().eh_unwind_resume
902     }
903
904     pub fn rust_try_fn<'a>(&'a self) -> &'a Cell<Option<ValueRef>> {
905         &self.local().rust_try_fn
906     }
907
908     fn intrinsics<'a>(&'a self) -> &'a RefCell<FnvHashMap<&'static str, ValueRef>> {
909         &self.local().intrinsics
910     }
911
912     pub fn count_llvm_insn(&self) {
913         self.local().n_llvm_insns.set(self.local().n_llvm_insns.get() + 1);
914     }
915
916     pub fn obj_size_bound(&self) -> u64 {
917         self.tcx().data_layout.obj_size_bound()
918     }
919
920     pub fn report_overbig_object(&self, obj: Ty<'tcx>) -> ! {
921         self.sess().fatal(
922             &format!("the type `{:?}` is too big for the current architecture",
923                     obj))
924     }
925
926     pub fn enter_type_of(&self, ty: Ty<'tcx>) -> TypeOfDepthLock<'b, 'tcx> {
927         let current_depth = self.local().type_of_depth.get();
928         debug!("enter_type_of({:?}) at depth {:?}", ty, current_depth);
929         if current_depth > self.sess().recursion_limit.get() {
930             self.sess().fatal(
931                 &format!("overflow representing the type `{}`", ty))
932         }
933         self.local().type_of_depth.set(current_depth + 1);
934         TypeOfDepthLock(self.local())
935     }
936
937     pub fn layout_of(&self, ty: Ty<'tcx>) -> &'tcx ty::layout::Layout {
938         self.tcx().infer_ctxt(None, None, traits::Reveal::All).enter(|infcx| {
939             ty.layout(&infcx).unwrap_or_else(|e| {
940                 match e {
941                     ty::layout::LayoutError::SizeOverflow(_) =>
942                         self.sess().fatal(&e.to_string()),
943                     _ => bug!("failed to get layout for `{}`: {}", ty, e)
944                 }
945             })
946         })
947     }
948
949     pub fn check_overflow(&self) -> bool {
950         self.shared.check_overflow
951     }
952
953     pub fn use_dll_storage_attrs(&self) -> bool {
954         self.shared.use_dll_storage_attrs()
955     }
956
957     pub fn symbol_map(&self) -> &SymbolMap<'tcx> {
958         &*self.local().symbol_map
959     }
960
961     pub fn translation_items(&self) -> &RefCell<FnvHashSet<TransItem<'tcx>>> {
962         &self.shared.translation_items
963     }
964
965     /// Given the def-id of some item that has no type parameters, make
966     /// a suitable "empty substs" for it.
967     pub fn empty_substs_for_def_id(&self, item_def_id: DefId) -> &'tcx Substs<'tcx> {
968         self.shared().empty_substs_for_def_id(item_def_id)
969     }
970
971     /// Generate a new symbol name with the given prefix. This symbol name must
972     /// only be used for definitions with `internal` or `private` linkage.
973     pub fn generate_local_symbol_name(&self, prefix: &str) -> String {
974         let idx = self.local().local_gen_sym_counter.get();
975         self.local().local_gen_sym_counter.set(idx + 1);
976         // Include a '.' character, so there can be no accidental conflicts with
977         // user defined names
978         format!("{}.{}", prefix, idx)
979     }
980 }
981
982 pub struct TypeOfDepthLock<'a, 'tcx: 'a>(&'a LocalCrateContext<'tcx>);
983
984 impl<'a, 'tcx> Drop for TypeOfDepthLock<'a, 'tcx> {
985     fn drop(&mut self) {
986         self.0.type_of_depth.set(self.0.type_of_depth.get() - 1);
987     }
988 }
989
990 /// Declare any llvm intrinsics that you might need
991 fn declare_intrinsic(ccx: &CrateContext, key: &str) -> Option<ValueRef> {
992     macro_rules! ifn {
993         ($name:expr, fn() -> $ret:expr) => (
994             if key == $name {
995                 let f = declare::declare_cfn(ccx, $name, Type::func(&[], &$ret));
996                 llvm::SetUnnamedAddr(f, false);
997                 ccx.intrinsics().borrow_mut().insert($name, f.clone());
998                 return Some(f);
999             }
1000         );
1001         ($name:expr, fn(...) -> $ret:expr) => (
1002             if key == $name {
1003                 let f = declare::declare_cfn(ccx, $name, Type::variadic_func(&[], &$ret));
1004                 llvm::SetUnnamedAddr(f, false);
1005                 ccx.intrinsics().borrow_mut().insert($name, f.clone());
1006                 return Some(f);
1007             }
1008         );
1009         ($name:expr, fn($($arg:expr),*) -> $ret:expr) => (
1010             if key == $name {
1011                 let f = declare::declare_cfn(ccx, $name, Type::func(&[$($arg),*], &$ret));
1012                 llvm::SetUnnamedAddr(f, false);
1013                 ccx.intrinsics().borrow_mut().insert($name, f.clone());
1014                 return Some(f);
1015             }
1016         );
1017     }
1018     macro_rules! mk_struct {
1019         ($($field_ty:expr),*) => (Type::struct_(ccx, &[$($field_ty),*], false))
1020     }
1021
1022     let i8p = Type::i8p(ccx);
1023     let void = Type::void(ccx);
1024     let i1 = Type::i1(ccx);
1025     let t_i8 = Type::i8(ccx);
1026     let t_i16 = Type::i16(ccx);
1027     let t_i32 = Type::i32(ccx);
1028     let t_i64 = Type::i64(ccx);
1029     let t_f32 = Type::f32(ccx);
1030     let t_f64 = Type::f64(ccx);
1031
1032     ifn!("llvm.memcpy.p0i8.p0i8.i16", fn(i8p, i8p, t_i16, t_i32, i1) -> void);
1033     ifn!("llvm.memcpy.p0i8.p0i8.i32", fn(i8p, i8p, t_i32, t_i32, i1) -> void);
1034     ifn!("llvm.memcpy.p0i8.p0i8.i64", fn(i8p, i8p, t_i64, t_i32, i1) -> void);
1035     ifn!("llvm.memmove.p0i8.p0i8.i16", fn(i8p, i8p, t_i16, t_i32, i1) -> void);
1036     ifn!("llvm.memmove.p0i8.p0i8.i32", fn(i8p, i8p, t_i32, t_i32, i1) -> void);
1037     ifn!("llvm.memmove.p0i8.p0i8.i64", fn(i8p, i8p, t_i64, t_i32, i1) -> void);
1038     ifn!("llvm.memset.p0i8.i16", fn(i8p, t_i8, t_i16, t_i32, i1) -> void);
1039     ifn!("llvm.memset.p0i8.i32", fn(i8p, t_i8, t_i32, t_i32, i1) -> void);
1040     ifn!("llvm.memset.p0i8.i64", fn(i8p, t_i8, t_i64, t_i32, i1) -> void);
1041
1042     ifn!("llvm.trap", fn() -> void);
1043     ifn!("llvm.debugtrap", fn() -> void);
1044     ifn!("llvm.frameaddress", fn(t_i32) -> i8p);
1045
1046     ifn!("llvm.powi.f32", fn(t_f32, t_i32) -> t_f32);
1047     ifn!("llvm.powi.f64", fn(t_f64, t_i32) -> t_f64);
1048     ifn!("llvm.pow.f32", fn(t_f32, t_f32) -> t_f32);
1049     ifn!("llvm.pow.f64", fn(t_f64, t_f64) -> t_f64);
1050
1051     ifn!("llvm.sqrt.f32", fn(t_f32) -> t_f32);
1052     ifn!("llvm.sqrt.f64", fn(t_f64) -> t_f64);
1053     ifn!("llvm.sin.f32", fn(t_f32) -> t_f32);
1054     ifn!("llvm.sin.f64", fn(t_f64) -> t_f64);
1055     ifn!("llvm.cos.f32", fn(t_f32) -> t_f32);
1056     ifn!("llvm.cos.f64", fn(t_f64) -> t_f64);
1057     ifn!("llvm.exp.f32", fn(t_f32) -> t_f32);
1058     ifn!("llvm.exp.f64", fn(t_f64) -> t_f64);
1059     ifn!("llvm.exp2.f32", fn(t_f32) -> t_f32);
1060     ifn!("llvm.exp2.f64", fn(t_f64) -> t_f64);
1061     ifn!("llvm.log.f32", fn(t_f32) -> t_f32);
1062     ifn!("llvm.log.f64", fn(t_f64) -> t_f64);
1063     ifn!("llvm.log10.f32", fn(t_f32) -> t_f32);
1064     ifn!("llvm.log10.f64", fn(t_f64) -> t_f64);
1065     ifn!("llvm.log2.f32", fn(t_f32) -> t_f32);
1066     ifn!("llvm.log2.f64", fn(t_f64) -> t_f64);
1067
1068     ifn!("llvm.fma.f32", fn(t_f32, t_f32, t_f32) -> t_f32);
1069     ifn!("llvm.fma.f64", fn(t_f64, t_f64, t_f64) -> t_f64);
1070
1071     ifn!("llvm.fabs.f32", fn(t_f32) -> t_f32);
1072     ifn!("llvm.fabs.f64", fn(t_f64) -> t_f64);
1073
1074     ifn!("llvm.floor.f32", fn(t_f32) -> t_f32);
1075     ifn!("llvm.floor.f64", fn(t_f64) -> t_f64);
1076     ifn!("llvm.ceil.f32", fn(t_f32) -> t_f32);
1077     ifn!("llvm.ceil.f64", fn(t_f64) -> t_f64);
1078     ifn!("llvm.trunc.f32", fn(t_f32) -> t_f32);
1079     ifn!("llvm.trunc.f64", fn(t_f64) -> t_f64);
1080
1081     ifn!("llvm.copysign.f32", fn(t_f32, t_f32) -> t_f32);
1082     ifn!("llvm.copysign.f64", fn(t_f64, t_f64) -> t_f64);
1083     ifn!("llvm.round.f32", fn(t_f32) -> t_f32);
1084     ifn!("llvm.round.f64", fn(t_f64) -> t_f64);
1085
1086     ifn!("llvm.rint.f32", fn(t_f32) -> t_f32);
1087     ifn!("llvm.rint.f64", fn(t_f64) -> t_f64);
1088     ifn!("llvm.nearbyint.f32", fn(t_f32) -> t_f32);
1089     ifn!("llvm.nearbyint.f64", fn(t_f64) -> t_f64);
1090
1091     ifn!("llvm.ctpop.i8", fn(t_i8) -> t_i8);
1092     ifn!("llvm.ctpop.i16", fn(t_i16) -> t_i16);
1093     ifn!("llvm.ctpop.i32", fn(t_i32) -> t_i32);
1094     ifn!("llvm.ctpop.i64", fn(t_i64) -> t_i64);
1095
1096     ifn!("llvm.ctlz.i8", fn(t_i8 , i1) -> t_i8);
1097     ifn!("llvm.ctlz.i16", fn(t_i16, i1) -> t_i16);
1098     ifn!("llvm.ctlz.i32", fn(t_i32, i1) -> t_i32);
1099     ifn!("llvm.ctlz.i64", fn(t_i64, i1) -> t_i64);
1100
1101     ifn!("llvm.cttz.i8", fn(t_i8 , i1) -> t_i8);
1102     ifn!("llvm.cttz.i16", fn(t_i16, i1) -> t_i16);
1103     ifn!("llvm.cttz.i32", fn(t_i32, i1) -> t_i32);
1104     ifn!("llvm.cttz.i64", fn(t_i64, i1) -> t_i64);
1105
1106     ifn!("llvm.bswap.i16", fn(t_i16) -> t_i16);
1107     ifn!("llvm.bswap.i32", fn(t_i32) -> t_i32);
1108     ifn!("llvm.bswap.i64", fn(t_i64) -> t_i64);
1109
1110     ifn!("llvm.sadd.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
1111     ifn!("llvm.sadd.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
1112     ifn!("llvm.sadd.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
1113     ifn!("llvm.sadd.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
1114
1115     ifn!("llvm.uadd.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
1116     ifn!("llvm.uadd.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
1117     ifn!("llvm.uadd.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
1118     ifn!("llvm.uadd.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
1119
1120     ifn!("llvm.ssub.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
1121     ifn!("llvm.ssub.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
1122     ifn!("llvm.ssub.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
1123     ifn!("llvm.ssub.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
1124
1125     ifn!("llvm.usub.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
1126     ifn!("llvm.usub.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
1127     ifn!("llvm.usub.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
1128     ifn!("llvm.usub.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
1129
1130     ifn!("llvm.smul.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
1131     ifn!("llvm.smul.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
1132     ifn!("llvm.smul.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
1133     ifn!("llvm.smul.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
1134
1135     ifn!("llvm.umul.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
1136     ifn!("llvm.umul.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
1137     ifn!("llvm.umul.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
1138     ifn!("llvm.umul.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
1139
1140     ifn!("llvm.lifetime.start", fn(t_i64,i8p) -> void);
1141     ifn!("llvm.lifetime.end", fn(t_i64, i8p) -> void);
1142
1143     ifn!("llvm.expect.i1", fn(i1, i1) -> i1);
1144     ifn!("llvm.eh.typeid.for", fn(i8p) -> t_i32);
1145     ifn!("llvm.localescape", fn(...) -> void);
1146     ifn!("llvm.localrecover", fn(i8p, i8p, t_i32) -> i8p);
1147     ifn!("llvm.x86.seh.recoverfp", fn(i8p, i8p) -> i8p);
1148
1149     ifn!("llvm.assume", fn(i1) -> void);
1150
1151     if ccx.sess().opts.debuginfo != NoDebugInfo {
1152         ifn!("llvm.dbg.declare", fn(Type::metadata(ccx), Type::metadata(ccx)) -> void);
1153         ifn!("llvm.dbg.value", fn(Type::metadata(ccx), t_i64, Type::metadata(ccx)) -> void);
1154     }
1155     return None;
1156 }