//! returns: 0
//! Test that stack arguments do not clobber caller state.
//!
//! The caller keeps more values live across the call than there are
//! callee-saved registers, so some live in spill slots. One of them is the
//! stack argument, which the caller must load from its spill slot while SP is
//! lowered. A local array whose address is also passed must keep its contents.

record Wide { a: u32, b: u32, c: u32 }

/// Write through the pointer, then combine all arguments.
fn scribble(buf: &mut [u32], a: u32, b: u32, c: u32, d: u32, e: u32, f: u32, g: u32) -> Wide {
    set buf[0] = 0xdead;
    set buf[3] = 0xbeef;
    return Wide { a: a + b + c + d, b: e + f + g, c: buf[0] + buf[3] };
}

fn caller(x: u32) -> u32 {
    let late = x + 99;
    let v0 = x + 1;
    let v1 = x + 2;
    let v2 = x + 3;
    let v3 = x + 4;
    let v4 = x + 5;
    let v5 = x + 6;
    let v6 = x + 7;
    let v7 = x + 8;
    let v8 = x + 9;
    let v9 = x + 10;
    let v10 = x + 11;
    let v11 = x + 12;
    let v12 = x + 13;
    let v13 = x + 14;
    let v14 = x + 15;
    let v15 = x + 16;
    let v16 = x + 17;
    let v17 = x + 18;
    let mut buf: [u32; 4] = [x, x + 1, x + 2, x + 3];
    let local = Wide { a: v0, b: v1, c: v2 };

    let w = scribble(&mut buf[..], v13, v12, v11, v10, v9, v14, late);
    assert w.a == v13 + v12 + v11 + v10;
    assert w.b == v9 + v14 + late;
    assert w.c == 0xdead + 0xbeef;
    assert buf[0] == 0xdead;
    assert buf[1] == x + 1;
    assert buf[2] == x + 2;
    assert buf[3] == 0xbeef;
    assert local.a == v0 and local.b == v1 and local.c == v2;

    // Each value is read three times after the call, so `late` is the cheapest
    // value to keep in a spill slot, and it is also the last stack argument.
    let total =
        v0
            + v1
            + v2
            + v3
            + v4
            + v5
            + v6
            + v7
            + v8
            + v9
            + v10
            + v11
            + v12
            + v13
            + v14
            + v15
            + v16
            + v17;
    let again =
        v0
            + v1
            + v2
            + v3
            + v4
            + v5
            + v6
            + v7
            + v8
            + v9
            + v10
            + v11
            + v12
            + v13
            + v14
            + v15
            + v16
            + v17;
    let third =
        v0
            + v1
            + v2
            + v3
            + v4
            + v5
            + v6
            + v7
            + v8
            + v9
            + v10
            + v11
            + v12
            + v13
            + v14
            + v15
            + v16
            + v17;
    assert again == total and third == total;
    return total + late - x - 99;
}

@default fn main() -> i32 {
    assert caller(100) == 18 * 100 + 171;
    assert caller(7) == 18 * 7 + 171;
    return 0;
}
