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