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