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