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