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