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::common::TypeKind;
12use rustc_codegen_ssa::errors as ssa_errors;
13use rustc_codegen_ssa::traits::*;
14use rustc_data_structures::base_n::{ALPHANUMERIC_ONLY, ToBaseN};
15use rustc_data_structures::fx::FxHashMap;
16use rustc_data_structures::small_c_str::SmallCStr;
17use rustc_hir::def_id::DefId;
18use rustc_middle::middle::codegen_fn_attrs::PatchableFunctionEntry;
19use rustc_middle::mir::mono::CodegenUnit;
20use rustc_middle::ty::layout::{
21 FnAbiError, FnAbiOfHelpers, FnAbiRequest, HasTypingEnv, LayoutError, LayoutOfHelpers,
22};
23use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
24use rustc_middle::{bug, span_bug};
25use rustc_session::Session;
26use rustc_session::config::{
27 BranchProtection, CFGuard, CFProtection, CrateType, DebugInfo, FunctionReturn, PAuthKey, PacRet,
28};
29use rustc_span::source_map::Spanned;
30use rustc_span::{DUMMY_SP, Span};
31use rustc_symbol_mangling::mangle_internal_symbol;
32use rustc_target::spec::{HasTargetSpec, RelocModel, SmallDataThresholdSupport, Target, TlsModel};
33use smallvec::SmallVec;
34
35use crate::back::write::to_llvm_code_model;
36use crate::callee::get_fn;
37use crate::common::AsCCharPtr;
38use crate::debuginfo::metadata::apply_vcall_visibility_metadata;
39use crate::llvm::Metadata;
40use crate::type_::Type;
41use crate::value::Value;
42use crate::{attributes, common, coverageinfo, debuginfo, llvm, 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 vtables: RefCell<FxHashMap<(Ty<'tcx>, Option<ty::ExistentialTraitRef<'tcx>>), &'ll Value>>,
106 pub const_str_cache: RefCell<FxHashMap<String, &'ll Value>>,
108
109 pub const_globals: RefCell<FxHashMap<&'ll Value, &'ll Value>>,
111
112 pub statics_to_rauw: RefCell<Vec<(&'ll Value, &'ll Value)>>,
117
118 pub used_statics: Vec<&'ll Value>,
121
122 pub compiler_used_statics: Vec<&'ll Value>,
125
126 pub type_lowering: RefCell<FxHashMap<(Ty<'tcx>, Option<VariantIdx>), &'ll Type>>,
128
129 pub scalar_lltypes: RefCell<FxHashMap<Ty<'tcx>, &'ll Type>>,
131
132 pub coverage_cx: Option<coverageinfo::CguCoverageContext<'ll, 'tcx>>,
134 pub dbg_cx: Option<debuginfo::CodegenUnitDebugContext<'ll, 'tcx>>,
135
136 eh_personality: Cell<Option<&'ll Value>>,
137 eh_catch_typeinfo: Cell<Option<&'ll Value>>,
138 pub rust_try_fn: Cell<Option<(&'ll Type, &'ll Value)>>,
139
140 intrinsics:
141 RefCell<FxHashMap<(Cow<'static, str>, SmallVec<[&'ll Type; 2]>), (&'ll Type, &'ll Value)>>,
142
143 local_gen_sym_counter: Cell<usize>,
145
146 pub renamed_statics: RefCell<FxHashMap<DefId, &'ll Value>>,
151}
152
153fn to_llvm_tls_model(tls_model: TlsModel) -> llvm::ThreadLocalMode {
154 match tls_model {
155 TlsModel::GeneralDynamic => llvm::ThreadLocalMode::GeneralDynamic,
156 TlsModel::LocalDynamic => llvm::ThreadLocalMode::LocalDynamic,
157 TlsModel::InitialExec => llvm::ThreadLocalMode::InitialExec,
158 TlsModel::LocalExec => llvm::ThreadLocalMode::LocalExec,
159 TlsModel::Emulated => llvm::ThreadLocalMode::GeneralDynamic,
160 }
161}
162
163pub(crate) unsafe fn create_module<'ll>(
164 tcx: TyCtxt<'_>,
165 llcx: &'ll llvm::Context,
166 mod_name: &str,
167) -> &'ll llvm::Module {
168 let sess = tcx.sess;
169 let mod_name = SmallCStr::new(mod_name);
170 let llmod = unsafe { llvm::LLVMModuleCreateWithNameInContext(mod_name.as_ptr(), llcx) };
171
172 let mut target_data_layout = sess.target.data_layout.to_string();
173 let llvm_version = llvm_util::get_version();
174
175 if llvm_version < (20, 0, 0) {
176 if sess.target.arch == "aarch64" || sess.target.arch.starts_with("arm64") {
177 target_data_layout =
181 target_data_layout.replace("-p270:32:32-p271:32:32-p272:64:64", "");
182 }
183 if sess.target.arch.starts_with("sparc") {
184 target_data_layout = target_data_layout.replace("-i128:128", "");
187 }
188 if sess.target.arch.starts_with("mips64") {
189 target_data_layout = target_data_layout.replace("-i128:128", "");
192 }
193 if sess.target.arch.starts_with("powerpc64") {
194 target_data_layout = target_data_layout.replace("-i128:128", "");
197 }
198 if sess.target.arch.starts_with("wasm32") || sess.target.arch.starts_with("wasm64") {
199 target_data_layout = target_data_layout.replace("-i128:128", "");
202 }
203 }
204 if llvm_version < (21, 0, 0) {
205 if sess.target.arch == "nvptx64" {
206 target_data_layout = target_data_layout.replace("e-p6:32:32-i64", "e-i64");
208 }
209 }
210
211 {
213 let tm = crate::back::write::create_informational_target_machine(tcx.sess, false);
214 unsafe {
215 llvm::LLVMRustSetDataLayoutFromTargetMachine(llmod, tm.raw());
216 }
217
218 let llvm_data_layout = unsafe { llvm::LLVMGetDataLayoutStr(llmod) };
219 let llvm_data_layout =
220 str::from_utf8(unsafe { CStr::from_ptr(llvm_data_layout) }.to_bytes())
221 .expect("got a non-UTF8 data-layout from LLVM");
222
223 if target_data_layout != llvm_data_layout {
224 tcx.dcx().emit_err(crate::errors::MismatchedDataLayout {
225 rustc_target: sess.opts.target_triple.to_string().as_str(),
226 rustc_layout: target_data_layout.as_str(),
227 llvm_target: sess.target.llvm_target.borrow(),
228 llvm_layout: llvm_data_layout,
229 });
230 }
231 }
232
233 let data_layout = SmallCStr::new(&target_data_layout);
234 unsafe {
235 llvm::LLVMSetDataLayout(llmod, data_layout.as_ptr());
236 }
237
238 let llvm_target = SmallCStr::new(&versioned_llvm_target(sess));
239 unsafe {
240 llvm::LLVMRustSetNormalizedTarget(llmod, llvm_target.as_ptr());
241 }
242
243 let reloc_model = sess.relocation_model();
244 if matches!(reloc_model, RelocModel::Pic | RelocModel::Pie) {
245 unsafe {
246 llvm::LLVMRustSetModulePICLevel(llmod);
247 }
248 if reloc_model == RelocModel::Pie
251 || tcx.crate_types().iter().all(|ty| *ty == CrateType::Executable)
252 {
253 unsafe {
254 llvm::LLVMRustSetModulePIELevel(llmod);
255 }
256 }
257 }
258
259 unsafe {
265 llvm::LLVMRustSetModuleCodeModel(llmod, to_llvm_code_model(sess.code_model()));
266 }
267
268 if !sess.needs_plt() {
271 llvm::add_module_flag_u32(llmod, llvm::ModuleFlagMergeBehavior::Warning, "RtLibUseGOT", 1);
272 }
273
274 if sess.is_sanitizer_cfi_canonical_jump_tables_enabled() && sess.is_sanitizer_cfi_enabled() {
276 llvm::add_module_flag_u32(
277 llmod,
278 llvm::ModuleFlagMergeBehavior::Override,
279 "CFI Canonical Jump Tables",
280 1,
281 );
282 }
283
284 if sess.is_sanitizer_cfi_normalize_integers_enabled() {
287 llvm::add_module_flag_u32(
288 llmod,
289 llvm::ModuleFlagMergeBehavior::Override,
290 "cfi-normalize-integers",
291 1,
292 );
293 }
294
295 if sess.is_split_lto_unit_enabled() || sess.is_sanitizer_cfi_enabled() {
298 llvm::add_module_flag_u32(
299 llmod,
300 llvm::ModuleFlagMergeBehavior::Override,
301 "EnableSplitLTOUnit",
302 1,
303 );
304 }
305
306 if sess.is_sanitizer_kcfi_enabled() {
308 llvm::add_module_flag_u32(llmod, llvm::ModuleFlagMergeBehavior::Override, "kcfi", 1);
309
310 let pfe =
313 PatchableFunctionEntry::from_config(sess.opts.unstable_opts.patchable_function_entry);
314 if pfe.prefix() > 0 {
315 llvm::add_module_flag_u32(
316 llmod,
317 llvm::ModuleFlagMergeBehavior::Override,
318 "kcfi-offset",
319 pfe.prefix().into(),
320 );
321 }
322
323 if sess.is_sanitizer_kcfi_arity_enabled() {
326 if llvm_version < (21, 0, 0) {
328 tcx.dcx().emit_err(crate::errors::SanitizerKcfiArityRequiresLLVM2100);
329 }
330
331 llvm::add_module_flag_u32(
332 llmod,
333 llvm::ModuleFlagMergeBehavior::Override,
334 "kcfi-arity",
335 1,
336 );
337 }
338 }
339
340 if sess.target.is_like_msvc
342 || (sess.target.options.os == "windows"
343 && sess.target.options.env == "gnu"
344 && sess.target.options.abi == "llvm")
345 {
346 match sess.opts.cg.control_flow_guard {
347 CFGuard::Disabled => {}
348 CFGuard::NoChecks => {
349 llvm::add_module_flag_u32(
351 llmod,
352 llvm::ModuleFlagMergeBehavior::Warning,
353 "cfguard",
354 1,
355 );
356 }
357 CFGuard::Checks => {
358 llvm::add_module_flag_u32(
360 llmod,
361 llvm::ModuleFlagMergeBehavior::Warning,
362 "cfguard",
363 2,
364 );
365 }
366 }
367 }
368
369 if let Some(BranchProtection { bti, pac_ret }) = sess.opts.unstable_opts.branch_protection {
370 if sess.target.arch == "aarch64" {
371 llvm::add_module_flag_u32(
372 llmod,
373 llvm::ModuleFlagMergeBehavior::Min,
374 "branch-target-enforcement",
375 bti.into(),
376 );
377 llvm::add_module_flag_u32(
378 llmod,
379 llvm::ModuleFlagMergeBehavior::Min,
380 "sign-return-address",
381 pac_ret.is_some().into(),
382 );
383 let pac_opts = pac_ret.unwrap_or(PacRet { leaf: false, pc: false, key: PAuthKey::A });
384 llvm::add_module_flag_u32(
385 llmod,
386 llvm::ModuleFlagMergeBehavior::Min,
387 "branch-protection-pauth-lr",
388 pac_opts.pc.into(),
389 );
390 llvm::add_module_flag_u32(
391 llmod,
392 llvm::ModuleFlagMergeBehavior::Min,
393 "sign-return-address-all",
394 pac_opts.leaf.into(),
395 );
396 llvm::add_module_flag_u32(
397 llmod,
398 llvm::ModuleFlagMergeBehavior::Min,
399 "sign-return-address-with-bkey",
400 u32::from(pac_opts.key == PAuthKey::B),
401 );
402 } else {
403 bug!(
404 "branch-protection used on non-AArch64 target; \
405 this should be checked in rustc_session."
406 );
407 }
408 }
409
410 if let CFProtection::Branch | CFProtection::Full = sess.opts.unstable_opts.cf_protection {
412 llvm::add_module_flag_u32(
413 llmod,
414 llvm::ModuleFlagMergeBehavior::Override,
415 "cf-protection-branch",
416 1,
417 );
418 }
419 if let CFProtection::Return | CFProtection::Full = sess.opts.unstable_opts.cf_protection {
420 llvm::add_module_flag_u32(
421 llmod,
422 llvm::ModuleFlagMergeBehavior::Override,
423 "cf-protection-return",
424 1,
425 );
426 }
427
428 if sess.opts.unstable_opts.virtual_function_elimination {
429 llvm::add_module_flag_u32(
430 llmod,
431 llvm::ModuleFlagMergeBehavior::Error,
432 "Virtual Function Elim",
433 1,
434 );
435 }
436
437 if sess.opts.unstable_opts.ehcont_guard {
439 llvm::add_module_flag_u32(llmod, llvm::ModuleFlagMergeBehavior::Warning, "ehcontguard", 1);
440 }
441
442 match sess.opts.unstable_opts.function_return {
443 FunctionReturn::Keep => {}
444 FunctionReturn::ThunkExtern => {
445 llvm::add_module_flag_u32(
446 llmod,
447 llvm::ModuleFlagMergeBehavior::Override,
448 "function_return_thunk_extern",
449 1,
450 );
451 }
452 }
453
454 match (sess.opts.unstable_opts.small_data_threshold, sess.target.small_data_threshold_support())
455 {
456 (Some(threshold), SmallDataThresholdSupport::LlvmModuleFlag(flag)) => {
459 llvm::add_module_flag_u32(
460 llmod,
461 llvm::ModuleFlagMergeBehavior::Error,
462 &flag,
463 threshold as u32,
464 );
465 }
466 _ => (),
467 };
468
469 #[allow(clippy::option_env_unwrap)]
474 let rustc_producer =
475 format!("rustc version {}", option_env!("CFG_VERSION").expect("CFG_VERSION"));
476 let name_metadata = unsafe {
477 llvm::LLVMMDStringInContext2(
478 llcx,
479 rustc_producer.as_c_char_ptr(),
480 rustc_producer.as_bytes().len(),
481 )
482 };
483 unsafe {
484 llvm::LLVMAddNamedMetadataOperand(
485 llmod,
486 c"llvm.ident".as_ptr(),
487 &llvm::LLVMMetadataAsValue(llcx, llvm::LLVMMDNodeInContext2(llcx, &name_metadata, 1)),
488 );
489 }
490
491 let llvm_abiname = &sess.target.options.llvm_abiname;
497 if matches!(sess.target.arch.as_ref(), "riscv32" | "riscv64") && !llvm_abiname.is_empty() {
498 llvm::add_module_flag_str(
499 llmod,
500 llvm::ModuleFlagMergeBehavior::Error,
501 "target-abi",
502 llvm_abiname,
503 );
504 }
505
506 for (key, value, merge_behavior) in &sess.opts.unstable_opts.llvm_module_flag {
508 let merge_behavior = match merge_behavior.as_str() {
509 "error" => llvm::ModuleFlagMergeBehavior::Error,
510 "warning" => llvm::ModuleFlagMergeBehavior::Warning,
511 "require" => llvm::ModuleFlagMergeBehavior::Require,
512 "override" => llvm::ModuleFlagMergeBehavior::Override,
513 "append" => llvm::ModuleFlagMergeBehavior::Append,
514 "appendunique" => llvm::ModuleFlagMergeBehavior::AppendUnique,
515 "max" => llvm::ModuleFlagMergeBehavior::Max,
516 "min" => llvm::ModuleFlagMergeBehavior::Min,
517 _ => unreachable!(),
519 };
520 llvm::add_module_flag_u32(llmod, merge_behavior, key, *value);
521 }
522
523 llmod
524}
525
526impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> {
527 pub(crate) fn new(
528 tcx: TyCtxt<'tcx>,
529 codegen_unit: &'tcx CodegenUnit<'tcx>,
530 llvm_module: &'ll crate::ModuleLlvm,
531 ) -> Self {
532 let use_dll_storage_attrs = tcx.sess.target.is_like_windows;
585
586 let tls_model = to_llvm_tls_model(tcx.sess.tls_model());
587
588 let (llcx, llmod) = (&*llvm_module.llcx, llvm_module.llmod());
589
590 let coverage_cx =
591 tcx.sess.instrument_coverage().then(coverageinfo::CguCoverageContext::new);
592
593 let dbg_cx = if tcx.sess.opts.debuginfo != DebugInfo::None {
594 let dctx = debuginfo::CodegenUnitDebugContext::new(llmod);
595 debuginfo::metadata::build_compile_unit_di_node(
596 tcx,
597 codegen_unit.name().as_str(),
598 &dctx,
599 );
600 Some(dctx)
601 } else {
602 None
603 };
604
605 GenericCx(
606 FullCx {
607 tcx,
608 scx: SimpleCx::new(llmod, llcx, tcx.data_layout.pointer_size),
609 use_dll_storage_attrs,
610 tls_model,
611 codegen_unit,
612 instances: Default::default(),
613 vtables: Default::default(),
614 const_str_cache: Default::default(),
615 const_globals: Default::default(),
616 statics_to_rauw: RefCell::new(Vec::new()),
617 used_statics: Vec::new(),
618 compiler_used_statics: Vec::new(),
619 type_lowering: Default::default(),
620 scalar_lltypes: Default::default(),
621 coverage_cx,
622 dbg_cx,
623 eh_personality: Cell::new(None),
624 eh_catch_typeinfo: Cell::new(None),
625 rust_try_fn: Cell::new(None),
626 intrinsics: Default::default(),
627 local_gen_sym_counter: Cell::new(0),
628 renamed_statics: Default::default(),
629 },
630 PhantomData,
631 )
632 }
633
634 pub(crate) fn statics_to_rauw(&self) -> &RefCell<Vec<(&'ll Value, &'ll Value)>> {
635 &self.statics_to_rauw
636 }
637
638 #[inline]
640 #[track_caller]
641 pub(crate) fn coverage_cx(&self) -> &coverageinfo::CguCoverageContext<'ll, 'tcx> {
642 self.coverage_cx.as_ref().expect("only called when coverage instrumentation is enabled")
643 }
644
645 pub(crate) fn create_used_variable_impl(&self, name: &'static CStr, values: &[&'ll Value]) {
646 let array = self.const_array(self.type_ptr(), values);
647
648 let g = llvm::add_global(self.llmod, self.val_ty(array), name);
649 llvm::set_initializer(g, array);
650 llvm::set_linkage(g, llvm::Linkage::AppendingLinkage);
651 llvm::set_section(g, c"llvm.metadata");
652 }
653}
654impl<'ll> SimpleCx<'ll> {
655 pub(crate) fn get_return_type(&self, ty: &'ll Type) -> &'ll Type {
656 assert_eq!(self.type_kind(ty), TypeKind::Function);
657 unsafe { llvm::LLVMGetReturnType(ty) }
658 }
659 pub(crate) fn get_type_of_global(&self, val: &'ll Value) -> &'ll Type {
660 unsafe { llvm::LLVMGlobalGetValueType(val) }
661 }
662 pub(crate) fn val_ty(&self, v: &'ll Value) -> &'ll Type {
663 common::val_ty(v)
664 }
665}
666impl<'ll> SimpleCx<'ll> {
667 pub(crate) fn new(
668 llmod: &'ll llvm::Module,
669 llcx: &'ll llvm::Context,
670 pointer_size: Size,
671 ) -> Self {
672 let isize_ty = llvm::Type::ix_llcx(llcx, pointer_size.bits());
673 Self(SCx { llmod, llcx, isize_ty }, PhantomData)
674 }
675}
676
677impl<'ll, CX: Borrow<SCx<'ll>>> GenericCx<'ll, CX> {
678 pub(crate) fn get_metadata_value(&self, metadata: &'ll Metadata) -> &'ll Value {
679 llvm::LLVMMetadataAsValue(self.llcx(), metadata)
680 }
681
682 pub(crate) fn get_const_int(&self, ty: &'ll Type, val: u64) -> &'ll Value {
683 unsafe { llvm::LLVMConstInt(ty, val, llvm::False) }
684 }
685
686 pub(crate) fn get_function(&self, name: &str) -> Option<&'ll Value> {
687 let name = SmallCStr::new(name);
688 unsafe { llvm::LLVMGetNamedFunction((**self).borrow().llmod, name.as_ptr()) }
689 }
690
691 pub(crate) fn get_md_kind_id(&self, name: &str) -> llvm::MetadataKindId {
692 unsafe {
693 llvm::LLVMGetMDKindIDInContext(
694 self.llcx(),
695 name.as_ptr() as *const c_char,
696 name.len() as c_uint,
697 )
698 }
699 }
700
701 pub(crate) fn create_metadata(&self, name: String) -> Option<&'ll Metadata> {
702 Some(unsafe {
703 llvm::LLVMMDStringInContext2(self.llcx(), name.as_ptr() as *const c_char, name.len())
704 })
705 }
706
707 pub(crate) fn get_functions(&self) -> Vec<&'ll Value> {
708 let mut functions = vec![];
709 let mut func = unsafe { llvm::LLVMGetFirstFunction(self.llmod()) };
710 while let Some(f) = func {
711 functions.push(f);
712 func = unsafe { llvm::LLVMGetNextFunction(f) }
713 }
714 functions
715 }
716}
717
718impl<'ll, 'tcx> MiscCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> {
719 fn vtables(
720 &self,
721 ) -> &RefCell<FxHashMap<(Ty<'tcx>, Option<ty::ExistentialTraitRef<'tcx>>), &'ll Value>> {
722 &self.vtables
723 }
724
725 fn apply_vcall_visibility_metadata(
726 &self,
727 ty: Ty<'tcx>,
728 poly_trait_ref: Option<ty::ExistentialTraitRef<'tcx>>,
729 vtable: &'ll Value,
730 ) {
731 apply_vcall_visibility_metadata(self, ty, poly_trait_ref, vtable);
732 }
733
734 fn get_fn(&self, instance: Instance<'tcx>) -> &'ll Value {
735 get_fn(self, instance)
736 }
737
738 fn get_fn_addr(&self, instance: Instance<'tcx>) -> &'ll Value {
739 get_fn(self, instance)
740 }
741
742 fn eh_personality(&self) -> &'ll Value {
743 if let Some(llpersonality) = self.eh_personality.get() {
764 return llpersonality;
765 }
766
767 let name = if wants_msvc_seh(self.sess()) {
768 Some("__CxxFrameHandler3")
769 } else if wants_wasm_eh(self.sess()) {
770 Some("__gxx_wasm_personality_v0")
775 } else {
776 None
777 };
778
779 let tcx = self.tcx;
780 let llfn = match tcx.lang_items().eh_personality() {
781 Some(def_id) if name.is_none() => self.get_fn_addr(ty::Instance::expect_resolve(
782 tcx,
783 self.typing_env(),
784 def_id,
785 ty::List::empty(),
786 DUMMY_SP,
787 )),
788 _ => {
789 let name = name.unwrap_or("rust_eh_personality");
790 if let Some(llfn) = self.get_declared_value(name) {
791 llfn
792 } else {
793 let fty = self.type_variadic_func(&[], self.type_i32());
794 let llfn = self.declare_cfn(name, llvm::UnnamedAddr::Global, fty);
795 let target_cpu = attributes::target_cpu_attr(self);
796 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &[target_cpu]);
797 llfn
798 }
799 }
800 };
801 self.eh_personality.set(Some(llfn));
802 llfn
803 }
804
805 fn sess(&self) -> &Session {
806 self.tcx.sess
807 }
808
809 fn set_frame_pointer_type(&self, llfn: &'ll Value) {
810 if let Some(attr) = attributes::frame_pointer_type_attr(self) {
811 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &[attr]);
812 }
813 }
814
815 fn apply_target_cpu_attr(&self, llfn: &'ll Value) {
816 let mut attrs = SmallVec::<[_; 2]>::new();
817 attrs.push(attributes::target_cpu_attr(self));
818 attrs.extend(attributes::tune_cpu_attr(self));
819 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &attrs);
820 }
821
822 fn declare_c_main(&self, fn_type: Self::Type) -> Option<Self::Function> {
823 let entry_name = self.sess().target.entry_name.as_ref();
824 if self.get_declared_value(entry_name).is_none() {
825 Some(self.declare_entry_fn(
826 entry_name,
827 llvm::CallConv::from_conv(
828 self.sess().target.entry_abi,
829 self.sess().target.arch.borrow(),
830 ),
831 llvm::UnnamedAddr::Global,
832 fn_type,
833 ))
834 } else {
835 None
838 }
839 }
840}
841
842impl<'ll> CodegenCx<'ll, '_> {
843 pub(crate) fn get_intrinsic(
844 &self,
845 base_name: Cow<'static, str>,
846 type_params: &[&'ll Type],
847 ) -> (&'ll Type, &'ll Value) {
848 *self
849 .intrinsics
850 .borrow_mut()
851 .entry((base_name, SmallVec::from_slice(type_params)))
852 .or_insert_with_key(|(base_name, type_params)| {
853 self.declare_intrinsic(base_name, type_params)
854 })
855 }
856
857 fn declare_intrinsic(
858 &self,
859 base_name: &str,
860 type_params: &[&'ll Type],
861 ) -> (&'ll Type, &'ll Value) {
862 if base_name == "memcmp" {
866 let fn_ty = self
867 .type_func(&[self.type_ptr(), self.type_ptr(), self.type_isize()], self.type_int());
868 let f = self.declare_cfn("memcmp", llvm::UnnamedAddr::No, fn_ty);
869
870 return (fn_ty, f);
871 }
872
873 let intrinsic = llvm::Intrinsic::lookup(base_name.as_bytes())
874 .unwrap_or_else(|| bug!("Unknown intrinsic: `{base_name}`"));
875 let f = intrinsic.get_declaration(self.llmod, &type_params);
876
877 (self.get_type_of_global(f), f)
878 }
879
880 pub(crate) fn eh_catch_typeinfo(&self) -> &'ll Value {
881 if let Some(eh_catch_typeinfo) = self.eh_catch_typeinfo.get() {
882 return eh_catch_typeinfo;
883 }
884 let tcx = self.tcx;
885 assert!(self.sess().target.os == "emscripten");
886 let eh_catch_typeinfo = match tcx.lang_items().eh_catch_typeinfo() {
887 Some(def_id) => self.get_static(def_id),
888 _ => {
889 let ty = self.type_struct(&[self.type_ptr(), self.type_ptr()], false);
890 self.declare_global(&mangle_internal_symbol(self.tcx, "rust_eh_catch_typeinfo"), ty)
891 }
892 };
893 self.eh_catch_typeinfo.set(Some(eh_catch_typeinfo));
894 eh_catch_typeinfo
895 }
896}
897
898impl CodegenCx<'_, '_> {
899 pub(crate) fn generate_local_symbol_name(&self, prefix: &str) -> String {
902 let idx = self.local_gen_sym_counter.get();
903 self.local_gen_sym_counter.set(idx + 1);
904 let mut name = String::with_capacity(prefix.len() + 6);
907 name.push_str(prefix);
908 name.push('.');
909 name.push_str(&(idx as u64).to_base(ALPHANUMERIC_ONLY));
910 name
911 }
912}
913
914impl<'ll, CX: Borrow<SCx<'ll>>> GenericCx<'ll, CX> {
915 pub(crate) fn set_metadata<'a>(
917 &self,
918 val: &'a Value,
919 kind_id: impl Into<llvm::MetadataKindId>,
920 md: &'ll Metadata,
921 ) {
922 let node = self.get_metadata_value(md);
923 llvm::LLVMSetMetadata(val, kind_id.into(), node);
924 }
925}
926
927impl HasDataLayout for CodegenCx<'_, '_> {
928 #[inline]
929 fn data_layout(&self) -> &TargetDataLayout {
930 &self.tcx.data_layout
931 }
932}
933
934impl HasTargetSpec for CodegenCx<'_, '_> {
935 #[inline]
936 fn target_spec(&self) -> &Target {
937 &self.tcx.sess.target
938 }
939}
940
941impl<'tcx> ty::layout::HasTyCtxt<'tcx> for CodegenCx<'_, 'tcx> {
942 #[inline]
943 fn tcx(&self) -> TyCtxt<'tcx> {
944 self.tcx
945 }
946}
947
948impl<'tcx, 'll> HasTypingEnv<'tcx> for CodegenCx<'ll, 'tcx> {
949 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
950 ty::TypingEnv::fully_monomorphized()
951 }
952}
953
954impl<'tcx> LayoutOfHelpers<'tcx> for CodegenCx<'_, 'tcx> {
955 #[inline]
956 fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
957 if let LayoutError::SizeOverflow(_) | LayoutError::ReferencesError(_) = err {
958 self.tcx.dcx().emit_fatal(Spanned { span, node: err.into_diagnostic() })
959 } else {
960 self.tcx.dcx().emit_fatal(ssa_errors::FailedToGetLayout { span, ty, err })
961 }
962 }
963}
964
965impl<'tcx> FnAbiOfHelpers<'tcx> for CodegenCx<'_, 'tcx> {
966 #[inline]
967 fn handle_fn_abi_err(
968 &self,
969 err: FnAbiError<'tcx>,
970 span: Span,
971 fn_abi_request: FnAbiRequest<'tcx>,
972 ) -> ! {
973 match err {
974 FnAbiError::Layout(LayoutError::SizeOverflow(_) | LayoutError::Cycle(_)) => {
975 self.tcx.dcx().emit_fatal(Spanned { span, node: err });
976 }
977 _ => match fn_abi_request {
978 FnAbiRequest::OfFnPtr { sig, extra_args } => {
979 span_bug!(span, "`fn_abi_of_fn_ptr({sig}, {extra_args:?})` failed: {err:?}",);
980 }
981 FnAbiRequest::OfInstance { instance, extra_args } => {
982 span_bug!(
983 span,
984 "`fn_abi_of_instance({instance}, {extra_args:?})` failed: {err:?}",
985 );
986 }
987 },
988 }
989 }
990}