]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/context.rs
Auto merge of #42593 - ibabushkin:on-demand-external-source, r=eddyb
[rust.git] / src / librustc_trans / context.rs
1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use llvm;
12 use llvm::{ContextRef, ModuleRef, ValueRef};
13 use rustc::dep_graph::{DepGraph, DepGraphSafe};
14 use rustc::hir;
15 use rustc::hir::def_id::DefId;
16 use rustc::traits;
17 use debuginfo;
18 use callee;
19 use base;
20 use declare;
21 use monomorphize::Instance;
22
23 use partitioning::CodegenUnit;
24 use type_::Type;
25 use rustc_data_structures::base_n;
26 use rustc::session::config::{self, NoDebugInfo, OutputFilenames};
27 use rustc::session::Session;
28 use rustc::ty::subst::Substs;
29 use rustc::ty::{self, Ty, TyCtxt};
30 use rustc::ty::layout::{LayoutCx, LayoutError, LayoutTyper, TyLayout};
31 use rustc::util::nodemap::{NodeSet, DefIdMap, FxHashMap};
32
33 use std::ffi::{CStr, CString};
34 use std::cell::{Cell, RefCell};
35 use std::ptr;
36 use std::iter;
37 use std::str;
38 use std::marker::PhantomData;
39 use syntax::ast;
40 use syntax::symbol::InternedString;
41 use syntax_pos::DUMMY_SP;
42 use abi::Abi;
43
44 #[derive(Clone, Default)]
45 pub struct Stats {
46     pub n_glues_created: Cell<usize>,
47     pub n_null_glues: Cell<usize>,
48     pub n_real_glues: Cell<usize>,
49     pub n_fns: Cell<usize>,
50     pub n_inlines: Cell<usize>,
51     pub n_closures: Cell<usize>,
52     pub n_llvm_insns: Cell<usize>,
53     pub llvm_insns: RefCell<FxHashMap<String, usize>>,
54     // (ident, llvm-instructions)
55     pub fn_stats: RefCell<Vec<(String, usize)> >,
56 }
57
58 impl Stats {
59     pub fn extend(&mut self, stats: Stats) {
60         self.n_glues_created.set(self.n_glues_created.get() + stats.n_glues_created.get());
61         self.n_null_glues.set(self.n_null_glues.get() + stats.n_null_glues.get());
62         self.n_real_glues.set(self.n_real_glues.get() + stats.n_real_glues.get());
63         self.n_fns.set(self.n_fns.get() + stats.n_fns.get());
64         self.n_inlines.set(self.n_inlines.get() + stats.n_inlines.get());
65         self.n_closures.set(self.n_closures.get() + stats.n_closures.get());
66         self.n_llvm_insns.set(self.n_llvm_insns.get() + stats.n_llvm_insns.get());
67         self.llvm_insns.borrow_mut().extend(
68             stats.llvm_insns.borrow().iter()
69                                      .map(|(key, value)| (key.clone(), value.clone())));
70         self.fn_stats.borrow_mut().append(&mut *stats.fn_stats.borrow_mut());
71     }
72 }
73
74 /// The shared portion of a `CrateContext`.  There is one `SharedCrateContext`
75 /// per crate.  The data here is shared between all compilation units of the
76 /// crate, so it must not contain references to any LLVM data structures
77 /// (aside from metadata-related ones).
78 pub struct SharedCrateContext<'a, 'tcx: 'a> {
79     exported_symbols: NodeSet,
80     tcx: TyCtxt<'a, 'tcx, 'tcx>,
81     check_overflow: bool,
82
83     use_dll_storage_attrs: bool,
84
85     output_filenames: &'a OutputFilenames,
86 }
87
88 /// The local portion of a `CrateContext`.  There is one `LocalCrateContext`
89 /// per compilation unit.  Each one has its own LLVM `ContextRef` so that
90 /// several compilation units may be optimized in parallel.  All other LLVM
91 /// data structures in the `LocalCrateContext` are tied to that `ContextRef`.
92 pub struct LocalCrateContext<'a, 'tcx: 'a> {
93     llmod: ModuleRef,
94     llcx: ContextRef,
95     stats: Stats,
96     codegen_unit: CodegenUnit<'tcx>,
97     /// Cache instances of monomorphic and polymorphic items
98     instances: RefCell<FxHashMap<Instance<'tcx>, ValueRef>>,
99     /// Cache generated vtables
100     vtables: RefCell<FxHashMap<(ty::Ty<'tcx>,
101                                 Option<ty::PolyExistentialTraitRef<'tcx>>), ValueRef>>,
102     /// Cache of constant strings,
103     const_cstr_cache: RefCell<FxHashMap<InternedString, ValueRef>>,
104
105     /// Reverse-direction for const ptrs cast from globals.
106     /// Key is a ValueRef holding a *T,
107     /// Val is a ValueRef holding a *[T].
108     ///
109     /// Needed because LLVM loses pointer->pointee association
110     /// when we ptrcast, and we have to ptrcast during translation
111     /// of a [T] const because we form a slice, a (*T,usize) pair, not
112     /// a pointer to an LLVM array type. Similar for trait objects.
113     const_unsized: RefCell<FxHashMap<ValueRef, ValueRef>>,
114
115     /// Cache of emitted const globals (value -> global)
116     const_globals: RefCell<FxHashMap<ValueRef, ValueRef>>,
117
118     /// Cache of emitted const values
119     const_values: RefCell<FxHashMap<(ast::NodeId, &'tcx Substs<'tcx>), ValueRef>>,
120
121     /// Cache of external const values
122     extern_const_values: RefCell<DefIdMap<ValueRef>>,
123
124     /// Mapping from static definitions to their DefId's.
125     statics: RefCell<FxHashMap<ValueRef, DefId>>,
126
127     /// List of globals for static variables which need to be passed to the
128     /// LLVM function ReplaceAllUsesWith (RAUW) when translation is complete.
129     /// (We have to make sure we don't invalidate any ValueRefs referring
130     /// to constants.)
131     statics_to_rauw: RefCell<Vec<(ValueRef, ValueRef)>>,
132
133     /// Statics that will be placed in the llvm.used variable
134     /// See http://llvm.org/docs/LangRef.html#the-llvm-used-global-variable for details
135     used_statics: RefCell<Vec<ValueRef>>,
136
137     lltypes: RefCell<FxHashMap<Ty<'tcx>, Type>>,
138     type_hashcodes: RefCell<FxHashMap<Ty<'tcx>, String>>,
139     int_type: Type,
140     opaque_vec_type: Type,
141     str_slice_type: Type,
142
143     dbg_cx: Option<debuginfo::CrateDebugContext<'tcx>>,
144
145     eh_personality: Cell<Option<ValueRef>>,
146     eh_unwind_resume: Cell<Option<ValueRef>>,
147     rust_try_fn: Cell<Option<ValueRef>>,
148
149     intrinsics: RefCell<FxHashMap<&'static str, ValueRef>>,
150
151     /// Depth of the current type-of computation - used to bail out
152     type_of_depth: Cell<usize>,
153
154     /// A counter that is used for generating local symbol names
155     local_gen_sym_counter: Cell<usize>,
156
157     /// A placeholder so we can add lifetimes
158     placeholder: PhantomData<&'a ()>,
159 }
160
161 /// A CrateContext value binds together one LocalCrateContext with the
162 /// SharedCrateContext. It exists as a convenience wrapper, so we don't have to
163 /// pass around (SharedCrateContext, LocalCrateContext) tuples all over trans.
164 pub struct CrateContext<'a, 'tcx: 'a> {
165     shared: &'a SharedCrateContext<'a, 'tcx>,
166     local_ccx: &'a LocalCrateContext<'a, 'tcx>,
167 }
168
169 impl<'a, 'tcx> CrateContext<'a, 'tcx> {
170     pub fn new(shared: &'a SharedCrateContext<'a, 'tcx>,
171                local_ccx: &'a LocalCrateContext<'a, 'tcx>)
172                -> Self {
173         CrateContext { shared, local_ccx }
174     }
175 }
176
177 impl<'a, 'tcx> DepGraphSafe for CrateContext<'a, 'tcx> {
178 }
179
180 pub fn get_reloc_model(sess: &Session) -> llvm::RelocMode {
181     let reloc_model_arg = match sess.opts.cg.relocation_model {
182         Some(ref s) => &s[..],
183         None => &sess.target.target.options.relocation_model[..],
184     };
185
186     match ::back::write::RELOC_MODEL_ARGS.iter().find(
187         |&&arg| arg.0 == reloc_model_arg) {
188         Some(x) => x.1,
189         _ => {
190             sess.err(&format!("{:?} is not a valid relocation mode",
191                              sess.opts
192                                  .cg
193                                  .code_model));
194             sess.abort_if_errors();
195             bug!();
196         }
197     }
198 }
199
200 fn is_any_library(sess: &Session) -> bool {
201     sess.crate_types.borrow().iter().any(|ty| {
202         *ty != config::CrateTypeExecutable
203     })
204 }
205
206 pub fn is_pie_binary(sess: &Session) -> bool {
207     !is_any_library(sess) && get_reloc_model(sess) == llvm::RelocMode::PIC
208 }
209
210 pub unsafe fn create_context_and_module(sess: &Session, mod_name: &str) -> (ContextRef, ModuleRef) {
211     let llcx = llvm::LLVMContextCreate();
212     let mod_name = CString::new(mod_name).unwrap();
213     let llmod = llvm::LLVMModuleCreateWithNameInContext(mod_name.as_ptr(), llcx);
214
215     // Ensure the data-layout values hardcoded remain the defaults.
216     if sess.target.target.options.is_builtin {
217         let tm = ::back::write::create_target_machine(sess);
218         llvm::LLVMRustSetDataLayoutFromTargetMachine(llmod, tm);
219         llvm::LLVMRustDisposeTargetMachine(tm);
220
221         let data_layout = llvm::LLVMGetDataLayout(llmod);
222         let data_layout = str::from_utf8(CStr::from_ptr(data_layout).to_bytes())
223             .ok().expect("got a non-UTF8 data-layout from LLVM");
224
225         // Unfortunately LLVM target specs change over time, and right now we
226         // don't have proper support to work with any more than one
227         // `data_layout` than the one that is in the rust-lang/rust repo. If
228         // this compiler is configured against a custom LLVM, we may have a
229         // differing data layout, even though we should update our own to use
230         // that one.
231         //
232         // As an interim hack, if CFG_LLVM_ROOT is not an empty string then we
233         // disable this check entirely as we may be configured with something
234         // that has a different target layout.
235         //
236         // Unsure if this will actually cause breakage when rustc is configured
237         // as such.
238         //
239         // FIXME(#34960)
240         let cfg_llvm_root = option_env!("CFG_LLVM_ROOT").unwrap_or("");
241         let custom_llvm_used = cfg_llvm_root.trim() != "";
242
243         if !custom_llvm_used && sess.target.target.data_layout != data_layout {
244             bug!("data-layout for builtin `{}` target, `{}`, \
245                   differs from LLVM default, `{}`",
246                  sess.target.target.llvm_target,
247                  sess.target.target.data_layout,
248                  data_layout);
249         }
250     }
251
252     let data_layout = CString::new(&sess.target.target.data_layout[..]).unwrap();
253     llvm::LLVMSetDataLayout(llmod, data_layout.as_ptr());
254
255     let llvm_target = sess.target.target.llvm_target.as_bytes();
256     let llvm_target = CString::new(llvm_target).unwrap();
257     llvm::LLVMRustSetNormalizedTarget(llmod, llvm_target.as_ptr());
258
259     if is_pie_binary(sess) {
260         llvm::LLVMRustSetModulePIELevel(llmod);
261     }
262
263     (llcx, llmod)
264 }
265
266 impl<'b, 'tcx> SharedCrateContext<'b, 'tcx> {
267     pub fn new(tcx: TyCtxt<'b, 'tcx, 'tcx>,
268                exported_symbols: NodeSet,
269                check_overflow: bool,
270                output_filenames: &'b OutputFilenames)
271                -> SharedCrateContext<'b, 'tcx> {
272         // An interesting part of Windows which MSVC forces our hand on (and
273         // apparently MinGW didn't) is the usage of `dllimport` and `dllexport`
274         // attributes in LLVM IR as well as native dependencies (in C these
275         // correspond to `__declspec(dllimport)`).
276         //
277         // Whenever a dynamic library is built by MSVC it must have its public
278         // interface specified by functions tagged with `dllexport` or otherwise
279         // they're not available to be linked against. This poses a few problems
280         // for the compiler, some of which are somewhat fundamental, but we use
281         // the `use_dll_storage_attrs` variable below to attach the `dllexport`
282         // attribute to all LLVM functions that are exported e.g. they're
283         // already tagged with external linkage). This is suboptimal for a few
284         // reasons:
285         //
286         // * If an object file will never be included in a dynamic library,
287         //   there's no need to attach the dllexport attribute. Most object
288         //   files in Rust are not destined to become part of a dll as binaries
289         //   are statically linked by default.
290         // * If the compiler is emitting both an rlib and a dylib, the same
291         //   source object file is currently used but with MSVC this may be less
292         //   feasible. The compiler may be able to get around this, but it may
293         //   involve some invasive changes to deal with this.
294         //
295         // The flipside of this situation is that whenever you link to a dll and
296         // you import a function from it, the import should be tagged with
297         // `dllimport`. At this time, however, the compiler does not emit
298         // `dllimport` for any declarations other than constants (where it is
299         // required), which is again suboptimal for even more reasons!
300         //
301         // * Calling a function imported from another dll without using
302         //   `dllimport` causes the linker/compiler to have extra overhead (one
303         //   `jmp` instruction on x86) when calling the function.
304         // * The same object file may be used in different circumstances, so a
305         //   function may be imported from a dll if the object is linked into a
306         //   dll, but it may be just linked against if linked into an rlib.
307         // * The compiler has no knowledge about whether native functions should
308         //   be tagged dllimport or not.
309         //
310         // For now the compiler takes the perf hit (I do not have any numbers to
311         // this effect) by marking very little as `dllimport` and praying the
312         // linker will take care of everything. Fixing this problem will likely
313         // require adding a few attributes to Rust itself (feature gated at the
314         // start) and then strongly recommending static linkage on MSVC!
315         let use_dll_storage_attrs = tcx.sess.target.target.options.is_like_msvc;
316
317         SharedCrateContext {
318             exported_symbols: exported_symbols,
319             tcx: tcx,
320             check_overflow: check_overflow,
321             use_dll_storage_attrs: use_dll_storage_attrs,
322             output_filenames: output_filenames,
323         }
324     }
325
326     pub fn type_needs_drop(&self, ty: Ty<'tcx>) -> bool {
327         ty.needs_drop(self.tcx, ty::ParamEnv::empty(traits::Reveal::All))
328     }
329
330     pub fn type_is_sized(&self, ty: Ty<'tcx>) -> bool {
331         ty.is_sized(self.tcx, ty::ParamEnv::empty(traits::Reveal::All), DUMMY_SP)
332     }
333
334     pub fn type_is_freeze(&self, ty: Ty<'tcx>) -> bool {
335         ty.is_freeze(self.tcx, ty::ParamEnv::empty(traits::Reveal::All), DUMMY_SP)
336     }
337
338     pub fn exported_symbols<'a>(&'a self) -> &'a NodeSet {
339         &self.exported_symbols
340     }
341
342     pub fn tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> {
343         self.tcx
344     }
345
346     pub fn sess<'a>(&'a self) -> &'a Session {
347         &self.tcx.sess
348     }
349
350     pub fn dep_graph<'a>(&'a self) -> &'a DepGraph {
351         &self.tcx.dep_graph
352     }
353
354     pub fn use_dll_storage_attrs(&self) -> bool {
355         self.use_dll_storage_attrs
356     }
357
358     pub fn output_filenames(&self) -> &OutputFilenames {
359         self.output_filenames
360     }
361 }
362
363 impl<'a, 'tcx> LocalCrateContext<'a, 'tcx> {
364     pub fn new(shared: &SharedCrateContext<'a, 'tcx>,
365                codegen_unit: CodegenUnit<'tcx>)
366                -> LocalCrateContext<'a, 'tcx> {
367         unsafe {
368             // Append ".rs" to LLVM module identifier.
369             //
370             // LLVM code generator emits a ".file filename" directive
371             // for ELF backends. Value of the "filename" is set as the
372             // LLVM module identifier.  Due to a LLVM MC bug[1], LLVM
373             // crashes if the module identifier is same as other symbols
374             // such as a function name in the module.
375             // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
376             let llmod_id = format!("{}.rs", codegen_unit.name());
377
378             let (llcx, llmod) = create_context_and_module(&shared.tcx.sess,
379                                                           &llmod_id[..]);
380
381             let dbg_cx = if shared.tcx.sess.opts.debuginfo != NoDebugInfo {
382                 let dctx = debuginfo::CrateDebugContext::new(llmod);
383                 debuginfo::metadata::compile_unit_metadata(shared,
384                                                            codegen_unit.name(),
385                                                            &dctx,
386                                                            shared.tcx.sess);
387                 Some(dctx)
388             } else {
389                 None
390             };
391
392             let local_ccx = LocalCrateContext {
393                 llmod: llmod,
394                 llcx: llcx,
395                 stats: Stats::default(),
396                 codegen_unit: codegen_unit,
397                 instances: RefCell::new(FxHashMap()),
398                 vtables: RefCell::new(FxHashMap()),
399                 const_cstr_cache: RefCell::new(FxHashMap()),
400                 const_unsized: RefCell::new(FxHashMap()),
401                 const_globals: RefCell::new(FxHashMap()),
402                 const_values: RefCell::new(FxHashMap()),
403                 extern_const_values: RefCell::new(DefIdMap()),
404                 statics: RefCell::new(FxHashMap()),
405                 statics_to_rauw: RefCell::new(Vec::new()),
406                 used_statics: RefCell::new(Vec::new()),
407                 lltypes: RefCell::new(FxHashMap()),
408                 type_hashcodes: RefCell::new(FxHashMap()),
409                 int_type: Type::from_ref(ptr::null_mut()),
410                 opaque_vec_type: Type::from_ref(ptr::null_mut()),
411                 str_slice_type: Type::from_ref(ptr::null_mut()),
412                 dbg_cx: dbg_cx,
413                 eh_personality: Cell::new(None),
414                 eh_unwind_resume: Cell::new(None),
415                 rust_try_fn: Cell::new(None),
416                 intrinsics: RefCell::new(FxHashMap()),
417                 type_of_depth: Cell::new(0),
418                 local_gen_sym_counter: Cell::new(0),
419                 placeholder: PhantomData,
420             };
421
422             let (int_type, opaque_vec_type, str_slice_ty, mut local_ccx) = {
423                 // Do a little dance to create a dummy CrateContext, so we can
424                 // create some things in the LLVM module of this codegen unit
425                 let mut local_ccxs = vec![local_ccx];
426                 let (int_type, opaque_vec_type, str_slice_ty) = {
427                     let dummy_ccx = LocalCrateContext::dummy_ccx(shared,
428                                                                  local_ccxs.as_mut_slice());
429                     let mut str_slice_ty = Type::named_struct(&dummy_ccx, "str_slice");
430                     str_slice_ty.set_struct_body(&[Type::i8p(&dummy_ccx),
431                                                    Type::int(&dummy_ccx)],
432                                                  false);
433                     (Type::int(&dummy_ccx), Type::opaque_vec(&dummy_ccx), str_slice_ty)
434                 };
435                 (int_type, opaque_vec_type, str_slice_ty, local_ccxs.pop().unwrap())
436             };
437
438             local_ccx.int_type = int_type;
439             local_ccx.opaque_vec_type = opaque_vec_type;
440             local_ccx.str_slice_type = str_slice_ty;
441
442             local_ccx
443         }
444     }
445
446     /// Create a dummy `CrateContext` from `self` and  the provided
447     /// `SharedCrateContext`.  This is somewhat dangerous because `self` may
448     /// not be fully initialized.
449     ///
450     /// This is used in the `LocalCrateContext` constructor to allow calling
451     /// functions that expect a complete `CrateContext`, even before the local
452     /// portion is fully initialized and attached to the `SharedCrateContext`.
453     fn dummy_ccx(shared: &'a SharedCrateContext<'a, 'tcx>,
454                  local_ccxs: &'a [LocalCrateContext<'a, 'tcx>])
455                  -> CrateContext<'a, 'tcx> {
456         assert!(local_ccxs.len() == 1);
457         CrateContext {
458             shared: shared,
459             local_ccx: &local_ccxs[0]
460         }
461     }
462
463     pub fn into_stats(self) -> Stats {
464         self.stats
465     }
466 }
467
468 impl<'b, 'tcx> CrateContext<'b, 'tcx> {
469     pub fn shared(&self) -> &'b SharedCrateContext<'b, 'tcx> {
470         self.shared
471     }
472
473     fn local(&self) -> &'b LocalCrateContext<'b, 'tcx> {
474         self.local_ccx
475     }
476
477     pub fn tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> {
478         self.shared.tcx
479     }
480
481     pub fn sess<'a>(&'a self) -> &'a Session {
482         &self.shared.tcx.sess
483     }
484
485     pub fn get_intrinsic(&self, key: &str) -> ValueRef {
486         if let Some(v) = self.intrinsics().borrow().get(key).cloned() {
487             return v;
488         }
489         match declare_intrinsic(self, key) {
490             Some(v) => return v,
491             None => bug!("unknown intrinsic '{}'", key)
492         }
493     }
494
495     pub fn llmod(&self) -> ModuleRef {
496         self.local().llmod
497     }
498
499     pub fn llcx(&self) -> ContextRef {
500         self.local().llcx
501     }
502
503     pub fn codegen_unit(&self) -> &CodegenUnit<'tcx> {
504         &self.local().codegen_unit
505     }
506
507     pub fn td(&self) -> llvm::TargetDataRef {
508         unsafe { llvm::LLVMRustGetModuleDataLayout(self.llmod()) }
509     }
510
511     pub fn instances<'a>(&'a self) -> &'a RefCell<FxHashMap<Instance<'tcx>, ValueRef>> {
512         &self.local().instances
513     }
514
515     pub fn vtables<'a>(&'a self)
516         -> &'a RefCell<FxHashMap<(ty::Ty<'tcx>,
517                                   Option<ty::PolyExistentialTraitRef<'tcx>>), ValueRef>> {
518         &self.local().vtables
519     }
520
521     pub fn const_cstr_cache<'a>(&'a self) -> &'a RefCell<FxHashMap<InternedString, ValueRef>> {
522         &self.local().const_cstr_cache
523     }
524
525     pub fn const_unsized<'a>(&'a self) -> &'a RefCell<FxHashMap<ValueRef, ValueRef>> {
526         &self.local().const_unsized
527     }
528
529     pub fn const_globals<'a>(&'a self) -> &'a RefCell<FxHashMap<ValueRef, ValueRef>> {
530         &self.local().const_globals
531     }
532
533     pub fn const_values<'a>(&'a self) -> &'a RefCell<FxHashMap<(ast::NodeId, &'tcx Substs<'tcx>),
534                                                                ValueRef>> {
535         &self.local().const_values
536     }
537
538     pub fn extern_const_values<'a>(&'a self) -> &'a RefCell<DefIdMap<ValueRef>> {
539         &self.local().extern_const_values
540     }
541
542     pub fn statics<'a>(&'a self) -> &'a RefCell<FxHashMap<ValueRef, DefId>> {
543         &self.local().statics
544     }
545
546     pub fn statics_to_rauw<'a>(&'a self) -> &'a RefCell<Vec<(ValueRef, ValueRef)>> {
547         &self.local().statics_to_rauw
548     }
549
550     pub fn used_statics<'a>(&'a self) -> &'a RefCell<Vec<ValueRef>> {
551         &self.local().used_statics
552     }
553
554     pub fn lltypes<'a>(&'a self) -> &'a RefCell<FxHashMap<Ty<'tcx>, Type>> {
555         &self.local().lltypes
556     }
557
558     pub fn type_hashcodes<'a>(&'a self) -> &'a RefCell<FxHashMap<Ty<'tcx>, String>> {
559         &self.local().type_hashcodes
560     }
561
562     pub fn stats<'a>(&'a self) -> &'a Stats {
563         &self.local().stats
564     }
565
566     pub fn int_type(&self) -> Type {
567         self.local().int_type
568     }
569
570     pub fn opaque_vec_type(&self) -> Type {
571         self.local().opaque_vec_type
572     }
573
574     pub fn str_slice_type(&self) -> Type {
575         self.local().str_slice_type
576     }
577
578     pub fn dbg_cx<'a>(&'a self) -> &'a Option<debuginfo::CrateDebugContext<'tcx>> {
579         &self.local().dbg_cx
580     }
581
582     pub fn rust_try_fn<'a>(&'a self) -> &'a Cell<Option<ValueRef>> {
583         &self.local().rust_try_fn
584     }
585
586     fn intrinsics<'a>(&'a self) -> &'a RefCell<FxHashMap<&'static str, ValueRef>> {
587         &self.local().intrinsics
588     }
589
590     pub fn obj_size_bound(&self) -> u64 {
591         self.tcx().data_layout.obj_size_bound()
592     }
593
594     pub fn report_overbig_object(&self, obj: Ty<'tcx>) -> ! {
595         self.sess().fatal(
596             &format!("the type `{:?}` is too big for the current architecture",
597                     obj))
598     }
599
600     pub fn enter_type_of(&self, ty: Ty<'tcx>) -> TypeOfDepthLock<'b, 'tcx> {
601         let current_depth = self.local().type_of_depth.get();
602         debug!("enter_type_of({:?}) at depth {:?}", ty, current_depth);
603         if current_depth > self.sess().recursion_limit.get() {
604             self.sess().fatal(
605                 &format!("overflow representing the type `{}`", ty))
606         }
607         self.local().type_of_depth.set(current_depth + 1);
608         TypeOfDepthLock(self.local())
609     }
610
611     pub fn check_overflow(&self) -> bool {
612         self.shared.check_overflow
613     }
614
615     pub fn use_dll_storage_attrs(&self) -> bool {
616         self.shared.use_dll_storage_attrs()
617     }
618
619     /// Given the def-id of some item that has no type parameters, make
620     /// a suitable "empty substs" for it.
621     pub fn empty_substs_for_def_id(&self, item_def_id: DefId) -> &'tcx Substs<'tcx> {
622         self.tcx().empty_substs_for_def_id(item_def_id)
623     }
624
625     /// Generate a new symbol name with the given prefix. This symbol name must
626     /// only be used for definitions with `internal` or `private` linkage.
627     pub fn generate_local_symbol_name(&self, prefix: &str) -> String {
628         let idx = self.local().local_gen_sym_counter.get();
629         self.local().local_gen_sym_counter.set(idx + 1);
630         // Include a '.' character, so there can be no accidental conflicts with
631         // user defined names
632         let mut name = String::with_capacity(prefix.len() + 6);
633         name.push_str(prefix);
634         name.push_str(".");
635         base_n::push_str(idx as u64, base_n::ALPHANUMERIC_ONLY, &mut name);
636         name
637     }
638
639     pub fn eh_personality(&self) -> ValueRef {
640         // The exception handling personality function.
641         //
642         // If our compilation unit has the `eh_personality` lang item somewhere
643         // within it, then we just need to translate that. Otherwise, we're
644         // building an rlib which will depend on some upstream implementation of
645         // this function, so we just codegen a generic reference to it. We don't
646         // specify any of the types for the function, we just make it a symbol
647         // that LLVM can later use.
648         //
649         // Note that MSVC is a little special here in that we don't use the
650         // `eh_personality` lang item at all. Currently LLVM has support for
651         // both Dwarf and SEH unwind mechanisms for MSVC targets and uses the
652         // *name of the personality function* to decide what kind of unwind side
653         // tables/landing pads to emit. It looks like Dwarf is used by default,
654         // injecting a dependency on the `_Unwind_Resume` symbol for resuming
655         // an "exception", but for MSVC we want to force SEH. This means that we
656         // can't actually have the personality function be our standard
657         // `rust_eh_personality` function, but rather we wired it up to the
658         // CRT's custom personality function, which forces LLVM to consider
659         // landing pads as "landing pads for SEH".
660         if let Some(llpersonality) = self.local().eh_personality.get() {
661             return llpersonality
662         }
663         let tcx = self.tcx();
664         let llfn = match tcx.lang_items.eh_personality() {
665             Some(def_id) if !base::wants_msvc_seh(self.sess()) => {
666                 callee::resolve_and_get_fn(self, def_id, tcx.intern_substs(&[]))
667             }
668             _ => {
669                 let name = if base::wants_msvc_seh(self.sess()) {
670                     "__CxxFrameHandler3"
671                 } else {
672                     "rust_eh_personality"
673                 };
674                 let fty = Type::variadic_func(&[], &Type::i32(self));
675                 declare::declare_cfn(self, name, fty)
676             }
677         };
678         self.local().eh_personality.set(Some(llfn));
679         llfn
680     }
681
682     // Returns a ValueRef of the "eh_unwind_resume" lang item if one is defined,
683     // otherwise declares it as an external function.
684     pub fn eh_unwind_resume(&self) -> ValueRef {
685         use attributes;
686         let unwresume = &self.local().eh_unwind_resume;
687         if let Some(llfn) = unwresume.get() {
688             return llfn;
689         }
690
691         let tcx = self.tcx();
692         assert!(self.sess().target.target.options.custom_unwind_resume);
693         if let Some(def_id) = tcx.lang_items.eh_unwind_resume() {
694             let llfn = callee::resolve_and_get_fn(self, def_id, tcx.intern_substs(&[]));
695             unwresume.set(Some(llfn));
696             return llfn;
697         }
698
699         let ty = tcx.mk_fn_ptr(ty::Binder(tcx.mk_fn_sig(
700             iter::once(tcx.mk_mut_ptr(tcx.types.u8)),
701             tcx.types.never,
702             false,
703             hir::Unsafety::Unsafe,
704             Abi::C
705         )));
706
707         let llfn = declare::declare_fn(self, "rust_eh_unwind_resume", ty);
708         attributes::unwind(llfn, true);
709         unwresume.set(Some(llfn));
710         llfn
711     }
712 }
713
714 impl<'a, 'tcx> ty::layout::HasDataLayout for &'a SharedCrateContext<'a, 'tcx> {
715     fn data_layout(&self) -> &ty::layout::TargetDataLayout {
716         &self.tcx.data_layout
717     }
718 }
719
720 impl<'a, 'tcx> ty::layout::HasDataLayout for &'a CrateContext<'a, 'tcx> {
721     fn data_layout(&self) -> &ty::layout::TargetDataLayout {
722         &self.shared.tcx.data_layout
723     }
724 }
725
726 impl<'a, 'tcx> LayoutTyper<'tcx> for &'a SharedCrateContext<'a, 'tcx> {
727     type TyLayout = TyLayout<'tcx>;
728
729     fn tcx<'b>(&'b self) -> TyCtxt<'b, 'tcx, 'tcx> {
730         self.tcx
731     }
732
733     fn layout_of(self, ty: Ty<'tcx>) -> Self::TyLayout {
734         let param_env = ty::ParamEnv::empty(traits::Reveal::All);
735         LayoutCx::new(self.tcx, param_env)
736             .layout_of(ty)
737             .unwrap_or_else(|e| match e {
738                 LayoutError::SizeOverflow(_) => self.sess().fatal(&e.to_string()),
739                 _ => bug!("failed to get layout for `{}`: {}", ty, e)
740             })
741     }
742
743     fn normalize_projections(self, ty: Ty<'tcx>) -> Ty<'tcx> {
744         self.tcx().normalize_associated_type(&ty)
745     }
746 }
747
748 impl<'a, 'tcx> LayoutTyper<'tcx> for &'a CrateContext<'a, 'tcx> {
749     type TyLayout = TyLayout<'tcx>;
750
751     fn tcx<'b>(&'b self) -> TyCtxt<'b, 'tcx, 'tcx> {
752         self.shared.tcx
753     }
754
755     fn layout_of(self, ty: Ty<'tcx>) -> Self::TyLayout {
756         self.shared.layout_of(ty)
757     }
758
759     fn normalize_projections(self, ty: Ty<'tcx>) -> Ty<'tcx> {
760         self.shared.normalize_projections(ty)
761     }
762 }
763
764 pub struct TypeOfDepthLock<'a, 'tcx: 'a>(&'a LocalCrateContext<'a, 'tcx>);
765
766 impl<'a, 'tcx> Drop for TypeOfDepthLock<'a, 'tcx> {
767     fn drop(&mut self) {
768         self.0.type_of_depth.set(self.0.type_of_depth.get() - 1);
769     }
770 }
771
772 /// Declare any llvm intrinsics that you might need
773 fn declare_intrinsic(ccx: &CrateContext, key: &str) -> Option<ValueRef> {
774     macro_rules! ifn {
775         ($name:expr, fn() -> $ret:expr) => (
776             if key == $name {
777                 let f = declare::declare_cfn(ccx, $name, Type::func(&[], &$ret));
778                 llvm::SetUnnamedAddr(f, false);
779                 ccx.intrinsics().borrow_mut().insert($name, f.clone());
780                 return Some(f);
781             }
782         );
783         ($name:expr, fn(...) -> $ret:expr) => (
784             if key == $name {
785                 let f = declare::declare_cfn(ccx, $name, Type::variadic_func(&[], &$ret));
786                 llvm::SetUnnamedAddr(f, false);
787                 ccx.intrinsics().borrow_mut().insert($name, f.clone());
788                 return Some(f);
789             }
790         );
791         ($name:expr, fn($($arg:expr),*) -> $ret:expr) => (
792             if key == $name {
793                 let f = declare::declare_cfn(ccx, $name, Type::func(&[$($arg),*], &$ret));
794                 llvm::SetUnnamedAddr(f, false);
795                 ccx.intrinsics().borrow_mut().insert($name, f.clone());
796                 return Some(f);
797             }
798         );
799     }
800     macro_rules! mk_struct {
801         ($($field_ty:expr),*) => (Type::struct_(ccx, &[$($field_ty),*], false))
802     }
803
804     let i8p = Type::i8p(ccx);
805     let void = Type::void(ccx);
806     let i1 = Type::i1(ccx);
807     let t_i8 = Type::i8(ccx);
808     let t_i16 = Type::i16(ccx);
809     let t_i32 = Type::i32(ccx);
810     let t_i64 = Type::i64(ccx);
811     let t_i128 = Type::i128(ccx);
812     let t_f32 = Type::f32(ccx);
813     let t_f64 = Type::f64(ccx);
814
815     ifn!("llvm.memcpy.p0i8.p0i8.i16", fn(i8p, i8p, t_i16, t_i32, i1) -> void);
816     ifn!("llvm.memcpy.p0i8.p0i8.i32", fn(i8p, i8p, t_i32, t_i32, i1) -> void);
817     ifn!("llvm.memcpy.p0i8.p0i8.i64", fn(i8p, i8p, t_i64, t_i32, i1) -> void);
818     ifn!("llvm.memmove.p0i8.p0i8.i16", fn(i8p, i8p, t_i16, t_i32, i1) -> void);
819     ifn!("llvm.memmove.p0i8.p0i8.i32", fn(i8p, i8p, t_i32, t_i32, i1) -> void);
820     ifn!("llvm.memmove.p0i8.p0i8.i64", fn(i8p, i8p, t_i64, t_i32, i1) -> void);
821     ifn!("llvm.memset.p0i8.i16", fn(i8p, t_i8, t_i16, t_i32, i1) -> void);
822     ifn!("llvm.memset.p0i8.i32", fn(i8p, t_i8, t_i32, t_i32, i1) -> void);
823     ifn!("llvm.memset.p0i8.i64", fn(i8p, t_i8, t_i64, t_i32, i1) -> void);
824
825     ifn!("llvm.trap", fn() -> void);
826     ifn!("llvm.debugtrap", fn() -> void);
827     ifn!("llvm.frameaddress", fn(t_i32) -> i8p);
828
829     ifn!("llvm.powi.f32", fn(t_f32, t_i32) -> t_f32);
830     ifn!("llvm.powi.f64", fn(t_f64, t_i32) -> t_f64);
831     ifn!("llvm.pow.f32", fn(t_f32, t_f32) -> t_f32);
832     ifn!("llvm.pow.f64", fn(t_f64, t_f64) -> t_f64);
833
834     ifn!("llvm.sqrt.f32", fn(t_f32) -> t_f32);
835     ifn!("llvm.sqrt.f64", fn(t_f64) -> t_f64);
836     ifn!("llvm.sin.f32", fn(t_f32) -> t_f32);
837     ifn!("llvm.sin.f64", fn(t_f64) -> t_f64);
838     ifn!("llvm.cos.f32", fn(t_f32) -> t_f32);
839     ifn!("llvm.cos.f64", fn(t_f64) -> t_f64);
840     ifn!("llvm.exp.f32", fn(t_f32) -> t_f32);
841     ifn!("llvm.exp.f64", fn(t_f64) -> t_f64);
842     ifn!("llvm.exp2.f32", fn(t_f32) -> t_f32);
843     ifn!("llvm.exp2.f64", fn(t_f64) -> t_f64);
844     ifn!("llvm.log.f32", fn(t_f32) -> t_f32);
845     ifn!("llvm.log.f64", fn(t_f64) -> t_f64);
846     ifn!("llvm.log10.f32", fn(t_f32) -> t_f32);
847     ifn!("llvm.log10.f64", fn(t_f64) -> t_f64);
848     ifn!("llvm.log2.f32", fn(t_f32) -> t_f32);
849     ifn!("llvm.log2.f64", fn(t_f64) -> t_f64);
850
851     ifn!("llvm.fma.f32", fn(t_f32, t_f32, t_f32) -> t_f32);
852     ifn!("llvm.fma.f64", fn(t_f64, t_f64, t_f64) -> t_f64);
853
854     ifn!("llvm.fabs.f32", fn(t_f32) -> t_f32);
855     ifn!("llvm.fabs.f64", fn(t_f64) -> t_f64);
856
857     ifn!("llvm.floor.f32", fn(t_f32) -> t_f32);
858     ifn!("llvm.floor.f64", fn(t_f64) -> t_f64);
859     ifn!("llvm.ceil.f32", fn(t_f32) -> t_f32);
860     ifn!("llvm.ceil.f64", fn(t_f64) -> t_f64);
861     ifn!("llvm.trunc.f32", fn(t_f32) -> t_f32);
862     ifn!("llvm.trunc.f64", fn(t_f64) -> t_f64);
863
864     ifn!("llvm.copysign.f32", fn(t_f32, t_f32) -> t_f32);
865     ifn!("llvm.copysign.f64", fn(t_f64, t_f64) -> t_f64);
866     ifn!("llvm.round.f32", fn(t_f32) -> t_f32);
867     ifn!("llvm.round.f64", fn(t_f64) -> t_f64);
868
869     ifn!("llvm.rint.f32", fn(t_f32) -> t_f32);
870     ifn!("llvm.rint.f64", fn(t_f64) -> t_f64);
871     ifn!("llvm.nearbyint.f32", fn(t_f32) -> t_f32);
872     ifn!("llvm.nearbyint.f64", fn(t_f64) -> t_f64);
873
874     ifn!("llvm.ctpop.i8", fn(t_i8) -> t_i8);
875     ifn!("llvm.ctpop.i16", fn(t_i16) -> t_i16);
876     ifn!("llvm.ctpop.i32", fn(t_i32) -> t_i32);
877     ifn!("llvm.ctpop.i64", fn(t_i64) -> t_i64);
878     ifn!("llvm.ctpop.i128", fn(t_i128) -> t_i128);
879
880     ifn!("llvm.ctlz.i8", fn(t_i8 , i1) -> t_i8);
881     ifn!("llvm.ctlz.i16", fn(t_i16, i1) -> t_i16);
882     ifn!("llvm.ctlz.i32", fn(t_i32, i1) -> t_i32);
883     ifn!("llvm.ctlz.i64", fn(t_i64, i1) -> t_i64);
884     ifn!("llvm.ctlz.i128", fn(t_i128, i1) -> t_i128);
885
886     ifn!("llvm.cttz.i8", fn(t_i8 , i1) -> t_i8);
887     ifn!("llvm.cttz.i16", fn(t_i16, i1) -> t_i16);
888     ifn!("llvm.cttz.i32", fn(t_i32, i1) -> t_i32);
889     ifn!("llvm.cttz.i64", fn(t_i64, i1) -> t_i64);
890     ifn!("llvm.cttz.i128", fn(t_i128, i1) -> t_i128);
891
892     ifn!("llvm.bswap.i16", fn(t_i16) -> t_i16);
893     ifn!("llvm.bswap.i32", fn(t_i32) -> t_i32);
894     ifn!("llvm.bswap.i64", fn(t_i64) -> t_i64);
895     ifn!("llvm.bswap.i128", fn(t_i128) -> t_i128);
896
897     ifn!("llvm.sadd.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
898     ifn!("llvm.sadd.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
899     ifn!("llvm.sadd.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
900     ifn!("llvm.sadd.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
901     ifn!("llvm.sadd.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1});
902
903     ifn!("llvm.uadd.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
904     ifn!("llvm.uadd.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
905     ifn!("llvm.uadd.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
906     ifn!("llvm.uadd.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
907     ifn!("llvm.uadd.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1});
908
909     ifn!("llvm.ssub.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
910     ifn!("llvm.ssub.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
911     ifn!("llvm.ssub.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
912     ifn!("llvm.ssub.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
913     ifn!("llvm.ssub.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1});
914
915     ifn!("llvm.usub.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
916     ifn!("llvm.usub.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
917     ifn!("llvm.usub.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
918     ifn!("llvm.usub.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
919     ifn!("llvm.usub.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1});
920
921     ifn!("llvm.smul.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
922     ifn!("llvm.smul.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
923     ifn!("llvm.smul.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
924     ifn!("llvm.smul.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
925     ifn!("llvm.smul.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1});
926
927     ifn!("llvm.umul.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
928     ifn!("llvm.umul.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
929     ifn!("llvm.umul.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
930     ifn!("llvm.umul.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
931     ifn!("llvm.umul.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1});
932
933     ifn!("llvm.lifetime.start", fn(t_i64,i8p) -> void);
934     ifn!("llvm.lifetime.end", fn(t_i64, i8p) -> void);
935
936     ifn!("llvm.expect.i1", fn(i1, i1) -> i1);
937     ifn!("llvm.eh.typeid.for", fn(i8p) -> t_i32);
938     ifn!("llvm.localescape", fn(...) -> void);
939     ifn!("llvm.localrecover", fn(i8p, i8p, t_i32) -> i8p);
940     ifn!("llvm.x86.seh.recoverfp", fn(i8p, i8p) -> i8p);
941
942     ifn!("llvm.assume", fn(i1) -> void);
943     ifn!("llvm.prefetch", fn(i8p, t_i32, t_i32, t_i32) -> void);
944
945     if ccx.sess().opts.debuginfo != NoDebugInfo {
946         ifn!("llvm.dbg.declare", fn(Type::metadata(ccx), Type::metadata(ccx)) -> void);
947         ifn!("llvm.dbg.value", fn(Type::metadata(ccx), t_i64, Type::metadata(ccx)) -> void);
948     }
949     return None;
950 }