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