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