1use std::borrow::{Borrow, Cow};
2use std::iter;
3use std::ops::Deref;
4
5use rustc_ast::expand::typetree::FncTree;
6pub(crate) mod autodiff;
7pub(crate) mod gpu_offload;
8
9use libc::{c_char, c_uint};
10use rustc_abi::{self as abi, Align, CanonAbi, Size, WrappingRange};
11use rustc_codegen_ssa::MemFlags;
12use rustc_codegen_ssa::common::{IntPredicate, RealPredicate, SynchronizationScope, TypeKind};
13use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
14use rustc_codegen_ssa::mir::place::PlaceRef;
15use rustc_codegen_ssa::traits::*;
16use rustc_data_structures::small_c_str::SmallCStr;
17use rustc_hir::attrs::{AttributeKind, UnrollAttr};
18use rustc_hir::def_id::DefId;
19use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
20use rustc_middle::ty::layout::{
21 FnAbiError, FnAbiOfHelpers, FnAbiRequest, HasTypingEnv, LayoutError, LayoutOfHelpers,
22 TyAndLayout,
23};
24use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
25use rustc_sanitizers::{cfi, kcfi};
26use rustc_session::config::OptLevel;
27use rustc_span::Span;
28use rustc_target::callconv::{FnAbi, PassMode};
29use rustc_target::spec::{Arch, HasTargetSpec, LlvmAbi, SanitizerSet, Target};
30use smallvec::SmallVec;
31use tracing::{debug, instrument};
32
33use crate::abi::FnAbiLlvmExt;
34use crate::attributes;
35use crate::common::Funclet;
36use crate::context::{CodegenCx, FullCx, GenericCx, SCx};
37use crate::llvm::{
38 self, AtomicOrdering, AtomicRmwBinOp, BasicBlock, FromGeneric, GEPNoWrapFlags, Metadata, TRUE,
39 ToLlvmBool, Type, Value,
40};
41use crate::type_of::LayoutLlvmExt;
42
43#[must_use]
44pub(crate) struct GenericBuilder<'a, 'll, CX: Borrow<SCx<'ll>>> {
45 pub llbuilder: &'ll mut llvm::Builder<'ll>,
46 pub cx: &'a GenericCx<'ll, CX>,
47}
48
49pub(crate) type SBuilder<'a, 'll> = GenericBuilder<'a, 'll, SCx<'ll>>;
50pub(crate) type Builder<'a, 'll, 'tcx> = GenericBuilder<'a, 'll, FullCx<'ll, 'tcx>>;
51
52impl<'a, 'll, CX: Borrow<SCx<'ll>>> Drop for GenericBuilder<'a, 'll, CX> {
53 fn drop(&mut self) {
54 unsafe {
55 llvm::LLVMDisposeBuilder(&mut *(self.llbuilder as *mut _));
56 }
57 }
58}
59
60impl<'a, 'll> SBuilder<'a, 'll> {
61 pub(crate) fn call(
62 &mut self,
63 llty: &'ll Type,
64 llfn: &'ll Value,
65 args: &[&'ll Value],
66 funclet: Option<&Funclet<'ll>>,
67 ) -> &'ll Value {
68 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/builder.rs:68",
"rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
::tracing_core::__macro_support::Option::Some(68u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("call {0:?} with args ({1:?})",
llfn, args) as &dyn Value))])
});
} else { ; }
};debug!("call {:?} with args ({:?})", llfn, args);
69
70 let args = self.check_call("call", llty, llfn, args);
71 let funclet_bundle = funclet.map(|funclet| funclet.bundle());
72 let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
73 if let Some(funclet_bundle) = funclet_bundle {
74 bundles.push(funclet_bundle);
75 }
76
77 let call = unsafe {
78 llvm::LLVMBuildCallWithOperandBundles(
79 self.llbuilder,
80 llty,
81 llfn,
82 args.as_ptr() as *const &llvm::Value,
83 args.len() as c_uint,
84 bundles.as_ptr(),
85 bundles.len() as c_uint,
86 c"".as_ptr(),
87 )
88 };
89 call
90 }
91}
92
93impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
94 fn with_cx(scx: &'a GenericCx<'ll, CX>) -> Self {
95 let llbuilder = unsafe { llvm::LLVMCreateBuilderInContext(scx.deref().borrow().llcx) };
97 GenericBuilder { llbuilder, cx: scx }
98 }
99
100 pub(crate) fn append_block(
101 cx: &'a GenericCx<'ll, CX>,
102 llfn: &'ll Value,
103 name: &str,
104 ) -> &'ll BasicBlock {
105 unsafe {
106 let name = SmallCStr::new(name);
107 llvm::LLVMAppendBasicBlockInContext(cx.llcx(), llfn, name.as_ptr())
108 }
109 }
110
111 pub(crate) fn trunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
112 unsafe { llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
113 }
114
115 pub(crate) fn bitcast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
116 unsafe { llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty, UNNAMED) }
117 }
118
119 pub(crate) fn ret_void(&mut self) {
120 llvm::LLVMBuildRetVoid(self.llbuilder);
121 }
122
123 pub(crate) fn ret(&mut self, v: &'ll Value) {
124 unsafe {
125 llvm::LLVMBuildRet(self.llbuilder, v);
126 }
127 }
128
129 pub(crate) fn build(cx: &'a GenericCx<'ll, CX>, llbb: &'ll BasicBlock) -> Self {
130 let bx = Self::with_cx(cx);
131 unsafe {
132 llvm::LLVMPositionBuilderAtEnd(bx.llbuilder, llbb);
133 }
134 bx
135 }
136
137 pub(crate) fn direct_alloca(&mut self, ty: &'ll Type, align: Align, name: &str) -> &'ll Value {
142 let val = unsafe {
143 let alloca = llvm::LLVMBuildAlloca(self.llbuilder, ty, UNNAMED);
144 llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
145 llvm::LLVMBuildPointerCast(self.llbuilder, alloca, self.cx.type_ptr(), UNNAMED)
147 };
148 if name != "" {
149 let name = std::ffi::CString::new(name).unwrap();
150 llvm::set_value_name(val, &name.as_bytes());
151 }
152 val
153 }
154
155 pub(crate) fn inbounds_gep(
156 &mut self,
157 ty: &'ll Type,
158 ptr: &'ll Value,
159 indices: &[&'ll Value],
160 ) -> &'ll Value {
161 unsafe {
162 llvm::LLVMBuildGEPWithNoWrapFlags(
163 self.llbuilder,
164 ty,
165 ptr,
166 indices.as_ptr(),
167 indices.len() as c_uint,
168 UNNAMED,
169 GEPNoWrapFlags::InBounds,
170 )
171 }
172 }
173
174 pub(crate) fn store(&mut self, val: &'ll Value, ptr: &'ll Value, align: Align) -> &'ll Value {
175 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/builder.rs:175",
"rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
::tracing_core::__macro_support::Option::Some(175u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("Store {0:?} -> {1:?}",
val, ptr) as &dyn Value))])
});
} else { ; }
};debug!("Store {:?} -> {:?}", val, ptr);
176 {
match (&self.cx.type_kind(self.cx.val_ty(ptr)), &TypeKind::Pointer) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(self.cx.type_kind(self.cx.val_ty(ptr)), TypeKind::Pointer);
177 unsafe {
178 let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
179 llvm::LLVMSetAlignment(store, align.bytes() as c_uint);
180 store
181 }
182 }
183
184 pub(crate) fn load(&mut self, ty: &'ll Type, ptr: &'ll Value, align: Align) -> &'ll Value {
185 unsafe {
186 let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
187 llvm::LLVMSetAlignment(load, align.bytes() as c_uint);
188 load
189 }
190 }
191}
192
193pub(crate) const UNNAMED: *const c_char = c"".as_ptr();
197
198impl<'ll, CX: Borrow<SCx<'ll>>> BackendTypes for GenericBuilder<'_, 'll, CX> {
199 type Function = <GenericCx<'ll, CX> as BackendTypes>::Function;
200 type BasicBlock = <GenericCx<'ll, CX> as BackendTypes>::BasicBlock;
201 type Funclet = <GenericCx<'ll, CX> as BackendTypes>::Funclet;
202
203 type Value = <GenericCx<'ll, CX> as BackendTypes>::Value;
204 type Type = <GenericCx<'ll, CX> as BackendTypes>::Type;
205 type FunctionSignature = <GenericCx<'ll, CX> as BackendTypes>::FunctionSignature;
206
207 type DIScope = <GenericCx<'ll, CX> as BackendTypes>::DIScope;
208 type DILocation = <GenericCx<'ll, CX> as BackendTypes>::DILocation;
209 type DIVariable = <GenericCx<'ll, CX> as BackendTypes>::DIVariable;
210}
211
212impl abi::HasDataLayout for Builder<'_, '_, '_> {
213 fn data_layout(&self) -> &abi::TargetDataLayout {
214 self.cx.data_layout()
215 }
216}
217
218impl<'tcx> ty::layout::HasTyCtxt<'tcx> for Builder<'_, '_, 'tcx> {
219 #[inline]
220 fn tcx(&self) -> TyCtxt<'tcx> {
221 self.cx.tcx
222 }
223}
224
225impl<'tcx> ty::layout::HasTypingEnv<'tcx> for Builder<'_, '_, 'tcx> {
226 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
227 self.cx.typing_env()
228 }
229}
230
231impl HasTargetSpec for Builder<'_, '_, '_> {
232 #[inline]
233 fn target_spec(&self) -> &Target {
234 self.cx.target_spec()
235 }
236}
237
238impl<'tcx> LayoutOfHelpers<'tcx> for Builder<'_, '_, 'tcx> {
239 #[inline]
240 fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
241 self.cx.handle_layout_err(err, span, ty)
242 }
243}
244
245impl<'tcx> FnAbiOfHelpers<'tcx> for Builder<'_, '_, 'tcx> {
246 #[inline]
247 fn handle_fn_abi_err(
248 &self,
249 err: FnAbiError<'tcx>,
250 span: Span,
251 fn_abi_request: FnAbiRequest<'tcx>,
252 ) -> ! {
253 self.cx.handle_fn_abi_err(err, span, fn_abi_request)
254 }
255}
256
257impl<'ll, 'tcx> Deref for Builder<'_, 'll, 'tcx> {
258 type Target = CodegenCx<'ll, 'tcx>;
259
260 #[inline]
261 fn deref(&self) -> &Self::Target {
262 self.cx
263 }
264}
265
266macro_rules! math_builder_methods {
267 ($($name:ident($($arg:ident),*) => $llvm_capi:ident),+ $(,)?) => {
268 $(fn $name(&mut self, $($arg: &'ll Value),*) -> &'ll Value {
269 unsafe {
270 llvm::$llvm_capi(self.llbuilder, $($arg,)* UNNAMED)
271 }
272 })+
273 }
274}
275
276macro_rules! set_math_builder_methods {
277 ($($name:ident($($arg:ident),*) => ($llvm_capi:ident, $llvm_set_math:ident)),+ $(,)?) => {
278 $(fn $name(&mut self, $($arg: &'ll Value),*) -> &'ll Value {
279 unsafe {
280 let instr = llvm::$llvm_capi(self.llbuilder, $($arg,)* UNNAMED);
281 llvm::$llvm_set_math(instr);
282 instr
283 }
284 })+
285 }
286}
287
288impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> {
289 type CodegenCx = CodegenCx<'ll, 'tcx>;
290
291 fn build(cx: &'a CodegenCx<'ll, 'tcx>, llbb: &'ll BasicBlock) -> Self {
292 let bx = Builder::with_cx(cx);
293 unsafe {
294 llvm::LLVMPositionBuilderAtEnd(bx.llbuilder, llbb);
295 }
296 bx
297 }
298
299 fn cx(&self) -> &CodegenCx<'ll, 'tcx> {
300 self.cx
301 }
302
303 fn llbb(&self) -> &'ll BasicBlock {
304 unsafe { llvm::LLVMGetInsertBlock(self.llbuilder) }
305 }
306
307 fn set_span(&mut self, _span: Span) {}
308
309 fn append_block(cx: &'a CodegenCx<'ll, 'tcx>, llfn: &'ll Value, name: &str) -> &'ll BasicBlock {
310 unsafe {
311 let name = SmallCStr::new(name);
312 llvm::LLVMAppendBasicBlockInContext(cx.llcx, llfn, name.as_ptr())
313 }
314 }
315
316 fn append_sibling_block(&mut self, name: &str) -> &'ll BasicBlock {
317 Self::append_block(self.cx, self.llfn(), name)
318 }
319
320 fn switch_to_block(&mut self, llbb: Self::BasicBlock) {
321 *self = Self::build(self.cx, llbb)
322 }
323
324 fn ret_void(&mut self) {
325 llvm::LLVMBuildRetVoid(self.llbuilder);
326 }
327
328 fn ret(&mut self, v: &'ll Value) {
329 unsafe {
330 llvm::LLVMBuildRet(self.llbuilder, v);
331 }
332 }
333
334 fn br(&mut self, dest: &'ll BasicBlock) {
335 unsafe {
336 llvm::LLVMBuildBr(self.llbuilder, dest);
337 }
338 }
339
340 fn br_with_attrs(&mut self, dest: &'ll BasicBlock, attributes: &[AttributeKind]) {
341 unsafe {
342 let val = llvm::LLVMBuildBr(self.llbuilder, dest);
343
344 let mut nodes = Vec::new();
345
346 for attribute in attributes {
347 let AttributeKind::Unroll(unroll) = attribute else {
348 continue;
349 };
350 let md_node = if let UnrollAttr::Count(count) = unroll {
353 let unroll_meta = self.create_metadata("llvm.loop.unroll.count".as_bytes());
354 let count = llvm::LLVMValueAsMetadata(self.get_const_i32(u64::from(*count)));
355 self.md_node_in_context(&[unroll_meta, count])
356 } else {
357 let metadata_str = match unroll {
358 UnrollAttr::Hint => "llvm.loop.unroll.enable",
359 UnrollAttr::Full => "llvm.loop.unroll.full",
360 UnrollAttr::Never => "llvm.loop.unroll.disable",
361 UnrollAttr::Count(_) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
362 };
363 let unroll_meta = self.create_metadata(metadata_str.as_bytes());
364 self.md_node_in_context(&[unroll_meta])
365 };
366 nodes.push(md_node);
367 }
368
369 if let [first, ..] = nodes[..] {
370 nodes.insert(0, first);
371
372 let loop_meta_mdnode = self.set_metadata_node(val, llvm::MD_loop, &nodes);
374
375 let loop_meta_val = llvm::LLVMGetMetadata(val, llvm::MD_loop).unwrap();
377
378 llvm::LLVMReplaceMDNodeOperandWith(loop_meta_val, 0, loop_meta_mdnode);
381 }
382 }
383 }
384
385 fn cond_br(
386 &mut self,
387 cond: &'ll Value,
388 then_llbb: &'ll BasicBlock,
389 else_llbb: &'ll BasicBlock,
390 ) {
391 unsafe {
392 llvm::LLVMBuildCondBr(self.llbuilder, cond, then_llbb, else_llbb);
393 }
394 }
395
396 fn switch(
397 &mut self,
398 v: &'ll Value,
399 else_llbb: &'ll BasicBlock,
400 cases: impl ExactSizeIterator<Item = (u128, &'ll BasicBlock)>,
401 ) {
402 let switch =
403 unsafe { llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, cases.len() as c_uint) };
404 for (on_val, dest) in cases {
405 let on_val = self.const_uint_big(self.val_ty(v), on_val);
406 unsafe { llvm::LLVMAddCase(switch, on_val, dest) }
407 }
408 }
409
410 fn switch_with_weights(
411 &mut self,
412 v: Self::Value,
413 else_llbb: Self::BasicBlock,
414 else_is_cold: bool,
415 cases: impl ExactSizeIterator<Item = (u128, Self::BasicBlock, bool)>,
416 ) {
417 if self.cx.sess().opts.optimize == rustc_session::config::OptLevel::No {
418 self.switch(v, else_llbb, cases.map(|(val, dest, _)| (val, dest)));
419 return;
420 }
421
422 let id = self.cx.create_metadata(b"branch_weights");
423
424 let cold_weight = llvm::LLVMValueAsMetadata(self.cx.const_u32(1));
429 let hot_weight = llvm::LLVMValueAsMetadata(self.cx.const_u32(2000));
430 let weight =
431 |is_cold: bool| -> &Metadata { if is_cold { cold_weight } else { hot_weight } };
432
433 let mut md: SmallVec<[&Metadata; 16]> = SmallVec::with_capacity(cases.len() + 2);
434 md.push(id);
435 md.push(weight(else_is_cold));
436
437 let switch =
438 unsafe { llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, cases.len() as c_uint) };
439 for (on_val, dest, is_cold) in cases {
440 let on_val = self.const_uint_big(self.val_ty(v), on_val);
441 unsafe { llvm::LLVMAddCase(switch, on_val, dest) }
442 md.push(weight(is_cold));
443 }
444
445 self.cx.set_metadata_node(switch, llvm::MD_prof, &md);
446 }
447
448 fn invoke(
449 &mut self,
450 llty: &'ll Type,
451 fn_attrs: Option<&CodegenFnAttrs>,
452 fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
453 llfn: &'ll Value,
454 args: &[&'ll Value],
455 then: &'ll BasicBlock,
456 catch: &'ll BasicBlock,
457 funclet: Option<&Funclet<'ll>>,
458 instance: Option<Instance<'tcx>>,
459 ) -> &'ll Value {
460 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/builder.rs:460",
"rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
::tracing_core::__macro_support::Option::Some(460u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("invoke {0:?} with args ({1:?})",
llfn, args) as &dyn Value))])
});
} else { ; }
};debug!("invoke {:?} with args ({:?})", llfn, args);
461
462 let args = self.check_call("invoke", llty, llfn, args);
463 let funclet_bundle = funclet.map(|funclet| funclet.bundle());
464 let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
465 if let Some(funclet_bundle) = funclet_bundle {
466 bundles.push(funclet_bundle);
467 }
468
469 self.cfi_type_test(fn_attrs, fn_abi, instance, llfn);
471
472 let kcfi_bundle = self.kcfi_operand_bundle(fn_attrs, fn_abi, instance, llfn);
474 if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|b| b.as_ref()) {
475 bundles.push(kcfi_bundle);
476 }
477
478 let pauth = self.ptrauth_operand_bundle(llfn, fn_abi);
479 if let Some(p) = pauth.as_ref().map(|b| b.as_ref()) {
480 bundles.push(p);
481 }
482
483 let invoke = unsafe {
484 llvm::LLVMBuildInvokeWithOperandBundles(
485 self.llbuilder,
486 llty,
487 llfn,
488 args.as_ptr(),
489 args.len() as c_uint,
490 then,
491 catch,
492 bundles.as_ptr(),
493 bundles.len() as c_uint,
494 UNNAMED,
495 )
496 };
497 if let Some(fn_abi) = fn_abi {
498 fn_abi.apply_attrs_callsite(self, invoke);
499 }
500 invoke
501 }
502
503 fn unreachable(&mut self) {
504 unsafe {
505 llvm::LLVMBuildUnreachable(self.llbuilder);
506 }
507 }
508
509 fn unchecked_umul(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
unsafe { llvm::LLVMBuildNUWMul(self.llbuilder, x, y, UNNAMED) }
}math_builder_methods! {
510 add(a, b) => LLVMBuildAdd,
511 fadd(a, b) => LLVMBuildFAdd,
512 sub(a, b) => LLVMBuildSub,
513 fsub(a, b) => LLVMBuildFSub,
514 mul(a, b) => LLVMBuildMul,
515 fmul(a, b) => LLVMBuildFMul,
516 udiv(a, b) => LLVMBuildUDiv,
517 exactudiv(a, b) => LLVMBuildExactUDiv,
518 sdiv(a, b) => LLVMBuildSDiv,
519 exactsdiv(a, b) => LLVMBuildExactSDiv,
520 fdiv(a, b) => LLVMBuildFDiv,
521 urem(a, b) => LLVMBuildURem,
522 srem(a, b) => LLVMBuildSRem,
523 frem(a, b) => LLVMBuildFRem,
524 shl(a, b) => LLVMBuildShl,
525 lshr(a, b) => LLVMBuildLShr,
526 ashr(a, b) => LLVMBuildAShr,
527 and(a, b) => LLVMBuildAnd,
528 or(a, b) => LLVMBuildOr,
529 xor(a, b) => LLVMBuildXor,
530 neg(x) => LLVMBuildNeg,
531 fneg(x) => LLVMBuildFNeg,
532 not(x) => LLVMBuildNot,
533 unchecked_sadd(x, y) => LLVMBuildNSWAdd,
534 unchecked_uadd(x, y) => LLVMBuildNUWAdd,
535 unchecked_ssub(x, y) => LLVMBuildNSWSub,
536 unchecked_usub(x, y) => LLVMBuildNUWSub,
537 unchecked_smul(x, y) => LLVMBuildNSWMul,
538 unchecked_umul(x, y) => LLVMBuildNUWMul,
539 }
540
541 fn unchecked_suadd(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
542 unsafe {
543 let add = llvm::LLVMBuildAdd(self.llbuilder, a, b, UNNAMED);
544 if llvm::LLVMIsAInstruction(add).is_some() {
545 llvm::LLVMSetNUW(add, TRUE);
546 llvm::LLVMSetNSW(add, TRUE);
547 }
548 add
549 }
550 }
551 fn unchecked_susub(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
552 unsafe {
553 let sub = llvm::LLVMBuildSub(self.llbuilder, a, b, UNNAMED);
554 if llvm::LLVMIsAInstruction(sub).is_some() {
555 llvm::LLVMSetNUW(sub, TRUE);
556 llvm::LLVMSetNSW(sub, TRUE);
557 }
558 sub
559 }
560 }
561 fn unchecked_sumul(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
562 unsafe {
563 let mul = llvm::LLVMBuildMul(self.llbuilder, a, b, UNNAMED);
564 if llvm::LLVMIsAInstruction(mul).is_some() {
565 llvm::LLVMSetNUW(mul, TRUE);
566 llvm::LLVMSetNSW(mul, TRUE);
567 }
568 mul
569 }
570 }
571
572 fn or_disjoint(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
573 unsafe {
574 let or = llvm::LLVMBuildOr(self.llbuilder, a, b, UNNAMED);
575
576 if llvm::LLVMIsAInstruction(or).is_some() {
580 llvm::LLVMSetIsDisjoint(or, TRUE);
581 }
582 or
583 }
584 }
585
586 fn frem_algebraic(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
unsafe {
let instr = llvm::LLVMBuildFRem(self.llbuilder, x, y, UNNAMED);
llvm::LLVMRustSetAlgebraicMath(instr);
instr
}
}set_math_builder_methods! {
587 fadd_fast(x, y) => (LLVMBuildFAdd, LLVMRustSetFastMath),
588 fsub_fast(x, y) => (LLVMBuildFSub, LLVMRustSetFastMath),
589 fmul_fast(x, y) => (LLVMBuildFMul, LLVMRustSetFastMath),
590 fdiv_fast(x, y) => (LLVMBuildFDiv, LLVMRustSetFastMath),
591 frem_fast(x, y) => (LLVMBuildFRem, LLVMRustSetFastMath),
592 fadd_algebraic(x, y) => (LLVMBuildFAdd, LLVMRustSetAlgebraicMath),
593 fsub_algebraic(x, y) => (LLVMBuildFSub, LLVMRustSetAlgebraicMath),
594 fmul_algebraic(x, y) => (LLVMBuildFMul, LLVMRustSetAlgebraicMath),
595 fdiv_algebraic(x, y) => (LLVMBuildFDiv, LLVMRustSetAlgebraicMath),
596 frem_algebraic(x, y) => (LLVMBuildFRem, LLVMRustSetAlgebraicMath),
597 }
598
599 fn checked_binop(
600 &mut self,
601 oop: OverflowOp,
602 ty: Ty<'tcx>,
603 lhs: Self::Value,
604 rhs: Self::Value,
605 ) -> (Self::Value, Self::Value) {
606 let (size, signed) = ty.int_size_and_signed(self.tcx);
607 let width = size.bits();
608
609 if !signed {
610 match oop {
611 OverflowOp::Sub => {
612 let sub = self.sub(lhs, rhs);
616 let cmp = self.icmp(IntPredicate::IntULT, lhs, rhs);
617 return (sub, cmp);
618 }
619 OverflowOp::Add => {
620 let add = self.add(lhs, rhs);
623 let cmp = self.icmp(IntPredicate::IntULT, add, lhs);
624 return (add, cmp);
625 }
626 OverflowOp::Mul => {}
627 }
628 }
629
630 let oop_str = match oop {
631 OverflowOp::Add => "add",
632 OverflowOp::Sub => "sub",
633 OverflowOp::Mul => "mul",
634 };
635
636 let name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("llvm.{0}{1}.with.overflow",
if signed { 's' } else { 'u' }, oop_str))
})format!("llvm.{}{oop_str}.with.overflow", if signed { 's' } else { 'u' });
637
638 let res = self.call_intrinsic(name, &[self.type_ix(width)], &[lhs, rhs]);
639 (self.extract_value(res, 0), self.extract_value(res, 1))
640 }
641
642 fn from_immediate(&mut self, val: Self::Value) -> Self::Value {
643 if self.cx().val_ty(val) == self.cx().type_i1() {
644 self.zext(val, self.cx().type_i8())
645 } else {
646 val
647 }
648 }
649
650 fn to_immediate_scalar(&mut self, val: Self::Value, scalar: abi::Scalar) -> Self::Value {
651 if scalar.is_bool() {
652 return self.unchecked_utrunc(val, self.cx().type_i1());
653 }
654 val
655 }
656
657 fn alloca(&mut self, size: Size, align: Align) -> &'ll Value {
658 let mut bx = Builder::with_cx(self.cx);
659 bx.position_at_start(unsafe { llvm::LLVMGetFirstBasicBlock(self.llfn()) });
660 let ty = self.cx().type_array(self.cx().type_i8(), size.bytes());
661 unsafe {
662 let alloca = llvm::LLVMBuildAlloca(bx.llbuilder, ty, UNNAMED);
663 llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
664 llvm::LLVMBuildPointerCast(bx.llbuilder, alloca, self.cx().type_ptr(), UNNAMED)
666 }
667 }
668
669 fn alloca_with_ty(&mut self, layout: TyAndLayout<'tcx>) -> Self::Value {
670 let mut bx = Builder::with_cx(self.cx);
671 bx.position_at_start(unsafe { llvm::LLVMGetFirstBasicBlock(self.llfn()) });
672 let scalable_vector_ty = layout.llvm_type(self.cx);
673
674 unsafe {
675 let alloca = llvm::LLVMBuildAlloca(&bx.llbuilder, scalable_vector_ty, UNNAMED);
676 llvm::LLVMSetAlignment(alloca, layout.align.abi.bytes() as c_uint);
677 alloca
678 }
679 }
680
681 fn load(&mut self, ty: &'ll Type, ptr: &'ll Value, align: Align) -> &'ll Value {
682 unsafe {
683 let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
684 let align = align.min(self.cx().tcx.sess.target.max_reliable_alignment());
685 llvm::LLVMSetAlignment(load, align.bytes() as c_uint);
686 load
687 }
688 }
689
690 fn volatile_load(&mut self, ty: &'ll Type, ptr: &'ll Value, align: Align) -> &'ll Value {
691 unsafe {
692 let load = self.load(ty, ptr, align);
693 llvm::LLVMSetVolatile(load, llvm::TRUE);
694 load
695 }
696 }
697
698 fn atomic_load(
699 &mut self,
700 ty: &'ll Type,
701 ptr: &'ll Value,
702 order: rustc_middle::ty::AtomicOrdering,
703 size: Size,
704 ) -> &'ll Value {
705 unsafe {
706 let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
707 llvm::LLVMSetOrdering(load, AtomicOrdering::from_generic(order));
709 llvm::LLVMSetAlignment(load, size.bytes() as c_uint);
711 load
712 }
713 }
714
715 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("load_operand",
"rustc_codegen_llvm::builder", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
::tracing_core::__macro_support::Option::Some(715u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
::tracing_core::field::FieldSet::new(&["place"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: OperandRef<'tcx, &'ll Value> =
loop {};
return __tracing_attr_fake_return;
}
{
if place.layout.is_unsized() {
let tail =
self.tcx.struct_tail_for_codegen(place.layout.ty,
self.typing_env());
if #[allow(non_exhaustive_omitted_patterns)] match tail.kind()
{
ty::Foreign(..) => true,
_ => false,
} {
{
::core::panicking::panic_fmt(format_args!("unsized locals must not be `extern` types"));
};
}
}
{
match (&place.val.llextra.is_some(),
&place.layout.is_unsized()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
if place.layout.is_zst() {
return OperandRef::zero_sized(place.layout);
}
fn scalar_load_metadata<'a, 'll,
'tcx>(bx: &mut Builder<'a, 'll, 'tcx>, load: &'ll Value,
scalar: abi::Scalar, layout: TyAndLayout<'tcx>,
offset: Size) {
{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("scalar_load_metadata",
"rustc_codegen_llvm::builder", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
::tracing_core::__macro_support::Option::Some(732u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
::tracing_core::field::FieldSet::new(&["load", "scalar",
"layout", "offset"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&load)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&scalar)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&layout)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&offset)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy
:: needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
if bx.cx.sess().opts.optimize == OptLevel::No { return; }
if !scalar.is_uninit_valid() { bx.noundef_metadata(load); }
match scalar.primitive() {
abi::Primitive::Int(..) => {
if !scalar.is_always_valid(bx) {
bx.range_metadata(load, scalar.valid_range(bx));
}
}
abi::Primitive::Pointer(_) => {
if !scalar.valid_range(bx).contains(0) {
bx.nonnull_metadata(load);
}
if let Some(pointee) = layout.pointee_info_at(bx, offset) &&
pointee.align > Align::ONE {
bx.align_metadata(load, pointee.align);
}
}
abi::Primitive::Float(_) => {}
}
}
}
}
}
let val =
if let Some(_) = place.val.llextra {
OperandValue::Ref(place.val)
} else if place.layout.is_llvm_immediate() {
let mut const_llval = None;
let llty = place.layout.llvm_type(self);
if let Some(global) =
llvm::LLVMIsAGlobalVariable(place.val.llval) {
if llvm::LLVMIsGlobalConstant(global).is_true() {
if let Some(init) = llvm::LLVMGetInitializer(global) {
if self.val_ty(init) == llty { const_llval = Some(init); }
}
}
}
let llval =
const_llval.unwrap_or_else(||
{
let load =
self.load(llty, place.val.llval, place.val.align);
if let abi::BackendRepr::Scalar(scalar) =
place.layout.backend_repr {
scalar_load_metadata(self, load, scalar, place.layout,
Size::ZERO);
self.to_immediate_scalar(load, scalar)
} else { load }
});
OperandValue::Immediate(llval)
} else if let abi::BackendRepr::ScalarPair(a, b) =
place.layout.backend_repr {
let b_offset =
a.size(self).align_to(b.default_align(self).abi);
let mut load =
|i, scalar: abi::Scalar, layout, align, offset|
{
let llptr =
if i == 0 {
place.val.llval
} else {
self.inbounds_ptradd(place.val.llval,
self.const_usize(b_offset.bytes()))
};
let llty =
place.layout.scalar_pair_element_llvm_type(self, i, false);
let load = self.load(llty, llptr, align);
scalar_load_metadata(self, load, scalar, layout, offset);
self.to_immediate_scalar(load, scalar)
};
OperandValue::Pair(load(0, a, place.layout, place.val.align,
Size::ZERO),
load(1, b, place.layout,
place.val.align.restrict_for_offset(b_offset), b_offset))
} else { OperandValue::Ref(place.val) };
OperandRef { val, layout: place.layout, move_annotation: None }
}
}
}#[instrument(level = "trace", skip(self))]
716 fn load_operand(&mut self, place: PlaceRef<'tcx, &'ll Value>) -> OperandRef<'tcx, &'ll Value> {
717 if place.layout.is_unsized() {
718 let tail = self.tcx.struct_tail_for_codegen(place.layout.ty, self.typing_env());
719 if matches!(tail.kind(), ty::Foreign(..)) {
720 panic!("unsized locals must not be `extern` types");
724 }
725 }
726 assert_eq!(place.val.llextra.is_some(), place.layout.is_unsized());
727
728 if place.layout.is_zst() {
729 return OperandRef::zero_sized(place.layout);
730 }
731
732 #[instrument(level = "trace", skip(bx))]
733 fn scalar_load_metadata<'a, 'll, 'tcx>(
734 bx: &mut Builder<'a, 'll, 'tcx>,
735 load: &'ll Value,
736 scalar: abi::Scalar,
737 layout: TyAndLayout<'tcx>,
738 offset: Size,
739 ) {
740 if bx.cx.sess().opts.optimize == OptLevel::No {
741 return;
743 }
744
745 if !scalar.is_uninit_valid() {
746 bx.noundef_metadata(load);
747 }
748
749 match scalar.primitive() {
750 abi::Primitive::Int(..) => {
751 if !scalar.is_always_valid(bx) {
752 bx.range_metadata(load, scalar.valid_range(bx));
753 }
754 }
755 abi::Primitive::Pointer(_) => {
756 if !scalar.valid_range(bx).contains(0) {
757 bx.nonnull_metadata(load);
758 }
759
760 if let Some(pointee) = layout.pointee_info_at(bx, offset)
761 && pointee.align > Align::ONE
762 {
763 bx.align_metadata(load, pointee.align);
764 }
765 }
766 abi::Primitive::Float(_) => {}
767 }
768 }
769
770 let val = if let Some(_) = place.val.llextra {
771 OperandValue::Ref(place.val)
773 } else if place.layout.is_llvm_immediate() {
774 let mut const_llval = None;
775 let llty = place.layout.llvm_type(self);
776 if let Some(global) = llvm::LLVMIsAGlobalVariable(place.val.llval) {
777 if llvm::LLVMIsGlobalConstant(global).is_true() {
778 if let Some(init) = llvm::LLVMGetInitializer(global) {
779 if self.val_ty(init) == llty {
780 const_llval = Some(init);
781 }
782 }
783 }
784 }
785
786 let llval = const_llval.unwrap_or_else(|| {
787 let load = self.load(llty, place.val.llval, place.val.align);
788 if let abi::BackendRepr::Scalar(scalar) = place.layout.backend_repr {
789 scalar_load_metadata(self, load, scalar, place.layout, Size::ZERO);
790 self.to_immediate_scalar(load, scalar)
791 } else {
792 load
793 }
794 });
795 OperandValue::Immediate(llval)
796 } else if let abi::BackendRepr::ScalarPair(a, b) = place.layout.backend_repr {
797 let b_offset = a.size(self).align_to(b.default_align(self).abi);
798
799 let mut load = |i, scalar: abi::Scalar, layout, align, offset| {
800 let llptr = if i == 0 {
801 place.val.llval
802 } else {
803 self.inbounds_ptradd(place.val.llval, self.const_usize(b_offset.bytes()))
804 };
805 let llty = place.layout.scalar_pair_element_llvm_type(self, i, false);
806 let load = self.load(llty, llptr, align);
807 scalar_load_metadata(self, load, scalar, layout, offset);
808 self.to_immediate_scalar(load, scalar)
809 };
810
811 OperandValue::Pair(
812 load(0, a, place.layout, place.val.align, Size::ZERO),
813 load(1, b, place.layout, place.val.align.restrict_for_offset(b_offset), b_offset),
814 )
815 } else {
816 OperandValue::Ref(place.val)
817 };
818
819 OperandRef { val, layout: place.layout, move_annotation: None }
820 }
821
822 fn write_operand_repeatedly(
823 &mut self,
824 cg_elem: OperandRef<'tcx, &'ll Value>,
825 count: u64,
826 dest: PlaceRef<'tcx, &'ll Value>,
827 ) {
828 if self.cx.sess().opts.optimize == OptLevel::No {
829 self.write_operand_repeatedly_unoptimized(cg_elem, count, dest);
837 } else {
838 self.write_operand_repeatedly_optimized(cg_elem, count, dest);
839 }
840 }
841
842 fn range_metadata(&mut self, load: &'ll Value, range: WrappingRange) {
843 if self.cx.sess().opts.optimize == OptLevel::No {
844 return;
846 }
847
848 let llty = self.cx.val_ty(load);
849 let md = [
850 llvm::LLVMValueAsMetadata(self.cx.const_uint_big(llty, range.start)),
851 llvm::LLVMValueAsMetadata(self.cx.const_uint_big(llty, range.end.wrapping_add(1))),
852 ];
853 self.set_metadata_node(load, llvm::MD_range, &md);
854 }
855
856 fn nonnull_metadata(&mut self, load: &'ll Value) {
857 self.set_metadata_node(load, llvm::MD_nonnull, &[]);
858 }
859
860 fn store(&mut self, val: &'ll Value, ptr: &'ll Value, align: Align) -> &'ll Value {
861 self.store_with_flags(val, ptr, align, MemFlags::empty())
862 }
863
864 fn store_with_flags(
865 &mut self,
866 val: &'ll Value,
867 ptr: &'ll Value,
868 align: Align,
869 flags: MemFlags,
870 ) -> &'ll Value {
871 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/builder.rs:871",
"rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
::tracing_core::__macro_support::Option::Some(871u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("Store {0:?} -> {1:?} ({2:?})",
val, ptr, flags) as &dyn Value))])
});
} else { ; }
};debug!("Store {:?} -> {:?} ({:?})", val, ptr, flags);
872 {
match (&self.cx.type_kind(self.cx.val_ty(ptr)), &TypeKind::Pointer) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(self.cx.type_kind(self.cx.val_ty(ptr)), TypeKind::Pointer);
873 unsafe {
874 let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
875 let align = align.min(self.cx().tcx.sess.target.max_reliable_alignment());
876 let align =
877 if flags.contains(MemFlags::UNALIGNED) { 1 } else { align.bytes() as c_uint };
878 llvm::LLVMSetAlignment(store, align);
879 if flags.contains(MemFlags::VOLATILE) {
880 llvm::LLVMSetVolatile(store, llvm::TRUE);
881 }
882 if flags.contains(MemFlags::NONTEMPORAL) {
883 let use_nontemporal = #[allow(non_exhaustive_omitted_patterns)] match self.cx.tcx.sess.target.arch {
Arch::AArch64 | Arch::Arm | Arch::RiscV32 | Arch::RiscV64 => true,
_ => false,
}matches!(
896 self.cx.tcx.sess.target.arch,
897 Arch::AArch64 | Arch::Arm | Arch::RiscV32 | Arch::RiscV64
898 );
899 if use_nontemporal {
900 let one = llvm::LLVMValueAsMetadata(self.cx.const_i32(1));
905 self.set_metadata_node(store, llvm::MD_nontemporal, &[one]);
906 }
907 }
908 if flags.contains(MemFlags::CAPTURES_READ_ONLY)
909 && crate::llvm_util::get_version() >= (22, 0, 0)
910 {
911 if !(self.type_kind(self.val_ty(val)) == TypeKind::Pointer) {
{
::core::panicking::panic_fmt(format_args!("CAPTURED_READ_ONLY is only supported on pointer stores"));
}
};assert!(
912 self.type_kind(self.val_ty(val)) == TypeKind::Pointer,
913 "CAPTURED_READ_ONLY is only supported on pointer stores"
914 );
915 let args = [
916 self.cx.create_metadata(b"address"),
917 self.cx.create_metadata(b"read_provenance"),
918 ];
919 let id = self.get_md_kind_id("captures");
921 let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, args.as_ptr(), args.len());
922 self.set_metadata(store, id, md);
923 }
924 store
925 }
926 }
927
928 fn atomic_store(
929 &mut self,
930 val: &'ll Value,
931 ptr: &'ll Value,
932 order: rustc_middle::ty::AtomicOrdering,
933 size: Size,
934 ) {
935 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/builder.rs:935",
"rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
::tracing_core::__macro_support::Option::Some(935u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("Store {0:?} -> {1:?}",
val, ptr) as &dyn Value))])
});
} else { ; }
};debug!("Store {:?} -> {:?}", val, ptr);
936 {
match (&self.cx.type_kind(self.cx.val_ty(ptr)), &TypeKind::Pointer) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(self.cx.type_kind(self.cx.val_ty(ptr)), TypeKind::Pointer);
937 unsafe {
938 let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
939 llvm::LLVMSetOrdering(store, AtomicOrdering::from_generic(order));
941 llvm::LLVMSetAlignment(store, size.bytes() as c_uint);
943 }
944 }
945
946 fn gep(&mut self, ty: &'ll Type, ptr: &'ll Value, indices: &[&'ll Value]) -> &'ll Value {
947 unsafe {
948 llvm::LLVMBuildGEPWithNoWrapFlags(
949 self.llbuilder,
950 ty,
951 ptr,
952 indices.as_ptr(),
953 indices.len() as c_uint,
954 UNNAMED,
955 GEPNoWrapFlags::default(),
956 )
957 }
958 }
959
960 fn inbounds_gep(
961 &mut self,
962 ty: &'ll Type,
963 ptr: &'ll Value,
964 indices: &[&'ll Value],
965 ) -> &'ll Value {
966 unsafe {
967 llvm::LLVMBuildGEPWithNoWrapFlags(
968 self.llbuilder,
969 ty,
970 ptr,
971 indices.as_ptr(),
972 indices.len() as c_uint,
973 UNNAMED,
974 GEPNoWrapFlags::InBounds,
975 )
976 }
977 }
978
979 fn inbounds_nuw_gep(
980 &mut self,
981 ty: &'ll Type,
982 ptr: &'ll Value,
983 indices: &[&'ll Value],
984 ) -> &'ll Value {
985 unsafe {
986 llvm::LLVMBuildGEPWithNoWrapFlags(
987 self.llbuilder,
988 ty,
989 ptr,
990 indices.as_ptr(),
991 indices.len() as c_uint,
992 UNNAMED,
993 GEPNoWrapFlags::InBounds | GEPNoWrapFlags::NUW,
994 )
995 }
996 }
997
998 fn trunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1000 unsafe { llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
1001 }
1002
1003 fn unchecked_utrunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1004 if true {
{
match (&self.val_ty(val), &dest_ty) {
(left_val, right_val) => {
if *left_val == *right_val {
let kind = ::core::panicking::AssertKind::Ne;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_ne!(self.val_ty(val), dest_ty);
1005
1006 let trunc = self.trunc(val, dest_ty);
1007 unsafe {
1008 if llvm::LLVMIsAInstruction(trunc).is_some() {
1009 llvm::LLVMSetNUW(trunc, TRUE);
1010 }
1011 }
1012 trunc
1013 }
1014
1015 fn unchecked_strunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1016 if true {
{
match (&self.val_ty(val), &dest_ty) {
(left_val, right_val) => {
if *left_val == *right_val {
let kind = ::core::panicking::AssertKind::Ne;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_ne!(self.val_ty(val), dest_ty);
1017
1018 let trunc = self.trunc(val, dest_ty);
1019 unsafe {
1020 if llvm::LLVMIsAInstruction(trunc).is_some() {
1021 llvm::LLVMSetNSW(trunc, TRUE);
1022 }
1023 }
1024 trunc
1025 }
1026
1027 fn sext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1028 unsafe { llvm::LLVMBuildSExt(self.llbuilder, val, dest_ty, UNNAMED) }
1029 }
1030
1031 fn fptoui_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1032 self.call_intrinsic("llvm.fptoui.sat", &[dest_ty, self.val_ty(val)], &[val])
1033 }
1034
1035 fn fptosi_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1036 self.call_intrinsic("llvm.fptosi.sat", &[dest_ty, self.val_ty(val)], &[val])
1037 }
1038
1039 fn fptoui(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1040 if self.sess().target.is_like_wasm {
1055 let src_ty = self.cx.val_ty(val);
1056 if self.cx.type_kind(src_ty) != TypeKind::Vector {
1057 let float_width = self.cx.float_width(src_ty);
1058 let int_width = self.cx.int_width(dest_ty);
1059 if #[allow(non_exhaustive_omitted_patterns)] match (int_width, float_width) {
(32 | 64, 32 | 64) => true,
_ => false,
}matches!((int_width, float_width), (32 | 64, 32 | 64)) {
1060 return self.call_intrinsic(
1061 "llvm.wasm.trunc.unsigned",
1062 &[dest_ty, src_ty],
1063 &[val],
1064 );
1065 }
1066 }
1067 }
1068 unsafe { llvm::LLVMBuildFPToUI(self.llbuilder, val, dest_ty, UNNAMED) }
1069 }
1070
1071 fn fptosi(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1072 if self.sess().target.is_like_wasm {
1074 let src_ty = self.cx.val_ty(val);
1075 if self.cx.type_kind(src_ty) != TypeKind::Vector {
1076 let float_width = self.cx.float_width(src_ty);
1077 let int_width = self.cx.int_width(dest_ty);
1078 if #[allow(non_exhaustive_omitted_patterns)] match (int_width, float_width) {
(32 | 64, 32 | 64) => true,
_ => false,
}matches!((int_width, float_width), (32 | 64, 32 | 64)) {
1079 return self.call_intrinsic(
1080 "llvm.wasm.trunc.signed",
1081 &[dest_ty, src_ty],
1082 &[val],
1083 );
1084 }
1085 }
1086 }
1087 unsafe { llvm::LLVMBuildFPToSI(self.llbuilder, val, dest_ty, UNNAMED) }
1088 }
1089
1090 fn uitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1091 unsafe { llvm::LLVMBuildUIToFP(self.llbuilder, val, dest_ty, UNNAMED) }
1092 }
1093
1094 fn sitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1095 unsafe { llvm::LLVMBuildSIToFP(self.llbuilder, val, dest_ty, UNNAMED) }
1096 }
1097
1098 fn fptrunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1099 unsafe { llvm::LLVMBuildFPTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
1100 }
1101
1102 fn fpext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1103 unsafe { llvm::LLVMBuildFPExt(self.llbuilder, val, dest_ty, UNNAMED) }
1104 }
1105
1106 fn ptrtoint(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1107 unsafe { llvm::LLVMBuildPtrToInt(self.llbuilder, val, dest_ty, UNNAMED) }
1108 }
1109
1110 fn inttoptr(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1111 unsafe { llvm::LLVMBuildIntToPtr(self.llbuilder, val, dest_ty, UNNAMED) }
1112 }
1113
1114 fn bitcast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1115 unsafe { llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty, UNNAMED) }
1116 }
1117
1118 fn intcast(&mut self, val: &'ll Value, dest_ty: &'ll Type, is_signed: bool) -> &'ll Value {
1119 unsafe {
1120 llvm::LLVMBuildIntCast2(self.llbuilder, val, dest_ty, is_signed.to_llvm_bool(), UNNAMED)
1121 }
1122 }
1123
1124 fn pointercast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1125 unsafe { llvm::LLVMBuildPointerCast(self.llbuilder, val, dest_ty, UNNAMED) }
1126 }
1127
1128 fn icmp(&mut self, op: IntPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1130 let op = llvm::IntPredicate::from_generic(op);
1131 unsafe { llvm::LLVMBuildICmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
1132 }
1133
1134 fn fcmp(&mut self, op: RealPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1135 let op = llvm::RealPredicate::from_generic(op);
1136 unsafe { llvm::LLVMBuildFCmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
1137 }
1138
1139 fn three_way_compare(
1140 &mut self,
1141 ty: Ty<'tcx>,
1142 lhs: Self::Value,
1143 rhs: Self::Value,
1144 ) -> Self::Value {
1145 let size = ty.primitive_size(self.tcx);
1146 let name = if ty.is_signed() { "llvm.scmp" } else { "llvm.ucmp" };
1147
1148 self.call_intrinsic(name, &[self.type_i8(), self.type_ix(size.bits())], &[lhs, rhs])
1149 }
1150
1151 fn memcpy(
1153 &mut self,
1154 dst: &'ll Value,
1155 dst_align: Align,
1156 src: &'ll Value,
1157 src_align: Align,
1158 size: &'ll Value,
1159 flags: MemFlags,
1160 tt: Option<FncTree>,
1161 ) {
1162 if !!flags.contains(MemFlags::NONTEMPORAL) {
{
::core::panicking::panic_fmt(format_args!("non-temporal memcpy not supported"));
}
};assert!(!flags.contains(MemFlags::NONTEMPORAL), "non-temporal memcpy not supported");
1163 let size = self.intcast(size, self.type_isize(), false);
1164 let is_volatile = flags.contains(MemFlags::VOLATILE);
1165 let memcpy = unsafe {
1166 llvm::LLVMRustBuildMemCpy(
1167 self.llbuilder,
1168 dst,
1169 dst_align.bytes() as c_uint,
1170 src,
1171 src_align.bytes() as c_uint,
1172 size,
1173 is_volatile,
1174 )
1175 };
1176
1177 if let Some(tt) = tt {
1183 crate::typetree::add_tt(self.cx().llmod, self.cx().llcx, memcpy, tt);
1184 }
1185 }
1186
1187 fn memmove(
1188 &mut self,
1189 dst: &'ll Value,
1190 dst_align: Align,
1191 src: &'ll Value,
1192 src_align: Align,
1193 size: &'ll Value,
1194 flags: MemFlags,
1195 ) {
1196 if !!flags.contains(MemFlags::NONTEMPORAL) {
{
::core::panicking::panic_fmt(format_args!("non-temporal memmove not supported"));
}
};assert!(!flags.contains(MemFlags::NONTEMPORAL), "non-temporal memmove not supported");
1197 let size = self.intcast(size, self.type_isize(), false);
1198 let is_volatile = flags.contains(MemFlags::VOLATILE);
1199 unsafe {
1200 llvm::LLVMRustBuildMemMove(
1201 self.llbuilder,
1202 dst,
1203 dst_align.bytes() as c_uint,
1204 src,
1205 src_align.bytes() as c_uint,
1206 size,
1207 is_volatile,
1208 );
1209 }
1210 }
1211
1212 fn memset(
1213 &mut self,
1214 ptr: &'ll Value,
1215 fill_byte: &'ll Value,
1216 size: &'ll Value,
1217 align: Align,
1218 flags: MemFlags,
1219 ) {
1220 if !!flags.contains(MemFlags::NONTEMPORAL) {
{
::core::panicking::panic_fmt(format_args!("non-temporal memset not supported"));
}
};assert!(!flags.contains(MemFlags::NONTEMPORAL), "non-temporal memset not supported");
1221 let is_volatile = flags.contains(MemFlags::VOLATILE);
1222 unsafe {
1223 llvm::LLVMRustBuildMemSet(
1224 self.llbuilder,
1225 ptr,
1226 align.bytes() as c_uint,
1227 fill_byte,
1228 size,
1229 is_volatile,
1230 );
1231 }
1232 }
1233
1234 fn vscale(&mut self, ty: &'ll Type) -> &'ll Value {
1235 unsafe { llvm::LLVMRustBuildVScale(self.llbuilder, ty) }
1236 }
1237
1238 fn select(
1239 &mut self,
1240 cond: &'ll Value,
1241 then_val: &'ll Value,
1242 else_val: &'ll Value,
1243 ) -> &'ll Value {
1244 unsafe { llvm::LLVMBuildSelect(self.llbuilder, cond, then_val, else_val, UNNAMED) }
1245 }
1246
1247 fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
1248 unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) }
1249 }
1250
1251 fn extract_element(&mut self, vec: &'ll Value, idx: &'ll Value) -> &'ll Value {
1252 unsafe { llvm::LLVMBuildExtractElement(self.llbuilder, vec, idx, UNNAMED) }
1253 }
1254
1255 fn vector_splat(&mut self, num_elts: usize, elt: &'ll Value) -> &'ll Value {
1256 unsafe {
1257 let elt_ty = self.cx.val_ty(elt);
1258 let undef = llvm::LLVMGetUndef(self.type_vector(elt_ty, num_elts as u64));
1259 let vec = self.insert_element(undef, elt, self.cx.const_i32(0));
1260 let vec_i32_ty = self.type_vector(self.type_i32(), num_elts as u64);
1261 self.shuffle_vector(vec, undef, self.const_null(vec_i32_ty))
1262 }
1263 }
1264
1265 fn extract_value(&mut self, agg_val: &'ll Value, idx: u64) -> &'ll Value {
1266 {
match (&(idx as c_uint as u64), &idx) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(idx as c_uint as u64, idx);
1267 unsafe { llvm::LLVMBuildExtractValue(self.llbuilder, agg_val, idx as c_uint, UNNAMED) }
1268 }
1269
1270 fn insert_value(&mut self, agg_val: &'ll Value, elt: &'ll Value, idx: u64) -> &'ll Value {
1271 {
match (&(idx as c_uint as u64), &idx) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(idx as c_uint as u64, idx);
1272 unsafe { llvm::LLVMBuildInsertValue(self.llbuilder, agg_val, elt, idx as c_uint, UNNAMED) }
1273 }
1274
1275 fn set_personality_fn(&mut self, personality: &'ll Value) {
1276 unsafe {
1277 llvm::LLVMSetPersonalityFn(self.llfn(), personality);
1278 }
1279 }
1280
1281 fn cleanup_landing_pad(&mut self, pers_fn: &'ll Value) -> (&'ll Value, &'ll Value) {
1282 let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1283 let landing_pad = self.landing_pad(ty, pers_fn, 0);
1284 unsafe {
1285 llvm::LLVMSetCleanup(landing_pad, llvm::TRUE);
1286 }
1287 (self.extract_value(landing_pad, 0), self.extract_value(landing_pad, 1))
1288 }
1289
1290 fn filter_landing_pad(&mut self, pers_fn: &'ll Value) {
1291 let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1292 let landing_pad = self.landing_pad(ty, pers_fn, 1);
1293 self.add_clause(landing_pad, self.const_array(self.type_ptr(), &[]));
1294 }
1295
1296 fn resume(&mut self, exn0: &'ll Value, exn1: &'ll Value) {
1297 let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1298 let mut exn = self.const_poison(ty);
1299 exn = self.insert_value(exn, exn0, 0);
1300 exn = self.insert_value(exn, exn1, 1);
1301 unsafe {
1302 llvm::LLVMBuildResume(self.llbuilder, exn);
1303 }
1304 }
1305
1306 fn cleanup_pad(&mut self, parent: Option<&'ll Value>, args: &[&'ll Value]) -> Funclet<'ll> {
1307 let ret = unsafe {
1308 llvm::LLVMBuildCleanupPad(
1309 self.llbuilder,
1310 parent,
1311 args.as_ptr(),
1312 args.len() as c_uint,
1313 c"cleanuppad".as_ptr(),
1314 )
1315 };
1316 Funclet::new(ret.expect("LLVM does not have support for cleanuppad"))
1317 }
1318
1319 fn cleanup_ret(&mut self, funclet: &Funclet<'ll>, unwind: Option<&'ll BasicBlock>) {
1320 unsafe {
1321 llvm::LLVMBuildCleanupRet(self.llbuilder, funclet.cleanuppad(), unwind)
1322 .expect("LLVM does not have support for cleanupret");
1323 }
1324 }
1325
1326 fn catch_pad(&mut self, parent: &'ll Value, args: &[&'ll Value]) -> Funclet<'ll> {
1327 let ret = unsafe {
1328 llvm::LLVMBuildCatchPad(
1329 self.llbuilder,
1330 parent,
1331 args.as_ptr(),
1332 args.len() as c_uint,
1333 c"catchpad".as_ptr(),
1334 )
1335 };
1336 Funclet::new(ret.expect("LLVM does not have support for catchpad"))
1337 }
1338
1339 fn catch_switch(
1340 &mut self,
1341 parent: Option<&'ll Value>,
1342 unwind: Option<&'ll BasicBlock>,
1343 handlers: &[&'ll BasicBlock],
1344 ) -> &'ll Value {
1345 let ret = unsafe {
1346 llvm::LLVMBuildCatchSwitch(
1347 self.llbuilder,
1348 parent,
1349 unwind,
1350 handlers.len() as c_uint,
1351 c"catchswitch".as_ptr(),
1352 )
1353 };
1354 let ret = ret.expect("LLVM does not have support for catchswitch");
1355 for handler in handlers {
1356 unsafe {
1357 llvm::LLVMAddHandler(ret, handler);
1358 }
1359 }
1360 ret
1361 }
1362
1363 fn get_funclet_cleanuppad(&self, funclet: &Funclet<'ll>) -> &'ll Value {
1364 funclet.cleanuppad()
1365 }
1366
1367 fn atomic_cmpxchg(
1369 &mut self,
1370 dst: &'ll Value,
1371 cmp: &'ll Value,
1372 src: &'ll Value,
1373 order: rustc_middle::ty::AtomicOrdering,
1374 failure_order: rustc_middle::ty::AtomicOrdering,
1375 weak: bool,
1376 ) -> (&'ll Value, &'ll Value) {
1377 unsafe {
1378 let value = llvm::LLVMBuildAtomicCmpXchg(
1379 self.llbuilder,
1380 dst,
1381 cmp,
1382 src,
1383 AtomicOrdering::from_generic(order),
1384 AtomicOrdering::from_generic(failure_order),
1385 llvm::FALSE, );
1387 llvm::LLVMSetWeak(value, weak.to_llvm_bool());
1388 let val = self.extract_value(value, 0);
1389 let success = self.extract_value(value, 1);
1390 (val, success)
1391 }
1392 }
1393
1394 fn atomic_rmw(
1395 &mut self,
1396 op: rustc_codegen_ssa::common::AtomicRmwBinOp,
1397 dst: &'ll Value,
1398 src: &'ll Value,
1399 order: rustc_middle::ty::AtomicOrdering,
1400 ret_ptr: bool,
1401 ) -> &'ll Value {
1402 let mut res = unsafe {
1406 llvm::LLVMBuildAtomicRMW(
1407 self.llbuilder,
1408 AtomicRmwBinOp::from_generic(op),
1409 dst,
1410 src,
1411 AtomicOrdering::from_generic(order),
1412 llvm::FALSE, )
1414 };
1415 if ret_ptr && self.val_ty(res) != self.type_ptr() {
1416 res = self.inttoptr(res, self.type_ptr());
1417 }
1418 res
1419 }
1420
1421 fn atomic_fence(
1422 &mut self,
1423 order: rustc_middle::ty::AtomicOrdering,
1424 scope: SynchronizationScope,
1425 ) {
1426 let single_threaded = match scope {
1427 SynchronizationScope::SingleThread => true,
1428 SynchronizationScope::CrossThread => false,
1429 };
1430 unsafe {
1431 llvm::LLVMBuildFence(
1432 self.llbuilder,
1433 AtomicOrdering::from_generic(order),
1434 single_threaded.to_llvm_bool(),
1435 UNNAMED,
1436 );
1437 }
1438 }
1439
1440 fn set_invariant_load(&mut self, load: &'ll Value) {
1441 self.set_metadata_node(load, llvm::MD_invariant_load, &[]);
1442 }
1443
1444 fn lifetime_start(&mut self, ptr: &'ll Value, size: Size) {
1445 self.call_lifetime_intrinsic("llvm.lifetime.start", ptr, size);
1446 }
1447
1448 fn lifetime_end(&mut self, ptr: &'ll Value, size: Size) {
1449 self.call_lifetime_intrinsic("llvm.lifetime.end", ptr, size);
1450 }
1451
1452 fn call(
1453 &mut self,
1454 llty: &'ll Type,
1455 caller_attrs: Option<&CodegenFnAttrs>,
1456 fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1457 llfn: &'ll Value,
1458 args: &[&'ll Value],
1459 funclet: Option<&Funclet<'ll>>,
1460 callee_instance: Option<Instance<'tcx>>,
1461 ) -> &'ll Value {
1462 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/builder.rs:1462",
"rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
::tracing_core::__macro_support::Option::Some(1462u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("call {0:?} with args ({1:?})",
llfn, args) as &dyn Value))])
});
} else { ; }
};debug!("call {:?} with args ({:?})", llfn, args);
1463
1464 let args = self.check_call("call", llty, llfn, args);
1465 let funclet_bundle = funclet.map(|funclet| funclet.bundle());
1466 let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
1467 if let Some(funclet_bundle) = funclet_bundle {
1468 bundles.push(funclet_bundle);
1469 }
1470
1471 self.cfi_type_test(caller_attrs, fn_abi, callee_instance, llfn);
1473
1474 let kcfi_bundle = self.kcfi_operand_bundle(caller_attrs, fn_abi, callee_instance, llfn);
1476 if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|b| b.as_ref()) {
1477 bundles.push(kcfi_bundle);
1478 }
1479
1480 let pauth = self.ptrauth_operand_bundle(llfn, fn_abi);
1481 if let Some(p) = pauth.as_ref().map(|b| b.as_ref()) {
1482 bundles.push(p);
1483 }
1484
1485 let call = unsafe {
1486 llvm::LLVMBuildCallWithOperandBundles(
1487 self.llbuilder,
1488 llty,
1489 llfn,
1490 args.as_ptr() as *const &llvm::Value,
1491 args.len() as c_uint,
1492 bundles.as_ptr(),
1493 bundles.len() as c_uint,
1494 c"".as_ptr(),
1495 )
1496 };
1497
1498 if let Some(callee_instance) = callee_instance {
1499 let callee_attrs = self.cx.tcx.codegen_fn_attrs(callee_instance.def_id());
1501
1502 if let Some(inlining_rule) =
1503 attributes::inline_attr(&self.cx, self.cx.tcx, callee_instance, callee_attrs)
1504 {
1505 attributes::apply_to_callsite(
1506 call,
1507 llvm::AttributePlace::Function,
1508 &[inlining_rule],
1509 );
1510 }
1511 }
1512
1513 if let Some(fn_abi) = fn_abi {
1514 fn_abi.apply_attrs_callsite(self, call);
1515 }
1516 call
1517 }
1518
1519 fn tail_call(
1520 &mut self,
1521 llty: Self::Type,
1522 caller_attrs: Option<&CodegenFnAttrs>,
1523 fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
1524 llfn: Self::Value,
1525 args: &[Self::Value],
1526 funclet: Option<&Self::Funclet>,
1527 callee_instance: Option<Instance<'tcx>>,
1528 ) {
1529 let call =
1530 self.call(llty, caller_attrs, Some(fn_abi), llfn, args, funclet, callee_instance);
1531 llvm::LLVMSetTailCallKind(call, llvm::TailCallKind::MustTail);
1532
1533 match &fn_abi.ret.mode {
1534 PassMode::Ignore | PassMode::Indirect { .. } => self.ret_void(),
1535 PassMode::Direct(_) | PassMode::Pair { .. } | PassMode::Cast { .. } => self.ret(call),
1536 }
1537 }
1538
1539 fn zext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1540 unsafe { llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty, UNNAMED) }
1541 }
1542
1543 fn apply_attrs_to_cleanup_callsite(&mut self, llret: &'ll Value) {
1544 let cold_inline = llvm::AttributeKind::Cold.create_attr(self.llcx);
1546 attributes::apply_to_callsite(llret, llvm::AttributePlace::Function, &[cold_inline]);
1547 }
1548}
1549
1550impl<'ll> StaticBuilderMethods for Builder<'_, 'll, '_> {
1551 fn get_static(&mut self, def_id: DefId) -> &'ll Value {
1552 let global = self.cx().get_static(def_id);
1554 if self.cx().tcx.is_thread_local_static(def_id) {
1555 let pointer =
1556 self.call_intrinsic("llvm.threadlocal.address", &[self.val_ty(global)], &[global]);
1557 self.pointercast(pointer, self.type_ptr())
1559 } else {
1560 self.cx().const_pointercast(global, self.type_ptr())
1562 }
1563 }
1564}
1565
1566impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1567 pub(crate) fn llfn(&self) -> &'ll Value {
1568 unsafe { llvm::LLVMGetBasicBlockParent(self.llbb()) }
1569 }
1570}
1571
1572impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1573 fn position_at_start(&mut self, llbb: &'ll BasicBlock) {
1574 unsafe {
1575 llvm::LLVMRustPositionBuilderAtStart(self.llbuilder, llbb);
1576 }
1577 }
1578}
1579impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1580 fn align_metadata(&mut self, load: &'ll Value, align: Align) {
1581 let md = [llvm::LLVMValueAsMetadata(self.cx.const_u64(align.bytes()))];
1582 self.set_metadata_node(load, llvm::MD_align, &md);
1583 }
1584
1585 fn noundef_metadata(&mut self, load: &'ll Value) {
1586 self.set_metadata_node(load, llvm::MD_noundef, &[]);
1587 }
1588
1589 pub(crate) fn set_unpredictable(&mut self, inst: &'ll Value) {
1590 self.set_metadata_node(inst, llvm::MD_unpredictable, &[]);
1591 }
1592
1593 fn write_operand_repeatedly_optimized(
1594 &mut self,
1595 cg_elem: OperandRef<'tcx, &'ll Value>,
1596 count: u64,
1597 dest: PlaceRef<'tcx, &'ll Value>,
1598 ) {
1599 let zero = self.const_usize(0);
1600 let count = self.const_usize(count);
1601
1602 let header_bb = self.append_sibling_block("repeat_loop_header");
1603 let body_bb = self.append_sibling_block("repeat_loop_body");
1604 let next_bb = self.append_sibling_block("repeat_loop_next");
1605
1606 self.br(header_bb);
1607
1608 let mut header_bx = Self::build(self.cx, header_bb);
1609 let i = header_bx.phi(self.val_ty(zero), &[zero], &[self.llbb()]);
1610
1611 let keep_going = header_bx.icmp(IntPredicate::IntULT, i, count);
1612 header_bx.cond_br(keep_going, body_bb, next_bb);
1613
1614 let mut body_bx = Self::build(self.cx, body_bb);
1615 let dest_elem = dest.project_index(&mut body_bx, i);
1616 cg_elem.val.store(&mut body_bx, dest_elem);
1617
1618 let next = body_bx.unchecked_uadd(i, self.const_usize(1));
1619 body_bx.br(header_bb);
1620 header_bx.add_incoming_to_phi(i, next, body_bb);
1621
1622 *self = Self::build(self.cx, next_bb);
1623 }
1624
1625 fn write_operand_repeatedly_unoptimized(
1626 &mut self,
1627 cg_elem: OperandRef<'tcx, &'ll Value>,
1628 count: u64,
1629 dest: PlaceRef<'tcx, &'ll Value>,
1630 ) {
1631 let zero = self.const_usize(0);
1632 let count = self.const_usize(count);
1633 let start = dest.project_index(self, zero).val.llval;
1634 let end = dest.project_index(self, count).val.llval;
1635
1636 let header_bb = self.append_sibling_block("repeat_loop_header");
1637 let body_bb = self.append_sibling_block("repeat_loop_body");
1638 let next_bb = self.append_sibling_block("repeat_loop_next");
1639
1640 self.br(header_bb);
1641
1642 let mut header_bx = Self::build(self.cx, header_bb);
1643 let current = header_bx.phi(self.val_ty(start), &[start], &[self.llbb()]);
1644
1645 let keep_going = header_bx.icmp(IntPredicate::IntNE, current, end);
1646 header_bx.cond_br(keep_going, body_bb, next_bb);
1647
1648 let mut body_bx = Self::build(self.cx, body_bb);
1649 let align = dest.val.align.restrict_for_offset(dest.layout.field(self.cx(), 0).size);
1650 cg_elem
1651 .val
1652 .store(&mut body_bx, PlaceRef::new_sized_aligned(current, cg_elem.layout, align));
1653
1654 let next = body_bx.inbounds_gep(
1655 self.backend_type(cg_elem.layout),
1656 current,
1657 &[self.const_usize(1)],
1658 );
1659 body_bx.br(header_bb);
1660 header_bx.add_incoming_to_phi(current, next, body_bb);
1661
1662 *self = Self::build(self.cx, next_bb);
1663 }
1664
1665 pub(crate) fn minimum_number_nsz(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1666 let call = self.call_intrinsic("llvm.minimumnum", &[self.val_ty(lhs)], &[lhs, rhs]);
1667 unsafe { llvm::LLVMRustSetNoSignedZeros(call) };
1668 call
1669 }
1670
1671 pub(crate) fn maximum_number_nsz(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1672 let call = self.call_intrinsic("llvm.maximumnum", &[self.val_ty(lhs)], &[lhs, rhs]);
1673 unsafe { llvm::LLVMRustSetNoSignedZeros(call) };
1674 call
1675 }
1676
1677 pub(crate) fn insert_element(
1678 &mut self,
1679 vec: &'ll Value,
1680 elt: &'ll Value,
1681 idx: &'ll Value,
1682 ) -> &'ll Value {
1683 unsafe { llvm::LLVMBuildInsertElement(self.llbuilder, vec, elt, idx, UNNAMED) }
1684 }
1685
1686 pub(crate) fn shuffle_vector(
1687 &mut self,
1688 v1: &'ll Value,
1689 v2: &'ll Value,
1690 mask: &'ll Value,
1691 ) -> &'ll Value {
1692 unsafe { llvm::LLVMBuildShuffleVector(self.llbuilder, v1, v2, mask, UNNAMED) }
1693 }
1694
1695 pub(crate) fn vector_reduce_fadd(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1696 self.call_intrinsic("llvm.vector.reduce.fadd", &[self.val_ty(src)], &[acc, src])
1697 }
1698 pub(crate) fn vector_reduce_fmul(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1699 self.call_intrinsic("llvm.vector.reduce.fmul", &[self.val_ty(src)], &[acc, src])
1700 }
1701 pub(crate) fn vector_reduce_fadd_reassoc(
1702 &mut self,
1703 acc: &'ll Value,
1704 src: &'ll Value,
1705 ) -> &'ll Value {
1706 unsafe {
1707 let instr =
1708 self.call_intrinsic("llvm.vector.reduce.fadd", &[self.val_ty(src)], &[acc, src]);
1709 llvm::LLVMRustSetAllowReassoc(instr);
1710 instr
1711 }
1712 }
1713 pub(crate) fn vector_reduce_fmul_reassoc(
1714 &mut self,
1715 acc: &'ll Value,
1716 src: &'ll Value,
1717 ) -> &'ll Value {
1718 unsafe {
1719 let instr =
1720 self.call_intrinsic("llvm.vector.reduce.fmul", &[self.val_ty(src)], &[acc, src]);
1721 llvm::LLVMRustSetAllowReassoc(instr);
1722 instr
1723 }
1724 }
1725 pub(crate) fn vector_reduce_add(&mut self, src: &'ll Value) -> &'ll Value {
1726 self.call_intrinsic("llvm.vector.reduce.add", &[self.val_ty(src)], &[src])
1727 }
1728 pub(crate) fn vector_reduce_mul(&mut self, src: &'ll Value) -> &'ll Value {
1729 self.call_intrinsic("llvm.vector.reduce.mul", &[self.val_ty(src)], &[src])
1730 }
1731 pub(crate) fn vector_reduce_and(&mut self, src: &'ll Value) -> &'ll Value {
1732 self.call_intrinsic("llvm.vector.reduce.and", &[self.val_ty(src)], &[src])
1733 }
1734 pub(crate) fn vector_reduce_or(&mut self, src: &'ll Value) -> &'ll Value {
1735 self.call_intrinsic("llvm.vector.reduce.or", &[self.val_ty(src)], &[src])
1736 }
1737 pub(crate) fn vector_reduce_xor(&mut self, src: &'ll Value) -> &'ll Value {
1738 self.call_intrinsic("llvm.vector.reduce.xor", &[self.val_ty(src)], &[src])
1739 }
1740 pub(crate) fn vector_reduce_min(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1741 self.call_intrinsic(
1742 if is_signed { "llvm.vector.reduce.smin" } else { "llvm.vector.reduce.umin" },
1743 &[self.val_ty(src)],
1744 &[src],
1745 )
1746 }
1747 pub(crate) fn vector_reduce_max(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1748 self.call_intrinsic(
1749 if is_signed { "llvm.vector.reduce.smax" } else { "llvm.vector.reduce.umax" },
1750 &[self.val_ty(src)],
1751 &[src],
1752 )
1753 }
1754}
1755impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1756 pub(crate) fn add_clause(&mut self, landing_pad: &'ll Value, clause: &'ll Value) {
1757 unsafe {
1758 llvm::LLVMAddClause(landing_pad, clause);
1759 }
1760 }
1761
1762 pub(crate) fn catch_ret(
1763 &mut self,
1764 funclet: &Funclet<'ll>,
1765 unwind: &'ll BasicBlock,
1766 ) -> &'ll Value {
1767 let ret = unsafe { llvm::LLVMBuildCatchRet(self.llbuilder, funclet.cleanuppad(), unwind) };
1768 ret.expect("LLVM does not have support for catchret")
1769 }
1770
1771 pub(crate) fn check_call<'b>(
1772 &mut self,
1773 typ: &str,
1774 fn_ty: &'ll Type,
1775 llfn: &'ll Value,
1776 args: &'b [&'ll Value],
1777 ) -> Cow<'b, [&'ll Value]> {
1778 if !(self.cx.type_kind(fn_ty) == TypeKind::Function) {
{
::core::panicking::panic_fmt(format_args!("builder::{0} not passed a function, but {1:?}",
typ, fn_ty));
}
};assert!(
1779 self.cx.type_kind(fn_ty) == TypeKind::Function,
1780 "builder::{typ} not passed a function, but {fn_ty:?}"
1781 );
1782
1783 let param_tys = self.cx.func_params_types(fn_ty);
1784
1785 let all_args_match = iter::zip(¶m_tys, args.iter().map(|&v| self.cx.val_ty(v)))
1786 .all(|(expected_ty, actual_ty)| *expected_ty == actual_ty);
1787
1788 if all_args_match {
1789 return Cow::Borrowed(args);
1790 }
1791
1792 let casted_args: Vec<_> = iter::zip(param_tys, args)
1793 .enumerate()
1794 .map(|(i, (expected_ty, &actual_val))| {
1795 let actual_ty = self.cx.val_ty(actual_val);
1796 if expected_ty != actual_ty {
1797 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/builder.rs:1797",
"rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
::tracing_core::__macro_support::Option::Some(1797u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("type mismatch in function call of {0:?}. Expected {1:?} for param {2}, got {3:?}; injecting bitcast",
llfn, expected_ty, i, actual_ty) as &dyn Value))])
});
} else { ; }
};debug!(
1798 "type mismatch in function call of {:?}. \
1799 Expected {:?} for param {}, got {:?}; injecting bitcast",
1800 llfn, expected_ty, i, actual_ty
1801 );
1802 self.bitcast(actual_val, expected_ty)
1803 } else {
1804 actual_val
1805 }
1806 })
1807 .collect();
1808
1809 Cow::Owned(casted_args)
1810 }
1811
1812 pub(crate) fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
1813 unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) }
1814 }
1815}
1816
1817impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1818 pub(crate) fn call_intrinsic(
1819 &mut self,
1820 base_name: impl Into<Cow<'static, str>>,
1821 type_params: &[&'ll Type],
1822 args: &[&'ll Value],
1823 ) -> &'ll Value {
1824 let (ty, f) = self.cx.get_intrinsic(base_name.into(), type_params);
1825 self.call(ty, None, None, f, args, None, None)
1826 }
1827
1828 fn call_lifetime_intrinsic(&mut self, intrinsic: &'static str, ptr: &'ll Value, size: Size) {
1829 let size = size.bytes();
1830 if size == 0 {
1831 return;
1832 }
1833
1834 if !self.cx().sess().emit_lifetime_markers() {
1835 return;
1836 }
1837
1838 if crate::llvm_util::get_version() >= (22, 0, 0) {
1839 let ptr = unsafe { llvm::LLVMRustStripPointerCasts(ptr) };
1842 self.call_intrinsic(intrinsic, &[self.val_ty(ptr)], &[ptr]);
1843 } else {
1844 self.call_intrinsic(intrinsic, &[self.val_ty(ptr)], &[self.cx.const_u64(size), ptr]);
1845 }
1846 }
1847}
1848impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1849 pub(crate) fn phi(
1850 &mut self,
1851 ty: &'ll Type,
1852 vals: &[&'ll Value],
1853 bbs: &[&'ll BasicBlock],
1854 ) -> &'ll Value {
1855 {
match (&vals.len(), &bbs.len()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(vals.len(), bbs.len());
1856 let phi = unsafe { llvm::LLVMBuildPhi(self.llbuilder, ty, UNNAMED) };
1857 unsafe {
1858 llvm::LLVMAddIncoming(phi, vals.as_ptr(), bbs.as_ptr(), vals.len() as c_uint);
1859 phi
1860 }
1861 }
1862
1863 fn add_incoming_to_phi(&mut self, phi: &'ll Value, val: &'ll Value, bb: &'ll BasicBlock) {
1864 unsafe {
1865 llvm::LLVMAddIncoming(phi, &val, &bb, 1 as c_uint);
1866 }
1867 }
1868}
1869impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1870 pub(crate) fn landing_pad(
1871 &mut self,
1872 ty: &'ll Type,
1873 pers_fn: &'ll Value,
1874 num_clauses: usize,
1875 ) -> &'ll Value {
1876 self.set_personality_fn(pers_fn);
1880 unsafe {
1881 llvm::LLVMBuildLandingPad(self.llbuilder, ty, None, num_clauses as c_uint, UNNAMED)
1882 }
1883 }
1884
1885 pub(crate) fn callbr(
1886 &mut self,
1887 llty: &'ll Type,
1888 fn_attrs: Option<&CodegenFnAttrs>,
1889 fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1890 llfn: &'ll Value,
1891 args: &[&'ll Value],
1892 default_dest: &'ll BasicBlock,
1893 indirect_dest: &[&'ll BasicBlock],
1894 funclet: Option<&Funclet<'ll>>,
1895 instance: Option<Instance<'tcx>>,
1896 ) -> &'ll Value {
1897 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/builder.rs:1897",
"rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
::tracing_core::__macro_support::Option::Some(1897u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("invoke {0:?} with args ({1:?})",
llfn, args) as &dyn Value))])
});
} else { ; }
};debug!("invoke {:?} with args ({:?})", llfn, args);
1898
1899 let args = self.check_call("callbr", llty, llfn, args);
1900 let funclet_bundle = funclet.map(|funclet| funclet.bundle());
1901 let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
1902 if let Some(funclet_bundle) = funclet_bundle {
1903 bundles.push(funclet_bundle);
1904 }
1905
1906 self.cfi_type_test(fn_attrs, fn_abi, instance, llfn);
1908
1909 let kcfi_bundle = self.kcfi_operand_bundle(fn_attrs, fn_abi, instance, llfn);
1911 if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|b| b.as_ref()) {
1912 bundles.push(kcfi_bundle);
1913 }
1914
1915 let pauth = self.ptrauth_operand_bundle(llfn, fn_abi);
1916 if let Some(p) = pauth.as_ref().map(|b| b.as_ref()) {
1917 bundles.push(p);
1918 }
1919
1920 let callbr = unsafe {
1921 llvm::LLVMBuildCallBr(
1922 self.llbuilder,
1923 llty,
1924 llfn,
1925 default_dest,
1926 indirect_dest.as_ptr(),
1927 indirect_dest.len() as c_uint,
1928 args.as_ptr(),
1929 args.len() as c_uint,
1930 bundles.as_ptr(),
1931 bundles.len() as c_uint,
1932 UNNAMED,
1933 )
1934 };
1935 if let Some(fn_abi) = fn_abi {
1936 fn_abi.apply_attrs_callsite(self, callbr);
1937 }
1938 callbr
1939 }
1940
1941 fn cfi_type_test(
1943 &mut self,
1944 fn_attrs: Option<&CodegenFnAttrs>,
1945 fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1946 instance: Option<Instance<'tcx>>,
1947 llfn: &'ll Value,
1948 ) {
1949 let is_indirect_call = unsafe { llvm::LLVMRustIsNonGVFunctionPointerTy(llfn) };
1950 if self.tcx.sess.is_sanitizer_cfi_enabled()
1951 && let Some(fn_abi) = fn_abi
1952 && is_indirect_call
1953 {
1954 if let Some(fn_attrs) = fn_attrs
1955 && fn_attrs.sanitizers.disabled.contains(SanitizerSet::CFI)
1956 {
1957 return;
1958 }
1959
1960 let mut options = cfi::TypeIdOptions::empty();
1961 if self.tcx.sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1962 options.insert(cfi::TypeIdOptions::GENERALIZE_POINTERS);
1963 }
1964 if self.tcx.sess.is_sanitizer_cfi_normalize_integers_enabled() {
1965 options.insert(cfi::TypeIdOptions::NORMALIZE_INTEGERS);
1966 }
1967
1968 let typeid = if let Some(instance) = instance {
1969 cfi::typeid_for_instance(self.tcx, instance, options)
1970 } else {
1971 cfi::typeid_for_fnabi(self.tcx, fn_abi, options)
1972 };
1973 let typeid_metadata = self.cx.create_metadata(typeid.as_bytes());
1974 let dbg_loc = self.get_dbg_loc();
1975
1976 let typeid = self.get_metadata_value(typeid_metadata);
1980 let cond = self.call_intrinsic("llvm.type.test", &[], &[llfn, typeid]);
1981 let bb_pass = self.append_sibling_block("type_test.pass");
1982 let bb_fail = self.append_sibling_block("type_test.fail");
1983 self.cond_br(cond, bb_pass, bb_fail);
1984
1985 self.switch_to_block(bb_fail);
1986 if let Some(dbg_loc) = dbg_loc {
1987 self.set_dbg_loc(dbg_loc);
1988 }
1989 self.abort();
1990 self.unreachable();
1991
1992 self.switch_to_block(bb_pass);
1993 if let Some(dbg_loc) = dbg_loc {
1994 self.set_dbg_loc(dbg_loc);
1995 }
1996 }
1997 }
1998
1999 fn kcfi_operand_bundle(
2001 &mut self,
2002 fn_attrs: Option<&CodegenFnAttrs>,
2003 fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
2004 instance: Option<Instance<'tcx>>,
2005 llfn: &'ll Value,
2006 ) -> Option<llvm::OperandBundleBox<'ll>> {
2007 let is_indirect_call = unsafe { llvm::LLVMRustIsNonGVFunctionPointerTy(llfn) };
2008 let kcfi_bundle = if self.tcx.sess.is_sanitizer_kcfi_enabled()
2009 && let Some(fn_abi) = fn_abi
2010 && is_indirect_call
2011 {
2012 if let Some(fn_attrs) = fn_attrs
2013 && fn_attrs.sanitizers.disabled.contains(SanitizerSet::KCFI)
2014 {
2015 return None;
2016 }
2017
2018 let mut options = kcfi::TypeIdOptions::empty();
2019 if self.tcx.sess.is_sanitizer_cfi_generalize_pointers_enabled() {
2020 options.insert(kcfi::TypeIdOptions::GENERALIZE_POINTERS);
2021 }
2022 if self.tcx.sess.is_sanitizer_cfi_normalize_integers_enabled() {
2023 options.insert(kcfi::TypeIdOptions::NORMALIZE_INTEGERS);
2024 }
2025
2026 let kcfi_typeid = if let Some(instance) = instance {
2027 kcfi::typeid_for_instance(self.tcx, instance, options)
2028 } else {
2029 kcfi::typeid_for_fnabi(self.tcx, fn_abi, options)
2030 };
2031
2032 Some(llvm::OperandBundleBox::new("kcfi", &[self.const_u32(kcfi_typeid)]))
2033 } else {
2034 None
2035 };
2036 kcfi_bundle
2037 }
2038
2039 fn ptrauth_operand_bundle(
2041 &mut self,
2042 llfn: &'ll Value,
2043 fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
2044 ) -> Option<llvm::OperandBundleBox<'ll>> {
2045 if self.sess().target.llvm_abiname != LlvmAbi::Pauthtest {
2046 return None;
2047 }
2048 if fn_abi?.conv != CanonAbi::C {
2051 return None;
2052 }
2053 if llvm::get_value_name(llfn).starts_with(b"llvm.") {
2055 return None;
2056 }
2057
2058 let key: u32 = 0;
2066 let discriminator: u64 = 0;
2067 Some(llvm::OperandBundleBox::new(
2068 "ptrauth",
2069 &[self.const_u32(key), self.const_u64(discriminator)],
2070 ))
2071 }
2072
2073 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("instrprof_increment",
"rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
::tracing_core::__macro_support::Option::Some(2074u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
::tracing_core::field::FieldSet::new(&["fn_name", "hash",
"num_counters", "index"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_name)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&hash)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&num_counters)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&index)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
self.call_intrinsic("llvm.instrprof.increment", &[],
&[fn_name, hash, num_counters, index]);
}
}
}#[instrument(level = "debug", skip(self))]
2075 pub(crate) fn instrprof_increment(
2076 &mut self,
2077 fn_name: &'ll Value,
2078 hash: &'ll Value,
2079 num_counters: &'ll Value,
2080 index: &'ll Value,
2081 ) {
2082 self.call_intrinsic("llvm.instrprof.increment", &[], &[fn_name, hash, num_counters, index]);
2083 }
2084}