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.
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.
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;
18 use rustc_mir::mir_map::MirMap;
21 use trans::builder::Builder;
22 use trans::common::{ExternMap,BuilderRef_res};
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;
32 use util::sha2::Sha256;
33 use util::nodemap::{NodeMap, NodeSet, DefIdMap, FnvHashMap, FnvHashSet};
35 use std::ffi::CString;
36 use std::cell::{Cell, RefCell};
37 use std::marker::PhantomData;
41 use syntax::parse::token::InternedString;
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)> >,
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>>,
64 metadata_llmod: ModuleRef,
65 metadata_llcx: ContextRef,
67 export_map: ExportMap,
69 item_symbols: RefCell<NodeMap<String>>,
71 symbol_hasher: RefCell<Sha256>,
72 tcx: &'a ty::ctxt<'tcx>,
75 check_drop_flag_for_sanity: bool,
76 mir_map: &'a MirMap<'tcx>,
78 available_drop_glues: RefCell<FnvHashMap<DropGlueKind<'tcx>, String>>,
79 use_dll_storage_attrs: bool,
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> {
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
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>>,
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].
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>>,
119 /// Cache of emitted const globals (value -> global)
120 const_globals: RefCell<FnvHashMap<ValueRef, ValueRef>>,
122 /// Cache of emitted const values
123 const_values: RefCell<FnvHashMap<(ast::NodeId, &'tcx Substs<'tcx>), ValueRef>>,
125 /// Cache of external const values
126 extern_const_values: RefCell<DefIdMap<ValueRef>>,
128 impl_method_cache: RefCell<FnvHashMap<(DefId, ast::Name), DefId>>,
130 /// Cache of closure wrappers for bare fn's.
131 closure_bare_wrapper_cache: RefCell<FnvHashMap<ValueRef, ValueRef>>,
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
137 statics_to_rauw: RefCell<Vec<(ValueRef, ValueRef)>>,
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>>,
144 opaque_vec_type: Type,
145 builder: BuilderRef_res,
147 /// Holds the LLVM values for closure IDs.
148 closure_vals: RefCell<FnvHashMap<MonoId<'tcx>, ValueRef>>,
150 dbg_cx: Option<debuginfo::CrateDebugContext<'tcx>>,
152 eh_personality: RefCell<Option<ValueRef>>,
153 eh_unwind_resume: RefCell<Option<ValueRef>>,
154 rust_try_fn: RefCell<Option<ValueRef>>,
156 intrinsics: RefCell<FnvHashMap<&'static str, ValueRef>>,
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>,
163 /// Depth of the current type-of computation - used to bail out
164 type_of_depth: Cell<usize>,
166 trait_cache: RefCell<DepTrackingMap<TraitSelectionCache<'tcx>>>,
169 // Implement DepTrackingMapConfig for `trait_cache`
170 pub struct TraitSelectionCache<'tcx> {
171 data: PhantomData<&'tcx ()>
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()
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`.
193 pub struct CrateContextIterator<'a, 'tcx: 'a> {
194 shared: &'a SharedCrateContext<'a, 'tcx>,
198 impl<'a, 'tcx> Iterator for CrateContextIterator<'a,'tcx> {
199 type Item = CrateContext<'a, 'tcx>;
201 fn next(&mut self) -> Option<CrateContext<'a, 'tcx>> {
202 if self.index >= self.shared.local_ccxs.len() {
206 let index = self.index;
211 local: &self.shared.local_ccxs[index],
217 /// The iterator produced by `CrateContext::maybe_iter`.
218 pub struct CrateContextMaybeIterator<'a, 'tcx: 'a> {
219 shared: &'a SharedCrateContext<'a, 'tcx>,
225 impl<'a, 'tcx> Iterator for CrateContextMaybeIterator<'a, 'tcx> {
226 type Item = (CrateContext<'a, 'tcx>, bool);
228 fn next(&mut self) -> Option<(CrateContext<'a, 'tcx>, bool)> {
229 if self.index >= self.shared.local_ccxs.len() {
233 let index = self.index;
236 self.index = self.shared.local_ccxs.len();
239 let ccx = CrateContext {
241 local: &self.shared.local_ccxs[index],
244 Some((ccx, index == self.origin))
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);
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());
258 let tm = ::back::write::create_target_machine(sess);
259 llvm::LLVMRustSetDataLayoutFromTargetMachine(llmod, tm);
260 llvm::LLVMRustDisposeTargetMachine(tm);
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());
269 impl<'b, 'tcx> SharedCrateContext<'b, 'tcx> {
270 pub fn new(crate_name: &str,
272 tcx: &'b ty::ctxt<'tcx>,
273 mir_map: &'b MirMap<'tcx>,
274 export_map: ExportMap,
275 symbol_hasher: Sha256,
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")
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)`).
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
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.
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!
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.
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;
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),
342 n_glues_created: Cell::new(0),
343 n_null_glues: Cell::new(0),
344 n_real_glues: 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()),
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,
359 for i in 0..local_count {
360 // Append ".rs" to crate name as LLVM module identifier.
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);
376 pub fn iter<'a>(&'a self) -> CrateContextIterator<'a, 'tcx> {
377 CrateContextIterator {
383 pub fn get_ccx<'a>(&'a self, index: usize) -> CrateContext<'a, 'tcx> {
386 local: &self.local_ccxs[index],
391 fn get_smallest_ccx<'a>(&'a self) -> CrateContext<'a, 'tcx> {
392 let (local_ccx, index) =
395 .zip(0..self.local_ccxs.len())
396 .min_by_key(|&(local_ccx, _idx)| local_ccx.n_llvm_insns.get())
406 pub fn metadata_llmod(&self) -> ModuleRef {
410 pub fn metadata_llcx(&self) -> ContextRef {
414 pub fn export_map<'a>(&'a self) -> &'a ExportMap {
418 pub fn reachable<'a>(&'a self) -> &'a NodeSet {
422 pub fn item_symbols<'a>(&'a self) -> &'a RefCell<NodeMap<String>> {
426 pub fn link_meta<'a>(&'a self) -> &'a LinkMeta {
430 pub fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> {
434 pub fn sess<'a>(&'a self) -> &'a Session {
438 pub fn stats<'a>(&'a self) -> &'a Stats {
442 pub fn use_dll_storage_attrs(&self) -> bool {
443 self.use_dll_storage_attrs
447 impl<'tcx> LocalCrateContext<'tcx> {
448 fn new<'a>(shared: &SharedCrateContext<'a, 'tcx>,
450 -> LocalCrateContext<'tcx> {
452 let (llcx, llmod) = create_context_and_module(&shared.tcx.sess, name);
454 let dbg_cx = if shared.tcx.sess.opts.debuginfo != NoDebugInfo {
455 Some(debuginfo::CrateDebugContext::new(llmod))
460 let mut local_ccx = LocalCrateContext {
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()),
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
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));
506 // Done mutating local_ccx directly. (The rest of the
507 // initialization goes through RefCell.)
509 let ccx = local_ccx.dummy_ccx(shared);
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);
515 if ccx.sess().count_llvm_insns() {
516 base::init_insn_ctxt()
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.
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> {
542 impl<'b, 'tcx> CrateContext<'b, 'tcx> {
543 pub fn shared(&self) -> &'b SharedCrateContext<'b, 'tcx> {
547 pub fn local(&self) -> &'b LocalCrateContext<'tcx> {
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()
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
564 pub fn maybe_iter(&self, iter_all: bool) -> CrateContextMaybeIterator<'b, 'tcx> {
565 CrateContextMaybeIterator {
567 index: if iter_all { 0 } else { self.index },
574 pub fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> {
578 pub fn sess<'a>(&'a self) -> &'a Session {
579 &self.shared.tcx.sess
582 pub fn builder<'a>(&'a self) -> Builder<'a, 'tcx> {
586 pub fn raw_builder<'a>(&'a self) -> BuilderRef {
590 pub fn get_intrinsic(&self, key: &str) -> ValueRef {
591 if let Some(v) = self.intrinsics().borrow().get(key).cloned() {
594 match declare_intrinsic(self, key) {
596 None => panic!("unknown intrinsic '{}'", key)
600 pub fn llmod(&self) -> ModuleRef {
604 pub fn llcx(&self) -> ContextRef {
608 pub fn td(&self) -> llvm::TargetDataRef {
609 unsafe { llvm::LLVMRustGetModuleDataLayout(self.llmod()) }
612 pub fn tn<'a>(&'a self) -> &'a TypeNames {
616 pub fn externs<'a>(&'a self) -> &'a RefCell<ExternMap> {
620 pub fn item_vals<'a>(&'a self) -> &'a RefCell<NodeMap<ValueRef>> {
621 &self.local.item_vals
624 pub fn export_map<'a>(&'a self) -> &'a ExportMap {
625 &self.shared.export_map
628 pub fn reachable<'a>(&'a self) -> &'a NodeSet {
629 &self.shared.reachable
632 pub fn item_symbols<'a>(&'a self) -> &'a RefCell<NodeMap<String>> {
633 &self.shared.item_symbols
636 pub fn link_meta<'a>(&'a self) -> &'a LinkMeta {
637 &self.shared.link_meta
640 pub fn needs_unwind_cleanup_cache(&self) -> &RefCell<FnvHashMap<Ty<'tcx>, bool>> {
641 &self.local.needs_unwind_cleanup_cache
644 pub fn fn_pointer_shims(&self) -> &RefCell<FnvHashMap<Ty<'tcx>, ValueRef>> {
645 &self.local.fn_pointer_shims
648 pub fn drop_glues<'a>(&'a self) -> &'a RefCell<FnvHashMap<DropGlueKind<'tcx>, ValueRef>> {
649 &self.local.drop_glues
652 pub fn external<'a>(&'a self) -> &'a RefCell<DefIdMap<Option<ast::NodeId>>> {
656 pub fn external_srcs<'a>(&'a self) -> &'a RefCell<NodeMap<DefId>> {
657 &self.local.external_srcs
660 pub fn monomorphized<'a>(&'a self) -> &'a RefCell<FnvHashMap<MonoId<'tcx>, ValueRef>> {
661 &self.local.monomorphized
664 pub fn monomorphizing<'a>(&'a self) -> &'a RefCell<DefIdMap<usize>> {
665 &self.local.monomorphizing
668 pub fn vtables<'a>(&'a self) -> &'a RefCell<FnvHashMap<ty::PolyTraitRef<'tcx>, ValueRef>> {
672 pub fn const_cstr_cache<'a>(&'a self) -> &'a RefCell<FnvHashMap<InternedString, ValueRef>> {
673 &self.local.const_cstr_cache
676 pub fn const_unsized<'a>(&'a self) -> &'a RefCell<FnvHashMap<ValueRef, ValueRef>> {
677 &self.local.const_unsized
680 pub fn const_globals<'a>(&'a self) -> &'a RefCell<FnvHashMap<ValueRef, ValueRef>> {
681 &self.local.const_globals
684 pub fn const_values<'a>(&'a self) -> &'a RefCell<FnvHashMap<(ast::NodeId, &'tcx Substs<'tcx>),
686 &self.local.const_values
689 pub fn extern_const_values<'a>(&'a self) -> &'a RefCell<DefIdMap<ValueRef>> {
690 &self.local.extern_const_values
693 pub fn impl_method_cache<'a>(&'a self)
694 -> &'a RefCell<FnvHashMap<(DefId, ast::Name), DefId>> {
695 &self.local.impl_method_cache
698 pub fn closure_bare_wrapper_cache<'a>(&'a self) -> &'a RefCell<FnvHashMap<ValueRef, ValueRef>> {
699 &self.local.closure_bare_wrapper_cache
702 pub fn statics_to_rauw<'a>(&'a self) -> &'a RefCell<Vec<(ValueRef, ValueRef)>> {
703 &self.local.statics_to_rauw
706 pub fn lltypes<'a>(&'a self) -> &'a RefCell<FnvHashMap<Ty<'tcx>, Type>> {
710 pub fn llsizingtypes<'a>(&'a self) -> &'a RefCell<FnvHashMap<Ty<'tcx>, Type>> {
711 &self.local.llsizingtypes
714 pub fn adt_reprs<'a>(&'a self) -> &'a RefCell<FnvHashMap<Ty<'tcx>, Rc<adt::Repr<'tcx>>>> {
715 &self.local.adt_reprs
718 pub fn symbol_hasher<'a>(&'a self) -> &'a RefCell<Sha256> {
719 &self.shared.symbol_hasher
722 pub fn type_hashcodes<'a>(&'a self) -> &'a RefCell<FnvHashMap<Ty<'tcx>, String>> {
723 &self.local.type_hashcodes
726 pub fn stats<'a>(&'a self) -> &'a Stats {
730 pub fn available_monomorphizations<'a>(&'a self) -> &'a RefCell<FnvHashSet<String>> {
731 &self.local.available_monomorphizations
734 pub fn available_drop_glues(&self) -> &RefCell<FnvHashMap<DropGlueKind<'tcx>, String>> {
735 &self.shared.available_drop_glues
738 pub fn int_type(&self) -> Type {
742 pub fn opaque_vec_type(&self) -> Type {
743 self.local.opaque_vec_type
746 pub fn closure_vals<'a>(&'a self) -> &'a RefCell<FnvHashMap<MonoId<'tcx>, ValueRef>> {
747 &self.local.closure_vals
750 pub fn dbg_cx<'a>(&'a self) -> &'a Option<debuginfo::CrateDebugContext<'tcx>> {
754 pub fn eh_personality<'a>(&'a self) -> &'a RefCell<Option<ValueRef>> {
755 &self.local.eh_personality
758 pub fn eh_unwind_resume<'a>(&'a self) -> &'a RefCell<Option<ValueRef>> {
759 &self.local.eh_unwind_resume
762 pub fn rust_try_fn<'a>(&'a self) -> &'a RefCell<Option<ValueRef>> {
763 &self.local.rust_try_fn
766 fn intrinsics<'a>(&'a self) -> &'a RefCell<FnvHashMap<&'static str, ValueRef>> {
767 &self.local.intrinsics
770 pub fn count_llvm_insn(&self) {
771 self.local.n_llvm_insns.set(self.local.n_llvm_insns.get() + 1);
774 pub fn trait_cache(&self) -> &RefCell<DepTrackingMap<TraitSelectionCache<'tcx>>> {
775 &self.local.trait_cache
778 /// Return exclusive upper bound on object size.
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.
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[..] {
793 _ => unreachable!() // error handled by config::build_target_config
797 pub fn report_overbig_object(&self, obj: Ty<'tcx>) -> ! {
799 &format!("the type `{:?}` is too big for the current architecture",
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() {
808 &format!("overflow representing the type `{}`", ty))
810 self.local.type_of_depth.set(current_depth + 1);
811 TypeOfDepthLock(self.local)
814 pub fn check_overflow(&self) -> bool {
815 self.shared.check_overflow
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
822 self.shared.check_drop_flag_for_sanity
825 pub fn use_dll_storage_attrs(&self) -> bool {
826 self.shared.use_dll_storage_attrs()
829 pub fn mir_map(&self) -> &'b MirMap<'tcx> {
834 pub struct TypeOfDepthLock<'a, 'tcx: 'a>(&'a LocalCrateContext<'tcx>);
836 impl<'a, 'tcx> Drop for TypeOfDepthLock<'a, 'tcx> {
838 self.0.type_of_depth.set(self.0.type_of_depth.get() - 1);
842 /// Declare any llvm intrinsics that you might need
843 fn declare_intrinsic(ccx: &CrateContext, key: &str) -> Option<ValueRef> {
845 ($name:expr, fn() -> $ret:expr) => (
847 let f = declare::declare_cfn(ccx, $name, Type::func(&[], &$ret),
849 llvm::SetUnnamedAddr(f, false);
850 ccx.intrinsics().borrow_mut().insert($name, f.clone());
854 ($name:expr, fn($($arg:expr),*) -> $ret:expr) => (
856 let f = declare::declare_cfn(ccx, $name, Type::func(&[$($arg),*], &$ret),
858 llvm::SetUnnamedAddr(f, false);
859 ccx.intrinsics().borrow_mut().insert($name, f.clone());
864 macro_rules! mk_struct {
865 ($($field_ty:expr),*) => (Type::struct_(ccx, &[$($field_ty),*], false))
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);
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);
888 ifn!("llvm.trap", fn() -> void);
889 ifn!("llvm.debugtrap", fn() -> void);
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);
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);
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);
916 ifn!("llvm.fabs.f32", fn(t_f32) -> t_f32);
917 ifn!("llvm.fabs.f64", fn(t_f64) -> t_f64);
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);
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);
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);
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);
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);
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);
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);
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});
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});
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});
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});
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});
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});
985 ifn!("llvm.lifetime.start", fn(t_i64,i8p) -> void);
986 ifn!("llvm.lifetime.end", fn(t_i64, i8p) -> void);
988 ifn!("llvm.expect.i1", fn(i1, i1) -> i1);
989 ifn!("llvm.eh.typeid.for", fn(i8p) -> t_i32);
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);
1004 let bld = ccx.builder();
1006 llvm::LLVMAppendBasicBlockInContext(ccx.llcx(), f,
1007 "entry-block\0".as_ptr() as *const _)
1010 bld.position_at_end(llbb);
1013 ccx.intrinsics().borrow_mut().insert($name, f.clone());
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());
1031 compatible_ifn!("llvm.assume", noop(llvmcompat_assume(i1) -> void), 6);
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);