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