]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/context.rs
Refactor determining of relocation model into methods
[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 rustc::mir::mir_map::MirMap;
19 use rustc::mir::repr as mir;
20 use adt;
21 use base;
22 use builder::Builder;
23 use common::BuilderRef_res;
24 use debuginfo;
25 use declare;
26 use glue::DropGlueKind;
27 use mir::CachedMir;
28 use monomorphize::Instance;
29
30 use partitioning::CodegenUnit;
31 use trans_item::TransItem;
32 use type_::{Type, TypeNames};
33 use rustc::ty::subst::{Substs, VecPerParamSpace};
34 use rustc::ty::{self, Ty, TyCtxt};
35 use session::config::NoDebugInfo;
36 use session::Session;
37 use session::config;
38 use symbol_map::SymbolMap;
39 use util::sha2::Sha256;
40 use util::nodemap::{NodeMap, NodeSet, DefIdMap, FnvHashMap, FnvHashSet};
41
42 use std::ffi::{CStr, CString};
43 use std::cell::{Cell, RefCell};
44 use std::marker::PhantomData;
45 use std::ptr;
46 use std::rc::Rc;
47 use std::str;
48 use syntax::ast;
49 use syntax::parse::token::InternedString;
50 use abi::FnType;
51
52 pub struct Stats {
53     pub n_glues_created: Cell<usize>,
54     pub n_null_glues: Cell<usize>,
55     pub n_real_glues: Cell<usize>,
56     pub n_fallback_instantiations: Cell<usize>,
57     pub n_fns: Cell<usize>,
58     pub n_monos: Cell<usize>,
59     pub n_inlines: Cell<usize>,
60     pub n_closures: Cell<usize>,
61     pub n_llvm_insns: Cell<usize>,
62     pub llvm_insns: RefCell<FnvHashMap<String, usize>>,
63     // (ident, llvm-instructions)
64     pub fn_stats: RefCell<Vec<(String, usize)> >,
65 }
66
67 /// The shared portion of a `CrateContext`.  There is one `SharedCrateContext`
68 /// per crate.  The data here is shared between all compilation units of the
69 /// crate, so it must not contain references to any LLVM data structures
70 /// (aside from metadata-related ones).
71 pub struct SharedCrateContext<'a, 'tcx: 'a> {
72     metadata_llmod: ModuleRef,
73     metadata_llcx: ContextRef,
74
75     export_map: ExportMap,
76     reachable: NodeSet,
77     link_meta: LinkMeta,
78     symbol_hasher: RefCell<Sha256>,
79     tcx: TyCtxt<'a, 'tcx, 'tcx>,
80     stats: Stats,
81     check_overflow: bool,
82     check_drop_flag_for_sanity: bool,
83     mir_map: &'a MirMap<'tcx>,
84     mir_cache: RefCell<DefIdMap<Rc<mir::Mir<'tcx>>>>,
85
86     use_dll_storage_attrs: bool,
87
88     translation_items: RefCell<FnvHashSet<TransItem<'tcx>>>,
89     trait_cache: RefCell<DepTrackingMap<TraitSelectionCache<'tcx>>>,
90 }
91
92 /// The local portion of a `CrateContext`.  There is one `LocalCrateContext`
93 /// per compilation unit.  Each one has its own LLVM `ContextRef` so that
94 /// several compilation units may be optimized in parallel.  All other LLVM
95 /// data structures in the `LocalCrateContext` are tied to that `ContextRef`.
96 pub struct LocalCrateContext<'tcx> {
97     llmod: ModuleRef,
98     llcx: ContextRef,
99     previous_work_product: Option<WorkProduct>,
100     tn: TypeNames, // FIXME: This seems to be largely unused.
101     codegen_unit: CodegenUnit<'tcx>,
102     needs_unwind_cleanup_cache: RefCell<FnvHashMap<Ty<'tcx>, bool>>,
103     fn_pointer_shims: RefCell<FnvHashMap<Ty<'tcx>, ValueRef>>,
104     drop_glues: RefCell<FnvHashMap<DropGlueKind<'tcx>, (ValueRef, FnType)>>,
105     /// Track mapping of external ids to local items imported for inlining
106     external: RefCell<DefIdMap<Option<ast::NodeId>>>,
107     /// Backwards version of the `external` map (inlined items to where they
108     /// came from)
109     external_srcs: RefCell<NodeMap<DefId>>,
110     /// Cache instances of monomorphic and polymorphic items
111     instances: RefCell<FnvHashMap<Instance<'tcx>, ValueRef>>,
112     monomorphizing: RefCell<DefIdMap<usize>>,
113     /// Cache generated vtables
114     vtables: RefCell<FnvHashMap<ty::PolyTraitRef<'tcx>, ValueRef>>,
115     /// Cache of constant strings,
116     const_cstr_cache: RefCell<FnvHashMap<InternedString, ValueRef>>,
117
118     /// Reverse-direction for const ptrs cast from globals.
119     /// Key is a ValueRef holding a *T,
120     /// Val is a ValueRef holding a *[T].
121     ///
122     /// Needed because LLVM loses pointer->pointee association
123     /// when we ptrcast, and we have to ptrcast during translation
124     /// of a [T] const because we form a slice, a (*T,usize) pair, not
125     /// a pointer to an LLVM array type. Similar for trait objects.
126     const_unsized: RefCell<FnvHashMap<ValueRef, ValueRef>>,
127
128     /// Cache of emitted const globals (value -> global)
129     const_globals: RefCell<FnvHashMap<ValueRef, ValueRef>>,
130
131     /// Cache of emitted const values
132     const_values: RefCell<FnvHashMap<(ast::NodeId, &'tcx Substs<'tcx>), ValueRef>>,
133
134     /// Cache of external const values
135     extern_const_values: RefCell<DefIdMap<ValueRef>>,
136
137     /// Mapping from static definitions to their DefId's.
138     statics: RefCell<FnvHashMap<ValueRef, DefId>>,
139
140     impl_method_cache: RefCell<FnvHashMap<(DefId, ast::Name), DefId>>,
141
142     /// Cache of closure wrappers for bare fn's.
143     closure_bare_wrapper_cache: RefCell<FnvHashMap<ValueRef, ValueRef>>,
144
145     /// List of globals for static variables which need to be passed to the
146     /// LLVM function ReplaceAllUsesWith (RAUW) when translation is complete.
147     /// (We have to make sure we don't invalidate any ValueRefs referring
148     /// to constants.)
149     statics_to_rauw: RefCell<Vec<(ValueRef, ValueRef)>>,
150
151     lltypes: RefCell<FnvHashMap<Ty<'tcx>, Type>>,
152     llsizingtypes: RefCell<FnvHashMap<Ty<'tcx>, Type>>,
153     adt_reprs: RefCell<FnvHashMap<Ty<'tcx>, Rc<adt::Repr<'tcx>>>>,
154     type_hashcodes: RefCell<FnvHashMap<Ty<'tcx>, String>>,
155     int_type: Type,
156     opaque_vec_type: Type,
157     builder: BuilderRef_res,
158
159     /// Holds the LLVM values for closure IDs.
160     closure_vals: RefCell<FnvHashMap<Instance<'tcx>, ValueRef>>,
161
162     dbg_cx: Option<debuginfo::CrateDebugContext<'tcx>>,
163
164     eh_personality: Cell<Option<ValueRef>>,
165     eh_unwind_resume: Cell<Option<ValueRef>>,
166     rust_try_fn: Cell<Option<ValueRef>>,
167
168     intrinsics: RefCell<FnvHashMap<&'static str, ValueRef>>,
169
170     /// Number of LLVM instructions translated into this `LocalCrateContext`.
171     /// This is used to perform some basic load-balancing to keep all LLVM
172     /// contexts around the same size.
173     n_llvm_insns: Cell<usize>,
174
175     /// Depth of the current type-of computation - used to bail out
176     type_of_depth: Cell<usize>,
177
178     symbol_map: Rc<SymbolMap<'tcx>>,
179 }
180
181 // Implement DepTrackingMapConfig for `trait_cache`
182 pub struct TraitSelectionCache<'tcx> {
183     data: PhantomData<&'tcx ()>
184 }
185
186 impl<'tcx> DepTrackingMapConfig for TraitSelectionCache<'tcx> {
187     type Key = ty::PolyTraitRef<'tcx>;
188     type Value = traits::Vtable<'tcx, ()>;
189     fn to_dep_node(key: &ty::PolyTraitRef<'tcx>) -> DepNode<DefId> {
190         key.to_poly_trait_predicate().dep_node()
191     }
192 }
193
194 /// This list owns a number of LocalCrateContexts and binds them to their common
195 /// SharedCrateContext. This type just exists as a convenience, something to
196 /// pass around all LocalCrateContexts with and get an iterator over them.
197 pub struct CrateContextList<'a, 'tcx: 'a> {
198     shared: &'a SharedCrateContext<'a, 'tcx>,
199     local_ccxs: Vec<LocalCrateContext<'tcx>>,
200 }
201
202 impl<'a, 'tcx: 'a> CrateContextList<'a, 'tcx> {
203     pub fn new(shared_ccx: &'a SharedCrateContext<'a, 'tcx>,
204                codegen_units: Vec<CodegenUnit<'tcx>>,
205                previous_work_products: Vec<Option<WorkProduct>>,
206                symbol_map: Rc<SymbolMap<'tcx>>)
207                -> CrateContextList<'a, 'tcx> {
208         CrateContextList {
209             shared: shared_ccx,
210             local_ccxs: codegen_units.into_iter().zip(previous_work_products).map(|(cgu, wp)| {
211                 LocalCrateContext::new(shared_ccx, cgu, wp, symbol_map.clone())
212             }).collect()
213         }
214     }
215
216     /// Iterate over all crate contexts, whether or not they need
217     /// translation.  That is, whether or not a `.o` file is available
218     /// for re-use from a previous incr. comp.).
219     pub fn iter_all<'b>(&'b self) -> CrateContextIterator<'b, 'tcx> {
220         CrateContextIterator {
221             shared: self.shared,
222             index: 0,
223             local_ccxs: &self.local_ccxs[..],
224             filter_to_previous_work_product_unavail: false,
225         }
226     }
227
228     /// Iterator over all CCX that need translation (cannot reuse results from
229     /// previous incr. comp.).
230     pub fn iter_need_trans<'b>(&'b self) -> CrateContextIterator<'b, 'tcx> {
231         CrateContextIterator {
232             shared: self.shared,
233             index: 0,
234             local_ccxs: &self.local_ccxs[..],
235             filter_to_previous_work_product_unavail: true,
236         }
237     }
238
239     pub fn shared(&self) -> &'a SharedCrateContext<'a, 'tcx> {
240         self.shared
241     }
242 }
243
244 /// A CrateContext value binds together one LocalCrateContext with the
245 /// SharedCrateContext. It exists as a convenience wrapper, so we don't have to
246 /// pass around (SharedCrateContext, LocalCrateContext) tuples all over trans.
247 pub struct CrateContext<'a, 'tcx: 'a> {
248     shared: &'a SharedCrateContext<'a, 'tcx>,
249     local_ccxs: &'a [LocalCrateContext<'tcx>],
250     /// The index of `local` in `local_ccxs`.  This is used in
251     /// `maybe_iter(true)` to identify the original `LocalCrateContext`.
252     index: usize,
253 }
254
255 pub struct CrateContextIterator<'a, 'tcx: 'a> {
256     shared: &'a SharedCrateContext<'a, 'tcx>,
257     local_ccxs: &'a [LocalCrateContext<'tcx>],
258     index: usize,
259
260     /// if true, only return results where `previous_work_product` is none
261     filter_to_previous_work_product_unavail: bool,
262 }
263
264 impl<'a, 'tcx> Iterator for CrateContextIterator<'a,'tcx> {
265     type Item = CrateContext<'a, 'tcx>;
266
267     fn next(&mut self) -> Option<CrateContext<'a, 'tcx>> {
268         loop {
269             if self.index >= self.local_ccxs.len() {
270                 return None;
271             }
272
273             let index = self.index;
274             self.index += 1;
275
276             let ccx = CrateContext {
277                 shared: self.shared,
278                 index: index,
279                 local_ccxs: self.local_ccxs,
280             };
281
282             if
283                 self.filter_to_previous_work_product_unavail &&
284                 ccx.previous_work_product().is_some()
285             {
286                 continue;
287             }
288
289             return Some(ccx);
290         }
291     }
292 }
293
294 /// The iterator produced by `CrateContext::maybe_iter`.
295 pub struct CrateContextMaybeIterator<'a, 'tcx: 'a> {
296     shared: &'a SharedCrateContext<'a, 'tcx>,
297     local_ccxs: &'a [LocalCrateContext<'tcx>],
298     index: usize,
299     single: bool,
300     origin: usize,
301 }
302
303 impl<'a, 'tcx> Iterator for CrateContextMaybeIterator<'a, 'tcx> {
304     type Item = (CrateContext<'a, 'tcx>, bool);
305
306     fn next(&mut self) -> Option<(CrateContext<'a, 'tcx>, bool)> {
307         if self.index >= self.local_ccxs.len() {
308             return None;
309         }
310
311         let index = self.index;
312         self.index += 1;
313         if self.single {
314             self.index = self.local_ccxs.len();
315         }
316
317         let ccx = CrateContext {
318             shared: self.shared,
319             index: index,
320             local_ccxs: self.local_ccxs
321         };
322         Some((ccx, index == self.origin))
323     }
324 }
325
326 pub fn get_reloc_model(sess: &Session) -> llvm::RelocMode {
327     let reloc_model_arg = match sess.opts.cg.relocation_model {
328         Some(ref s) => &s[..],
329         None => &sess.target.target.options.relocation_model[..],
330     };
331
332     match reloc_model_arg {
333         "pic" => llvm::RelocPIC,
334         "static" => llvm::RelocStatic,
335         "default" => llvm::RelocDefault,
336         "dynamic-no-pic" => llvm::RelocDynamicNoPic,
337         _ => {
338             sess.err(&format!("{:?} is not a valid relocation mode",
339                              sess.opts
340                                  .cg
341                                  .relocation_model));
342             sess.abort_if_errors();
343             bug!();
344         }
345     }
346 }
347
348 fn is_any_library(sess: &Session) -> bool {
349     sess.crate_types.borrow().iter().any(|ty| {
350         *ty != config::CrateTypeExecutable
351     })
352 }
353
354 pub fn is_pie_binary(sess: &Session) -> bool {
355     !is_any_library(sess) && get_reloc_model(sess) == llvm::RelocPIC
356 }
357
358 unsafe fn create_context_and_module(sess: &Session, mod_name: &str) -> (ContextRef, ModuleRef) {
359     let llcx = llvm::LLVMContextCreate();
360     let mod_name = CString::new(mod_name).unwrap();
361     let llmod = llvm::LLVMModuleCreateWithNameInContext(mod_name.as_ptr(), llcx);
362
363     // Ensure the data-layout values hardcoded remain the defaults.
364     if sess.target.target.options.is_builtin {
365         let tm = ::back::write::create_target_machine(sess);
366         llvm::LLVMRustSetDataLayoutFromTargetMachine(llmod, tm);
367         llvm::LLVMRustDisposeTargetMachine(tm);
368
369         let data_layout = llvm::LLVMGetDataLayout(llmod);
370         let data_layout = str::from_utf8(CStr::from_ptr(data_layout).to_bytes())
371             .ok().expect("got a non-UTF8 data-layout from LLVM");
372
373         if sess.target.target.data_layout != data_layout {
374             bug!("data-layout for builtin `{}` target, `{}`, \
375                   differs from LLVM default, `{}`",
376                  sess.target.target.llvm_target,
377                  sess.target.target.data_layout,
378                  data_layout);
379         }
380     }
381
382     let data_layout = CString::new(&sess.target.target.data_layout[..]).unwrap();
383     llvm::LLVMSetDataLayout(llmod, data_layout.as_ptr());
384
385     let llvm_target = sess.target.target.llvm_target.as_bytes();
386     let llvm_target = CString::new(llvm_target).unwrap();
387     llvm::LLVMRustSetNormalizedTarget(llmod, llvm_target.as_ptr());
388
389     if is_pie_binary(sess) {
390         llvm::LLVMRustSetModulePIELevel(llmod);
391     }
392
393     (llcx, llmod)
394 }
395
396 impl<'b, 'tcx> SharedCrateContext<'b, 'tcx> {
397     pub fn new(tcx: TyCtxt<'b, 'tcx, 'tcx>,
398                mir_map: &'b MirMap<'tcx>,
399                export_map: ExportMap,
400                symbol_hasher: Sha256,
401                link_meta: LinkMeta,
402                reachable: NodeSet,
403                check_overflow: bool,
404                check_drop_flag_for_sanity: bool)
405                -> SharedCrateContext<'b, 'tcx> {
406         let (metadata_llcx, metadata_llmod) = unsafe {
407             create_context_and_module(&tcx.sess, "metadata")
408         };
409
410         // An interesting part of Windows which MSVC forces our hand on (and
411         // apparently MinGW didn't) is the usage of `dllimport` and `dllexport`
412         // attributes in LLVM IR as well as native dependencies (in C these
413         // correspond to `__declspec(dllimport)`).
414         //
415         // Whenever a dynamic library is built by MSVC it must have its public
416         // interface specified by functions tagged with `dllexport` or otherwise
417         // they're not available to be linked against. This poses a few problems
418         // for the compiler, some of which are somewhat fundamental, but we use
419         // the `use_dll_storage_attrs` variable below to attach the `dllexport`
420         // attribute to all LLVM functions that are reachable (e.g. they're
421         // already tagged with external linkage). This is suboptimal for a few
422         // reasons:
423         //
424         // * If an object file will never be included in a dynamic library,
425         //   there's no need to attach the dllexport attribute. Most object
426         //   files in Rust are not destined to become part of a dll as binaries
427         //   are statically linked by default.
428         // * If the compiler is emitting both an rlib and a dylib, the same
429         //   source object file is currently used but with MSVC this may be less
430         //   feasible. The compiler may be able to get around this, but it may
431         //   involve some invasive changes to deal with this.
432         //
433         // The flipside of this situation is that whenever you link to a dll and
434         // you import a function from it, the import should be tagged with
435         // `dllimport`. At this time, however, the compiler does not emit
436         // `dllimport` for any declarations other than constants (where it is
437         // required), which is again suboptimal for even more reasons!
438         //
439         // * Calling a function imported from another dll without using
440         //   `dllimport` causes the linker/compiler to have extra overhead (one
441         //   `jmp` instruction on x86) when calling the function.
442         // * The same object file may be used in different circumstances, so a
443         //   function may be imported from a dll if the object is linked into a
444         //   dll, but it may be just linked against if linked into an rlib.
445         // * The compiler has no knowledge about whether native functions should
446         //   be tagged dllimport or not.
447         //
448         // For now the compiler takes the perf hit (I do not have any numbers to
449         // this effect) by marking very little as `dllimport` and praying the
450         // linker will take care of everything. Fixing this problem will likely
451         // require adding a few attributes to Rust itself (feature gated at the
452         // start) and then strongly recommending static linkage on MSVC!
453         let use_dll_storage_attrs = tcx.sess.target.target.options.is_like_msvc;
454
455         SharedCrateContext {
456             metadata_llmod: metadata_llmod,
457             metadata_llcx: metadata_llcx,
458             export_map: export_map,
459             reachable: reachable,
460             link_meta: link_meta,
461             symbol_hasher: RefCell::new(symbol_hasher),
462             tcx: tcx,
463             mir_map: mir_map,
464             mir_cache: RefCell::new(DefIdMap()),
465             stats: Stats {
466                 n_glues_created: Cell::new(0),
467                 n_null_glues: Cell::new(0),
468                 n_real_glues: Cell::new(0),
469                 n_fallback_instantiations: Cell::new(0),
470                 n_fns: Cell::new(0),
471                 n_monos: Cell::new(0),
472                 n_inlines: Cell::new(0),
473                 n_closures: Cell::new(0),
474                 n_llvm_insns: Cell::new(0),
475                 llvm_insns: RefCell::new(FnvHashMap()),
476                 fn_stats: RefCell::new(Vec::new()),
477             },
478             check_overflow: check_overflow,
479             check_drop_flag_for_sanity: check_drop_flag_for_sanity,
480             use_dll_storage_attrs: use_dll_storage_attrs,
481             translation_items: RefCell::new(FnvHashSet()),
482             trait_cache: RefCell::new(DepTrackingMap::new(tcx.dep_graph.clone())),
483         }
484     }
485
486     pub fn metadata_llmod(&self) -> ModuleRef {
487         self.metadata_llmod
488     }
489
490     pub fn metadata_llcx(&self) -> ContextRef {
491         self.metadata_llcx
492     }
493
494     pub fn export_map<'a>(&'a self) -> &'a ExportMap {
495         &self.export_map
496     }
497
498     pub fn reachable<'a>(&'a self) -> &'a NodeSet {
499         &self.reachable
500     }
501
502     pub fn trait_cache(&self) -> &RefCell<DepTrackingMap<TraitSelectionCache<'tcx>>> {
503         &self.trait_cache
504     }
505
506     pub fn link_meta<'a>(&'a self) -> &'a LinkMeta {
507         &self.link_meta
508     }
509
510     pub fn tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> {
511         self.tcx
512     }
513
514     pub fn sess<'a>(&'a self) -> &'a Session {
515         &self.tcx.sess
516     }
517
518     pub fn stats<'a>(&'a self) -> &'a Stats {
519         &self.stats
520     }
521
522     pub fn use_dll_storage_attrs(&self) -> bool {
523         self.use_dll_storage_attrs
524     }
525
526     pub fn get_mir(&self, def_id: DefId) -> Option<CachedMir<'b, 'tcx>> {
527         if def_id.is_local() {
528             let node_id = self.tcx.map.as_local_node_id(def_id).unwrap();
529             self.mir_map.map.get(&node_id).map(CachedMir::Ref)
530         } else {
531             if let Some(mir) = self.mir_cache.borrow().get(&def_id).cloned() {
532                 return Some(CachedMir::Owned(mir));
533             }
534
535             let mir = self.sess().cstore.maybe_get_item_mir(self.tcx, def_id);
536             let cached = mir.map(Rc::new);
537             if let Some(ref mir) = cached {
538                 self.mir_cache.borrow_mut().insert(def_id, mir.clone());
539             }
540             cached.map(CachedMir::Owned)
541         }
542     }
543
544     pub fn translation_items(&self) -> &RefCell<FnvHashSet<TransItem<'tcx>>> {
545         &self.translation_items
546     }
547
548     /// Given the def-id of some item that has no type parameters, make
549     /// a suitable "empty substs" for it.
550     pub fn empty_substs_for_def_id(&self, item_def_id: DefId) -> &'tcx Substs<'tcx> {
551         let scheme = self.tcx().lookup_item_type(item_def_id);
552         self.empty_substs_for_scheme(&scheme)
553     }
554
555     pub fn empty_substs_for_scheme(&self, scheme: &ty::TypeScheme<'tcx>)
556                                    -> &'tcx Substs<'tcx> {
557         assert!(scheme.generics.types.is_empty());
558         self.tcx().mk_substs(
559             Substs::new(VecPerParamSpace::empty(),
560                         scheme.generics.regions.map(|_| ty::ReErased)))
561     }
562
563     pub fn symbol_hasher(&self) -> &RefCell<Sha256> {
564         &self.symbol_hasher
565     }
566
567     pub fn mir_map(&self) -> &MirMap<'tcx> {
568         &self.mir_map
569     }
570
571     pub fn metadata_symbol_name(&self) -> String {
572         format!("rust_metadata_{}_{}",
573                 self.link_meta().crate_name,
574                 self.link_meta().crate_hash)
575     }
576 }
577
578 impl<'tcx> LocalCrateContext<'tcx> {
579     fn new<'a>(shared: &SharedCrateContext<'a, 'tcx>,
580                codegen_unit: CodegenUnit<'tcx>,
581                previous_work_product: Option<WorkProduct>,
582                symbol_map: Rc<SymbolMap<'tcx>>)
583            -> LocalCrateContext<'tcx> {
584         unsafe {
585             // Append ".rs" to LLVM module identifier.
586             //
587             // LLVM code generator emits a ".file filename" directive
588             // for ELF backends. Value of the "filename" is set as the
589             // LLVM module identifier.  Due to a LLVM MC bug[1], LLVM
590             // crashes if the module identifier is same as other symbols
591             // such as a function name in the module.
592             // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
593             let llmod_id = format!("{}.rs", codegen_unit.name());
594
595             let (llcx, llmod) = create_context_and_module(&shared.tcx.sess,
596                                                           &llmod_id[..]);
597
598             let dbg_cx = if shared.tcx.sess.opts.debuginfo != NoDebugInfo {
599                 let dctx = debuginfo::CrateDebugContext::new(llmod);
600                 debuginfo::metadata::compile_unit_metadata(shared, &dctx, shared.tcx.sess);
601                 Some(dctx)
602             } else {
603                 None
604             };
605
606             let local_ccx = LocalCrateContext {
607                 llmod: llmod,
608                 llcx: llcx,
609                 previous_work_product: previous_work_product,
610                 codegen_unit: codegen_unit,
611                 tn: TypeNames::new(),
612                 needs_unwind_cleanup_cache: RefCell::new(FnvHashMap()),
613                 fn_pointer_shims: RefCell::new(FnvHashMap()),
614                 drop_glues: RefCell::new(FnvHashMap()),
615                 external: RefCell::new(DefIdMap()),
616                 external_srcs: RefCell::new(NodeMap()),
617                 instances: RefCell::new(FnvHashMap()),
618                 monomorphizing: RefCell::new(DefIdMap()),
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                 adt_reprs: RefCell::new(FnvHashMap()),
632                 type_hashcodes: RefCell::new(FnvHashMap()),
633                 int_type: Type::from_ref(ptr::null_mut()),
634                 opaque_vec_type: Type::from_ref(ptr::null_mut()),
635                 builder: BuilderRef_res(llvm::LLVMCreateBuilderInContext(llcx)),
636                 closure_vals: RefCell::new(FnvHashMap()),
637                 dbg_cx: dbg_cx,
638                 eh_personality: Cell::new(None),
639                 eh_unwind_resume: Cell::new(None),
640                 rust_try_fn: Cell::new(None),
641                 intrinsics: RefCell::new(FnvHashMap()),
642                 n_llvm_insns: Cell::new(0),
643                 type_of_depth: Cell::new(0),
644                 symbol_map: symbol_map,
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 external<'a>(&'a self) -> &'a RefCell<DefIdMap<Option<ast::NodeId>>> {
811         &self.local().external
812     }
813
814     pub fn external_srcs<'a>(&'a self) -> &'a RefCell<NodeMap<DefId>> {
815         &self.local().external_srcs
816     }
817
818     pub fn instances<'a>(&'a self) -> &'a RefCell<FnvHashMap<Instance<'tcx>, ValueRef>> {
819         &self.local().instances
820     }
821
822     pub fn monomorphizing<'a>(&'a self) -> &'a RefCell<DefIdMap<usize>> {
823         &self.local().monomorphizing
824     }
825
826     pub fn vtables<'a>(&'a self) -> &'a RefCell<FnvHashMap<ty::PolyTraitRef<'tcx>, ValueRef>> {
827         &self.local().vtables
828     }
829
830     pub fn const_cstr_cache<'a>(&'a self) -> &'a RefCell<FnvHashMap<InternedString, ValueRef>> {
831         &self.local().const_cstr_cache
832     }
833
834     pub fn const_unsized<'a>(&'a self) -> &'a RefCell<FnvHashMap<ValueRef, ValueRef>> {
835         &self.local().const_unsized
836     }
837
838     pub fn const_globals<'a>(&'a self) -> &'a RefCell<FnvHashMap<ValueRef, ValueRef>> {
839         &self.local().const_globals
840     }
841
842     pub fn const_values<'a>(&'a self) -> &'a RefCell<FnvHashMap<(ast::NodeId, &'tcx Substs<'tcx>),
843                                                                 ValueRef>> {
844         &self.local().const_values
845     }
846
847     pub fn extern_const_values<'a>(&'a self) -> &'a RefCell<DefIdMap<ValueRef>> {
848         &self.local().extern_const_values
849     }
850
851     pub fn statics<'a>(&'a self) -> &'a RefCell<FnvHashMap<ValueRef, DefId>> {
852         &self.local().statics
853     }
854
855     pub fn impl_method_cache<'a>(&'a self)
856             -> &'a RefCell<FnvHashMap<(DefId, ast::Name), DefId>> {
857         &self.local().impl_method_cache
858     }
859
860     pub fn closure_bare_wrapper_cache<'a>(&'a self) -> &'a RefCell<FnvHashMap<ValueRef, ValueRef>> {
861         &self.local().closure_bare_wrapper_cache
862     }
863
864     pub fn statics_to_rauw<'a>(&'a self) -> &'a RefCell<Vec<(ValueRef, ValueRef)>> {
865         &self.local().statics_to_rauw
866     }
867
868     pub fn lltypes<'a>(&'a self) -> &'a RefCell<FnvHashMap<Ty<'tcx>, Type>> {
869         &self.local().lltypes
870     }
871
872     pub fn llsizingtypes<'a>(&'a self) -> &'a RefCell<FnvHashMap<Ty<'tcx>, Type>> {
873         &self.local().llsizingtypes
874     }
875
876     pub fn adt_reprs<'a>(&'a self) -> &'a RefCell<FnvHashMap<Ty<'tcx>, Rc<adt::Repr<'tcx>>>> {
877         &self.local().adt_reprs
878     }
879
880     pub fn symbol_hasher<'a>(&'a self) -> &'a RefCell<Sha256> {
881         &self.shared.symbol_hasher
882     }
883
884     pub fn type_hashcodes<'a>(&'a self) -> &'a RefCell<FnvHashMap<Ty<'tcx>, String>> {
885         &self.local().type_hashcodes
886     }
887
888     pub fn stats<'a>(&'a self) -> &'a Stats {
889         &self.shared.stats
890     }
891
892     pub fn int_type(&self) -> Type {
893         self.local().int_type
894     }
895
896     pub fn opaque_vec_type(&self) -> Type {
897         self.local().opaque_vec_type
898     }
899
900     pub fn closure_vals<'a>(&'a self) -> &'a RefCell<FnvHashMap<Instance<'tcx>, ValueRef>> {
901         &self.local().closure_vals
902     }
903
904     pub fn dbg_cx<'a>(&'a self) -> &'a Option<debuginfo::CrateDebugContext<'tcx>> {
905         &self.local().dbg_cx
906     }
907
908     pub fn eh_personality<'a>(&'a self) -> &'a Cell<Option<ValueRef>> {
909         &self.local().eh_personality
910     }
911
912     pub fn eh_unwind_resume<'a>(&'a self) -> &'a Cell<Option<ValueRef>> {
913         &self.local().eh_unwind_resume
914     }
915
916     pub fn rust_try_fn<'a>(&'a self) -> &'a Cell<Option<ValueRef>> {
917         &self.local().rust_try_fn
918     }
919
920     fn intrinsics<'a>(&'a self) -> &'a RefCell<FnvHashMap<&'static str, ValueRef>> {
921         &self.local().intrinsics
922     }
923
924     pub fn count_llvm_insn(&self) {
925         self.local().n_llvm_insns.set(self.local().n_llvm_insns.get() + 1);
926     }
927
928     pub fn obj_size_bound(&self) -> u64 {
929         self.tcx().data_layout.obj_size_bound()
930     }
931
932     pub fn report_overbig_object(&self, obj: Ty<'tcx>) -> ! {
933         self.sess().fatal(
934             &format!("the type `{:?}` is too big for the current architecture",
935                     obj))
936     }
937
938     pub fn enter_type_of(&self, ty: Ty<'tcx>) -> TypeOfDepthLock<'b, 'tcx> {
939         let current_depth = self.local().type_of_depth.get();
940         debug!("enter_type_of({:?}) at depth {:?}", ty, current_depth);
941         if current_depth > self.sess().recursion_limit.get() {
942             self.sess().fatal(
943                 &format!("overflow representing the type `{}`", ty))
944         }
945         self.local().type_of_depth.set(current_depth + 1);
946         TypeOfDepthLock(self.local())
947     }
948
949     pub fn check_overflow(&self) -> bool {
950         self.shared.check_overflow
951     }
952
953     pub fn check_drop_flag_for_sanity(&self) -> bool {
954         // This controls whether we emit a conditional llvm.debugtrap
955         // guarded on whether the dropflag is one of its (two) valid
956         // values.
957         self.shared.check_drop_flag_for_sanity
958     }
959
960     pub fn use_dll_storage_attrs(&self) -> bool {
961         self.shared.use_dll_storage_attrs()
962     }
963
964     pub fn get_mir(&self, def_id: DefId) -> Option<CachedMir<'b, 'tcx>> {
965         self.shared.get_mir(def_id)
966     }
967
968     pub fn symbol_map(&self) -> &SymbolMap<'tcx> {
969         &*self.local().symbol_map
970     }
971
972     pub fn translation_items(&self) -> &RefCell<FnvHashSet<TransItem<'tcx>>> {
973         &self.shared.translation_items
974     }
975
976     /// Given the def-id of some item that has no type parameters, make
977     /// a suitable "empty substs" for it.
978     pub fn empty_substs_for_def_id(&self, item_def_id: DefId) -> &'tcx Substs<'tcx> {
979         self.shared().empty_substs_for_def_id(item_def_id)
980     }
981
982     pub fn empty_substs_for_scheme(&self, scheme: &ty::TypeScheme<'tcx>)
983                                    -> &'tcx Substs<'tcx> {
984         self.shared().empty_substs_for_scheme(scheme)
985     }
986 }
987
988 pub struct TypeOfDepthLock<'a, 'tcx: 'a>(&'a LocalCrateContext<'tcx>);
989
990 impl<'a, 'tcx> Drop for TypeOfDepthLock<'a, 'tcx> {
991     fn drop(&mut self) {
992         self.0.type_of_depth.set(self.0.type_of_depth.get() - 1);
993     }
994 }
995
996 /// Declare any llvm intrinsics that you might need
997 fn declare_intrinsic(ccx: &CrateContext, key: &str) -> Option<ValueRef> {
998     macro_rules! ifn {
999         ($name:expr, fn() -> $ret:expr) => (
1000             if key == $name {
1001                 let f = declare::declare_cfn(ccx, $name, Type::func(&[], &$ret));
1002                 llvm::SetUnnamedAddr(f, false);
1003                 ccx.intrinsics().borrow_mut().insert($name, f.clone());
1004                 return Some(f);
1005             }
1006         );
1007         ($name:expr, fn(...) -> $ret:expr) => (
1008             if key == $name {
1009                 let f = declare::declare_cfn(ccx, $name, Type::variadic_func(&[], &$ret));
1010                 llvm::SetUnnamedAddr(f, false);
1011                 ccx.intrinsics().borrow_mut().insert($name, f.clone());
1012                 return Some(f);
1013             }
1014         );
1015         ($name:expr, fn($($arg:expr),*) -> $ret:expr) => (
1016             if key == $name {
1017                 let f = declare::declare_cfn(ccx, $name, Type::func(&[$($arg),*], &$ret));
1018                 llvm::SetUnnamedAddr(f, false);
1019                 ccx.intrinsics().borrow_mut().insert($name, f.clone());
1020                 return Some(f);
1021             }
1022         );
1023     }
1024     macro_rules! mk_struct {
1025         ($($field_ty:expr),*) => (Type::struct_(ccx, &[$($field_ty),*], false))
1026     }
1027
1028     let i8p = Type::i8p(ccx);
1029     let void = Type::void(ccx);
1030     let i1 = Type::i1(ccx);
1031     let t_i8 = Type::i8(ccx);
1032     let t_i16 = Type::i16(ccx);
1033     let t_i32 = Type::i32(ccx);
1034     let t_i64 = Type::i64(ccx);
1035     let t_f32 = Type::f32(ccx);
1036     let t_f64 = Type::f64(ccx);
1037
1038     ifn!("llvm.memcpy.p0i8.p0i8.i16", fn(i8p, i8p, t_i16, t_i32, i1) -> void);
1039     ifn!("llvm.memcpy.p0i8.p0i8.i32", fn(i8p, i8p, t_i32, t_i32, i1) -> void);
1040     ifn!("llvm.memcpy.p0i8.p0i8.i64", fn(i8p, i8p, t_i64, t_i32, i1) -> void);
1041     ifn!("llvm.memmove.p0i8.p0i8.i16", fn(i8p, i8p, t_i16, t_i32, i1) -> void);
1042     ifn!("llvm.memmove.p0i8.p0i8.i32", fn(i8p, i8p, t_i32, t_i32, i1) -> void);
1043     ifn!("llvm.memmove.p0i8.p0i8.i64", fn(i8p, i8p, t_i64, t_i32, i1) -> void);
1044     ifn!("llvm.memset.p0i8.i16", fn(i8p, t_i8, t_i16, t_i32, i1) -> void);
1045     ifn!("llvm.memset.p0i8.i32", fn(i8p, t_i8, t_i32, t_i32, i1) -> void);
1046     ifn!("llvm.memset.p0i8.i64", fn(i8p, t_i8, t_i64, t_i32, i1) -> void);
1047
1048     ifn!("llvm.trap", fn() -> void);
1049     ifn!("llvm.debugtrap", fn() -> void);
1050     ifn!("llvm.frameaddress", fn(t_i32) -> i8p);
1051
1052     ifn!("llvm.powi.f32", fn(t_f32, t_i32) -> t_f32);
1053     ifn!("llvm.powi.f64", fn(t_f64, t_i32) -> t_f64);
1054     ifn!("llvm.pow.f32", fn(t_f32, t_f32) -> t_f32);
1055     ifn!("llvm.pow.f64", fn(t_f64, t_f64) -> t_f64);
1056
1057     ifn!("llvm.sqrt.f32", fn(t_f32) -> t_f32);
1058     ifn!("llvm.sqrt.f64", fn(t_f64) -> t_f64);
1059     ifn!("llvm.sin.f32", fn(t_f32) -> t_f32);
1060     ifn!("llvm.sin.f64", fn(t_f64) -> t_f64);
1061     ifn!("llvm.cos.f32", fn(t_f32) -> t_f32);
1062     ifn!("llvm.cos.f64", fn(t_f64) -> t_f64);
1063     ifn!("llvm.exp.f32", fn(t_f32) -> t_f32);
1064     ifn!("llvm.exp.f64", fn(t_f64) -> t_f64);
1065     ifn!("llvm.exp2.f32", fn(t_f32) -> t_f32);
1066     ifn!("llvm.exp2.f64", fn(t_f64) -> t_f64);
1067     ifn!("llvm.log.f32", fn(t_f32) -> t_f32);
1068     ifn!("llvm.log.f64", fn(t_f64) -> t_f64);
1069     ifn!("llvm.log10.f32", fn(t_f32) -> t_f32);
1070     ifn!("llvm.log10.f64", fn(t_f64) -> t_f64);
1071     ifn!("llvm.log2.f32", fn(t_f32) -> t_f32);
1072     ifn!("llvm.log2.f64", fn(t_f64) -> t_f64);
1073
1074     ifn!("llvm.fma.f32", fn(t_f32, t_f32, t_f32) -> t_f32);
1075     ifn!("llvm.fma.f64", fn(t_f64, t_f64, t_f64) -> t_f64);
1076
1077     ifn!("llvm.fabs.f32", fn(t_f32) -> t_f32);
1078     ifn!("llvm.fabs.f64", fn(t_f64) -> t_f64);
1079
1080     ifn!("llvm.floor.f32", fn(t_f32) -> t_f32);
1081     ifn!("llvm.floor.f64", fn(t_f64) -> t_f64);
1082     ifn!("llvm.ceil.f32", fn(t_f32) -> t_f32);
1083     ifn!("llvm.ceil.f64", fn(t_f64) -> t_f64);
1084     ifn!("llvm.trunc.f32", fn(t_f32) -> t_f32);
1085     ifn!("llvm.trunc.f64", fn(t_f64) -> t_f64);
1086
1087     ifn!("llvm.copysign.f32", fn(t_f32, t_f32) -> t_f32);
1088     ifn!("llvm.copysign.f64", fn(t_f64, t_f64) -> t_f64);
1089     ifn!("llvm.round.f32", fn(t_f32) -> t_f32);
1090     ifn!("llvm.round.f64", fn(t_f64) -> t_f64);
1091
1092     ifn!("llvm.rint.f32", fn(t_f32) -> t_f32);
1093     ifn!("llvm.rint.f64", fn(t_f64) -> t_f64);
1094     ifn!("llvm.nearbyint.f32", fn(t_f32) -> t_f32);
1095     ifn!("llvm.nearbyint.f64", fn(t_f64) -> t_f64);
1096
1097     ifn!("llvm.ctpop.i8", fn(t_i8) -> t_i8);
1098     ifn!("llvm.ctpop.i16", fn(t_i16) -> t_i16);
1099     ifn!("llvm.ctpop.i32", fn(t_i32) -> t_i32);
1100     ifn!("llvm.ctpop.i64", fn(t_i64) -> t_i64);
1101
1102     ifn!("llvm.ctlz.i8", fn(t_i8 , i1) -> t_i8);
1103     ifn!("llvm.ctlz.i16", fn(t_i16, i1) -> t_i16);
1104     ifn!("llvm.ctlz.i32", fn(t_i32, i1) -> t_i32);
1105     ifn!("llvm.ctlz.i64", fn(t_i64, i1) -> t_i64);
1106
1107     ifn!("llvm.cttz.i8", fn(t_i8 , i1) -> t_i8);
1108     ifn!("llvm.cttz.i16", fn(t_i16, i1) -> t_i16);
1109     ifn!("llvm.cttz.i32", fn(t_i32, i1) -> t_i32);
1110     ifn!("llvm.cttz.i64", fn(t_i64, i1) -> t_i64);
1111
1112     ifn!("llvm.bswap.i16", fn(t_i16) -> t_i16);
1113     ifn!("llvm.bswap.i32", fn(t_i32) -> t_i32);
1114     ifn!("llvm.bswap.i64", fn(t_i64) -> t_i64);
1115
1116     ifn!("llvm.sadd.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
1117     ifn!("llvm.sadd.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
1118     ifn!("llvm.sadd.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
1119     ifn!("llvm.sadd.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
1120
1121     ifn!("llvm.uadd.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
1122     ifn!("llvm.uadd.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
1123     ifn!("llvm.uadd.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
1124     ifn!("llvm.uadd.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
1125
1126     ifn!("llvm.ssub.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
1127     ifn!("llvm.ssub.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
1128     ifn!("llvm.ssub.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
1129     ifn!("llvm.ssub.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
1130
1131     ifn!("llvm.usub.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
1132     ifn!("llvm.usub.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
1133     ifn!("llvm.usub.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
1134     ifn!("llvm.usub.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
1135
1136     ifn!("llvm.smul.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
1137     ifn!("llvm.smul.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
1138     ifn!("llvm.smul.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
1139     ifn!("llvm.smul.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
1140
1141     ifn!("llvm.umul.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
1142     ifn!("llvm.umul.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
1143     ifn!("llvm.umul.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
1144     ifn!("llvm.umul.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
1145
1146     ifn!("llvm.lifetime.start", fn(t_i64,i8p) -> void);
1147     ifn!("llvm.lifetime.end", fn(t_i64, i8p) -> void);
1148
1149     ifn!("llvm.expect.i1", fn(i1, i1) -> i1);
1150     ifn!("llvm.eh.typeid.for", fn(i8p) -> t_i32);
1151     ifn!("llvm.localescape", fn(...) -> void);
1152     ifn!("llvm.localrecover", fn(i8p, i8p, t_i32) -> i8p);
1153     ifn!("llvm.x86.seh.recoverfp", fn(i8p, i8p) -> i8p);
1154
1155     ifn!("llvm.assume", fn(i1) -> void);
1156
1157     if ccx.sess().opts.debuginfo != NoDebugInfo {
1158         ifn!("llvm.dbg.declare", fn(Type::metadata(ccx), Type::metadata(ccx)) -> void);
1159         ifn!("llvm.dbg.value", fn(Type::metadata(ccx), t_i64, Type::metadata(ccx)) -> void);
1160     }
1161     return None;
1162 }