]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/builder.rs
Rollup merge of #100092 - compiler-errors:issue-100075, r=oli-obk
[rust.git] / compiler / rustc_codegen_llvm / src / builder.rs
1 use crate::attributes;
2 use crate::common::Funclet;
3 use crate::context::CodegenCx;
4 use crate::llvm::{self, BasicBlock, False};
5 use crate::llvm::{AtomicOrdering, AtomicRmwBinOp, SynchronizationScope};
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, instrument};
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     #[instrument(level = "trace", skip(self))]
467     fn load_operand(&mut self, place: PlaceRef<'tcx, &'ll Value>) -> OperandRef<'tcx, &'ll Value> {
468         assert_eq!(place.llextra.is_some(), place.layout.is_unsized());
469
470         if place.layout.is_zst() {
471             return OperandRef::new_zst(self, place.layout);
472         }
473
474         #[instrument(level = "trace", skip(bx))]
475         fn scalar_load_metadata<'a, 'll, 'tcx>(
476             bx: &mut Builder<'a, 'll, 'tcx>,
477             load: &'ll Value,
478             scalar: abi::Scalar,
479             layout: TyAndLayout<'tcx>,
480             offset: Size,
481         ) {
482             if !scalar.is_always_valid(bx) {
483                 bx.noundef_metadata(load);
484             }
485
486             match scalar.primitive() {
487                 abi::Int(..) => {
488                     if !scalar.is_always_valid(bx) {
489                         bx.range_metadata(load, scalar.valid_range(bx));
490                     }
491                 }
492                 abi::Pointer => {
493                     if !scalar.valid_range(bx).contains(0) {
494                         bx.nonnull_metadata(load);
495                     }
496
497                     if let Some(pointee) = layout.pointee_info_at(bx, offset) {
498                         if let Some(_) = pointee.safe {
499                             bx.align_metadata(load, pointee.align);
500                         }
501                     }
502                 }
503                 abi::F32 | abi::F64 => {}
504             }
505         }
506
507         let val = if let Some(llextra) = place.llextra {
508             OperandValue::Ref(place.llval, Some(llextra), place.align)
509         } else if place.layout.is_llvm_immediate() {
510             let mut const_llval = None;
511             let llty = place.layout.llvm_type(self);
512             unsafe {
513                 if let Some(global) = llvm::LLVMIsAGlobalVariable(place.llval) {
514                     if llvm::LLVMIsGlobalConstant(global) == llvm::True {
515                         if let Some(init) = llvm::LLVMGetInitializer(global) {
516                             if self.val_ty(init) == llty {
517                                 const_llval = Some(init);
518                             }
519                         }
520                     }
521                 }
522             }
523             let llval = const_llval.unwrap_or_else(|| {
524                 let load = self.load(llty, place.llval, place.align);
525                 if let abi::Abi::Scalar(scalar) = place.layout.abi {
526                     scalar_load_metadata(self, load, scalar, place.layout, Size::ZERO);
527                 }
528                 load
529             });
530             OperandValue::Immediate(self.to_immediate(llval, place.layout))
531         } else if let abi::Abi::ScalarPair(a, b) = place.layout.abi {
532             let b_offset = a.size(self).align_to(b.align(self).abi);
533             let pair_ty = place.layout.llvm_type(self);
534
535             let mut load = |i, scalar: abi::Scalar, layout, align, offset| {
536                 let llptr = self.struct_gep(pair_ty, place.llval, i as u64);
537                 let llty = place.layout.scalar_pair_element_llvm_type(self, i, false);
538                 let load = self.load(llty, llptr, align);
539                 scalar_load_metadata(self, load, scalar, layout, offset);
540                 self.to_immediate_scalar(load, scalar)
541             };
542
543             OperandValue::Pair(
544                 load(0, a, place.layout, place.align, Size::ZERO),
545                 load(1, b, place.layout, place.align.restrict_for_offset(b_offset), b_offset),
546             )
547         } else {
548             OperandValue::Ref(place.llval, None, place.align)
549         };
550
551         OperandRef { val, layout: place.layout }
552     }
553
554     fn write_operand_repeatedly(
555         mut self,
556         cg_elem: OperandRef<'tcx, &'ll Value>,
557         count: u64,
558         dest: PlaceRef<'tcx, &'ll Value>,
559     ) -> Self {
560         let zero = self.const_usize(0);
561         let count = self.const_usize(count);
562         let start = dest.project_index(&mut self, zero).llval;
563         let end = dest.project_index(&mut self, count).llval;
564
565         let header_bb = self.append_sibling_block("repeat_loop_header");
566         let body_bb = self.append_sibling_block("repeat_loop_body");
567         let next_bb = self.append_sibling_block("repeat_loop_next");
568
569         self.br(header_bb);
570
571         let mut header_bx = Self::build(self.cx, header_bb);
572         let current = header_bx.phi(self.val_ty(start), &[start], &[self.llbb()]);
573
574         let keep_going = header_bx.icmp(IntPredicate::IntNE, current, end);
575         header_bx.cond_br(keep_going, body_bb, next_bb);
576
577         let mut body_bx = Self::build(self.cx, body_bb);
578         let align = dest.align.restrict_for_offset(dest.layout.field(self.cx(), 0).size);
579         cg_elem
580             .val
581             .store(&mut body_bx, PlaceRef::new_sized_aligned(current, cg_elem.layout, align));
582
583         let next = body_bx.inbounds_gep(
584             self.backend_type(cg_elem.layout),
585             current,
586             &[self.const_usize(1)],
587         );
588         body_bx.br(header_bb);
589         header_bx.add_incoming_to_phi(current, next, body_bb);
590
591         Self::build(self.cx, next_bb)
592     }
593
594     fn range_metadata(&mut self, load: &'ll Value, range: WrappingRange) {
595         if self.sess().target.arch == "amdgpu" {
596             // amdgpu/LLVM does something weird and thinks an i64 value is
597             // split into a v2i32, halving the bitwidth LLVM expects,
598             // tripping an assertion. So, for now, just disable this
599             // optimization.
600             return;
601         }
602
603         unsafe {
604             let llty = self.cx.val_ty(load);
605             let v = [
606                 self.cx.const_uint_big(llty, range.start),
607                 self.cx.const_uint_big(llty, range.end.wrapping_add(1)),
608             ];
609
610             llvm::LLVMSetMetadata(
611                 load,
612                 llvm::MD_range as c_uint,
613                 llvm::LLVMMDNodeInContext(self.cx.llcx, v.as_ptr(), v.len() as c_uint),
614             );
615         }
616     }
617
618     fn nonnull_metadata(&mut self, load: &'ll Value) {
619         unsafe {
620             llvm::LLVMSetMetadata(
621                 load,
622                 llvm::MD_nonnull as c_uint,
623                 llvm::LLVMMDNodeInContext(self.cx.llcx, ptr::null(), 0),
624             );
625         }
626     }
627
628     fn store(&mut self, val: &'ll Value, ptr: &'ll Value, align: Align) -> &'ll Value {
629         self.store_with_flags(val, ptr, align, MemFlags::empty())
630     }
631
632     fn store_with_flags(
633         &mut self,
634         val: &'ll Value,
635         ptr: &'ll Value,
636         align: Align,
637         flags: MemFlags,
638     ) -> &'ll Value {
639         debug!("Store {:?} -> {:?} ({:?})", val, ptr, flags);
640         let ptr = self.check_store(val, ptr);
641         unsafe {
642             let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
643             let align =
644                 if flags.contains(MemFlags::UNALIGNED) { 1 } else { align.bytes() as c_uint };
645             llvm::LLVMSetAlignment(store, align);
646             if flags.contains(MemFlags::VOLATILE) {
647                 llvm::LLVMSetVolatile(store, llvm::True);
648             }
649             if flags.contains(MemFlags::NONTEMPORAL) {
650                 // According to LLVM [1] building a nontemporal store must
651                 // *always* point to a metadata value of the integer 1.
652                 //
653                 // [1]: https://llvm.org/docs/LangRef.html#store-instruction
654                 let one = self.cx.const_i32(1);
655                 let node = llvm::LLVMMDNodeInContext(self.cx.llcx, &one, 1);
656                 llvm::LLVMSetMetadata(store, llvm::MD_nontemporal as c_uint, node);
657             }
658             store
659         }
660     }
661
662     fn atomic_store(
663         &mut self,
664         val: &'ll Value,
665         ptr: &'ll Value,
666         order: rustc_codegen_ssa::common::AtomicOrdering,
667         size: Size,
668     ) {
669         debug!("Store {:?} -> {:?}", val, ptr);
670         let ptr = self.check_store(val, ptr);
671         unsafe {
672             let store = llvm::LLVMRustBuildAtomicStore(
673                 self.llbuilder,
674                 val,
675                 ptr,
676                 AtomicOrdering::from_generic(order),
677             );
678             // LLVM requires the alignment of atomic stores to be at least the size of the type.
679             llvm::LLVMSetAlignment(store, size.bytes() as c_uint);
680         }
681     }
682
683     fn gep(&mut self, ty: &'ll Type, ptr: &'ll Value, indices: &[&'ll Value]) -> &'ll Value {
684         unsafe {
685             llvm::LLVMBuildGEP2(
686                 self.llbuilder,
687                 ty,
688                 ptr,
689                 indices.as_ptr(),
690                 indices.len() as c_uint,
691                 UNNAMED,
692             )
693         }
694     }
695
696     fn inbounds_gep(
697         &mut self,
698         ty: &'ll Type,
699         ptr: &'ll Value,
700         indices: &[&'ll Value],
701     ) -> &'ll Value {
702         unsafe {
703             llvm::LLVMBuildInBoundsGEP2(
704                 self.llbuilder,
705                 ty,
706                 ptr,
707                 indices.as_ptr(),
708                 indices.len() as c_uint,
709                 UNNAMED,
710             )
711         }
712     }
713
714     fn struct_gep(&mut self, ty: &'ll Type, ptr: &'ll Value, idx: u64) -> &'ll Value {
715         assert_eq!(idx as c_uint as u64, idx);
716         unsafe { llvm::LLVMBuildStructGEP2(self.llbuilder, ty, ptr, idx as c_uint, UNNAMED) }
717     }
718
719     /* Casts */
720     fn trunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
721         unsafe { llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
722     }
723
724     fn sext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
725         unsafe { llvm::LLVMBuildSExt(self.llbuilder, val, dest_ty, UNNAMED) }
726     }
727
728     fn fptoui_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> Option<&'ll Value> {
729         self.fptoint_sat(false, val, dest_ty)
730     }
731
732     fn fptosi_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> Option<&'ll Value> {
733         self.fptoint_sat(true, val, dest_ty)
734     }
735
736     fn fptoui(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
737         // On WebAssembly the `fptoui` and `fptosi` instructions currently have
738         // poor codegen. The reason for this is that the corresponding wasm
739         // instructions, `i32.trunc_f32_s` for example, will trap when the float
740         // is out-of-bounds, infinity, or nan. This means that LLVM
741         // automatically inserts control flow around `fptoui` and `fptosi`
742         // because the LLVM instruction `fptoui` is defined as producing a
743         // poison value, not having UB on out-of-bounds values.
744         //
745         // This method, however, is only used with non-saturating casts that
746         // have UB on out-of-bounds values. This means that it's ok if we use
747         // the raw wasm instruction since out-of-bounds values can do whatever
748         // we like. To ensure that LLVM picks the right instruction we choose
749         // the raw wasm intrinsic functions which avoid LLVM inserting all the
750         // other control flow automatically.
751         if self.sess().target.is_like_wasm {
752             let src_ty = self.cx.val_ty(val);
753             if self.cx.type_kind(src_ty) != TypeKind::Vector {
754                 let float_width = self.cx.float_width(src_ty);
755                 let int_width = self.cx.int_width(dest_ty);
756                 let name = match (int_width, float_width) {
757                     (32, 32) => Some("llvm.wasm.trunc.unsigned.i32.f32"),
758                     (32, 64) => Some("llvm.wasm.trunc.unsigned.i32.f64"),
759                     (64, 32) => Some("llvm.wasm.trunc.unsigned.i64.f32"),
760                     (64, 64) => Some("llvm.wasm.trunc.unsigned.i64.f64"),
761                     _ => None,
762                 };
763                 if let Some(name) = name {
764                     return self.call_intrinsic(name, &[val]);
765                 }
766             }
767         }
768         unsafe { llvm::LLVMBuildFPToUI(self.llbuilder, val, dest_ty, UNNAMED) }
769     }
770
771     fn fptosi(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
772         // see `fptoui` above for why wasm is different here
773         if self.sess().target.is_like_wasm {
774             let src_ty = self.cx.val_ty(val);
775             if self.cx.type_kind(src_ty) != TypeKind::Vector {
776                 let float_width = self.cx.float_width(src_ty);
777                 let int_width = self.cx.int_width(dest_ty);
778                 let name = match (int_width, float_width) {
779                     (32, 32) => Some("llvm.wasm.trunc.signed.i32.f32"),
780                     (32, 64) => Some("llvm.wasm.trunc.signed.i32.f64"),
781                     (64, 32) => Some("llvm.wasm.trunc.signed.i64.f32"),
782                     (64, 64) => Some("llvm.wasm.trunc.signed.i64.f64"),
783                     _ => None,
784                 };
785                 if let Some(name) = name {
786                     return self.call_intrinsic(name, &[val]);
787                 }
788             }
789         }
790         unsafe { llvm::LLVMBuildFPToSI(self.llbuilder, val, dest_ty, UNNAMED) }
791     }
792
793     fn uitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
794         unsafe { llvm::LLVMBuildUIToFP(self.llbuilder, val, dest_ty, UNNAMED) }
795     }
796
797     fn sitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
798         unsafe { llvm::LLVMBuildSIToFP(self.llbuilder, val, dest_ty, UNNAMED) }
799     }
800
801     fn fptrunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
802         unsafe { llvm::LLVMBuildFPTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
803     }
804
805     fn fpext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
806         unsafe { llvm::LLVMBuildFPExt(self.llbuilder, val, dest_ty, UNNAMED) }
807     }
808
809     fn ptrtoint(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
810         unsafe { llvm::LLVMBuildPtrToInt(self.llbuilder, val, dest_ty, UNNAMED) }
811     }
812
813     fn inttoptr(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
814         unsafe { llvm::LLVMBuildIntToPtr(self.llbuilder, val, dest_ty, UNNAMED) }
815     }
816
817     fn bitcast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
818         unsafe { llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty, UNNAMED) }
819     }
820
821     fn intcast(&mut self, val: &'ll Value, dest_ty: &'ll Type, is_signed: bool) -> &'ll Value {
822         unsafe { llvm::LLVMRustBuildIntCast(self.llbuilder, val, dest_ty, is_signed) }
823     }
824
825     fn pointercast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
826         unsafe { llvm::LLVMBuildPointerCast(self.llbuilder, val, dest_ty, UNNAMED) }
827     }
828
829     /* Comparisons */
830     fn icmp(&mut self, op: IntPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
831         let op = llvm::IntPredicate::from_generic(op);
832         unsafe { llvm::LLVMBuildICmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
833     }
834
835     fn fcmp(&mut self, op: RealPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
836         let op = llvm::RealPredicate::from_generic(op);
837         unsafe { llvm::LLVMBuildFCmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
838     }
839
840     /* Miscellaneous instructions */
841     fn memcpy(
842         &mut self,
843         dst: &'ll Value,
844         dst_align: Align,
845         src: &'ll Value,
846         src_align: Align,
847         size: &'ll Value,
848         flags: MemFlags,
849     ) {
850         assert!(!flags.contains(MemFlags::NONTEMPORAL), "non-temporal memcpy not supported");
851         let size = self.intcast(size, self.type_isize(), false);
852         let is_volatile = flags.contains(MemFlags::VOLATILE);
853         let dst = self.pointercast(dst, self.type_i8p());
854         let src = self.pointercast(src, self.type_i8p());
855         unsafe {
856             llvm::LLVMRustBuildMemCpy(
857                 self.llbuilder,
858                 dst,
859                 dst_align.bytes() as c_uint,
860                 src,
861                 src_align.bytes() as c_uint,
862                 size,
863                 is_volatile,
864             );
865         }
866     }
867
868     fn memmove(
869         &mut self,
870         dst: &'ll Value,
871         dst_align: Align,
872         src: &'ll Value,
873         src_align: Align,
874         size: &'ll Value,
875         flags: MemFlags,
876     ) {
877         assert!(!flags.contains(MemFlags::NONTEMPORAL), "non-temporal memmove not supported");
878         let size = self.intcast(size, self.type_isize(), false);
879         let is_volatile = flags.contains(MemFlags::VOLATILE);
880         let dst = self.pointercast(dst, self.type_i8p());
881         let src = self.pointercast(src, self.type_i8p());
882         unsafe {
883             llvm::LLVMRustBuildMemMove(
884                 self.llbuilder,
885                 dst,
886                 dst_align.bytes() as c_uint,
887                 src,
888                 src_align.bytes() as c_uint,
889                 size,
890                 is_volatile,
891             );
892         }
893     }
894
895     fn memset(
896         &mut self,
897         ptr: &'ll Value,
898         fill_byte: &'ll Value,
899         size: &'ll Value,
900         align: Align,
901         flags: MemFlags,
902     ) {
903         let is_volatile = flags.contains(MemFlags::VOLATILE);
904         let ptr = self.pointercast(ptr, self.type_i8p());
905         unsafe {
906             llvm::LLVMRustBuildMemSet(
907                 self.llbuilder,
908                 ptr,
909                 align.bytes() as c_uint,
910                 fill_byte,
911                 size,
912                 is_volatile,
913             );
914         }
915     }
916
917     fn select(
918         &mut self,
919         cond: &'ll Value,
920         then_val: &'ll Value,
921         else_val: &'ll Value,
922     ) -> &'ll Value {
923         unsafe { llvm::LLVMBuildSelect(self.llbuilder, cond, then_val, else_val, UNNAMED) }
924     }
925
926     fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
927         unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) }
928     }
929
930     fn extract_element(&mut self, vec: &'ll Value, idx: &'ll Value) -> &'ll Value {
931         unsafe { llvm::LLVMBuildExtractElement(self.llbuilder, vec, idx, UNNAMED) }
932     }
933
934     fn vector_splat(&mut self, num_elts: usize, elt: &'ll Value) -> &'ll Value {
935         unsafe {
936             let elt_ty = self.cx.val_ty(elt);
937             let undef = llvm::LLVMGetUndef(self.type_vector(elt_ty, num_elts as u64));
938             let vec = self.insert_element(undef, elt, self.cx.const_i32(0));
939             let vec_i32_ty = self.type_vector(self.type_i32(), num_elts as u64);
940             self.shuffle_vector(vec, undef, self.const_null(vec_i32_ty))
941         }
942     }
943
944     fn extract_value(&mut self, agg_val: &'ll Value, idx: u64) -> &'ll Value {
945         assert_eq!(idx as c_uint as u64, idx);
946         unsafe { llvm::LLVMBuildExtractValue(self.llbuilder, agg_val, idx as c_uint, UNNAMED) }
947     }
948
949     fn insert_value(&mut self, agg_val: &'ll Value, elt: &'ll Value, idx: u64) -> &'ll Value {
950         assert_eq!(idx as c_uint as u64, idx);
951         unsafe { llvm::LLVMBuildInsertValue(self.llbuilder, agg_val, elt, idx as c_uint, UNNAMED) }
952     }
953
954     fn set_personality_fn(&mut self, personality: &'ll Value) {
955         unsafe {
956             llvm::LLVMSetPersonalityFn(self.llfn(), personality);
957         }
958     }
959
960     fn cleanup_landing_pad(&mut self, ty: &'ll Type, pers_fn: &'ll Value) -> &'ll Value {
961         let landing_pad = self.landing_pad(ty, pers_fn, 1 /* FIXME should this be 0? */);
962         unsafe {
963             llvm::LLVMSetCleanup(landing_pad, llvm::True);
964         }
965         landing_pad
966     }
967
968     fn resume(&mut self, exn: &'ll Value) {
969         unsafe {
970             llvm::LLVMBuildResume(self.llbuilder, exn);
971         }
972     }
973
974     fn cleanup_pad(&mut self, parent: Option<&'ll Value>, args: &[&'ll Value]) -> Funclet<'ll> {
975         let name = cstr!("cleanuppad");
976         let ret = unsafe {
977             llvm::LLVMRustBuildCleanupPad(
978                 self.llbuilder,
979                 parent,
980                 args.len() as c_uint,
981                 args.as_ptr(),
982                 name.as_ptr(),
983             )
984         };
985         Funclet::new(ret.expect("LLVM does not have support for cleanuppad"))
986     }
987
988     fn cleanup_ret(&mut self, funclet: &Funclet<'ll>, unwind: Option<&'ll BasicBlock>) {
989         unsafe {
990             llvm::LLVMRustBuildCleanupRet(self.llbuilder, funclet.cleanuppad(), unwind)
991                 .expect("LLVM does not have support for cleanupret");
992         }
993     }
994
995     fn catch_pad(&mut self, parent: &'ll Value, args: &[&'ll Value]) -> Funclet<'ll> {
996         let name = cstr!("catchpad");
997         let ret = unsafe {
998             llvm::LLVMRustBuildCatchPad(
999                 self.llbuilder,
1000                 parent,
1001                 args.len() as c_uint,
1002                 args.as_ptr(),
1003                 name.as_ptr(),
1004             )
1005         };
1006         Funclet::new(ret.expect("LLVM does not have support for catchpad"))
1007     }
1008
1009     fn catch_switch(
1010         &mut self,
1011         parent: Option<&'ll Value>,
1012         unwind: Option<&'ll BasicBlock>,
1013         handlers: &[&'ll BasicBlock],
1014     ) -> &'ll Value {
1015         let name = cstr!("catchswitch");
1016         let ret = unsafe {
1017             llvm::LLVMRustBuildCatchSwitch(
1018                 self.llbuilder,
1019                 parent,
1020                 unwind,
1021                 handlers.len() as c_uint,
1022                 name.as_ptr(),
1023             )
1024         };
1025         let ret = ret.expect("LLVM does not have support for catchswitch");
1026         for handler in handlers {
1027             unsafe {
1028                 llvm::LLVMRustAddHandler(ret, handler);
1029             }
1030         }
1031         ret
1032     }
1033
1034     // Atomic Operations
1035     fn atomic_cmpxchg(
1036         &mut self,
1037         dst: &'ll Value,
1038         cmp: &'ll Value,
1039         src: &'ll Value,
1040         order: rustc_codegen_ssa::common::AtomicOrdering,
1041         failure_order: rustc_codegen_ssa::common::AtomicOrdering,
1042         weak: bool,
1043     ) -> &'ll Value {
1044         let weak = if weak { llvm::True } else { llvm::False };
1045         unsafe {
1046             llvm::LLVMRustBuildAtomicCmpXchg(
1047                 self.llbuilder,
1048                 dst,
1049                 cmp,
1050                 src,
1051                 AtomicOrdering::from_generic(order),
1052                 AtomicOrdering::from_generic(failure_order),
1053                 weak,
1054             )
1055         }
1056     }
1057     fn atomic_rmw(
1058         &mut self,
1059         op: rustc_codegen_ssa::common::AtomicRmwBinOp,
1060         dst: &'ll Value,
1061         src: &'ll Value,
1062         order: rustc_codegen_ssa::common::AtomicOrdering,
1063     ) -> &'ll Value {
1064         unsafe {
1065             llvm::LLVMBuildAtomicRMW(
1066                 self.llbuilder,
1067                 AtomicRmwBinOp::from_generic(op),
1068                 dst,
1069                 src,
1070                 AtomicOrdering::from_generic(order),
1071                 False,
1072             )
1073         }
1074     }
1075
1076     fn atomic_fence(
1077         &mut self,
1078         order: rustc_codegen_ssa::common::AtomicOrdering,
1079         scope: rustc_codegen_ssa::common::SynchronizationScope,
1080     ) {
1081         unsafe {
1082             llvm::LLVMRustBuildAtomicFence(
1083                 self.llbuilder,
1084                 AtomicOrdering::from_generic(order),
1085                 SynchronizationScope::from_generic(scope),
1086             );
1087         }
1088     }
1089
1090     fn set_invariant_load(&mut self, load: &'ll Value) {
1091         unsafe {
1092             llvm::LLVMSetMetadata(
1093                 load,
1094                 llvm::MD_invariant_load as c_uint,
1095                 llvm::LLVMMDNodeInContext(self.cx.llcx, ptr::null(), 0),
1096             );
1097         }
1098     }
1099
1100     fn lifetime_start(&mut self, ptr: &'ll Value, size: Size) {
1101         self.call_lifetime_intrinsic("llvm.lifetime.start.p0i8", ptr, size);
1102     }
1103
1104     fn lifetime_end(&mut self, ptr: &'ll Value, size: Size) {
1105         self.call_lifetime_intrinsic("llvm.lifetime.end.p0i8", ptr, size);
1106     }
1107
1108     fn instrprof_increment(
1109         &mut self,
1110         fn_name: &'ll Value,
1111         hash: &'ll Value,
1112         num_counters: &'ll Value,
1113         index: &'ll Value,
1114     ) {
1115         debug!(
1116             "instrprof_increment() with args ({:?}, {:?}, {:?}, {:?})",
1117             fn_name, hash, num_counters, index
1118         );
1119
1120         let llfn = unsafe { llvm::LLVMRustGetInstrProfIncrementIntrinsic(self.cx().llmod) };
1121         let llty = self.cx.type_func(
1122             &[self.cx.type_i8p(), self.cx.type_i64(), self.cx.type_i32(), self.cx.type_i32()],
1123             self.cx.type_void(),
1124         );
1125         let args = &[fn_name, hash, num_counters, index];
1126         let args = self.check_call("call", llty, llfn, args);
1127
1128         unsafe {
1129             let _ = llvm::LLVMRustBuildCall(
1130                 self.llbuilder,
1131                 llty,
1132                 llfn,
1133                 args.as_ptr() as *const &llvm::Value,
1134                 args.len() as c_uint,
1135                 None,
1136             );
1137         }
1138     }
1139
1140     fn call(
1141         &mut self,
1142         llty: &'ll Type,
1143         llfn: &'ll Value,
1144         args: &[&'ll Value],
1145         funclet: Option<&Funclet<'ll>>,
1146     ) -> &'ll Value {
1147         debug!("call {:?} with args ({:?})", llfn, args);
1148
1149         let args = self.check_call("call", llty, llfn, args);
1150         let bundle = funclet.map(|funclet| funclet.bundle());
1151         let bundle = bundle.as_ref().map(|b| &*b.raw);
1152
1153         unsafe {
1154             llvm::LLVMRustBuildCall(
1155                 self.llbuilder,
1156                 llty,
1157                 llfn,
1158                 args.as_ptr() as *const &llvm::Value,
1159                 args.len() as c_uint,
1160                 bundle,
1161             )
1162         }
1163     }
1164
1165     fn zext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1166         unsafe { llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty, UNNAMED) }
1167     }
1168
1169     fn do_not_inline(&mut self, llret: &'ll Value) {
1170         let noinline = llvm::AttributeKind::NoInline.create_attr(self.llcx);
1171         attributes::apply_to_callsite(llret, llvm::AttributePlace::Function, &[noinline]);
1172     }
1173 }
1174
1175 impl<'ll> StaticBuilderMethods for Builder<'_, 'll, '_> {
1176     fn get_static(&mut self, def_id: DefId) -> &'ll Value {
1177         // Forward to the `get_static` method of `CodegenCx`
1178         self.cx().get_static(def_id)
1179     }
1180 }
1181
1182 impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1183     fn with_cx(cx: &'a CodegenCx<'ll, 'tcx>) -> Self {
1184         // Create a fresh builder from the crate context.
1185         let llbuilder = unsafe { llvm::LLVMCreateBuilderInContext(cx.llcx) };
1186         Builder { llbuilder, cx }
1187     }
1188
1189     pub fn llfn(&self) -> &'ll Value {
1190         unsafe { llvm::LLVMGetBasicBlockParent(self.llbb()) }
1191     }
1192
1193     fn position_at_start(&mut self, llbb: &'ll BasicBlock) {
1194         unsafe {
1195             llvm::LLVMRustPositionBuilderAtStart(self.llbuilder, llbb);
1196         }
1197     }
1198
1199     fn align_metadata(&mut self, load: &'ll Value, align: Align) {
1200         unsafe {
1201             let v = [self.cx.const_u64(align.bytes())];
1202
1203             llvm::LLVMSetMetadata(
1204                 load,
1205                 llvm::MD_align as c_uint,
1206                 llvm::LLVMMDNodeInContext(self.cx.llcx, v.as_ptr(), v.len() as c_uint),
1207             );
1208         }
1209     }
1210
1211     fn noundef_metadata(&mut self, load: &'ll Value) {
1212         unsafe {
1213             llvm::LLVMSetMetadata(
1214                 load,
1215                 llvm::MD_noundef as c_uint,
1216                 llvm::LLVMMDNodeInContext(self.cx.llcx, ptr::null(), 0),
1217             );
1218         }
1219     }
1220
1221     pub fn minnum(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1222         unsafe { llvm::LLVMRustBuildMinNum(self.llbuilder, lhs, rhs) }
1223     }
1224
1225     pub fn maxnum(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1226         unsafe { llvm::LLVMRustBuildMaxNum(self.llbuilder, lhs, rhs) }
1227     }
1228
1229     pub fn insert_element(
1230         &mut self,
1231         vec: &'ll Value,
1232         elt: &'ll Value,
1233         idx: &'ll Value,
1234     ) -> &'ll Value {
1235         unsafe { llvm::LLVMBuildInsertElement(self.llbuilder, vec, elt, idx, UNNAMED) }
1236     }
1237
1238     pub fn shuffle_vector(
1239         &mut self,
1240         v1: &'ll Value,
1241         v2: &'ll Value,
1242         mask: &'ll Value,
1243     ) -> &'ll Value {
1244         unsafe { llvm::LLVMBuildShuffleVector(self.llbuilder, v1, v2, mask, UNNAMED) }
1245     }
1246
1247     pub fn vector_reduce_fadd(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1248         unsafe { llvm::LLVMRustBuildVectorReduceFAdd(self.llbuilder, acc, src) }
1249     }
1250     pub fn vector_reduce_fmul(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1251         unsafe { llvm::LLVMRustBuildVectorReduceFMul(self.llbuilder, acc, src) }
1252     }
1253     pub fn vector_reduce_fadd_fast(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1254         unsafe {
1255             let instr = llvm::LLVMRustBuildVectorReduceFAdd(self.llbuilder, acc, src);
1256             llvm::LLVMRustSetFastMath(instr);
1257             instr
1258         }
1259     }
1260     pub fn vector_reduce_fmul_fast(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1261         unsafe {
1262             let instr = llvm::LLVMRustBuildVectorReduceFMul(self.llbuilder, acc, src);
1263             llvm::LLVMRustSetFastMath(instr);
1264             instr
1265         }
1266     }
1267     pub fn vector_reduce_add(&mut self, src: &'ll Value) -> &'ll Value {
1268         unsafe { llvm::LLVMRustBuildVectorReduceAdd(self.llbuilder, src) }
1269     }
1270     pub fn vector_reduce_mul(&mut self, src: &'ll Value) -> &'ll Value {
1271         unsafe { llvm::LLVMRustBuildVectorReduceMul(self.llbuilder, src) }
1272     }
1273     pub fn vector_reduce_and(&mut self, src: &'ll Value) -> &'ll Value {
1274         unsafe { llvm::LLVMRustBuildVectorReduceAnd(self.llbuilder, src) }
1275     }
1276     pub fn vector_reduce_or(&mut self, src: &'ll Value) -> &'ll Value {
1277         unsafe { llvm::LLVMRustBuildVectorReduceOr(self.llbuilder, src) }
1278     }
1279     pub fn vector_reduce_xor(&mut self, src: &'ll Value) -> &'ll Value {
1280         unsafe { llvm::LLVMRustBuildVectorReduceXor(self.llbuilder, src) }
1281     }
1282     pub fn vector_reduce_fmin(&mut self, src: &'ll Value) -> &'ll Value {
1283         unsafe {
1284             llvm::LLVMRustBuildVectorReduceFMin(self.llbuilder, src, /*NoNaNs:*/ false)
1285         }
1286     }
1287     pub fn vector_reduce_fmax(&mut self, src: &'ll Value) -> &'ll Value {
1288         unsafe {
1289             llvm::LLVMRustBuildVectorReduceFMax(self.llbuilder, src, /*NoNaNs:*/ false)
1290         }
1291     }
1292     pub fn vector_reduce_fmin_fast(&mut self, src: &'ll Value) -> &'ll Value {
1293         unsafe {
1294             let instr =
1295                 llvm::LLVMRustBuildVectorReduceFMin(self.llbuilder, src, /*NoNaNs:*/ true);
1296             llvm::LLVMRustSetFastMath(instr);
1297             instr
1298         }
1299     }
1300     pub fn vector_reduce_fmax_fast(&mut self, src: &'ll Value) -> &'ll Value {
1301         unsafe {
1302             let instr =
1303                 llvm::LLVMRustBuildVectorReduceFMax(self.llbuilder, src, /*NoNaNs:*/ true);
1304             llvm::LLVMRustSetFastMath(instr);
1305             instr
1306         }
1307     }
1308     pub fn vector_reduce_min(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1309         unsafe { llvm::LLVMRustBuildVectorReduceMin(self.llbuilder, src, is_signed) }
1310     }
1311     pub fn vector_reduce_max(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1312         unsafe { llvm::LLVMRustBuildVectorReduceMax(self.llbuilder, src, is_signed) }
1313     }
1314
1315     pub fn add_clause(&mut self, landing_pad: &'ll Value, clause: &'ll Value) {
1316         unsafe {
1317             llvm::LLVMAddClause(landing_pad, clause);
1318         }
1319     }
1320
1321     pub fn catch_ret(&mut self, funclet: &Funclet<'ll>, unwind: &'ll BasicBlock) -> &'ll Value {
1322         let ret =
1323             unsafe { llvm::LLVMRustBuildCatchRet(self.llbuilder, funclet.cleanuppad(), unwind) };
1324         ret.expect("LLVM does not have support for catchret")
1325     }
1326
1327     fn check_store(&mut self, val: &'ll Value, ptr: &'ll Value) -> &'ll Value {
1328         let dest_ptr_ty = self.cx.val_ty(ptr);
1329         let stored_ty = self.cx.val_ty(val);
1330         let stored_ptr_ty = self.cx.type_ptr_to(stored_ty);
1331
1332         assert_eq!(self.cx.type_kind(dest_ptr_ty), TypeKind::Pointer);
1333
1334         if dest_ptr_ty == stored_ptr_ty {
1335             ptr
1336         } else {
1337             debug!(
1338                 "type mismatch in store. \
1339                     Expected {:?}, got {:?}; inserting bitcast",
1340                 dest_ptr_ty, stored_ptr_ty
1341             );
1342             self.bitcast(ptr, stored_ptr_ty)
1343         }
1344     }
1345
1346     fn check_call<'b>(
1347         &mut self,
1348         typ: &str,
1349         fn_ty: &'ll Type,
1350         llfn: &'ll Value,
1351         args: &'b [&'ll Value],
1352     ) -> Cow<'b, [&'ll Value]> {
1353         assert!(
1354             self.cx.type_kind(fn_ty) == TypeKind::Function,
1355             "builder::{} not passed a function, but {:?}",
1356             typ,
1357             fn_ty
1358         );
1359
1360         let param_tys = self.cx.func_params_types(fn_ty);
1361
1362         let all_args_match = iter::zip(&param_tys, args.iter().map(|&v| self.val_ty(v)))
1363             .all(|(expected_ty, actual_ty)| *expected_ty == actual_ty);
1364
1365         if all_args_match {
1366             return Cow::Borrowed(args);
1367         }
1368
1369         let casted_args: Vec<_> = iter::zip(param_tys, args)
1370             .enumerate()
1371             .map(|(i, (expected_ty, &actual_val))| {
1372                 let actual_ty = self.val_ty(actual_val);
1373                 if expected_ty != actual_ty {
1374                     debug!(
1375                         "type mismatch in function call of {:?}. \
1376                             Expected {:?} for param {}, got {:?}; injecting bitcast",
1377                         llfn, expected_ty, i, actual_ty
1378                     );
1379                     self.bitcast(actual_val, expected_ty)
1380                 } else {
1381                     actual_val
1382                 }
1383             })
1384             .collect();
1385
1386         Cow::Owned(casted_args)
1387     }
1388
1389     pub fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
1390         unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) }
1391     }
1392
1393     pub(crate) fn call_intrinsic(&mut self, intrinsic: &str, args: &[&'ll Value]) -> &'ll Value {
1394         let (ty, f) = self.cx.get_intrinsic(intrinsic);
1395         self.call(ty, f, args, None)
1396     }
1397
1398     fn call_lifetime_intrinsic(&mut self, intrinsic: &str, ptr: &'ll Value, size: Size) {
1399         let size = size.bytes();
1400         if size == 0 {
1401             return;
1402         }
1403
1404         if !self.cx().sess().emit_lifetime_markers() {
1405             return;
1406         }
1407
1408         let ptr = self.pointercast(ptr, self.cx.type_i8p());
1409         self.call_intrinsic(intrinsic, &[self.cx.const_u64(size), ptr]);
1410     }
1411
1412     pub(crate) fn phi(
1413         &mut self,
1414         ty: &'ll Type,
1415         vals: &[&'ll Value],
1416         bbs: &[&'ll BasicBlock],
1417     ) -> &'ll Value {
1418         assert_eq!(vals.len(), bbs.len());
1419         let phi = unsafe { llvm::LLVMBuildPhi(self.llbuilder, ty, UNNAMED) };
1420         unsafe {
1421             llvm::LLVMAddIncoming(phi, vals.as_ptr(), bbs.as_ptr(), vals.len() as c_uint);
1422             phi
1423         }
1424     }
1425
1426     fn add_incoming_to_phi(&mut self, phi: &'ll Value, val: &'ll Value, bb: &'ll BasicBlock) {
1427         unsafe {
1428             llvm::LLVMAddIncoming(phi, &val, &bb, 1 as c_uint);
1429         }
1430     }
1431
1432     fn fptoint_sat(
1433         &mut self,
1434         signed: bool,
1435         val: &'ll Value,
1436         dest_ty: &'ll Type,
1437     ) -> Option<&'ll Value> {
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             assert_eq!(self.cx.vector_length(src_ty), self.cx.vector_length(dest_ty));
1441             (
1442                 self.cx.element_type(src_ty),
1443                 self.cx.element_type(dest_ty),
1444                 Some(self.cx.vector_length(src_ty)),
1445             )
1446         } else {
1447             (src_ty, dest_ty, None)
1448         };
1449         let float_width = self.cx.float_width(float_ty);
1450         let int_width = self.cx.int_width(int_ty);
1451
1452         let instr = if signed { "fptosi" } else { "fptoui" };
1453         let name = if let Some(vector_length) = vector_length {
1454             format!(
1455                 "llvm.{}.sat.v{}i{}.v{}f{}",
1456                 instr, vector_length, int_width, vector_length, float_width
1457             )
1458         } else {
1459             format!("llvm.{}.sat.i{}.f{}", instr, int_width, float_width)
1460         };
1461         let f = self.declare_cfn(&name, llvm::UnnamedAddr::No, self.type_func(&[src_ty], dest_ty));
1462         Some(self.call(self.type_func(&[src_ty], dest_ty), f, &[val], None))
1463     }
1464
1465     pub(crate) fn landing_pad(
1466         &mut self,
1467         ty: &'ll Type,
1468         pers_fn: &'ll Value,
1469         num_clauses: usize,
1470     ) -> &'ll Value {
1471         // Use LLVMSetPersonalityFn to set the personality. It supports arbitrary Consts while,
1472         // LLVMBuildLandingPad requires the argument to be a Function (as of LLVM 12). The
1473         // personality lives on the parent function anyway.
1474         self.set_personality_fn(pers_fn);
1475         unsafe {
1476             llvm::LLVMBuildLandingPad(self.llbuilder, ty, None, num_clauses as c_uint, UNNAMED)
1477         }
1478     }
1479 }