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