builder.rs 48.8 KB
Newer Older
T
Taiki Endo 已提交
1 2
use crate::common::Funclet;
use crate::context::CodegenCx;
M
Mark Rousskov 已提交
3 4
use crate::llvm::{self, BasicBlock, False};
use crate::llvm::{AtomicOrdering, AtomicRmwBinOp, SynchronizationScope};
T
Taiki Endo 已提交
5 6 7
use crate::type_::Type;
use crate::type_of::LayoutLlvmExt;
use crate::value::Value;
M
Mark Rousskov 已提交
8
use libc::{c_char, c_uint};
9
use rustc_codegen_ssa::base::to_immediate;
M
Mark Rousskov 已提交
10 11
use rustc_codegen_ssa::common::{IntPredicate, RealPredicate, TypeKind};
use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
12
use rustc_codegen_ssa::mir::place::PlaceRef;
M
Mark Rousskov 已提交
13 14 15 16
use rustc_codegen_ssa::traits::*;
use rustc_codegen_ssa::MemFlags;
use rustc_data_structures::const_cstr;
use rustc_data_structures::small_c_str::SmallCStr;
17
use rustc_hir::def_id::DefId;
18
use rustc_middle::ty::layout::TyAndLayout;
M
Mazdak Farrokhzad 已提交
19
use rustc_middle::ty::{self, Ty, TyCtxt};
20
use rustc_span::sym;
21
use rustc_target::abi::{self, Align, Size};
S
Saleem Jaffer 已提交
22
use rustc_target::spec::{HasTargetSpec, Target};
23
use std::borrow::Cow;
24
use std::ffi::CStr;
M
Mark Rousskov 已提交
25
use std::iter::TrustedLen;
B
bjorn3 已提交
26
use std::ops::{Deref, Range};
27
use std::ptr;
B
bishtpawan 已提交
28
use tracing::debug;
29

30 31
// All Builders must have an llfn associated with them
#[must_use]
32
pub struct Builder<'a, 'll, 'tcx> {
33
    pub llbuilder: &'ll mut llvm::Builder<'ll>,
34
    pub cx: &'a CodegenCx<'ll, 'tcx>,
35 36
}

37
impl Drop for Builder<'a, 'll, 'tcx> {
M
Mark-Simulacrum 已提交
38 39
    fn drop(&mut self) {
        unsafe {
40
            llvm::LLVMDisposeBuilder(&mut *(self.llbuilder as *mut _));
M
Mark-Simulacrum 已提交
41 42 43 44
        }
    }
}

45
// FIXME(eddyb) use a checked constructor when they become `const fn`.
M
Mark Rousskov 已提交
46
const EMPTY_C_STR: &CStr = unsafe { CStr::from_bytes_with_nul_unchecked(b"\0") };
47 48 49 50 51

/// Empty string, to be used where LLVM expects an instruction name, indicating
/// that the instruction is to be left unnamed (i.e. numbered, in textual IR).
// FIXME(eddyb) pass `&CStr` directly to FFI once it's a thin pointer.
const UNNAMED: *const c_char = EMPTY_C_STR.as_ptr();
52

53 54
impl BackendTypes for Builder<'_, 'll, 'tcx> {
    type Value = <CodegenCx<'ll, 'tcx> as BackendTypes>::Value;
B
bjorn3 已提交
55
    type Function = <CodegenCx<'ll, 'tcx> as BackendTypes>::Function;
56 57
    type BasicBlock = <CodegenCx<'ll, 'tcx> as BackendTypes>::BasicBlock;
    type Type = <CodegenCx<'ll, 'tcx> as BackendTypes>::Type;
58
    type Funclet = <CodegenCx<'ll, 'tcx> as BackendTypes>::Funclet;
59 60

    type DIScope = <CodegenCx<'ll, 'tcx> as BackendTypes>::DIScope;
61
    type DIVariable = <CodegenCx<'ll, 'tcx> as BackendTypes>::DIVariable;
D
Denis Merigoux 已提交
62 63
}

64 65
impl abi::HasDataLayout for Builder<'_, '_, '_> {
    fn data_layout(&self) -> &abi::TargetDataLayout {
D
Denis Merigoux 已提交
66 67 68 69 70
        self.cx.data_layout()
    }
}

impl ty::layout::HasTyCtxt<'tcx> for Builder<'_, '_, 'tcx> {
71
    fn tcx(&self) -> TyCtxt<'tcx> {
D
Denis Merigoux 已提交
72 73 74 75
        self.cx.tcx
    }
}

S
Saleem Jaffer 已提交
76 77 78 79 80 81
impl ty::layout::HasParamEnv<'tcx> for Builder<'_, '_, 'tcx> {
    fn param_env(&self) -> ty::ParamEnv<'tcx> {
        self.cx.param_env()
    }
}

S
Saleem Jaffer 已提交
82 83 84 85 86 87
impl HasTargetSpec for Builder<'_, '_, 'tcx> {
    fn target_spec(&self) -> &Target {
        &self.cx.target_spec()
    }
}

88
impl abi::LayoutOf for Builder<'_, '_, 'tcx> {
D
Denis Merigoux 已提交
89
    type Ty = Ty<'tcx>;
90
    type TyAndLayout = TyAndLayout<'tcx>;
D
Denis Merigoux 已提交
91

92
    fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyAndLayout {
D
Denis Merigoux 已提交
93 94 95 96
        self.cx.layout_of(ty)
    }
}

B
bjorn3 已提交
97 98 99 100 101 102 103
impl Deref for Builder<'_, 'll, 'tcx> {
    type Target = CodegenCx<'ll, 'tcx>;

    fn deref(&self) -> &Self::Target {
        self.cx
    }
}
D
Denis Merigoux 已提交
104 105

impl HasCodegen<'tcx> for Builder<'_, 'll, 'tcx> {
D
Denis Merigoux 已提交
106
    type CodegenCx = CodegenCx<'ll, 'tcx>;
107
}
108

109 110 111 112
macro_rules! builder_methods_for_value_instructions {
    ($($name:ident($($arg:ident),*) => $llvm_capi:ident),+ $(,)?) => {
        $(fn $name(&mut self, $($arg: &'ll Value),*) -> &'ll Value {
            unsafe {
113
                llvm::$llvm_capi(self.llbuilder, $($arg,)* UNNAMED)
114
            }
115
        })+
116 117 118
    }
}

119
impl BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> {
M
Mark Rousskov 已提交
120
    fn new_block<'b>(cx: &'a CodegenCx<'ll, 'tcx>, llfn: &'ll Value, name: &'b str) -> Self {
121
        let mut bx = Builder::with_cx(cx);
122
        let llbb = unsafe {
123
            let name = SmallCStr::new(name);
M
Mark Rousskov 已提交
124
            llvm::LLVMAppendBasicBlockInContext(cx.llcx, llfn, name.as_ptr())
125
        };
126 127
        bx.position_at_end(llbb);
        bx
128 129
    }

130
    fn with_cx(cx: &'a CodegenCx<'ll, 'tcx>) -> Self {
M
Mark-Simulacrum 已提交
131
        // Create a fresh builder from the crate context.
M
Mark Rousskov 已提交
132 133
        let llbuilder = unsafe { llvm::LLVMCreateBuilderInContext(cx.llcx) };
        Builder { llbuilder, cx }
134 135
    }

J
Jeremy Stucki 已提交
136
    fn build_sibling_block(&self, name: &str) -> Self {
137
        Builder::new_block(self.cx, self.llfn(), name)
138 139
    }

140
    fn llbb(&self) -> &'ll BasicBlock {
M
Mark Rousskov 已提交
141
        unsafe { llvm::LLVMGetInsertBlock(self.llbuilder) }
142 143
    }

144
    fn position_at_end(&mut self, llbb: &'ll BasicBlock) {
145 146 147 148 149
        unsafe {
            llvm::LLVMPositionBuilderAtEnd(self.llbuilder, llbb);
        }
    }

150
    fn ret_void(&mut self) {
151 152 153 154 155
        unsafe {
            llvm::LLVMBuildRetVoid(self.llbuilder);
        }
    }

156
    fn ret(&mut self, v: &'ll Value) {
157 158 159 160 161
        unsafe {
            llvm::LLVMBuildRet(self.llbuilder, v);
        }
    }

162
    fn br(&mut self, dest: &'ll BasicBlock) {
163 164 165 166 167
        unsafe {
            llvm::LLVMBuildBr(self.llbuilder, dest);
        }
    }

168
    fn cond_br(
169
        &mut self,
170 171 172
        cond: &'ll Value,
        then_llbb: &'ll BasicBlock,
        else_llbb: &'ll BasicBlock,
173
    ) {
174 175 176 177 178
        unsafe {
            llvm::LLVMBuildCondBr(self.llbuilder, cond, then_llbb, else_llbb);
        }
    }

179
    fn switch(
180
        &mut self,
181 182
        v: &'ll Value,
        else_llbb: &'ll BasicBlock,
183
        cases: impl ExactSizeIterator<Item = (u128, &'ll BasicBlock)> + TrustedLen,
B
bjorn3 已提交
184
    ) {
M
Mark Rousskov 已提交
185 186
        let switch =
            unsafe { llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, cases.len() as c_uint) };
B
bjorn3 已提交
187 188
        for (on_val, dest) in cases {
            let on_val = self.const_uint_big(self.val_ty(v), on_val);
M
Mark Rousskov 已提交
189
            unsafe { llvm::LLVMAddCase(switch, on_val, dest) }
190 191 192
        }
    }

193
    fn invoke(
194
        &mut self,
195 196 197 198 199 200
        llfn: &'ll Value,
        args: &[&'ll Value],
        then: &'ll BasicBlock,
        catch: &'ll BasicBlock,
        funclet: Option<&Funclet<'ll>>,
    ) -> &'ll Value {
M
Mark Rousskov 已提交
201
        debug!("invoke {:?} with args ({:?})", llfn, args);
202

203
        let args = self.check_call("invoke", llfn, args);
204
        let bundle = funclet.map(|funclet| funclet.bundle());
205
        let bundle = bundle.as_ref().map(|b| &*b.raw);
206

207
        unsafe {
M
Mark Rousskov 已提交
208 209 210 211 212 213 214 215 216 217
            llvm::LLVMRustBuildInvoke(
                self.llbuilder,
                llfn,
                args.as_ptr(),
                args.len() as c_uint,
                then,
                catch,
                bundle,
                UNNAMED,
            )
218
        }
219 220
    }

221
    fn unreachable(&mut self) {
222 223 224 225 226
        unsafe {
            llvm::LLVMBuildUnreachable(self.llbuilder);
        }
    }

227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
    builder_methods_for_value_instructions! {
        add(a, b) => LLVMBuildAdd,
        fadd(a, b) => LLVMBuildFAdd,
        sub(a, b) => LLVMBuildSub,
        fsub(a, b) => LLVMBuildFSub,
        mul(a, b) => LLVMBuildMul,
        fmul(a, b) => LLVMBuildFMul,
        udiv(a, b) => LLVMBuildUDiv,
        exactudiv(a, b) => LLVMBuildExactUDiv,
        sdiv(a, b) => LLVMBuildSDiv,
        exactsdiv(a, b) => LLVMBuildExactSDiv,
        fdiv(a, b) => LLVMBuildFDiv,
        urem(a, b) => LLVMBuildURem,
        srem(a, b) => LLVMBuildSRem,
        frem(a, b) => LLVMBuildFRem,
        shl(a, b) => LLVMBuildShl,
        lshr(a, b) => LLVMBuildLShr,
        ashr(a, b) => LLVMBuildAShr,
        and(a, b) => LLVMBuildAnd,
        or(a, b) => LLVMBuildOr,
        xor(a, b) => LLVMBuildXor,
        neg(x) => LLVMBuildNeg,
        fneg(x) => LLVMBuildFNeg,
        not(x) => LLVMBuildNot,
251 252 253 254 255 256
        unchecked_sadd(x, y) => LLVMBuildNSWAdd,
        unchecked_uadd(x, y) => LLVMBuildNUWAdd,
        unchecked_ssub(x, y) => LLVMBuildNSWSub,
        unchecked_usub(x, y) => LLVMBuildNUWSub,
        unchecked_smul(x, y) => LLVMBuildNSWMul,
        unchecked_umul(x, y) => LLVMBuildNUWMul,
257 258
    }

259
    fn fadd_fast(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
260
        unsafe {
261
            let instr = llvm::LLVMBuildFAdd(self.llbuilder, lhs, rhs, UNNAMED);
262 263 264 265 266
            llvm::LLVMRustSetHasUnsafeAlgebra(instr);
            instr
        }
    }

267
    fn fsub_fast(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
268
        unsafe {
269
            let instr = llvm::LLVMBuildFSub(self.llbuilder, lhs, rhs, UNNAMED);
270 271 272 273 274
            llvm::LLVMRustSetHasUnsafeAlgebra(instr);
            instr
        }
    }

275
    fn fmul_fast(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
276
        unsafe {
277
            let instr = llvm::LLVMBuildFMul(self.llbuilder, lhs, rhs, UNNAMED);
278 279 280 281 282
            llvm::LLVMRustSetHasUnsafeAlgebra(instr);
            instr
        }
    }

283
    fn fdiv_fast(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
284
        unsafe {
285
            let instr = llvm::LLVMBuildFDiv(self.llbuilder, lhs, rhs, UNNAMED);
286 287 288 289 290
            llvm::LLVMRustSetHasUnsafeAlgebra(instr);
            instr
        }
    }

291
    fn frem_fast(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
292
        unsafe {
293
            let instr = llvm::LLVMBuildFRem(self.llbuilder, lhs, rhs, UNNAMED);
294 295 296 297 298
            llvm::LLVMRustSetHasUnsafeAlgebra(instr);
            instr
        }
    }

299 300 301
    fn checked_binop(
        &mut self,
        oop: OverflowOp,
302
        ty: Ty<'_>,
303 304 305
        lhs: Self::Value,
        rhs: Self::Value,
    ) -> (Self::Value, Self::Value) {
U
Ujjwal Sharma 已提交
306 307
        use rustc_ast::IntTy::*;
        use rustc_ast::UintTy::*;
M
Mazdak Farrokhzad 已提交
308
        use rustc_middle::ty::{Int, Uint};
309

V
varkor 已提交
310
        let new_kind = match ty.kind {
M
Mark Rousskov 已提交
311 312
            Int(t @ Isize) => Int(t.normalize(self.tcx.sess.target.ptr_width)),
            Uint(t @ Usize) => Uint(t.normalize(self.tcx.sess.target.ptr_width)),
313
            ref t @ (Uint(_) | Int(_)) => t.clone(),
M
Mark Rousskov 已提交
314
            _ => panic!("tried to get overflow intrinsic for op applied to non-int type"),
315 316 317
        };

        let name = match oop {
V
varkor 已提交
318
            OverflowOp::Add => match new_kind {
319 320 321 322 323 324 325 326 327 328 329 330 331 332
                Int(I8) => "llvm.sadd.with.overflow.i8",
                Int(I16) => "llvm.sadd.with.overflow.i16",
                Int(I32) => "llvm.sadd.with.overflow.i32",
                Int(I64) => "llvm.sadd.with.overflow.i64",
                Int(I128) => "llvm.sadd.with.overflow.i128",

                Uint(U8) => "llvm.uadd.with.overflow.i8",
                Uint(U16) => "llvm.uadd.with.overflow.i16",
                Uint(U32) => "llvm.uadd.with.overflow.i32",
                Uint(U64) => "llvm.uadd.with.overflow.i64",
                Uint(U128) => "llvm.uadd.with.overflow.i128",

                _ => unreachable!(),
            },
V
varkor 已提交
333
            OverflowOp::Sub => match new_kind {
334 335 336 337 338 339 340 341 342 343 344 345 346 347
                Int(I8) => "llvm.ssub.with.overflow.i8",
                Int(I16) => "llvm.ssub.with.overflow.i16",
                Int(I32) => "llvm.ssub.with.overflow.i32",
                Int(I64) => "llvm.ssub.with.overflow.i64",
                Int(I128) => "llvm.ssub.with.overflow.i128",

                Uint(U8) => "llvm.usub.with.overflow.i8",
                Uint(U16) => "llvm.usub.with.overflow.i16",
                Uint(U32) => "llvm.usub.with.overflow.i32",
                Uint(U64) => "llvm.usub.with.overflow.i64",
                Uint(U128) => "llvm.usub.with.overflow.i128",

                _ => unreachable!(),
            },
V
varkor 已提交
348
            OverflowOp::Mul => match new_kind {
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
                Int(I8) => "llvm.smul.with.overflow.i8",
                Int(I16) => "llvm.smul.with.overflow.i16",
                Int(I32) => "llvm.smul.with.overflow.i32",
                Int(I64) => "llvm.smul.with.overflow.i64",
                Int(I128) => "llvm.smul.with.overflow.i128",

                Uint(U8) => "llvm.umul.with.overflow.i8",
                Uint(U16) => "llvm.umul.with.overflow.i16",
                Uint(U32) => "llvm.umul.with.overflow.i32",
                Uint(U64) => "llvm.umul.with.overflow.i64",
                Uint(U128) => "llvm.umul.with.overflow.i128",

                _ => unreachable!(),
            },
        };

365
        let intrinsic = self.get_intrinsic(&name);
366
        let res = self.call(intrinsic, &[lhs, rhs], None);
M
Mark Rousskov 已提交
367
        (self.extract_value(res, 0), self.extract_value(res, 1))
368 369
    }

370
    fn alloca(&mut self, ty: &'ll Type, align: Align) -> &'ll Value {
371
        let mut bx = Builder::with_cx(self.cx);
M
Mark Rousskov 已提交
372
        bx.position_at_start(unsafe { llvm::LLVMGetFirstBasicBlock(self.llfn()) });
373
        bx.dynamic_alloca(ty, align)
374 375
    }

376
    fn dynamic_alloca(&mut self, ty: &'ll Type, align: Align) -> &'ll Value {
377
        unsafe {
378
            let alloca = llvm::LLVMBuildAlloca(self.llbuilder, ty, UNNAMED);
379
            llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
380
            alloca
381 382 383
        }
    }

M
Mark Rousskov 已提交
384
    fn array_alloca(&mut self, ty: &'ll Type, len: &'ll Value, align: Align) -> &'ll Value {
M
Masaki Hara 已提交
385
        unsafe {
386
            let alloca = llvm::LLVMBuildArrayAlloca(self.llbuilder, ty, len, UNNAMED);
387
            llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
M
Masaki Hara 已提交
388 389 390 391
            alloca
        }
    }

392
    fn load(&mut self, ptr: &'ll Value, align: Align) -> &'ll Value {
393
        unsafe {
394
            let load = llvm::LLVMBuildLoad(self.llbuilder, ptr, UNNAMED);
395
            llvm::LLVMSetAlignment(load, align.bytes() as c_uint);
396
            load
397 398 399
        }
    }

400
    fn volatile_load(&mut self, ptr: &'ll Value) -> &'ll Value {
401
        unsafe {
402
            let load = llvm::LLVMBuildLoad(self.llbuilder, ptr, UNNAMED);
403 404
            llvm::LLVMSetVolatile(load, llvm::True);
            load
405 406 407
        }
    }

408
    fn atomic_load(
409
        &mut self,
410
        ptr: &'ll Value,
411
        order: rustc_codegen_ssa::common::AtomicOrdering,
412
        size: Size,
413
    ) -> &'ll Value {
414
        unsafe {
415 416 417
            let load = llvm::LLVMRustBuildAtomicLoad(
                self.llbuilder,
                ptr,
418
                UNNAMED,
419 420
                AtomicOrdering::from_generic(order),
            );
421 422
            // LLVM requires the alignment of atomic loads to be at least the size of the type.
            llvm::LLVMSetAlignment(load, size.bytes() as c_uint);
423
            load
424 425 426
        }
    }

M
Mark Rousskov 已提交
427
    fn load_operand(&mut self, place: PlaceRef<'tcx, &'ll Value>) -> OperandRef<'tcx, &'ll Value> {
428 429 430 431 432
        debug!("PlaceRef::load: {:?}", place);

        assert_eq!(place.llextra.is_some(), place.layout.is_unsized());

        if place.layout.is_zst() {
433
            return OperandRef::new_zst(self, place.layout);
434 435
        }

436 437 438
        fn scalar_load_metadata<'a, 'll, 'tcx>(
            bx: &mut Builder<'a, 'll, 'tcx>,
            load: &'ll Value,
439
            scalar: &abi::Scalar,
440
        ) {
441 442
            let vr = scalar.valid_range.clone();
            match scalar.value {
443
                abi::Int(..) => {
444
                    let range = scalar.valid_range_exclusive(bx);
445
                    if range.start != range.end {
446
                        bx.range_metadata(load, range);
447 448
                    }
                }
449
                abi::Pointer if vr.start() < vr.end() && !vr.contains(&0) => {
450
                    bx.nonnull_metadata(load);
451 452 453
                }
                _ => {}
            }
454
        }
455 456 457 458 459 460 461 462 463 464 465 466 467 468

        let val = if let Some(llextra) = place.llextra {
            OperandValue::Ref(place.llval, Some(llextra), place.align)
        } else if place.layout.is_llvm_immediate() {
            let mut const_llval = None;
            unsafe {
                if let Some(global) = llvm::LLVMIsAGlobalVariable(place.llval) {
                    if llvm::LLVMIsGlobalConstant(global) == llvm::True {
                        const_llval = llvm::LLVMGetInitializer(global);
                    }
                }
            }
            let llval = const_llval.unwrap_or_else(|| {
                let load = self.load(place.llval, place.align);
469
                if let abi::Abi::Scalar(ref scalar) = place.layout.abi {
470
                    scalar_load_metadata(self, load, scalar);
471 472 473
                }
                load
            });
474
            OperandValue::Immediate(to_immediate(self, llval, place.layout))
475
        } else if let abi::Abi::ScalarPair(ref a, ref b) = place.layout.abi {
476 477
            let b_offset = a.value.size(self).align_to(b.value.align(self).abi);

478
            let mut load = |i, scalar: &abi::Scalar, align| {
479
                let llptr = self.struct_gep(place.llval, i as u64);
480
                let load = self.load(llptr, align);
481
                scalar_load_metadata(self, load, scalar);
482
                if scalar.is_bool() { self.trunc(load, self.type_i1()) } else { load }
483
            };
484 485 486 487 488

            OperandValue::Pair(
                load(0, a, place.align),
                load(1, b, place.align.restrict_for_offset(b_offset)),
            )
489 490 491 492 493 494 495
        } else {
            OperandValue::Ref(place.llval, None, place.align)
        };

        OperandRef { val, layout: place.layout }
    }

496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
    fn write_operand_repeatedly(
        mut self,
        cg_elem: OperandRef<'tcx, &'ll Value>,
        count: u64,
        dest: PlaceRef<'tcx, &'ll Value>,
    ) -> Self {
        let zero = self.const_usize(0);
        let count = self.const_usize(count);
        let start = dest.project_index(&mut self, zero).llval;
        let end = dest.project_index(&mut self, count).llval;

        let mut header_bx = self.build_sibling_block("repeat_loop_header");
        let mut body_bx = self.build_sibling_block("repeat_loop_body");
        let next_bx = self.build_sibling_block("repeat_loop_next");

        self.br(header_bx.llbb());
        let current = header_bx.phi(self.val_ty(start), &[start], &[self.llbb()]);

        let keep_going = header_bx.icmp(IntPredicate::IntNE, current, end);
        header_bx.cond_br(keep_going, body_bx.llbb(), next_bx.llbb());
516

517
        let align = dest.align.restrict_for_offset(dest.layout.field(self.cx(), 0).size);
M
Mark Rousskov 已提交
518 519 520
        cg_elem
            .val
            .store(&mut body_bx, PlaceRef::new_sized_aligned(current, cg_elem.layout, align));
521 522 523 524 525 526 527

        let next = body_bx.inbounds_gep(current, &[self.const_usize(1)]);
        body_bx.br(header_bx.llbb());
        header_bx.add_incoming_to_phi(current, next, body_bx.llbb());

        next_bx
    }
528

529
    fn range_metadata(&mut self, load: &'ll Value, range: Range<u128>) {
530
        if self.sess().target.target.arch == "amdgpu" {
531 532 533 534 535 536 537
            // amdgpu/LLVM does something weird and thinks a i64 value is
            // split into a v2i32, halving the bitwidth LLVM expects,
            // tripping an assertion. So, for now, just disable this
            // optimization.
            return;
        }

538
        unsafe {
539
            let llty = self.cx.val_ty(load);
540
            let v = [
541
                self.cx.const_uint_big(llty, range.start),
M
Mark Rousskov 已提交
542
                self.cx.const_uint_big(llty, range.end),
543
            ];
544

M
Mark Rousskov 已提交
545 546 547 548 549
            llvm::LLVMSetMetadata(
                load,
                llvm::MD_range as c_uint,
                llvm::LLVMMDNodeInContext(self.cx.llcx, v.as_ptr(), v.len() as c_uint),
            );
550 551 552
        }
    }

553
    fn nonnull_metadata(&mut self, load: &'ll Value) {
554
        unsafe {
M
Mark Rousskov 已提交
555 556 557 558 559
            llvm::LLVMSetMetadata(
                load,
                llvm::MD_nonnull as c_uint,
                llvm::LLVMMDNodeInContext(self.cx.llcx, ptr::null(), 0),
            );
560 561 562
        }
    }

563
    fn store(&mut self, val: &'ll Value, ptr: &'ll Value, align: Align) -> &'ll Value {
564 565 566
        self.store_with_flags(val, ptr, align, MemFlags::empty())
    }

567
    fn store_with_flags(
568
        &mut self,
569 570
        val: &'ll Value,
        ptr: &'ll Value,
571
        align: Align,
572
        flags: MemFlags,
573
    ) -> &'ll Value {
574
        debug!("Store {:?} -> {:?} ({:?})", val, ptr, flags);
575
        let ptr = self.check_store(val, ptr);
576
        unsafe {
577
            let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
M
Mark Rousskov 已提交
578 579
            let align =
                if flags.contains(MemFlags::UNALIGNED) { 1 } else { align.bytes() as c_uint };
580
            llvm::LLVMSetAlignment(store, align);
581 582 583 584 585 586 587 588
            if flags.contains(MemFlags::VOLATILE) {
                llvm::LLVMSetVolatile(store, llvm::True);
            }
            if flags.contains(MemFlags::NONTEMPORAL) {
                // According to LLVM [1] building a nontemporal store must
                // *always* point to a metadata value of the integer 1.
                //
                // [1]: http://llvm.org/docs/LangRef.html#store-instruction
589
                let one = self.cx.const_i32(1);
590 591 592
                let node = llvm::LLVMMDNodeInContext(self.cx.llcx, &one, 1);
                llvm::LLVMSetMetadata(store, llvm::MD_nontemporal as c_uint, node);
            }
593
            store
594 595 596
        }
    }

M
Mark Rousskov 已提交
597 598 599 600 601 602 603
    fn atomic_store(
        &mut self,
        val: &'ll Value,
        ptr: &'ll Value,
        order: rustc_codegen_ssa::common::AtomicOrdering,
        size: Size,
    ) {
604
        debug!("Store {:?} -> {:?}", val, ptr);
605
        let ptr = self.check_store(val, ptr);
606
        unsafe {
607 608 609 610 611 612
            let store = llvm::LLVMRustBuildAtomicStore(
                self.llbuilder,
                val,
                ptr,
                AtomicOrdering::from_generic(order),
            );
613 614
            // LLVM requires the alignment of atomic stores to be at least the size of the type.
            llvm::LLVMSetAlignment(store, size.bytes() as c_uint);
615 616 617
        }
    }

618
    fn gep(&mut self, ptr: &'ll Value, indices: &[&'ll Value]) -> &'ll Value {
619
        unsafe {
M
Mark Rousskov 已提交
620 621 622 623 624 625 626
            llvm::LLVMBuildGEP(
                self.llbuilder,
                ptr,
                indices.as_ptr(),
                indices.len() as c_uint,
                UNNAMED,
            )
627 628 629
        }
    }

630
    fn inbounds_gep(&mut self, ptr: &'ll Value, indices: &[&'ll Value]) -> &'ll Value {
631 632
        unsafe {
            llvm::LLVMBuildInBoundsGEP(
M
Mark Rousskov 已提交
633 634 635 636 637 638
                self.llbuilder,
                ptr,
                indices.as_ptr(),
                indices.len() as c_uint,
                UNNAMED,
            )
639 640 641
        }
    }

B
bjorn3 已提交
642 643
    fn struct_gep(&mut self, ptr: &'ll Value, idx: u64) -> &'ll Value {
        assert_eq!(idx as c_uint as u64, idx);
M
Mark Rousskov 已提交
644
        unsafe { llvm::LLVMBuildStructGEP(self.llbuilder, ptr, idx as c_uint, UNNAMED) }
B
bjorn3 已提交
645 646
    }

647
    /* Casts */
648
    fn trunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
M
Mark Rousskov 已提交
649
        unsafe { llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
650 651
    }

652
    fn sext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
M
Mark Rousskov 已提交
653
        unsafe { llvm::LLVMBuildSExt(self.llbuilder, val, dest_ty, UNNAMED) }
654 655
    }

656
    fn fptoui_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> Option<&'ll Value> {
657 658 659
        // WebAssembly has saturating floating point to integer casts if the
        // `nontrapping-fptoint` target feature is activated. We'll use those if
        // they are available.
660
        if self.sess().target.target.arch == "wasm32"
661
            && self.sess().target_features.contains(&sym::nontrapping_dash_fptoint)
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
        {
            let src_ty = self.cx.val_ty(val);
            let float_width = self.cx.float_width(src_ty);
            let int_width = self.cx.int_width(dest_ty);
            let name = match (int_width, float_width) {
                (32, 32) => Some("llvm.wasm.trunc.saturate.unsigned.i32.f32"),
                (32, 64) => Some("llvm.wasm.trunc.saturate.unsigned.i32.f64"),
                (64, 32) => Some("llvm.wasm.trunc.saturate.unsigned.i64.f32"),
                (64, 64) => Some("llvm.wasm.trunc.saturate.unsigned.i64.f64"),
                _ => None,
            };
            if let Some(name) = name {
                let intrinsic = self.get_intrinsic(name);
                return Some(self.call(intrinsic, &[val], None));
            }
        }
        None
    }

    fn fptosi_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> Option<&'ll Value> {
682 683 684
        // WebAssembly has saturating floating point to integer casts if the
        // `nontrapping-fptoint` target feature is activated. We'll use those if
        // they are available.
685
        if self.sess().target.target.arch == "wasm32"
686
            && self.sess().target_features.contains(&sym::nontrapping_dash_fptoint)
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
        {
            let src_ty = self.cx.val_ty(val);
            let float_width = self.cx.float_width(src_ty);
            let int_width = self.cx.int_width(dest_ty);
            let name = match (int_width, float_width) {
                (32, 32) => Some("llvm.wasm.trunc.saturate.signed.i32.f32"),
                (32, 64) => Some("llvm.wasm.trunc.saturate.signed.i32.f64"),
                (64, 32) => Some("llvm.wasm.trunc.saturate.signed.i64.f32"),
                (64, 64) => Some("llvm.wasm.trunc.saturate.signed.i64.f64"),
                _ => None,
            };
            if let Some(name) = name {
                let intrinsic = self.get_intrinsic(name);
                return Some(self.call(intrinsic, &[val], None));
            }
        }
        None
    }

706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
    fn fptosui_may_trap(&self, val: &'ll Value, dest_ty: &'ll Type) -> bool {
        // Most of the time we'll be generating the `fptosi` or `fptoui`
        // instruction for floating-point-to-integer conversions. These
        // instructions by definition in LLVM do not trap. For the WebAssembly
        // target, however, we'll lower in some cases to intrinsic calls instead
        // which may trap. If we detect that this is a situation where we'll be
        // using the intrinsics then we report that the call map trap, which
        // callers might need to handle.
        if !self.wasm_and_missing_nontrapping_fptoint() {
            return false;
        }
        let src_ty = self.cx.val_ty(val);
        let float_width = self.cx.float_width(src_ty);
        let int_width = self.cx.int_width(dest_ty);
        match (int_width, float_width) {
            (32, 32) | (32, 64) | (64, 32) | (64, 64) => true,
            _ => false,
        }
    }

726
    fn fptoui(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
727 728 729 730
        // When we can, use the native wasm intrinsics which have tighter
        // codegen. Note that this has a semantic difference in that the
        // intrinsic can trap whereas `fptoui` never traps. That difference,
        // however, is handled by `fptosui_may_trap` above.
731 732 733
        //
        // Note that we skip the wasm intrinsics for vector types where `fptoui`
        // must be used instead.
734 735
        if self.wasm_and_missing_nontrapping_fptoint() {
            let src_ty = self.cx.val_ty(val);
736 737 738 739 740 741 742 743 744 745 746 747 748 749
            if self.cx.type_kind(src_ty) != TypeKind::Vector {
                let float_width = self.cx.float_width(src_ty);
                let int_width = self.cx.int_width(dest_ty);
                let name = match (int_width, float_width) {
                    (32, 32) => Some("llvm.wasm.trunc.unsigned.i32.f32"),
                    (32, 64) => Some("llvm.wasm.trunc.unsigned.i32.f64"),
                    (64, 32) => Some("llvm.wasm.trunc.unsigned.i64.f32"),
                    (64, 64) => Some("llvm.wasm.trunc.unsigned.i64.f64"),
                    _ => None,
                };
                if let Some(name) = name {
                    let intrinsic = self.get_intrinsic(name);
                    return self.call(intrinsic, &[val], None);
                }
750 751
            }
        }
M
Mark Rousskov 已提交
752
        unsafe { llvm::LLVMBuildFPToUI(self.llbuilder, val, dest_ty, UNNAMED) }
753 754
    }

755
    fn fptosi(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
756 757
        if self.wasm_and_missing_nontrapping_fptoint() {
            let src_ty = self.cx.val_ty(val);
758 759 760 761 762 763 764 765 766 767 768 769 770 771
            if self.cx.type_kind(src_ty) != TypeKind::Vector {
                let float_width = self.cx.float_width(src_ty);
                let int_width = self.cx.int_width(dest_ty);
                let name = match (int_width, float_width) {
                    (32, 32) => Some("llvm.wasm.trunc.signed.i32.f32"),
                    (32, 64) => Some("llvm.wasm.trunc.signed.i32.f64"),
                    (64, 32) => Some("llvm.wasm.trunc.signed.i64.f32"),
                    (64, 64) => Some("llvm.wasm.trunc.signed.i64.f64"),
                    _ => None,
                };
                if let Some(name) = name {
                    let intrinsic = self.get_intrinsic(name);
                    return self.call(intrinsic, &[val], None);
                }
772 773
            }
        }
M
Mark Rousskov 已提交
774
        unsafe { llvm::LLVMBuildFPToSI(self.llbuilder, val, dest_ty, UNNAMED) }
775 776
    }

777
    fn uitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
M
Mark Rousskov 已提交
778
        unsafe { llvm::LLVMBuildUIToFP(self.llbuilder, val, dest_ty, UNNAMED) }
779 780
    }

781
    fn sitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
M
Mark Rousskov 已提交
782
        unsafe { llvm::LLVMBuildSIToFP(self.llbuilder, val, dest_ty, UNNAMED) }
783 784
    }

785
    fn fptrunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
M
Mark Rousskov 已提交
786
        unsafe { llvm::LLVMBuildFPTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
787 788
    }

789
    fn fpext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
M
Mark Rousskov 已提交
790
        unsafe { llvm::LLVMBuildFPExt(self.llbuilder, val, dest_ty, UNNAMED) }
791 792
    }

793
    fn ptrtoint(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
M
Mark Rousskov 已提交
794
        unsafe { llvm::LLVMBuildPtrToInt(self.llbuilder, val, dest_ty, UNNAMED) }
795 796
    }

797
    fn inttoptr(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
M
Mark Rousskov 已提交
798
        unsafe { llvm::LLVMBuildIntToPtr(self.llbuilder, val, dest_ty, UNNAMED) }
799 800
    }

801
    fn bitcast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
M
Mark Rousskov 已提交
802
        unsafe { llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty, UNNAMED) }
803 804
    }

805
    fn intcast(&mut self, val: &'ll Value, dest_ty: &'ll Type, is_signed: bool) -> &'ll Value {
M
Mark Rousskov 已提交
806
        unsafe { llvm::LLVMRustBuildIntCast(self.llbuilder, val, dest_ty, is_signed) }
807 808
    }

809
    fn pointercast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
M
Mark Rousskov 已提交
810
        unsafe { llvm::LLVMBuildPointerCast(self.llbuilder, val, dest_ty, UNNAMED) }
811 812 813
    }

    /* Comparisons */
814
    fn icmp(&mut self, op: IntPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
815
        let op = llvm::IntPredicate::from_generic(op);
M
Mark Rousskov 已提交
816
        unsafe { llvm::LLVMBuildICmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
817 818
    }

819
    fn fcmp(&mut self, op: RealPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
M
Mark Rousskov 已提交
820
        unsafe { llvm::LLVMBuildFCmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
821 822 823
    }

    /* Miscellaneous instructions */
M
Mark Rousskov 已提交
824 825 826 827 828 829 830 831 832
    fn memcpy(
        &mut self,
        dst: &'ll Value,
        dst_align: Align,
        src: &'ll Value,
        src_align: Align,
        size: &'ll Value,
        flags: MemFlags,
    ) {
833 834 835
        if flags.contains(MemFlags::NONTEMPORAL) {
            // HACK(nox): This is inefficient but there is no nontemporal memcpy.
            let val = self.load(src, src_align);
836
            let ptr = self.pointercast(dst, self.type_ptr_to(self.val_ty(val)));
837 838 839
            self.store_with_flags(val, ptr, dst_align, flags);
            return;
        }
840
        let size = self.intcast(size, self.type_isize(), false);
841
        let is_volatile = flags.contains(MemFlags::VOLATILE);
842 843
        let dst = self.pointercast(dst, self.type_i8p());
        let src = self.pointercast(src, self.type_i8p());
844
        unsafe {
M
Mark Rousskov 已提交
845 846 847 848 849 850 851 852 853
            llvm::LLVMRustBuildMemCpy(
                self.llbuilder,
                dst,
                dst_align.bytes() as c_uint,
                src,
                src_align.bytes() as c_uint,
                size,
                is_volatile,
            );
854 855 856
        }
    }

M
Mark Rousskov 已提交
857 858 859 860 861 862 863 864 865
    fn memmove(
        &mut self,
        dst: &'ll Value,
        dst_align: Align,
        src: &'ll Value,
        src_align: Align,
        size: &'ll Value,
        flags: MemFlags,
    ) {
866 867 868
        if flags.contains(MemFlags::NONTEMPORAL) {
            // HACK(nox): This is inefficient but there is no nontemporal memmove.
            let val = self.load(src, src_align);
869
            let ptr = self.pointercast(dst, self.type_ptr_to(self.val_ty(val)));
870 871 872
            self.store_with_flags(val, ptr, dst_align, flags);
            return;
        }
873
        let size = self.intcast(size, self.type_isize(), false);
874
        let is_volatile = flags.contains(MemFlags::VOLATILE);
875 876
        let dst = self.pointercast(dst, self.type_i8p());
        let src = self.pointercast(src, self.type_i8p());
877
        unsafe {
M
Mark Rousskov 已提交
878 879 880 881 882 883 884 885 886
            llvm::LLVMRustBuildMemMove(
                self.llbuilder,
                dst,
                dst_align.bytes() as c_uint,
                src,
                src_align.bytes() as c_uint,
                size,
                is_volatile,
            );
887 888 889
        }
    }

890
    fn memset(
891
        &mut self,
892 893 894
        ptr: &'ll Value,
        fill_byte: &'ll Value,
        size: &'ll Value,
895
        align: Align,
896 897
        flags: MemFlags,
    ) {
N
Nikita Popov 已提交
898
        let is_volatile = flags.contains(MemFlags::VOLATILE);
899
        let ptr = self.pointercast(ptr, self.type_i8p());
N
Nikita Popov 已提交
900 901 902 903 904 905 906 907 908 909
        unsafe {
            llvm::LLVMRustBuildMemSet(
                self.llbuilder,
                ptr,
                align.bytes() as c_uint,
                fill_byte,
                size,
                is_volatile,
            );
        }
910 911
    }

912
    fn select(
M
Mark Rousskov 已提交
913 914
        &mut self,
        cond: &'ll Value,
915 916 917
        then_val: &'ll Value,
        else_val: &'ll Value,
    ) -> &'ll Value {
M
Mark Rousskov 已提交
918
        unsafe { llvm::LLVMBuildSelect(self.llbuilder, cond, then_val, else_val, UNNAMED) }
919 920
    }

B
bjorn3 已提交
921 922
    #[allow(dead_code)]
    fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
M
Mark Rousskov 已提交
923
        unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) }
B
bjorn3 已提交
924 925
    }

926
    fn extract_element(&mut self, vec: &'ll Value, idx: &'ll Value) -> &'ll Value {
M
Mark Rousskov 已提交
927
        unsafe { llvm::LLVMBuildExtractElement(self.llbuilder, vec, idx, UNNAMED) }
928 929
    }

930
    fn vector_splat(&mut self, num_elts: usize, elt: &'ll Value) -> &'ll Value {
931
        unsafe {
932
            let elt_ty = self.cx.val_ty(elt);
933
            let undef = llvm::LLVMGetUndef(self.type_vector(elt_ty, num_elts as u64));
934
            let vec = self.insert_element(undef, elt, self.cx.const_i32(0));
935 936
            let vec_i32_ty = self.type_vector(self.type_i32(), num_elts as u64);
            self.shuffle_vector(vec, undef, self.const_null(vec_i32_ty))
937 938 939
        }
    }

940
    fn extract_value(&mut self, agg_val: &'ll Value, idx: u64) -> &'ll Value {
941
        assert_eq!(idx as c_uint as u64, idx);
M
Mark Rousskov 已提交
942
        unsafe { llvm::LLVMBuildExtractValue(self.llbuilder, agg_val, idx as c_uint, UNNAMED) }
943 944
    }

M
Mark Rousskov 已提交
945
    fn insert_value(&mut self, agg_val: &'ll Value, elt: &'ll Value, idx: u64) -> &'ll Value {
946
        assert_eq!(idx as c_uint as u64, idx);
M
Mark Rousskov 已提交
947
        unsafe { llvm::LLVMBuildInsertValue(self.llbuilder, agg_val, elt, idx as c_uint, UNNAMED) }
948 949
    }

M
Mark Rousskov 已提交
950 951 952 953 954 955
    fn landing_pad(
        &mut self,
        ty: &'ll Type,
        pers_fn: &'ll Value,
        num_clauses: usize,
    ) -> &'ll Value {
956
        unsafe {
M
Mark Rousskov 已提交
957
            llvm::LLVMBuildLandingPad(self.llbuilder, ty, pers_fn, num_clauses as c_uint, UNNAMED)
958 959 960
        }
    }

961
    fn set_cleanup(&mut self, landing_pad: &'ll Value) {
962
        unsafe {
963
            llvm::LLVMSetCleanup(landing_pad, llvm::True);
964 965 966
        }
    }

967
    fn resume(&mut self, exn: &'ll Value) -> &'ll Value {
M
Mark Rousskov 已提交
968
        unsafe { llvm::LLVMBuildResume(self.llbuilder, exn) }
969 970
    }

M
Mark Rousskov 已提交
971
    fn cleanup_pad(&mut self, parent: Option<&'ll Value>, args: &[&'ll Value]) -> Funclet<'ll> {
972
        let name = const_cstr!("cleanuppad");
973
        let ret = unsafe {
M
Mark Rousskov 已提交
974 975 976 977 978 979 980
            llvm::LLVMRustBuildCleanupPad(
                self.llbuilder,
                parent,
                args.len() as c_uint,
                args.as_ptr(),
                name.as_ptr(),
            )
981
        };
982
        Funclet::new(ret.expect("LLVM does not have support for cleanuppad"))
983 984
    }

985
    fn cleanup_ret(
M
Mark Rousskov 已提交
986 987
        &mut self,
        funclet: &Funclet<'ll>,
988 989
        unwind: Option<&'ll BasicBlock>,
    ) -> &'ll Value {
M
Mark Rousskov 已提交
990 991
        let ret =
            unsafe { llvm::LLVMRustBuildCleanupRet(self.llbuilder, funclet.cleanuppad(), unwind) };
992
        ret.expect("LLVM does not have support for cleanupret")
993 994
    }

M
Mark Rousskov 已提交
995
    fn catch_pad(&mut self, parent: &'ll Value, args: &[&'ll Value]) -> Funclet<'ll> {
996
        let name = const_cstr!("catchpad");
997
        let ret = unsafe {
M
Mark Rousskov 已提交
998 999 1000 1001 1002 1003 1004
            llvm::LLVMRustBuildCatchPad(
                self.llbuilder,
                parent,
                args.len() as c_uint,
                args.as_ptr(),
                name.as_ptr(),
            )
1005
        };
1006
        Funclet::new(ret.expect("LLVM does not have support for catchpad"))
1007 1008
    }

1009
    fn catch_switch(
1010
        &mut self,
1011 1012
        parent: Option<&'ll Value>,
        unwind: Option<&'ll BasicBlock>,
1013
        num_handlers: usize,
1014
    ) -> &'ll Value {
1015
        let name = const_cstr!("catchswitch");
1016
        let ret = unsafe {
M
Mark Rousskov 已提交
1017 1018 1019 1020 1021 1022 1023
            llvm::LLVMRustBuildCatchSwitch(
                self.llbuilder,
                parent,
                unwind,
                num_handlers as c_uint,
                name.as_ptr(),
            )
1024
        };
1025
        ret.expect("LLVM does not have support for catchswitch")
1026 1027
    }

1028
    fn add_handler(&mut self, catch_switch: &'ll Value, handler: &'ll BasicBlock) {
1029 1030 1031 1032 1033
        unsafe {
            llvm::LLVMRustAddHandler(catch_switch, handler);
        }
    }

1034
    fn set_personality_fn(&mut self, personality: &'ll Value) {
1035
        unsafe {
1036
            llvm::LLVMSetPersonalityFn(self.llfn(), personality);
1037 1038 1039
        }
    }

1040
    // Atomic Operations
1041
    fn atomic_cmpxchg(
1042
        &mut self,
1043 1044 1045
        dst: &'ll Value,
        cmp: &'ll Value,
        src: &'ll Value,
1046 1047
        order: rustc_codegen_ssa::common::AtomicOrdering,
        failure_order: rustc_codegen_ssa::common::AtomicOrdering,
1048
        weak: bool,
1049
    ) -> &'ll Value {
1050
        let weak = if weak { llvm::True } else { llvm::False };
1051
        unsafe {
1052 1053 1054 1055 1056 1057 1058
            llvm::LLVMRustBuildAtomicCmpXchg(
                self.llbuilder,
                dst,
                cmp,
                src,
                AtomicOrdering::from_generic(order),
                AtomicOrdering::from_generic(failure_order),
M
Mark Rousskov 已提交
1059
                weak,
1060
            )
1061 1062
        }
    }
1063
    fn atomic_rmw(
1064
        &mut self,
1065
        op: rustc_codegen_ssa::common::AtomicRmwBinOp,
1066 1067
        dst: &'ll Value,
        src: &'ll Value,
1068
        order: rustc_codegen_ssa::common::AtomicOrdering,
1069
    ) -> &'ll Value {
1070
        unsafe {
1071 1072 1073 1074 1075
            llvm::LLVMBuildAtomicRMW(
                self.llbuilder,
                AtomicRmwBinOp::from_generic(op),
                dst,
                src,
1076
                AtomicOrdering::from_generic(order),
M
Mark Rousskov 已提交
1077 1078
                False,
            )
1079 1080
        }
    }
J
James Miller 已提交
1081

D
Denis Merigoux 已提交
1082
    fn atomic_fence(
1083
        &mut self,
1084
        order: rustc_codegen_ssa::common::AtomicOrdering,
M
Mark Rousskov 已提交
1085
        scope: rustc_codegen_ssa::common::SynchronizationScope,
D
Denis Merigoux 已提交
1086
    ) {
J
James Miller 已提交
1087
        unsafe {
1088 1089 1090
            llvm::LLVMRustBuildAtomicFence(
                self.llbuilder,
                AtomicOrdering::from_generic(order),
M
Mark Rousskov 已提交
1091
                SynchronizationScope::from_generic(scope),
1092
            );
J
James Miller 已提交
1093 1094
        }
    }
1095

1096
    fn set_invariant_load(&mut self, load: &'ll Value) {
1097
        unsafe {
M
Mark Rousskov 已提交
1098 1099 1100 1101 1102
            llvm::LLVMSetMetadata(
                load,
                llvm::MD_invariant_load as c_uint,
                llvm::LLVMMDNodeInContext(self.cx.llcx, ptr::null(), 0),
            );
1103 1104 1105
        }
    }

1106
    fn lifetime_start(&mut self, ptr: &'ll Value, size: Size) {
1107
        self.call_lifetime_intrinsic("llvm.lifetime.start.p0i8", ptr, size);
1108 1109
    }

1110
    fn lifetime_end(&mut self, ptr: &'ll Value, size: Size) {
1111
        self.call_lifetime_intrinsic("llvm.lifetime.end.p0i8", ptr, size);
1112 1113
    }

1114 1115 1116 1117 1118 1119
    fn instrprof_increment(
        &mut self,
        fn_name: &'ll Value,
        hash: &'ll Value,
        num_counters: &'ll Value,
        index: &'ll Value,
1120
    ) {
1121 1122 1123 1124 1125
        debug!(
            "instrprof_increment() with args ({:?}, {:?}, {:?}, {:?})",
            fn_name, hash, num_counters, index
        );

R
Rich Kadel 已提交
1126
        let llfn = unsafe { llvm::LLVMRustGetInstrProfIncrementIntrinsic(self.cx().llmod) };
1127 1128 1129 1130
        let args = &[fn_name, hash, num_counters, index];
        let args = self.check_call("call", llfn, args);

        unsafe {
1131
            let _ = llvm::LLVMRustBuildCall(
1132 1133 1134 1135 1136
                self.llbuilder,
                llfn,
                args.as_ptr() as *const &llvm::Value,
                args.len() as c_uint,
                None,
1137
            );
1138 1139 1140
        }
    }

1141
    fn call(
1142
        &mut self,
1143 1144 1145 1146
        llfn: &'ll Value,
        args: &[&'ll Value],
        funclet: Option<&Funclet<'ll>>,
    ) -> &'ll Value {
M
Mark Rousskov 已提交
1147
        debug!("call {:?} with args ({:?})", llfn, args);
1148 1149

        let args = self.check_call("call", llfn, args);
1150
        let bundle = funclet.map(|funclet| funclet.bundle());
1151
        let bundle = bundle.as_ref().map(|b| &*b.raw);
1152 1153 1154 1155 1156 1157 1158

        unsafe {
            llvm::LLVMRustBuildCall(
                self.llbuilder,
                llfn,
                args.as_ptr() as *const &llvm::Value,
                args.len() as c_uint,
M
Mark Rousskov 已提交
1159
                bundle,
1160 1161 1162 1163
            )
        }
    }

1164
    fn zext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
M
Mark Rousskov 已提交
1165
        unsafe { llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty, UNNAMED) }
1166 1167
    }

1168
    fn cx(&self) -> &CodegenCx<'ll, 'tcx> {
1169
        self.cx
1170
    }
1171

1172 1173
    unsafe fn delete_basic_block(&mut self, bb: &'ll BasicBlock) {
        llvm::LLVMDeleteBasicBlock(bb);
1174 1175
    }

1176
    fn do_not_inline(&mut self, llret: &'ll Value) {
1177 1178
        llvm::Attribute::NoInline.apply_callsite(llvm::AttributePlace::Function, llret);
    }
1179
}
1180

1181 1182
impl StaticBuilderMethods for Builder<'a, 'll, 'tcx> {
    fn get_static(&mut self, def_id: DefId) -> &'ll Value {
B
bjorn3 已提交
1183
        // Forward to the `get_static` method of `CodegenCx`
B
bjorn3 已提交
1184 1185 1186 1187
        self.cx().get_static(def_id)
    }
}

1188
impl Builder<'a, 'll, 'tcx> {
B
bjorn3 已提交
1189
    pub fn llfn(&self) -> &'ll Value {
M
Mark Rousskov 已提交
1190
        unsafe { llvm::LLVMGetBasicBlockParent(self.llbb()) }
B
bjorn3 已提交
1191 1192
    }

1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
    fn position_at_start(&mut self, llbb: &'ll BasicBlock) {
        unsafe {
            llvm::LLVMRustPositionBuilderAtStart(self.llbuilder, llbb);
        }
    }

    pub fn minnum(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
        unsafe { llvm::LLVMRustBuildMinNum(self.llbuilder, lhs, rhs) }
    }

    pub fn maxnum(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
        unsafe { llvm::LLVMRustBuildMaxNum(self.llbuilder, lhs, rhs) }
    }

    pub fn insert_element(
M
Mark Rousskov 已提交
1208 1209
        &mut self,
        vec: &'ll Value,
1210 1211 1212
        elt: &'ll Value,
        idx: &'ll Value,
    ) -> &'ll Value {
M
Mark Rousskov 已提交
1213
        unsafe { llvm::LLVMBuildInsertElement(self.llbuilder, vec, elt, idx, UNNAMED) }
1214 1215 1216 1217 1218 1219 1220 1221
    }

    pub fn shuffle_vector(
        &mut self,
        v1: &'ll Value,
        v2: &'ll Value,
        mask: &'ll Value,
    ) -> &'ll Value {
M
Mark Rousskov 已提交
1222
        unsafe { llvm::LLVMBuildShuffleVector(self.llbuilder, v1, v2, mask, UNNAMED) }
1223 1224
    }

1225 1226 1227 1228 1229 1230
    pub fn vector_reduce_fadd(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
        unsafe { llvm::LLVMRustBuildVectorReduceFAdd(self.llbuilder, acc, src) }
    }
    pub fn vector_reduce_fmul(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
        unsafe { llvm::LLVMRustBuildVectorReduceFMul(self.llbuilder, acc, src) }
    }
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
    pub fn vector_reduce_fadd_fast(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
        unsafe {
            let instr = llvm::LLVMRustBuildVectorReduceFAdd(self.llbuilder, acc, src);
            llvm::LLVMRustSetHasUnsafeAlgebra(instr);
            instr
        }
    }
    pub fn vector_reduce_fmul_fast(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
        unsafe {
            let instr = llvm::LLVMRustBuildVectorReduceFMul(self.llbuilder, acc, src);
            llvm::LLVMRustSetHasUnsafeAlgebra(instr);
            instr
        }
    }
    pub fn vector_reduce_add(&mut self, src: &'ll Value) -> &'ll Value {
        unsafe { llvm::LLVMRustBuildVectorReduceAdd(self.llbuilder, src) }
    }
    pub fn vector_reduce_mul(&mut self, src: &'ll Value) -> &'ll Value {
        unsafe { llvm::LLVMRustBuildVectorReduceMul(self.llbuilder, src) }
    }
    pub fn vector_reduce_and(&mut self, src: &'ll Value) -> &'ll Value {
        unsafe { llvm::LLVMRustBuildVectorReduceAnd(self.llbuilder, src) }
    }
    pub fn vector_reduce_or(&mut self, src: &'ll Value) -> &'ll Value {
        unsafe { llvm::LLVMRustBuildVectorReduceOr(self.llbuilder, src) }
    }
    pub fn vector_reduce_xor(&mut self, src: &'ll Value) -> &'ll Value {
        unsafe { llvm::LLVMRustBuildVectorReduceXor(self.llbuilder, src) }
    }
    pub fn vector_reduce_fmin(&mut self, src: &'ll Value) -> &'ll Value {
M
Mark Rousskov 已提交
1261 1262 1263
        unsafe {
            llvm::LLVMRustBuildVectorReduceFMin(self.llbuilder, src, /*NoNaNs:*/ false)
        }
1264 1265
    }
    pub fn vector_reduce_fmax(&mut self, src: &'ll Value) -> &'ll Value {
M
Mark Rousskov 已提交
1266 1267 1268
        unsafe {
            llvm::LLVMRustBuildVectorReduceFMax(self.llbuilder, src, /*NoNaNs:*/ false)
        }
1269 1270 1271
    }
    pub fn vector_reduce_fmin_fast(&mut self, src: &'ll Value) -> &'ll Value {
        unsafe {
M
Mark Rousskov 已提交
1272 1273
            let instr =
                llvm::LLVMRustBuildVectorReduceFMin(self.llbuilder, src, /*NoNaNs:*/ true);
1274 1275 1276 1277 1278 1279
            llvm::LLVMRustSetHasUnsafeAlgebra(instr);
            instr
        }
    }
    pub fn vector_reduce_fmax_fast(&mut self, src: &'ll Value) -> &'ll Value {
        unsafe {
M
Mark Rousskov 已提交
1280 1281
            let instr =
                llvm::LLVMRustBuildVectorReduceFMax(self.llbuilder, src, /*NoNaNs:*/ true);
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
            llvm::LLVMRustSetHasUnsafeAlgebra(instr);
            instr
        }
    }
    pub fn vector_reduce_min(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
        unsafe { llvm::LLVMRustBuildVectorReduceMin(self.llbuilder, src, is_signed) }
    }
    pub fn vector_reduce_max(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
        unsafe { llvm::LLVMRustBuildVectorReduceMax(self.llbuilder, src, is_signed) }
    }

    pub fn add_clause(&mut self, landing_pad: &'ll Value, clause: &'ll Value) {
        unsafe {
            llvm::LLVMAddClause(landing_pad, clause);
        }
    }

    pub fn catch_ret(&mut self, funclet: &Funclet<'ll>, unwind: &'ll BasicBlock) -> &'ll Value {
M
Mark Rousskov 已提交
1300 1301
        let ret =
            unsafe { llvm::LLVMRustBuildCatchRet(self.llbuilder, funclet.cleanuppad(), unwind) };
1302 1303 1304
        ret.expect("LLVM does not have support for catchret")
    }

1305
    fn check_store(&mut self, val: &'ll Value, ptr: &'ll Value) -> &'ll Value {
1306 1307 1308 1309 1310 1311 1312 1313 1314
        let dest_ptr_ty = self.cx.val_ty(ptr);
        let stored_ty = self.cx.val_ty(val);
        let stored_ptr_ty = self.cx.type_ptr_to(stored_ty);

        assert_eq!(self.cx.type_kind(dest_ptr_ty), TypeKind::Pointer);

        if dest_ptr_ty == stored_ptr_ty {
            ptr
        } else {
M
Mark Rousskov 已提交
1315 1316
            debug!(
                "type mismatch in store. \
1317
                    Expected {:?}, got {:?}; inserting bitcast",
M
Mark Rousskov 已提交
1318 1319
                dest_ptr_ty, stored_ptr_ty
            );
1320 1321 1322 1323
            self.bitcast(ptr, stored_ptr_ty)
        }
    }

M
Mark Rousskov 已提交
1324 1325 1326 1327 1328 1329
    fn check_call<'b>(
        &mut self,
        typ: &str,
        llfn: &'ll Value,
        args: &'b [&'ll Value],
    ) -> Cow<'b, [&'ll Value]> {
1330 1331 1332 1333 1334 1335
        let mut fn_ty = self.cx.val_ty(llfn);
        // Strip off pointers
        while self.cx.type_kind(fn_ty) == TypeKind::Pointer {
            fn_ty = self.cx.element_type(fn_ty);
        }

M
Mark Rousskov 已提交
1336 1337 1338 1339 1340 1341
        assert!(
            self.cx.type_kind(fn_ty) == TypeKind::Function,
            "builder::{} not passed a function, but {:?}",
            typ,
            fn_ty
        );
1342 1343 1344

        let param_tys = self.cx.func_params_types(fn_ty);

M
Mark Rousskov 已提交
1345 1346
        let all_args_match = param_tys
            .iter()
1347 1348 1349 1350 1351 1352 1353
            .zip(args.iter().map(|&v| self.val_ty(v)))
            .all(|(expected_ty, actual_ty)| *expected_ty == actual_ty);

        if all_args_match {
            return Cow::Borrowed(args);
        }

M
Mark Rousskov 已提交
1354 1355
        let casted_args: Vec<_> = param_tys
            .into_iter()
1356 1357 1358 1359 1360
            .zip(args.iter())
            .enumerate()
            .map(|(i, (expected_ty, &actual_val))| {
                let actual_ty = self.val_ty(actual_val);
                if expected_ty != actual_ty {
M
Mark Rousskov 已提交
1361 1362
                    debug!(
                        "type mismatch in function call of {:?}. \
1363
                            Expected {:?} for param {}, got {:?}; injecting bitcast",
M
Mark Rousskov 已提交
1364 1365
                        llfn, expected_ty, i, actual_ty
                    );
1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
                    self.bitcast(actual_val, expected_ty)
                } else {
                    actual_val
                }
            })
            .collect();

        Cow::Owned(casted_args)
    }

    pub fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
M
Mark Rousskov 已提交
1377
        unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) }
1378 1379
    }

1380
    fn call_lifetime_intrinsic(&mut self, intrinsic: &str, ptr: &'ll Value, size: Size) {
1381 1382
        let size = size.bytes();
        if size == 0 {
1383 1384 1385
            return;
        }

1386
        if !self.cx().sess().emit_lifetime_markers() {
1387 1388 1389 1390 1391 1392 1393 1394
            return;
        }

        let lifetime_intrinsic = self.cx.get_intrinsic(intrinsic);

        let ptr = self.pointercast(ptr, self.cx.type_i8p());
        self.call(lifetime_intrinsic, &[self.cx.const_u64(size), ptr], None);
    }
1395

1396 1397 1398 1399 1400 1401
    pub(crate) fn phi(
        &mut self,
        ty: &'ll Type,
        vals: &[&'ll Value],
        bbs: &[&'ll BasicBlock],
    ) -> &'ll Value {
1402
        assert_eq!(vals.len(), bbs.len());
M
Mark Rousskov 已提交
1403
        let phi = unsafe { llvm::LLVMBuildPhi(self.llbuilder, ty, UNNAMED) };
1404
        unsafe {
M
Mark Rousskov 已提交
1405
            llvm::LLVMAddIncoming(phi, vals.as_ptr(), bbs.as_ptr(), vals.len() as c_uint);
1406 1407 1408 1409 1410 1411 1412 1413 1414
            phi
        }
    }

    fn add_incoming_to_phi(&mut self, phi: &'ll Value, val: &'ll Value, bb: &'ll BasicBlock) {
        unsafe {
            llvm::LLVMAddIncoming(phi, &val, &bb, 1 as c_uint);
        }
    }
1415 1416 1417 1418 1419

    fn wasm_and_missing_nontrapping_fptoint(&self) -> bool {
        self.sess().target.target.arch == "wasm32"
            && !self.sess().target_features.contains(&sym::nontrapping_dash_fptoint)
    }
1420
}