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