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