]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/context.rs
f9f162bb823679ac76956b8ab214db267d30fa19
[rust.git] / src / librustc_codegen_llvm / 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 attributes;
12 use common;
13 use llvm;
14 use rustc::dep_graph::DepGraphSafe;
15 use rustc::hir;
16 use debuginfo;
17 use callee;
18 use base;
19 use declare;
20 use monomorphize::Instance;
21 use value::Value;
22
23 use monomorphize::partitioning::CodegenUnit;
24 use type_::Type;
25 use type_of::PointeeInfo;
26 use interfaces::*;
27
28 use rustc_data_structures::base_n;
29 use rustc_data_structures::small_c_str::SmallCStr;
30 use rustc::mir::mono::Stats;
31 use rustc::session::config::{self, DebugInfo};
32 use rustc::session::Session;
33 use rustc::ty::layout::{LayoutError, LayoutOf, Size, TyLayout, VariantIdx};
34 use rustc::ty::{self, Ty, TyCtxt};
35 use rustc::util::nodemap::FxHashMap;
36 use rustc_target::spec::{HasTargetSpec, Target};
37
38 use std::ffi::CStr;
39 use std::cell::{Cell, RefCell};
40 use std::iter;
41 use std::str;
42 use std::sync::Arc;
43 use syntax::symbol::LocalInternedString;
44 use abi::Abi;
45
46 /// There is one `CodegenCx` per compilation unit. Each one has its own LLVM
47 /// `llvm::Context` so that several compilation units may be optimized in parallel.
48 /// All other LLVM data structures in the `CodegenCx` are tied to that `llvm::Context`.
49 pub struct CodegenCx<'a, 'tcx: 'a, V = &'a Value> {
50     pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
51     pub check_overflow: bool,
52     pub use_dll_storage_attrs: bool,
53     pub tls_model: llvm::ThreadLocalMode,
54
55     pub llmod: &'a llvm::Module,
56     pub llcx: &'a llvm::Context,
57     pub stats: RefCell<Stats>,
58     pub codegen_unit: Arc<CodegenUnit<'tcx>>,
59
60     /// Cache instances of monomorphic and polymorphic items
61     pub instances: RefCell<FxHashMap<Instance<'tcx>, V>>,
62     /// Cache generated vtables
63     pub vtables: RefCell<FxHashMap<(Ty<'tcx>, ty::PolyExistentialTraitRef<'tcx>), V>>,
64     /// Cache of constant strings,
65     pub const_cstr_cache: RefCell<FxHashMap<LocalInternedString, V>>,
66
67     /// Reverse-direction for const ptrs cast from globals.
68     /// Key is a Value holding a *T,
69     /// Val is a Value holding a *[T].
70     ///
71     /// Needed because LLVM loses pointer->pointee association
72     /// when we ptrcast, and we have to ptrcast during codegen
73     /// of a [T] const because we form a slice, a (*T,usize) pair, not
74     /// a pointer to an LLVM array type. Similar for trait objects.
75     pub const_unsized: RefCell<FxHashMap<V, V>>,
76
77     /// Cache of emitted const globals (value -> global)
78     pub const_globals: RefCell<FxHashMap<V, V>>,
79
80     /// List of globals for static variables which need to be passed to the
81     /// LLVM function ReplaceAllUsesWith (RAUW) when codegen is complete.
82     /// (We have to make sure we don't invalidate any Values referring
83     /// to constants.)
84     pub statics_to_rauw: RefCell<Vec<(V, V)>>,
85
86     /// Statics that will be placed in the llvm.used variable
87     /// See http://llvm.org/docs/LangRef.html#the-llvm-used-global-variable for details
88     pub used_statics: RefCell<Vec<V>>,
89
90     pub lltypes: RefCell<FxHashMap<(Ty<'tcx>, Option<VariantIdx>), &'a Type>>,
91     pub scalar_lltypes: RefCell<FxHashMap<Ty<'tcx>, &'a Type>>,
92     pub pointee_infos: RefCell<FxHashMap<(Ty<'tcx>, Size), Option<PointeeInfo>>>,
93     pub isize_ty: &'a Type,
94
95     pub dbg_cx: Option<debuginfo::CrateDebugContext<'a, 'tcx>>,
96
97     eh_personality: Cell<Option<V>>,
98     eh_unwind_resume: Cell<Option<V>>,
99     pub rust_try_fn: Cell<Option<V>>,
100
101     intrinsics: RefCell<FxHashMap<&'static str, V>>,
102
103     /// A counter that is used for generating local symbol names
104     local_gen_sym_counter: Cell<usize>,
105 }
106
107 impl<'a, 'tcx> DepGraphSafe for CodegenCx<'a, 'tcx> {
108 }
109
110 pub fn get_reloc_model(sess: &Session) -> llvm::RelocMode {
111     let reloc_model_arg = match sess.opts.cg.relocation_model {
112         Some(ref s) => &s[..],
113         None => &sess.target.target.options.relocation_model[..],
114     };
115
116     match ::back::write::RELOC_MODEL_ARGS.iter().find(
117         |&&arg| arg.0 == reloc_model_arg) {
118         Some(x) => x.1,
119         _ => {
120             sess.err(&format!("{:?} is not a valid relocation mode",
121                               reloc_model_arg));
122             sess.abort_if_errors();
123             bug!();
124         }
125     }
126 }
127
128 fn get_tls_model(sess: &Session) -> llvm::ThreadLocalMode {
129     let tls_model_arg = match sess.opts.debugging_opts.tls_model {
130         Some(ref s) => &s[..],
131         None => &sess.target.target.options.tls_model[..],
132     };
133
134     match ::back::write::TLS_MODEL_ARGS.iter().find(
135         |&&arg| arg.0 == tls_model_arg) {
136         Some(x) => x.1,
137         _ => {
138             sess.err(&format!("{:?} is not a valid TLS model",
139                               tls_model_arg));
140             sess.abort_if_errors();
141             bug!();
142         }
143     }
144 }
145
146 fn is_any_library(sess: &Session) -> bool {
147     sess.crate_types.borrow().iter().any(|ty| {
148         *ty != config::CrateType::Executable
149     })
150 }
151
152 pub fn is_pie_binary(sess: &Session) -> bool {
153     !is_any_library(sess) && get_reloc_model(sess) == llvm::RelocMode::PIC
154 }
155
156 pub unsafe fn create_module(
157     sess: &Session,
158     llcx: &'ll llvm::Context,
159     mod_name: &str,
160 ) -> &'ll llvm::Module {
161     let mod_name = SmallCStr::new(mod_name);
162     let llmod = llvm::LLVMModuleCreateWithNameInContext(mod_name.as_ptr(), llcx);
163
164     // Ensure the data-layout values hardcoded remain the defaults.
165     if sess.target.target.options.is_builtin {
166         let tm = ::back::write::create_target_machine(sess, false);
167         llvm::LLVMRustSetDataLayoutFromTargetMachine(llmod, tm);
168         llvm::LLVMRustDisposeTargetMachine(tm);
169
170         let data_layout = llvm::LLVMGetDataLayout(llmod);
171         let data_layout = str::from_utf8(CStr::from_ptr(data_layout).to_bytes())
172             .ok().expect("got a non-UTF8 data-layout from LLVM");
173
174         // Unfortunately LLVM target specs change over time, and right now we
175         // don't have proper support to work with any more than one
176         // `data_layout` than the one that is in the rust-lang/rust repo. If
177         // this compiler is configured against a custom LLVM, we may have a
178         // differing data layout, even though we should update our own to use
179         // that one.
180         //
181         // As an interim hack, if CFG_LLVM_ROOT is not an empty string then we
182         // disable this check entirely as we may be configured with something
183         // that has a different target layout.
184         //
185         // Unsure if this will actually cause breakage when rustc is configured
186         // as such.
187         //
188         // FIXME(#34960)
189         let cfg_llvm_root = option_env!("CFG_LLVM_ROOT").unwrap_or("");
190         let custom_llvm_used = cfg_llvm_root.trim() != "";
191
192         if !custom_llvm_used && sess.target.target.data_layout != data_layout {
193             bug!("data-layout for builtin `{}` target, `{}`, \
194                   differs from LLVM default, `{}`",
195                  sess.target.target.llvm_target,
196                  sess.target.target.data_layout,
197                  data_layout);
198         }
199     }
200
201     let data_layout = SmallCStr::new(&sess.target.target.data_layout);
202     llvm::LLVMSetDataLayout(llmod, data_layout.as_ptr());
203
204     let llvm_target = SmallCStr::new(&sess.target.target.llvm_target);
205     llvm::LLVMRustSetNormalizedTarget(llmod, llvm_target.as_ptr());
206
207     if is_pie_binary(sess) {
208         llvm::LLVMRustSetModulePIELevel(llmod);
209     }
210
211     // If skipping the PLT is enabled, we need to add some module metadata
212     // to ensure intrinsic calls don't use it.
213     if !sess.needs_plt() {
214         let avoid_plt = "RtLibUseGOT\0".as_ptr() as *const _;
215         llvm::LLVMRustAddModuleFlag(llmod, avoid_plt, 1);
216     }
217
218     llmod
219 }
220
221 impl<'a, 'tcx> CodegenCx<'a, 'tcx> {
222     crate fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
223                  codegen_unit: Arc<CodegenUnit<'tcx>>,
224                  llvm_module: &'a ::ModuleLlvm)
225                  -> CodegenCx<'a, 'tcx> {
226         // An interesting part of Windows which MSVC forces our hand on (and
227         // apparently MinGW didn't) is the usage of `dllimport` and `dllexport`
228         // attributes in LLVM IR as well as native dependencies (in C these
229         // correspond to `__declspec(dllimport)`).
230         //
231         // Whenever a dynamic library is built by MSVC it must have its public
232         // interface specified by functions tagged with `dllexport` or otherwise
233         // they're not available to be linked against. This poses a few problems
234         // for the compiler, some of which are somewhat fundamental, but we use
235         // the `use_dll_storage_attrs` variable below to attach the `dllexport`
236         // attribute to all LLVM functions that are exported e.g. they're
237         // already tagged with external linkage). This is suboptimal for a few
238         // reasons:
239         //
240         // * If an object file will never be included in a dynamic library,
241         //   there's no need to attach the dllexport attribute. Most object
242         //   files in Rust are not destined to become part of a dll as binaries
243         //   are statically linked by default.
244         // * If the compiler is emitting both an rlib and a dylib, the same
245         //   source object file is currently used but with MSVC this may be less
246         //   feasible. The compiler may be able to get around this, but it may
247         //   involve some invasive changes to deal with this.
248         //
249         // The flipside of this situation is that whenever you link to a dll and
250         // you import a function from it, the import should be tagged with
251         // `dllimport`. At this time, however, the compiler does not emit
252         // `dllimport` for any declarations other than constants (where it is
253         // required), which is again suboptimal for even more reasons!
254         //
255         // * Calling a function imported from another dll without using
256         //   `dllimport` causes the linker/compiler to have extra overhead (one
257         //   `jmp` instruction on x86) when calling the function.
258         // * The same object file may be used in different circumstances, so a
259         //   function may be imported from a dll if the object is linked into a
260         //   dll, but it may be just linked against if linked into an rlib.
261         // * The compiler has no knowledge about whether native functions should
262         //   be tagged dllimport or not.
263         //
264         // For now the compiler takes the perf hit (I do not have any numbers to
265         // this effect) by marking very little as `dllimport` and praying the
266         // linker will take care of everything. Fixing this problem will likely
267         // require adding a few attributes to Rust itself (feature gated at the
268         // start) and then strongly recommending static linkage on MSVC!
269         let use_dll_storage_attrs = tcx.sess.target.target.options.is_like_msvc;
270
271         let check_overflow = tcx.sess.overflow_checks();
272
273         let tls_model = get_tls_model(&tcx.sess);
274
275         let (llcx, llmod) = (&*llvm_module.llcx, llvm_module.llmod());
276
277         let dbg_cx = if tcx.sess.opts.debuginfo != DebugInfo::None {
278             let dctx = debuginfo::CrateDebugContext::new(llmod);
279             debuginfo::metadata::compile_unit_metadata(tcx,
280                                                        &codegen_unit.name().as_str(),
281                                                        &dctx);
282             Some(dctx)
283         } else {
284             None
285         };
286
287         let isize_ty = Type::ix_llcx(llcx, tcx.data_layout.pointer_size.bits());
288
289         CodegenCx {
290             tcx,
291             check_overflow,
292             use_dll_storage_attrs,
293             tls_model,
294             llmod,
295             llcx,
296             stats: RefCell::new(Stats::default()),
297             codegen_unit,
298             instances: Default::default(),
299             vtables: Default::default(),
300             const_cstr_cache: Default::default(),
301             const_unsized: Default::default(),
302             const_globals: Default::default(),
303             statics_to_rauw: RefCell::new(Vec::new()),
304             used_statics: RefCell::new(Vec::new()),
305             lltypes: Default::default(),
306             scalar_lltypes: Default::default(),
307             pointee_infos: Default::default(),
308             isize_ty,
309             dbg_cx,
310             eh_personality: Cell::new(None),
311             eh_unwind_resume: Cell::new(None),
312             rust_try_fn: Cell::new(None),
313             intrinsics: Default::default(),
314             local_gen_sym_counter: Cell::new(0),
315         }
316     }
317 }
318
319 impl<'b, 'tcx> CodegenCx<'b, 'tcx> {
320     pub fn sess<'a>(&'a self) -> &'a Session {
321         &self.tcx.sess
322     }
323 }
324
325 impl MiscMethods<'tcx> for CodegenCx<'ll, 'tcx> {
326     fn vtables(&self) -> &RefCell<FxHashMap<(Ty<'tcx>,
327                                 ty::PolyExistentialTraitRef<'tcx>), &'ll Value>>
328     {
329         &self.vtables
330     }
331     fn get_fn(&self, instance: Instance<'tcx>) -> &'ll Value {
332         callee::get_fn(&&self,instance)
333     }
334 }
335
336 impl IntrinsicDeclarationMethods<'tcx> for CodegenCx<'b, 'tcx> {
337     fn get_intrinsic(&self, key: &str) -> &'b Value {
338         if let Some(v) = self.intrinsics.borrow().get(key).cloned() {
339             return v;
340         }
341
342         self.declare_intrinsic(key).unwrap_or_else(|| bug!("unknown intrinsic '{}'", key))
343     }
344
345     /// Declare any llvm intrinsics that you might need
346     fn declare_intrinsic(
347         &self,
348         key: &str
349     ) -> Option<&'b Value> {
350         macro_rules! ifn {
351             ($name:expr, fn() -> $ret:expr) => (
352                 if key == $name {
353                     let f = declare::declare_cfn(&self, $name, self.type_func(&[], $ret));
354                     llvm::SetUnnamedAddr(f, false);
355                     self.intrinsics.borrow_mut().insert($name, f.clone());
356                     return Some(f);
357                 }
358             );
359             ($name:expr, fn(...) -> $ret:expr) => (
360                 if key == $name {
361                     let f = declare::declare_cfn(&self, $name, self.type_variadic_func(&[], $ret));
362                     llvm::SetUnnamedAddr(f, false);
363                     self.intrinsics.borrow_mut().insert($name, f.clone());
364                     return Some(f);
365                 }
366             );
367             ($name:expr, fn($($arg:expr),*) -> $ret:expr) => (
368                 if key == $name {
369                     let f = declare::declare_cfn(&self, $name, self.type_func(&[$($arg),*], $ret));
370                     llvm::SetUnnamedAddr(f, false);
371                     self.intrinsics.borrow_mut().insert($name, f.clone());
372                     return Some(f);
373                 }
374             );
375         }
376         macro_rules! mk_struct {
377             ($($field_ty:expr),*) => (self.type_struct( &[$($field_ty),*], false))
378         }
379
380         let i8p = self.type_i8p();
381         let void = self.type_void();
382         let i1 = self.type_i1();
383         let t_i8 = self.type_i8();
384         let t_i16 = self.type_i16();
385         let t_i32 = self.type_i32();
386         let t_i64 = self.type_i64();
387         let t_i128 = self.type_i128();
388         let t_f32 = self.type_f32();
389         let t_f64 = self.type_f64();
390
391         let t_v2f32 = self.type_vector(t_f32, 2);
392         let t_v4f32 = self.type_vector(t_f32, 4);
393         let t_v8f32 = self.type_vector(t_f32, 8);
394         let t_v16f32 = self.type_vector(t_f32, 16);
395
396         let t_v2f64 = self.type_vector(t_f64, 2);
397         let t_v4f64 = self.type_vector(t_f64, 4);
398         let t_v8f64 = self.type_vector(t_f64, 8);
399
400         ifn!("llvm.memset.p0i8.i16", fn(i8p, t_i8, t_i16, t_i32, i1) -> void);
401         ifn!("llvm.memset.p0i8.i32", fn(i8p, t_i8, t_i32, t_i32, i1) -> void);
402         ifn!("llvm.memset.p0i8.i64", fn(i8p, t_i8, t_i64, t_i32, i1) -> void);
403
404         ifn!("llvm.trap", fn() -> void);
405         ifn!("llvm.debugtrap", fn() -> void);
406         ifn!("llvm.frameaddress", fn(t_i32) -> i8p);
407
408         ifn!("llvm.powi.f32", fn(t_f32, t_i32) -> t_f32);
409         ifn!("llvm.powi.v2f32", fn(t_v2f32, t_i32) -> t_v2f32);
410         ifn!("llvm.powi.v4f32", fn(t_v4f32, t_i32) -> t_v4f32);
411         ifn!("llvm.powi.v8f32", fn(t_v8f32, t_i32) -> t_v8f32);
412         ifn!("llvm.powi.v16f32", fn(t_v16f32, t_i32) -> t_v16f32);
413         ifn!("llvm.powi.f64", fn(t_f64, t_i32) -> t_f64);
414         ifn!("llvm.powi.v2f64", fn(t_v2f64, t_i32) -> t_v2f64);
415         ifn!("llvm.powi.v4f64", fn(t_v4f64, t_i32) -> t_v4f64);
416         ifn!("llvm.powi.v8f64", fn(t_v8f64, t_i32) -> t_v8f64);
417
418         ifn!("llvm.pow.f32", fn(t_f32, t_f32) -> t_f32);
419         ifn!("llvm.pow.v2f32", fn(t_v2f32, t_v2f32) -> t_v2f32);
420         ifn!("llvm.pow.v4f32", fn(t_v4f32, t_v4f32) -> t_v4f32);
421         ifn!("llvm.pow.v8f32", fn(t_v8f32, t_v8f32) -> t_v8f32);
422         ifn!("llvm.pow.v16f32", fn(t_v16f32, t_v16f32) -> t_v16f32);
423         ifn!("llvm.pow.f64", fn(t_f64, t_f64) -> t_f64);
424         ifn!("llvm.pow.v2f64", fn(t_v2f64, t_v2f64) -> t_v2f64);
425         ifn!("llvm.pow.v4f64", fn(t_v4f64, t_v4f64) -> t_v4f64);
426         ifn!("llvm.pow.v8f64", fn(t_v8f64, t_v8f64) -> t_v8f64);
427
428         ifn!("llvm.sqrt.f32", fn(t_f32) -> t_f32);
429         ifn!("llvm.sqrt.v2f32", fn(t_v2f32) -> t_v2f32);
430         ifn!("llvm.sqrt.v4f32", fn(t_v4f32) -> t_v4f32);
431         ifn!("llvm.sqrt.v8f32", fn(t_v8f32) -> t_v8f32);
432         ifn!("llvm.sqrt.v16f32", fn(t_v16f32) -> t_v16f32);
433         ifn!("llvm.sqrt.f64", fn(t_f64) -> t_f64);
434         ifn!("llvm.sqrt.v2f64", fn(t_v2f64) -> t_v2f64);
435         ifn!("llvm.sqrt.v4f64", fn(t_v4f64) -> t_v4f64);
436         ifn!("llvm.sqrt.v8f64", fn(t_v8f64) -> t_v8f64);
437
438         ifn!("llvm.sin.f32", fn(t_f32) -> t_f32);
439         ifn!("llvm.sin.v2f32", fn(t_v2f32) -> t_v2f32);
440         ifn!("llvm.sin.v4f32", fn(t_v4f32) -> t_v4f32);
441         ifn!("llvm.sin.v8f32", fn(t_v8f32) -> t_v8f32);
442         ifn!("llvm.sin.v16f32", fn(t_v16f32) -> t_v16f32);
443         ifn!("llvm.sin.f64", fn(t_f64) -> t_f64);
444         ifn!("llvm.sin.v2f64", fn(t_v2f64) -> t_v2f64);
445         ifn!("llvm.sin.v4f64", fn(t_v4f64) -> t_v4f64);
446         ifn!("llvm.sin.v8f64", fn(t_v8f64) -> t_v8f64);
447
448         ifn!("llvm.cos.f32", fn(t_f32) -> t_f32);
449         ifn!("llvm.cos.v2f32", fn(t_v2f32) -> t_v2f32);
450         ifn!("llvm.cos.v4f32", fn(t_v4f32) -> t_v4f32);
451         ifn!("llvm.cos.v8f32", fn(t_v8f32) -> t_v8f32);
452         ifn!("llvm.cos.v16f32", fn(t_v16f32) -> t_v16f32);
453         ifn!("llvm.cos.f64", fn(t_f64) -> t_f64);
454         ifn!("llvm.cos.v2f64", fn(t_v2f64) -> t_v2f64);
455         ifn!("llvm.cos.v4f64", fn(t_v4f64) -> t_v4f64);
456         ifn!("llvm.cos.v8f64", fn(t_v8f64) -> t_v8f64);
457
458         ifn!("llvm.exp.f32", fn(t_f32) -> t_f32);
459         ifn!("llvm.exp.v2f32", fn(t_v2f32) -> t_v2f32);
460         ifn!("llvm.exp.v4f32", fn(t_v4f32) -> t_v4f32);
461         ifn!("llvm.exp.v8f32", fn(t_v8f32) -> t_v8f32);
462         ifn!("llvm.exp.v16f32", fn(t_v16f32) -> t_v16f32);
463         ifn!("llvm.exp.f64", fn(t_f64) -> t_f64);
464         ifn!("llvm.exp.v2f64", fn(t_v2f64) -> t_v2f64);
465         ifn!("llvm.exp.v4f64", fn(t_v4f64) -> t_v4f64);
466         ifn!("llvm.exp.v8f64", fn(t_v8f64) -> t_v8f64);
467
468         ifn!("llvm.exp2.f32", fn(t_f32) -> t_f32);
469         ifn!("llvm.exp2.v2f32", fn(t_v2f32) -> t_v2f32);
470         ifn!("llvm.exp2.v4f32", fn(t_v4f32) -> t_v4f32);
471         ifn!("llvm.exp2.v8f32", fn(t_v8f32) -> t_v8f32);
472         ifn!("llvm.exp2.v16f32", fn(t_v16f32) -> t_v16f32);
473         ifn!("llvm.exp2.f64", fn(t_f64) -> t_f64);
474         ifn!("llvm.exp2.v2f64", fn(t_v2f64) -> t_v2f64);
475         ifn!("llvm.exp2.v4f64", fn(t_v4f64) -> t_v4f64);
476         ifn!("llvm.exp2.v8f64", fn(t_v8f64) -> t_v8f64);
477
478         ifn!("llvm.log.f32", fn(t_f32) -> t_f32);
479         ifn!("llvm.log.v2f32", fn(t_v2f32) -> t_v2f32);
480         ifn!("llvm.log.v4f32", fn(t_v4f32) -> t_v4f32);
481         ifn!("llvm.log.v8f32", fn(t_v8f32) -> t_v8f32);
482         ifn!("llvm.log.v16f32", fn(t_v16f32) -> t_v16f32);
483         ifn!("llvm.log.f64", fn(t_f64) -> t_f64);
484         ifn!("llvm.log.v2f64", fn(t_v2f64) -> t_v2f64);
485         ifn!("llvm.log.v4f64", fn(t_v4f64) -> t_v4f64);
486         ifn!("llvm.log.v8f64", fn(t_v8f64) -> t_v8f64);
487
488         ifn!("llvm.log10.f32", fn(t_f32) -> t_f32);
489         ifn!("llvm.log10.v2f32", fn(t_v2f32) -> t_v2f32);
490         ifn!("llvm.log10.v4f32", fn(t_v4f32) -> t_v4f32);
491         ifn!("llvm.log10.v8f32", fn(t_v8f32) -> t_v8f32);
492         ifn!("llvm.log10.v16f32", fn(t_v16f32) -> t_v16f32);
493         ifn!("llvm.log10.f64", fn(t_f64) -> t_f64);
494         ifn!("llvm.log10.v2f64", fn(t_v2f64) -> t_v2f64);
495         ifn!("llvm.log10.v4f64", fn(t_v4f64) -> t_v4f64);
496         ifn!("llvm.log10.v8f64", fn(t_v8f64) -> t_v8f64);
497
498         ifn!("llvm.log2.f32", fn(t_f32) -> t_f32);
499         ifn!("llvm.log2.v2f32", fn(t_v2f32) -> t_v2f32);
500         ifn!("llvm.log2.v4f32", fn(t_v4f32) -> t_v4f32);
501         ifn!("llvm.log2.v8f32", fn(t_v8f32) -> t_v8f32);
502         ifn!("llvm.log2.v16f32", fn(t_v16f32) -> t_v16f32);
503         ifn!("llvm.log2.f64", fn(t_f64) -> t_f64);
504         ifn!("llvm.log2.v2f64", fn(t_v2f64) -> t_v2f64);
505         ifn!("llvm.log2.v4f64", fn(t_v4f64) -> t_v4f64);
506         ifn!("llvm.log2.v8f64", fn(t_v8f64) -> t_v8f64);
507
508         ifn!("llvm.fma.f32", fn(t_f32, t_f32, t_f32) -> t_f32);
509         ifn!("llvm.fma.v2f32", fn(t_v2f32, t_v2f32, t_v2f32) -> t_v2f32);
510         ifn!("llvm.fma.v4f32", fn(t_v4f32, t_v4f32, t_v4f32) -> t_v4f32);
511         ifn!("llvm.fma.v8f32", fn(t_v8f32, t_v8f32, t_v8f32) -> t_v8f32);
512         ifn!("llvm.fma.v16f32", fn(t_v16f32, t_v16f32, t_v16f32) -> t_v16f32);
513         ifn!("llvm.fma.f64", fn(t_f64, t_f64, t_f64) -> t_f64);
514         ifn!("llvm.fma.v2f64", fn(t_v2f64, t_v2f64, t_v2f64) -> t_v2f64);
515         ifn!("llvm.fma.v4f64", fn(t_v4f64, t_v4f64, t_v4f64) -> t_v4f64);
516         ifn!("llvm.fma.v8f64", fn(t_v8f64, t_v8f64, t_v8f64) -> t_v8f64);
517
518         ifn!("llvm.fabs.f32", fn(t_f32) -> t_f32);
519         ifn!("llvm.fabs.v2f32", fn(t_v2f32) -> t_v2f32);
520         ifn!("llvm.fabs.v4f32", fn(t_v4f32) -> t_v4f32);
521         ifn!("llvm.fabs.v8f32", fn(t_v8f32) -> t_v8f32);
522         ifn!("llvm.fabs.v16f32", fn(t_v16f32) -> t_v16f32);
523         ifn!("llvm.fabs.f64", fn(t_f64) -> t_f64);
524         ifn!("llvm.fabs.v2f64", fn(t_v2f64) -> t_v2f64);
525         ifn!("llvm.fabs.v4f64", fn(t_v4f64) -> t_v4f64);
526         ifn!("llvm.fabs.v8f64", fn(t_v8f64) -> t_v8f64);
527
528         ifn!("llvm.floor.f32", fn(t_f32) -> t_f32);
529         ifn!("llvm.floor.v2f32", fn(t_v2f32) -> t_v2f32);
530         ifn!("llvm.floor.v4f32", fn(t_v4f32) -> t_v4f32);
531         ifn!("llvm.floor.v8f32", fn(t_v8f32) -> t_v8f32);
532         ifn!("llvm.floor.v16f32", fn(t_v16f32) -> t_v16f32);
533         ifn!("llvm.floor.f64", fn(t_f64) -> t_f64);
534         ifn!("llvm.floor.v2f64", fn(t_v2f64) -> t_v2f64);
535         ifn!("llvm.floor.v4f64", fn(t_v4f64) -> t_v4f64);
536         ifn!("llvm.floor.v8f64", fn(t_v8f64) -> t_v8f64);
537
538         ifn!("llvm.ceil.f32", fn(t_f32) -> t_f32);
539         ifn!("llvm.ceil.v2f32", fn(t_v2f32) -> t_v2f32);
540         ifn!("llvm.ceil.v4f32", fn(t_v4f32) -> t_v4f32);
541         ifn!("llvm.ceil.v8f32", fn(t_v8f32) -> t_v8f32);
542         ifn!("llvm.ceil.v16f32", fn(t_v16f32) -> t_v16f32);
543         ifn!("llvm.ceil.f64", fn(t_f64) -> t_f64);
544         ifn!("llvm.ceil.v2f64", fn(t_v2f64) -> t_v2f64);
545         ifn!("llvm.ceil.v4f64", fn(t_v4f64) -> t_v4f64);
546         ifn!("llvm.ceil.v8f64", fn(t_v8f64) -> t_v8f64);
547
548         ifn!("llvm.trunc.f32", fn(t_f32) -> t_f32);
549         ifn!("llvm.trunc.f64", fn(t_f64) -> t_f64);
550
551         ifn!("llvm.copysign.f32", fn(t_f32, t_f32) -> t_f32);
552         ifn!("llvm.copysign.f64", fn(t_f64, t_f64) -> t_f64);
553         ifn!("llvm.round.f32", fn(t_f32) -> t_f32);
554         ifn!("llvm.round.f64", fn(t_f64) -> t_f64);
555
556         ifn!("llvm.rint.f32", fn(t_f32) -> t_f32);
557         ifn!("llvm.rint.f64", fn(t_f64) -> t_f64);
558         ifn!("llvm.nearbyint.f32", fn(t_f32) -> t_f32);
559         ifn!("llvm.nearbyint.f64", fn(t_f64) -> t_f64);
560
561         ifn!("llvm.ctpop.i8", fn(t_i8) -> t_i8);
562         ifn!("llvm.ctpop.i16", fn(t_i16) -> t_i16);
563         ifn!("llvm.ctpop.i32", fn(t_i32) -> t_i32);
564         ifn!("llvm.ctpop.i64", fn(t_i64) -> t_i64);
565         ifn!("llvm.ctpop.i128", fn(t_i128) -> t_i128);
566
567         ifn!("llvm.ctlz.i8", fn(t_i8 , i1) -> t_i8);
568         ifn!("llvm.ctlz.i16", fn(t_i16, i1) -> t_i16);
569         ifn!("llvm.ctlz.i32", fn(t_i32, i1) -> t_i32);
570         ifn!("llvm.ctlz.i64", fn(t_i64, i1) -> t_i64);
571         ifn!("llvm.ctlz.i128", fn(t_i128, i1) -> t_i128);
572
573         ifn!("llvm.cttz.i8", fn(t_i8 , i1) -> t_i8);
574         ifn!("llvm.cttz.i16", fn(t_i16, i1) -> t_i16);
575         ifn!("llvm.cttz.i32", fn(t_i32, i1) -> t_i32);
576         ifn!("llvm.cttz.i64", fn(t_i64, i1) -> t_i64);
577         ifn!("llvm.cttz.i128", fn(t_i128, i1) -> t_i128);
578
579         ifn!("llvm.bswap.i16", fn(t_i16) -> t_i16);
580         ifn!("llvm.bswap.i32", fn(t_i32) -> t_i32);
581         ifn!("llvm.bswap.i64", fn(t_i64) -> t_i64);
582         ifn!("llvm.bswap.i128", fn(t_i128) -> t_i128);
583
584         ifn!("llvm.bitreverse.i8", fn(t_i8) -> t_i8);
585         ifn!("llvm.bitreverse.i16", fn(t_i16) -> t_i16);
586         ifn!("llvm.bitreverse.i32", fn(t_i32) -> t_i32);
587         ifn!("llvm.bitreverse.i64", fn(t_i64) -> t_i64);
588         ifn!("llvm.bitreverse.i128", fn(t_i128) -> t_i128);
589
590     ifn!("llvm.fshl.i8", fn(t_i8, t_i8, t_i8) -> t_i8);
591     ifn!("llvm.fshl.i16", fn(t_i16, t_i16, t_i16) -> t_i16);
592     ifn!("llvm.fshl.i32", fn(t_i32, t_i32, t_i32) -> t_i32);
593     ifn!("llvm.fshl.i64", fn(t_i64, t_i64, t_i64) -> t_i64);
594     ifn!("llvm.fshl.i128", fn(t_i128, t_i128, t_i128) -> t_i128);
595
596     ifn!("llvm.fshr.i8", fn(t_i8, t_i8, t_i8) -> t_i8);
597     ifn!("llvm.fshr.i16", fn(t_i16, t_i16, t_i16) -> t_i16);
598     ifn!("llvm.fshr.i32", fn(t_i32, t_i32, t_i32) -> t_i32);
599     ifn!("llvm.fshr.i64", fn(t_i64, t_i64, t_i64) -> t_i64);
600     ifn!("llvm.fshr.i128", fn(t_i128, t_i128, t_i128) -> t_i128);
601
602         ifn!("llvm.sadd.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
603         ifn!("llvm.sadd.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
604         ifn!("llvm.sadd.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
605         ifn!("llvm.sadd.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
606         ifn!("llvm.sadd.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1});
607
608         ifn!("llvm.uadd.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
609         ifn!("llvm.uadd.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
610         ifn!("llvm.uadd.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
611         ifn!("llvm.uadd.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
612         ifn!("llvm.uadd.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1});
613
614         ifn!("llvm.ssub.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
615         ifn!("llvm.ssub.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
616         ifn!("llvm.ssub.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
617         ifn!("llvm.ssub.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
618         ifn!("llvm.ssub.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1});
619
620         ifn!("llvm.usub.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
621         ifn!("llvm.usub.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
622         ifn!("llvm.usub.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
623         ifn!("llvm.usub.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
624         ifn!("llvm.usub.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1});
625
626         ifn!("llvm.smul.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
627         ifn!("llvm.smul.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
628         ifn!("llvm.smul.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
629         ifn!("llvm.smul.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
630         ifn!("llvm.smul.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1});
631
632         ifn!("llvm.umul.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
633         ifn!("llvm.umul.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
634         ifn!("llvm.umul.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
635         ifn!("llvm.umul.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
636         ifn!("llvm.umul.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1});
637
638         ifn!("llvm.lifetime.start", fn(t_i64,i8p) -> void);
639         ifn!("llvm.lifetime.end", fn(t_i64, i8p) -> void);
640
641         ifn!("llvm.expect.i1", fn(i1, i1) -> i1);
642         ifn!("llvm.eh.typeid.for", fn(i8p) -> t_i32);
643         ifn!("llvm.localescape", fn(...) -> void);
644         ifn!("llvm.localrecover", fn(i8p, i8p, t_i32) -> i8p);
645         ifn!("llvm.x86.seh.recoverfp", fn(i8p, i8p) -> i8p);
646
647         ifn!("llvm.assume", fn(i1) -> void);
648         ifn!("llvm.prefetch", fn(i8p, t_i32, t_i32, t_i32) -> void);
649
650         if self.sess().opts.debuginfo != DebugInfo::None {
651             ifn!("llvm.dbg.declare", fn(self.type_metadata(), self.type_metadata()) -> void);
652             ifn!("llvm.dbg.value", fn(self.type_metadata(), t_i64, self.type_metadata()) -> void);
653         }
654         return None;
655     }
656 }
657
658 impl<'b, 'tcx> CodegenCx<'b, 'tcx> {
659     /// Generate a new symbol name with the given prefix. This symbol name must
660     /// only be used for definitions with `internal` or `private` linkage.
661     pub fn generate_local_symbol_name(&self, prefix: &str) -> String {
662         let idx = self.local_gen_sym_counter.get();
663         self.local_gen_sym_counter.set(idx + 1);
664         // Include a '.' character, so there can be no accidental conflicts with
665         // user defined names
666         let mut name = String::with_capacity(prefix.len() + 6);
667         name.push_str(prefix);
668         name.push_str(".");
669         base_n::push_str(idx as u128, base_n::ALPHANUMERIC_ONLY, &mut name);
670         name
671     }
672
673     pub fn eh_personality(&self) -> &'b Value {
674         // The exception handling personality function.
675         //
676         // If our compilation unit has the `eh_personality` lang item somewhere
677         // within it, then we just need to codegen that. Otherwise, we're
678         // building an rlib which will depend on some upstream implementation of
679         // this function, so we just codegen a generic reference to it. We don't
680         // specify any of the types for the function, we just make it a symbol
681         // that LLVM can later use.
682         //
683         // Note that MSVC is a little special here in that we don't use the
684         // `eh_personality` lang item at all. Currently LLVM has support for
685         // both Dwarf and SEH unwind mechanisms for MSVC targets and uses the
686         // *name of the personality function* to decide what kind of unwind side
687         // tables/landing pads to emit. It looks like Dwarf is used by default,
688         // injecting a dependency on the `_Unwind_Resume` symbol for resuming
689         // an "exception", but for MSVC we want to force SEH. This means that we
690         // can't actually have the personality function be our standard
691         // `rust_eh_personality` function, but rather we wired it up to the
692         // CRT's custom personality function, which forces LLVM to consider
693         // landing pads as "landing pads for SEH".
694         if let Some(llpersonality) = self.eh_personality.get() {
695             return llpersonality
696         }
697         let tcx = self.tcx;
698         let llfn = match tcx.lang_items().eh_personality() {
699             Some(def_id) if !base::wants_msvc_seh(self.sess()) => {
700                 callee::resolve_and_get_fn(self, def_id, tcx.intern_substs(&[]))
701             }
702             _ => {
703                 let name = if base::wants_msvc_seh(self.sess()) {
704                     "__CxxFrameHandler3"
705                 } else {
706                     "rust_eh_personality"
707                 };
708                 let fty = self.type_variadic_func(&[], self.type_i32());
709                 declare::declare_cfn(self, name, fty)
710             }
711         };
712         attributes::apply_target_cpu_attr(self, llfn);
713         self.eh_personality.set(Some(llfn));
714         llfn
715     }
716
717     // Returns a Value of the "eh_unwind_resume" lang item if one is defined,
718     // otherwise declares it as an external function.
719     pub fn eh_unwind_resume(&self) -> &'b Value {
720         use attributes;
721         let unwresume = &self.eh_unwind_resume;
722         if let Some(llfn) = unwresume.get() {
723             return llfn;
724         }
725
726         let tcx = self.tcx;
727         assert!(self.sess().target.target.options.custom_unwind_resume);
728         if let Some(def_id) = tcx.lang_items().eh_unwind_resume() {
729             let llfn = callee::resolve_and_get_fn(self, def_id, tcx.intern_substs(&[]));
730             unwresume.set(Some(llfn));
731             return llfn;
732         }
733
734         let sig = ty::Binder::bind(tcx.mk_fn_sig(
735             iter::once(tcx.mk_mut_ptr(tcx.types.u8)),
736             tcx.types.never,
737             false,
738             hir::Unsafety::Unsafe,
739             Abi::C
740         ));
741
742         let llfn = declare::declare_fn(self, "rust_eh_unwind_resume", sig);
743         attributes::unwind(llfn, true);
744         attributes::apply_target_cpu_attr(self, llfn);
745         unwresume.set(Some(llfn));
746         llfn
747     }
748
749     pub fn type_needs_drop(&self, ty: Ty<'tcx>) -> bool {
750         common::type_needs_drop(self.tcx, ty)
751     }
752
753     pub fn type_is_sized(&self, ty: Ty<'tcx>) -> bool {
754         common::type_is_sized(self.tcx, ty)
755     }
756
757     pub fn type_is_freeze(&self, ty: Ty<'tcx>) -> bool {
758         common::type_is_freeze(self.tcx, ty)
759     }
760
761     pub fn type_has_metadata(&self, ty: Ty<'tcx>) -> bool {
762         use syntax_pos::DUMMY_SP;
763         if ty.is_sized(self.tcx.at(DUMMY_SP), ty::ParamEnv::reveal_all()) {
764             return false;
765         }
766
767         let tail = self.tcx.struct_tail(ty);
768         match tail.sty {
769             ty::Foreign(..) => false,
770             ty::Str | ty::Slice(..) | ty::Dynamic(..) => true,
771             _ => bug!("unexpected unsized tail: {:?}", tail.sty),
772         }
773     }
774 }
775
776 impl ty::layout::HasDataLayout for CodegenCx<'ll, 'tcx> {
777     fn data_layout(&self) -> &ty::layout::TargetDataLayout {
778         &self.tcx.data_layout
779     }
780 }
781
782 impl HasTargetSpec for CodegenCx<'ll, 'tcx> {
783     fn target_spec(&self) -> &Target {
784         &self.tcx.sess.target.target
785     }
786 }
787
788 impl ty::layout::HasTyCtxt<'tcx> for CodegenCx<'ll, 'tcx> {
789     fn tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> {
790         self.tcx
791     }
792 }
793
794 impl LayoutOf for CodegenCx<'ll, 'tcx> {
795     type Ty = Ty<'tcx>;
796     type TyLayout = TyLayout<'tcx>;
797
798     fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyLayout {
799         self.tcx.layout_of(ty::ParamEnv::reveal_all().and(ty))
800             .unwrap_or_else(|e| if let LayoutError::SizeOverflow(_) = e {
801                 self.sess().fatal(&e.to_string())
802             } else {
803                 bug!("failed to get layout for `{}`: {}", ty, e)
804             })
805     }
806 }