1use std::borrow::{Borrow, Cow};
2use std::cell::{Cell, RefCell};
3use std::ffi::{CStr, c_char, c_uint};
4use std::marker::PhantomData;
5use std::ops::{Deref, DerefMut};
6use std::str;
7
8use rustc_abi::{HasDataLayout, Size, TargetDataLayout, VariantIdx};
9use rustc_codegen_ssa::back::versioned_llvm_target;
10use rustc_codegen_ssa::base::{wants_msvc_seh, wants_wasm_eh};
11use rustc_codegen_ssa::errors as ssa_errors;
12use rustc_codegen_ssa::traits::*;
13use rustc_data_structures::base_n::{ALPHANUMERIC_ONLY, ToBaseN};
14use rustc_data_structures::fx::FxHashMap;
15use rustc_data_structures::small_c_str::SmallCStr;
16use rustc_hir::def_id::DefId;
17use rustc_middle::middle::codegen_fn_attrs::PatchableFunctionEntry;
18use rustc_middle::mir::mono::CodegenUnit;
19use rustc_middle::ty::layout::{
20 FnAbiError, FnAbiOfHelpers, FnAbiRequest, HasTypingEnv, LayoutError, LayoutOfHelpers,
21};
22use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
23use rustc_middle::{bug, span_bug};
24use rustc_session::Session;
25use rustc_session::config::{
26 BranchProtection, CFGuard, CFProtection, CrateType, DebugInfo, FunctionReturn, PAuthKey, PacRet,
27};
28use rustc_span::source_map::Spanned;
29use rustc_span::{DUMMY_SP, Span, Symbol};
30use rustc_symbol_mangling::mangle_internal_symbol;
31use rustc_target::spec::{
32 Abi, Arch, Env, HasTargetSpec, Os, RelocModel, SmallDataThresholdSupport, Target, TlsModel,
33};
34use smallvec::SmallVec;
35
36use crate::abi::to_llvm_calling_convention;
37use crate::back::write::to_llvm_code_model;
38use crate::builder::gpu_offload::{OffloadGlobals, OffloadKernelGlobals};
39use crate::callee::get_fn;
40use crate::debuginfo::metadata::apply_vcall_visibility_metadata;
41use crate::llvm::{self, Metadata, MetadataKindId, Module, Type, Value};
42use crate::{attributes, common, coverageinfo, debuginfo, llvm_util};
43
44pub(crate) struct SCx<'ll> {
49 pub llmod: &'ll llvm::Module,
50 pub llcx: &'ll llvm::Context,
51 pub isize_ty: &'ll Type,
52}
53
54impl<'ll> Borrow<SCx<'ll>> for FullCx<'ll, '_> {
55 fn borrow(&self) -> &SCx<'ll> {
56 &self.scx
57 }
58}
59
60impl<'ll, 'tcx> Deref for FullCx<'ll, 'tcx> {
61 type Target = SimpleCx<'ll>;
62
63 #[inline]
64 fn deref(&self) -> &Self::Target {
65 &self.scx
66 }
67}
68
69pub(crate) struct GenericCx<'ll, T: Borrow<SCx<'ll>>>(T, PhantomData<SCx<'ll>>);
70
71impl<'ll, T: Borrow<SCx<'ll>>> Deref for GenericCx<'ll, T> {
72 type Target = T;
73
74 #[inline]
75 fn deref(&self) -> &Self::Target {
76 &self.0
77 }
78}
79
80impl<'ll, T: Borrow<SCx<'ll>>> DerefMut for GenericCx<'ll, T> {
81 #[inline]
82 fn deref_mut(&mut self) -> &mut Self::Target {
83 &mut self.0
84 }
85}
86
87pub(crate) type SimpleCx<'ll> = GenericCx<'ll, SCx<'ll>>;
88
89pub(crate) type CodegenCx<'ll, 'tcx> = GenericCx<'ll, FullCx<'ll, 'tcx>>;
93
94pub(crate) struct FullCx<'ll, 'tcx> {
95 pub tcx: TyCtxt<'tcx>,
96 pub scx: SimpleCx<'ll>,
97 pub use_dll_storage_attrs: bool,
98 pub tls_model: llvm::ThreadLocalMode,
99
100 pub codegen_unit: &'tcx CodegenUnit<'tcx>,
101
102 pub instances: RefCell<FxHashMap<Instance<'tcx>, &'ll Value>>,
104 pub intrinsic_instances: RefCell<FxHashMap<Instance<'tcx>, &'ll Value>>,
106 pub vtables: RefCell<FxHashMap<(Ty<'tcx>, Option<ty::ExistentialTraitRef<'tcx>>), &'ll Value>>,
108 pub const_str_cache: RefCell<FxHashMap<String, &'ll Value>>,
110
111 pub const_globals: RefCell<FxHashMap<&'ll Value, &'ll Value>>,
113
114 pub statics_to_rauw: RefCell<Vec<(&'ll Value, &'ll Value)>>,
119
120 pub used_statics: Vec<&'ll Value>,
123
124 pub compiler_used_statics: RefCell<Vec<&'ll Value>>,
127
128 pub type_lowering: RefCell<FxHashMap<(Ty<'tcx>, Option<VariantIdx>), &'ll Type>>,
130
131 pub scalar_lltypes: RefCell<FxHashMap<Ty<'tcx>, &'ll Type>>,
133
134 pub coverage_cx: Option<coverageinfo::CguCoverageContext<'ll, 'tcx>>,
136 pub dbg_cx: Option<debuginfo::CodegenUnitDebugContext<'ll, 'tcx>>,
137
138 eh_personality: Cell<Option<&'ll Value>>,
139 eh_catch_typeinfo: Cell<Option<&'ll Value>>,
140 pub rust_try_fn: Cell<Option<(&'ll Type, &'ll Value)>>,
141
142 intrinsics:
143 RefCell<FxHashMap<(Cow<'static, str>, SmallVec<[&'ll Type; 2]>), (&'ll Type, &'ll Value)>>,
144
145 local_gen_sym_counter: Cell<usize>,
147
148 pub renamed_statics: RefCell<FxHashMap<DefId, &'ll Value>>,
153
154 pub objc_class_t: Cell<Option<&'ll Type>>,
156
157 pub objc_classrefs: RefCell<FxHashMap<Symbol, &'ll Value>>,
159
160 pub objc_selrefs: RefCell<FxHashMap<Symbol, &'ll Value>>,
162
163 pub offload_globals: RefCell<Option<OffloadGlobals<'ll>>>,
165
166 pub offload_kernel_cache: RefCell<FxHashMap<String, OffloadKernelGlobals<'ll>>>,
168}
169
170fn to_llvm_tls_model(tls_model: TlsModel) -> llvm::ThreadLocalMode {
171 match tls_model {
172 TlsModel::GeneralDynamic => llvm::ThreadLocalMode::GeneralDynamic,
173 TlsModel::LocalDynamic => llvm::ThreadLocalMode::LocalDynamic,
174 TlsModel::InitialExec => llvm::ThreadLocalMode::InitialExec,
175 TlsModel::LocalExec => llvm::ThreadLocalMode::LocalExec,
176 TlsModel::Emulated => llvm::ThreadLocalMode::GeneralDynamic,
177 }
178}
179
180pub(crate) unsafe fn create_module<'ll>(
181 tcx: TyCtxt<'_>,
182 llcx: &'ll llvm::Context,
183 mod_name: &str,
184) -> &'ll llvm::Module {
185 let sess = tcx.sess;
186 let mod_name = SmallCStr::new(mod_name);
187 let llmod = unsafe { llvm::LLVMModuleCreateWithNameInContext(mod_name.as_ptr(), llcx) };
188
189 let cx = SimpleCx::new(llmod, llcx, tcx.data_layout.pointer_size());
190
191 let mut target_data_layout = sess.target.data_layout.to_string();
192 let llvm_version = llvm_util::get_version();
193
194 if llvm_version < (21, 0, 0) {
195 if sess.target.arch == Arch::Nvptx64 {
196 target_data_layout = target_data_layout.replace("e-p6:32:32-i64", "e-i64");
198 }
199 if sess.target.arch == Arch::AmdGpu {
200 target_data_layout = target_data_layout.replace("p8:128:128:128:48", "p8:128:128")
203 }
204 }
205 if llvm_version < (22, 0, 0) {
206 if sess.target.arch == Arch::Avr {
207 target_data_layout = target_data_layout.replace("n8:16", "n8")
209 }
210 if sess.target.arch == Arch::Nvptx64 {
211 target_data_layout = target_data_layout.replace("-i256:256", "");
213 }
214 if sess.target.arch == Arch::PowerPC64 {
215 target_data_layout = target_data_layout.replace("-f64:32:64", "");
217 }
218 }
219
220 {
222 let tm = crate::back::write::create_informational_target_machine(sess, false);
223 unsafe {
224 llvm::LLVMRustSetDataLayoutFromTargetMachine(llmod, tm.raw());
225 }
226
227 let llvm_data_layout = unsafe { llvm::LLVMGetDataLayoutStr(llmod) };
228 let llvm_data_layout =
229 str::from_utf8(unsafe { CStr::from_ptr(llvm_data_layout) }.to_bytes())
230 .expect("got a non-UTF8 data-layout from LLVM");
231
232 if target_data_layout != llvm_data_layout {
233 tcx.dcx().emit_err(crate::errors::MismatchedDataLayout {
234 rustc_target: sess.opts.target_triple.to_string().as_str(),
235 rustc_layout: target_data_layout.as_str(),
236 llvm_target: sess.target.llvm_target.borrow(),
237 llvm_layout: llvm_data_layout,
238 });
239 }
240 }
241
242 let data_layout = SmallCStr::new(&target_data_layout);
243 unsafe {
244 llvm::LLVMSetDataLayout(llmod, data_layout.as_ptr());
245 }
246
247 let llvm_target = SmallCStr::new(&versioned_llvm_target(sess));
248 unsafe {
249 llvm::LLVMRustSetNormalizedTarget(llmod, llvm_target.as_ptr());
250 }
251
252 let reloc_model = sess.relocation_model();
253 if matches!(reloc_model, RelocModel::Pic | RelocModel::Pie) {
254 unsafe {
255 llvm::LLVMRustSetModulePICLevel(llmod);
256 }
257 if reloc_model == RelocModel::Pie
260 || tcx.crate_types().iter().all(|ty| *ty == CrateType::Executable)
261 {
262 unsafe {
263 llvm::LLVMRustSetModulePIELevel(llmod);
264 }
265 }
266 }
267
268 unsafe {
274 llvm::LLVMRustSetModuleCodeModel(llmod, to_llvm_code_model(sess.code_model()));
275 }
276
277 if !sess.needs_plt() {
280 llvm::add_module_flag_u32(llmod, llvm::ModuleFlagMergeBehavior::Warning, "RtLibUseGOT", 1);
281 }
282
283 if sess.is_sanitizer_cfi_canonical_jump_tables_enabled() && sess.is_sanitizer_cfi_enabled() {
285 llvm::add_module_flag_u32(
286 llmod,
287 llvm::ModuleFlagMergeBehavior::Override,
288 "CFI Canonical Jump Tables",
289 1,
290 );
291 }
292
293 if sess.is_sanitizer_cfi_normalize_integers_enabled() {
296 llvm::add_module_flag_u32(
297 llmod,
298 llvm::ModuleFlagMergeBehavior::Override,
299 "cfi-normalize-integers",
300 1,
301 );
302 }
303
304 if sess.is_split_lto_unit_enabled() || sess.is_sanitizer_cfi_enabled() {
307 llvm::add_module_flag_u32(
308 llmod,
309 llvm::ModuleFlagMergeBehavior::Override,
310 "EnableSplitLTOUnit",
311 1,
312 );
313 }
314
315 if sess.is_sanitizer_kcfi_enabled() {
317 llvm::add_module_flag_u32(llmod, llvm::ModuleFlagMergeBehavior::Override, "kcfi", 1);
318
319 let pfe =
322 PatchableFunctionEntry::from_config(sess.opts.unstable_opts.patchable_function_entry);
323 if pfe.prefix() > 0 {
324 llvm::add_module_flag_u32(
325 llmod,
326 llvm::ModuleFlagMergeBehavior::Override,
327 "kcfi-offset",
328 pfe.prefix().into(),
329 );
330 }
331
332 if sess.is_sanitizer_kcfi_arity_enabled() {
335 if llvm_version < (21, 0, 0) {
337 tcx.dcx().emit_err(crate::errors::SanitizerKcfiArityRequiresLLVM2100);
338 }
339
340 llvm::add_module_flag_u32(
341 llmod,
342 llvm::ModuleFlagMergeBehavior::Override,
343 "kcfi-arity",
344 1,
345 );
346 }
347 }
348
349 if sess.target.is_like_msvc
351 || (sess.target.options.os == Os::Windows
352 && sess.target.options.env == Env::Gnu
353 && sess.target.options.abi == Abi::Llvm)
354 {
355 match sess.opts.cg.control_flow_guard {
356 CFGuard::Disabled => {}
357 CFGuard::NoChecks => {
358 llvm::add_module_flag_u32(
360 llmod,
361 llvm::ModuleFlagMergeBehavior::Warning,
362 "cfguard",
363 1,
364 );
365 }
366 CFGuard::Checks => {
367 llvm::add_module_flag_u32(
369 llmod,
370 llvm::ModuleFlagMergeBehavior::Warning,
371 "cfguard",
372 2,
373 );
374 }
375 }
376 }
377
378 if let Some(regparm_count) = sess.opts.unstable_opts.regparm {
379 llvm::add_module_flag_u32(
380 llmod,
381 llvm::ModuleFlagMergeBehavior::Error,
382 "NumRegisterParameters",
383 regparm_count,
384 );
385 }
386
387 if let Some(BranchProtection { bti, pac_ret, gcs }) = sess.opts.unstable_opts.branch_protection
388 {
389 if sess.target.arch == Arch::AArch64 {
390 llvm::add_module_flag_u32(
391 llmod,
392 llvm::ModuleFlagMergeBehavior::Min,
393 "branch-target-enforcement",
394 bti.into(),
395 );
396 llvm::add_module_flag_u32(
397 llmod,
398 llvm::ModuleFlagMergeBehavior::Min,
399 "sign-return-address",
400 pac_ret.is_some().into(),
401 );
402 let pac_opts = pac_ret.unwrap_or(PacRet { leaf: false, pc: false, key: PAuthKey::A });
403 llvm::add_module_flag_u32(
404 llmod,
405 llvm::ModuleFlagMergeBehavior::Min,
406 "branch-protection-pauth-lr",
407 pac_opts.pc.into(),
408 );
409 llvm::add_module_flag_u32(
410 llmod,
411 llvm::ModuleFlagMergeBehavior::Min,
412 "sign-return-address-all",
413 pac_opts.leaf.into(),
414 );
415 llvm::add_module_flag_u32(
416 llmod,
417 llvm::ModuleFlagMergeBehavior::Min,
418 "sign-return-address-with-bkey",
419 u32::from(pac_opts.key == PAuthKey::B),
420 );
421 llvm::add_module_flag_u32(
422 llmod,
423 llvm::ModuleFlagMergeBehavior::Min,
424 "guarded-control-stack",
425 gcs.into(),
426 );
427 } else {
428 bug!(
429 "branch-protection used on non-AArch64 target; \
430 this should be checked in rustc_session."
431 );
432 }
433 }
434
435 if let CFProtection::Branch | CFProtection::Full = sess.opts.unstable_opts.cf_protection {
437 llvm::add_module_flag_u32(
438 llmod,
439 llvm::ModuleFlagMergeBehavior::Override,
440 "cf-protection-branch",
441 1,
442 );
443 }
444 if let CFProtection::Return | CFProtection::Full = sess.opts.unstable_opts.cf_protection {
445 llvm::add_module_flag_u32(
446 llmod,
447 llvm::ModuleFlagMergeBehavior::Override,
448 "cf-protection-return",
449 1,
450 );
451 }
452
453 if sess.opts.unstable_opts.virtual_function_elimination {
454 llvm::add_module_flag_u32(
455 llmod,
456 llvm::ModuleFlagMergeBehavior::Error,
457 "Virtual Function Elim",
458 1,
459 );
460 }
461
462 if sess.opts.unstable_opts.ehcont_guard {
464 llvm::add_module_flag_u32(llmod, llvm::ModuleFlagMergeBehavior::Warning, "ehcontguard", 1);
465 }
466
467 match sess.opts.unstable_opts.function_return {
468 FunctionReturn::Keep => {}
469 FunctionReturn::ThunkExtern => {
470 llvm::add_module_flag_u32(
471 llmod,
472 llvm::ModuleFlagMergeBehavior::Override,
473 "function_return_thunk_extern",
474 1,
475 );
476 }
477 }
478
479 if sess.opts.unstable_opts.indirect_branch_cs_prefix {
480 llvm::add_module_flag_u32(
481 llmod,
482 llvm::ModuleFlagMergeBehavior::Override,
483 "indirect_branch_cs_prefix",
484 1,
485 );
486 }
487
488 match (sess.opts.unstable_opts.small_data_threshold, sess.target.small_data_threshold_support())
489 {
490 (Some(threshold), SmallDataThresholdSupport::LlvmModuleFlag(flag)) => {
493 llvm::add_module_flag_u32(
494 llmod,
495 llvm::ModuleFlagMergeBehavior::Error,
496 &flag,
497 threshold as u32,
498 );
499 }
500 _ => (),
501 };
502
503 #[allow(clippy::option_env_unwrap)]
508 let rustc_producer =
509 format!("rustc version {}", option_env!("CFG_VERSION").expect("CFG_VERSION"));
510
511 let name_metadata = cx.create_metadata(rustc_producer.as_bytes());
512 cx.module_add_named_metadata_node(llmod, c"llvm.ident", &[name_metadata]);
513
514 let llvm_abiname = &sess.target.options.llvm_abiname;
520 if matches!(sess.target.arch, Arch::RiscV32 | Arch::RiscV64) && !llvm_abiname.is_empty() {
521 llvm::add_module_flag_str(
522 llmod,
523 llvm::ModuleFlagMergeBehavior::Error,
524 "target-abi",
525 llvm_abiname,
526 );
527 }
528
529 for (key, value, merge_behavior) in &sess.opts.unstable_opts.llvm_module_flag {
531 let merge_behavior = match merge_behavior.as_str() {
532 "error" => llvm::ModuleFlagMergeBehavior::Error,
533 "warning" => llvm::ModuleFlagMergeBehavior::Warning,
534 "require" => llvm::ModuleFlagMergeBehavior::Require,
535 "override" => llvm::ModuleFlagMergeBehavior::Override,
536 "append" => llvm::ModuleFlagMergeBehavior::Append,
537 "appendunique" => llvm::ModuleFlagMergeBehavior::AppendUnique,
538 "max" => llvm::ModuleFlagMergeBehavior::Max,
539 "min" => llvm::ModuleFlagMergeBehavior::Min,
540 _ => unreachable!(),
542 };
543 llvm::add_module_flag_u32(llmod, merge_behavior, key, *value);
544 }
545
546 llmod
547}
548
549impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> {
550 pub(crate) fn new(
551 tcx: TyCtxt<'tcx>,
552 codegen_unit: &'tcx CodegenUnit<'tcx>,
553 llvm_module: &'ll crate::ModuleLlvm,
554 ) -> Self {
555 let use_dll_storage_attrs = tcx.sess.target.is_like_windows;
608
609 let tls_model = to_llvm_tls_model(tcx.sess.tls_model());
610
611 let (llcx, llmod) = (&*llvm_module.llcx, llvm_module.llmod());
612
613 let coverage_cx =
614 tcx.sess.instrument_coverage().then(coverageinfo::CguCoverageContext::new);
615
616 let dbg_cx = if tcx.sess.opts.debuginfo != DebugInfo::None {
617 let dctx = debuginfo::CodegenUnitDebugContext::new(llmod);
618 debuginfo::metadata::build_compile_unit_di_node(
619 tcx,
620 codegen_unit.name().as_str(),
621 &dctx,
622 );
623 Some(dctx)
624 } else {
625 None
626 };
627
628 GenericCx(
629 FullCx {
630 tcx,
631 scx: SimpleCx::new(llmod, llcx, tcx.data_layout.pointer_size()),
632 use_dll_storage_attrs,
633 tls_model,
634 codegen_unit,
635 instances: Default::default(),
636 intrinsic_instances: Default::default(),
637 vtables: Default::default(),
638 const_str_cache: Default::default(),
639 const_globals: Default::default(),
640 statics_to_rauw: RefCell::new(Vec::new()),
641 used_statics: Vec::new(),
642 compiler_used_statics: Default::default(),
643 type_lowering: Default::default(),
644 scalar_lltypes: Default::default(),
645 coverage_cx,
646 dbg_cx,
647 eh_personality: Cell::new(None),
648 eh_catch_typeinfo: Cell::new(None),
649 rust_try_fn: Cell::new(None),
650 intrinsics: Default::default(),
651 local_gen_sym_counter: Cell::new(0),
652 renamed_statics: Default::default(),
653 objc_class_t: Cell::new(None),
654 objc_classrefs: Default::default(),
655 objc_selrefs: Default::default(),
656 offload_globals: Default::default(),
657 offload_kernel_cache: Default::default(),
658 },
659 PhantomData,
660 )
661 }
662
663 pub(crate) fn statics_to_rauw(&self) -> &RefCell<Vec<(&'ll Value, &'ll Value)>> {
664 &self.statics_to_rauw
665 }
666
667 #[inline]
669 #[track_caller]
670 pub(crate) fn coverage_cx(&self) -> &coverageinfo::CguCoverageContext<'ll, 'tcx> {
671 self.coverage_cx.as_ref().expect("only called when coverage instrumentation is enabled")
672 }
673
674 pub(crate) fn create_used_variable_impl(&self, name: &'static CStr, values: &[&'ll Value]) {
675 let array = self.const_array(self.type_ptr(), values);
676
677 let g = llvm::add_global(self.llmod, self.val_ty(array), name);
678 llvm::set_initializer(g, array);
679 llvm::set_linkage(g, llvm::Linkage::AppendingLinkage);
680 llvm::set_section(g, c"llvm.metadata");
681 }
682
683 pub(crate) fn objc_abi_version(&self) -> u32 {
687 assert!(self.tcx.sess.target.is_like_darwin);
688 if self.tcx.sess.target.arch == Arch::X86 && self.tcx.sess.target.os == Os::MacOs {
689 1
691 } else {
692 2
695 }
696 }
697
698 pub(crate) fn add_objc_module_flags(&self) {
702 let abi_version = self.objc_abi_version();
703
704 llvm::add_module_flag_u32(
705 self.llmod,
706 llvm::ModuleFlagMergeBehavior::Error,
707 "Objective-C Version",
708 abi_version,
709 );
710
711 llvm::add_module_flag_u32(
712 self.llmod,
713 llvm::ModuleFlagMergeBehavior::Error,
714 "Objective-C Image Info Version",
715 0,
716 );
717
718 llvm::add_module_flag_str(
719 self.llmod,
720 llvm::ModuleFlagMergeBehavior::Error,
721 "Objective-C Image Info Section",
722 match abi_version {
723 1 => "__OBJC,__image_info,regular",
724 2 => "__DATA,__objc_imageinfo,regular,no_dead_strip",
725 _ => unreachable!(),
726 },
727 );
728
729 if self.tcx.sess.target.env == Env::Sim {
730 llvm::add_module_flag_u32(
731 self.llmod,
732 llvm::ModuleFlagMergeBehavior::Error,
733 "Objective-C Is Simulated",
734 1 << 5,
735 );
736 }
737
738 llvm::add_module_flag_u32(
739 self.llmod,
740 llvm::ModuleFlagMergeBehavior::Error,
741 "Objective-C Class Properties",
742 1 << 6,
743 );
744 }
745}
746impl<'ll> SimpleCx<'ll> {
747 pub(crate) fn get_type_of_global(&self, val: &'ll Value) -> &'ll Type {
748 unsafe { llvm::LLVMGlobalGetValueType(val) }
749 }
750 pub(crate) fn val_ty(&self, v: &'ll Value) -> &'ll Type {
751 common::val_ty(v)
752 }
753}
754impl<'ll> SimpleCx<'ll> {
755 pub(crate) fn new(
756 llmod: &'ll llvm::Module,
757 llcx: &'ll llvm::Context,
758 pointer_size: Size,
759 ) -> Self {
760 let isize_ty = llvm::LLVMIntTypeInContext(llcx, pointer_size.bits() as c_uint);
761 Self(SCx { llmod, llcx, isize_ty }, PhantomData)
762 }
763}
764
765impl<'ll, CX: Borrow<SCx<'ll>>> GenericCx<'ll, CX> {
766 pub(crate) fn get_metadata_value(&self, metadata: &'ll Metadata) -> &'ll Value {
767 llvm::LLVMMetadataAsValue(self.llcx(), metadata)
768 }
769
770 pub(crate) fn get_const_int(&self, ty: &'ll Type, val: u64) -> &'ll Value {
771 unsafe { llvm::LLVMConstInt(ty, val, llvm::FALSE) }
772 }
773
774 pub(crate) fn get_const_i64(&self, n: u64) -> &'ll Value {
775 self.get_const_int(self.type_i64(), n)
776 }
777
778 pub(crate) fn get_const_i32(&self, n: u64) -> &'ll Value {
779 self.get_const_int(self.type_i32(), n)
780 }
781
782 pub(crate) fn get_const_i16(&self, n: u64) -> &'ll Value {
783 self.get_const_int(self.type_i16(), n)
784 }
785
786 pub(crate) fn get_const_i8(&self, n: u64) -> &'ll Value {
787 self.get_const_int(self.type_i8(), n)
788 }
789
790 pub(crate) fn get_function(&self, name: &str) -> Option<&'ll Value> {
791 let name = SmallCStr::new(name);
792 unsafe { llvm::LLVMGetNamedFunction((**self).borrow().llmod, name.as_ptr()) }
793 }
794
795 pub(crate) fn get_md_kind_id(&self, name: &str) -> llvm::MetadataKindId {
796 unsafe {
797 llvm::LLVMGetMDKindIDInContext(
798 self.llcx(),
799 name.as_ptr() as *const c_char,
800 name.len() as c_uint,
801 )
802 }
803 }
804
805 pub(crate) fn create_metadata(&self, name: &[u8]) -> &'ll Metadata {
806 unsafe {
807 llvm::LLVMMDStringInContext2(self.llcx(), name.as_ptr() as *const c_char, name.len())
808 }
809 }
810
811 pub(crate) fn get_functions(&self) -> Vec<&'ll Value> {
812 let mut functions = vec![];
813 let mut func = unsafe { llvm::LLVMGetFirstFunction(self.llmod()) };
814 while let Some(f) = func {
815 functions.push(f);
816 func = unsafe { llvm::LLVMGetNextFunction(f) }
817 }
818 functions
819 }
820}
821
822impl<'ll, 'tcx> MiscCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> {
823 fn vtables(
824 &self,
825 ) -> &RefCell<FxHashMap<(Ty<'tcx>, Option<ty::ExistentialTraitRef<'tcx>>), &'ll Value>> {
826 &self.vtables
827 }
828
829 fn apply_vcall_visibility_metadata(
830 &self,
831 ty: Ty<'tcx>,
832 poly_trait_ref: Option<ty::ExistentialTraitRef<'tcx>>,
833 vtable: &'ll Value,
834 ) {
835 apply_vcall_visibility_metadata(self, ty, poly_trait_ref, vtable);
836 }
837
838 fn get_fn(&self, instance: Instance<'tcx>) -> &'ll Value {
839 get_fn(self, instance)
840 }
841
842 fn get_fn_addr(&self, instance: Instance<'tcx>) -> &'ll Value {
843 get_fn(self, instance)
844 }
845
846 fn eh_personality(&self) -> &'ll Value {
847 if let Some(llpersonality) = self.eh_personality.get() {
868 return llpersonality;
869 }
870
871 let name = if wants_msvc_seh(self.sess()) {
872 Some("__CxxFrameHandler3")
873 } else if wants_wasm_eh(self.sess()) {
874 Some("__gxx_wasm_personality_v0")
879 } else {
880 None
881 };
882
883 let tcx = self.tcx;
884 let llfn = match tcx.lang_items().eh_personality() {
885 Some(def_id) if name.is_none() => self.get_fn_addr(ty::Instance::expect_resolve(
886 tcx,
887 self.typing_env(),
888 def_id,
889 ty::List::empty(),
890 DUMMY_SP,
891 )),
892 _ => {
893 let name = name.unwrap_or("rust_eh_personality");
894 if let Some(llfn) = self.get_declared_value(name) {
895 llfn
896 } else {
897 let fty = self.type_variadic_func(&[], self.type_i32());
898 let llfn = self.declare_cfn(name, llvm::UnnamedAddr::Global, fty);
899 let target_cpu = attributes::target_cpu_attr(self, self.sess());
900 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &[target_cpu]);
901 llfn
902 }
903 }
904 };
905 self.eh_personality.set(Some(llfn));
906 llfn
907 }
908
909 fn sess(&self) -> &Session {
910 self.tcx.sess
911 }
912
913 fn set_frame_pointer_type(&self, llfn: &'ll Value) {
914 if let Some(attr) = attributes::frame_pointer_type_attr(self, self.sess()) {
915 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &[attr]);
916 }
917 }
918
919 fn apply_target_cpu_attr(&self, llfn: &'ll Value) {
920 let mut attrs = SmallVec::<[_; 2]>::new();
921 attrs.push(attributes::target_cpu_attr(self, self.sess()));
922 attrs.extend(attributes::tune_cpu_attr(self, self.sess()));
923 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &attrs);
924 }
925
926 fn declare_c_main(&self, fn_type: Self::Type) -> Option<Self::Function> {
927 let entry_name = self.sess().target.entry_name.as_ref();
928 if self.get_declared_value(entry_name).is_none() {
929 let llfn = self.declare_entry_fn(
930 entry_name,
931 to_llvm_calling_convention(self.sess(), self.sess().target.entry_abi),
932 llvm::UnnamedAddr::Global,
933 fn_type,
934 );
935 attributes::apply_to_llfn(
936 llfn,
937 llvm::AttributePlace::Function,
938 attributes::target_features_attr(self, self.tcx, vec![]).as_slice(),
939 );
940 Some(llfn)
941 } else {
942 None
945 }
946 }
947}
948
949impl<'ll> CodegenCx<'ll, '_> {
950 pub(crate) fn get_intrinsic(
951 &self,
952 base_name: Cow<'static, str>,
953 type_params: &[&'ll Type],
954 ) -> (&'ll Type, &'ll Value) {
955 *self
956 .intrinsics
957 .borrow_mut()
958 .entry((base_name, SmallVec::from_slice(type_params)))
959 .or_insert_with_key(|(base_name, type_params)| {
960 self.declare_intrinsic(base_name, type_params)
961 })
962 }
963
964 fn declare_intrinsic(
965 &self,
966 base_name: &str,
967 type_params: &[&'ll Type],
968 ) -> (&'ll Type, &'ll Value) {
969 if base_name == "memcmp" {
973 let fn_ty = self
974 .type_func(&[self.type_ptr(), self.type_ptr(), self.type_isize()], self.type_int());
975 let f = self.declare_cfn("memcmp", llvm::UnnamedAddr::No, fn_ty);
976
977 return (fn_ty, f);
978 }
979
980 let intrinsic = llvm::Intrinsic::lookup(base_name.as_bytes())
981 .unwrap_or_else(|| bug!("Unknown intrinsic: `{base_name}`"));
982 let f = intrinsic.get_declaration(self.llmod, &type_params);
983
984 (self.get_type_of_global(f), f)
985 }
986
987 pub(crate) fn eh_catch_typeinfo(&self) -> &'ll Value {
988 if let Some(eh_catch_typeinfo) = self.eh_catch_typeinfo.get() {
989 return eh_catch_typeinfo;
990 }
991 let tcx = self.tcx;
992 assert!(self.sess().target.os == Os::Emscripten);
993 let eh_catch_typeinfo = match tcx.lang_items().eh_catch_typeinfo() {
994 Some(def_id) => self.get_static(def_id),
995 _ => {
996 let ty = self.type_struct(&[self.type_ptr(), self.type_ptr()], false);
997 self.declare_global(&mangle_internal_symbol(self.tcx, "rust_eh_catch_typeinfo"), ty)
998 }
999 };
1000 self.eh_catch_typeinfo.set(Some(eh_catch_typeinfo));
1001 eh_catch_typeinfo
1002 }
1003}
1004
1005impl CodegenCx<'_, '_> {
1006 pub(crate) fn generate_local_symbol_name(&self, prefix: &str) -> String {
1009 let idx = self.local_gen_sym_counter.get();
1010 self.local_gen_sym_counter.set(idx + 1);
1011 let mut name = String::with_capacity(prefix.len() + 6);
1014 name.push_str(prefix);
1015 name.push('.');
1016 name.push_str(&(idx as u64).to_base(ALPHANUMERIC_ONLY));
1017 name
1018 }
1019}
1020
1021impl<'ll, CX: Borrow<SCx<'ll>>> GenericCx<'ll, CX> {
1022 pub(crate) fn md_node_in_context(&self, md_list: &[&'ll Metadata]) -> &'ll Metadata {
1024 unsafe { llvm::LLVMMDNodeInContext2(self.llcx(), md_list.as_ptr(), md_list.len()) }
1025 }
1026
1027 pub(crate) fn set_metadata<'a>(
1029 &self,
1030 val: &'a Value,
1031 kind_id: MetadataKindId,
1032 md: &'ll Metadata,
1033 ) {
1034 let node = self.get_metadata_value(md);
1035 llvm::LLVMSetMetadata(val, kind_id, node);
1036 }
1037
1038 pub(crate) fn set_metadata_node(
1043 &self,
1044 instruction: &'ll Value,
1045 kind_id: MetadataKindId,
1046 md_list: &[&'ll Metadata],
1047 ) {
1048 let md = self.md_node_in_context(md_list);
1049 self.set_metadata(instruction, kind_id, md);
1050 }
1051
1052 pub(crate) fn module_add_named_metadata_node(
1057 &self,
1058 module: &'ll Module,
1059 kind_name: &CStr,
1060 md_list: &[&'ll Metadata],
1061 ) {
1062 let md = self.md_node_in_context(md_list);
1063 let md_as_val = self.get_metadata_value(md);
1064 unsafe { llvm::LLVMAddNamedMetadataOperand(module, kind_name.as_ptr(), md_as_val) };
1065 }
1066
1067 pub(crate) fn global_add_metadata_node(
1071 &self,
1072 global: &'ll Value,
1073 kind_id: MetadataKindId,
1074 md_list: &[&'ll Metadata],
1075 ) {
1076 let md = self.md_node_in_context(md_list);
1077 unsafe { llvm::LLVMRustGlobalAddMetadata(global, kind_id, md) };
1078 }
1079
1080 pub(crate) fn global_set_metadata_node(
1084 &self,
1085 global: &'ll Value,
1086 kind_id: MetadataKindId,
1087 md_list: &[&'ll Metadata],
1088 ) {
1089 let md = self.md_node_in_context(md_list);
1090 unsafe { llvm::LLVMGlobalSetMetadata(global, kind_id, md) };
1091 }
1092}
1093
1094impl HasDataLayout for CodegenCx<'_, '_> {
1095 #[inline]
1096 fn data_layout(&self) -> &TargetDataLayout {
1097 &self.tcx.data_layout
1098 }
1099}
1100
1101impl HasTargetSpec for CodegenCx<'_, '_> {
1102 #[inline]
1103 fn target_spec(&self) -> &Target {
1104 &self.tcx.sess.target
1105 }
1106}
1107
1108impl<'tcx> ty::layout::HasTyCtxt<'tcx> for CodegenCx<'_, 'tcx> {
1109 #[inline]
1110 fn tcx(&self) -> TyCtxt<'tcx> {
1111 self.tcx
1112 }
1113}
1114
1115impl<'tcx, 'll> HasTypingEnv<'tcx> for CodegenCx<'ll, 'tcx> {
1116 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
1117 ty::TypingEnv::fully_monomorphized()
1118 }
1119}
1120
1121impl<'tcx> LayoutOfHelpers<'tcx> for CodegenCx<'_, 'tcx> {
1122 #[inline]
1123 fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
1124 if let LayoutError::SizeOverflow(_)
1125 | LayoutError::ReferencesError(_)
1126 | LayoutError::InvalidSimd { .. } = err
1127 {
1128 self.tcx.dcx().emit_fatal(Spanned { span, node: err.into_diagnostic() })
1129 } else {
1130 self.tcx.dcx().emit_fatal(ssa_errors::FailedToGetLayout { span, ty, err })
1131 }
1132 }
1133}
1134
1135impl<'tcx> FnAbiOfHelpers<'tcx> for CodegenCx<'_, 'tcx> {
1136 #[inline]
1137 fn handle_fn_abi_err(
1138 &self,
1139 err: FnAbiError<'tcx>,
1140 span: Span,
1141 fn_abi_request: FnAbiRequest<'tcx>,
1142 ) -> ! {
1143 match err {
1144 FnAbiError::Layout(
1145 LayoutError::SizeOverflow(_)
1146 | LayoutError::Cycle(_)
1147 | LayoutError::InvalidSimd { .. },
1148 ) => {
1149 self.tcx.dcx().emit_fatal(Spanned { span, node: err });
1150 }
1151 _ => match fn_abi_request {
1152 FnAbiRequest::OfFnPtr { sig, extra_args } => {
1153 span_bug!(span, "`fn_abi_of_fn_ptr({sig}, {extra_args:?})` failed: {err:?}",);
1154 }
1155 FnAbiRequest::OfInstance { instance, extra_args } => {
1156 span_bug!(
1157 span,
1158 "`fn_abi_of_instance({instance}, {extra_args:?})` failed: {err:?}",
1159 );
1160 }
1161 },
1162 }
1163 }
1164}