]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/builder.rs
Introduce Bx::switch_to_block
[rust.git] / compiler / rustc_codegen_llvm / src / builder.rs
1 use crate::common::Funclet;
2 use crate::context::CodegenCx;
3 use crate::llvm::{self, BasicBlock, False};
4 use crate::llvm::{AtomicOrdering, AtomicRmwBinOp, SynchronizationScope};
5 use crate::llvm_util;
6 use crate::type_::Type;
7 use crate::type_of::LayoutLlvmExt;
8 use crate::value::Value;
9 use cstr::cstr;
10 use libc::{c_char, c_uint};
11 use rustc_codegen_ssa::common::{IntPredicate, RealPredicate, TypeKind};
12 use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
13 use rustc_codegen_ssa::mir::place::PlaceRef;
14 use rustc_codegen_ssa::traits::*;
15 use rustc_codegen_ssa::MemFlags;
16 use rustc_data_structures::small_c_str::SmallCStr;
17 use rustc_hir::def_id::DefId;
18 use rustc_middle::ty::layout::{
19     FnAbiError, FnAbiOfHelpers, FnAbiRequest, LayoutError, LayoutOfHelpers, TyAndLayout,
20 };
21 use rustc_middle::ty::{self, Ty, TyCtxt};
22 use rustc_span::Span;
23 use rustc_target::abi::{self, call::FnAbi, Align, Size, WrappingRange};
24 use rustc_target::spec::{HasTargetSpec, Target};
25 use std::borrow::Cow;
26 use std::ffi::CStr;
27 use std::iter;
28 use std::ops::Deref;
29 use std::ptr;
30 use tracing::debug;
31
32 // All Builders must have an llfn associated with them
33 #[must_use]
34 pub struct Builder<'a, 'll, 'tcx> {
35     pub llbuilder: &'ll mut llvm::Builder<'ll>,
36     pub cx: &'a CodegenCx<'ll, 'tcx>,
37 }
38
39 impl Drop for Builder<'_, '_, '_> {
40     fn drop(&mut self) {
41         unsafe {
42             llvm::LLVMDisposeBuilder(&mut *(self.llbuilder as *mut _));
43         }
44     }
45 }
46
47 // FIXME(eddyb) use a checked constructor when they become `const fn`.
48 const EMPTY_C_STR: &CStr = unsafe { CStr::from_bytes_with_nul_unchecked(b"\0") };
49
50 /// Empty string, to be used where LLVM expects an instruction name, indicating
51 /// that the instruction is to be left unnamed (i.e. numbered, in textual IR).
52 // FIXME(eddyb) pass `&CStr` directly to FFI once it's a thin pointer.
53 const UNNAMED: *const c_char = EMPTY_C_STR.as_ptr();
54
55 impl<'ll, 'tcx> BackendTypes for Builder<'_, 'll, 'tcx> {
56     type Value = <CodegenCx<'ll, 'tcx> as BackendTypes>::Value;
57     type Function = <CodegenCx<'ll, 'tcx> as BackendTypes>::Function;
58     type BasicBlock = <CodegenCx<'ll, 'tcx> as BackendTypes>::BasicBlock;
59     type Type = <CodegenCx<'ll, 'tcx> as BackendTypes>::Type;
60     type Funclet = <CodegenCx<'ll, 'tcx> as BackendTypes>::Funclet;
61
62     type DIScope = <CodegenCx<'ll, 'tcx> as BackendTypes>::DIScope;
63     type DILocation = <CodegenCx<'ll, 'tcx> as BackendTypes>::DILocation;
64     type DIVariable = <CodegenCx<'ll, 'tcx> as BackendTypes>::DIVariable;
65 }
66
67 impl abi::HasDataLayout for Builder<'_, '_, '_> {
68     fn data_layout(&self) -> &abi::TargetDataLayout {
69         self.cx.data_layout()
70     }
71 }
72
73 impl<'tcx> ty::layout::HasTyCtxt<'tcx> for Builder<'_, '_, 'tcx> {
74     #[inline]
75     fn tcx(&self) -> TyCtxt<'tcx> {
76         self.cx.tcx
77     }
78 }
79
80 impl<'tcx> ty::layout::HasParamEnv<'tcx> for Builder<'_, '_, 'tcx> {
81     fn param_env(&self) -> ty::ParamEnv<'tcx> {
82         self.cx.param_env()
83     }
84 }
85
86 impl HasTargetSpec for Builder<'_, '_, '_> {
87     #[inline]
88     fn target_spec(&self) -> &Target {
89         self.cx.target_spec()
90     }
91 }
92
93 impl<'tcx> LayoutOfHelpers<'tcx> for Builder<'_, '_, 'tcx> {
94     type LayoutOfResult = TyAndLayout<'tcx>;
95
96     #[inline]
97     fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
98         self.cx.handle_layout_err(err, span, ty)
99     }
100 }
101
102 impl<'tcx> FnAbiOfHelpers<'tcx> for Builder<'_, '_, 'tcx> {
103     type FnAbiOfResult = &'tcx FnAbi<'tcx, Ty<'tcx>>;
104
105     #[inline]
106     fn handle_fn_abi_err(
107         &self,
108         err: FnAbiError<'tcx>,
109         span: Span,
110         fn_abi_request: FnAbiRequest<'tcx>,
111     ) -> ! {
112         self.cx.handle_fn_abi_err(err, span, fn_abi_request)
113     }
114 }
115
116 impl<'ll, 'tcx> Deref for Builder<'_, 'll, 'tcx> {
117     type Target = CodegenCx<'ll, 'tcx>;
118
119     #[inline]
120     fn deref(&self) -> &Self::Target {
121         self.cx
122     }
123 }
124
125 impl<'ll, 'tcx> HasCodegen<'tcx> for Builder<'_, 'll, 'tcx> {
126     type CodegenCx = CodegenCx<'ll, 'tcx>;
127 }
128
129 macro_rules! builder_methods_for_value_instructions {
130     ($($name:ident($($arg:ident),*) => $llvm_capi:ident),+ $(,)?) => {
131         $(fn $name(&mut self, $($arg: &'ll Value),*) -> &'ll Value {
132             unsafe {
133                 llvm::$llvm_capi(self.llbuilder, $($arg,)* UNNAMED)
134             }
135         })+
136     }
137 }
138
139 impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> {
140     fn build(cx: &'a CodegenCx<'ll, 'tcx>, llbb: &'ll BasicBlock) -> Self {
141         let bx = Builder::with_cx(cx);
142         unsafe {
143             llvm::LLVMPositionBuilderAtEnd(bx.llbuilder, llbb);
144         }
145         bx
146     }
147
148     fn cx(&self) -> &CodegenCx<'ll, 'tcx> {
149         self.cx
150     }
151
152     fn llbb(&self) -> &'ll BasicBlock {
153         unsafe { llvm::LLVMGetInsertBlock(self.llbuilder) }
154     }
155
156     fn set_span(&mut self, _span: Span) {}
157
158     fn append_block(cx: &'a CodegenCx<'ll, 'tcx>, llfn: &'ll Value, name: &str) -> &'ll BasicBlock {
159         unsafe {
160             let name = SmallCStr::new(name);
161             llvm::LLVMAppendBasicBlockInContext(cx.llcx, llfn, name.as_ptr())
162         }
163     }
164
165     fn append_sibling_block(&mut self, name: &str) -> &'ll BasicBlock {
166         Self::append_block(self.cx, self.llfn(), name)
167     }
168
169     fn switch_to_block(&mut self, llbb: Self::BasicBlock) {
170         *self = Self::build(self.cx, llbb)
171     }
172
173     fn ret_void(&mut self) {
174         unsafe {
175             llvm::LLVMBuildRetVoid(self.llbuilder);
176         }
177     }
178
179     fn ret(&mut self, v: &'ll Value) {
180         unsafe {
181             llvm::LLVMBuildRet(self.llbuilder, v);
182         }
183     }
184
185     fn br(&mut self, dest: &'ll BasicBlock) {
186         unsafe {
187             llvm::LLVMBuildBr(self.llbuilder, dest);
188         }
189     }
190
191     fn cond_br(
192         &mut self,
193         cond: &'ll Value,
194         then_llbb: &'ll BasicBlock,
195         else_llbb: &'ll BasicBlock,
196     ) {
197         unsafe {
198             llvm::LLVMBuildCondBr(self.llbuilder, cond, then_llbb, else_llbb);
199         }
200     }
201
202     fn switch(
203         &mut self,
204         v: &'ll Value,
205         else_llbb: &'ll BasicBlock,
206         cases: impl ExactSizeIterator<Item = (u128, &'ll BasicBlock)>,
207     ) {
208         let switch =
209             unsafe { llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, cases.len() as c_uint) };
210         for (on_val, dest) in cases {
211             let on_val = self.const_uint_big(self.val_ty(v), on_val);
212             unsafe { llvm::LLVMAddCase(switch, on_val, dest) }
213         }
214     }
215
216     fn invoke(
217         &mut self,
218         llty: &'ll Type,
219         llfn: &'ll Value,
220         args: &[&'ll Value],
221         then: &'ll BasicBlock,
222         catch: &'ll BasicBlock,
223         funclet: Option<&Funclet<'ll>>,
224     ) -> &'ll Value {
225         debug!("invoke {:?} with args ({:?})", llfn, args);
226
227         let args = self.check_call("invoke", llty, llfn, args);
228         let bundle = funclet.map(|funclet| funclet.bundle());
229         let bundle = bundle.as_ref().map(|b| &*b.raw);
230
231         unsafe {
232             llvm::LLVMRustBuildInvoke(
233                 self.llbuilder,
234                 llty,
235                 llfn,
236                 args.as_ptr(),
237                 args.len() as c_uint,
238                 then,
239                 catch,
240                 bundle,
241                 UNNAMED,
242             )
243         }
244     }
245
246     fn unreachable(&mut self) {
247         unsafe {
248             llvm::LLVMBuildUnreachable(self.llbuilder);
249         }
250     }
251
252     builder_methods_for_value_instructions! {
253         add(a, b) => LLVMBuildAdd,
254         fadd(a, b) => LLVMBuildFAdd,
255         sub(a, b) => LLVMBuildSub,
256         fsub(a, b) => LLVMBuildFSub,
257         mul(a, b) => LLVMBuildMul,
258         fmul(a, b) => LLVMBuildFMul,
259         udiv(a, b) => LLVMBuildUDiv,
260         exactudiv(a, b) => LLVMBuildExactUDiv,
261         sdiv(a, b) => LLVMBuildSDiv,
262         exactsdiv(a, b) => LLVMBuildExactSDiv,
263         fdiv(a, b) => LLVMBuildFDiv,
264         urem(a, b) => LLVMBuildURem,
265         srem(a, b) => LLVMBuildSRem,
266         frem(a, b) => LLVMBuildFRem,
267         shl(a, b) => LLVMBuildShl,
268         lshr(a, b) => LLVMBuildLShr,
269         ashr(a, b) => LLVMBuildAShr,
270         and(a, b) => LLVMBuildAnd,
271         or(a, b) => LLVMBuildOr,
272         xor(a, b) => LLVMBuildXor,
273         neg(x) => LLVMBuildNeg,
274         fneg(x) => LLVMBuildFNeg,
275         not(x) => LLVMBuildNot,
276         unchecked_sadd(x, y) => LLVMBuildNSWAdd,
277         unchecked_uadd(x, y) => LLVMBuildNUWAdd,
278         unchecked_ssub(x, y) => LLVMBuildNSWSub,
279         unchecked_usub(x, y) => LLVMBuildNUWSub,
280         unchecked_smul(x, y) => LLVMBuildNSWMul,
281         unchecked_umul(x, y) => LLVMBuildNUWMul,
282     }
283
284     fn fadd_fast(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
285         unsafe {
286             let instr = llvm::LLVMBuildFAdd(self.llbuilder, lhs, rhs, UNNAMED);
287             llvm::LLVMRustSetFastMath(instr);
288             instr
289         }
290     }
291
292     fn fsub_fast(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
293         unsafe {
294             let instr = llvm::LLVMBuildFSub(self.llbuilder, lhs, rhs, UNNAMED);
295             llvm::LLVMRustSetFastMath(instr);
296             instr
297         }
298     }
299
300     fn fmul_fast(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
301         unsafe {
302             let instr = llvm::LLVMBuildFMul(self.llbuilder, lhs, rhs, UNNAMED);
303             llvm::LLVMRustSetFastMath(instr);
304             instr
305         }
306     }
307
308     fn fdiv_fast(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
309         unsafe {
310             let instr = llvm::LLVMBuildFDiv(self.llbuilder, lhs, rhs, UNNAMED);
311             llvm::LLVMRustSetFastMath(instr);
312             instr
313         }
314     }
315
316     fn frem_fast(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
317         unsafe {
318             let instr = llvm::LLVMBuildFRem(self.llbuilder, lhs, rhs, UNNAMED);
319             llvm::LLVMRustSetFastMath(instr);
320             instr
321         }
322     }
323
324     fn checked_binop(
325         &mut self,
326         oop: OverflowOp,
327         ty: Ty<'_>,
328         lhs: Self::Value,
329         rhs: Self::Value,
330     ) -> (Self::Value, Self::Value) {
331         use rustc_middle::ty::{Int, Uint};
332         use rustc_middle::ty::{IntTy::*, UintTy::*};
333
334         let new_kind = match ty.kind() {
335             Int(t @ Isize) => Int(t.normalize(self.tcx.sess.target.pointer_width)),
336             Uint(t @ Usize) => Uint(t.normalize(self.tcx.sess.target.pointer_width)),
337             t @ (Uint(_) | Int(_)) => t.clone(),
338             _ => panic!("tried to get overflow intrinsic for op applied to non-int type"),
339         };
340
341         let name = match oop {
342             OverflowOp::Add => match new_kind {
343                 Int(I8) => "llvm.sadd.with.overflow.i8",
344                 Int(I16) => "llvm.sadd.with.overflow.i16",
345                 Int(I32) => "llvm.sadd.with.overflow.i32",
346                 Int(I64) => "llvm.sadd.with.overflow.i64",
347                 Int(I128) => "llvm.sadd.with.overflow.i128",
348
349                 Uint(U8) => "llvm.uadd.with.overflow.i8",
350                 Uint(U16) => "llvm.uadd.with.overflow.i16",
351                 Uint(U32) => "llvm.uadd.with.overflow.i32",
352                 Uint(U64) => "llvm.uadd.with.overflow.i64",
353                 Uint(U128) => "llvm.uadd.with.overflow.i128",
354
355                 _ => unreachable!(),
356             },
357             OverflowOp::Sub => match new_kind {
358                 Int(I8) => "llvm.ssub.with.overflow.i8",
359                 Int(I16) => "llvm.ssub.with.overflow.i16",
360                 Int(I32) => "llvm.ssub.with.overflow.i32",
361                 Int(I64) => "llvm.ssub.with.overflow.i64",
362                 Int(I128) => "llvm.ssub.with.overflow.i128",
363
364                 Uint(U8) => "llvm.usub.with.overflow.i8",
365                 Uint(U16) => "llvm.usub.with.overflow.i16",
366                 Uint(U32) => "llvm.usub.with.overflow.i32",
367                 Uint(U64) => "llvm.usub.with.overflow.i64",
368                 Uint(U128) => "llvm.usub.with.overflow.i128",
369
370                 _ => unreachable!(),
371             },
372             OverflowOp::Mul => match new_kind {
373                 Int(I8) => "llvm.smul.with.overflow.i8",
374                 Int(I16) => "llvm.smul.with.overflow.i16",
375                 Int(I32) => "llvm.smul.with.overflow.i32",
376                 Int(I64) => "llvm.smul.with.overflow.i64",
377                 Int(I128) => "llvm.smul.with.overflow.i128",
378
379                 Uint(U8) => "llvm.umul.with.overflow.i8",
380                 Uint(U16) => "llvm.umul.with.overflow.i16",
381                 Uint(U32) => "llvm.umul.with.overflow.i32",
382                 Uint(U64) => "llvm.umul.with.overflow.i64",
383                 Uint(U128) => "llvm.umul.with.overflow.i128",
384
385                 _ => unreachable!(),
386             },
387         };
388
389         let res = self.call_intrinsic(name, &[lhs, rhs]);
390         (self.extract_value(res, 0), self.extract_value(res, 1))
391     }
392
393     fn from_immediate(&mut self, val: Self::Value) -> Self::Value {
394         if self.cx().val_ty(val) == self.cx().type_i1() {
395             self.zext(val, self.cx().type_i8())
396         } else {
397             val
398         }
399     }
400     fn to_immediate_scalar(&mut self, val: Self::Value, scalar: abi::Scalar) -> Self::Value {
401         if scalar.is_bool() {
402             return self.trunc(val, self.cx().type_i1());
403         }
404         val
405     }
406
407     fn alloca(&mut self, ty: &'ll Type, align: Align) -> &'ll Value {
408         let mut bx = Builder::with_cx(self.cx);
409         bx.position_at_start(unsafe { llvm::LLVMGetFirstBasicBlock(self.llfn()) });
410         bx.dynamic_alloca(ty, align)
411     }
412
413     fn dynamic_alloca(&mut self, ty: &'ll Type, align: Align) -> &'ll Value {
414         unsafe {
415             let alloca = llvm::LLVMBuildAlloca(self.llbuilder, ty, UNNAMED);
416             llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
417             alloca
418         }
419     }
420
421     fn array_alloca(&mut self, ty: &'ll Type, len: &'ll Value, align: Align) -> &'ll Value {
422         unsafe {
423             let alloca = llvm::LLVMBuildArrayAlloca(self.llbuilder, ty, len, UNNAMED);
424             llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
425             alloca
426         }
427     }
428
429     fn load(&mut self, ty: &'ll Type, ptr: &'ll Value, align: Align) -> &'ll Value {
430         unsafe {
431             let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
432             llvm::LLVMSetAlignment(load, align.bytes() as c_uint);
433             load
434         }
435     }
436
437     fn volatile_load(&mut self, ty: &'ll Type, ptr: &'ll Value) -> &'ll Value {
438         unsafe {
439             let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
440             llvm::LLVMSetVolatile(load, llvm::True);
441             load
442         }
443     }
444
445     fn atomic_load(
446         &mut self,
447         ty: &'ll Type,
448         ptr: &'ll Value,
449         order: rustc_codegen_ssa::common::AtomicOrdering,
450         size: Size,
451     ) -> &'ll Value {
452         unsafe {
453             let load = llvm::LLVMRustBuildAtomicLoad(
454                 self.llbuilder,
455                 ty,
456                 ptr,
457                 UNNAMED,
458                 AtomicOrdering::from_generic(order),
459             );
460             // LLVM requires the alignment of atomic loads to be at least the size of the type.
461             llvm::LLVMSetAlignment(load, size.bytes() as c_uint);
462             load
463         }
464     }
465
466     fn load_operand(&mut self, place: PlaceRef<'tcx, &'ll Value>) -> OperandRef<'tcx, &'ll Value> {
467         debug!("PlaceRef::load: {:?}", place);
468
469         assert_eq!(place.llextra.is_some(), place.layout.is_unsized());
470
471         if place.layout.is_zst() {
472             return OperandRef::new_zst(self, place.layout);
473         }
474
475         fn scalar_load_metadata<'a, 'll, 'tcx>(
476             bx: &mut Builder<'a, 'll, 'tcx>,
477             load: &'ll Value,
478             scalar: abi::Scalar,
479         ) {
480             match scalar.value {
481                 abi::Int(..) => {
482                     if !scalar.is_always_valid(bx) {
483                         bx.range_metadata(load, scalar.valid_range);
484                     }
485                 }
486                 abi::Pointer if !scalar.valid_range.contains(0) => {
487                     bx.nonnull_metadata(load);
488                 }
489                 _ => {}
490             }
491         }
492
493         let val = if let Some(llextra) = place.llextra {
494             OperandValue::Ref(place.llval, Some(llextra), place.align)
495         } else if place.layout.is_llvm_immediate() {
496             let mut const_llval = None;
497             unsafe {
498                 if let Some(global) = llvm::LLVMIsAGlobalVariable(place.llval) {
499                     if llvm::LLVMIsGlobalConstant(global) == llvm::True {
500                         const_llval = llvm::LLVMGetInitializer(global);
501                     }
502                 }
503             }
504             let llval = const_llval.unwrap_or_else(|| {
505                 let load = self.load(place.layout.llvm_type(self), place.llval, place.align);
506                 if let abi::Abi::Scalar(scalar) = place.layout.abi {
507                     scalar_load_metadata(self, load, scalar);
508                 }
509                 load
510             });
511             OperandValue::Immediate(self.to_immediate(llval, place.layout))
512         } else if let abi::Abi::ScalarPair(a, b) = place.layout.abi {
513             let b_offset = a.value.size(self).align_to(b.value.align(self).abi);
514             let pair_ty = place.layout.llvm_type(self);
515
516             let mut load = |i, scalar: abi::Scalar, align| {
517                 let llptr = self.struct_gep(pair_ty, place.llval, i as u64);
518                 let llty = place.layout.scalar_pair_element_llvm_type(self, i, false);
519                 let load = self.load(llty, llptr, align);
520                 scalar_load_metadata(self, load, scalar);
521                 self.to_immediate_scalar(load, scalar)
522             };
523
524             OperandValue::Pair(
525                 load(0, a, place.align),
526                 load(1, b, place.align.restrict_for_offset(b_offset)),
527             )
528         } else {
529             OperandValue::Ref(place.llval, None, place.align)
530         };
531
532         OperandRef { val, layout: place.layout }
533     }
534
535     fn write_operand_repeatedly(
536         mut self,
537         cg_elem: OperandRef<'tcx, &'ll Value>,
538         count: u64,
539         dest: PlaceRef<'tcx, &'ll Value>,
540     ) -> Self {
541         let zero = self.const_usize(0);
542         let count = self.const_usize(count);
543         let start = dest.project_index(&mut self, zero).llval;
544         let end = dest.project_index(&mut self, count).llval;
545
546         let header_bb = self.append_sibling_block("repeat_loop_header");
547         let body_bb = self.append_sibling_block("repeat_loop_body");
548         let next_bb = self.append_sibling_block("repeat_loop_next");
549
550         self.br(header_bb);
551
552         let mut header_bx = Self::build(self.cx, header_bb);
553         let current = header_bx.phi(self.val_ty(start), &[start], &[self.llbb()]);
554
555         let keep_going = header_bx.icmp(IntPredicate::IntNE, current, end);
556         header_bx.cond_br(keep_going, body_bb, next_bb);
557
558         let mut body_bx = Self::build(self.cx, body_bb);
559         let align = dest.align.restrict_for_offset(dest.layout.field(self.cx(), 0).size);
560         cg_elem
561             .val
562             .store(&mut body_bx, PlaceRef::new_sized_aligned(current, cg_elem.layout, align));
563
564         let next = body_bx.inbounds_gep(
565             self.backend_type(cg_elem.layout),
566             current,
567             &[self.const_usize(1)],
568         );
569         body_bx.br(header_bb);
570         header_bx.add_incoming_to_phi(current, next, body_bb);
571
572         Self::build(self.cx, next_bb)
573     }
574
575     fn range_metadata(&mut self, load: &'ll Value, range: WrappingRange) {
576         if self.sess().target.arch == "amdgpu" {
577             // amdgpu/LLVM does something weird and thinks an i64 value is
578             // split into a v2i32, halving the bitwidth LLVM expects,
579             // tripping an assertion. So, for now, just disable this
580             // optimization.
581             return;
582         }
583
584         unsafe {
585             let llty = self.cx.val_ty(load);
586             let v = [
587                 self.cx.const_uint_big(llty, range.start),
588                 self.cx.const_uint_big(llty, range.end.wrapping_add(1)),
589             ];
590
591             llvm::LLVMSetMetadata(
592                 load,
593                 llvm::MD_range as c_uint,
594                 llvm::LLVMMDNodeInContext(self.cx.llcx, v.as_ptr(), v.len() as c_uint),
595             );
596         }
597     }
598
599     fn nonnull_metadata(&mut self, load: &'ll Value) {
600         unsafe {
601             llvm::LLVMSetMetadata(
602                 load,
603                 llvm::MD_nonnull as c_uint,
604                 llvm::LLVMMDNodeInContext(self.cx.llcx, ptr::null(), 0),
605             );
606         }
607     }
608
609     fn type_metadata(&mut self, function: &'ll Value, typeid: String) {
610         let typeid_metadata = self.typeid_metadata(typeid);
611         let v = [self.const_usize(0), typeid_metadata];
612         unsafe {
613             llvm::LLVMGlobalSetMetadata(
614                 function,
615                 llvm::MD_type as c_uint,
616                 llvm::LLVMValueAsMetadata(llvm::LLVMMDNodeInContext(
617                     self.cx.llcx,
618                     v.as_ptr(),
619                     v.len() as c_uint,
620                 )),
621             )
622         }
623     }
624
625     fn typeid_metadata(&mut self, typeid: String) -> Self::Value {
626         unsafe {
627             llvm::LLVMMDStringInContext(
628                 self.cx.llcx,
629                 typeid.as_ptr() as *const c_char,
630                 typeid.as_bytes().len() as c_uint,
631             )
632         }
633     }
634
635     fn store(&mut self, val: &'ll Value, ptr: &'ll Value, align: Align) -> &'ll Value {
636         self.store_with_flags(val, ptr, align, MemFlags::empty())
637     }
638
639     fn store_with_flags(
640         &mut self,
641         val: &'ll Value,
642         ptr: &'ll Value,
643         align: Align,
644         flags: MemFlags,
645     ) -> &'ll Value {
646         debug!("Store {:?} -> {:?} ({:?})", val, ptr, flags);
647         let ptr = self.check_store(val, ptr);
648         unsafe {
649             let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
650             let align =
651                 if flags.contains(MemFlags::UNALIGNED) { 1 } else { align.bytes() as c_uint };
652             llvm::LLVMSetAlignment(store, align);
653             if flags.contains(MemFlags::VOLATILE) {
654                 llvm::LLVMSetVolatile(store, llvm::True);
655             }
656             if flags.contains(MemFlags::NONTEMPORAL) {
657                 // According to LLVM [1] building a nontemporal store must
658                 // *always* point to a metadata value of the integer 1.
659                 //
660                 // [1]: https://llvm.org/docs/LangRef.html#store-instruction
661                 let one = self.cx.const_i32(1);
662                 let node = llvm::LLVMMDNodeInContext(self.cx.llcx, &one, 1);
663                 llvm::LLVMSetMetadata(store, llvm::MD_nontemporal as c_uint, node);
664             }
665             store
666         }
667     }
668
669     fn atomic_store(
670         &mut self,
671         val: &'ll Value,
672         ptr: &'ll Value,
673         order: rustc_codegen_ssa::common::AtomicOrdering,
674         size: Size,
675     ) {
676         debug!("Store {:?} -> {:?}", val, ptr);
677         let ptr = self.check_store(val, ptr);
678         unsafe {
679             let store = llvm::LLVMRustBuildAtomicStore(
680                 self.llbuilder,
681                 val,
682                 ptr,
683                 AtomicOrdering::from_generic(order),
684             );
685             // LLVM requires the alignment of atomic stores to be at least the size of the type.
686             llvm::LLVMSetAlignment(store, size.bytes() as c_uint);
687         }
688     }
689
690     fn gep(&mut self, ty: &'ll Type, ptr: &'ll Value, indices: &[&'ll Value]) -> &'ll Value {
691         unsafe {
692             llvm::LLVMBuildGEP2(
693                 self.llbuilder,
694                 ty,
695                 ptr,
696                 indices.as_ptr(),
697                 indices.len() as c_uint,
698                 UNNAMED,
699             )
700         }
701     }
702
703     fn inbounds_gep(
704         &mut self,
705         ty: &'ll Type,
706         ptr: &'ll Value,
707         indices: &[&'ll Value],
708     ) -> &'ll Value {
709         unsafe {
710             llvm::LLVMBuildInBoundsGEP2(
711                 self.llbuilder,
712                 ty,
713                 ptr,
714                 indices.as_ptr(),
715                 indices.len() as c_uint,
716                 UNNAMED,
717             )
718         }
719     }
720
721     fn struct_gep(&mut self, ty: &'ll Type, ptr: &'ll Value, idx: u64) -> &'ll Value {
722         assert_eq!(idx as c_uint as u64, idx);
723         unsafe { llvm::LLVMBuildStructGEP2(self.llbuilder, ty, ptr, idx as c_uint, UNNAMED) }
724     }
725
726     /* Casts */
727     fn trunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
728         unsafe { llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
729     }
730
731     fn sext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
732         unsafe { llvm::LLVMBuildSExt(self.llbuilder, val, dest_ty, UNNAMED) }
733     }
734
735     fn fptoui_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> Option<&'ll Value> {
736         self.fptoint_sat(false, val, dest_ty)
737     }
738
739     fn fptosi_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> Option<&'ll Value> {
740         self.fptoint_sat(true, val, dest_ty)
741     }
742
743     fn fptoui(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
744         // On WebAssembly the `fptoui` and `fptosi` instructions currently have
745         // poor codegen. The reason for this is that the corresponding wasm
746         // instructions, `i32.trunc_f32_s` for example, will trap when the float
747         // is out-of-bounds, infinity, or nan. This means that LLVM
748         // automatically inserts control flow around `fptoui` and `fptosi`
749         // because the LLVM instruction `fptoui` is defined as producing a
750         // poison value, not having UB on out-of-bounds values.
751         //
752         // This method, however, is only used with non-saturating casts that
753         // have UB on out-of-bounds values. This means that it's ok if we use
754         // the raw wasm instruction since out-of-bounds values can do whatever
755         // we like. To ensure that LLVM picks the right instruction we choose
756         // the raw wasm intrinsic functions which avoid LLVM inserting all the
757         // other control flow automatically.
758         if self.sess().target.is_like_wasm {
759             let src_ty = self.cx.val_ty(val);
760             if self.cx.type_kind(src_ty) != TypeKind::Vector {
761                 let float_width = self.cx.float_width(src_ty);
762                 let int_width = self.cx.int_width(dest_ty);
763                 let name = match (int_width, float_width) {
764                     (32, 32) => Some("llvm.wasm.trunc.unsigned.i32.f32"),
765                     (32, 64) => Some("llvm.wasm.trunc.unsigned.i32.f64"),
766                     (64, 32) => Some("llvm.wasm.trunc.unsigned.i64.f32"),
767                     (64, 64) => Some("llvm.wasm.trunc.unsigned.i64.f64"),
768                     _ => None,
769                 };
770                 if let Some(name) = name {
771                     return self.call_intrinsic(name, &[val]);
772                 }
773             }
774         }
775         unsafe { llvm::LLVMBuildFPToUI(self.llbuilder, val, dest_ty, UNNAMED) }
776     }
777
778     fn fptosi(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
779         // see `fptoui` above for why wasm is different here
780         if self.sess().target.is_like_wasm {
781             let src_ty = self.cx.val_ty(val);
782             if self.cx.type_kind(src_ty) != TypeKind::Vector {
783                 let float_width = self.cx.float_width(src_ty);
784                 let int_width = self.cx.int_width(dest_ty);
785                 let name = match (int_width, float_width) {
786                     (32, 32) => Some("llvm.wasm.trunc.signed.i32.f32"),
787                     (32, 64) => Some("llvm.wasm.trunc.signed.i32.f64"),
788                     (64, 32) => Some("llvm.wasm.trunc.signed.i64.f32"),
789                     (64, 64) => Some("llvm.wasm.trunc.signed.i64.f64"),
790                     _ => None,
791                 };
792                 if let Some(name) = name {
793                     return self.call_intrinsic(name, &[val]);
794                 }
795             }
796         }
797         unsafe { llvm::LLVMBuildFPToSI(self.llbuilder, val, dest_ty, UNNAMED) }
798     }
799
800     fn uitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
801         unsafe { llvm::LLVMBuildUIToFP(self.llbuilder, val, dest_ty, UNNAMED) }
802     }
803
804     fn sitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
805         unsafe { llvm::LLVMBuildSIToFP(self.llbuilder, val, dest_ty, UNNAMED) }
806     }
807
808     fn fptrunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
809         unsafe { llvm::LLVMBuildFPTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
810     }
811
812     fn fpext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
813         unsafe { llvm::LLVMBuildFPExt(self.llbuilder, val, dest_ty, UNNAMED) }
814     }
815
816     fn ptrtoint(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
817         unsafe { llvm::LLVMBuildPtrToInt(self.llbuilder, val, dest_ty, UNNAMED) }
818     }
819
820     fn inttoptr(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
821         unsafe { llvm::LLVMBuildIntToPtr(self.llbuilder, val, dest_ty, UNNAMED) }
822     }
823
824     fn bitcast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
825         unsafe { llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty, UNNAMED) }
826     }
827
828     fn intcast(&mut self, val: &'ll Value, dest_ty: &'ll Type, is_signed: bool) -> &'ll Value {
829         unsafe { llvm::LLVMRustBuildIntCast(self.llbuilder, val, dest_ty, is_signed) }
830     }
831
832     fn pointercast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
833         unsafe { llvm::LLVMBuildPointerCast(self.llbuilder, val, dest_ty, UNNAMED) }
834     }
835
836     /* Comparisons */
837     fn icmp(&mut self, op: IntPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
838         let op = llvm::IntPredicate::from_generic(op);
839         unsafe { llvm::LLVMBuildICmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
840     }
841
842     fn fcmp(&mut self, op: RealPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
843         let op = llvm::RealPredicate::from_generic(op);
844         unsafe { llvm::LLVMBuildFCmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
845     }
846
847     /* Miscellaneous instructions */
848     fn memcpy(
849         &mut self,
850         dst: &'ll Value,
851         dst_align: Align,
852         src: &'ll Value,
853         src_align: Align,
854         size: &'ll Value,
855         flags: MemFlags,
856     ) {
857         assert!(!flags.contains(MemFlags::NONTEMPORAL), "non-temporal memcpy not supported");
858         let size = self.intcast(size, self.type_isize(), false);
859         let is_volatile = flags.contains(MemFlags::VOLATILE);
860         let dst = self.pointercast(dst, self.type_i8p());
861         let src = self.pointercast(src, self.type_i8p());
862         unsafe {
863             llvm::LLVMRustBuildMemCpy(
864                 self.llbuilder,
865                 dst,
866                 dst_align.bytes() as c_uint,
867                 src,
868                 src_align.bytes() as c_uint,
869                 size,
870                 is_volatile,
871             );
872         }
873     }
874
875     fn memmove(
876         &mut self,
877         dst: &'ll Value,
878         dst_align: Align,
879         src: &'ll Value,
880         src_align: Align,
881         size: &'ll Value,
882         flags: MemFlags,
883     ) {
884         assert!(!flags.contains(MemFlags::NONTEMPORAL), "non-temporal memmove not supported");
885         let size = self.intcast(size, self.type_isize(), false);
886         let is_volatile = flags.contains(MemFlags::VOLATILE);
887         let dst = self.pointercast(dst, self.type_i8p());
888         let src = self.pointercast(src, self.type_i8p());
889         unsafe {
890             llvm::LLVMRustBuildMemMove(
891                 self.llbuilder,
892                 dst,
893                 dst_align.bytes() as c_uint,
894                 src,
895                 src_align.bytes() as c_uint,
896                 size,
897                 is_volatile,
898             );
899         }
900     }
901
902     fn memset(
903         &mut self,
904         ptr: &'ll Value,
905         fill_byte: &'ll Value,
906         size: &'ll Value,
907         align: Align,
908         flags: MemFlags,
909     ) {
910         let is_volatile = flags.contains(MemFlags::VOLATILE);
911         let ptr = self.pointercast(ptr, self.type_i8p());
912         unsafe {
913             llvm::LLVMRustBuildMemSet(
914                 self.llbuilder,
915                 ptr,
916                 align.bytes() as c_uint,
917                 fill_byte,
918                 size,
919                 is_volatile,
920             );
921         }
922     }
923
924     fn select(
925         &mut self,
926         cond: &'ll Value,
927         then_val: &'ll Value,
928         else_val: &'ll Value,
929     ) -> &'ll Value {
930         unsafe { llvm::LLVMBuildSelect(self.llbuilder, cond, then_val, else_val, UNNAMED) }
931     }
932
933     fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
934         unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) }
935     }
936
937     fn extract_element(&mut self, vec: &'ll Value, idx: &'ll Value) -> &'ll Value {
938         unsafe { llvm::LLVMBuildExtractElement(self.llbuilder, vec, idx, UNNAMED) }
939     }
940
941     fn vector_splat(&mut self, num_elts: usize, elt: &'ll Value) -> &'ll Value {
942         unsafe {
943             let elt_ty = self.cx.val_ty(elt);
944             let undef = llvm::LLVMGetUndef(self.type_vector(elt_ty, num_elts as u64));
945             let vec = self.insert_element(undef, elt, self.cx.const_i32(0));
946             let vec_i32_ty = self.type_vector(self.type_i32(), num_elts as u64);
947             self.shuffle_vector(vec, undef, self.const_null(vec_i32_ty))
948         }
949     }
950
951     fn extract_value(&mut self, agg_val: &'ll Value, idx: u64) -> &'ll Value {
952         assert_eq!(idx as c_uint as u64, idx);
953         unsafe { llvm::LLVMBuildExtractValue(self.llbuilder, agg_val, idx as c_uint, UNNAMED) }
954     }
955
956     fn insert_value(&mut self, agg_val: &'ll Value, elt: &'ll Value, idx: u64) -> &'ll Value {
957         assert_eq!(idx as c_uint as u64, idx);
958         unsafe { llvm::LLVMBuildInsertValue(self.llbuilder, agg_val, elt, idx as c_uint, UNNAMED) }
959     }
960
961     fn set_personality_fn(&mut self, personality: &'ll Value) {
962         unsafe {
963             llvm::LLVMSetPersonalityFn(self.llfn(), personality);
964         }
965     }
966
967     fn cleanup_landing_pad(&mut self, ty: &'ll Type, pers_fn: &'ll Value) -> &'ll Value {
968         let landing_pad = self.landing_pad(ty, pers_fn, 1 /* FIXME should this be 0? */);
969         unsafe {
970             llvm::LLVMSetCleanup(landing_pad, llvm::True);
971         }
972         landing_pad
973     }
974
975     fn resume(&mut self, exn: &'ll Value) {
976         unsafe {
977             llvm::LLVMBuildResume(self.llbuilder, exn);
978         }
979     }
980
981     fn cleanup_pad(&mut self, parent: Option<&'ll Value>, args: &[&'ll Value]) -> Funclet<'ll> {
982         let name = cstr!("cleanuppad");
983         let ret = unsafe {
984             llvm::LLVMRustBuildCleanupPad(
985                 self.llbuilder,
986                 parent,
987                 args.len() as c_uint,
988                 args.as_ptr(),
989                 name.as_ptr(),
990             )
991         };
992         Funclet::new(ret.expect("LLVM does not have support for cleanuppad"))
993     }
994
995     fn cleanup_ret(&mut self, funclet: &Funclet<'ll>, unwind: Option<&'ll BasicBlock>) {
996         unsafe {
997             llvm::LLVMRustBuildCleanupRet(self.llbuilder, funclet.cleanuppad(), unwind)
998                 .expect("LLVM does not have support for cleanupret");
999         }
1000     }
1001
1002     fn catch_pad(&mut self, parent: &'ll Value, args: &[&'ll Value]) -> Funclet<'ll> {
1003         let name = cstr!("catchpad");
1004         let ret = unsafe {
1005             llvm::LLVMRustBuildCatchPad(
1006                 self.llbuilder,
1007                 parent,
1008                 args.len() as c_uint,
1009                 args.as_ptr(),
1010                 name.as_ptr(),
1011             )
1012         };
1013         Funclet::new(ret.expect("LLVM does not have support for catchpad"))
1014     }
1015
1016     fn catch_switch(
1017         &mut self,
1018         parent: Option<&'ll Value>,
1019         unwind: Option<&'ll BasicBlock>,
1020         handlers: &[&'ll BasicBlock],
1021     ) -> &'ll Value {
1022         let name = cstr!("catchswitch");
1023         let ret = unsafe {
1024             llvm::LLVMRustBuildCatchSwitch(
1025                 self.llbuilder,
1026                 parent,
1027                 unwind,
1028                 handlers.len() as c_uint,
1029                 name.as_ptr(),
1030             )
1031         };
1032         let ret = ret.expect("LLVM does not have support for catchswitch");
1033         for handler in handlers {
1034             unsafe {
1035                 llvm::LLVMRustAddHandler(ret, handler);
1036             }
1037         }
1038         ret
1039     }
1040
1041     // Atomic Operations
1042     fn atomic_cmpxchg(
1043         &mut self,
1044         dst: &'ll Value,
1045         cmp: &'ll Value,
1046         src: &'ll Value,
1047         order: rustc_codegen_ssa::common::AtomicOrdering,
1048         failure_order: rustc_codegen_ssa::common::AtomicOrdering,
1049         weak: bool,
1050     ) -> &'ll Value {
1051         let weak = if weak { llvm::True } else { llvm::False };
1052         unsafe {
1053             llvm::LLVMRustBuildAtomicCmpXchg(
1054                 self.llbuilder,
1055                 dst,
1056                 cmp,
1057                 src,
1058                 AtomicOrdering::from_generic(order),
1059                 AtomicOrdering::from_generic(failure_order),
1060                 weak,
1061             )
1062         }
1063     }
1064     fn atomic_rmw(
1065         &mut self,
1066         op: rustc_codegen_ssa::common::AtomicRmwBinOp,
1067         dst: &'ll Value,
1068         src: &'ll Value,
1069         order: rustc_codegen_ssa::common::AtomicOrdering,
1070     ) -> &'ll Value {
1071         unsafe {
1072             llvm::LLVMBuildAtomicRMW(
1073                 self.llbuilder,
1074                 AtomicRmwBinOp::from_generic(op),
1075                 dst,
1076                 src,
1077                 AtomicOrdering::from_generic(order),
1078                 False,
1079             )
1080         }
1081     }
1082
1083     fn atomic_fence(
1084         &mut self,
1085         order: rustc_codegen_ssa::common::AtomicOrdering,
1086         scope: rustc_codegen_ssa::common::SynchronizationScope,
1087     ) {
1088         unsafe {
1089             llvm::LLVMRustBuildAtomicFence(
1090                 self.llbuilder,
1091                 AtomicOrdering::from_generic(order),
1092                 SynchronizationScope::from_generic(scope),
1093             );
1094         }
1095     }
1096
1097     fn set_invariant_load(&mut self, load: &'ll Value) {
1098         unsafe {
1099             llvm::LLVMSetMetadata(
1100                 load,
1101                 llvm::MD_invariant_load as c_uint,
1102                 llvm::LLVMMDNodeInContext(self.cx.llcx, ptr::null(), 0),
1103             );
1104         }
1105     }
1106
1107     fn lifetime_start(&mut self, ptr: &'ll Value, size: Size) {
1108         self.call_lifetime_intrinsic("llvm.lifetime.start.p0i8", ptr, size);
1109     }
1110
1111     fn lifetime_end(&mut self, ptr: &'ll Value, size: Size) {
1112         self.call_lifetime_intrinsic("llvm.lifetime.end.p0i8", ptr, size);
1113     }
1114
1115     fn instrprof_increment(
1116         &mut self,
1117         fn_name: &'ll Value,
1118         hash: &'ll Value,
1119         num_counters: &'ll Value,
1120         index: &'ll Value,
1121     ) {
1122         debug!(
1123             "instrprof_increment() with args ({:?}, {:?}, {:?}, {:?})",
1124             fn_name, hash, num_counters, index
1125         );
1126
1127         let llfn = unsafe { llvm::LLVMRustGetInstrProfIncrementIntrinsic(self.cx().llmod) };
1128         let llty = self.cx.type_func(
1129             &[self.cx.type_i8p(), self.cx.type_i64(), self.cx.type_i32(), self.cx.type_i32()],
1130             self.cx.type_void(),
1131         );
1132         let args = &[fn_name, hash, num_counters, index];
1133         let args = self.check_call("call", llty, llfn, args);
1134
1135         unsafe {
1136             let _ = llvm::LLVMRustBuildCall(
1137                 self.llbuilder,
1138                 llty,
1139                 llfn,
1140                 args.as_ptr() as *const &llvm::Value,
1141                 args.len() as c_uint,
1142                 None,
1143             );
1144         }
1145     }
1146
1147     fn call(
1148         &mut self,
1149         llty: &'ll Type,
1150         llfn: &'ll Value,
1151         args: &[&'ll Value],
1152         funclet: Option<&Funclet<'ll>>,
1153     ) -> &'ll Value {
1154         debug!("call {:?} with args ({:?})", llfn, args);
1155
1156         let args = self.check_call("call", llty, llfn, args);
1157         let bundle = funclet.map(|funclet| funclet.bundle());
1158         let bundle = bundle.as_ref().map(|b| &*b.raw);
1159
1160         unsafe {
1161             llvm::LLVMRustBuildCall(
1162                 self.llbuilder,
1163                 llty,
1164                 llfn,
1165                 args.as_ptr() as *const &llvm::Value,
1166                 args.len() as c_uint,
1167                 bundle,
1168             )
1169         }
1170     }
1171
1172     fn zext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1173         unsafe { llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty, UNNAMED) }
1174     }
1175
1176     fn apply_attrs_to_cleanup_callsite(&mut self, llret: &'ll Value) {
1177         // Cleanup is always the cold path.
1178         llvm::Attribute::Cold.apply_callsite(llvm::AttributePlace::Function, llret);
1179
1180         // In LLVM versions with deferred inlining (currently, system LLVM < 14),
1181         // inlining drop glue can lead to exponential size blowup, see #41696 and #92110.
1182         if !llvm_util::is_rust_llvm() && llvm_util::get_version() < (14, 0, 0) {
1183             llvm::Attribute::NoInline.apply_callsite(llvm::AttributePlace::Function, llret);
1184         }
1185     }
1186 }
1187
1188 impl<'ll> StaticBuilderMethods for Builder<'_, 'll, '_> {
1189     fn get_static(&mut self, def_id: DefId) -> &'ll Value {
1190         // Forward to the `get_static` method of `CodegenCx`
1191         self.cx().get_static(def_id)
1192     }
1193 }
1194
1195 impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1196     fn with_cx(cx: &'a CodegenCx<'ll, 'tcx>) -> Self {
1197         // Create a fresh builder from the crate context.
1198         let llbuilder = unsafe { llvm::LLVMCreateBuilderInContext(cx.llcx) };
1199         Builder { llbuilder, cx }
1200     }
1201
1202     pub fn llfn(&self) -> &'ll Value {
1203         unsafe { llvm::LLVMGetBasicBlockParent(self.llbb()) }
1204     }
1205
1206     fn position_at_start(&mut self, llbb: &'ll BasicBlock) {
1207         unsafe {
1208             llvm::LLVMRustPositionBuilderAtStart(self.llbuilder, llbb);
1209         }
1210     }
1211
1212     pub fn minnum(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1213         unsafe { llvm::LLVMRustBuildMinNum(self.llbuilder, lhs, rhs) }
1214     }
1215
1216     pub fn maxnum(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1217         unsafe { llvm::LLVMRustBuildMaxNum(self.llbuilder, lhs, rhs) }
1218     }
1219
1220     pub fn insert_element(
1221         &mut self,
1222         vec: &'ll Value,
1223         elt: &'ll Value,
1224         idx: &'ll Value,
1225     ) -> &'ll Value {
1226         unsafe { llvm::LLVMBuildInsertElement(self.llbuilder, vec, elt, idx, UNNAMED) }
1227     }
1228
1229     pub fn shuffle_vector(
1230         &mut self,
1231         v1: &'ll Value,
1232         v2: &'ll Value,
1233         mask: &'ll Value,
1234     ) -> &'ll Value {
1235         unsafe { llvm::LLVMBuildShuffleVector(self.llbuilder, v1, v2, mask, UNNAMED) }
1236     }
1237
1238     pub fn vector_reduce_fadd(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1239         unsafe { llvm::LLVMRustBuildVectorReduceFAdd(self.llbuilder, acc, src) }
1240     }
1241     pub fn vector_reduce_fmul(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1242         unsafe { llvm::LLVMRustBuildVectorReduceFMul(self.llbuilder, acc, src) }
1243     }
1244     pub fn vector_reduce_fadd_fast(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1245         unsafe {
1246             let instr = llvm::LLVMRustBuildVectorReduceFAdd(self.llbuilder, acc, src);
1247             llvm::LLVMRustSetFastMath(instr);
1248             instr
1249         }
1250     }
1251     pub fn vector_reduce_fmul_fast(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1252         unsafe {
1253             let instr = llvm::LLVMRustBuildVectorReduceFMul(self.llbuilder, acc, src);
1254             llvm::LLVMRustSetFastMath(instr);
1255             instr
1256         }
1257     }
1258     pub fn vector_reduce_add(&mut self, src: &'ll Value) -> &'ll Value {
1259         unsafe { llvm::LLVMRustBuildVectorReduceAdd(self.llbuilder, src) }
1260     }
1261     pub fn vector_reduce_mul(&mut self, src: &'ll Value) -> &'ll Value {
1262         unsafe { llvm::LLVMRustBuildVectorReduceMul(self.llbuilder, src) }
1263     }
1264     pub fn vector_reduce_and(&mut self, src: &'ll Value) -> &'ll Value {
1265         unsafe { llvm::LLVMRustBuildVectorReduceAnd(self.llbuilder, src) }
1266     }
1267     pub fn vector_reduce_or(&mut self, src: &'ll Value) -> &'ll Value {
1268         unsafe { llvm::LLVMRustBuildVectorReduceOr(self.llbuilder, src) }
1269     }
1270     pub fn vector_reduce_xor(&mut self, src: &'ll Value) -> &'ll Value {
1271         unsafe { llvm::LLVMRustBuildVectorReduceXor(self.llbuilder, src) }
1272     }
1273     pub fn vector_reduce_fmin(&mut self, src: &'ll Value) -> &'ll Value {
1274         unsafe {
1275             llvm::LLVMRustBuildVectorReduceFMin(self.llbuilder, src, /*NoNaNs:*/ false)
1276         }
1277     }
1278     pub fn vector_reduce_fmax(&mut self, src: &'ll Value) -> &'ll Value {
1279         unsafe {
1280             llvm::LLVMRustBuildVectorReduceFMax(self.llbuilder, src, /*NoNaNs:*/ false)
1281         }
1282     }
1283     pub fn vector_reduce_fmin_fast(&mut self, src: &'ll Value) -> &'ll Value {
1284         unsafe {
1285             let instr =
1286                 llvm::LLVMRustBuildVectorReduceFMin(self.llbuilder, src, /*NoNaNs:*/ true);
1287             llvm::LLVMRustSetFastMath(instr);
1288             instr
1289         }
1290     }
1291     pub fn vector_reduce_fmax_fast(&mut self, src: &'ll Value) -> &'ll Value {
1292         unsafe {
1293             let instr =
1294                 llvm::LLVMRustBuildVectorReduceFMax(self.llbuilder, src, /*NoNaNs:*/ true);
1295             llvm::LLVMRustSetFastMath(instr);
1296             instr
1297         }
1298     }
1299     pub fn vector_reduce_min(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1300         unsafe { llvm::LLVMRustBuildVectorReduceMin(self.llbuilder, src, is_signed) }
1301     }
1302     pub fn vector_reduce_max(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1303         unsafe { llvm::LLVMRustBuildVectorReduceMax(self.llbuilder, src, is_signed) }
1304     }
1305
1306     pub fn add_clause(&mut self, landing_pad: &'ll Value, clause: &'ll Value) {
1307         unsafe {
1308             llvm::LLVMAddClause(landing_pad, clause);
1309         }
1310     }
1311
1312     pub fn catch_ret(&mut self, funclet: &Funclet<'ll>, unwind: &'ll BasicBlock) -> &'ll Value {
1313         let ret =
1314             unsafe { llvm::LLVMRustBuildCatchRet(self.llbuilder, funclet.cleanuppad(), unwind) };
1315         ret.expect("LLVM does not have support for catchret")
1316     }
1317
1318     fn check_store(&mut self, val: &'ll Value, ptr: &'ll Value) -> &'ll Value {
1319         let dest_ptr_ty = self.cx.val_ty(ptr);
1320         let stored_ty = self.cx.val_ty(val);
1321         let stored_ptr_ty = self.cx.type_ptr_to(stored_ty);
1322
1323         assert_eq!(self.cx.type_kind(dest_ptr_ty), TypeKind::Pointer);
1324
1325         if dest_ptr_ty == stored_ptr_ty {
1326             ptr
1327         } else {
1328             debug!(
1329                 "type mismatch in store. \
1330                     Expected {:?}, got {:?}; inserting bitcast",
1331                 dest_ptr_ty, stored_ptr_ty
1332             );
1333             self.bitcast(ptr, stored_ptr_ty)
1334         }
1335     }
1336
1337     fn check_call<'b>(
1338         &mut self,
1339         typ: &str,
1340         fn_ty: &'ll Type,
1341         llfn: &'ll Value,
1342         args: &'b [&'ll Value],
1343     ) -> Cow<'b, [&'ll Value]> {
1344         assert!(
1345             self.cx.type_kind(fn_ty) == TypeKind::Function,
1346             "builder::{} not passed a function, but {:?}",
1347             typ,
1348             fn_ty
1349         );
1350
1351         let param_tys = self.cx.func_params_types(fn_ty);
1352
1353         let all_args_match = iter::zip(&param_tys, args.iter().map(|&v| self.val_ty(v)))
1354             .all(|(expected_ty, actual_ty)| *expected_ty == actual_ty);
1355
1356         if all_args_match {
1357             return Cow::Borrowed(args);
1358         }
1359
1360         let casted_args: Vec<_> = iter::zip(param_tys, args)
1361             .enumerate()
1362             .map(|(i, (expected_ty, &actual_val))| {
1363                 let actual_ty = self.val_ty(actual_val);
1364                 if expected_ty != actual_ty {
1365                     debug!(
1366                         "type mismatch in function call of {:?}. \
1367                             Expected {:?} for param {}, got {:?}; injecting bitcast",
1368                         llfn, expected_ty, i, actual_ty
1369                     );
1370                     self.bitcast(actual_val, expected_ty)
1371                 } else {
1372                     actual_val
1373                 }
1374             })
1375             .collect();
1376
1377         Cow::Owned(casted_args)
1378     }
1379
1380     pub fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
1381         unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) }
1382     }
1383
1384     crate fn call_intrinsic(&mut self, intrinsic: &str, args: &[&'ll Value]) -> &'ll Value {
1385         let (ty, f) = self.cx.get_intrinsic(intrinsic);
1386         self.call(ty, f, args, None)
1387     }
1388
1389     fn call_lifetime_intrinsic(&mut self, intrinsic: &str, ptr: &'ll Value, size: Size) {
1390         let size = size.bytes();
1391         if size == 0 {
1392             return;
1393         }
1394
1395         if !self.cx().sess().emit_lifetime_markers() {
1396             return;
1397         }
1398
1399         let ptr = self.pointercast(ptr, self.cx.type_i8p());
1400         self.call_intrinsic(intrinsic, &[self.cx.const_u64(size), ptr]);
1401     }
1402
1403     pub(crate) fn phi(
1404         &mut self,
1405         ty: &'ll Type,
1406         vals: &[&'ll Value],
1407         bbs: &[&'ll BasicBlock],
1408     ) -> &'ll Value {
1409         assert_eq!(vals.len(), bbs.len());
1410         let phi = unsafe { llvm::LLVMBuildPhi(self.llbuilder, ty, UNNAMED) };
1411         unsafe {
1412             llvm::LLVMAddIncoming(phi, vals.as_ptr(), bbs.as_ptr(), vals.len() as c_uint);
1413             phi
1414         }
1415     }
1416
1417     fn add_incoming_to_phi(&mut self, phi: &'ll Value, val: &'ll Value, bb: &'ll BasicBlock) {
1418         unsafe {
1419             llvm::LLVMAddIncoming(phi, &val, &bb, 1 as c_uint);
1420         }
1421     }
1422
1423     fn fptoint_sat_broken_in_llvm(&self) -> bool {
1424         match self.tcx.sess.target.arch.as_str() {
1425             // FIXME - https://bugs.llvm.org/show_bug.cgi?id=50083
1426             "riscv64" => llvm_util::get_version() < (13, 0, 0),
1427             _ => false,
1428         }
1429     }
1430
1431     fn fptoint_sat(
1432         &mut self,
1433         signed: bool,
1434         val: &'ll Value,
1435         dest_ty: &'ll Type,
1436     ) -> Option<&'ll Value> {
1437         if !self.fptoint_sat_broken_in_llvm() {
1438             let src_ty = self.cx.val_ty(val);
1439             let (float_ty, int_ty, vector_length) = if self.cx.type_kind(src_ty) == TypeKind::Vector
1440             {
1441                 assert_eq!(self.cx.vector_length(src_ty), self.cx.vector_length(dest_ty));
1442                 (
1443                     self.cx.element_type(src_ty),
1444                     self.cx.element_type(dest_ty),
1445                     Some(self.cx.vector_length(src_ty)),
1446                 )
1447             } else {
1448                 (src_ty, dest_ty, None)
1449             };
1450             let float_width = self.cx.float_width(float_ty);
1451             let int_width = self.cx.int_width(int_ty);
1452
1453             let instr = if signed { "fptosi" } else { "fptoui" };
1454             let name = if let Some(vector_length) = vector_length {
1455                 format!(
1456                     "llvm.{}.sat.v{}i{}.v{}f{}",
1457                     instr, vector_length, int_width, vector_length, float_width
1458                 )
1459             } else {
1460                 format!("llvm.{}.sat.i{}.f{}", instr, int_width, float_width)
1461             };
1462             let f =
1463                 self.declare_cfn(&name, llvm::UnnamedAddr::No, self.type_func(&[src_ty], dest_ty));
1464             Some(self.call(self.type_func(&[src_ty], dest_ty), f, &[val], None))
1465         } else {
1466             None
1467         }
1468     }
1469
1470     pub(crate) fn landing_pad(
1471         &mut self,
1472         ty: &'ll Type,
1473         pers_fn: &'ll Value,
1474         num_clauses: usize,
1475     ) -> &'ll Value {
1476         // Use LLVMSetPersonalityFn to set the personality. It supports arbitrary Consts while,
1477         // LLVMBuildLandingPad requires the argument to be a Function (as of LLVM 12). The
1478         // personality lives on the parent function anyway.
1479         self.set_personality_fn(pers_fn);
1480         unsafe {
1481             llvm::LLVMBuildLandingPad(self.llbuilder, ty, None, num_clauses as c_uint, UNNAMED)
1482         }
1483     }
1484 }