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