1use rustc_hir::attrs::{InlineAttr, InstructionSetAttr, OptimizeAttr, RtsanSetting};
3use rustc_hir::def_id::DefId;
4use rustc_hir::find_attr;
5use rustc_middle::middle::codegen_fn_attrs::{
6 CodegenFnAttrFlags, CodegenFnAttrs, PatchableFunctionEntry, SanitizerFnAttrs,
7};
8use rustc_middle::ty::{self, TyCtxt};
9use rustc_session::config::{BranchProtection, FunctionReturn, OptLevel, PAuthKey, PacRet};
10use rustc_symbol_mangling::mangle_internal_symbol;
11use rustc_target::spec::{Arch, FramePointer, SanitizerSet, StackProbeType, StackProtector};
12use smallvec::SmallVec;
13
14use crate::context::SimpleCx;
15use crate::errors::SanitizerMemtagRequiresMte;
16use crate::llvm::AttributePlace::Function;
17use crate::llvm::{
18 self, AllocKindFlags, Attribute, AttributeKind, AttributePlace, MemoryEffects, Value,
19};
20use crate::{Session, attributes, llvm_util};
21
22pub(crate) fn apply_to_llfn(llfn: &Value, idx: AttributePlace, attrs: &[&Attribute]) {
23 if !attrs.is_empty() {
24 llvm::AddFunctionAttributes(llfn, idx, attrs);
25 }
26}
27
28pub(crate) fn apply_to_callsite(callsite: &Value, idx: AttributePlace, attrs: &[&Attribute]) {
29 if !attrs.is_empty() {
30 llvm::AddCallSiteAttributes(callsite, idx, attrs);
31 }
32}
33
34pub(crate) fn has_string_attr(llfn: &Value, name: &str) -> bool {
35 llvm::HasStringAttribute(llfn, name)
36}
37
38pub(crate) fn remove_string_attr_from_llfn(llfn: &Value, name: &str) {
39 llvm::RemoveStringAttrFromFn(llfn, name);
40}
41
42pub(crate) fn inline_attr<'ll, 'tcx>(
44 cx: &SimpleCx<'ll>,
45 tcx: TyCtxt<'tcx>,
46 instance: ty::Instance<'tcx>,
47) -> Option<&'ll Attribute> {
48 let codegen_fn_attrs = tcx.codegen_fn_attrs(instance.def_id());
50 let inline = match (codegen_fn_attrs.inline, &codegen_fn_attrs.optimize) {
51 (_, OptimizeAttr::DoNotOptimize) => InlineAttr::Never,
52 (InlineAttr::None, _) if instance.def.requires_inline(tcx) => InlineAttr::Hint,
53 (inline, _) => inline,
54 };
55
56 if !tcx.sess.opts.unstable_opts.inline_llvm {
57 return Some(AttributeKind::NoInline.create_attr(cx.llcx));
59 }
60 match inline {
61 InlineAttr::Hint => Some(AttributeKind::InlineHint.create_attr(cx.llcx)),
62 InlineAttr::Always | InlineAttr::Force { .. } => {
63 Some(AttributeKind::AlwaysInline.create_attr(cx.llcx))
64 }
65 InlineAttr::Never => {
66 if tcx.sess.target.arch != Arch::AmdGpu {
67 Some(AttributeKind::NoInline.create_attr(cx.llcx))
68 } else {
69 None
70 }
71 }
72 InlineAttr::None => None,
73 }
74}
75
76#[inline]
77fn patchable_function_entry_attrs<'ll>(
78 cx: &SimpleCx<'ll>,
79 sess: &Session,
80 attr: Option<PatchableFunctionEntry>,
81) -> SmallVec<[&'ll Attribute; 2]> {
82 let mut attrs = SmallVec::new();
83 let patchable_spec = attr.unwrap_or_else(|| {
84 PatchableFunctionEntry::from_config(sess.opts.unstable_opts.patchable_function_entry)
85 });
86 let entry = patchable_spec.entry();
87 let prefix = patchable_spec.prefix();
88 if entry > 0 {
89 attrs.push(llvm::CreateAttrStringValue(
90 cx.llcx,
91 "patchable-function-entry",
92 &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", entry))
})format!("{}", entry),
93 ));
94 }
95 if prefix > 0 {
96 attrs.push(llvm::CreateAttrStringValue(
97 cx.llcx,
98 "patchable-function-prefix",
99 &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", prefix))
})format!("{}", prefix),
100 ));
101 }
102 attrs
103}
104
105#[inline]
107pub(crate) fn sanitize_attrs<'ll, 'tcx>(
108 cx: &SimpleCx<'ll>,
109 tcx: TyCtxt<'tcx>,
110 sanitizer_fn_attr: SanitizerFnAttrs,
111) -> SmallVec<[&'ll Attribute; 4]> {
112 let mut attrs = SmallVec::new();
113 let enabled = tcx.sess.sanitizers() - sanitizer_fn_attr.disabled;
114 if enabled.contains(SanitizerSet::ADDRESS) || enabled.contains(SanitizerSet::KERNELADDRESS) {
115 attrs.push(llvm::AttributeKind::SanitizeAddress.create_attr(cx.llcx));
116 }
117 if enabled.contains(SanitizerSet::MEMORY) {
118 attrs.push(llvm::AttributeKind::SanitizeMemory.create_attr(cx.llcx));
119 }
120 if enabled.contains(SanitizerSet::THREAD) {
121 attrs.push(llvm::AttributeKind::SanitizeThread.create_attr(cx.llcx));
122 }
123 if enabled.contains(SanitizerSet::HWADDRESS) {
124 attrs.push(llvm::AttributeKind::SanitizeHWAddress.create_attr(cx.llcx));
125 }
126 if enabled.contains(SanitizerSet::SHADOWCALLSTACK) {
127 attrs.push(llvm::AttributeKind::ShadowCallStack.create_attr(cx.llcx));
128 }
129 if enabled.contains(SanitizerSet::MEMTAG) {
130 let features = tcx.global_backend_features(());
132 let mte_feature =
133 features.iter().map(|s| &s[..]).rfind(|n| ["+mte", "-mte"].contains(&&n[..]));
134 if let None | Some("-mte") = mte_feature {
135 tcx.dcx().emit_err(SanitizerMemtagRequiresMte);
136 }
137
138 attrs.push(llvm::AttributeKind::SanitizeMemTag.create_attr(cx.llcx));
139 }
140 if enabled.contains(SanitizerSet::SAFESTACK) {
141 attrs.push(llvm::AttributeKind::SanitizeSafeStack.create_attr(cx.llcx));
142 }
143 if tcx.sess.sanitizers().contains(SanitizerSet::REALTIME) {
144 match sanitizer_fn_attr.rtsan_setting {
145 RtsanSetting::Nonblocking => {
146 attrs.push(llvm::AttributeKind::SanitizeRealtimeNonblocking.create_attr(cx.llcx))
147 }
148 RtsanSetting::Blocking => {
149 attrs.push(llvm::AttributeKind::SanitizeRealtimeBlocking.create_attr(cx.llcx))
150 }
151 RtsanSetting::Caller => (),
153 }
154 }
155 attrs
156}
157
158#[inline]
160pub(crate) fn uwtable_attr(llcx: &llvm::Context, use_sync_unwind: Option<bool>) -> &Attribute {
161 let async_unwind = !use_sync_unwind.unwrap_or(false);
165 llvm::CreateUWTableAttr(llcx, async_unwind)
166}
167
168pub(crate) fn frame_pointer_type_attr<'ll>(
169 cx: &SimpleCx<'ll>,
170 sess: &Session,
171) -> Option<&'ll Attribute> {
172 let mut fp = sess.target.frame_pointer;
173 let opts = &sess.opts;
174 if opts.unstable_opts.instrument_mcount {
177 fp.ratchet(FramePointer::Always);
178 }
179 fp.ratchet(opts.cg.force_frame_pointers);
180 let attr_value = match fp {
181 FramePointer::Always => "all",
182 FramePointer::NonLeaf => "non-leaf",
183 FramePointer::MayOmit => return None,
184 };
185 Some(llvm::CreateAttrStringValue(cx.llcx, "frame-pointer", attr_value))
186}
187
188fn function_return_attr<'ll>(cx: &SimpleCx<'ll>, sess: &Session) -> Option<&'ll Attribute> {
189 let function_return_attr = match sess.opts.unstable_opts.function_return {
190 FunctionReturn::Keep => return None,
191 FunctionReturn::ThunkExtern => AttributeKind::FnRetThunkExtern,
192 };
193
194 Some(function_return_attr.create_attr(cx.llcx))
195}
196
197#[inline]
199fn instrument_function_attr<'ll>(
200 cx: &SimpleCx<'ll>,
201 sess: &Session,
202) -> SmallVec<[&'ll Attribute; 4]> {
203 let mut attrs = SmallVec::new();
204 if sess.opts.unstable_opts.instrument_mcount {
205 let mcount_name = match &sess.target.llvm_mcount_intrinsic {
211 Some(llvm_mcount_intrinsic) => llvm_mcount_intrinsic.as_ref(),
212 None => sess.target.mcount.as_ref(),
213 };
214
215 attrs.push(llvm::CreateAttrStringValue(
216 cx.llcx,
217 "instrument-function-entry-inlined",
218 mcount_name,
219 ));
220 }
221 if let Some(options) = &sess.opts.unstable_opts.instrument_xray {
222 if options.always {
226 attrs.push(llvm::CreateAttrStringValue(cx.llcx, "function-instrument", "xray-always"));
227 }
228 if options.never {
229 attrs.push(llvm::CreateAttrStringValue(cx.llcx, "function-instrument", "xray-never"));
230 }
231 if options.ignore_loops {
232 attrs.push(llvm::CreateAttrString(cx.llcx, "xray-ignore-loops"));
233 }
234 let threshold = options.instruction_threshold.unwrap_or(200);
237 attrs.push(llvm::CreateAttrStringValue(
238 cx.llcx,
239 "xray-instruction-threshold",
240 &threshold.to_string(),
241 ));
242 if options.skip_entry {
243 attrs.push(llvm::CreateAttrString(cx.llcx, "xray-skip-entry"));
244 }
245 if options.skip_exit {
246 attrs.push(llvm::CreateAttrString(cx.llcx, "xray-skip-exit"));
247 }
248 }
249 attrs
250}
251
252fn nojumptables_attr<'ll>(cx: &SimpleCx<'ll>, sess: &Session) -> Option<&'ll Attribute> {
253 if sess.opts.cg.jump_tables {
254 return None;
255 }
256
257 Some(llvm::CreateAttrStringValue(cx.llcx, "no-jump-tables", "true"))
258}
259
260fn probestack_attr<'ll, 'tcx>(cx: &SimpleCx<'ll>, tcx: TyCtxt<'tcx>) -> Option<&'ll Attribute> {
261 if tcx.sess.sanitizers().intersects(SanitizerSet::ADDRESS | SanitizerSet::THREAD) {
265 return None;
266 }
267
268 if tcx.sess.opts.cg.profile_generate.enabled() {
270 return None;
271 }
272
273 let attr_value = match tcx.sess.target.stack_probes {
274 StackProbeType::None => return None,
275 StackProbeType::Inline => "inline-asm",
278 StackProbeType::Call => &mangle_internal_symbol(tcx, "__rust_probestack"),
281 StackProbeType::InlineOrCall { min_llvm_version_for_inline } => {
283 if llvm_util::get_version() < min_llvm_version_for_inline {
284 &mangle_internal_symbol(tcx, "__rust_probestack")
285 } else {
286 "inline-asm"
287 }
288 }
289 };
290 Some(llvm::CreateAttrStringValue(cx.llcx, "probe-stack", attr_value))
291}
292
293fn stackprotector_attr<'ll>(cx: &SimpleCx<'ll>, sess: &Session) -> Option<&'ll Attribute> {
294 let sspattr = match sess.stack_protector() {
295 StackProtector::None => return None,
296 StackProtector::All => AttributeKind::StackProtectReq,
297 StackProtector::Strong => AttributeKind::StackProtectStrong,
298 StackProtector::Basic => AttributeKind::StackProtect,
299 };
300
301 Some(sspattr.create_attr(cx.llcx))
302}
303
304pub(crate) fn target_cpu_attr<'ll>(cx: &SimpleCx<'ll>, sess: &Session) -> &'ll Attribute {
305 let target_cpu = llvm_util::target_cpu(sess);
306 llvm::CreateAttrStringValue(cx.llcx, "target-cpu", target_cpu)
307}
308
309pub(crate) fn tune_cpu_attr<'ll>(cx: &SimpleCx<'ll>, sess: &Session) -> Option<&'ll Attribute> {
310 llvm_util::tune_cpu(sess)
311 .map(|tune_cpu| llvm::CreateAttrStringValue(cx.llcx, "tune-cpu", tune_cpu))
312}
313
314pub(crate) fn target_features_attr<'ll, 'tcx>(
316 cx: &SimpleCx<'ll>,
317 tcx: TyCtxt<'tcx>,
318 function_features: Vec<String>,
319) -> Option<&'ll Attribute> {
320 let global_features = tcx.global_backend_features(()).iter().map(String::as_str);
321 let function_features = function_features.iter().map(String::as_str);
322 let target_features =
323 global_features.chain(function_features).intersperse(",").collect::<String>();
324 (!target_features.is_empty())
325 .then(|| llvm::CreateAttrStringValue(cx.llcx, "target-features", &target_features))
326}
327
328pub(crate) fn non_lazy_bind_attr<'ll>(
331 cx: &SimpleCx<'ll>,
332 sess: &Session,
333) -> Option<&'ll Attribute> {
334 if !sess.needs_plt() { Some(AttributeKind::NonLazyBind.create_attr(cx.llcx)) } else { None }
336}
337
338#[inline]
340pub(crate) fn default_optimisation_attrs<'ll>(
341 cx: &SimpleCx<'ll>,
342 sess: &Session,
343) -> SmallVec<[&'ll Attribute; 2]> {
344 let mut attrs = SmallVec::new();
345 match sess.opts.optimize {
346 OptLevel::Size => {
347 attrs.push(llvm::AttributeKind::OptimizeForSize.create_attr(cx.llcx));
348 }
349 OptLevel::SizeMin => {
350 attrs.push(llvm::AttributeKind::MinSize.create_attr(cx.llcx));
351 attrs.push(llvm::AttributeKind::OptimizeForSize.create_attr(cx.llcx));
352 }
353 _ => {}
354 }
355 attrs
356}
357
358fn create_alloc_family_attr(llcx: &llvm::Context) -> &llvm::Attribute {
359 llvm::CreateAttrStringValue(llcx, "alloc-family", "__rust_alloc")
360}
361
362pub(crate) fn llfn_attrs_from_instance<'ll, 'tcx>(
366 cx: &SimpleCx<'ll>,
367 tcx: TyCtxt<'tcx>,
368 llfn: &'ll Value,
369 codegen_fn_attrs: &CodegenFnAttrs,
370 instance: Option<ty::Instance<'tcx>>,
371) {
372 let sess = tcx.sess;
373 let mut to_add = SmallVec::<[_; 16]>::new();
374
375 match codegen_fn_attrs.optimize {
376 OptimizeAttr::Default => {
377 to_add.extend(default_optimisation_attrs(cx, sess));
378 }
379 OptimizeAttr::DoNotOptimize => {
380 to_add.push(llvm::AttributeKind::OptimizeNone.create_attr(cx.llcx));
381 }
382 OptimizeAttr::Size => {
383 to_add.push(llvm::AttributeKind::MinSize.create_attr(cx.llcx));
384 to_add.push(llvm::AttributeKind::OptimizeForSize.create_attr(cx.llcx));
385 }
386 OptimizeAttr::Speed => {}
387 }
388
389 if sess.must_emit_unwind_tables() {
390 to_add.push(uwtable_attr(cx.llcx, sess.opts.unstable_opts.use_sync_unwind));
391 }
392
393 if sess.opts.unstable_opts.profile_sample_use.is_some() {
394 to_add.push(llvm::CreateAttrString(cx.llcx, "use-sample-profile"));
395 }
396
397 to_add.extend(frame_pointer_type_attr(cx, sess));
399 to_add.extend(function_return_attr(cx, sess));
400 to_add.extend(instrument_function_attr(cx, sess));
401 to_add.extend(nojumptables_attr(cx, sess));
402 to_add.extend(probestack_attr(cx, tcx));
403 to_add.extend(stackprotector_attr(cx, sess));
404
405 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NO_BUILTINS) {
406 to_add.push(llvm::CreateAttrString(cx.llcx, "no-builtins"));
407 }
408
409 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::OFFLOAD_KERNEL) {
410 to_add.push(llvm::CreateAttrString(cx.llcx, "offload-kernel"))
411 }
412
413 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
414 to_add.push(AttributeKind::Cold.create_attr(cx.llcx));
415 }
416 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_PURE) {
417 to_add.push(MemoryEffects::ReadOnly.create_attr(cx.llcx));
418 }
419 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_CONST) {
420 to_add.push(MemoryEffects::None.create_attr(cx.llcx));
421 }
422 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
423 } else {
427 to_add.extend(sanitize_attrs(cx, tcx, codegen_fn_attrs.sanitizers));
429
430 if let Some(BranchProtection { bti, pac_ret, gcs }) =
432 sess.opts.unstable_opts.branch_protection
433 {
434 if !(sess.target.arch == Arch::AArch64) {
::core::panicking::panic("assertion failed: sess.target.arch == Arch::AArch64")
};assert!(sess.target.arch == Arch::AArch64);
435 if bti {
436 to_add.push(llvm::CreateAttrString(cx.llcx, "branch-target-enforcement"));
437 }
438 if gcs {
439 to_add.push(llvm::CreateAttrString(cx.llcx, "guarded-control-stack"));
440 }
441 if let Some(PacRet { leaf, pc, key }) = pac_ret {
442 if pc {
443 to_add.push(llvm::CreateAttrString(cx.llcx, "branch-protection-pauth-lr"));
444 }
445 to_add.push(llvm::CreateAttrStringValue(
446 cx.llcx,
447 "sign-return-address",
448 if leaf { "all" } else { "non-leaf" },
449 ));
450 to_add.push(llvm::CreateAttrStringValue(
451 cx.llcx,
452 "sign-return-address-key",
453 if key == PAuthKey::A { "a_key" } else { "b_key" },
454 ));
455 }
456 }
457 }
458 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR)
459 || codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR_ZEROED)
460 {
461 to_add.push(create_alloc_family_attr(cx.llcx));
462 if let Some(instance) = instance
463 && let Some(name) = {
'done:
{
for i in tcx.get_all_attrs(instance.def_id()) {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(rustc_hir::attrs::AttributeKind::RustcAllocatorZeroedVariant {
name }) => {
break 'done Some(name);
}
_ => {}
}
}
None
}
}find_attr!(tcx.get_all_attrs(instance.def_id()), rustc_hir::attrs::AttributeKind::RustcAllocatorZeroedVariant {name} => name)
464 {
465 to_add.push(llvm::CreateAttrStringValue(
466 cx.llcx,
467 "alloc-variant-zeroed",
468 &mangle_internal_symbol(tcx, name.as_str()),
469 ));
470 }
471 let alloc_align = AttributeKind::AllocAlign.create_attr(cx.llcx);
473 attributes::apply_to_llfn(llfn, AttributePlace::Argument(1), &[alloc_align]);
474 to_add.push(llvm::CreateAllocSizeAttr(cx.llcx, 0));
475 let mut flags = AllocKindFlags::Alloc | AllocKindFlags::Aligned;
476 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR) {
477 flags |= AllocKindFlags::Uninitialized;
478 } else {
479 flags |= AllocKindFlags::Zeroed;
480 }
481 to_add.push(llvm::CreateAllocKindAttr(cx.llcx, flags));
482 let no_alias = AttributeKind::NoAlias.create_attr(cx.llcx);
485 attributes::apply_to_llfn(llfn, AttributePlace::ReturnValue, &[no_alias]);
486 }
487 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::REALLOCATOR) {
488 to_add.push(create_alloc_family_attr(cx.llcx));
489 to_add.push(llvm::CreateAllocKindAttr(
490 cx.llcx,
491 AllocKindFlags::Realloc | AllocKindFlags::Aligned,
492 ));
493 let allocated_pointer = AttributeKind::AllocatedPointer.create_attr(cx.llcx);
495 attributes::apply_to_llfn(llfn, AttributePlace::Argument(0), &[allocated_pointer]);
496 let alloc_align = AttributeKind::AllocAlign.create_attr(cx.llcx);
498 attributes::apply_to_llfn(llfn, AttributePlace::Argument(2), &[alloc_align]);
499 to_add.push(llvm::CreateAllocSizeAttr(cx.llcx, 3));
500 let no_alias = AttributeKind::NoAlias.create_attr(cx.llcx);
501 attributes::apply_to_llfn(llfn, AttributePlace::ReturnValue, &[no_alias]);
502 }
503 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::DEALLOCATOR) {
504 to_add.push(create_alloc_family_attr(cx.llcx));
505 to_add.push(llvm::CreateAllocKindAttr(cx.llcx, AllocKindFlags::Free));
506 let allocated_pointer = AttributeKind::AllocatedPointer.create_attr(cx.llcx);
508 let attrs: &[_] = if llvm_util::get_version() >= (21, 0, 0) {
509 let captures_addr = AttributeKind::CapturesAddress.create_attr(cx.llcx);
513 &[allocated_pointer, captures_addr]
514 } else {
515 &[allocated_pointer]
516 };
517 attributes::apply_to_llfn(llfn, AttributePlace::Argument(0), attrs);
518 }
519 if let Some(align) = codegen_fn_attrs.alignment {
520 llvm::set_alignment(llfn, align);
521 }
522 to_add.extend(patchable_function_entry_attrs(
523 cx,
524 sess,
525 codegen_fn_attrs.patchable_function_entry,
526 ));
527
528 to_add.push(target_cpu_attr(cx, sess));
532 to_add.extend(tune_cpu_attr(cx, sess));
535
536 let function_features =
537 codegen_fn_attrs.target_features.iter().map(|f| f.name.as_str()).collect::<Vec<&str>>();
538
539 if function_features.is_empty() {
542 if let Some(instance) = instance
543 && let Some(inline_attr) = inline_attr(cx, tcx, instance)
544 {
545 to_add.push(inline_attr);
546 }
547 }
548
549 let function_features = function_features
550 .iter()
551 .flat_map(|feat| llvm_util::to_llvm_features(sess, feat))
553 .flat_map(|feat| feat.into_iter().map(|f| ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("+{0}", f)) })format!("+{f}")))
555 .chain(codegen_fn_attrs.instruction_set.iter().map(|x| match x {
556 InstructionSetAttr::ArmA32 => "-thumb-mode".to_string(),
557 InstructionSetAttr::ArmT32 => "+thumb-mode".to_string(),
558 }))
559 .collect::<Vec<String>>();
560
561 if sess.target.is_like_wasm {
562 if let Some(instance) = instance
565 && let Some(module) = wasm_import_module(tcx, instance.def_id())
566 {
567 to_add.push(llvm::CreateAttrStringValue(cx.llcx, "wasm-import-module", module));
568
569 let name =
570 codegen_fn_attrs.symbol_name.unwrap_or_else(|| tcx.item_name(instance.def_id()));
571 let name = name.as_str();
572 to_add.push(llvm::CreateAttrStringValue(cx.llcx, "wasm-import-name", name));
573 }
574 }
575
576 to_add.extend(target_features_attr(cx, tcx, function_features));
577
578 attributes::apply_to_llfn(llfn, Function, &to_add);
579}
580
581fn wasm_import_module(tcx: TyCtxt<'_>, id: DefId) -> Option<&String> {
582 tcx.wasm_import_module_map(id.krate).get(&id)
583}