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