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