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, b_offset }
= place.layout.backend_repr {
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, b_offset } = place.layout.backend_repr {
797 let mut load = |i, scalar: abi::Scalar, layout, align, offset| {
798 let llptr = if i == 0 {
799 place.val.llval
800 } else {
801 self.inbounds_ptradd(place.val.llval, self.const_usize(b_offset.bytes()))
802 };
803 let llty = place.layout.scalar_pair_element_llvm_type(self, i, false);
804 let load = self.load(llty, llptr, align);
805 scalar_load_metadata(self, load, scalar, layout, offset);
806 self.to_immediate_scalar(load, scalar)
807 };
808
809 OperandValue::Pair(
810 load(0, a, place.layout, place.val.align, Size::ZERO),
811 load(1, b, place.layout, place.val.align.restrict_for_offset(b_offset), b_offset),
812 )
813 } else {
814 OperandValue::Ref(place.val)
815 };
816
817 OperandRef { val, layout: place.layout, move_annotation: None }
818 }
819
820 fn write_operand_repeatedly(
821 &mut self,
822 cg_elem: OperandRef<'tcx, &'ll Value>,
823 count: u64,
824 dest: PlaceRef<'tcx, &'ll Value>,
825 ) {
826 if self.cx.sess().opts.optimize == OptLevel::No {
827 self.write_operand_repeatedly_unoptimized(cg_elem, count, dest);
835 } else {
836 self.write_operand_repeatedly_optimized(cg_elem, count, dest);
837 }
838 }
839
840 fn range_metadata(&mut self, load: &'ll Value, range: WrappingRange) {
841 if self.cx.sess().opts.optimize == OptLevel::No {
842 return;
844 }
845
846 let llty = self.cx.val_ty(load);
847 let md = [
848 llvm::LLVMValueAsMetadata(self.cx.const_uint_big(llty, range.start)),
849 llvm::LLVMValueAsMetadata(self.cx.const_uint_big(llty, range.end.wrapping_add(1))),
850 ];
851 self.set_metadata_node(load, llvm::MD_range, &md);
852 }
853
854 fn nonnull_metadata(&mut self, load: &'ll Value) {
855 self.set_metadata_node(load, llvm::MD_nonnull, &[]);
856 }
857
858 fn store(&mut self, val: &'ll Value, ptr: &'ll Value, align: Align) -> &'ll Value {
859 self.store_with_flags(val, ptr, align, MemFlags::empty())
860 }
861
862 fn store_with_flags(
863 &mut self,
864 val: &'ll Value,
865 ptr: &'ll Value,
866 align: Align,
867 flags: MemFlags,
868 ) -> &'ll Value {
869 {
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:869",
"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(869u32),
::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);
870 {
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);
871 unsafe {
872 let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
873 let align = align.min(self.cx().tcx.sess.target.max_reliable_alignment());
874 let align = align.bytes() as c_uint;
875 llvm::LLVMSetAlignment(store, align);
876 if flags.contains(MemFlags::VOLATILE) {
877 llvm::LLVMSetVolatile(store, llvm::TRUE);
878 }
879 if flags.contains(MemFlags::NONTEMPORAL) {
880 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!(
893 self.cx.tcx.sess.target.arch,
894 Arch::AArch64 | Arch::Arm | Arch::RiscV32 | Arch::RiscV64
895 );
896 if use_nontemporal {
897 let one = llvm::LLVMValueAsMetadata(self.cx.const_i32(1));
902 self.set_metadata_node(store, llvm::MD_nontemporal, &[one]);
903 }
904 }
905 if flags.contains(MemFlags::CAPTURES_READ_ONLY)
906 && crate::llvm_util::get_version() >= (22, 0, 0)
907 {
908 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!(
909 self.type_kind(self.val_ty(val)) == TypeKind::Pointer,
910 "CAPTURED_READ_ONLY is only supported on pointer stores"
911 );
912 let args = [
913 self.cx.create_metadata(b"address"),
914 self.cx.create_metadata(b"read_provenance"),
915 ];
916 let id = self.get_md_kind_id("captures");
918 let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, args.as_ptr(), args.len());
919 self.set_metadata(store, id, md);
920 }
921 store
922 }
923 }
924
925 fn atomic_store(
926 &mut self,
927 val: &'ll Value,
928 ptr: &'ll Value,
929 order: rustc_middle::ty::AtomicOrdering,
930 size: Size,
931 ) {
932 {
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:932",
"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(932u32),
::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);
933 {
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);
934 unsafe {
935 let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
936 llvm::LLVMSetOrdering(store, AtomicOrdering::from_generic(order));
938 llvm::LLVMSetAlignment(store, size.bytes() as c_uint);
940 }
941 }
942
943 fn gep(&mut self, ty: &'ll Type, ptr: &'ll Value, indices: &[&'ll Value]) -> &'ll Value {
944 unsafe {
945 llvm::LLVMBuildGEPWithNoWrapFlags(
946 self.llbuilder,
947 ty,
948 ptr,
949 indices.as_ptr(),
950 indices.len() as c_uint,
951 UNNAMED,
952 GEPNoWrapFlags::default(),
953 )
954 }
955 }
956
957 fn inbounds_gep(
958 &mut self,
959 ty: &'ll Type,
960 ptr: &'ll Value,
961 indices: &[&'ll Value],
962 ) -> &'ll Value {
963 unsafe {
964 llvm::LLVMBuildGEPWithNoWrapFlags(
965 self.llbuilder,
966 ty,
967 ptr,
968 indices.as_ptr(),
969 indices.len() as c_uint,
970 UNNAMED,
971 GEPNoWrapFlags::InBounds,
972 )
973 }
974 }
975
976 fn inbounds_nuw_gep(
977 &mut self,
978 ty: &'ll Type,
979 ptr: &'ll Value,
980 indices: &[&'ll Value],
981 ) -> &'ll Value {
982 unsafe {
983 llvm::LLVMBuildGEPWithNoWrapFlags(
984 self.llbuilder,
985 ty,
986 ptr,
987 indices.as_ptr(),
988 indices.len() as c_uint,
989 UNNAMED,
990 GEPNoWrapFlags::InBounds | GEPNoWrapFlags::NUW,
991 )
992 }
993 }
994
995 fn trunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
997 unsafe { llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
998 }
999
1000 fn unchecked_utrunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1001 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);
1002
1003 let trunc = self.trunc(val, dest_ty);
1004 unsafe {
1005 if llvm::LLVMIsAInstruction(trunc).is_some() {
1006 llvm::LLVMSetNUW(trunc, TRUE);
1007 }
1008 }
1009 trunc
1010 }
1011
1012 fn unchecked_strunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1013 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);
1014
1015 let trunc = self.trunc(val, dest_ty);
1016 unsafe {
1017 if llvm::LLVMIsAInstruction(trunc).is_some() {
1018 llvm::LLVMSetNSW(trunc, TRUE);
1019 }
1020 }
1021 trunc
1022 }
1023
1024 fn sext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1025 unsafe { llvm::LLVMBuildSExt(self.llbuilder, val, dest_ty, UNNAMED) }
1026 }
1027
1028 fn fptoui_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1029 self.call_intrinsic("llvm.fptoui.sat", &[dest_ty, self.val_ty(val)], &[val])
1030 }
1031
1032 fn fptosi_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1033 self.call_intrinsic("llvm.fptosi.sat", &[dest_ty, self.val_ty(val)], &[val])
1034 }
1035
1036 fn fptoui(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1037 if self.sess().target.is_like_wasm {
1052 let src_ty = self.cx.val_ty(val);
1053 if self.cx.type_kind(src_ty) != TypeKind::Vector {
1054 let float_width = self.cx.float_width(src_ty);
1055 let int_width = self.cx.int_width(dest_ty);
1056 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)) {
1057 return self.call_intrinsic(
1058 "llvm.wasm.trunc.unsigned",
1059 &[dest_ty, src_ty],
1060 &[val],
1061 );
1062 }
1063 }
1064 }
1065 unsafe { llvm::LLVMBuildFPToUI(self.llbuilder, val, dest_ty, UNNAMED) }
1066 }
1067
1068 fn fptosi(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1069 if self.sess().target.is_like_wasm {
1071 let src_ty = self.cx.val_ty(val);
1072 if self.cx.type_kind(src_ty) != TypeKind::Vector {
1073 let float_width = self.cx.float_width(src_ty);
1074 let int_width = self.cx.int_width(dest_ty);
1075 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)) {
1076 return self.call_intrinsic(
1077 "llvm.wasm.trunc.signed",
1078 &[dest_ty, src_ty],
1079 &[val],
1080 );
1081 }
1082 }
1083 }
1084 unsafe { llvm::LLVMBuildFPToSI(self.llbuilder, val, dest_ty, UNNAMED) }
1085 }
1086
1087 fn uitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1088 unsafe { llvm::LLVMBuildUIToFP(self.llbuilder, val, dest_ty, UNNAMED) }
1089 }
1090
1091 fn sitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1092 unsafe { llvm::LLVMBuildSIToFP(self.llbuilder, val, dest_ty, UNNAMED) }
1093 }
1094
1095 fn fptrunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1096 unsafe { llvm::LLVMBuildFPTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
1097 }
1098
1099 fn fpext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1100 unsafe { llvm::LLVMBuildFPExt(self.llbuilder, val, dest_ty, UNNAMED) }
1101 }
1102
1103 fn ptrtoint(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1104 unsafe { llvm::LLVMBuildPtrToInt(self.llbuilder, val, dest_ty, UNNAMED) }
1105 }
1106
1107 fn inttoptr(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1108 unsafe { llvm::LLVMBuildIntToPtr(self.llbuilder, val, dest_ty, UNNAMED) }
1109 }
1110
1111 fn bitcast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1112 unsafe { llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty, UNNAMED) }
1113 }
1114
1115 fn intcast(&mut self, val: &'ll Value, dest_ty: &'ll Type, is_signed: bool) -> &'ll Value {
1116 unsafe {
1117 llvm::LLVMBuildIntCast2(self.llbuilder, val, dest_ty, is_signed.to_llvm_bool(), UNNAMED)
1118 }
1119 }
1120
1121 fn pointercast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1122 unsafe { llvm::LLVMBuildPointerCast(self.llbuilder, val, dest_ty, UNNAMED) }
1123 }
1124
1125 fn icmp(&mut self, op: IntPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1127 let op = llvm::IntPredicate::from_generic(op);
1128 unsafe { llvm::LLVMBuildICmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
1129 }
1130
1131 fn fcmp(&mut self, op: RealPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1132 let op = llvm::RealPredicate::from_generic(op);
1133 unsafe { llvm::LLVMBuildFCmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
1134 }
1135
1136 fn three_way_compare(
1137 &mut self,
1138 ty: Ty<'tcx>,
1139 lhs: Self::Value,
1140 rhs: Self::Value,
1141 ) -> Self::Value {
1142 let size = ty.primitive_size(self.tcx);
1143 let name = if ty.is_signed() { "llvm.scmp" } else { "llvm.ucmp" };
1144
1145 self.call_intrinsic(name, &[self.type_i8(), self.type_ix(size.bits())], &[lhs, rhs])
1146 }
1147
1148 fn memcpy(
1150 &mut self,
1151 dst: &'ll Value,
1152 dst_align: Align,
1153 src: &'ll Value,
1154 src_align: Align,
1155 size: &'ll Value,
1156 flags: MemFlags,
1157 tt: Option<FncTree>,
1158 ) {
1159 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");
1160 let size = self.intcast(size, self.type_isize(), false);
1161 let is_volatile = flags.contains(MemFlags::VOLATILE);
1162 let memcpy = unsafe {
1163 llvm::LLVMRustBuildMemCpy(
1164 self.llbuilder,
1165 dst,
1166 dst_align.bytes() as c_uint,
1167 src,
1168 src_align.bytes() as c_uint,
1169 size,
1170 is_volatile,
1171 )
1172 };
1173
1174 if let Some(tt) = tt {
1180 crate::typetree::add_tt(self, memcpy, tt);
1181 }
1182 }
1183
1184 fn memmove(
1185 &mut self,
1186 dst: &'ll Value,
1187 dst_align: Align,
1188 src: &'ll Value,
1189 src_align: Align,
1190 size: &'ll Value,
1191 flags: MemFlags,
1192 ) {
1193 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");
1194 let size = self.intcast(size, self.type_isize(), false);
1195 let is_volatile = flags.contains(MemFlags::VOLATILE);
1196 unsafe {
1197 llvm::LLVMRustBuildMemMove(
1198 self.llbuilder,
1199 dst,
1200 dst_align.bytes() as c_uint,
1201 src,
1202 src_align.bytes() as c_uint,
1203 size,
1204 is_volatile,
1205 );
1206 }
1207 }
1208
1209 fn memset(
1210 &mut self,
1211 ptr: &'ll Value,
1212 fill_byte: &'ll Value,
1213 size: &'ll Value,
1214 align: Align,
1215 flags: MemFlags,
1216 ) {
1217 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");
1218 let is_volatile = flags.contains(MemFlags::VOLATILE);
1219 unsafe {
1220 llvm::LLVMRustBuildMemSet(
1221 self.llbuilder,
1222 ptr,
1223 align.bytes() as c_uint,
1224 fill_byte,
1225 size,
1226 is_volatile,
1227 );
1228 }
1229 }
1230
1231 fn vscale(&mut self, ty: &'ll Type) -> &'ll Value {
1232 unsafe { llvm::LLVMRustBuildVScale(self.llbuilder, ty) }
1233 }
1234
1235 fn select(
1236 &mut self,
1237 cond: &'ll Value,
1238 then_val: &'ll Value,
1239 else_val: &'ll Value,
1240 ) -> &'ll Value {
1241 unsafe { llvm::LLVMBuildSelect(self.llbuilder, cond, then_val, else_val, UNNAMED) }
1242 }
1243
1244 fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
1245 unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) }
1246 }
1247
1248 fn extract_element(&mut self, vec: &'ll Value, idx: &'ll Value) -> &'ll Value {
1249 unsafe { llvm::LLVMBuildExtractElement(self.llbuilder, vec, idx, UNNAMED) }
1250 }
1251
1252 fn vector_splat(&mut self, num_elts: usize, elt: &'ll Value) -> &'ll Value {
1253 unsafe {
1254 let elt_ty = self.cx.val_ty(elt);
1255 let undef = llvm::LLVMGetUndef(self.type_vector(elt_ty, num_elts as u64));
1256 let vec = self.insert_element(undef, elt, self.cx.const_i32(0));
1257 let vec_i32_ty = self.type_vector(self.type_i32(), num_elts as u64);
1258 self.shuffle_vector(vec, undef, self.const_null(vec_i32_ty))
1259 }
1260 }
1261
1262 fn extract_value(&mut self, agg_val: &'ll Value, idx: u64) -> &'ll Value {
1263 {
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);
1264 unsafe { llvm::LLVMBuildExtractValue(self.llbuilder, agg_val, idx as c_uint, UNNAMED) }
1265 }
1266
1267 fn insert_value(&mut self, agg_val: &'ll Value, elt: &'ll Value, idx: u64) -> &'ll Value {
1268 {
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);
1269 unsafe { llvm::LLVMBuildInsertValue(self.llbuilder, agg_val, elt, idx as c_uint, UNNAMED) }
1270 }
1271
1272 fn set_personality_fn(&mut self, personality: &'ll Value) {
1273 unsafe {
1274 llvm::LLVMSetPersonalityFn(self.llfn(), personality);
1275 }
1276 }
1277
1278 fn cleanup_landing_pad(&mut self, pers_fn: &'ll Value) -> (&'ll Value, &'ll Value) {
1279 let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1280 let landing_pad = self.landing_pad(ty, pers_fn, 0);
1281 unsafe {
1282 llvm::LLVMSetCleanup(landing_pad, llvm::TRUE);
1283 }
1284 (self.extract_value(landing_pad, 0), self.extract_value(landing_pad, 1))
1285 }
1286
1287 fn filter_landing_pad(&mut self, pers_fn: &'ll Value) {
1288 let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1289 let landing_pad = self.landing_pad(ty, pers_fn, 1);
1290 self.add_clause(landing_pad, self.const_array(self.type_ptr(), &[]));
1291 }
1292
1293 fn resume(&mut self, exn0: &'ll Value, exn1: &'ll Value) {
1294 let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1295 let mut exn = self.const_poison(ty);
1296 exn = self.insert_value(exn, exn0, 0);
1297 exn = self.insert_value(exn, exn1, 1);
1298 unsafe {
1299 llvm::LLVMBuildResume(self.llbuilder, exn);
1300 }
1301 }
1302
1303 fn cleanup_pad(&mut self, parent: Option<&'ll Value>, args: &[&'ll Value]) -> Funclet<'ll> {
1304 let ret = unsafe {
1305 llvm::LLVMBuildCleanupPad(
1306 self.llbuilder,
1307 parent,
1308 args.as_ptr(),
1309 args.len() as c_uint,
1310 c"cleanuppad".as_ptr(),
1311 )
1312 };
1313 Funclet::new(ret.expect("LLVM does not have support for cleanuppad"))
1314 }
1315
1316 fn cleanup_ret(&mut self, funclet: &Funclet<'ll>, unwind: Option<&'ll BasicBlock>) {
1317 unsafe {
1318 llvm::LLVMBuildCleanupRet(self.llbuilder, funclet.cleanuppad(), unwind)
1319 .expect("LLVM does not have support for cleanupret");
1320 }
1321 }
1322
1323 fn catch_pad(&mut self, parent: &'ll Value, args: &[&'ll Value]) -> Funclet<'ll> {
1324 let ret = unsafe {
1325 llvm::LLVMBuildCatchPad(
1326 self.llbuilder,
1327 parent,
1328 args.as_ptr(),
1329 args.len() as c_uint,
1330 c"catchpad".as_ptr(),
1331 )
1332 };
1333 Funclet::new(ret.expect("LLVM does not have support for catchpad"))
1334 }
1335
1336 fn catch_switch(
1337 &mut self,
1338 parent: Option<&'ll Value>,
1339 unwind: Option<&'ll BasicBlock>,
1340 handlers: &[&'ll BasicBlock],
1341 ) -> &'ll Value {
1342 let ret = unsafe {
1343 llvm::LLVMBuildCatchSwitch(
1344 self.llbuilder,
1345 parent,
1346 unwind,
1347 handlers.len() as c_uint,
1348 c"catchswitch".as_ptr(),
1349 )
1350 };
1351 let ret = ret.expect("LLVM does not have support for catchswitch");
1352 for handler in handlers {
1353 unsafe {
1354 llvm::LLVMAddHandler(ret, handler);
1355 }
1356 }
1357 ret
1358 }
1359
1360 fn get_funclet_cleanuppad(&self, funclet: &Funclet<'ll>) -> &'ll Value {
1361 funclet.cleanuppad()
1362 }
1363
1364 fn atomic_cmpxchg(
1366 &mut self,
1367 dst: &'ll Value,
1368 cmp: &'ll Value,
1369 src: &'ll Value,
1370 order: rustc_middle::ty::AtomicOrdering,
1371 failure_order: rustc_middle::ty::AtomicOrdering,
1372 weak: bool,
1373 ) -> (&'ll Value, &'ll Value) {
1374 unsafe {
1375 let value = llvm::LLVMBuildAtomicCmpXchg(
1376 self.llbuilder,
1377 dst,
1378 cmp,
1379 src,
1380 AtomicOrdering::from_generic(order),
1381 AtomicOrdering::from_generic(failure_order),
1382 llvm::FALSE, );
1384 llvm::LLVMSetWeak(value, weak.to_llvm_bool());
1385 let val = self.extract_value(value, 0);
1386 let success = self.extract_value(value, 1);
1387 (val, success)
1388 }
1389 }
1390
1391 fn atomic_rmw(
1392 &mut self,
1393 op: rustc_codegen_ssa::common::AtomicRmwBinOp,
1394 dst: &'ll Value,
1395 src: &'ll Value,
1396 order: rustc_middle::ty::AtomicOrdering,
1397 ret_ptr: bool,
1398 ) -> &'ll Value {
1399 let mut res = unsafe {
1403 llvm::LLVMBuildAtomicRMW(
1404 self.llbuilder,
1405 AtomicRmwBinOp::from_generic(op),
1406 dst,
1407 src,
1408 AtomicOrdering::from_generic(order),
1409 llvm::FALSE, )
1411 };
1412 if ret_ptr && self.val_ty(res) != self.type_ptr() {
1413 res = self.inttoptr(res, self.type_ptr());
1414 }
1415 res
1416 }
1417
1418 fn atomic_fence(
1419 &mut self,
1420 order: rustc_middle::ty::AtomicOrdering,
1421 scope: SynchronizationScope,
1422 ) {
1423 let single_threaded = match scope {
1424 SynchronizationScope::SingleThread => true,
1425 SynchronizationScope::CrossThread => false,
1426 };
1427 unsafe {
1428 llvm::LLVMBuildFence(
1429 self.llbuilder,
1430 AtomicOrdering::from_generic(order),
1431 single_threaded.to_llvm_bool(),
1432 UNNAMED,
1433 );
1434 }
1435 }
1436
1437 fn set_invariant_load(&mut self, load: &'ll Value) {
1438 self.set_metadata_node(load, llvm::MD_invariant_load, &[]);
1439 }
1440
1441 fn lifetime_start(&mut self, ptr: &'ll Value, size: Size) {
1442 self.call_lifetime_intrinsic("llvm.lifetime.start", ptr, size);
1443 }
1444
1445 fn lifetime_end(&mut self, ptr: &'ll Value, size: Size) {
1446 self.call_lifetime_intrinsic("llvm.lifetime.end", ptr, size);
1447 }
1448
1449 fn call(
1450 &mut self,
1451 llty: &'ll Type,
1452 caller_attrs: Option<&CodegenFnAttrs>,
1453 fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1454 llfn: &'ll Value,
1455 args: &[&'ll Value],
1456 funclet: Option<&Funclet<'ll>>,
1457 callee_instance: Option<Instance<'tcx>>,
1458 ) -> &'ll Value {
1459 {
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:1459",
"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(1459u32),
::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);
1460
1461 let args = self.check_call("call", llty, llfn, args);
1462 let funclet_bundle = funclet.map(|funclet| funclet.bundle());
1463 let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
1464 if let Some(funclet_bundle) = funclet_bundle {
1465 bundles.push(funclet_bundle);
1466 }
1467
1468 self.cfi_type_test(caller_attrs, fn_abi, callee_instance, llfn);
1470
1471 let kcfi_bundle = self.kcfi_operand_bundle(caller_attrs, fn_abi, callee_instance, llfn);
1473 if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|b| b.as_ref()) {
1474 bundles.push(kcfi_bundle);
1475 }
1476
1477 let pauth = self.ptrauth_operand_bundle(llfn, fn_abi);
1478 if let Some(p) = pauth.as_ref().map(|b| b.as_ref()) {
1479 bundles.push(p);
1480 }
1481
1482 let call = unsafe {
1483 llvm::LLVMBuildCallWithOperandBundles(
1484 self.llbuilder,
1485 llty,
1486 llfn,
1487 args.as_ptr() as *const &llvm::Value,
1488 args.len() as c_uint,
1489 bundles.as_ptr(),
1490 bundles.len() as c_uint,
1491 c"".as_ptr(),
1492 )
1493 };
1494
1495 if let Some(callee_instance) = callee_instance {
1496 let callee_attrs = self.cx.tcx.codegen_fn_attrs(callee_instance.def_id());
1498
1499 if let Some(inlining_rule) =
1500 attributes::inline_attr(&self.cx, self.cx.tcx, callee_instance, callee_attrs)
1501 {
1502 attributes::apply_to_callsite(
1503 call,
1504 llvm::AttributePlace::Function,
1505 &[inlining_rule],
1506 );
1507 }
1508 }
1509
1510 if let Some(fn_abi) = fn_abi {
1511 fn_abi.apply_attrs_callsite(self, call);
1512 }
1513 call
1514 }
1515
1516 fn tail_call(
1517 &mut self,
1518 llty: Self::Type,
1519 caller_attrs: Option<&CodegenFnAttrs>,
1520 fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
1521 llfn: Self::Value,
1522 args: &[Self::Value],
1523 funclet: Option<&Self::Funclet>,
1524 callee_instance: Option<Instance<'tcx>>,
1525 ) {
1526 let call =
1527 self.call(llty, caller_attrs, Some(fn_abi), llfn, args, funclet, callee_instance);
1528 llvm::LLVMSetTailCallKind(call, llvm::TailCallKind::MustTail);
1529
1530 match &fn_abi.ret.mode {
1531 PassMode::Ignore | PassMode::Indirect { .. } => self.ret_void(),
1532 PassMode::Direct(_) | PassMode::Pair { .. } | PassMode::Cast { .. } => self.ret(call),
1533 }
1534 }
1535
1536 fn zext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1537 unsafe { llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty, UNNAMED) }
1538 }
1539
1540 fn apply_attrs_to_cleanup_callsite(&mut self, llret: &'ll Value) {
1541 let cold_inline = llvm::AttributeKind::Cold.create_attr(self.llcx);
1543 attributes::apply_to_callsite(llret, llvm::AttributePlace::Function, &[cold_inline]);
1544 }
1545}
1546
1547impl<'ll> StaticBuilderMethods for Builder<'_, 'll, '_> {
1548 fn get_static(&mut self, def_id: DefId) -> &'ll Value {
1549 let global = self.cx().get_static(def_id);
1551 if self.cx().tcx.is_thread_local_static(def_id) {
1552 let pointer =
1553 self.call_intrinsic("llvm.threadlocal.address", &[self.val_ty(global)], &[global]);
1554 self.pointercast(pointer, self.type_ptr())
1556 } else {
1557 self.cx().const_pointercast(global, self.type_ptr())
1559 }
1560 }
1561}
1562
1563impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1564 pub(crate) fn llfn(&self) -> &'ll Value {
1565 unsafe { llvm::LLVMGetBasicBlockParent(self.llbb()) }
1566 }
1567}
1568
1569impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1570 fn position_at_start(&mut self, llbb: &'ll BasicBlock) {
1571 unsafe {
1572 llvm::LLVMRustPositionBuilderAtStart(self.llbuilder, llbb);
1573 }
1574 }
1575}
1576impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1577 fn align_metadata(&mut self, load: &'ll Value, align: Align) {
1578 let md = [llvm::LLVMValueAsMetadata(self.cx.const_u64(align.bytes()))];
1579 self.set_metadata_node(load, llvm::MD_align, &md);
1580 }
1581
1582 fn noundef_metadata(&mut self, load: &'ll Value) {
1583 self.set_metadata_node(load, llvm::MD_noundef, &[]);
1584 }
1585
1586 pub(crate) fn set_unpredictable(&mut self, inst: &'ll Value) {
1587 self.set_metadata_node(inst, llvm::MD_unpredictable, &[]);
1588 }
1589
1590 fn write_operand_repeatedly_optimized(
1591 &mut self,
1592 cg_elem: OperandRef<'tcx, &'ll Value>,
1593 count: u64,
1594 dest: PlaceRef<'tcx, &'ll Value>,
1595 ) {
1596 let zero = self.const_usize(0);
1597 let count = self.const_usize(count);
1598
1599 let header_bb = self.append_sibling_block("repeat_loop_header");
1600 let body_bb = self.append_sibling_block("repeat_loop_body");
1601 let next_bb = self.append_sibling_block("repeat_loop_next");
1602
1603 self.br(header_bb);
1604
1605 let mut header_bx = Self::build(self.cx, header_bb);
1606 let i = header_bx.phi(self.val_ty(zero), &[zero], &[self.llbb()]);
1607
1608 let keep_going = header_bx.icmp(IntPredicate::IntULT, i, count);
1609 header_bx.cond_br(keep_going, body_bb, next_bb);
1610
1611 let mut body_bx = Self::build(self.cx, body_bb);
1612 let dest_elem = dest.project_index(&mut body_bx, i);
1613 cg_elem.val.store(&mut body_bx, dest_elem);
1614
1615 let next = body_bx.unchecked_uadd(i, self.const_usize(1));
1616 body_bx.br(header_bb);
1617 header_bx.add_incoming_to_phi(i, next, body_bb);
1618
1619 *self = Self::build(self.cx, next_bb);
1620 }
1621
1622 fn write_operand_repeatedly_unoptimized(
1623 &mut self,
1624 cg_elem: OperandRef<'tcx, &'ll Value>,
1625 count: u64,
1626 dest: PlaceRef<'tcx, &'ll Value>,
1627 ) {
1628 let zero = self.const_usize(0);
1629 let count = self.const_usize(count);
1630 let start = dest.project_index(self, zero).val.llval;
1631 let end = dest.project_index(self, count).val.llval;
1632
1633 let header_bb = self.append_sibling_block("repeat_loop_header");
1634 let body_bb = self.append_sibling_block("repeat_loop_body");
1635 let next_bb = self.append_sibling_block("repeat_loop_next");
1636
1637 self.br(header_bb);
1638
1639 let mut header_bx = Self::build(self.cx, header_bb);
1640 let current = header_bx.phi(self.val_ty(start), &[start], &[self.llbb()]);
1641
1642 let keep_going = header_bx.icmp(IntPredicate::IntNE, current, end);
1643 header_bx.cond_br(keep_going, body_bb, next_bb);
1644
1645 let mut body_bx = Self::build(self.cx, body_bb);
1646 let align = dest.val.align.restrict_for_offset(dest.layout.field(self.cx(), 0).size);
1647 cg_elem
1648 .val
1649 .store(&mut body_bx, PlaceRef::new_sized_aligned(current, cg_elem.layout, align));
1650
1651 let next = body_bx.inbounds_gep(
1652 self.backend_type(cg_elem.layout),
1653 current,
1654 &[self.const_usize(1)],
1655 );
1656 body_bx.br(header_bb);
1657 header_bx.add_incoming_to_phi(current, next, body_bb);
1658
1659 *self = Self::build(self.cx, next_bb);
1660 }
1661
1662 pub(crate) fn minimum_number_nsz(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1663 let call = self.call_intrinsic("llvm.minimumnum", &[self.val_ty(lhs)], &[lhs, rhs]);
1664 unsafe { llvm::LLVMRustSetNoSignedZeros(call) };
1665 call
1666 }
1667
1668 pub(crate) fn maximum_number_nsz(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1669 let call = self.call_intrinsic("llvm.maximumnum", &[self.val_ty(lhs)], &[lhs, rhs]);
1670 unsafe { llvm::LLVMRustSetNoSignedZeros(call) };
1671 call
1672 }
1673
1674 pub(crate) fn insert_element(
1675 &mut self,
1676 vec: &'ll Value,
1677 elt: &'ll Value,
1678 idx: &'ll Value,
1679 ) -> &'ll Value {
1680 unsafe { llvm::LLVMBuildInsertElement(self.llbuilder, vec, elt, idx, UNNAMED) }
1681 }
1682
1683 pub(crate) fn shuffle_vector(
1684 &mut self,
1685 v1: &'ll Value,
1686 v2: &'ll Value,
1687 mask: &'ll Value,
1688 ) -> &'ll Value {
1689 unsafe { llvm::LLVMBuildShuffleVector(self.llbuilder, v1, v2, mask, UNNAMED) }
1690 }
1691
1692 pub(crate) fn vector_reduce_fadd(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1693 self.call_intrinsic("llvm.vector.reduce.fadd", &[self.val_ty(src)], &[acc, src])
1694 }
1695 pub(crate) fn vector_reduce_fmul(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1696 self.call_intrinsic("llvm.vector.reduce.fmul", &[self.val_ty(src)], &[acc, src])
1697 }
1698 pub(crate) fn vector_reduce_fadd_reassoc(
1699 &mut self,
1700 acc: &'ll Value,
1701 src: &'ll Value,
1702 ) -> &'ll Value {
1703 unsafe {
1704 let instr =
1705 self.call_intrinsic("llvm.vector.reduce.fadd", &[self.val_ty(src)], &[acc, src]);
1706 llvm::LLVMRustSetAllowReassoc(instr);
1707 instr
1708 }
1709 }
1710 pub(crate) fn vector_reduce_fmul_reassoc(
1711 &mut self,
1712 acc: &'ll Value,
1713 src: &'ll Value,
1714 ) -> &'ll Value {
1715 unsafe {
1716 let instr =
1717 self.call_intrinsic("llvm.vector.reduce.fmul", &[self.val_ty(src)], &[acc, src]);
1718 llvm::LLVMRustSetAllowReassoc(instr);
1719 instr
1720 }
1721 }
1722 pub(crate) fn vector_reduce_add(&mut self, src: &'ll Value) -> &'ll Value {
1723 self.call_intrinsic("llvm.vector.reduce.add", &[self.val_ty(src)], &[src])
1724 }
1725 pub(crate) fn vector_reduce_mul(&mut self, src: &'ll Value) -> &'ll Value {
1726 self.call_intrinsic("llvm.vector.reduce.mul", &[self.val_ty(src)], &[src])
1727 }
1728 pub(crate) fn vector_reduce_and(&mut self, src: &'ll Value) -> &'ll Value {
1729 self.call_intrinsic("llvm.vector.reduce.and", &[self.val_ty(src)], &[src])
1730 }
1731 pub(crate) fn vector_reduce_or(&mut self, src: &'ll Value) -> &'ll Value {
1732 self.call_intrinsic("llvm.vector.reduce.or", &[self.val_ty(src)], &[src])
1733 }
1734 pub(crate) fn vector_reduce_xor(&mut self, src: &'ll Value) -> &'ll Value {
1735 self.call_intrinsic("llvm.vector.reduce.xor", &[self.val_ty(src)], &[src])
1736 }
1737 pub(crate) fn vector_reduce_min(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1738 self.call_intrinsic(
1739 if is_signed { "llvm.vector.reduce.smin" } else { "llvm.vector.reduce.umin" },
1740 &[self.val_ty(src)],
1741 &[src],
1742 )
1743 }
1744 pub(crate) fn vector_reduce_max(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1745 self.call_intrinsic(
1746 if is_signed { "llvm.vector.reduce.smax" } else { "llvm.vector.reduce.umax" },
1747 &[self.val_ty(src)],
1748 &[src],
1749 )
1750 }
1751}
1752impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1753 pub(crate) fn add_clause(&mut self, landing_pad: &'ll Value, clause: &'ll Value) {
1754 unsafe {
1755 llvm::LLVMAddClause(landing_pad, clause);
1756 }
1757 }
1758
1759 pub(crate) fn catch_ret(
1760 &mut self,
1761 funclet: &Funclet<'ll>,
1762 unwind: &'ll BasicBlock,
1763 ) -> &'ll Value {
1764 let ret = unsafe { llvm::LLVMBuildCatchRet(self.llbuilder, funclet.cleanuppad(), unwind) };
1765 ret.expect("LLVM does not have support for catchret")
1766 }
1767
1768 pub(crate) fn check_call<'b>(
1769 &mut self,
1770 typ: &str,
1771 fn_ty: &'ll Type,
1772 llfn: &'ll Value,
1773 args: &'b [&'ll Value],
1774 ) -> Cow<'b, [&'ll Value]> {
1775 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!(
1776 self.cx.type_kind(fn_ty) == TypeKind::Function,
1777 "builder::{typ} not passed a function, but {fn_ty:?}"
1778 );
1779
1780 let param_tys = self.cx.func_params_types(fn_ty);
1781
1782 let all_args_match = iter::zip(¶m_tys, args.iter().map(|&v| self.cx.val_ty(v)))
1783 .all(|(expected_ty, actual_ty)| *expected_ty == actual_ty);
1784
1785 if all_args_match {
1786 return Cow::Borrowed(args);
1787 }
1788
1789 let casted_args: Vec<_> = iter::zip(param_tys, args)
1790 .enumerate()
1791 .map(|(i, (expected_ty, &actual_val))| {
1792 let actual_ty = self.cx.val_ty(actual_val);
1793 if expected_ty != actual_ty {
1794 {
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:1794",
"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(1794u32),
::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!(
1795 "type mismatch in function call of {:?}. \
1796 Expected {:?} for param {}, got {:?}; injecting bitcast",
1797 llfn, expected_ty, i, actual_ty
1798 );
1799 self.bitcast(actual_val, expected_ty)
1800 } else {
1801 actual_val
1802 }
1803 })
1804 .collect();
1805
1806 Cow::Owned(casted_args)
1807 }
1808
1809 pub(crate) fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
1810 unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) }
1811 }
1812}
1813
1814impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1815 pub(crate) fn call_intrinsic(
1816 &mut self,
1817 base_name: impl Into<Cow<'static, str>>,
1818 type_params: &[&'ll Type],
1819 args: &[&'ll Value],
1820 ) -> &'ll Value {
1821 let (ty, f) = self.cx.get_intrinsic(base_name.into(), type_params);
1822 self.call(ty, None, None, f, args, None, None)
1823 }
1824
1825 fn call_lifetime_intrinsic(&mut self, intrinsic: &'static str, ptr: &'ll Value, size: Size) {
1826 let size = size.bytes();
1827 if size == 0 {
1828 return;
1829 }
1830
1831 if !self.cx().sess().emit_lifetime_markers() {
1832 return;
1833 }
1834
1835 if crate::llvm_util::get_version() >= (22, 0, 0) {
1836 let ptr = unsafe { llvm::LLVMRustStripPointerCasts(ptr) };
1839 self.call_intrinsic(intrinsic, &[self.val_ty(ptr)], &[ptr]);
1840 } else {
1841 self.call_intrinsic(intrinsic, &[self.val_ty(ptr)], &[self.cx.const_u64(size), ptr]);
1842 }
1843 }
1844}
1845impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1846 pub(crate) fn phi(
1847 &mut self,
1848 ty: &'ll Type,
1849 vals: &[&'ll Value],
1850 bbs: &[&'ll BasicBlock],
1851 ) -> &'ll Value {
1852 {
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());
1853 let phi = unsafe { llvm::LLVMBuildPhi(self.llbuilder, ty, UNNAMED) };
1854 unsafe {
1855 llvm::LLVMAddIncoming(phi, vals.as_ptr(), bbs.as_ptr(), vals.len() as c_uint);
1856 phi
1857 }
1858 }
1859
1860 fn add_incoming_to_phi(&mut self, phi: &'ll Value, val: &'ll Value, bb: &'ll BasicBlock) {
1861 unsafe {
1862 llvm::LLVMAddIncoming(phi, &val, &bb, 1 as c_uint);
1863 }
1864 }
1865}
1866impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1867 pub(crate) fn landing_pad(
1868 &mut self,
1869 ty: &'ll Type,
1870 pers_fn: &'ll Value,
1871 num_clauses: usize,
1872 ) -> &'ll Value {
1873 self.set_personality_fn(pers_fn);
1877 unsafe {
1878 llvm::LLVMBuildLandingPad(self.llbuilder, ty, None, num_clauses as c_uint, UNNAMED)
1879 }
1880 }
1881
1882 pub(crate) fn callbr(
1883 &mut self,
1884 llty: &'ll Type,
1885 fn_attrs: Option<&CodegenFnAttrs>,
1886 fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1887 llfn: &'ll Value,
1888 args: &[&'ll Value],
1889 default_dest: &'ll BasicBlock,
1890 indirect_dest: &[&'ll BasicBlock],
1891 funclet: Option<&Funclet<'ll>>,
1892 instance: Option<Instance<'tcx>>,
1893 ) -> &'ll Value {
1894 {
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:1894",
"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(1894u32),
::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);
1895
1896 let args = self.check_call("callbr", llty, llfn, args);
1897 let funclet_bundle = funclet.map(|funclet| funclet.bundle());
1898 let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
1899 if let Some(funclet_bundle) = funclet_bundle {
1900 bundles.push(funclet_bundle);
1901 }
1902
1903 self.cfi_type_test(fn_attrs, fn_abi, instance, llfn);
1905
1906 let kcfi_bundle = self.kcfi_operand_bundle(fn_attrs, fn_abi, instance, llfn);
1908 if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|b| b.as_ref()) {
1909 bundles.push(kcfi_bundle);
1910 }
1911
1912 let pauth = self.ptrauth_operand_bundle(llfn, fn_abi);
1913 if let Some(p) = pauth.as_ref().map(|b| b.as_ref()) {
1914 bundles.push(p);
1915 }
1916
1917 let callbr = unsafe {
1918 llvm::LLVMBuildCallBr(
1919 self.llbuilder,
1920 llty,
1921 llfn,
1922 default_dest,
1923 indirect_dest.as_ptr(),
1924 indirect_dest.len() as c_uint,
1925 args.as_ptr(),
1926 args.len() as c_uint,
1927 bundles.as_ptr(),
1928 bundles.len() as c_uint,
1929 UNNAMED,
1930 )
1931 };
1932 if let Some(fn_abi) = fn_abi {
1933 fn_abi.apply_attrs_callsite(self, callbr);
1934 }
1935 callbr
1936 }
1937
1938 fn cfi_type_test(
1940 &mut self,
1941 fn_attrs: Option<&CodegenFnAttrs>,
1942 fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1943 instance: Option<Instance<'tcx>>,
1944 llfn: &'ll Value,
1945 ) {
1946 let is_indirect_call = unsafe { llvm::LLVMRustIsNonGVFunctionPointerTy(llfn) };
1947 if self.tcx.sess.is_sanitizer_cfi_enabled()
1948 && let Some(fn_abi) = fn_abi
1949 && is_indirect_call
1950 {
1951 if let Some(fn_attrs) = fn_attrs
1952 && fn_attrs.sanitizers.disabled.contains(SanitizerSet::CFI)
1953 {
1954 return;
1955 }
1956
1957 let mut options = cfi::TypeIdOptions::empty();
1958 if self.tcx.sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1959 options.insert(cfi::TypeIdOptions::GENERALIZE_POINTERS);
1960 }
1961 if self.tcx.sess.is_sanitizer_cfi_normalize_integers_enabled() {
1962 options.insert(cfi::TypeIdOptions::NORMALIZE_INTEGERS);
1963 }
1964
1965 let typeid = if let Some(instance) = instance {
1966 cfi::typeid_for_instance(self.tcx, instance, options)
1967 } else {
1968 cfi::typeid_for_fnabi(self.tcx, fn_abi, options)
1969 };
1970 let typeid_metadata = self.cx.create_metadata(typeid.as_bytes());
1971 let dbg_loc = self.get_dbg_loc();
1972
1973 let typeid = self.get_metadata_value(typeid_metadata);
1977 let cond = self.call_intrinsic("llvm.type.test", &[], &[llfn, typeid]);
1978 let bb_pass = self.append_sibling_block("type_test.pass");
1979 let bb_fail = self.append_sibling_block("type_test.fail");
1980 self.cond_br(cond, bb_pass, bb_fail);
1981
1982 self.switch_to_block(bb_fail);
1983 if let Some(dbg_loc) = dbg_loc {
1984 self.set_dbg_loc(dbg_loc);
1985 }
1986 self.abort();
1987 self.unreachable();
1988
1989 self.switch_to_block(bb_pass);
1990 if let Some(dbg_loc) = dbg_loc {
1991 self.set_dbg_loc(dbg_loc);
1992 }
1993 }
1994 }
1995
1996 fn kcfi_operand_bundle(
1998 &mut self,
1999 fn_attrs: Option<&CodegenFnAttrs>,
2000 fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
2001 instance: Option<Instance<'tcx>>,
2002 llfn: &'ll Value,
2003 ) -> Option<llvm::OperandBundleBox<'ll>> {
2004 let is_indirect_call = unsafe { llvm::LLVMRustIsNonGVFunctionPointerTy(llfn) };
2005 let kcfi_bundle = if self.tcx.sess.is_sanitizer_kcfi_enabled()
2006 && let Some(fn_abi) = fn_abi
2007 && is_indirect_call
2008 {
2009 if let Some(fn_attrs) = fn_attrs
2010 && fn_attrs.sanitizers.disabled.contains(SanitizerSet::KCFI)
2011 {
2012 return None;
2013 }
2014
2015 let mut options = kcfi::TypeIdOptions::empty();
2016 if self.tcx.sess.is_sanitizer_cfi_generalize_pointers_enabled() {
2017 options.insert(kcfi::TypeIdOptions::GENERALIZE_POINTERS);
2018 }
2019 if self.tcx.sess.is_sanitizer_cfi_normalize_integers_enabled() {
2020 options.insert(kcfi::TypeIdOptions::NORMALIZE_INTEGERS);
2021 }
2022
2023 let kcfi_typeid = if let Some(instance) = instance {
2024 kcfi::typeid_for_instance(self.tcx, instance, options)
2025 } else {
2026 kcfi::typeid_for_fnabi(self.tcx, fn_abi, options)
2027 };
2028
2029 Some(llvm::OperandBundleBox::new("kcfi", &[self.const_u32(kcfi_typeid)]))
2030 } else {
2031 None
2032 };
2033 kcfi_bundle
2034 }
2035
2036 fn ptrauth_operand_bundle(
2038 &mut self,
2039 llfn: &'ll Value,
2040 fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
2041 ) -> Option<llvm::OperandBundleBox<'ll>> {
2042 if self.sess().target.llvm_abiname != LlvmAbi::Pauthtest {
2043 return None;
2044 }
2045 if fn_abi?.conv != CanonAbi::C {
2048 return None;
2049 }
2050 if llvm::get_value_name(llfn).starts_with(b"llvm.") {
2052 return None;
2053 }
2054
2055 let key: u32 = 0;
2063 let discriminator: u64 = 0;
2064 Some(llvm::OperandBundleBox::new(
2065 "ptrauth",
2066 &[self.const_u32(key), self.const_u64(discriminator)],
2067 ))
2068 }
2069
2070 #[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(2071u32),
::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))]
2072 pub(crate) fn instrprof_increment(
2073 &mut self,
2074 fn_name: &'ll Value,
2075 hash: &'ll Value,
2076 num_counters: &'ll Value,
2077 index: &'ll Value,
2078 ) {
2079 self.call_intrinsic("llvm.instrprof.increment", &[], &[fn_name, hash, num_counters, index]);
2080 }
2081}