lang: Verify unions with mixed payload layouts

f0b7d201f59fb23c3535331a7dd93ff7b829d9327822faba81196856f4aebc59
Describe mixed unions as protected slots with a layout for each variant.
Checked union.get reads a payload or field, and union.set writes a tag
with its matching payload. Support both instructions in the binary
format, printer, verifier and RV64 backend.

Check constant initializers against each nested union tag. Keep distinct
error shapes in typed result regions through construction, catches and
propagation. Reject safe mutable data that holds or reaches a mixed
union, and patterns that bind its payload by reference.

Use field snapshots, scalar-bit equality, cached payload classification
and ordered layout lookup. Recognize whole union construction as
initialization. Preserve guarded-match subjects and share variant
lookup.

Cover executable patterns, nested constants, mixed-shape errors, hostile
packages and malformed layouts. Require every safe standalone fixture to
pass verification.

Assisted-by: Codex:gpt-6
Alexis Sellier committed ago 1 parent 4e859282
lib/std/arch/rv64/emit.rad +25 -6
839 839
    }
840 840
    let totalSize = frame.totalSize;
841 841
    if e.stackCheck {
842 842
        try emitStackCheck(e, totalSize);
843 843
    }
844 +
    // The save area is next to the incoming stack pointer. A common base keeps its
845 +
    // accesses within one instruction when the local area is large.
846 +
    let mut saveBase = super::SP;
847 +
    let mut saveOffset: i32 = 0;
848 +
    if totalSize > super::MAX_IMM and frame.savedRegsLen >= 2 {
849 +
        try emit(e, encode::addi(super::ADDR_SCRATCH, super::SP, 0));
850 +
        set saveBase = super::ADDR_SCRATCH;
851 +
        set saveOffset = totalSize;
852 +
    }
844 853
    // Allocate stack frame.
845 854
    let negFrame = 0 - totalSize;
846 855
    if negFrame >= super::MIN_IMM {
847 856
        try emit(e, encode::addi(super::SP, super::SP, negFrame));
848 857
    } else {
849 858
        try loadImm(e, super::SCRATCH1, totalSize as i64);
850 859
        try emit(e, encode::sub(super::SP, super::SP, super::SCRATCH1));
851 860
    }
852 861
    // Save return address.
853 862
    if not frame.isLeaf {
854 -
        try emitSd(e, super::RA, super::SP, totalSize - super::DWORD_SIZE);
863 +
        try emitSd(e, super::RA, saveBase, totalSize - super::DWORD_SIZE - saveOffset);
855 864
    }
856 865
    // Save callee-saved registers.
857 866
    for i in 0 .. frame.savedRegsLen {
858 867
        let sr = frame.savedRegs[i];
859 -
        try emitSd(e, sr.reg, super::SP, sr.offset);
868 +
        try emitSd(e, sr.reg, saveBase, sr.offset - saveOffset);
860 869
    }
861 870
}
862 871
863 872
/// Emit a return: jump to epilogue, or emit `ret` directly for leaf functions.
864 873
export fn emitReturn(e: &mut Emitter, frame: &Frame) throws (super::Error) {
880 889
    if frame.totalSize == 0 {
881 890
        try emit(e, encode::ret());
882 891
        return;
883 892
    }
884 893
    let totalSize = frame.totalSize;
885 -
894 +
    let mut saveBase = super::SP;
895 +
    let mut saveOffset: i32 = 0;
896 +
    if totalSize > super::MAX_IMM and frame.savedRegsLen >= 2 {
897 +
        try emitAddImm(e, super::ADDR_SCRATCH, super::SP, totalSize);
898 +
        set saveBase = super::ADDR_SCRATCH;
899 +
        set saveOffset = totalSize;
900 +
    }
886 901
    // Restore callee-saved registers.
887 902
    for i in 0 .. frame.savedRegsLen {
888 903
        let sr = frame.savedRegs[i];
889 -
        try emitLd(e, sr.reg, super::SP, sr.offset);
904 +
        try emitLd(e, sr.reg, saveBase, sr.offset - saveOffset);
890 905
    }
891 906
    // Restore return address.
892 907
    if not frame.isLeaf {
893 -
        try emitLd(e, super::RA, super::SP, totalSize - super::DWORD_SIZE);
908 +
        try emitLd(e, super::RA, saveBase, totalSize - super::DWORD_SIZE - saveOffset);
894 909
    }
895 910
    // Deallocate stack frame.
896 -
    try emitAddImm(e, super::SP, super::SP, totalSize);
911 +
    if saveOffset > 0 {
912 +
        try emit(e, encode::addi(super::SP, saveBase, 0));
913 +
    } else {
914 +
        try emitAddImm(e, super::SP, super::SP, totalSize);
915 +
    }
897 916
    try emit(e, encode::ret());
898 917
}
899 918
900 919
//////////////////
901 920
// Code Access  //
lib/std/arch/rv64/isel.rad +140 -58
879 879
    try emit::emit(e, encode::addi(dst, dst, unit as i32));
880 880
    let offset = (start as i32 - e.code.len as i32) * super::INSTR_SIZE;
881 881
    try emit::emit(e, encode::bne(src, end, offset));
882 882
}
883 883
884 +
/// Copy an object of layout `object` from `src` to `dst`. Both addresses are aligned to the
885 +
/// layout, so every access up to the alignment is. A spilled operand sits in the scratch
886 +
/// register that the caller chose: `SCRATCH1` for the source and `SCRATCH2` for the destination,
887 +
/// or `SCRATCH3` for the source.
888 +
fn emitBlit(
889 +
    e: &mut emit::Emitter, dst: gen::Reg, src: gen::Reg, object: il::Layout
890 +
) throws (super::Error) {
891 +
    if object.size > MAX_OBJECT_SIZE {
892 +
        throw super::Error::Invalid;
893 +
    }
894 +
    if object.size == 0 {
895 +
        return;
896 +
    }
897 +
    let unit = copyUnit(object.alignment);
898 +
    if object.size / unit <= super::BLIT_UNROLL_UNITS {
899 +
        try emitCopy(e, dst, src, object.size, unit);
900 +
        return;
901 +
    }
902 +
    // The cursors and the end are scratch registers, so that both addresses keep their
903 +
    // values. A spilled operand sits in a scratch register that is reused once the move that
904 +
    // reads it has run: the source in the register of the destination cursor, and the
905 +
    // destination in that of the end.
906 +
    let body = object.size - object.size % unit;
907 +
    try emit::emit(e, encode::addi(super::SCRATCH3, src, 0));
908 +
    try emit::emit(e, encode::addi(super::SCRATCH1, dst, 0));
909 +
    if body as i32 <= super::MAX_IMM {
910 +
        try emit::emit(e, encode::addi(super::SCRATCH2, super::SCRATCH3, body as i32));
911 +
    } else {
912 +
        try emit::loadImm(e, super::SCRATCH2, body as i64);
913 +
        try emit::emit(e, encode::add(super::SCRATCH2, super::SCRATCH2, super::SCRATCH3));
914 +
    }
915 +
    try emitCopyLoop(
916 +
        e, super::SCRATCH3, super::SCRATCH1, super::SCRATCH2, super::ADDR_SCRATCH, unit
917 +
    );
918 +
    try emitCopy(e, super::SCRATCH1, super::SCRATCH3, object.size - body, unit);
919 +
}
920 +
884 921
/// Multiply `rs` by the constant `size`. `rd` can be `rs`. A `size` that is not a
885 922
/// power of two is loaded into `tmp`, which must differ from `rs`.
886 923
fn emitScale(
887 924
    e: &mut emit::Emitter, rd: gen::Reg, rs: gen::Reg, size: u32, tmp: gen::Reg
888 925
) throws (super::Error) {
938 975
            set c.count += 1;
939 976
        }
940 977
    }
941 978
}
942 979
943 -
/// Offset past the last byte of a slot of layout `l`, or zero for a layout without slots.
944 -
fn slotsEnd(layouts: &[il::Layout], l: &il::Layout) -> u64 {
945 -
    let mut end: u64 = 0;
980 +
/// Bytes of an object that a reserve must zero so that no slot holds stale bytes: from `lo` to
981 +
/// `hi`. A layout without slots has none, and then `hi` is zero.
982 +
record Span: Copy {
983 +
    /// Offset of the first byte.
984 +
    lo: u64,
985 +
    /// Offset past the last byte.
986 +
    hi: u64,
987 +
    /// Whether the layout has a union slot, which needs only its tag and the slots of one variant.
988 +
    unions: bool,
989 +
}
990 +
991 +
/// Find the bytes of an object of layout `l` that must start as zero. A union slot needs its tag
992 +
/// byte and the slots of its variant with tag 0, since its other variants are read only after a
993 +
/// check of the tag, and the tag byte is zero.
994 +
fn zeroSpan(layouts: &[il::Layout], l: &il::Layout) -> Span {
995 +
    let mut span = Span { lo: l.size as u64, hi: 0, unions: false };
946 996
    for slot in l.slots {
947 -
        let mut size: u64 = super::DWORD_SIZE as u64;
997 +
        let start = slot.offset as u64;
998 +
        let mut inner = Span { lo: 0, hi: super::DWORD_SIZE as u64, unions: false };
948 999
        match slot.kind {
949 -
            case il::SlotKind::Slice(_)   => set size = SLICE_SIZE as u64,
950 -
            case il::SlotKind::Sub(inner) => set size = layouts[inner].size as u64,
951 -
            case il::SlotKind::Array { layout, count } =>
952 -
                set size = layouts[layout].size as u64 * count as u64,
1000 +
            case il::SlotKind::Slice(_), il::SlotKind::Trait(_) =>
1001 +
                set inner.hi = SLICE_SIZE as u64,
1002 +
            case il::SlotKind::Union { offset, variants, .. } => {
1003 +
                set inner.hi = 1;
1004 +
                set inner.unions = true;
1005 +
                for variant in variants {
1006 +
                    if let payload = variant.layout; variant.tag == 0 {
1007 +
                        let zeroed = zeroSpan(layouts, &layouts[payload]);
1008 +
                        if zeroed.hi > 0 {
1009 +
                            set inner.hi = offset as u64 + zeroed.hi;
1010 +
                        }
1011 +
                    }
1012 +
                }
1013 +
            }
1014 +
            case il::SlotKind::Sub(child) => set inner = zeroSpan(layouts, &layouts[child]),
1015 +
            case il::SlotKind::Array { layout, count } => {
1016 +
                let element = zeroSpan(layouts, &layouts[layout]);
1017 +
                set inner.lo = element.lo;
1018 +
                set inner.unions = element.unions;
1019 +
                set inner.hi = 0;
1020 +
                if count > 0 {
1021 +
                    set inner.hi = element.hi + (count as u64 - 1) * layouts[layout].size as u64;
1022 +
                }
1023 +
            }
953 1024
            else => {}
954 1025
        }
955 -
        if slot.offset as u64 + size > end {
956 -
            set end = slot.offset as u64 + size;
1026 +
        if start + inner.lo < span.lo {
1027 +
            set span.lo = start + inner.lo;
957 1028
        }
1029 +
        if start + inner.hi > span.hi {
1030 +
            set span.hi = start + inner.hi;
1031 +
        }
1032 +
        set span.unions = span.unions or inner.unions;
958 1033
    }
959 -
    return end;
1034 +
    return span;
960 1035
}
961 1036
962 1037
/// Whether the reserve at `index` of the block is followed by a write to its first bytes that
963 1038
/// covers every slot of its layout `l`, before anything else uses the reserve.
964 1039
///
965 1040
/// A reserve is zeroed so that no slot holds stale bytes. The zeroes are not observable when
966 1041
/// the object is overwritten first. The address of a reserve exists only after the reserve, so
967 1042
/// no instruction can read or write the object unless it has the address as an operand. The
968 -
/// write is a `blit`, `slice.new` or `slice.sub` that has the reserve as its destination and
969 -
/// does not have it as another operand, so it does not read the object. It is in the same
970 -
/// block within `ZERO_LOOKAHEAD` instructions, and nothing branches in between, so it runs
971 -
/// whenever the reserve does. A trap in between ends the domain. The bytes of the object
972 -
/// outside its slots are plain data, which is not zeroed when the slots are not.
1043 +
/// write is a `blit`, `union.get`, `union.set`, `slice.new` or `slice.sub` that has the reserve as its
1044 +
/// destination and does not have it as another operand, so it does not read the object. It is
1045 +
/// in the same block within `ZERO_LOOKAHEAD` instructions, and nothing branches in between, so
1046 +
/// it runs whenever the reserve does. A trap in between ends the domain. The bytes of the
1047 +
/// object outside its slots are plain data, which is not zeroed when the slots are not.
1048 +
/// A whole union constructor initializes its tag and every slot of the active variant.
973 1049
fn isOverwritten(
974 1050
    func: *il::Fn, blockIdx: u32, index: u32, layouts: &[il::Layout], l: &il::Layout, reg: il::Reg
975 1051
) -> bool {
976 1052
    let instrs = func.blocks[blockIdx].instrs;
977 1053
    let mut at = index + 1;
985 1061
                case il::Instr::Blit { dst, layout, .. } => {
986 1062
                    if dst.n == reg.n {
987 1063
                        set written = layouts[layout].size as u64;
988 1064
                    }
989 1065
                }
1066 +
                case il::Instr::UnionSet { dst, .. } => {
1067 +
                    if dst.n == reg.n and l.slots.len == 1 and l.slots[0].offset == 0 {
1068 +
                        if let case il::SlotKind::Union { size, .. } =
1069 +
                            l.slots[0].kind;
1070 +
                            size == l.size
1071 +
                        {
1072 +
                            return uses.count == 1;
1073 +
                        }
1074 +
                    }
1075 +
                }
1076 +
                case il::Instr::UnionGet { dst, layout, .. } => {
1077 +
                    if dst.n == reg.n {
1078 +
                        set written = layouts[layout].size as u64;
1079 +
                    }
1080 +
                }
990 1081
                case il::Instr::SliceNew { dst, .. } => {
991 1082
                    if dst.n == reg.n {
992 1083
                        set written = SLICE_SIZE as u64;
993 1084
                    }
994 1085
                }
997 1088
                        set written = SLICE_SIZE as u64;
998 1089
                    }
999 1090
                }
1000 1091
                else => {}
1001 1092
            }
1002 -
            return uses.count == 1 and written >= slotsEnd(layouts, l);
1093 +
            return uses.count == 1
1094 +
                and (written >= l.size as u64 or written >= zeroSpan(layouts, l).hi);
1003 1095
        }
1004 1096
        set at += 1;
1005 1097
    }
1006 1098
    return false;
1007 1099
}
1446 1538
            // A slot must never hold stale bytes, so an object with slots starts zeroed, unless
1447 1539
            // it is overwritten first.
1448 1540
            if info.slots.len > 0
1449 1541
                and not isOverwritten(func, blockIdx, s.instrIndex, layouts, &info, dst)
1450 1542
            {
1451 -
                try emitZeroFrame(e, offset, info.size);
1543 +
                let span = zeroSpan(layouts, &info);
1544 +
                if span.unions {
1545 +
                    let lo = span.lo - span.lo % super::DWORD_SIZE as u64;
1546 +
                    try emitZeroFrame(e, offset + lo as i32, (span.hi - lo) as u32);
1547 +
                } else {
1548 +
                    try emitZeroFrame(e, offset, info.size);
1549 +
                }
1452 1550
            }
1453 1551
        }
1454 1552
        case il::Instr::Field { dst, src, offset } => {
1455 1553
            let rd = getDstReg(s, dst, super::SCRATCH1);
1456 1554
            let rs = try getSrcReg(s, e, src, super::SCRATCH2);
1602 1700
            let base = try getSrcReg(s, e, dst, super::SCRATCH2);
1603 1701
            let rs = try resolveVal(s, e, super::SCRATCH1, src);
1604 1702
            try emit::emitStore(e, rs, base, offset, il::Type::W64);
1605 1703
        }
1606 1704
        case il::Instr::Blit { dst, src, layout } => {
1607 -
            let object = layouts[layout];
1608 -
            if object.size > MAX_OBJECT_SIZE {
1609 -
                throw super::Error::Invalid;
1610 -
            }
1611 -
            if object.size == 0 {
1612 -
                return;
1613 -
            }
1614 -
            // Both addresses are aligned to the layout, so every access up to the alignment is.
1615 -
            let mut unit = object.alignment;
1616 -
            if unit > super::DWORD_SIZE as u32 {
1617 -
                set unit = super::DWORD_SIZE as u32;
1618 -
            }
1619 1705
            let rdst = try getSrcReg(s, e, dst, super::SCRATCH2);
1620 1706
            let rsrc = try getSrcReg(s, e, src, super::SCRATCH1);
1621 -
1622 -
            if object.size / unit <= super::BLIT_UNROLL_UNITS {
1623 -
                try emitCopy(e, rdst, rsrc, object.size, unit);
1624 -
            } else {
1625 -
                // The cursors and the end are scratch registers, so that both addresses keep
1626 -
                // their values. A spilled operand sits in a scratch register that is reused
1627 -
                // once the move that reads it has run: the source in the register of the
1628 -
                // destination cursor, and the destination in that of the end.
1629 -
                let body = object.size - object.size % unit;
1630 -
                try emit::emit(e, encode::addi(super::SCRATCH3, rsrc, 0));
1631 -
                try emit::emit(e, encode::addi(super::SCRATCH1, rdst, 0));
1632 -
                if body as i32 <= super::MAX_IMM {
1633 -
                    try emit::emit(e, encode::addi(super::SCRATCH2, super::SCRATCH3, body as i32));
1634 -
                } else {
1635 -
                    try emit::loadImm(e, super::SCRATCH2, body as i64);
1636 -
                    try emit::emit(e, encode::add(
1637 -
                        super::SCRATCH2, super::SCRATCH2, super::SCRATCH3
1638 -
                    ));
1639 -
                }
1640 -
                let start = e.code.len;
1641 -
                try emit::emitSload(e, super::ADDR_SCRATCH, super::SCRATCH3, 0, accessType(unit));
1642 -
                try emit::emitStore(e, super::ADDR_SCRATCH, super::SCRATCH1, 0, accessType(unit));
1643 -
                try emit::emit(e, encode::addi(super::SCRATCH3, super::SCRATCH3, unit as i32));
1644 -
                try emit::emit(e, encode::addi(super::SCRATCH1, super::SCRATCH1, unit as i32));
1645 -
                let offset = (start as i32 - e.code.len as i32) * super::INSTR_SIZE;
1646 -
                try emit::emit(e, encode::bne(super::SCRATCH3, super::SCRATCH2, offset));
1647 -
                try emitCopy(e, super::SCRATCH1, super::SCRATCH3, object.size - body, unit);
1648 -
            }
1707 +
            try emitBlit(e, rdst, rsrc, layouts[layout]);
1649 1708
        }
1650 1709
        case il::Instr::Zext { typ, dst, val } => {
1651 1710
            let rd = getDstReg(s, dst, super::SCRATCH1);
1652 1711
            let rs = try resolveVal(s, e, super::SCRATCH1, val);
1653 1712
            if isExtended(s, val, typ, false) {
1842 1901
            try emit::emitLd(e, super::SCRATCH3, rsrc, TRAIT_RECV_OFFSET);
1843 1902
            try emit::emitSd(e, super::SCRATCH3, rdst, TRAIT_RECV_OFFSET);
1844 1903
            try emit::emitLd(e, super::SCRATCH3, rsrc, TRAIT_TABLE_OFFSET);
1845 1904
            try emit::emitSd(e, super::SCRATCH3, rdst, TRAIT_TABLE_OFFSET);
1846 1905
        }
1906 +
        case il::Instr::UnionGet { dst, src, tag, offset, layout } => {
1907 +
            let rdst = try getSrcReg(s, e, dst, super::SCRATCH2);
1908 +
            let rsrc = try getSrcReg(s, e, src, super::SCRATCH1);
1909 +
            // A tag other than the variant traps.
1910 +
            try emit::emitLoad(e, super::SCRATCH3, rsrc, 0, il::Type::W8);
1911 +
            try emit::loadImm(e, super::ADDR_SCRATCH, tag as i64);
1912 +
            try emit::emit(e, encode::beq(
1913 +
                super::SCRATCH3, super::ADDR_SCRATCH, super::INSTR_SIZE * 2
1914 +
            ));
1915 +
            try emit::emit(e, encode::ebreak());
1916 +
            try emitAddOffset(e, super::SCRATCH3, rsrc, offset as i64);
1917 +
            try emitBlit(e, rdst, super::SCRATCH3, layouts[layout]);
1918 +
        }
1919 +
        case il::Instr::UnionSet { dst, tag, offset, src, layout } => {
1920 +
            let rdst = try getSrcReg(s, e, dst, super::SCRATCH2);
1921 +
            try emit::loadImm(e, super::ADDR_SCRATCH, tag as i64);
1922 +
            try emit::emitStore(e, super::ADDR_SCRATCH, rdst, 0, il::Type::W8);
1923 +
            if let payload = layout {
1924 +
                let rsrc = try resolveVal(s, e, super::SCRATCH1, src);
1925 +
                try emitAddOffset(e, super::SCRATCH2, rdst, offset as i64);
1926 +
                try emitBlit(e, super::SCRATCH2, rsrc, layouts[payload]);
1927 +
            }
1928 +
        }
1847 1929
        case il::Instr::TraitNew { dst, recv, table } => {
1848 1930
            let base = try getSrcReg(s, e, dst, super::SCRATCH2);
1849 1931
            let rr = try getSrcReg(s, e, recv, super::SCRATCH1);
1850 1932
            try emit::emitStore(e, rr, base, TRAIT_RECV_OFFSET, il::Type::W64);
1851 1933
            let rt = try resolveVal(s, e, super::SCRATCH1, table);
lib/std/arch/rv64/tests.rad +98 -0
806 806
        }
807 807
    }
808 808
    try testing::expect(trapped and cleared);
809 809
}
810 810
811 +
/// Number of stores with `funct3` in `code`: 0 for `sb` and 3 for `sd`.
812 +
fn stores(code: *[u32], funct3: u32) -> u32 {
813 +
    let mut count: u32 = 0;
814 +
    for word in code {
815 +
        if (word & 0x7f) == 0x23 and ((word >> 12) & 7) == funct3 {
816 +
            set count += 1;
817 +
        }
818 +
    }
819 +
    return count;
820 +
}
821 +
822 +
/// Number of `ebreak` instructions in `code`.
823 +
fn traps(code: *[u32]) -> u32 {
824 +
    let mut count: u32 = 0;
825 +
    for word in code {
826 +
        if word == encode::ebreak() {
827 +
            set count += 1;
828 +
        }
829 +
    }
830 +
    return count;
831 +
}
832 +
833 +
/// A union read loads the tag byte, compares it with the variant and traps on a mismatch, and
834 +
/// then copies the payload. A union write stores the tag byte, and copies the payload when
835 +
/// there is one.
836 +
@test unsafe fn testUnionSlotAccess() throws (testing::TestError) {
837 +
    let layouts = [il::Layout { size: 8, alignment: 8, slots: &[] }];
838 +
    let get = try generateBody(&layouts[..], nil, &[
839 +
        il::Instr::UnionGet {
840 +
            dst: il::Reg { n: 1 }, src: il::Reg { n: 0 }, tag: 5, offset: 8, layout: 0
841 +
        },
842 +
    ]);
843 +
    // The loads are the tag byte and the payload, and the one store is the payload.
844 +
    try testing::expect(traps(get) == 1 and loads(get, 4) == 1);
845 +
    try testing::expect(loads(get, 3) == 1 and stores(get, 3) == 1 and stores(get, 0) == 0);
846 +
    let written = try generateBody(&layouts[..], nil, &[
847 +
        il::Instr::UnionSet {
848 +
            dst: il::Reg { n: 0 }, tag: 5, offset: 8, src: reg(1), layout: 0
849 +
        },
850 +
    ]);
851 +
    try testing::expect(traps(written) == 0 and stores(written, 0) == 1);
852 +
    try testing::expect(loads(written, 3) == 1 and stores(written, 3) == 1);
853 +
    let bare = try generateBody(&layouts[..], nil, &[
854 +
        il::Instr::UnionSet {
855 +
            dst: il::Reg { n: 0 }, tag: 6, offset: 8, src: il::Val::Undef, layout: nil
856 +
        },
857 +
    ]);
858 +
    try testing::expect(traps(bare) == 0 and stores(bare, 0) == 1);
859 +
    try testing::expect(loads(bare, 3) == 0 and stores(bare, 3) == 0);
860 +
}
861 +
811 862
/// Number of loads with `funct3` in `code`: 2 for `lw` and 6 for `lwu`.
812 863
fn loads(code: *[u32], funct3: u32) -> u32 {
813 864
    let mut count: u32 = 0;
814 865
    for word in code {
815 866
        if (word & 0x7f) == 0x03 and ((word >> 12) & 7) == funct3 {
1702 1753
        );
1703 1754
        assert size == 16 and count == 1;
1704 1755
        assert symbols[0].addr == 24;
1705 1756
    }
1706 1757
}
1758 +
1759 +
/// A constructor initializes a whole union before its first read.
1760 +
@test unsafe fn testUnionConstructionZeroing() throws (testing::TestError) {
1761 +
    let arena = heap::over(&mut REGISTER_SCRATCH[..]);
1762 +
    let mut variants: *mut [il::UnionVariant] = &mut [];
1763 +
    try! variants.append(il::UnionVariant { tag: 0, layout: 0 }, arena);
1764 +
    try! variants.append(il::UnionVariant { tag: 1, layout: nil }, arena);
1765 +
    let mut slots: *mut [il::Slot] = &mut [];
1766 +
    try! slots.append(
1767 +
        il::Slot {
1768 +
            offset: 0,
1769 +
            kind: il::SlotKind::Union {
1770 +
                offset: 8, size: 16, variants: &variants[..]
1771 +
            },
1772 +
        },
1773 +
        arena
1774 +
    );
1775 +
    let table = [
1776 +
        il::Layout { size: 8,  alignment: 8, slots: &[] },
1777 +
        il::Layout { size: 16, alignment: 8, slots: &slots[..] },
1778 +
    ];
1779 +
    let write = il::Instr::UnionSet {
1780 +
        dst: il::Reg { n: 2 }, tag: 1, offset: 8, src: il::Val::Undef, layout: nil
1781 +
    };
1782 +
    assert stores(try generateBody(&table[..], 1, &[write]), 0) == 1;
1783 +
    let read = il::Instr::Load {
1784 +
        typ: il::Type::W8, dst: il::Reg { n: 3 }, src: il::Reg { n: 2 }, offset: 0
1785 +
    };
1786 +
    assert stores(try generateBody(&table[..], 1, &[read, write]), 0) == 2;
1787 +
    let alias = il::Instr::UnionSet {
1788 +
        dst: il::Reg { n: 2 }, tag: 0, offset: 8, src: reg(2), layout: 0
1789 +
    };
1790 +
    assert stores(try generateBody(&table[..], 1, &[alias]), 0) == 2;
1791 +
}
1792 +
1793 +
/// Large frames address the register save area from one common base.
1794 +
@test unsafe fn testLargeFrameRegisterAccess() throws (testing::TestError) {
1795 +
    let arena = heap::over(&mut ASSEMBLY_ARENA_STORAGE[..]);
1796 +
    let tables = try! testLabels(arena);
1797 +
    let mut e = try! rv64::emit::emitter(arena, false, tables);
1798 +
    let frame = try! rv64::emit::computeFrame(4096, 0xff, 0, false);
1799 +
    try! rv64::emit::emitPrologue(&mut e, &frame);
1800 +
    try! rv64::emit::emitEpilogue(&mut e, &frame);
1801 +
    assert stores(&e.code[..], 3) == 9;
1802 +
    assert loads(&e.code[..], 3) == 9;
1803 +
    assert e.code.len <= 32;
1804 +
}
lib/std/lang/il.rad +64 -0
514 514
        /// Address of the slot that receives the object.
515 515
        dst: Reg,
516 516
        /// Address of the slot that holds the object.
517 517
        src: Reg,
518 518
    },
519 +
    /// Read a part of the payload of a union slot: `union.get %dst %src <tag> <offset> $L;`.
520 +
    ///
521 +
    /// `src` addresses a union slot and `dst` addresses an object of layout `L`. The
522 +
    /// instruction traps unless the tag byte of the union is `tag`, and then copies `size L`
523 +
    /// bytes from `src` plus `offset` to `dst`. The variant `tag` of the slot has a payload
524 +
    /// layout, and `offset` is not before the payload. The part is what that layout holds there:
525 +
    /// an object of layout `L`, or a single slot that `L` is made of.
526 +
    UnionGet {
527 +
        /// Address of the object that receives the payload.
528 +
        dst: Reg,
529 +
        /// Address of the union slot.
530 +
        src: Reg,
531 +
        /// Tag of the variant that is read.
532 +
        tag: u32,
533 +
        /// Byte offset of the part in the union.
534 +
        offset: u32,
535 +
        /// Index of the layout of the part in `Program.layouts`.
536 +
        layout: u32,
537 +
    },
538 +
    /// Write a variant into a union slot: `union.set %dst <tag> <offset> <src> $L;`.
539 +
    ///
540 +
    /// `dst` addresses a union slot. The instruction writes the tag byte `tag` and copies
541 +
    /// `size L` bytes from `src` to `dst` plus `offset`. A variant without a payload has `src`
542 +
    /// `undef` and no layout, and leaves the payload bytes as they are.
543 +
    UnionSet {
544 +
        /// Address of the union slot.
545 +
        dst: Reg,
546 +
        /// Tag of the variant that is written.
547 +
        tag: u32,
548 +
        /// Byte offset of the payload in the union.
549 +
        offset: u32,
550 +
        /// Address of the payload, or `undef` for a variant without one.
551 +
        src: Val,
552 +
        /// Index of the layout of the payload in `Program.layouts`, or nil without a payload.
553 +
        layout: ?u32,
554 +
    },
519 555
    /// Call a method of a trait object:
520 556
    /// `trait.call <type> %dst %obj <method> at <receiver>(<arg>...);`.
521 557
    ///
522 558
    /// `obj` addresses a trait object slot. The argument at position `receiver`
523 559
    /// is `undef`; the call passes the receiver of the object there. The
815 851
    isZeroInit: bool,
816 852
    /// Initializer values.
817 853
    values: *[DataValue],
818 854
}
819 855
856 +
/// A variant of a union slot.
857 +
export record UnionVariant: Copy {
858 +
    /// Tag byte that identifies the variant.
859 +
    tag: u32,
860 +
    /// Index of the layout of the payload, or nil for a variant without a payload.
861 +
    layout: ?u32,
862 +
}
863 +
820 864
/// Kind of a pointer-like slot of a layout.
821 865
export union SlotKind: Copy {
822 866
    /// Pointer of 8 bytes. The pointee layout is that of the pointer type.
823 867
    Ptr(PtrType),
824 868
    /// Slice of 16 bytes: a pointer at offset 0, a 32-bit length at offset 8
831 875
    Heap(HeapType),
832 876
    /// Trait object of 16 bytes: the receiver at offset 0 and the address of
833 877
    /// a method table at offset 8. Only `trait.new` writes it, and only a copy
834 878
    /// of the whole slot moves it.
835 879
    Trait(ObjectType),
880 +
    /// Union whose variants do not share one payload layout, of `size` bytes: a tag byte at
881 +
    /// offset 0 and a payload at `offset`. Only `union.set` writes the tag and the payload,
882 +
    /// and only `union.get` or a copy of the whole slot reads them as typed values. A plain
883 +
    /// load of the tag is allowed.
884 +
    Union {
885 +
        /// Byte offset of the payload from the start of the slot.
886 +
        offset: u32,
887 +
        /// Size of the whole union in bytes.
888 +
        size: u32,
889 +
        /// The variants. Their layouts have lower indices than the enclosing layout.
890 +
        variants: *[UnionVariant],
891 +
    },
836 892
    /// Nested object that contains slots, at the offset of the slot. Holds the
837 893
    /// index of its layout, which is lower than the index of the enclosing layout.
838 894
    Sub(u32),
839 895
    /// Run of `count` consecutive objects of a layout that contains slots,
840 896
    /// starting at the offset of the slot. The layout index is lower than the
1097 1153
        }
1098 1154
        case Instr::TraitCopy { dst, src } => {
1099 1155
            visitor.visit(dst);
1100 1156
            visitor.visit(src);
1101 1157
        }
1158 +
        case Instr::UnionGet { dst, src, .. } => {
1159 +
            visitor.visit(dst);
1160 +
            visitor.visit(src);
1161 +
        }
1162 +
        case Instr::UnionSet { dst, src, .. } => {
1163 +
            visitor.visit(dst);
1164 +
            withReg(src, visitor);
1165 +
        }
1102 1166
        case Instr::TraitCall { obj, args, .. } => {
1103 1167
            visitor.visit(obj);
1104 1168
            for arg in argVals(func, args) {
1105 1169
                withReg(arg, visitor);
1106 1170
            }
lib/std/lang/il/binary.rad +8 -0
13 13
14 14
/// Minimum wire bytes in a register and value-type parameter.
15 15
export constant MIN_PARAM_BYTES: u32 = 5;
16 16
/// Minimum wire bytes in a layout slot.
17 17
export constant MIN_SLOT_BYTES: u32 = 9;
18 +
/// Minimum wire bytes in a variant of a union slot.
19 +
export constant MIN_VARIANT_BYTES: u32 = 5;
18 20
/// Minimum wire bytes in a global data record.
19 21
export constant MIN_DATA_BYTES: u32 = 15;
20 22
/// Minimum wire bytes in a repeated data value.
21 23
export constant MIN_DATA_VALUE_BYTES: u32 = 5;
22 24
/// Minimum wire bytes in a function record.
130 132
export constant SLOT_ARRAY: u8 = 4;
131 133
/// Wire tag for slot kind Trait.
132 134
export constant SLOT_TRAIT: u8 = 5;
133 135
/// Wire tag for slot kind Heap.
134 136
export constant SLOT_HEAP: u8 = 6;
137 +
/// Wire tag for slot kind Union.
138 +
export constant SLOT_UNION: u8 = 7;
135 139
136 140
/// Heap type flag: the heap can provide elements that have slots.
137 141
export constant HEAP_TYPED: u8 = 1;
138 142
/// Heap type flag: the heap can be reset. A heap never has both flags.
139 143
export constant HEAP_RESET: u8 = 2;
175 179
export constant INSTR_SLICE_GROW: u8 = 35;
176 180
/// Wire tag for instruction PageHeap.
177 181
export constant INSTR_PAGE_HEAP: u8 = 36;
178 182
/// Wire tag for instruction HeapReset.
179 183
export constant INSTR_HEAP_RESET: u8 = 37;
184 +
/// Wire tag for instruction UnionGet.
185 +
export constant INSTR_UNION_GET: u8 = 38;
186 +
/// Wire tag for instruction UnionSet.
187 +
export constant INSTR_UNION_SET: u8 = 39;
180 188
181 189
/// Wire tag for data Val.
182 190
export constant DATA_VAL: u8 = 0;
183 191
/// Wire tag for data Sym.
184 192
export constant DATA_SYM: u8 = 1;
lib/std/lang/il/binary/collect.rad +2 -0
185 185
        case il::Instr::SliceLen { length, .. } => try value(names, owner, length, a),
186 186
        case il::Instr::Elem { index, .. }      => try value(names, owner, index, a),
187 187
        case il::Instr::SliceElem { index, .. } => try value(names, owner, index, a),
188 188
        case il::Instr::StorePtr { src, .. }    => try value(names, owner, src, a),
189 189
        case il::Instr::TraitNew { table, .. }  => try value(names, owner, table, a),
190 +
        case il::Instr::UnionSet { src, .. }    => try value(names, owner, src, a),
190 191
        case il::Instr::TraitCall { args, .. } =>
191 192
            try values(names, owner, il::argVals(func, args), a),
192 193
        case
193 194
            il::Instr::Field { .. },
194 195
            il::Instr::TraitCopy { .. },
196 +
            il::Instr::UnionGet { .. },
195 197
            il::Instr::SliceCopy { .. },
196 198
            il::Instr::LoadPtr { .. },
197 199
            il::Instr::Reserve { .. },
198 200
            il::Instr::Blit { .. },
199 201
            il::Instr::Load { .. },
lib/std/lang/il/binary/program.rad +32 -0
243 243
                    set kind = il::SlotKind::Trait(il::ObjectType {
244 244
                        iface, own: rights.own, mutable: rights.mutable
245 245
                    });
246 246
                    set width = 16;
247 247
                }
248 +
                case binary::SLOT_UNION => {
249 +
                    let payload = try reader::integer(input, wire, 4) as u32;
250 +
                    let unionSize = try reader::integer(input, wire, 4) as u32;
251 +
                    let variantCount = try reader::count(input, wire, binary::MIN_VARIANT_BYTES);
252 +
                    let mut variants: *mut [il::UnionVariant] = &mut [];
253 +
                    try variants.reserve(variantCount, a) catch {
254 +
                        throw binary::Error::Storage;
255 +
                    };
256 +
                    // The slot is as aligned as its payloads.
257 +
                    set slotAlignment = 1;
258 +
                    for _ in 0 .. variantCount {
259 +
                        let variantTag = try reader::integer(input, wire, 4) as u32;
260 +
                        let variantLayout = try reader::optionalLayoutIndex(input, wire);
261 +
                        if let payloadLayout = variantLayout {
262 +
                            if payloadLayout >= i {
263 +
                                throw binary::Error::Invalid;
264 +
                            }
265 +
                            if items[payloadLayout].alignment > slotAlignment {
266 +
                                set slotAlignment = items[payloadLayout].alignment;
267 +
                            }
268 +
                        }
269 +
                        try variants.append(
270 +
                            il::UnionVariant { tag: variantTag, layout: variantLayout }, a
271 +
                        ) catch {
272 +
                            throw binary::Error::Storage;
273 +
                        };
274 +
                    }
275 +
                    set kind = il::SlotKind::Union {
276 +
                        offset: payload, size: unionSize, variants: &variants[..]
277 +
                    };
278 +
                    set width = unionSize as u64;
279 +
                }
248 280
                case binary::SLOT_SUB => {
249 281
                    let sub = try reader::integer(input, wire, 4) as u32;
250 282
                    if sub >= i {
251 283
                        throw binary::Error::Invalid;
252 284
                    }
lib/std/lang/il/binary/reader.rad +28 -0
126 126
        throw binary::Error::Invalid;
127 127
    }
128 128
    return n;
129 129
}
130 130
131 +
/// Read an optional layout table index within the package.
132 +
export fn optionalLayoutIndex(input: &mut Reader, wire: &[u8]) -> ?u32 throws (binary::Error) {
133 +
    if try flag(input, wire) {
134 +
        return try layoutIndex(input, wire);
135 +
    }
136 +
    return nil;
137 +
}
138 +
131 139
/// Read a signature table index within the package.
132 140
export fn signatureIndex(input: &mut Reader, wire: &[u8]) -> u32 throws (binary::Error) {
133 141
    let n = try integer(input, wire, 4) as u32;
134 142
    if n >= input.signatures {
135 143
        throw binary::Error::Invalid;
581 589
        case super::INSTR_TRAIT_COPY => {
582 590
            let vdst = try reg(input, wire);
583 591
            let vsrc = try reg(input, wire);
584 592
            return il::Instr::TraitCopy { dst: vdst, src: vsrc };
585 593
        }
594 +
        case super::INSTR_UNION_GET => {
595 +
            let vdst = try reg(input, wire);
596 +
            let vsrc = try reg(input, wire);
597 +
            let vtag = try integer(input, wire, 4) as u32;
598 +
            let voffset = try integer(input, wire, 4) as u32;
599 +
            let vlayout = try layoutIndex(input, wire);
600 +
            return il::Instr::UnionGet {
601 +
                dst: vdst, src: vsrc, tag: vtag, offset: voffset, layout: vlayout
602 +
            };
603 +
        }
604 +
        case super::INSTR_UNION_SET => {
605 +
            let vdst = try reg(input, wire);
606 +
            let vtag = try integer(input, wire, 4) as u32;
607 +
            let voffset = try integer(input, wire, 4) as u32;
608 +
            let vsrc = try val(input, wire);
609 +
            let vlayout = try optionalLayoutIndex(input, wire);
610 +
            return il::Instr::UnionSet {
611 +
                dst: vdst, tag: vtag, offset: voffset, src: vsrc, layout: vlayout
612 +
            };
613 +
        }
586 614
        case super::INSTR_TRAIT_CALL => {
587 615
            let vretTy = try valType(input, wire);
588 616
            let mut vdst: ?il::Reg = nil;
589 617
            if try flag(input, wire) {
590 618
                set vdst = try reg(input, wire);
lib/std/lang/il/binary/tests.rad +44 -0
324 324
        args: ONE_ARG,
325 325
    }, &[30, 1, 8, 1, 3, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 4]);
326 326
    try instruction(il::Instr::TraitCopy {
327 327
        dst: il::Reg { n: 1 }, src: il::Reg { n: 2 }
328 328
    }, &[31, 1, 0, 0, 0, 2, 0, 0, 0]);
329 +
    try instruction(il::Instr::UnionGet {
330 +
        dst: il::Reg { n: 1 }, src: il::Reg { n: 2 }, tag: 3, offset: 8, layout: 3
331 +
    }, &[38, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 8, 0, 0, 0, 3, 0, 0, 0]);
332 +
    try instruction(il::Instr::UnionSet {
333 +
        dst: il::Reg { n: 1 }, tag: 3, offset: 8, src: il::Val::Reg(il::Reg { n: 2 }), layout: 3
334 +
    }, &[39, 1, 0, 0, 0, 3, 0, 0, 0, 8, 0, 0, 0, 0, 2, 0, 0, 0, 1, 3, 0, 0, 0]);
335 +
    try instruction(il::Instr::UnionSet {
336 +
        dst: il::Reg { n: 1 }, tag: 2, offset: 8, src: il::Val::Undef, layout: nil
337 +
    }, &[39, 1, 0, 0, 0, 2, 0, 0, 0, 8, 0, 0, 0, 4, 0]);
329 338
    try instruction(il::Instr::Ebreak, &[17]);
330 339
    try instruction(il::Instr::MemoryFence, &[18]);
331 340
    for typ in [il::Type::W8, il::Type::W16, il::Type::W32, il::Type::W64] {
332 341
        let mut read: [u8; 8] = [19, 0, 1, 0, 0, 0, 4, 4];
333 342
        let mut write: [u8; 5] = [20, 0, 4, 4, 4];
690 699
    }) catch {
691 700
        throw testing::TestError::Failed;
692 701
    };
693 702
    try testing::expectBytesEq(&buffer[.. out.offset], &[2, 0, 0, 0, 1, 4, 3, 1, 0, 0, 0, 0]);
694 703
}
704 +
705 +
/// Check the wire form of a layout with a union slot.
706 +
@test unsafe fn unionSlotWire() throws (testing::TestError) {
707 +
    static buffer: [u8; 64] = [0; 64];
708 +
    let mut out = writer::new(&mut buffer[..] as *mut [u8], &[]);
709 +
    let layout = il::Layout {
710 +
        size: 16,
711 +
        alignment: 8,
712 +
        slots: &[
713 +
            il::Slot {
714 +
                offset: 0,
715 +
                kind: il::SlotKind::Union {
716 +
                    offset: 8,
717 +
                    size: 16,
718 +
                    variants: &[
719 +
                        il::UnionVariant { tag: 0, layout: 1 },
720 +
                        il::UnionVariant { tag: 2, layout: nil },
721 +
                    ],
722 +
                },
723 +
            },
724 +
        ],
725 +
    };
726 +
    try writer::layout(&mut out, layout) catch {
727 +
        throw testing::TestError::Failed;
728 +
    };
729 +
    try testing::expectBytesEq(
730 +
        &buffer[.. out.offset],
731 +
        &[
732 +
            16, 0, 0, 0, 8, 0, 0, 0, 1, 0, 0, 0,
733 +
            0, 0, 0, 0, 7, 8, 0, 0, 0, 16, 0, 0, 0, 2, 0, 0, 0,
734 +
            0, 0, 0, 0, 1, 1, 0, 0, 0,
735 +
            2, 0, 0, 0, 0,
736 +
        ]
737 +
    );
738 +
}
lib/std/lang/il/binary/tests/decode.rad +86 -0
1237 1237
            try testing::expect(pred == expectedPreds[i][j]);
1238 1238
        }
1239 1239
        try testing::expect(block.loopDepth == expectedDepth[i]);
1240 1240
    }
1241 1241
}
1242 +
1243 +
/// Storage for the layouts of the union tests.
1244 +
static UNION_STORAGE: [u8; 4096] = [0; 4096];
1245 +
1246 +
/// A layout of `size` bytes with `alignment` that has a union slot at offset 0, with its payload
1247 +
/// at `payload`, of `width` bytes, and the given variants. Its slices live in `a`.
1248 +
unsafe fn unionLayout(
1249 +
    a: &heap::Heap,
1250 +
    size: u32,
1251 +
    alignment: u32,
1252 +
    payload: u32,
1253 +
    width: u32,
1254 +
    variants: &[il::UnionVariant]
1255 +
) -> il::Layout {
1256 +
    let mut own: *mut [il::UnionVariant] = &mut [];
1257 +
    try! own.extend(variants, a);
1258 +
    let mut slots: *mut [il::Slot] = &mut [];
1259 +
    try! slots.append(
1260 +
        il::Slot {
1261 +
            offset: 0,
1262 +
            kind: il::SlotKind::Union { offset: payload, size: width, variants: &own[..] },
1263 +
        },
1264 +
        a
1265 +
    );
1266 +
    return il::Layout { size, alignment, slots: &slots[..] };
1267 +
}
1268 +
1269 +
/// The layouts of `items` as a table. Its slice lives in `a`.
1270 +
unsafe fn table(a: &heap::Heap, items: &[il::Layout]) -> *[il::Layout] {
1271 +
    let mut own: *mut [il::Layout] = &mut [];
1272 +
    try! own.extend(items, a);
1273 +
    return &own[..];
1274 +
}
1275 +
1276 +
/// Check that union slots survive encoding, and that the decoder rejects variant layouts
1277 +
/// that do not precede the layout, and slots that do not fit or are not aligned.
1278 +
@test unsafe fn unionPackage() throws (testing::TestError) {
1279 +
    let a = heap::over(&mut UNION_STORAGE[..]);
1280 +
    let layouts = table(
1281 +
        a,
1282 +
        &[
1283 +
            PLAIN,
1284 +
            PTR_LAYOUT,
1285 +
            unionLayout(
1286 +
                a,
1287 +
                16,
1288 +
                8,
1289 +
                8,
1290 +
                16,
1291 +
                &[
1292 +
                    il::UnionVariant { tag: 0, layout: 1 },
1293 +
                    il::UnionVariant { tag: 1, layout: 0 },
1294 +
                    il::UnionVariant { tag: 9, layout: nil },
1295 +
                ]
1296 +
            ),
1297 +
        ]
1298 +
    );
1299 +
    let ok = binary::Package {
1300 +
        symbols: &["p"],
1301 +
        name: "p",
1302 +
        dependencies: &[],
1303 +
        exports: &[],
1304 +
        entry: nil,
1305 +
        program: il::Program {
1306 +
            data: &[], fns: &[], layouts, signatures: &[], traits: &[]
1307 +
        },
1308 +
    };
1309 +
    try roundTrip(&ok);
1310 +
    let arena = heap::over(&mut MEMORY[..]);
1311 +
    let decoded = try reencoded(&ok, arena);
1312 +
    let case il::SlotKind::Union { offset, size, variants } =
1313 +
        decoded.program.layouts[2].slots[0].kind else throw testing::TestError::Failed;
1314 +
    try testing::expect(offset == 8 and size == 16 and variants.len == 3);
1315 +
    try testing::expect(variants[0] == il::UnionVariant { tag: 0, layout: 1 });
1316 +
    try testing::expect(variants[1] == il::UnionVariant { tag: 1, layout: 0 });
1317 +
    try testing::expect(variants[2] == il::UnionVariant { tag: 9, layout: nil });
1318 +
    // A variant layout precedes the layout of the slot, and exists.
1319 +
    let own = &[il::UnionVariant { tag: 0, layout: 1 }];
1320 +
    try rejectedLayouts(table(a, &[PLAIN, unionLayout(a, 16, 8, 8, 16, own)]), &[]);
1321 +
    let missing = &[il::UnionVariant { tag: 0, layout: 2 }];
1322 +
    try rejectedLayouts(table(a, &[PLAIN, unionLayout(a, 16, 8, 8, 16, missing)]), &[]);
1323 +
    // The slot lies within the layout, and is as aligned as its payloads.
1324 +
    let first = &[il::UnionVariant { tag: 0, layout: 0 }];
1325 +
    try rejectedLayouts(table(a, &[PLAIN, unionLayout(a, 8, 8, 4, 16, first)]), &[]);
1326 +
    try rejectedLayouts(table(a, &[PLAIN, unionLayout(a, 16, 4, 8, 16, first)]), &[]);
1327 +
}
lib/std/lang/il/binary/writer.rad +36 -0
168 168
            case il::SlotKind::Trait(object) => {
169 169
                try integer(out, super::SLOT_TRAIT as u64, 1);
170 170
                try integer(out, object.iface as u64, 4);
171 171
                try rights(out, object.own, object.mutable);
172 172
            }
173 +
            case il::SlotKind::Union { offset, size, variants } => {
174 +
                try integer(out, super::SLOT_UNION as u64, 1);
175 +
                try integer(out, offset as u64, 4);
176 +
                try integer(out, size as u64, 4);
177 +
                try integer(out, variants.len as u64, 4);
178 +
                for variant in variants {
179 +
                    try integer(out, variant.tag as u64, 4);
180 +
                    try optionalIndex(out, variant.layout);
181 +
                }
182 +
            }
173 183
            case il::SlotKind::Sub(sub) => {
174 184
                try integer(out, super::SLOT_SUB as u64, 1);
175 185
                try integer(out, sub as u64, 4);
176 186
            }
177 187
            case il::SlotKind::Array { layout: element, count } => {
181 191
            }
182 192
        }
183 193
    }
184 194
}
185 195
196 +
/// Write an optional table index: a presence byte, then the index when present.
197 +
fn optionalIndex(out: &mut Writer, index: ?u32) throws (binary::Error) {
198 +
    if let present = index {
199 +
        try integer(out, 1, 1);
200 +
        try integer(out, present as u64, 4);
201 +
    } else {
202 +
        try integer(out, 0, 1);
203 +
    }
204 +
}
205 +
186 206
/// Write the rights of a receiver as pointer type flags.
187 207
fn rights(out: &mut Writer, own: bool, mutable: bool) throws (binary::Error) {
188 208
    let mut flags: u8 = 0;
189 209
    if own {
190 210
        set flags |= super::PTR_OWN;
561 581
        case il::Instr::TraitCopy { dst: vdst, src: vsrc } => {
562 582
            try integer(out, super::INSTR_TRAIT_COPY as u64, 1);
563 583
            try integer(out, vdst.n as u64, 4);
564 584
            try integer(out, vsrc.n as u64, 4);
565 585
        }
586 +
        case il::Instr::UnionGet { dst: vdst, src: vsrc, tag, offset, layout: vlayout } => {
587 +
            try integer(out, super::INSTR_UNION_GET as u64, 1);
588 +
            try integer(out, vdst.n as u64, 4);
589 +
            try integer(out, vsrc.n as u64, 4);
590 +
            try integer(out, tag as u64, 4);
591 +
            try integer(out, offset as u64, 4);
592 +
            try integer(out, vlayout as u64, 4);
593 +
        }
594 +
        case il::Instr::UnionSet { dst: vdst, tag, offset, src: vsrc, layout: vlayout } => {
595 +
            try integer(out, super::INSTR_UNION_SET as u64, 1);
596 +
            try integer(out, vdst.n as u64, 4);
597 +
            try integer(out, tag as u64, 4);
598 +
            try integer(out, offset as u64, 4);
599 +
            try val(out, vsrc);
600 +
            try optionalIndex(out, vlayout);
601 +
        }
566 602
        case il::Instr::TraitCall {
567 603
            retTy: vretTy, dst: vdst, obj: vobj, method: vmethod, receiver: vreceiver, args: vargs
568 604
        } => {
569 605
            try integer(out, super::INSTR_TRAIT_CALL as u64, 1);
570 606
            try valType(out, vretTy);
lib/std/lang/il/printer.rad +42 -0
376 376
            out.write("trait.copy ");
377 377
            writeReg(out, dst);
378 378
            out.write(" ");
379 379
            writeReg(out, src);
380 380
        }
381 +
        case super::Instr::UnionGet { dst, src, tag, offset, layout } => {
382 +
            out.write("union.get ");
383 +
            writeReg(out, dst);
384 +
            out.write(" ");
385 +
            writeReg(out, src);
386 +
            out.write(" ");
387 +
            sexpr::writeI64(out, tag as i64);
388 +
            out.write(" ");
389 +
            sexpr::writeI64(out, offset as i64);
390 +
            out.write(" ");
391 +
            writeIndex(out, "L", layout);
392 +
        }
393 +
        case super::Instr::UnionSet { dst, tag, offset, src, layout } => {
394 +
            out.write("union.set ");
395 +
            writeReg(out, dst);
396 +
            out.write(" ");
397 +
            sexpr::writeI64(out, tag as i64);
398 +
            out.write(" ");
399 +
            sexpr::writeI64(out, offset as i64);
400 +
            out.write(" ");
401 +
            writeVal(out, src);
402 +
            if let l = layout {
403 +
                out.write(" ");
404 +
                writeIndex(out, "L", l);
405 +
            }
406 +
        }
381 407
        case super::Instr::TraitCall { retTy, dst, obj, method, receiver, args } => {
382 408
            out.write("trait.call ");
383 409
            writeValType(out, retTy);
384 410
            out.write(" ");
385 411
            if let d = dst {
743 769
            out.write("trait ");
744 770
            out.write("own " if object.own else "ref ");
745 771
            out.write("mut " if object.mutable else "const ");
746 772
            writeIndex(out, "T", object.iface);
747 773
        }
774 +
        case super::SlotKind::Union { offset, size, variants } => {
775 +
            out.write("union offset ");
776 +
            sexpr::writeI64(out, offset as i64);
777 +
            out.write(" size ");
778 +
            sexpr::writeI64(out, size as i64);
779 +
            for variant in variants {
780 +
                out.write(" ");
781 +
                sexpr::writeI64(out, variant.tag as i64);
782 +
                out.write(":");
783 +
                if let layout = variant.layout {
784 +
                    writeIndex(out, "L", layout);
785 +
                } else {
786 +
                    out.write("void");
787 +
                }
788 +
            }
789 +
        }
748 790
        case super::SlotKind::Sub(layout) => {
749 791
            out.write("sub ");
750 792
            writeIndex(out, "L", layout);
751 793
        }
752 794
        case super::SlotKind::Array { layout, count } => {
lib/std/lang/il/printer/tests.rad +43 -1
309 309
                },
310 310
                il::Slot { offset: 16, kind: il::SlotKind::Sub(1) },
311 311
                il::Slot { offset: 32, kind: il::SlotKind::Array { layout: 1, count: 2 } },
312 312
            ],
313 313
        },
314 +
        il::Layout {
315 +
            size: 16,
316 +
            alignment: 8,
317 +
            slots: &[
318 +
                il::Slot {
319 +
                    offset: 0,
320 +
                    kind: il::SlotKind::Union {
321 +
                        offset: 8,
322 +
                        size: 16,
323 +
                        variants: &[
324 +
                            il::UnionVariant { tag: 0, layout: 1 },
325 +
                            il::UnionVariant { tag: 2, layout: nil },
326 +
                        ],
327 +
                    },
328 +
                },
329 +
            ],
330 +
        },
314 331
    ];
315 332
    let signatures = [
316 333
        il::Signature { params: &[], ret: il::ValType::Void },
317 334
        il::Signature {
318 335
            params: &[
337 354
        &[
338 355
            "layout $L0 size 1 align 1 {}\n",
339 356
            "layout $L1 size 16 align 8 {\n    slot 0 ptr own mut $L0;\n    slot 8 fn $S1;\n}\n",
340 357
            "layout $L2 size 64 align 8 {\n",
341 358
            "    slot 0 slice ref const $L0;\n    slot 16 sub $L1;\n    slot 32 array $L1 2;\n}\n",
359 +
            "layout $L3 size 16 align 8 {\n    slot 0 union offset 8 size 16 0:$L1 2:void;\n}\n",
342 360
            "\nsignature $S0 () -> void;\n",
343 361
            "signature $S1 (w8, ptr ref mut $L2, ptr own const nullable $L1, fn $S0)",
344 362
            " -> ptr own const nullable $L0;\n",
345 363
        ]
346 364
    );
597 615
        il::Instr::PageHeap {
598 616
            err: il::Reg { n: 7 }, slot: il::Reg { n: 8 }, handle: il::Val::Reg(il::Reg { n: 0 })
599 617
        },
600 618
        a
601 619
    );
620 +
    try! instrs.append(
621 +
        il::Instr::UnionGet {
622 +
            dst: il::Reg { n: 9 }, src: il::Reg { n: 0 }, tag: 3, offset: 8, layout: 2
623 +
        },
624 +
        a
625 +
    );
626 +
    try! instrs.append(
627 +
        il::Instr::UnionSet {
628 +
            dst: il::Reg { n: 0 },
629 +
            tag: 3,
630 +
            offset: 8,
631 +
            src: il::Val::Reg(il::Reg { n: 9 }),
632 +
            layout: 2,
633 +
        },
634 +
        a
635 +
    );
636 +
    try! instrs.append(
637 +
        il::Instr::UnionSet {
638 +
            dst: il::Reg { n: 0 }, tag: 4, offset: 8, src: il::Val::Undef, layout: nil
639 +
        },
640 +
        a
641 +
    );
602 642
    try! instrs.append(il::Instr::HeapReset { heap: il::Val::Reg(il::Reg { n: 0 }) }, a);
603 643
    try! instrs.append(il::Instr::Ret { val: nil }, a);
604 644
    let mut blocks: *mut [il::Block] = &mut [];
605 645
    try! blocks.append(
606 646
        il::Block {
633 673
        &TABLES[.. out.pos],
634 674
        &[
635 675
            "fn void $f() {\n  @entry0\n",
636 676
            "    ecall %1 44 %0 0 0 0 buf %2 16;\n    ecall %3 1 0 0 0 0;\n",
637 677
            "    page.slice %4 %5 %0 write $L2;\n    page.slice %6 %5 0 read $L2;\n",
638 -
            "    page.heap %7 %8 %0;\n    heap.reset %0;\n    ret;\n}\n",
678 +
            "    page.heap %7 %8 %0;\n    union.get %9 %0 3 8 $L2;\n",
679 +
            "    union.set %0 3 8 %9 $L2;\n    union.set %0 4 8 undefined;\n",
680 +
            "    heap.reset %0;\n    ret;\n}\n",
639 681
        ]
640 682
    );
641 683
}
lib/std/lang/il/verify.rad +92 -13
977 977
        case il::SlotKind::Heap(want) => try assignState(v, val, s, il::ValType::Heap(want)),
978 978
        else                          => throw fail(v, Rule::Slot),
979 979
    }
980 980
}
981 981
982 -
/// Check a copy of an object of layout `l`. The source holds such an object. The destination
983 -
/// is a plain region, which takes any bytes, or holds such an object, and then a copy of
984 -
/// borrowed slots stays in the frame. Both regions are aligned for `l`.
985 -
fn checkBlit(v: &Verifier, dst: il::Reg, src: il::Reg, l: u32) throws (Error) {
982 +
/// Check that a writable pointer `d` can receive an object of layout `l`, which a copy
983 +
/// writes. The destination is a plain region, which takes any bytes, or holds such an
984 +
/// object, and then a copy of borrowed slots stays in the frame. Both regions are aligned
985 +
/// for `l`.
986 +
fn checkCopyTo(v: &Verifier, d: PtrState, l: u32) throws (Error) {
986 987
    let t = &v.ctx.table;
987 -
    let d = try writable(v, dst);
988 -
    let s = try accessible(v, src);
989 988
    let size = layout::size(t, l);
990 989
    let od = try extent(v, d, 0, size);
991 -
    let os = try extent(v, s, 0, size);
992 -
    if not layout::view(t, s.layout, os, l) {
993 -
        throw fail(v, Rule::View);
994 -
    }
995 990
    if layout::plainRegion(t, d.layout, od, size, layout::alignment(t, l)) {
996 991
        return;
997 992
    }
998 993
    if not layout::view(t, d.layout, od, l) {
999 994
        throw fail(v, Rule::View);
1001 996
    if t.infos[l].refs and not d.local {
1002 997
        throw fail(v, Rule::Class);
1003 998
    }
1004 999
}
1005 1000
1001 +
/// Check that a pointer `s` addresses an object of layout `l`, which a copy reads.
1002 +
fn checkCopyFrom(v: &Verifier, s: PtrState, l: u32) throws (Error) {
1003 +
    let t = &v.ctx.table;
1004 +
    let os = try extent(v, s, 0, layout::size(t, l));
1005 +
    if not layout::view(t, s.layout, os, l) {
1006 +
        throw fail(v, Rule::View);
1007 +
    }
1008 +
}
1009 +
1010 +
/// Check a copy of an object of layout `l`. The source holds such an object, and the
1011 +
/// destination can receive one.
1012 +
fn checkBlit(v: &Verifier, dst: il::Reg, src: il::Reg, l: u32) throws (Error) {
1013 +
    let d = try writable(v, dst);
1014 +
    try checkCopyFrom(v, try accessible(v, src), l);
1015 +
    try checkCopyTo(v, d, l);
1016 +
}
1017 +
1018 +
/// A variant found in a union slot, with the byte offset of the payload in the slot.
1019 +
record UnionPart: Copy {
1020 +
    /// Byte offset of the payload from the start of the slot.
1021 +
    payload: u32,
1022 +
    /// The variant.
1023 +
    variant: il::UnionVariant,
1024 +
}
1025 +
1026 +
/// Find variant `tag` of the union slot that a pointer addresses.
1027 +
fn unionVariant(v: &Verifier, p: PtrState, tag: u32) -> UnionPart throws (Error) {
1028 +
    let o = try extent(v, p, 0, 0);
1029 +
    let case il::SlotKind::Union { offset: payload, variants, .. } = layout::slotAt(
1030 +
        &v.ctx.table, p.layout, o
1031 +
    ) else {
1032 +
        throw fail(v, Rule::Slot);
1033 +
    };
1034 +
    let variant = layout::variantWith(variants, tag as u64) else throw fail(v, Rule::View);
1035 +
    return UnionPart { payload, variant };
1036 +
}
1037 +
1038 +
/// Check a read of a part of the payload of a union slot into an object of layout `l`. The tag
1039 +
/// check is part of the instruction, so the part is the one that the layout of the variant has
1040 +
/// at `offset`.
1041 +
fn checkUnionGet(
1042 +
    v: &Verifier, dst: il::Reg, src: il::Reg, tag: u32, offset: u32, l: u32
1043 +
) throws (Error) {
1044 +
    let d = try writable(v, dst);
1045 +
    let found = try unionVariant(v, try accessible(v, src), tag);
1046 +
    let payload = found.variant.layout else throw fail(v, Rule::View);
1047 +
    if offset < found.payload or not layout::holds(
1048 +
        &v.ctx.table, payload, (offset - found.payload) as u64, l
1049 +
    )
1050 +
    {
1051 +
        throw fail(v, Rule::View);
1052 +
    }
1053 +
    try checkCopyTo(v, d, l);
1054 +
}
1055 +
1056 +
/// Check a write of a variant into a union slot. The tag and the payload are written
1057 +
/// together, so a slot never holds the payload of another variant.
1058 +
fn checkUnionSet(
1059 +
    v: &Verifier, dst: il::Reg, tag: u32, offset: u32, src: il::Val, l: ?u32
1060 +
) throws (Error) {
1061 +
    let d = try writable(v, dst);
1062 +
    let found = try unionVariant(v, d, tag);
1063 +
    if offset <> found.payload or found.variant.layout <> l {
1064 +
        throw fail(v, Rule::View);
1065 +
    }
1066 +
    let payload = found.variant.layout else {
1067 +
        let case il::Val::Undef = src else {
1068 +
            throw fail(v, Rule::Type);
1069 +
        };
1070 +
        return;
1071 +
    };
1072 +
    let case il::Val::Reg(r) = src else {
1073 +
        throw fail(v, Rule::Type);
1074 +
    };
1075 +
    try checkCopyFrom(v, try accessible(v, r), payload);
1076 +
    if v.ctx.table.infos[payload].refs and not d.local {
1077 +
        throw fail(v, Rule::Class);
1078 +
    }
1079 +
}
1080 +
1006 1081
/// Check a call, and define its result.
1007 1082
fn checkCall(
1008 1083
    v: &mut Verifier, retTy: il::ValType, dst: ?il::Reg, callee: il::Val, args: il::ArgRange
1009 1084
) throws (Error) {
1010 1085
    let case RegState::Fn(f) = try operand(v, callee) else {
1229 1304
            try checkTraitNew(v, dst, recv, table);
1230 1305
        }
1231 1306
        case il::Instr::TraitCopy { dst, src } => {
1232 1307
            try checkTraitCopy(v, dst, src);
1233 1308
        }
1309 +
        case il::Instr::UnionGet { dst, src, tag, offset, layout } => {
1310 +
            try checkUnionGet(v, dst, src, tag, offset, layout);
1311 +
        }
1312 +
        case il::Instr::UnionSet { dst, tag, offset, src, layout } => {
1313 +
            try checkUnionSet(v, dst, tag, offset, src, layout);
1314 +
        }
1234 1315
        case il::Instr::TraitCall { retTy, dst, obj, method, receiver, args } => {
1235 1316
            try checkTraitCall(v, retTy, dst, obj, method, receiver, args);
1236 1317
        }
1237 1318
        case il::Instr::BinOp { dst, a, b, .. } => {
1238 1319
            try operand(v, a);
1445 1526
    return c;
1446 1527
}
1447 1528
1448 1529
/// Check data, function declarations and function bodies.
1449 1530
fn finish(c: Context, a: &heap::Heap) throws (Error) {
1450 -
    for i in 0 .. c.prog.data.len {
1451 -
        try data::check(&c, i);
1452 -
    }
1531 +
    try data::check(&c, a);
1453 1532
    let sizes = try measure(&c);
1454 1533
    if c.prog.fns.len == 0 {
1455 1534
        return;
1456 1535
    }
1457 1536
    let mut defs: *mut [Def] = &mut [];
lib/std/lang/il/verify/data.rad +174 -82
1 1
//! Data initializer checks of the RIL verifier.
2 2
//!
3 3
//! Static memory starts as the initializer says, and every byte that the initializer
4 4
//! leaves out or marks undefined is zero. Pointer and function slots may start as zero
5 -
//! or hold the address of a symbol that fits the slot. Trait object slots start as zero.
6 -
//! Bytes outside slots are free.
5 +
//! or hold the address of a symbol that fits the slot. Trait object slots start as zero. A union
6 +
//! slot holds the tag of one of its variants and a payload that fits the layout of that variant,
7 +
//! including unions nested in a payload. Bytes outside slots are free.
7 8
8 9
use std::collections::dict;
9 10
use std::lang::il;
10 11
use std::lang::il::verify;
11 12
use std::lang::il::verify::layout;
12 13
use std::mem;
14 +
use std::mem::heap;
13 15
14 16
/// Offset of the length within a slice slot.
15 17
constant SLICE_LEN: u64 = 8;
16 18
/// Byte offset of the capacity in a slice slot.
17 19
constant SLICE_CAP: u64 = 12;
24 26
    target: u32,
25 27
    /// Length that the slice has, which its capacity must equal. Zero until the length item.
26 28
    len: u64,
27 29
}
28 30
31 +
/// The tag byte of the last union slot that the initializer reached.
32 +
record UnionTag: Copy {
33 +
    /// Byte offset of the union slot in the data.
34 +
    start: u64,
35 +
    /// Tag byte of the union.
36 +
    tag: u64,
37 +
}
38 +
39 +
/// What the initializer has said about the slots that it passed.
40 +
record Live {
41 +
    /// The slice slot whose capacity is not checked.
42 +
    pending: ?Pending,
43 +
    /// The last union slot at each payload nesting level.
44 +
    tags: *mut [?UnionTag],
45 +
}
46 +
29 47
/// Build the error for a rule violation in data `index`.
30 48
fn fail(index: u32, rule: verify::Rule) -> verify::Error {
31 49
    return verify::Error { rule, place: verify::Place::Data(index) };
32 50
}
33 51
48 66
        case il::DataItem::Undef           => return true,
49 67
        else                               => return false,
50 68
    }
51 69
}
52 70
53 -
/// Check one repetition of an item that starts at `pos` and may touch a slot. `symbol` is
54 -
/// the index of the data definition or function that a symbol item names.
71 +
/// Check one repetition of an item at byte `pos` of data `index`, including
72 +
/// slots in nested payload layouts. Each nested layout has a byte offset from
73 +
/// the start of the data. `symbol` is the index of the data definition or
74 +
/// function that a symbol item names.
55 75
fn atom(
56 76
    c: &verify::Context,
57 77
    index: u32,
58 78
    pos: u64,
59 79
    item: il::DataItem,
60 80
    symbol: u32,
61 -
    pending: &mut ?Pending
81 +
    live: &mut Live
62 82
) throws (verify::Error) {
63 83
    let t = &c.table;
64 -
    let layoutIndex = c.prog.data[index].layout;
65 -
    let end = pos + width(item);
84 +
    let zero = isZero(item);
85 +
    let mut l = c.prog.data[index].layout;
86 +
    let mut base: u64 = 0;
87 +
    let mut pos = pos;
88 +
    // Payload nesting level of the current layout.
89 +
    let mut depth: u32 = 0;
66 90
    // A nonzero length needs an explicit capacity of the same value.
67 -
    if isZero(item) {
68 -
        if let last = *pending; last.len <> 0 {
91 +
    if zero {
92 +
        if let last = live.pending; last.len <> 0 {
69 93
            throw fail(index, verify::Rule::Data);
70 94
        }
71 95
    }
72 -
    let leaf = layout::leafAround(t, layoutIndex, pos) else {
73 -
        // The item starts in plain bytes, and must not run into a slot.
74 -
        if not layout::plain(t, layoutIndex, pos, end) {
75 -
            throw fail(index, verify::Rule::Data);
76 -
        }
77 -
        return;
78 -
    };
79 -
    if end > leaf.start + layout::slotWidth(t, leaf.kind) {
80 -
        throw fail(index, verify::Rule::Data);
81 -
    }
82 -
    if isZero(item) {
83 -
        return;
84 -
    }
85 -
    match leaf.kind {
86 -
        case il::SlotKind::Ptr(p) => {
87 -
            let case il::DataItem::Sym(_) = item else {
88 -
                throw fail(index, verify::Rule::Data);
89 -
            };
90 -
            let data = c.prog.data[symbol];
91 -
            if pos <> leaf.start
92 -
                or data.heap <> nil
93 -
                or (p.mutable and data.readOnly)
94 -
                or not layout::view(t, data.layout, 0, p.layout)
95 -
            {
96 +
    loop {
97 +
        let end = pos + width(item);
98 +
        let leaf = layout::leafAround(t, l, pos) else {
99 +
            // The item starts in plain bytes, and must not run into a slot. A symbol in the payload
100 +
            // of a union variant needs a slot of that variant.
101 +
            if not layout::plain(t, l, pos, end) {
96 102
                throw fail(index, verify::Rule::Data);
97 103
            }
104 +
            if base <> 0 and not zero {
105 +
                let case il::DataItem::Val { .. } = item else throw fail(index, verify::Rule::Data);
106 +
            }
107 +
            return;
108 +
        };
109 +
        if end > leaf.start + layout::slotWidth(t, leaf.kind) {
110 +
            throw fail(index, verify::Rule::Data);
98 111
        }
99 -
        case il::SlotKind::Fn(sig) => {
100 -
            let case il::DataItem::Fn(_) = item else {
101 -
                throw fail(index, verify::Rule::Data);
102 -
            };
103 -
            if pos <> leaf.start or not verify::sigEq(
104 -
                c, verify::SigRef::Table(sig), verify::SigRef::Func(symbol)
105 -
            )
106 -
            {
112 +
        if let case il::SlotKind::Union { offset: payload, variants, .. } = leaf.kind {
113 +
            // Each payload nesting level keeps the tag of its current union.
114 +
            let start = base + leaf.start;
115 +
            let rel = pos - leaf.start;
116 +
            if zero and rel == 0 {
117 +
                set live.tags[depth] = UnionTag { start, tag: 0 };
118 +
            }
119 +
            if zero {
120 +
                return;
121 +
            }
122 +
            if rel >= 1 and rel < payload as u64 {
107 123
                throw fail(index, verify::Rule::Data);
108 124
            }
125 +
            if rel == 0 {
126 +
                let case il::DataItem::Val { typ: il::Type::W8, val } = item
127 +
                    else throw fail(index, verify::Rule::Data);
128 +
                if layout::variantWith(variants, val as u64 & 0xff) == nil {
129 +
                    throw fail(index, verify::Rule::Data);
130 +
                }
131 +
                set live.tags[depth] = UnionTag { start, tag: val as u64 & 0xff };
132 +
                return;
133 +
            }
134 +
            // The payload fits the layout of the variant that the tag names.
135 +
            let mut tag: u64 = 0;
136 +
            if let seen = live.tags[depth]; seen.start == start {
137 +
                set tag = seen.tag;
138 +
            }
139 +
            let variant = layout::variantWith(variants, tag)
140 +
                else throw fail(index, verify::Rule::Data);
141 +
            let inner = variant.layout else throw fail(index, verify::Rule::Data);
142 +
            set l = inner;
143 +
            set base = start + payload as u64;
144 +
            set pos = rel - payload as u64;
145 +
            set depth += 1;
146 +
            continue;
147 +
        }
148 +
        if zero {
149 +
            return;
109 150
        }
110 -
        case il::SlotKind::Slice(p) => {
111 -
            let offset = pos - leaf.start;
112 -
            if offset == 0 {
113 -
                // The pointer of a slice, which the length that follows must fit.
151 +
        let start = base + leaf.start;
152 +
        match leaf.kind {
153 +
            case il::SlotKind::Ptr(p) => {
114 154
                let case il::DataItem::Sym(_) = item else {
115 155
                    throw fail(index, verify::Rule::Data);
116 156
                };
117 157
                let data = c.prog.data[symbol];
118 -
                if data.heap <> nil or (p.mutable and data.readOnly) {
158 +
                if pos <> leaf.start
159 +
                    or data.heap <> nil
160 +
                    or (p.mutable and data.readOnly)
161 +
                    or not layout::view(t, data.layout, 0, p.layout)
162 +
                {
119 163
                    throw fail(index, verify::Rule::Data);
120 164
                }
121 -
                set *pending = Pending { start: leaf.start, target: symbol, len: 0 };
122 -
                return;
123 165
            }
124 -
            let case il::DataItem::Val { typ: il::Type::W32, val } = item else {
125 -
                throw fail(index, verify::Rule::Data);
126 -
            };
127 -
            if offset == SLICE_CAP {
128 -
                // The capacity bounds the lengths that programs can set, so it is exactly
129 -
                // the length.
130 -
                let live = *pending else {
166 +
            case il::SlotKind::Fn(sig) => {
167 +
                let case il::DataItem::Fn(_) = item else {
131 168
                    throw fail(index, verify::Rule::Data);
132 169
                };
133 -
                if live.start <> leaf.start or (val as u64 & mem::U32_MAX as u64) <> live.len {
170 +
                if pos <> leaf.start or not verify::sigEq(
171 +
                    c, verify::SigRef::Table(sig), verify::SigRef::Func(symbol)
172 +
                )
173 +
                {
134 174
                    throw fail(index, verify::Rule::Data);
135 175
                }
136 -
                set *pending = nil;
137 -
                return;
138 176
            }
139 -
            if offset <> SLICE_LEN {
140 -
                throw fail(index, verify::Rule::Data);
141 -
            }
142 -
            // A length of zero needs no pointer.
143 -
            let len = val as u64 & mem::U32_MAX as u64;
144 -
            if len == 0 {
145 -
                return;
146 -
            }
147 -
            let live = *pending else {
148 -
                throw fail(index, verify::Rule::Data);
149 -
            };
150 -
            if live.start <> leaf.start {
151 -
                throw fail(index, verify::Rule::Data);
152 -
            }
153 -
            set *pending = Pending { start: live.start, target: live.target, len };
154 -
            let data = c.prog.data[live.target];
155 -
            if not layout::arrayView(t, data.layout, 0, p.layout, len as u32) {
156 -
                throw fail(index, verify::Rule::Data);
177 +
            case il::SlotKind::Slice(p) => {
178 +
                let offset = pos - leaf.start;
179 +
                if offset == 0 {
180 +
                    // The pointer of a slice, which the length that follows must fit.
181 +
                    let case il::DataItem::Sym(_) = item else {
182 +
                        throw fail(index, verify::Rule::Data);
183 +
                    };
184 +
                    let data = c.prog.data[symbol];
185 +
                    if data.heap <> nil or (p.mutable and data.readOnly) {
186 +
                        throw fail(index, verify::Rule::Data);
187 +
                    }
188 +
                    set live.pending = Pending { start, target: symbol, len: 0 };
189 +
                    return;
190 +
                }
191 +
                let case il::DataItem::Val { typ: il::Type::W32, val } = item else {
192 +
                    throw fail(index, verify::Rule::Data);
193 +
                };
194 +
                if offset == SLICE_CAP {
195 +
                    // The capacity bounds the lengths that programs can set, so it is exactly
196 +
                    // the length.
197 +
                    let last = live.pending else {
198 +
                        throw fail(index, verify::Rule::Data);
199 +
                    };
200 +
                    if last.start <> start or (val as u64 & mem::U32_MAX as u64) <> last.len {
201 +
                        throw fail(index, verify::Rule::Data);
202 +
                    }
203 +
                    set live.pending = nil;
204 +
                    return;
205 +
                }
206 +
                if offset <> SLICE_LEN {
207 +
                    throw fail(index, verify::Rule::Data);
208 +
                }
209 +
                // A length of zero needs no pointer.
210 +
                let len = val as u64 & mem::U32_MAX as u64;
211 +
                if len == 0 {
212 +
                    return;
213 +
                }
214 +
                let last = live.pending else {
215 +
                    throw fail(index, verify::Rule::Data);
216 +
                };
217 +
                if last.start <> start {
218 +
                    throw fail(index, verify::Rule::Data);
219 +
                }
220 +
                set live.pending = Pending { start, target: last.target, len };
221 +
                let data = c.prog.data[last.target];
222 +
                if not layout::arrayView(t, data.layout, 0, p.layout, len as u32) {
223 +
                    throw fail(index, verify::Rule::Data);
224 +
                }
157 225
            }
226 +
            case il::SlotKind::Trait(_), il::SlotKind::Heap(_) =>
227 +
                throw fail(index, verify::Rule::Data),
228 +
            else => panic "atom: leaf slot is a nested object",
158 229
        }
159 -
        case il::SlotKind::Trait(_), il::SlotKind::Heap(_) => throw fail(index, verify::Rule::Data),
160 -
        else => panic "atom: leaf slot is a nested object",
230 +
        return;
161 231
    }
162 232
}
163 233
164 234
/// Check the initializer of data `index` against its layout.
165 -
export fn check(c: &verify::Context, index: u32) throws (verify::Error) {
235 +
fn checkData(c: &verify::Context, index: u32, live: &mut Live) throws (verify::Error) {
166 236
    let t = &c.table;
167 237
    let data = c.prog.data[index];
168 238
    let l = c.prog.layouts[data.layout];
169 239
    if data.size <> l.size or data.alignment <> l.alignment {
170 240
        throw fail(index, verify::Rule::Data);
183 253
    // data would carry such an object to every context, so it counts too.
184 254
    if t.infos[data.layout].refs or (not data.readOnly and t.infos[data.layout].reaches) {
185 255
        throw fail(index, verify::Rule::Data);
186 256
    }
187 257
    let mut pos: u64 = 0;
188 -
    let mut pending: ?Pending = nil;
258 +
    for i in 0 .. live.tags.len {
259 +
        set live.tags[i] = nil;
260 +
    }
261 +
    set live.pending = nil;
189 262
    for value in data.values {
190 263
        // The index of the symbol that the item names. A function must have a body.
191 264
        let mut symbol: u32 = 0;
192 265
        match value.item {
193 266
            case il::DataItem::Sym(name) => {
215 288
        if w == 0 or layout::plain(t, data.layout, pos, pos + total) {
216 289
            set pos += total;
217 290
            continue;
218 291
        }
219 292
        for _ in 0 .. value.count {
220 -
            try atom(c, index, pos, value.item, symbol, &mut pending);
293 +
            try atom(c, index, pos, value.item, symbol, live);
221 294
            set pos += w;
222 295
        }
223 296
    }
224 297
    // Omitted bytes are zero, so a nonempty slice needs a checked capacity.
225 -
    if let last = pending; last.len <> 0 {
298 +
    if let last = live.pending; last.len <> 0 {
226 299
        throw fail(index, verify::Rule::Data);
227 300
    }
228 301
}
302 +
303 +
/// Check all data initializers with a shared tag table sized to their layout depth.
304 +
export fn check(c: &verify::Context, a: &heap::Heap) throws (verify::Error) {
305 +
    let mut depth: u32 = 0;
306 +
    for data in c.prog.data {
307 +
        let needed = c.table.infos[data.layout].depth + 1;
308 +
        if needed > depth {
309 +
            set depth = needed;
310 +
        }
311 +
    }
312 +
    let mut tags: *mut [?UnionTag] = &mut [];
313 +
    try tags.resize(depth, nil, a) catch {
314 +
        throw verify::STORAGE;
315 +
    };
316 +
    let mut live = Live { pending: nil, tags };
317 +
    for i in 0 .. c.prog.data.len {
318 +
        try checkData(c, i, &mut live);
319 +
    }
320 +
}
lib/std/lang/il/verify/layout.rad +59 -6
1 1
//! Layout table checks and queries of the RIL verifier.
2 2
//!
3 3
//! A layout lists the slots of an object, the byte ranges that hold pointers,
4 -
//! slices, function values and trait objects. All other bytes are plain data. The decoder
4 +
//! slices, function values, trait objects and unions. All other bytes are plain data. The decoder
5 5
//! establishes that slots are sorted, aligned, disjoint and inside the size, and
6 6
//! that nested layouts have lower indices than the layouts that contain them.
7 7
//! The queries here rely on that, and on table indices that are in range.
8 8
//!
9 9
//! Descent through nested layouts is bounded by [`verify::Config::layoutDepth`],
28 28
    /// protects, also in nested nodes, or nil when the layout is plain data.
29 29
    first: ?u64,
30 30
    /// Whether the layout has a non-owning pointer, slice or trait object slot, also in
31 31
    /// nested nodes.
32 32
    refs: bool,
33 -
    /// Whether the layout has a slot of two words that are written together, a slice or
34 -
    /// a trait object, also in nested nodes.
33 +
    /// Whether the layout has a slot that is written together, a slice, a trait object or a
34 +
    /// union, also in nested nodes.
35 35
    pairs: bool,
36 36
    /// Whether such a slot is reachable from the layout: it has one, or a pointer slot, also
37 37
    /// in nested nodes, whose pointee reaches one.
38 38
    reaches: bool,
39 39
}
126 126
                case il::SlotKind::Trait(object) => {
127 127
                    set info.pairs = true;
128 128
                    set info.refs = info.refs or not object.own;
129 129
                }
130 130
                case il::SlotKind::Fn(_), il::SlotKind::Heap(_) => {}
131 +
                case il::SlotKind::Union { offset, size: width, variants } => {
132 +
                    set info.pairs = true;
133 +
                    if offset == 0 or width == 0 {
134 +
                        throw fail(i, verify::Rule::Layout);
135 +
                    }
136 +
                    let mut seen: [bool; 256] = [false; 256];
137 +
                    for variant in variants {
138 +
                        if variant.tag > 255 or seen[variant.tag] {
139 +
                            throw fail(i, verify::Rule::Layout);
140 +
                        }
141 +
                        set seen[variant.tag] = true;
142 +
                        let child = variant.layout else {
143 +
                            continue;
144 +
                        };
145 +
                        // The payload is an object of the variant layout inside the slot.
146 +
                        if child >= i
147 +
                            or offset % layouts[child].alignment <> 0
148 +
                            or offset as u64 + layouts[child].size as u64 > width as u64
149 +
                        {
150 +
                            throw fail(i, verify::Rule::Layout);
151 +
                        }
152 +
                        absorb(&mut info, infos[child]);
153 +
                    }
154 +
                }
131 155
                case il::SlotKind::Sub(child) => {
132 156
                    if child >= i {
133 157
                        throw fail(i, verify::Rule::Layout);
134 158
                    }
135 159
                    absorb(&mut info, infos[child]);
247 271
/// Whether layout `l` is plain data, without any slot.
248 272
export fn isPlain(t: &Table, l: u32) -> bool {
249 273
    return t.infos[l].first == nil;
250 274
}
251 275
252 -
/// Number of bytes that a slot of kind `kind` covers.
276 +
/// Number of bytes that a slot of kind `kind` covers. A union slot covers its tag and payload.
253 277
export fn slotWidth(t: &Table, kind: il::SlotKind) -> u64 {
254 278
    match kind {
255 279
        case il::SlotKind::Ptr(_), il::SlotKind::Fn(_), il::SlotKind::Heap(_) => return WORD,
256 280
        case il::SlotKind::Slice(_) => return SLICE,
257 281
        case il::SlotKind::Trait(_) => return TRAIT,
282 +
        case il::SlotKind::Union { size: width, .. } => return width as u64,
258 283
        case il::SlotKind::Sub(child) => return size(t, child),
259 284
        case il::SlotKind::Array { layout, count } => return size(t, layout) * count as u64,
260 285
    }
261 286
}
262 287
320 345
        }
321 346
        return Leaf { start: o - at.offset + slot.offset as u64, kind: slot.kind };
322 347
    }
323 348
}
324 349
350 +
/// Find the variant of a union slot with the given tag.
351 +
export fn variantWith(variants: *[il::UnionVariant], tag: u64) -> ?il::UnionVariant {
352 +
    for variant in variants {
353 +
        if variant.tag as u64 == tag {
354 +
            return variant;
355 +
        }
356 +
    }
357 +
    return nil;
358 +
}
359 +
325 360
/// Find the leaf slot that starts exactly at byte `o` of layout `l`.
326 361
export fn slotAt(t: &Table, l: u32, o: u64) -> ?il::SlotKind {
327 362
    if let leaf = leafAround(t, l, o) {
328 363
        if leaf.start == o {
329 364
            return leaf.kind;
339 374
        case
340 375
            il::SlotKind::Ptr(_),
341 376
            il::SlotKind::Fn(_),
342 377
            il::SlotKind::Heap(_),
343 378
            il::SlotKind::Slice(_),
344 -
            il::SlotKind::Trait(_) => return 0,
379 +
            il::SlotKind::Trait(_),
380 +
            il::SlotKind::Union { .. } => return 0,
345 381
        case il::SlotKind::Sub(child) => return infos[child].first,
346 382
        case il::SlotKind::Array { layout, count } => {
347 383
            if count == 0 {
348 384
                return nil;
349 385
            }
370 406
        case
371 407
            il::SlotKind::Ptr(_),
372 408
            il::SlotKind::Fn(_),
373 409
            il::SlotKind::Heap(_),
374 410
            il::SlotKind::Slice(_),
375 -
            il::SlotKind::Trait(_) => return rel,
411 +
            il::SlotKind::Trait(_),
412 +
            il::SlotKind::Union { .. } => return rel,
376 413
        case il::SlotKind::Sub(child) => return firstProtected(t, child, rel),
377 414
        case il::SlotKind::Array { layout, count } => {
378 415
            // The slot covers a byte, so the element size is not zero.
379 416
            let element = size(t, layout);
380 417
            let index = rel / element;
451 488
        set at = next;
452 489
    }
453 490
    return true;
454 491
}
455 492
493 +
/// Whether the bytes at byte `o` of layout `l` hold an object of layout `m`: `m` is a view there,
494 +
/// or `m` is a single slot that fills it and `l` has the same slot at `o`.
495 +
export fn holds(t: &Table, l: u32, o: u64, m: u32) -> bool {
496 +
    if view(t, l, o, m) {
497 +
        return true;
498 +
    }
499 +
    let slots = t.layouts[m].slots;
500 +
    if slots.len <> 1 or slots[0].offset <> 0 or slotWidth(t, slots[0].kind) <> size(t, m) {
501 +
        return false;
502 +
    }
503 +
    let kind = slotAt(t, l, o) else {
504 +
        return false;
505 +
    };
506 +
    return kind == slots[0].kind;
507 +
}
508 +
456 509
/// Whether a pointer to layout `l` at byte `o` can be used as a pointer to `count` consecutive
457 510
/// objects of layout `e`. A plain `e` needs a plain region that is inside `l`. Any other
458 511
/// `e` needs an array node of `e` with that count, or a single object that is a view.
459 512
export fn arrayView(t: &Table, l: u32, o: u64, e: u32, count: u32) -> bool {
460 513
    let total = size(t, e) * count as u64;
lib/std/lang/il/verify/tests.rad +466 -0
2286 2286
            }
2287 2287
        }
2288 2288
    }
2289 2289
}
2290 2290
2291 +
/// A capacity check completes each slice in an array inside a union payload.
2292 +
@test unsafe fn nestedSliceDataCapacity() throws (testing::TestError) {
2293 +
    for capacity in &[0, 4] {
2294 +
        let mut b = newBuilder();
2295 +
        let pair = addLayout(&mut b, 32, 8, &[
2296 +
            il::Slot { offset: 0, kind: il::SlotKind::Array { layout: SLICE, count: 2 } }
2297 +
        ]);
2298 +
        let mut variants: *mut [il::UnionVariant] = &mut [];
2299 +
        try! variants.append(il::UnionVariant { tag: 0, layout: pair }, b.arena);
2300 +
        let outer = addLayout(&mut b, 40, 8, &[
2301 +
            il::Slot {
2302 +
                offset: 0,
2303 +
                kind: il::SlotKind::Union {
2304 +
                    offset: 8, size: 40, variants: &variants[..]
2305 +
                },
2306 +
            },
2307 +
        ]);
2308 +
        addData(&mut b, "bytes", P16, false, &[]);
2309 +
        addData(
2310 +
            &mut b,
2311 +
            "d",
2312 +
            outer,
2313 +
            true,
2314 +
            &[
2315 +
                number(il::Type::W64,                  0),
2316 +
                symbol("bytes"), number(il::Type::W32, 4), number(il::Type::W32, capacity),
2317 +
                symbol("bytes"), number(il::Type::W32, 4), number(il::Type::W32, 4),
2318 +
            ]
2319 +
        );
2320 +
        if capacity == 0 {
2321 +
            try rejected(&mut b, verify::Rule::Data);
2322 +
        } else {
2323 +
            try accepted(&mut b);
2324 +
        }
2325 +
    }
2326 +
}
2327 +
2291 2328
/// Slice initializers cannot name heap headers, even with no elements.
2292 2329
@test unsafe fn heapSliceData() throws (testing::TestError) {
2293 2330
    let heaps = &[
2294 2331
        il::HeapType::Typed,
2295 2332
        il::HeapType::Plain,
3460 3497
    assert not table.infos[cycle + 1].reaches;
3461 3498
    assert not table.infos[empty].reaches;
3462 3499
    assert table.infos[pairedCycle].reaches;
3463 3500
    assert table.infos[pairedCycle + 1].reaches;
3464 3501
}
3502 +
3503 +
///////////////////
3504 +
// Union slots   //
3505 +
///////////////////
3506 +
3507 +
/// Sixteen bytes: a union with a tag byte and a payload at offset 8, whose variants are 0, a
3508 +
/// `CELL`; 1, a `P4`; and 2, no payload. [`addUnions`] adds it after the layouts above.
3509 +
constant UNION: u32 = 27;
3510 +
/// Sixteen bytes: a union with the single variant 0, a `LOCAL`.
3511 +
constant BORROWED: u32 = 28;
3512 +
/// Eight bytes: an owned writable pointer to a `UNION`.
3513 +
constant UNIONPTR: u32 = 29;
3514 +
/// Sixteen bytes: a union with the variants 0, a `CELLC`; 1, a `P4`; and 2, no payload.
3515 +
constant UNIONRO: u32 = 30;
3516 +
/// Forty bytes: a union with the variants 0, a `PAIR`; and 1, a `P4`.
3517 +
constant UNIONPART: u32 = 31;
3518 +
3519 +
/// A variant of a union slot.
3520 +
fn variant(tag: u32, layout: ?u32) -> il::UnionVariant {
3521 +
    return il::UnionVariant { tag, layout };
3522 +
}
3523 +
3524 +
/// A union slot at offset 0 of `size` bytes with its payload at `offset`.
3525 +
fn unionSlot(b: &mut Builder, offset: u32, size: u32, variants: &[il::UnionVariant]) -> il::Slot {
3526 +
    let mut own: *mut [il::UnionVariant] = &mut [];
3527 +
    try! own.extend(variants, b.arena);
3528 +
    return il::Slot {
3529 +
        offset: 0, kind: il::SlotKind::Union { offset, size, variants: &own[..] }
3530 +
    };
3531 +
}
3532 +
3533 +
/// Add the layouts of the union tests, which have the indices named above.
3534 +
fn addUnions(b: &mut Builder) {
3535 +
    let first = unionSlot(b, 8, 16, &[variant(0, CELL), variant(1, P4), variant(2, nil)]);
3536 +
    assert addLayout(b, 16, 8, &[first]) == UNION;
3537 +
    let second = unionSlot(b, 8, 16, &[variant(0, LOCAL)]);
3538 +
    assert addLayout(b, 16, 8, &[second]) == BORROWED;
3539 +
    assert addLayout(b, 8, 8, &[ptrSlot(0, UNION, true, true)]) == UNIONPTR;
3540 +
    let third = unionSlot(b, 8, 16, &[variant(0, CELLC), variant(1, P4), variant(2, nil)]);
3541 +
    assert addLayout(b, 16, 8, &[third]) == UNIONRO;
3542 +
    let fourth = unionSlot(b, 8, 40, &[variant(0, PAIR), variant(1, P4)]);
3543 +
    assert addLayout(b, 40, 8, &[fourth]) == UNIONPART;
3544 +
}
3545 +
3546 +
/// Read the payload of the variant `tag` at `offset` of the union `src` into `dst`.
3547 +
fn unionGet(dst: u32, src: u32, tag: u32, offset: u32, layout: u32) -> il::Instr {
3548 +
    return il::Instr::UnionGet {
3549 +
        dst: il::Reg { n: dst }, src: il::Reg { n: src }, tag, offset, layout
3550 +
    };
3551 +
}
3552 +
3553 +
/// Write the variant `tag` into the union `dst`, with the payload at `src` or without one.
3554 +
fn unionSet(dst: u32, tag: u32, offset: u32, src: il::Val, layout: ?u32) -> il::Instr {
3555 +
    return il::Instr::UnionSet { dst: il::Reg { n: dst }, tag, offset, src, layout };
3556 +
}
3557 +
3558 +
/// Check `main`, which has a `UNION` in register 0, a `CELL` in register 1 and a `P4` in
3559 +
/// register 2, and then runs `instrs`.
3560 +
unsafe fn unionCase(instrs: &[il::Instr], rule: ?verify::Rule) throws (testing::TestError) {
3561 +
    let mut b = newBuilder();
3562 +
    addUnions(&mut b);
3563 +
    let mut body: *mut [il::Instr] = &mut [];
3564 +
    try! body.append(reserve(0, UNION), b.arena);
3565 +
    try! body.append(reserve(1, CELL), b.arena);
3566 +
    try! body.append(reserve(2, P4), b.arena);
3567 +
    try! body.extend(instrs, b.arena);
3568 +
    try! body.append(retVoid(), b.arena);
3569 +
    try checkIn(&mut b, &[], il::ValType::Void, &body[..], rule);
3570 +
}
3571 +
3572 +
/// Check that a union is written with a variant and read back with the same tag and layout,
3573 +
/// and that its tag and whole value are readable as data.
3574 +
@test unsafe fn unionSlotAccess() throws (testing::TestError) {
3575 +
    try unionCase(
3576 +
        &[
3577 +
            unionSet(0, 0, 8, reg(1), CELL),
3578 +
            unionGet(1, 0, 0, 8, CELL),
3579 +
            unionSet(0, 1, 8, reg(2), P4),
3580 +
            unionGet(2, 0, 1, 8, P4),
3581 +
            unionSet(0, 2, 8, il::Val::Undef, nil),
3582 +
            load(3,     0, 0),
3583 +
            reserve(4,  UNION),
3584 +
            blit(4,     0, UNION),
3585 +
        ],
3586 +
        nil
3587 +
    );
3588 +
}
3589 +
3590 +
/// Check `main`, which has a `UNIONPART` in register 0, and then runs `instrs`. The payload is at
3591 +
/// offset 8, and the `PAIR` has a `CELL` at 8 and a `SLICE` at 16 of its own offsets.
3592 +
unsafe fn partCase(instrs: &[il::Instr], rule: ?verify::Rule) throws (testing::TestError) {
3593 +
    let mut b = newBuilder();
3594 +
    addUnions(&mut b);
3595 +
    let mut body: *mut [il::Instr] = &mut [];
3596 +
    try! body.append(reserve(0, UNIONPART), b.arena);
3597 +
    try! body.extend(instrs, b.arena);
3598 +
    try! body.append(retVoid(), b.arena);
3599 +
    try checkIn(&mut b, &[], il::ValType::Void, &body[..], rule);
3600 +
}
3601 +
3602 +
/// Check that a read takes a part of the payload that the layout of the variant has there: a
3603 +
/// slot that fills a destination of its own, a nested object, or plain bytes, and nothing else.
3604 +
@test unsafe fn unionSlotParts() throws (testing::TestError) {
3605 +
    // The whole payload, a pointer, a slice and plain bytes, and the pointer is then loaded.
3606 +
    try partCase(&[reserve(1, PAIR), unionGet(1, 0, 0, 8, PAIR)], nil);
3607 +
    try partCase(&[reserve(1, CELL), unionGet(1, 0, 0, 16, CELL), loadPtr(2, 1, 0)], nil);
3608 +
    try partCase(&[reserve(1, SLICE), unionGet(1, 0, 0, 24, SLICE)], nil);
3609 +
    try partCase(&[reserve(1, P8), unionGet(1, 0, 0, 8, P8)], nil);
3610 +
    try partCase(&[reserve(1, P4), unionGet(1, 0, 1, 8, P4)], nil);
3611 +
    // An offset that is not where a slot of that layout is, or is before the payload.
3612 +
    try partCase(&[reserve(1, CELL), unionGet(1, 0, 0, 17, CELL)], verify::Rule::View);
3613 +
    try partCase(&[reserve(1, CELL), unionGet(1, 0, 0, 24, CELL)], verify::Rule::View);
3614 +
    try partCase(&[reserve(1, CELL), unionGet(1, 0, 0, 8, CELL)], verify::Rule::View);
3615 +
    try partCase(&[reserve(1, P8), unionGet(1, 0, 0, 4, P8)], verify::Rule::View);
3616 +
    // A slot of another kind than the one in the part.
3617 +
    try partCase(&[reserve(1, CELLC), unionGet(1, 0, 0, 16, CELLC)], verify::Rule::View);
3618 +
    try partCase(&[reserve(1, SLICEC), unionGet(1, 0, 0, 24, SLICEC)], verify::Rule::View);
3619 +
    // A part that straddles a slot, or is bytes of one.
3620 +
    try partCase(&[reserve(1, P16), unionGet(1, 0, 0, 16, P16)], verify::Rule::View);
3621 +
    try partCase(&[reserve(1, P8), unionGet(1, 0, 0, 16, P8)], verify::Rule::View);
3622 +
    try partCase(&[reserve(1, P8), unionGet(1, 0, 0, 24, P8)], verify::Rule::View);
3623 +
    // A part that runs past the payload of the variant, or that belongs to another variant.
3624 +
    try partCase(&[reserve(1, P16), unionGet(1, 0, 1, 8, P16)], verify::Rule::View);
3625 +
    try partCase(&[reserve(1, CELL), unionGet(1, 0, 1, 8, CELL)], verify::Rule::View);
3626 +
    try partCase(&[reserve(1, CELL), unionGet(1, 0, 1, 16, CELL)], verify::Rule::View);
3627 +
    // A write takes the whole payload.
3628 +
    try partCase(&[reserve(1, PAIR), unionSet(0, 0, 8, reg(1), PAIR)], nil);
3629 +
    try partCase(&[reserve(1, CELL), unionSet(0, 0, 16, reg(1), CELL)], verify::Rule::View);
3630 +
}
3631 +
3632 +
/// Check that the tag, the payload offset and the layout of a read or write match a variant
3633 +
/// of the slot, and that a variant without a payload takes none.
3634 +
@test unsafe fn unionSlotVariants() throws (testing::TestError) {
3635 +
    try unionCase(&[unionGet(1, 0, 3, 8, CELL)], verify::Rule::View);
3636 +
    try unionCase(&[unionGet(1, 0, 1, 8, CELL)], verify::Rule::View);
3637 +
    try unionCase(&[unionGet(1, 0, 0, 4, CELL)], verify::Rule::View);
3638 +
    try unionCase(&[unionGet(1, 0, 2, 8, CELL)], verify::Rule::View);
3639 +
    try unionCase(&[unionSet(0, 3, 8, reg(1), CELL)], verify::Rule::View);
3640 +
    try unionCase(&[unionSet(0, 0, 8, reg(2), P4)], verify::Rule::View);
3641 +
    try unionCase(&[unionSet(0, 0, 4, reg(1), CELL)], verify::Rule::View);
3642 +
    try unionCase(&[unionSet(0, 2, 8, reg(1), nil)], verify::Rule::Type);
3643 +
    try unionCase(&[unionSet(0, 2, 8, il::Val::Undef, CELL)], verify::Rule::View);
3644 +
    try unionCase(&[unionSet(0, 0, 8, il::Val::Undef, CELL)], verify::Rule::Type);
3645 +
    try unionCase(&[unionSet(0, 0, 8, imm(0), CELL)], verify::Rule::Type);
3646 +
    // The objects that carry the payload have the layout of the variant.
3647 +
    try unionCase(&[unionGet(1, 0, 1, 8, P4)], verify::Rule::View);
3648 +
    try unionCase(&[reserve(3,  P8), unionSet(0, 0, 8, reg(3), CELL)], verify::Rule::View);
3649 +
    // A payload that has slots can be read into plain bytes of its size.
3650 +
    try unionCase(&[reserve(3, P8), unionGet(3, 0, 0, 8, CELL)], nil);
3651 +
}
3652 +
3653 +
/// Check that the instructions need a pointer to the start of a writable union slot.
3654 +
@test unsafe fn unionSlotPointers() throws (testing::TestError) {
3655 +
    // The pointer is at the start of the slot.
3656 +
    try unionCase(&[field(3, 0, 8), unionGet(1, 3, 0, 8, CELL)], verify::Rule::Slot);
3657 +
    try unionCase(&[field(3, 0, 8), unionSet(3, 0, 8, reg(1), CELL)], verify::Rule::Slot);
3658 +
    try unionCase(&[field(3, 0, 4), unionSet(3, 1, 8, reg(2), P4)], verify::Rule::Slot);
3659 +
    // It addresses a union, and a writable one for a write.
3660 +
    try unionCase(&[unionGet(2, 1, 0, 8, P4)], verify::Rule::Slot);
3661 +
    try unionCase(&[unionSet(1, 0, 8, reg(1), CELL)], verify::Rule::Slot);
3662 +
    let mut b = newBuilder();
3663 +
    addUnions(&mut b);
3664 +
    try checkIn(
3665 +
        &mut b,
3666 +
        &[
3667 +
            param(0, ptrType(UNION, false, false, false)),
3668 +
            param(1, ptrType(CELL, false, true, false)),
3669 +
        ],
3670 +
        il::ValType::Void,
3671 +
        &[unionSet(0, 0, 8, reg(1), CELL), retVoid()],
3672 +
        verify::Rule::Mutability
3673 +
    );
3674 +
    // A union can be read through a read-only pointer, but not through a nullable one.
3675 +
    let mut c = newBuilder();
3676 +
    addUnions(&mut c);
3677 +
    try checkIn(
3678 +
        &mut c,
3679 +
        &[
3680 +
            param(0, ptrType(UNION, false, false, false)),
3681 +
            param(1, ptrType(CELL, false, true, false)),
3682 +
        ],
3683 +
        il::ValType::Void,
3684 +
        &[unionGet(1, 0, 0, 8, CELL), retVoid()],
3685 +
        nil
3686 +
    );
3687 +
    let mut d = newBuilder();
3688 +
    addUnions(&mut d);
3689 +
    try checkIn(
3690 +
        &mut d,
3691 +
        &[
3692 +
            param(0, ptrType(UNION, false, false, true)),
3693 +
            param(1, ptrType(CELL, false, true, false)),
3694 +
        ],
3695 +
        il::ValType::Void,
3696 +
        &[unionGet(1, 0, 0, 8, CELL), retVoid()],
3697 +
        verify::Rule::Null
3698 +
    );
3699 +
}
3700 +
3701 +
/// Check that nothing but the union instructions writes a tag or a payload, and that no
3702 +
/// interior pointer views them.
3703 +
@test unsafe fn unionSlotProtection() throws (testing::TestError) {
3704 +
    // Plain stores over the tag, the padding and the payload.
3705 +
    try unionCase(
3706 +
        &[
3707 +
            il::Instr::Store {
3708 +
                typ: il::Type::W8, src: imm(0), dst: il::Reg { n: 0 }, offset: 0
3709 +
            },
3710 +
        ],
3711 +
        verify::Rule::Slot
3712 +
    );
3713 +
    try unionCase(&[store(imm(0),   0, 4)], verify::Rule::Slot);
3714 +
    try unionCase(&[store(imm(0),   0, 8)], verify::Rule::Slot);
3715 +
    try unionCase(&[store64(imm(0), 0, 8)], verify::Rule::Slot);
3716 +
    // Typed accesses of the payload as a pointer.
3717 +
    try unionCase(&[storePtr(imm(0), 0, 8)], verify::Rule::Slot);
3718 +
    try unionCase(&[storePtr(imm(0), 0, 0)], verify::Rule::Slot);
3719 +
    try unionCase(&[loadPtr(3,       0, 8)], verify::Rule::Slot);
3720 +
    try unionCase(&[loadPtr(3,       0, 0)], verify::Rule::Slot);
3721 +
    // Reads as data are allowed.
3722 +
    try unionCase(&[load64(3, 0, 8), load64(4, 0, 0)], nil);
3723 +
    // An interior pointer does not view the payload, as data or as its layout.
3724 +
    try unionCase(&[field(3, 0, 8), blit(2, 3, P4)], verify::Rule::View);
3725 +
    try unionCase(&[field(3, 0, 8), blit(3, 2, P4)], verify::Rule::View);
3726 +
    try unionCase(&[field(3, 0, 8), blit(1, 3, CELL)], verify::Rule::View);
3727 +
    try unionCase(&[field(3, 0, 8), store(imm(0), 3, 0)], verify::Rule::Slot);
3728 +
    // Plain bytes cannot be copied over a union, and a union is copied as a whole only.
3729 +
    try unionCase(&[reserve(3, P16), blit(0, 3, P16)], verify::Rule::View);
3730 +
    try unionCase(&[reserve(3, P16), blit(3, 0, P16)], verify::Rule::View);
3731 +
    try unionCase(&[reserve(3, BORROWED), blit(3, 0, UNION)], verify::Rule::View);
3732 +
}
3733 +
3734 +
/// Check that a payload with a borrowed slot stays in the frame, as a copy of it does.
3735 +
@test unsafe fn unionSlotBorrows() throws (testing::TestError) {
3736 +
    let mut b = newBuilder();
3737 +
    addUnions(&mut b);
3738 +
    try checkIn(
3739 +
        &mut b,
3740 +
        &[param(0, ptrType(BORROWED, false, true, false))],
3741 +
        il::ValType::Void,
3742 +
        &[reserve(1, LOCAL), unionSet(0, 0, 8, reg(1), LOCAL), retVoid()],
3743 +
        verify::Rule::Class
3744 +
    );
3745 +
    let mut c = newBuilder();
3746 +
    addUnions(&mut c);
3747 +
    try checkIn(
3748 +
        &mut c,
3749 +
        &[param(0, ptrType(BORROWED, false, true, false))],
3750 +
        il::ValType::Void,
3751 +
        &[reserve(1, LOCAL), unionGet(1, 0, 0, 8, LOCAL), retVoid()],
3752 +
        nil
3753 +
    );
3754 +
    let mut d = newBuilder();
3755 +
    addUnions(&mut d);
3756 +
    try checkIn(
3757 +
        &mut d,
3758 +
        &[
3759 +
            param(0, ptrType(LOCAL, false, true, false)),
3760 +
            param(1, ptrType(BORROWED, false, true, false)),
3761 +
        ],
3762 +
        il::ValType::Void,
3763 +
        &[unionGet(0, 1, 0, 8, LOCAL), retVoid()],
3764 +
        verify::Rule::Class
3765 +
    );
3766 +
    let mut e = newBuilder();
3767 +
    addUnions(&mut e);
3768 +
    try checkIn(
3769 +
        &mut e,
3770 +
        &[],
3771 +
        il::ValType::Void,
3772 +
        &[reserve(0, BORROWED), reserve(1, LOCAL), unionSet(0, 0, 8, reg(1), LOCAL), retVoid()],
3773 +
        nil
3774 +
    );
3775 +
}
3776 +
3777 +
/// Check the program that holds the read-only data "t" of a `P4` and the data "d" of a `UNIONRO`
3778 +
/// with the initializer `values`: it is accepted when `rule` is nil, or rejected for `rule`.
3779 +
unsafe fn unionData(readOnly: bool, values: &[il::DataValue], rule: ?verify::Rule)
3780 +
    throws (testing::TestError)
3781 +
{
3782 +
    let mut b = newBuilder();
3783 +
    addUnions(&mut b);
3784 +
    addData(&mut b, "t", P4, true, &[number(il::Type::W32, 5)]);
3785 +
    addData(&mut b, "d", UNIONRO, readOnly, values);
3786 +
    try expect(&mut b, rule);
3787 +
}
3788 +
3789 +
/// Check that read-only data holds a union with the tag of a variant and a payload that fits the
3790 +
/// layout of that variant, and that mutable data cannot hold or reach a union, as for a slice.
3791 +
@test unsafe fn unionSlotData() throws (testing::TestError) {
3792 +
    let pad = repeat(il::DataItem::Undef, 7);
3793 +
    let rest = repeat(il::DataItem::Undef, 8);
3794 +
    // Zero is every variant at once.
3795 +
    try unionData(true, &[repeat(il::DataItem::Undef, 16)], nil);
3796 +
    try unionData(true, &[number(il::Type::W64,       0), number(il::Type::W64, 0)], nil);
3797 +
    // A pointer under the variant with a pointer, a number under the other, and no payload.
3798 +
    try unionData(true, &[number(il::Type::W8, 0), pad, symbol("t")], nil);
3799 +
    try unionData(
3800 +
        true,
3801 +
        &[number(il::Type::W8, 1), pad, number(il::Type::W32, 7), repeat(il::DataItem::Undef, 4)],
3802 +
        nil
3803 +
    );
3804 +
    try unionData(true, &[number(il::Type::W8, 2), pad, rest], nil);
3805 +
    // An unknown tag, or a tag that is not a byte.
3806 +
    try unionData(true, &[number(il::Type::W8, 9), pad, rest], verify::Rule::Data);
3807 +
    try unionData(
3808 +
        true, &[number(il::Type::W16, 1), repeat(il::DataItem::Undef, 14)], verify::Rule::Data
3809 +
    );
3810 +
    // A payload that does not match the layout of the tag: an address under the plain variant, a
3811 +
    // number under the pointer, an address that does not fit, and a payload under a variant
3812 +
    // without one.
3813 +
    try unionData(true, &[number(il::Type::W8, 1), pad, symbol("t")], verify::Rule::Data);
3814 +
    try unionData(
3815 +
        true, &[number(il::Type::W8, 0), pad, number(il::Type::W64, 5)], verify::Rule::Data
3816 +
    );
3817 +
    try unionData(true, &[number(il::Type::W8, 0), pad, symbol("d")], verify::Rule::Data);
3818 +
    try unionData(
3819 +
        true, &[number(il::Type::W8, 2), pad, number(il::Type::W64, 5)], verify::Rule::Data
3820 +
    );
3821 +
    // The padding is zero.
3822 +
    try unionData(
3823 +
        true,
3824 +
        &[number(il::Type::W8, 1), number(il::Type::W8, 1), repeat(il::DataItem::Undef, 6), rest],
3825 +
        verify::Rule::Data
3826 +
    );
3827 +
    // Mutable data cannot hold a union, or reach one.
3828 +
    try unionData(false, &[repeat(il::DataItem::Undef, 16)], verify::Rule::Data);
3829 +
    let mut d = newBuilder();
3830 +
    addUnions(&mut d);
3831 +
    addData(&mut d, "d", UNIONPTR, false, &[number(il::Type::W64, 0)]);
3832 +
    try rejected(&mut d, verify::Rule::Data);
3833 +
    let mut e = newBuilder();
3834 +
    addUnions(&mut e);
3835 +
    addData(&mut e, "d", UNIONPTR, true, &[number(il::Type::W64, 0)]);
3836 +
    try accepted(&mut e);
3837 +
}
3838 +
3839 +
/// Check nested union initializers with separate tags for the parent and each child.
3840 +
unsafe fn nestedUnionData(values: &[il::DataValue], rule: ?verify::Rule)
3841 +
    throws (testing::TestError)
3842 +
{
3843 +
    let mut b = newBuilder();
3844 +
    addUnions(&mut b);
3845 +
    let payload = addLayout(&mut b, 40, 8, &[subSlot(0, UNIONRO), subSlot(24, UNIONRO)]);
3846 +
    let slot = unionSlot(&mut b, 8, 48, &[variant(0, P4), variant(1, payload)]);
3847 +
    let outer = addLayout(&mut b, 48, 8, &[slot]);
3848 +
    addData(&mut b, "t", P4, true, &[number(il::Type::W32, 5)]);
3849 +
    addData(&mut b, "d", outer, true, values);
3850 +
    try expect(&mut b, rule);
3851 +
}
3852 +
3853 +
/// Nested tags select their own payload layouts and preserve the parent's tag.
3854 +
@test unsafe fn nestedUnionSlotData() throws (testing::TestError) {
3855 +
    let pad = repeat(il::DataItem::Undef, 7);
3856 +
    let mut values = [
3857 +
        number(il::Type::W8,  1), pad,
3858 +
        number(il::Type::W8,  1), pad, number(il::Type::W32, 7), repeat(il::DataItem::Undef, 4),
3859 +
        number(il::Type::W64, 9),
3860 +
        number(il::Type::W8,  0), pad, symbol("t"),
3861 +
    ];
3862 +
    try nestedUnionData(&values[..], nil);
3863 +
    // An unknown child tag cannot select a payload.
3864 +
    set values[2] = number(il::Type::W8, 9);
3865 +
    try nestedUnionData(&values[..], verify::Rule::Data);
3866 +
    // A numeric payload cannot initialize the pointer variant.
3867 +
    set values[2] = number(il::Type::W8, 0);
3868 +
    try nestedUnionData(&values[..], verify::Rule::Data);
3869 +
    set values[2] = number(il::Type::W8, 1);
3870 +
    // The second child cannot use the tag of its sibling.
3871 +
    set values[7] = number(il::Type::W8, 1);
3872 +
    try nestedUnionData(&values[..], verify::Rule::Data);
3873 +
    set values[7] = number(il::Type::W8, 0);
3874 +
    // Nested pointers must have the declared target layout.
3875 +
    set values[9] = symbol("d");
3876 +
    try nestedUnionData(&values[..], verify::Rule::Data);
3877 +
    set values[9] = symbol("t");
3878 +
    // Padding between a child tag and its payload is zero.
3879 +
    set values[3] = repeat(il::DataItem::Val { typ: il::Type::W8, val: 1 }, 7);
3880 +
    try nestedUnionData(&values[..], verify::Rule::Data);
3881 +
}
3882 +
3883 +
/// Check that a malformed union slot is rejected: a variant layout that does not precede the
3884 +
/// layout, a repeated or oversized tag, and a payload that does not fit or is not aligned.
3885 +
@test unsafe fn unionSlotLayouts() throws (testing::TestError) {
3886 +
    let mut a = newBuilder();
3887 +
    let own = a.layouts.len;
3888 +
    let slotA = unionSlot(&mut a, 8, 16, &[variant(0, own)]);
3889 +
    addLayout(&mut a, 16, 8, &[slotA]);
3890 +
    try rejected(&mut a, verify::Rule::Layout);
3891 +
    let mut b = newBuilder();
3892 +
    let slotB = unionSlot(&mut b, 8, 16, &[variant(0, P4), variant(0, P8)]);
3893 +
    addLayout(&mut b, 16, 8, &[slotB]);
3894 +
    try rejected(&mut b, verify::Rule::Layout);
3895 +
    let mut c = newBuilder();
3896 +
    let slotC = unionSlot(&mut c, 8, 16, &[variant(256, P4)]);
3897 +
    addLayout(&mut c, 16, 8, &[slotC]);
3898 +
    try rejected(&mut c, verify::Rule::Layout);
3899 +
    // The payload ends after the union.
3900 +
    let mut d = newBuilder();
3901 +
    let slotD = unionSlot(&mut d, 8, 16, &[variant(0, P16)]);
3902 +
    addLayout(&mut d, 16, 8, &[slotD]);
3903 +
    try rejected(&mut d, verify::Rule::Layout);
3904 +
    // The payload is not aligned, or overlaps the tag.
3905 +
    let mut e = newBuilder();
3906 +
    let slotE = unionSlot(&mut e, 4, 16, &[variant(0, P8)]);
3907 +
    addLayout(&mut e, 16, 8, &[slotE]);
3908 +
    try rejected(&mut e, verify::Rule::Layout);
3909 +
    let mut f = newBuilder();
3910 +
    let slotF = unionSlot(&mut f, 0, 16, &[variant(0, P8)]);
3911 +
    addLayout(&mut f, 16, 8, &[slotF]);
3912 +
    try rejected(&mut f, verify::Rule::Layout);
3913 +
    // A union that fits is accepted, also with variants only without payloads.
3914 +
    let mut g = newBuilder();
3915 +
    let slotG = unionSlot(&mut g, 4, 8, &[variant(255, P4), variant(7, nil)]);
3916 +
    addLayout(&mut g, 8, 4, &[slotG]);
3917 +
    try accepted(&mut g);
3918 +
    // A union is paired, and a borrowed payload makes the layout borrowed.
3919 +
    let mut h = newBuilder();
3920 +
    addUnions(&mut h);
3921 +
    let scratch = heap::over(&mut SCRATCH[..]);
3922 +
    let table = try! layout::build(&h.layouts[..], CONFIG, scratch);
3923 +
    assert table.infos[UNION].pairs and table.infos[UNION].reaches;
3924 +
    assert table.infos[BORROWED].refs and not table.infos[UNION].refs;
3925 +
    assert table.infos[UNIONPTR].reaches;
3926 +
    assert layout::size(&table, UNION) == 16;
3927 +
    assert not layout::isPlain(&table, UNION);
3928 +
    assert not layout::plain(&table, UNION, 0, 16);
3929 +
    assert layout::plain(&table, UNION, 0, 0);
3930 +
}
lib/std/lang/lower.rad +420 -280
388 388
    /// Traits of the current package that have an index.
389 389
    traitIndices: *mut [TraitIndex],
390 390
    /// Where the tables of each lowered package start, in lowering order.
391 391
    tableStarts: *mut [TableStart],
392 392
    /// Package-relative indices of layouts that are found by content: all layouts
393 -
    /// without slots, and the layouts of results.
393 +
    /// without slots, and the layouts of results. Sorted by size, alignment and slot count.
394 394
    sharedLayouts: *mut [u32],
395 395
    /// Layouts of the structural types that have slots, such as arrays and optionals.
396 396
    typeLayouts: *mut [TypeLayout],
397 397
    /// Layout cache of nominal types, indexed by nominal id.
398 398
    nominalLayouts: *mut [NominalLayout],
1083 1083
/// How an aggregate match subject is held while its pattern is bound.
1084 1084
union SubjectStorage: Copy {
1085 1085
    /// Copy an aggregate to a fresh stack slot, so bindings never read the source.
1086 1086
    StackCopy,
1087 1087
    /// Read an aggregate in place. Only valid when the source cannot change while
1088 -
    /// bindings that refer to it are live: the source is an immutable variable with
1089 -
    /// stable memory and every binding is immutable, or the only binding is a scalar
1090 -
    /// read out before any other code runs.
1088 +
    /// bindings that refer to it are live, or every binding copies its value before
1089 +
    /// user code can write the source.
1091 1090
    InPlace,
1092 1091
}
1093 1092
1094 1093
/// Classifies a match subject by how it should be compared and destructured.
1095 1094
union MatchSubjectKind: Copy {
2130 2129
    }
2131 2130
    set self.tables.traits[self.tables.traitBase + index].methods = &methods[..];
2132 2131
    return index;
2133 2132
}
2134 2133
2135 -
/// Whether a trait object type is a trait object slot. An unsafe trait object is
2136 -
/// plain data, since its receiver is.
2137 -
fn isTraitSlot(typ: resolver::Type) -> bool {
2138 -
    if let case resolver::Type::TraitObject { class, .. } = typ {
2139 -
        return class <> types::PointerClass::Unsafe;
2140 -
    }
2141 -
    return false;
2142 -
}
2143 -
2144 2134
/// Lower a method node into an IL function with the given qualified name.
2145 2135
/// Shared by both instance methods and standalone methods.
2146 2136
fn lowerMethod(
2147 2137
    self: &mut Lowerer,
2148 2138
    node: *ast::Node,
3596 3586
        let recInfo = recordInfoFromType(res, typ) else panic "slotValue: expected record type";
3597 3587
        return slotValue(res, recInfo.fields[0].fieldType);
3598 3588
    }
3599 3589
    match typ {
3600 3590
        case resolver::Type::Pointer { .. } => {
3601 -
            if isSlotType(typ) {
3591 +
            if resolver::isSlotType(typ) {
3602 3592
                return SlotValue::Pointer;
3603 3593
            }
3604 3594
        }
3605 3595
        case resolver::Type::Optional(resolver::Type::Pointer { .. }) => {
3606 -
            if isSlotType(typ) {
3596 +
            if resolver::isSlotType(typ) {
3607 3597
                return SlotValue::OptionalPointer;
3608 3598
            }
3609 3599
        }
3610 3600
        case resolver::Type::Fn(_) => return SlotValue::Fn,
3611 3601
        else                       => {}
4532 4522
    paramIdx: u32, // The index of the block parameter to set.
4533 4523
    val: il::Val   // The value to pass as the argument.
4534 4524
) throws (LowerError) {
4535 4525
    let ix = self.blockData[*from].instrs.len - 1; // The terminator is always the last instruction.
4536 4526
4537 -
    // Patch a copy of the terminator, because growing an argument range
4538 -
    // mutates the argument pool. The copy is stored back below, so later
4539 -
    // patches see the new range.
4540 -
    let mut instr = self.blockData[*from].instrs[ix];
4541 -
    match &mut instr {
4542 -
        case il::Instr::Jmp { args, .. } => {
4543 -
            set *args = try growArgs(self, *args, paramIdx + 1);
4544 -
            set self.argPool[(*args).start + paramIdx] = val;
4527 +
    // Growing an argument range mutates the argument pool, so the terminator is read by value
4528 +
    // and stored back with the new ranges, which later patches see.
4529 +
    match self.blockData[*from].instrs[ix] {
4530 +
        case il::Instr::Jmp { target: jumpTarget, args } => {
4531 +
            let grown = try growArgs(self, args, paramIdx + 1);
4532 +
            set self.argPool[grown.start + paramIdx] = val;
4533 +
            set self.blockData[*from].instrs[ix] = il::Instr::Jmp {
4534 +
                target: jumpTarget, args: grown
4535 +
            };
4545 4536
        }
4546 -
        case il::Instr::Br { thenTarget, thenArgs, elseTarget, elseArgs, .. } => {
4537 +
        case il::Instr::Br { op, typ, a, b, thenTarget, thenArgs, elseTarget, elseArgs } => {
4547 4538
            // Nb. both branches could target the same block (e.g. `if cond { x } else { x }`).
4548 -
            if *thenTarget == target {
4549 -
                set *thenArgs = try growArgs(self, *thenArgs, paramIdx + 1);
4550 -
                set self.argPool[(*thenArgs).start + paramIdx] = val;
4539 +
            let mut grownThen = thenArgs;
4540 +
            let mut grownElse = elseArgs;
4541 +
            if thenTarget == target {
4542 +
                set grownThen = try growArgs(self, thenArgs, paramIdx + 1);
4543 +
                set self.argPool[grownThen.start + paramIdx] = val;
4551 4544
            }
4552 -
            if *elseTarget == target {
4553 -
                set *elseArgs = try growArgs(self, *elseArgs, paramIdx + 1);
4554 -
                set self.argPool[(*elseArgs).start + paramIdx] = val;
4545 +
            if elseTarget == target {
4546 +
                set grownElse = try growArgs(self, elseArgs, paramIdx + 1);
4547 +
                set self.argPool[grownElse.start + paramIdx] = val;
4555 4548
            }
4549 +
            set self.blockData[*from].instrs[ix] = il::Instr::Br {
4550 +
                op,
4551 +
                typ,
4552 +
                a,
4553 +
                b,
4554 +
                thenTarget,
4555 +
                thenArgs: grownThen,
4556 +
                elseTarget,
4557 +
                elseArgs: grownElse,
4558 +
            };
4556 4559
        }
4557 -
        case il::Instr::Switch { defaultTarget, defaultArgs, cases, .. } => {
4558 -
            if *defaultTarget == target {
4559 -
                set *defaultArgs = try growArgs(self, *defaultArgs, paramIdx + 1);
4560 -
                set self.argPool[(*defaultArgs).start + paramIdx] = val;
4560 +
        case il::Instr::Switch { val: scrutinee, defaultTarget, defaultArgs, cases } => {
4561 +
            let mut grownDefault = defaultArgs;
4562 +
            if defaultTarget == target {
4563 +
                set grownDefault = try growArgs(self, defaultArgs, paramIdx + 1);
4564 +
                set self.argPool[grownDefault.start + paramIdx] = val;
4561 4565
            }
4562 4566
            let idx = paramIdx + 1;
4563 4567
            for ci in 0 .. cases.len {
4564 4568
                let caseIx = cases.start + ci;
4565 4569
                let c = self.caseList[caseIx];
4567 4571
                    let grown = try growArgs(self, c.args, idx);
4568 4572
                    set self.caseList[caseIx].args = grown;
4569 4573
                    set self.argPool[grown.start + paramIdx] = val;
4570 4574
                }
4571 4575
            }
4576 +
            set self.blockData[*from].instrs[ix] = il::Instr::Switch {
4577 +
                val: scrutinee, defaultTarget, defaultArgs: grownDefault, cases
4578 +
            };
4572 4579
        }
4573 4580
        else => {
4574 4581
            // Other terminators (e.g. `Ret`, `Unreachable`) don't have successor blocks.
4575 4582
        }
4576 4583
    }
4577 -
    set self.blockData[*from].instrs[ix] = instr;
4578 4584
}
4579 4585
4580 4586
/// Grow an argument range to hold at least the given capacity. A range that
4581 4587
/// must grow is copied to the end of the argument pool, and the new values
4582 4588
/// are `Undef`.
4988 4994
            continue;
4989 4995
        }
4990 4996
        // Positional variant patterns like `Variant(x, 7)`. Each argument matches
4991 4997
        // the payload field at its position.
4992 4998
        if let case ast::NodeValue::Call(call) = pattern.value {
4993 -
            if let case resolver::NodeExtra::UnionVariant { ordinal, .. } = resolver::extraFor(
4999 +
            if let case resolver::NodeExtra::UnionVariant { ordinal, tag } = resolver::extraFor(
4994 5000
                &self.resolver, pattern
4995 5001
            ) {
4996 5002
                let case MatchSubjectKind::Union(unionInfo) = subject.kind
4997 5003
                    else panic "bindPatternVariables: expected union subject";
4998 5004
                // The field types come from the variant's record info. They keep the
4999 5005
                // original data layout type (e.g. `*T`) even when the resolver resolved
5000 5006
                // the pattern against a dereferenced type (`T`).
5001 -
                let payloadRec = resolver::getRecord(
5002 -
                    &self.resolver, unionInfo.variants[ordinal].valueType
5003 -
                ) else panic "bindPatternVariables: expected record payload";
5007 +
                let payloadType = unionInfo.variants[ordinal].valueType;
5008 +
                let payloadRec = resolver::getRecord(&self.resolver, payloadType)
5009 +
                    else panic "bindPatternVariables: expected record payload";
5010 +
                let read = VariantRead { info: unionInfo, tag };
5004 5011
                let base = try emitValToReg(self, subject.val);
5005 5012
5006 5013
                for arg, i in call.args {
5007 5014
                    // Field offsets are relative to the payload, which follows the tag.
5008 -
                    let field = payloadRec.fields[i];
5009 -
                    let fieldInfo = resolver::RecordField {
5010 -
                        name: nil,
5011 -
                        fieldType: field.fieldType,
5012 -
                        offset: unionInfo.valOffset as i32 + field.offset,
5013 -
                    };
5014 -
                    try bindFieldVariable(self, arg, base, fieldInfo, subject.by, failBlock);
5015 +
                    let at = try unionField(self, read, base, arg, payloadRec.fields[i]);
5016 +
                    try bindFieldVariable(self, arg, at.base, at.field, subject.by, failBlock);
5015 5017
                }
5016 5018
            }
5017 5019
        }
5018 5020
        match pattern.value {
5019 5021
            // Compound variant patterns like `Variant { a, b }`.
5101 5103
                );
5102 5104
            }
5103 5105
            return;
5104 5106
        }
5105 5107
        let base = try emitValToReg(self, subject.val);
5106 -
        try bindNestedRecordFields(self, base, lit, recInfo, subject.by, failBlock);
5108 +
        try bindNestedRecordFields(self, base, lit, recInfo, subject.by, failBlock, nil);
5107 5109
        return;
5108 5110
    }
5109 5111
    // Get the union type info from the subject.
5110 5112
    let case MatchSubjectKind::Union(unionInfo) = subject.kind
5111 5113
        else panic "bindRecordPatternFields: expected union subject";
5112 5114
5113 5115
    // Get the variant index from the pattern node.
5114 -
    let case resolver::NodeExtra::UnionVariant { ordinal: variantOrdinal, .. } = resolver::extraFor(
5115 -
        &self.resolver, pattern
5116 -
    ) else throw LowerError::MissingMetadata;
5116 +
    let case resolver::NodeExtra::UnionVariant {
5117 +
        ordinal: variantOrdinal, tag: variantTag
5118 +
    } = resolver::extraFor(&self.resolver, pattern) else throw LowerError::MissingMetadata;
5117 5119
5118 5120
    // Get the record type from the variant's payload type.
5119 5121
    let payloadType = unionInfo.variants[variantOrdinal].valueType;
5120 5122
    let recInfo = resolver::getRecord(&self.resolver, payloadType)
5121 5123
        else throw LowerError::ExpectedRecord;
5122 5124
5123 5125
    // Get the payload base pointer which points to the record within the tagged union.
5124 5126
    let base = try emitValToReg(self, subject.val);
5125 -
    let valOffset = unionInfo.valOffset as i32;
5126 -
    let payloadBase = try emitPtrOffset(self, base, valOffset);
5127 -
5128 -
    try bindNestedRecordFields(self, payloadBase, lit, recInfo, subject.by, failBlock);
5127 +
    if not unionInfo.mixed {
5128 +
        let payloadBase = try emitPtrOffset(self, base, unionInfo.valOffset as i32);
5129 +
        try bindNestedRecordFields(self, payloadBase, lit, recInfo, subject.by, failBlock, nil);
5130 +
        return;
5131 +
    }
5132 +
    let read = VariantRead { info: unionInfo, tag: variantTag };
5133 +
    try bindNestedRecordFields(self, base, lit, recInfo, subject.by, failBlock, read);
5129 5134
}
5130 5135
5131 5136
/// Bind a single record field to a pattern variable, with support for nested
5132 5137
/// pattern tests that branch to `failBlock` on mismatch.
5133 5138
fn bindFieldVariable(
5174 5179
                set derefType = *target;
5175 5180
            }
5176 5181
            let recInfo = resolver::getRecord(&self.resolver, derefType)
5177 5182
                else throw LowerError::ExpectedRecord;
5178 5183
5179 -
            try bindNestedRecordFields(self, nestedBase, lit, recInfo, matchBy, failBlock);
5184 +
            try bindNestedRecordFields(self, nestedBase, lit, recInfo, matchBy, failBlock, nil);
5180 5185
        }
5181 5186
        else => {
5182 5187
            // Nested pattern requiring a test (union variant scope access, literal, etc).
5183 5188
            try emitNestedFieldTest(self, binding, base, fieldInfo, matchBy, failBlock);
5184 5189
        }
5324 5329
            }
5325 5330
        }
5326 5331
    }
5327 5332
}
5328 5333
5329 -
/// Bind variables from a nested record literal pattern.
5334 +
/// Bind variables from a nested record literal pattern. The record is the payload of the variant
5335 +
/// `read` of the union at `base` when there is one, and then field offsets are from the payload.
5330 5336
fn bindNestedRecordFields(
5331 5337
    self: &mut Lowerer,
5332 5338
    base: il::Reg,
5333 5339
    lit: ast::RecordLit,
5334 5340
    recInfo: resolver::RecordType,
5335 5341
    matchBy: resolver::MatchBy,
5336 -
    failBlock: ?BlockId
5342 +
    failBlock: ?BlockId,
5343 +
    read: ?VariantRead
5337 5344
) throws (LowerError) {
5338 5345
    for fieldNode in lit.fields {
5339 5346
        let case ast::NodeValue::RecordLitField(field) = fieldNode.value else {
5340 5347
            throw LowerError::UnexpectedNodeValue(fieldNode);
5341 5348
        };
5342 5349
        let fieldIdx = resolver::recordFieldIndexFor(&self.resolver, fieldNode)
5343 5350
            else throw LowerError::MissingMetadata;
5344 5351
        if fieldIdx >= recInfo.fields.len {
5345 5352
            throw LowerError::MissingMetadata;
5346 5353
        }
5347 -
        let fieldInfo = recInfo.fields[fieldIdx];
5348 -
5349 -
        try bindFieldVariable(self, field.value, base, fieldInfo, matchBy, failBlock);
5354 +
        let mut at = FieldAt { base, field: recInfo.fields[fieldIdx] };
5355 +
        if let variant = read {
5356 +
            set at = try unionField(self, variant, base, field.value, at.field);
5357 +
        }
5358 +
        try bindFieldVariable(self, field.value, at.base, at.field, matchBy, failBlock);
5350 5359
    }
5351 5360
}
5352 5361
5353 5362
/// Lower function body to a list of basic blocks.
5354 5363
fn lowerFnBody(self: &mut Lowerer, body: *ast::Node) -> *[il::Block] throws (LowerError) {
5543 5552
///
5544 5553
fn lowerMatch(self: &mut Lowerer, node: *ast::Node, m: ast::Match) throws (LowerError) {
5545 5554
    assert m.prongs.len > 0;
5546 5555
5547 5556
    let prongs = m.prongs;
5548 -
    // Lower the subject expression once; reused across all arms.
5549 -
    let subject = try lowerMatchSubject(self, m.subject, subjectStorage(self, m.subject, false));
5557 +
    // Lower the subject expression once; reused across all arms. Mixed union fields
5558 +
    // are copied when bound. A guard or a whole-value binding also needs the subject
5559 +
    // to keep its bytes for later reads.
5560 +
    let mut storage = subjectStorage(self, m.subject, false);
5561 +
    let ty = resolver::unwrapMatchSubject(try typeOf(self, m.subject)).effectiveTy;
5562 +
    if let unionInfo = unionInfoFromType(&self.resolver, ty); unionInfo.mixed {
5563 +
        let mut snapshot = false;
5564 +
        for prongNode in prongs {
5565 +
            let case ast::NodeValue::MatchProng(prong) = prongNode.value
5566 +
                else panic "lowerMatch: expected match prong";
5567 +
            if prong.guard <> nil {
5568 +
                set snapshot = true;
5569 +
            }
5570 +
            if let case ast::ProngArm::Binding(_) = prong.arm {
5571 +
                set snapshot = true;
5572 +
            }
5573 +
        }
5574 +
        if not snapshot {
5575 +
            set storage = SubjectStorage::InPlace;
5576 +
        }
5577 +
    }
5578 +
    let subject = try lowerMatchSubject(self, m.subject, storage);
5550 5579
    // Merge block created lazily if any arm needs it (i.e., doesn't diverge).
5551 5580
    let mut mergeBlock: ?BlockId = nil;
5552 5581
5553 5582
    // Use `switch` instruction for matches with constant patterns.
5554 5583
    if resolver::isMatchConst(&self.resolver, node) {
5680 5709
}
5681 5710
5682 5711
/// Choose how the subject of an `if let`, `while let` or `let ... else` pattern is
5683 5712
/// held. A binding pattern of a scalar value reads the value out of the subject
5684 5713
/// before the body or guard runs, so nothing refers to the subject afterwards and
5685 -
/// it is read in place. Other patterns follow [`subjectStorage`].
5714 +
/// it is read in place. A mixed union case also copies its bound fields before
5715 +
/// the body or guard runs. Other patterns follow [`subjectStorage`].
5686 5716
fn patternStorage(self: &mut Lowerer, pat: &ast::PatternMatch) -> SubjectStorage
5687 5717
    throws (LowerError)
5688 5718
{
5719 +
    if pat.kind == ast::PatternKind::Case {
5720 +
        let ty = resolver::unwrapMatchSubject(try typeOf(self, pat.scrutinee)).effectiveTy;
5721 +
        if let unionInfo = unionInfoFromType(&self.resolver, ty); unionInfo.mixed {
5722 +
            return SubjectStorage::InPlace;
5723 +
        }
5724 +
    }
5689 5725
    if pat.kind == ast::PatternKind::Binding {
5690 5726
        let unwrapped = resolver::unwrapMatchSubject(try typeOf(self, pat.scrutinee));
5691 5727
        let mut bound = unwrapped.effectiveTy;
5692 5728
        if let case resolver::Type::Optional(inner) = bound {
5693 5729
            set bound = *inner;
6227 6263
        }
6228 6264
    }
6229 6265
    return il::Val::Reg(dst);
6230 6266
}
6231 6267
6268 +
/// Get the tag byte of the union variant that the symbol `sym` names.
6269 +
fn variantTag(res: &resolver::Resolver, sym: resolver::SymbolId) -> u32 {
6270 +
    let case resolver::SymbolData::Variant { index, .. } = res.symbols[*sym].data
6271 +
        else panic "variantTag: not a variant";
6272 +
    return index;
6273 +
}
6274 +
6275 +
/// Emit the write of the variant `tag` into the mixed union at `dst`: the tag, and the payload
6276 +
/// at `payload` unless the variant has none. The tag and the payload move together.
6277 +
fn emitUnionSet(
6278 +
    self: &mut Lowerer,
6279 +
    dst: il::Reg,
6280 +
    tag: i64,
6281 +
    valOffset: i32,
6282 +
    payload: ?il::Reg,
6283 +
    payloadType: resolver::Type
6284 +
) throws (LowerError) {
6285 +
    let mut src = il::Val::Undef;
6286 +
    let mut layout: ?u32 = nil;
6287 +
    if let reg = payload {
6288 +
        set src = il::Val::Reg(reg);
6289 +
        set layout = try layoutOf(self, payloadType);
6290 +
    }
6291 +
    try emit(self, il::Instr::UnionSet {
6292 +
        dst, tag: tag as u32, offset: valOffset as u32, src, layout
6293 +
    });
6294 +
}
6295 +
6296 +
/// Build a value of the union type `unionTy` that holds the variant `tag`, with `payload` of
6297 +
/// type `payloadType` unless it is void.
6298 +
fn buildUnion(
6299 +
    self: &mut Lowerer,
6300 +
    unionTy: resolver::Type,
6301 +
    unionInfo: resolver::UnionType,
6302 +
    tag: i64,
6303 +
    payload: ?il::Val,
6304 +
    payloadType: resolver::Type
6305 +
) -> il::Val throws (LowerError) {
6306 +
    let layout = try layoutOf(self, unionTy);
6307 +
    let valOffset = unionInfo.valOffset as i32;
6308 +
    if not unionInfo.mixed {
6309 +
        return try buildTagged(self, layout, tag, payload, payloadType, 1, valOffset);
6310 +
    }
6311 +
    let dst = try emitReserveIndex(self, layout);
6312 +
    let mut src: ?il::Reg = nil;
6313 +
    if let val = payload {
6314 +
        if payloadType <> resolver::Type::Void {
6315 +
            // The payload is an object in memory, which a scalar record is not.
6316 +
            if isAggregateType(&self.resolver, payloadType) {
6317 +
                set src = try emitValToReg(self, val);
6318 +
            } else {
6319 +
                set src = try emitValToReg(self, try emitStackVal(self, payloadType, val));
6320 +
            }
6321 +
        }
6322 +
    }
6323 +
    try emitUnionSet(self, dst, tag, valOffset, src, payloadType);
6324 +
    return il::Val::Reg(dst);
6325 +
}
6326 +
6327 +
/// A variant whose payload fields a pattern reads.
6328 +
record VariantRead: Copy {
6329 +
    /// The union type.
6330 +
    info: resolver::UnionType,
6331 +
    /// Tag of the variant.
6332 +
    tag: u32,
6333 +
}
6334 +
6335 +
/// A field to read: a register that addresses it, and the field with its offset from there.
6336 +
record FieldAt: Copy {
6337 +
    /// Address that the offset is relative to.
6338 +
    base: il::Reg,
6339 +
    /// The field, with its offset.
6340 +
    field: resolver::RecordField,
6341 +
}
6342 +
6343 +
/// Find the field `field` of the payload of `read`, bound by `binding`, in the union that `base`
6344 +
/// addresses. The offset of `field` is from the start of the payload. A field of a mixed union
6345 +
/// that is a slot or an aggregate is copied to an object of its own, and the copy checks the tag.
6346 +
/// Plain scalars are loaded in place, since the tag test selected the variant, and other
6347 +
/// unions are read in place.
6348 +
fn unionField(
6349 +
    self: &mut Lowerer,
6350 +
    read: VariantRead,
6351 +
    base: il::Reg,
6352 +
    binding: *ast::Node,
6353 +
    field: resolver::RecordField
6354 +
) -> FieldAt throws (LowerError) {
6355 +
    let offset = read.info.valOffset as i32 + field.offset;
6356 +
    let typ = field.fieldType;
6357 +
    if binding.value == ast::NodeValue::Placeholder
6358 +
        or not (isAggregateType(&self.resolver, typ)
6359 +
            or slotValue(&self.resolver, typ) <> SlotValue::Data)
6360 +
        or not read.info.mixed
6361 +
    {
6362 +
        return FieldAt { base, field: resolver::RecordField { name: nil, fieldType: typ, offset } };
6363 +
    }
6364 +
    let dst = try emitReserve(self, typ);
6365 +
    try emit(self, il::Instr::UnionGet {
6366 +
        dst, src: base, tag: read.tag, offset: offset as u32, layout: try layoutOf(self, typ)
6367 +
    });
6368 +
    return FieldAt {
6369 +
        base: dst, field: resolver::RecordField { name: nil, fieldType: typ, offset: 0 }
6370 +
    };
6371 +
}
6372 +
6232 6373
/// Build a present or absent optional value.
6233 6374
///
6234 6375
/// Optional pointers and slices use present values as-is, since valid values
6235 6376
/// have non-null data pointers. Absent values use a null pointer or zero slice.
6236 6377
/// Other optionals use a tagged aggregate with tag `1` and a payload when
6273 6414
    let throwList = currentFnType(self).throwList;
6274 6415
    let layout = try resultLayoutOf(self, successType, throwList);
6275 6416
    // A success value is at the start of the payload region, and an error is after it.
6276 6417
    let mut valOffset = RESULT_VAL_OFFSET;
6277 6418
    if tag <> 0 {
6278 -
        set valOffset = try resultErrOffset(self, successType, throwList);
6419 +
        set valOffset = resultErrOffset(self, successType, throwList, payloadType);
6279 6420
    }
6280 6421
    return try buildTagged(
6281 6422
        self, layout, tag, payload, payloadType, resolver::PTR_SIZE as i32, valOffset
6282 6423
    );
6283 6424
}
6312 6453
    count: u32,
6313 6454
    start: il::Val,
6314 6455
    end: il::Val
6315 6456
) -> il::Val throws (LowerError) {
6316 6457
    let item = sliceItem(sliceType);
6317 -
    if not isSlotType(sliceType) {
6458 +
    if not resolver::isSlotType(sliceType) {
6318 6459
        // An unsafe slice is built from raw fields.
6319 6460
        let mut ptr = base;
6320 6461
        let mut len = end;
6321 6462
        if start <> il::Val::Imm(0) {
6322 6463
            let stride = resolver::getTypeLayout(&self.resolver, *item).size;
6391 6532
    instId: resolver::InstanceId
6392 6533
) -> il::Val throws (LowerError) {
6393 6534
    let inst = self.resolver.instances[*instId];
6394 6535
    let traitName = self.resolver.traits[*traitInfo].name;
6395 6536
    let vName = try vtableName(self, inst.moduleId, inst.concreteTypeName, traitName);
6396 -
    if isTraitSlot(objType) {
6537 +
    if resolver::isTraitSlot(objType) {
6397 6538
        let slot = try emitReserve(self, objType);
6398 6539
        let recv = try emitValToReg(self, dataVal);
6399 6540
        try emit(self, il::Instr::TraitNew { dst: slot, recv, table: il::Val::DataSym(vName) });
6400 6541
        return il::Val::Reg(slot);
6401 6542
    }
6588 6729
) -> il::Val throws (LowerError) {
6589 6730
    // For aggregate types, pass offset through and compare recursively.
6590 6731
    if isAggregateType(&self.resolver, fieldType) {
6591 6732
        return try lowerAggregateEq(self, fieldType, left, right, offset);
6592 6733
    }
6593 -
    // For scalar types, load and compare directly.
6594 -
    let a = try emitLoad(self, left, offset, fieldType);
6595 -
    let b = try emitLoad(self, right, offset, fieldType);
6734 +
    // Equality compares scalar bits without using a pointer or function value.
6735 +
    // These reads do not need the rights of a typed slot load.
6736 +
    let readType = resolver::Type::U64
6737 +
        if slotValue(&self.resolver, fieldType) <> SlotValue::Data
6738 +
        else fieldType;
6739 +
    let a = try emitLoad(self, left, offset, readType);
6740 +
    let b = try emitLoad(self, right, offset, readType);
6596 6741
    let dst = nextReg(self);
6597 6742
    try emit(self, il::Instr::BinOp { op: il::BinOp::Eq, typ: ilType(self, fieldType), dst, a, b });
6598 6743
6599 6744
    return il::Val::Reg(dst);
6600 6745
}
6808 6953
    let caseStart = self.caseList.len;
6809 6954
6810 6955
    let mut caseBlocks: [?BlockId; resolver::MAX_UNION_VARIANTS] =
6811 6956
        [nil; resolver::MAX_UNION_VARIANTS];
6812 6957
    for variant, i in unionInfo.variants {
6958 +
        let tag = variantTag(&self.resolver, variant.symbol) as i64;
6813 6959
        if variant.valueType == resolver::Type::Void {
6814 6960
            try self.caseList.append(
6815 6961
                il::SwitchCase {
6816 -
                    value: i as i64,
6962 +
                    value: tag,
6817 6963
                    target: *mergeBlock,
6818 6964
                    args: trueArgs,
6819 6965
                },
6820 6966
                self.fnArena
6821 6967
            ) catch {
6824 6970
            set caseBlocks[i] = nil;
6825 6971
        } else {
6826 6972
            let payloadBlock = try createBlock(self, "eq#payload");
6827 6973
            try self.caseList.append(
6828 6974
                il::SwitchCase {
6829 -
                    value: i as i64,
6975 +
                    value: tag,
6830 6976
                    target: *payloadBlock,
6831 6977
                    args: il::ArgRange { start: 0, len: 0 },
6832 6978
                },
6833 6979
                self.fnArena
6834 6980
            ) catch {
6855 7001
        } else {
6856 7002
            try addPredecessor(self, mergeBlock, tagBlock);
6857 7003
        }
6858 7004
    }
6859 7005
    let valOffset = unionInfo.valOffset as i32;
6860 -
6861 7006
    // Emit payload comparison blocks for non-void variants.
6862 7007
    for variant, i in unionInfo.variants {
6863 7008
        if let caseBlock = caseBlocks[i] {
6864 7009
            try switchToAndSeal(self, caseBlock);
6865 7010
            let payloadEq = try emitEqAtOffset(
6975 7120
            throw LowerError::MissingMetadata;
6976 7121
        };
6977 7122
        let valOffset = unionInfo.valOffset as i32;
6978 7123
        let dst = try emitReserve(self, typ);
6979 7124
7125 +
        if unionInfo.mixed {
7126 +
            let payload = try emitReserve(self, payloadType);
7127 +
            try lowerRecordFields(self, payload, &recInfo, lit.fields, 0);
7128 +
            try emitUnionSet(self, dst, index as i64, valOffset, payload, payloadType);
7129 +
            return il::Val::Reg(dst);
7130 +
        }
6980 7131
        try emitStoreW8At(self, il::Val::Imm(index as i64), dst, TVAL_TAG_OFFSET);
6981 7132
        try lowerRecordFields(self, dst, &recInfo, lit.fields, valOffset);
6982 7133
6983 7134
        return il::Val::Reg(dst);
6984 7135
    }
7085 7236
    let length = arrInfo.length;
7086 7237
    let elemLayout = resolver::getTypeLayout(&self.resolver, elemTy);
7087 7238
    let size = elemLayout.size;
7088 7239
    let isWordFill = length > REPEAT_UNROLL_MAX
7089 7240
        and (size == 1 or size == 2 or size == 4 or size == 8)
7090 -
        and not try hasSlots(self, elemTy);
7241 +
        and not resolver::hasSlots(&mut self.resolver, elemTy);
7091 7242
7092 7243
    // A word fill stores double words, so the array starts at an 8-byte boundary.
7093 7244
    let mut layout = resolver::getTypeLayout(&self.resolver, typ);
7094 7245
    if isWordFill {
7095 7246
        set layout.alignment = COPY_WORD_MAX;
7285 7436
        throw LowerError::ExpectedVariant;
7286 7437
    };
7287 7438
    let unionInfo = unionInfoFromType(&self.resolver, unionTy) else {
7288 7439
        throw LowerError::MissingMetadata;
7289 7440
    };
7290 -
    let valOffset = unionInfo.valOffset as i32;
7291 7441
    let mut payloadVal: ?il::Val = nil;
7292 7442
    if payloadType <> resolver::Type::Void {
7293 7443
        let case resolver::Type::Nominal(payloadNominal) = payloadType else {
7294 7444
            throw LowerError::MissingMetadata;
7295 7445
        };
7296 7446
        set payloadVal = try lowerRecordCtor(self, payloadNominal, call.args);
7297 7447
    }
7298 -
    return try buildTagged(
7299 -
        self, try layoutOf(self, unionTy), index as i64, payloadVal, payloadType, 1, valOffset
7300 -
    );
7448 +
    return try buildUnion(self, unionTy, unionInfo, index as i64, payloadVal, payloadType);
7301 7449
}
7302 7450
7303 7451
/// Lower a field access into a pointer to the field.
7304 7452
fn lowerFieldRef(self: &mut Lowerer, access: ast::Access) -> FieldRef throws (LowerError) {
7305 7453
    let parentTy = try typeOf(self, access.parent);
7417 7565
) -> il::Val throws (LowerError) {
7418 7566
    let info = resolver::sliceRangeInfoFor(&self.resolver, sliceNode) else {
7419 7567
        throw LowerError::MissingMetadata;
7420 7568
    };
7421 7569
    let sliceTy = try typeOf(self, sliceNode);
7422 -
    if not isSlotType(sliceTy) {
7570 +
    if not resolver::isSlotType(sliceTy) {
7423 7571
        let r = try resolveSliceRangePtr(self, container, range, info);
7424 7572
        return try buildRawSliceValue(
7425 7573
            self, info.itemType, info.mutable, il::Val::Reg(r.dataReg), r.count, r.capacity
7426 7574
        );
7427 7575
    }
7610 7758
    let indexVal = try lowerExpr(self, index);
7611 7759
    let baseReg = try emitValToReg(self, baseVal);
7612 7760
7613 7761
    match subjectTy {
7614 7762
        case resolver::Type::Slice { item, .. } => {
7615 -
            if isSlotType(subjectTy) {
7763 +
            if resolver::isSlotType(subjectTy) {
7616 7764
                let elemReg = try emitSliceElemAt(self, baseReg, indexVal, *item);
7617 7765
                return ElemPtrResult { elemReg, elemType: *item };
7618 7766
            }
7619 7767
            // An unsafe slice has no layout, so its length and pointer are plain fields.
7620 7768
            let sliceLen = try loadSliceLen(self, baseReg);
8023 8171
/// Whether the elements that `container` holds are described by a layout, so that
8024 8172
/// the instructions can check ranges and indices. An unsafe slice has no layout.
8025 8173
fn isChecked(self: &mut Lowerer, container: *ast::Node) -> bool throws (LowerError) {
8026 8174
    let subject = resolver::autoDeref(try typeOf(self, container));
8027 8175
    if let case resolver::Type::Slice { .. } = subject {
8028 -
        return isSlotType(subject);
8176 +
        return resolver::isSlotType(subject);
8029 8177
    }
8030 8178
    return true;
8031 8179
}
8032 8180
8033 8181
/// Lower `slice[range] = value`.
8391 8539
                // Array (length is known).
8392 8540
                set lengthVal = il::Val::Imm(len as i64);
8393 8541
            } else {
8394 8542
                // Slice (length must be loaded).
8395 8543
                set lengthVal = try loadSliceLen(self, containerReg);
8396 -
                if not isSlotType(resolver::autoDeref(try typeOf(self, f.iterable))) {
8544 +
                if not resolver::isSlotType(resolver::autoDeref(try typeOf(self, f.iterable))) {
8397 8545
                    set rawData = try loadSlicePtr(self, containerReg);
8398 8546
                }
8399 8547
            }
8400 8548
            let mut valVar: ?Var = nil;
8401 8549
            if bindingName <> nil {
9152 9300
            if let binding = first.binding {
9153 9301
                let case ast::NodeValue::Ident(name) = binding.value else {
9154 9302
                    throw LowerError::ExpectedIdentifier;
9155 9303
                };
9156 9304
                let errTy = *calleeInfo.throwList[0];
9157 -
                let errOffset = try resultErrOffset(
9158 -
                    self, *calleeInfo.returnType, calleeInfo.throwList
9305 +
                let errOffset = resultErrOffset(
9306 +
                    self, *calleeInfo.returnType, calleeInfo.throwList, errTy
9159 9307
                );
9160 9308
                let errVal = try tvalPayloadVal(self, base, errTy, errOffset);
9161 9309
                try newVar(self, name, try valTypeOf(self, errTy), false, errVal);
9162 9310
            }
9163 9311
            try lowerBlock(self, first.body);
9169 9317
        // TODO: We should have some kind of `panic` instruction?
9170 9318
        try emit(self, il::Instr::Unreachable);
9171 9319
    } else {
9172 9320
        // Plain `try` -- propagate the error to the caller by returning early.
9173 9321
        // Forward the callee's global error tag and payload directly.
9174 -
        let errLayout = try errorCopyLayout(self, calleeInfo.throwList);
9175 9322
        let callerType = *currentFnType(self).returnType;
9176 9323
        let callerThrows = currentFnType(self).throwList;
9177 9324
        let dst = try emitReserveIndex(self, try resultLayoutOf(self, callerType, callerThrows));
9178 9325
9179 9326
        try emitStoreW64At(self, il::Val::Reg(tagReg), dst, TVAL_TAG_OFFSET);
9180 -
        let calleeOffset = try resultErrOffset(self, *calleeInfo.returnType, calleeInfo.throwList);
9181 -
        let srcPayload = try emitPtrOffset(self, base, calleeOffset);
9182 -
        let dstPayload = try emitPtrOffset(
9183 -
            self,
9184 -
            dst,
9185 -
            try resultErrOffset(
9186 -
                self, callerType, callerThrows
9187 -
            )
9188 -
        );
9189 -
        try emit(self, il::Instr::Blit { dst: dstPayload, src: srcPayload, layout: errLayout });
9190 -
9327 +
        let calleeLayout = resultLayoutInfo(self, *calleeInfo.returnType, calleeInfo.throwList);
9328 +
        let callerLayout = resultLayoutInfo(self, callerType, callerThrows);
9329 +
        if calleeLayout.separateErrors or callerLayout.separateErrors {
9330 +
            // Inactive error regions hold valid zero values and can be copied
9331 +
            // with the active one.
9332 +
            for errType in calleeInfo.throwList {
9333 +
                let srcOffset = resultErrOffset(
9334 +
                    self, *calleeInfo.returnType, calleeInfo.throwList, *errType
9335 +
                );
9336 +
                let dstOffset = resultErrOffset(self, callerType, callerThrows, *errType);
9337 +
                let value = try tvalPayloadVal(self, base, *errType, srcOffset);
9338 +
                try emitStore(self, dst, dstOffset, *errType, value);
9339 +
            }
9340 +
        } else {
9341 +
            let srcPayload = try emitPtrOffset(self, base, calleeLayout.errOffset as i32);
9342 +
            let dstPayload = try emitPtrOffset(self, dst, callerLayout.errOffset as i32);
9343 +
            try emit(self, il::Instr::Blit {
9344 +
                dst: dstPayload,
9345 +
                src: srcPayload,
9346 +
                layout: try errorCopyLayout(self, calleeInfo.throwList),
9347 +
            });
9348 +
        }
9191 9349
        try emitRetVal(self, il::Val::Reg(dst));
9192 9350
    }
9193 9351
    // Switch to the merge block if one was created. If all paths diverged
9194 9352
    // (e.g both success and error returned), there's no merge block.
9195 9353
    if let blk = mergeBlock {
9283 9441
        if let binding = clause.binding {
9284 9442
            let case ast::NodeValue::Ident(name) = binding.value else {
9285 9443
                throw LowerError::ExpectedIdentifier;
9286 9444
            };
9287 9445
            let errTy = errTypes[i] else panic "lowerMultiCatch: catch-all with binding";
9288 -
            let errOffset = try resultErrOffset(self, *calleeInfo.returnType, calleeInfo.throwList);
9446 +
            let errOffset = resultErrOffset(
9447 +
                self, *calleeInfo.returnType, calleeInfo.throwList, errTy
9448 +
            );
9289 9449
            let errVal = try tvalPayloadVal(self, base, errTy, errOffset);
9290 9450
9291 9451
            try newVar(self, name, try valTypeOf(self, errTy), false, errVal);
9292 9452
        }
9293 9453
        try lowerBlock(self, clause.body);
9686 9846
) throws (LowerError) {
9687 9847
    let errId = self.resolver.allocError else panic "emitAllocationFailure: missing AllocError";
9688 9848
    let errType = resolver::Type::Nominal(errId);
9689 9849
    let tag = try getOrAssignErrorTag(self, errType) as i64;
9690 9850
    try emitStoreW64At(self, il::Val::Imm(tag), result, TVAL_TAG_OFFSET);
9691 -
    let errOffset = try resultErrOffset(self, *info.returnType, info.throwList);
9851 +
    let errOffset = resultErrOffset(self, *info.returnType, info.throwList, errType);
9692 9852
    try emitStore(self, result, errOffset, errType, il::Val::Imm(0));
9693 9853
    try emitJmp(self, doneBlock);
9694 9854
}
9695 9855
9696 9856
/// Set the length of the slice at `sliceReg` with `slice.len`, which checks the capacity,
10203 10363
    let traitObjVal = try lowerExpr(self, access.parent);
10204 10364
    let traitObjReg = try emitValToReg(self, traitObjVal);
10205 10365
    let methodFnType = self.resolver.traits[*traitInfo].methods[methodIndex].fnType;
10206 10366
    let argOffset: u32 = 1 if requiresReturnParam(&self.resolver, methodFnType) else 0;
10207 10367
10208 -
    if isTraitSlot(resolver::autoDeref(try typeOf(self, access.parent))) {
10368 +
    if resolver::isTraitSlot(resolver::autoDeref(try typeOf(self, access.parent))) {
10209 10369
        // The call passes the receiver of the object in its place among the arguments.
10210 10370
        let args = try allocVals(self, call.args.len + 1 + argOffset);
10211 10371
        set self.argPool[args.start + argOffset] = il::Val::Undef;
10212 10372
        for arg, i in call.args {
10213 10373
            let val = try lowerCallArg(
10284 10444
/// to an object views only its own layout, and the rights are part of the layout. Any
10285 10445
/// other argument is unchanged.
10286 10446
fn narrowObject(
10287 10447
    self: &mut Lowerer, val: il::Val, from: resolver::Type, to: resolver::Type
10288 10448
) -> il::Val throws (LowerError) {
10289 -
    if not isTraitSlot(from) or not isTraitSlot(to) or resolver::typesEqual(from, to) {
10449 +
    if not resolver::isTraitSlot(from)
10450 +
        or not resolver::isTraitSlot(to)
10451 +
        or resolver::typesEqual(from, to)
10452 +
    {
10290 10453
        return val;
10291 10454
    }
10292 10455
    let src = try emitValToReg(self, val);
10293 10456
    let dst = try emitReserve(self, to);
10294 10457
10789 10952
                return il::Val::Imm(indexValue);
10790 10953
            }
10791 10954
            let unionInfo = unionInfoFromType(&self.resolver, ty) else {
10792 10955
                throw LowerError::MissingMetadata;
10793 10956
            };
10794 -
            let valOffset = unionInfo.valOffset as i32;
10795 -
            return try buildTagged(
10796 -
                self, try layoutOf(self, ty), indexValue, nil, resolver::Type::Void, 1, valOffset
10797 -
            );
10957 +
            return try buildUnion(self, ty, unionInfo, indexValue, nil, resolver::Type::Void);
10798 10958
        }
10799 10959
        case resolver::SymbolData::Constant { type, .. } => {
10800 10960
            // Constant without compile-time value (e.g. record constant);
10801 10961
            // load from data section.
10802 10962
            let src = try emitDataAddr(self, sym);
11005 11165
    index: u32,
11006 11166
}
11007 11167
11008 11168
/// Layout state of a nominal type, indexed by nominal id.
11009 11169
record NominalLayout: Copy {
11010 -
    /// Whether the type has slots. Nil until it is first needed.
11011 -
    slots: ?bool,
11012 11170
    /// Index of the layout in the tables of the package. Nil until the layout is numbered.
11013 11171
    index: ?u32,
11014 11172
}
11015 11173
11016 11174
/// A numbered layout whose slots are not computed yet.
11027 11185
    Nested,
11028 11186
    /// Describe every slot.
11029 11187
    Full,
11030 11188
}
11031 11189
11032 -
/// Payload types that share the payload region of a union or result.
11033 -
record PayloadScan: Copy {
11034 -
    /// The first payload type. Nil while there is none.
11035 -
    first: ?resolver::Type,
11036 -
    /// Whether all payload types seen so far have the same shape.
11037 -
    same: bool,
11038 -
}
11039 -
11040 11190
/// Combine a hash with a number.
11041 11191
fn mixKey(h: u32, x: u32) -> u32 {
11042 11192
    return ((h << 5) | (h >> 27)) ^ x;
11043 11193
}
11044 11194
11086 11236
        }
11087 11237
    }
11088 11238
    return true;
11089 11239
}
11090 11240
11091 -
/// Whether a value of `typ` is a single slot: a pointer or slice that the verifier
11092 -
/// tracks, or a function value. Unsafe pointers and pointers to `opaque` are plain data.
11093 -
fn isSlotType(typ: resolver::Type) -> bool {
11094 -
    match typ {
11095 -
        case resolver::Type::Pointer { class, target, .. } =>
11096 -
            return class <> types::PointerClass::Unsafe and *target <> resolver::Type::Opaque,
11097 -
        case resolver::Type::Slice { class, item, .. } =>
11098 -
            return class <> types::PointerClass::Unsafe and *item <> resolver::Type::Opaque,
11099 -
        case resolver::Type::Fn(_)              => return true,
11100 -
        case resolver::Type::TraitObject { .. } => return isTraitSlot(typ),
11101 -
        case resolver::Type::Optional(inner) =>
11102 -
            return resolver::isNullableType(*inner) and isSlotType(*inner),
11103 -
        else => return false,
11104 -
    }
11105 -
}
11106 -
11107 -
/// Whether two types describe the same bytes: they are equal, or they are records whose
11108 -
/// fields have the same offsets and the same shapes, or arrays or optionals of the same
11109 -
/// shape. The payload of a union variant is a record of its own, so two variants with equal
11110 -
/// payload types still have different record types.
11111 -
fn sameShape(res: &resolver::Resolver, a: resolver::Type, b: resolver::Type) -> bool {
11112 -
    if resolver::typesEqual(a, b) {
11113 -
        return true;
11241 +
/// Get the type that describes the payload region of a union.
11242 +
fn unionPayload(self: &mut Lowerer, unionInfo: resolver::UnionType) -> ?resolver::Type {
11243 +
    if unionInfo.mixed {
11244 +
        return nil;
11114 11245
    }
11115 -
    match a {
11116 -
        case resolver::Type::Array(x) => {
11117 -
            let case resolver::Type::Array(y) = b else return false;
11118 -
            return x.length == y.length and sameShape(res, *x.item, *y.item);
11119 -
        }
11120 -
        case resolver::Type::Optional(x) => {
11121 -
            let case resolver::Type::Optional(y) = b else return false;
11122 -
            return sameShape(res, *x, *y);
11123 -
        }
11124 -
        case resolver::Type::Nominal(x) => {
11125 -
            let case resolver::Type::Nominal(y) = b else return false;
11126 -
            let case resolver::NominalType::Record(left) = res.nominals[*x] else return false;
11127 -
            let case resolver::NominalType::Record(right) = res.nominals[*y] else return false;
11128 -
            if left.fields.len <> right.fields.len {
11129 -
                return false;
11130 -
            }
11131 -
            for i in 0 .. left.fields.len {
11132 -
                if left.fields[i].offset <> right.fields[i].offset
11133 -
                    or not sameShape(res, left.fields[i].fieldType, right.fields[i].fieldType)
11134 -
                {
11135 -
                    return false;
11136 -
                }
11137 -
            }
11138 -
            return true;
11246 +
    for variant in unionInfo.variants {
11247 +
        if resolver::hasSlots(&mut self.resolver, variant.valueType) {
11248 +
            return variant.valueType;
11139 11249
        }
11140 -
        else => return false,
11141 11250
    }
11251 +
    return nil;
11142 11252
}
11143 11253
11144 -
/// Add a payload type to a scan. Types without a value are left out.
11145 -
fn scanPayload(res: &resolver::Resolver, scan: &mut PayloadScan, typ: resolver::Type) {
11146 -
    if typ == resolver::Type::Void or typ == resolver::Type::Never {
11147 -
        return;
11148 -
    }
11149 -
    if let first = scan.first {
11150 -
        if not sameShape(res, first, typ) {
11151 -
            set scan.same = false;
11152 -
        }
11153 -
    } else {
11154 -
        set scan.first = typ;
11254 +
/// Get the type that describes the error region of a result, if there is one. The error
11255 +
/// payloads must have the same shape, and the shape must have slots.
11256 +
fn errorPayload(self: &mut Lowerer, throwList: *[*resolver::Type]) -> ?resolver::Type {
11257 +
    let mut scan = resolver::PayloadScan { first: nil, same: true };
11258 +
    for errType in throwList {
11259 +
        resolver::scanPayload(&self.resolver, &mut scan, *errType);
11155 11260
    }
11156 -
}
11157 -
11158 -
/// Get the type that describes the shared payload region, if there is one. The payloads
11159 -
/// must have the same shape, and the shape must have slots. Otherwise the region is plain data.
11160 -
fn sharedPayload(self: &mut Lowerer, scan: PayloadScan) -> ?resolver::Type throws (LowerError) {
11161 11261
    let first = scan.first else {
11162 11262
        return nil;
11163 11263
    };
11164 -
    if scan.same and try hasSlots(self, first) {
11264 +
    if scan.same and resolver::hasSlots(&mut self.resolver, first) {
11165 11265
        return first;
11166 11266
    }
11167 11267
    return nil;
11168 11268
}
11169 11269
11170 -
/// Get the type that describes the payload region of a union.
11171 -
fn unionPayload(self: &mut Lowerer, unionInfo: resolver::UnionType) -> ?resolver::Type
11172 -
    throws (LowerError)
11173 -
{
11174 -
    let mut scan = PayloadScan { first: nil, same: true };
11175 -
    for variant in unionInfo.variants {
11176 -
        scanPayload(&self.resolver, &mut scan, variant.valueType);
11177 -
    }
11178 -
    return try sharedPayload(self, scan);
11179 -
}
11180 -
11181 -
/// Get the type that describes the error region of a result, if there is one.
11182 -
fn errorPayload(self: &mut Lowerer, throwList: *[*resolver::Type]) -> ?resolver::Type
11183 -
    throws (LowerError)
11184 -
{
11185 -
    let mut scan = PayloadScan { first: nil, same: true };
11186 -
    for errType in throwList {
11187 -
        scanPayload(&self.resolver, &mut scan, *errType);
11188 -
    }
11189 -
    return try sharedPayload(self, scan);
11190 -
}
11191 -
11192 11270
/// Get the index of the layout of the error payload of a result that throws `throwList`, for
11193 11271
/// copying the payload. It is the layout of the shared payload type when that has slots.
11194 11272
/// Otherwise it is plain data of the size of the largest error, with the largest alignment
11195 11273
/// that divides that size.
11196 11274
fn errorCopyLayout(self: &mut Lowerer, throwList: *[*resolver::Type]) -> u32 throws (LowerError) {
11197 -
    if let shared = try errorPayload(self, throwList) {
11275 +
    if let shared = errorPayload(self, throwList) {
11198 11276
        return try layoutOf(self, shared);
11199 11277
    }
11200 11278
    let size = maxErrSize(&self.resolver, throwList);
11201 11279
    let mut alignment: u32 = 1;
11202 11280
    for errType in throwList {
11214 11292
/// Grow the nominal layout cache to cover every nominal type.
11215 11293
fn growNominals(self: &mut Lowerer) throws (LowerError) {
11216 11294
    if self.tables.nominalLayouts.len < self.resolver.nominals.len {
11217 11295
        try self.tables.nominalLayouts.resize(
11218 11296
            self.resolver.nominals.len,
11219 -
            NominalLayout { slots: nil, index: nil },
11297 +
            NominalLayout { index: nil },
11220 11298
            self.resolver.arena
11221 11299
        ) catch {
11222 11300
            throw LowerError::AllocationFailed;
11223 11301
        };
11224 11302
    }
11225 11303
}
11226 11304
11227 -
/// Whether values of `typ` contain slots.
11228 -
fn hasSlots(self: &mut Lowerer, typ: resolver::Type) -> bool throws (LowerError) {
11229 -
    if isSlotType(typ) {
11230 -
        return true;
11231 -
    }
11232 -
    match typ {
11233 -
        case resolver::Type::Array(array) =>
11234 -
            return array.length > 0 and try hasSlots(self, *array.item),
11235 -
        case resolver::Type::Optional(inner) => {
11236 -
            // An optional pointer that is not a slot is plain data.
11237 -
            if resolver::isNullableType(*inner) {
11238 -
                return false;
11239 -
            }
11240 -
            return try hasSlots(self, *inner);
11241 -
        }
11242 -
        case resolver::Type::Nominal(id) => {
11243 -
            try growNominals(self);
11244 -
            if let known = self.tables.nominalLayouts[*id].slots {
11245 -
                return known;
11246 -
            }
11247 -
            let mut found = false;
11248 -
            match self.resolver.nominals[*id] {
11249 -
                case resolver::NominalType::Record(recInfo) => {
11250 -
                    for field in recInfo.fields {
11251 -
                        if try hasSlots(self, field.fieldType) {
11252 -
                            set found = true;
11253 -
                            break;
11254 -
                        }
11255 -
                    }
11256 -
                }
11257 -
                case resolver::NominalType::Union(unionInfo) =>
11258 -
                    set found = try unionPayload(self, unionInfo) <> nil,
11259 -
                case resolver::NominalType::Placeholder(_) => {}
11260 -
            }
11261 -
            set self.tables.nominalLayouts[*id].slots = found;
11262 -
            return found;
11263 -
        }
11264 -
        else => return false,
11265 -
    }
11266 -
}
11267 -
11268 11305
/// Get the index of a layout with the given size, alignment and slots. An equal
11269 11306
/// layout is reused. A zero alignment, as of a type without storage, becomes one.
11270 11307
fn internLayout(
11271 11308
    self: &mut Lowerer,
11272 11309
    size: u32,
11273 11310
    alignment: u32,
11274 11311
    slots: *[il::Slot]
11275 11312
) -> u32 throws (LowerError) {
11276 11313
    let aligned = alignment if alignment > 0 else 1;
11277 -
    for i in &self.tables.sharedLayouts[..] {
11314 +
    let mut lo: u32 = 0;
11315 +
    let mut hi = self.tables.sharedLayouts.len;
11316 +
    while lo < hi {
11317 +
        let mid = lo + (hi - lo) / 2;
11318 +
        let existing = self.tables.layouts[self.tables.layoutBase + self.tables.sharedLayouts[mid]];
11319 +
        if existing.size < size
11320 +
            or (existing.size == size and existing.alignment < aligned)
11321 +
            or (existing.size == size
11322 +
                and existing.alignment == aligned
11323 +
                and existing.slots.len < slots.len)
11324 +
        {
11325 +
            set lo = mid + 1;
11326 +
        } else {
11327 +
            set hi = mid;
11328 +
        }
11329 +
    }
11330 +
    while lo < self.tables.sharedLayouts.len {
11331 +
        let i = self.tables.sharedLayouts[lo];
11278 11332
        let existing = self.tables.layouts[self.tables.layoutBase + i];
11279 -
        if existing.size == size
11280 -
            and existing.alignment == aligned
11281 -
            and slotsEqual(
11282 -
                existing.slots, slots
11283 -
            )
11333 +
        if existing.size <> size
11334 +
            or existing.alignment <> aligned
11335 +
            or existing.slots.len <> slots.len
11284 11336
        {
11337 +
            break;
11338 +
        }
11339 +
        if slotsEqual(existing.slots, slots) {
11285 11340
            return i;
11286 11341
        }
11342 +
        set lo += 1;
11287 11343
    }
11288 11344
    let index = self.tables.layouts.len - self.tables.layoutBase;
11289 11345
    try self.tables.layouts.append(
11290 11346
        il::Layout { size, alignment: aligned, slots }, self.resolver.arena
11291 11347
    ) catch {
11292 11348
        throw LowerError::AllocationFailed;
11293 11349
    };
11294 11350
    try self.tables.sharedLayouts.append(index, self.resolver.arena) catch {
11295 11351
        throw LowerError::AllocationFailed;
11296 11352
    };
11353 +
    let mut at = self.tables.sharedLayouts.len - 1;
11354 +
    while at > lo {
11355 +
        set self.tables.sharedLayouts[at] = self.tables.sharedLayouts[at - 1];
11356 +
        set at -= 1;
11357 +
    }
11358 +
    set self.tables.sharedLayouts[lo] = index;
11297 11359
    return index;
11298 11360
}
11299 11361
11300 11362
/// Get the layout index of `pointee`, or zero while only nested layouts are numbered.
11301 11363
fn pointeeLayout(self: &mut Lowerer, pointee: resolver::Type, mode: SlotMode) -> u32 throws (
11332 11394
11333 11395
/// Get the slot kind of a type that is a single slot, or nil for any other type.
11334 11396
fn slotKind(self: &mut Lowerer, typ: resolver::Type, mode: SlotMode) -> ?il::SlotKind throws (
11335 11397
    LowerError
11336 11398
) {
11337 -
    if not isSlotType(typ) {
11399 +
    if not resolver::isSlotType(typ) {
11338 11400
        return nil;
11339 11401
    }
11340 11402
    if let rights = heapRights(self, typ) {
11341 11403
        return il::SlotKind::Heap(rights);
11342 11404
    }
11380 11442
    typ: resolver::Type,
11381 11443
    offset: u32,
11382 11444
    mode: SlotMode,
11383 11445
    out: &mut *mut [il::Slot]
11384 11446
) throws (LowerError) {
11385 -
    if not try hasSlots(self, typ) {
11447 +
    if not resolver::hasSlots(&mut self.resolver, typ) {
11386 11448
        return;
11387 11449
    }
11388 11450
    let mut kind: il::SlotKind = il::SlotKind::Sub(0);
11389 11451
    if let direct = try slotKind(self, typ, mode) {
11390 11452
        set kind = direct;
11393 11455
            layout: try layoutIndex(self, *array.item), count: array.length
11394 11456
        };
11395 11457
    } else {
11396 11458
        set kind = il::SlotKind::Sub(try layoutIndex(self, typ));
11397 11459
    }
11460 +
    // Numbering the nested layouts is all that the first pass needs.
11461 +
    if mode == SlotMode::Nested {
11462 +
        return;
11463 +
    }
11398 11464
    try out.append(il::Slot { offset, kind }, self.resolver.arena) catch {
11399 11465
        throw LowerError::AllocationFailed;
11400 11466
    };
11401 11467
}
11402 11468
11412 11478
    out: &mut *mut [il::Slot]
11413 11479
) throws (LowerError) {
11414 11480
    if let kind = try slotKind(self, typ, mode) {
11415 11481
        match kind {
11416 11482
            case il::SlotKind::Slice(_), il::SlotKind::Trait(_) => {
11417 -
                try out.append(
11418 -
                    il::Slot { offset, kind: il::SlotKind::Sub(try layoutIndex(self, typ)) },
11419 -
                    self.resolver.arena
11420 -
                ) catch {
11421 -
                    throw LowerError::AllocationFailed;
11422 -
                };
11483 +
                let sub = il::SlotKind::Sub(try layoutIndex(self, typ));
11484 +
                if mode == SlotMode::Full {
11485 +
                    try out.append(il::Slot { offset, kind: sub }, self.resolver.arena) catch {
11486 +
                        throw LowerError::AllocationFailed;
11487 +
                    };
11488 +
                }
11423 11489
                return;
11424 11490
            }
11425 11491
            else => {}
11426 11492
        }
11427 11493
    }
11450 11516
                    for field in recInfo.fields {
11451 11517
                        try part(self, field.fieldType, base + field.offset as u32, mode, out);
11452 11518
                    }
11453 11519
                }
11454 11520
                case resolver::NominalType::Union(unionInfo) => {
11455 -
                    if let payload = try unionPayload(self, unionInfo) {
11521 +
                    if let payload = unionPayload(self, unionInfo) {
11456 11522
                        try part(self, payload, base + unionInfo.valOffset, mode, out);
11523 +
                    } else if unionInfo.mixed {
11524 +
                        // The whole union is one slot, so that only its instructions write it.
11525 +
                        let mut variants: *mut [il::UnionVariant] = &mut [];
11526 +
                        for variant in unionInfo.variants {
11527 +
                            let tag = variantTag(&self.resolver, variant.symbol);
11528 +
                            let mut layout: ?u32 = nil;
11529 +
                            if variant.valueType <> resolver::Type::Void {
11530 +
                                set layout = try layoutIndex(self, variant.valueType);
11531 +
                            }
11532 +
                            if mode == SlotMode::Full {
11533 +
                                try variants.append(
11534 +
                                    il::UnionVariant { tag, layout }, self.resolver.arena
11535 +
                                ) catch {
11536 +
                                    throw LowerError::AllocationFailed;
11537 +
                                };
11538 +
                            }
11539 +
                        }
11540 +
                        if mode == SlotMode::Nested {
11541 +
                            return;
11542 +
                        }
11543 +
                        try out.append(
11544 +
                            il::Slot {
11545 +
                                offset: base,
11546 +
                                kind: il::SlotKind::Union {
11547 +
                                    offset: unionInfo.valOffset,
11548 +
                                    size: unionInfo.layout.size,
11549 +
                                    variants: &variants[..],
11550 +
                                },
11551 +
                            },
11552 +
                            self.resolver.arena
11553 +
                        ) catch {
11554 +
                            throw LowerError::AllocationFailed;
11555 +
                        };
11457 11556
                    }
11458 11557
                }
11459 11558
                case resolver::NominalType::Placeholder(_) => {}
11460 11559
            }
11461 11560
            return;
11508 11607
        if resolver::isNullableType(*inner) {
11509 11608
            return try layoutIndex(self, *inner);
11510 11609
        }
11511 11610
    }
11512 11611
    let layout = resolver::getTypeLayout(&self.resolver, typ);
11513 -
    if not try hasSlots(self, typ) {
11612 +
    if not resolver::hasSlots(&mut self.resolver, typ) {
11514 11613
        return try internLayout(self, layout.size, layout.alignment, &[]);
11515 11614
    }
11516 11615
    if let case resolver::Type::Nominal(id) = typ {
11616 +
        try growNominals(self);
11517 11617
        if let index = self.tables.nominalLayouts[*id].index {
11518 11618
            return index;
11519 11619
        }
11520 11620
        let index = try numberSlotted(self, typ, layout);
11521 11621
        set self.tables.nominalLayouts[*id].index = index;
11538 11638
11539 11639
/// Placement of the parts of a result: a tag, a success value, and an error payload.
11540 11640
record ResultLayout: Copy {
11541 11641
    /// Size and alignment of the whole result.
11542 11642
    layout: resolver::Layout,
11543 -
    /// Byte offset of the error payload. The success value is at `RESULT_VAL_OFFSET`.
11643 +
    /// Byte offset of the first error region. The success value is at
11644 +
    /// `RESULT_VAL_OFFSET`.
11544 11645
    errOffset: u32,
11545 11646
    /// Whether the success value and the errors have regions of their own. This is
11546 11647
    /// the case when either has slots. Otherwise they share the region after the tag.
11547 11648
    split: bool,
11649 +
    /// Whether each error type has its own region to preserve different slot shapes.
11650 +
    separateErrors: bool,
11548 11651
}
11549 11652
11550 11653
/// Compute the placement of the parts of the result of a function that returns
11551 11654
/// `payload` and throws the errors of `throwList`.
11552 11655
fn resultLayoutInfo(
11553 11656
    self: &mut Lowerer,
11554 11657
    payload: resolver::Type,
11555 11658
    throwList: *[*resolver::Type]
11556 -
) -> ResultLayout throws (LowerError) {
11557 -
    let mut split = try hasSlots(self, payload);
11659 +
) -> ResultLayout {
11660 +
    let mut errorSlots = false;
11661 +
    let mut errAlignment: u32 = 1;
11662 +
    let mut errSize: u32 = 0;
11558 11663
    for errType in throwList {
11559 -
        if try hasSlots(self, *errType) {
11560 -
            set split = true;
11664 +
        let layout = resolver::getTypeLayout(&self.resolver, *errType);
11665 +
        if layout.alignment > errAlignment {
11666 +
            set errAlignment = layout.alignment;
11667 +
        }
11668 +
        if layout.size > errSize {
11669 +
            set errSize = layout.size;
11670 +
        }
11671 +
        if resolver::hasSlots(&mut self.resolver, *errType) {
11672 +
            set errorSlots = true;
11561 11673
        }
11562 11674
    }
11675 +
    let split = resolver::hasSlots(&mut self.resolver, payload) or errorSlots;
11563 11676
    if not split {
11564 11677
        return ResultLayout {
11565 11678
            layout: resolver::getResultLayout(&self.resolver, payload, throwList),
11566 11679
            errOffset: RESULT_VAL_OFFSET as u32,
11567 11680
            split,
11681 +
            separateErrors: false,
11568 11682
        };
11569 11683
    }
11570 11684
    let success = resolver::getTypeLayout(&self.resolver, payload);
11571 11685
    assert success.alignment <= resolver::PTR_SIZE,
11572 11686
        "resultLayoutInfo: success value is over-aligned";
11573 -
    let mut errAlignment: u32 = 1;
11574 -
    for errType in throwList {
11575 -
        let alignment = resolver::getTypeLayout(&self.resolver, *errType).alignment;
11576 -
        if alignment > errAlignment {
11577 -
            set errAlignment = alignment;
11687 +
    let errOffset = mem::alignUp(RESULT_VAL_OFFSET as u32 + success.size, errAlignment);
11688 +
    let separateErrors = errorSlots and errorPayload(self, throwList) == nil;
11689 +
    let mut end = errOffset + errSize;
11690 +
    if separateErrors {
11691 +
        set end = errOffset;
11692 +
        for errType in throwList {
11693 +
            let layout = resolver::getTypeLayout(&self.resolver, *errType);
11694 +
            set end =
11695 +
                mem::alignUp(end, layout.alignment if layout.alignment > 0 else 1) + layout.size;
11578 11696
        }
11579 11697
    }
11580 -
    let errOffset = mem::alignUp(RESULT_VAL_OFFSET as u32 + success.size, errAlignment);
11581 11698
    let mut alignment = resolver::PTR_SIZE;
11582 11699
    if errAlignment > alignment {
11583 11700
        set alignment = errAlignment;
11584 11701
    }
11585 11702
    return ResultLayout {
11586 11703
        layout: resolver::Layout {
11587 -
            size: mem::alignUp(errOffset + maxErrSize(&self.resolver, throwList), alignment),
11704 +
            size: mem::alignUp(end, alignment),
11588 11705
            alignment,
11589 11706
        },
11590 11707
        errOffset,
11591 11708
        split,
11709 +
        separateErrors,
11592 11710
    };
11593 11711
}
11594 11712
11595 -
/// Get the byte offset of the error payload in the result of a function that returns
11596 -
/// `payload` and throws the errors of `throwList`.
11713 +
/// Get the byte offset of `errType` in a result that returns `payload` and
11714 +
/// throws `throwList`.
11597 11715
fn resultErrOffset(
11598 11716
    self: &mut Lowerer,
11599 11717
    payload: resolver::Type,
11600 -
    throwList: *[*resolver::Type]
11601 -
) -> i32 throws (LowerError) {
11602 -
    let info = try resultLayoutInfo(self, payload, throwList);
11603 -
    return info.errOffset as i32;
11718 +
    throwList: *[*resolver::Type],
11719 +
    errType: resolver::Type
11720 +
) -> i32 {
11721 +
    let info = resultLayoutInfo(self, payload, throwList);
11722 +
    if not info.separateErrors {
11723 +
        return info.errOffset as i32;
11724 +
    }
11725 +
    let mut offset = info.errOffset;
11726 +
    for typ in throwList {
11727 +
        let layout = resolver::getTypeLayout(&self.resolver, *typ);
11728 +
        set offset = mem::alignUp(offset, layout.alignment if layout.alignment > 0 else 1);
11729 +
        if resolver::typesEqual(*typ, errType) {
11730 +
            return offset as i32;
11731 +
        }
11732 +
        set offset += layout.size;
11733 +
    }
11734 +
    panic "resultErrOffset: error type is absent from throw list";
11604 11735
}
11605 11736
11606 11737
/// Get the layout index of the result of a function with the given success type and
11607 11738
/// error types. The result is a tag followed by the success value and the errors. The
11608 -
/// errors share a region, which is plain data unless all of them have the same shape.
11739 +
/// errors with the same shape share a region. Different shapes have separate regions
11740 +
/// when any error has slots.
11609 11741
fn resultLayoutIndex(
11610 11742
    self: &mut Lowerer,
11611 11743
    payload: resolver::Type,
11612 11744
    throwList: *[*resolver::Type]
11613 11745
) -> u32 throws (LowerError) {
11614 -
    let info = try resultLayoutInfo(self, payload, throwList);
11746 +
    let info = resultLayoutInfo(self, payload, throwList);
11615 11747
    let mut slots: *mut [il::Slot] = &mut [];
11616 11748
    if info.split {
11617 11749
        try part(self, payload, RESULT_VAL_OFFSET as u32, SlotMode::Full, &mut slots);
11618 -
        if let shared = try errorPayload(self, throwList) {
11750 +
        if info.separateErrors {
11751 +
            let mut offset = info.errOffset;
11752 +
            for errType in throwList {
11753 +
                let layout = resolver::getTypeLayout(&self.resolver, *errType);
11754 +
                set offset = mem::alignUp(offset, layout.alignment if layout.alignment > 0 else 1);
11755 +
                try part(self, *errType, offset, SlotMode::Full, &mut slots);
11756 +
                set offset += layout.size;
11757 +
            }
11758 +
        } else if let shared = errorPayload(self, throwList) {
11619 11759
            try part(self, shared, info.errOffset, SlotMode::Full, &mut slots);
11620 11760
        }
11621 11761
    }
11622 11762
    return try internLayout(self, info.layout.size, info.layout.alignment, &slots[..]);
11623 11763
}
lib/std/lang/lower/tests.rad +36 -0
2 2
3 3
use std::mem;
4 4
use std::testing;
5 5
use std::mem::heap;
6 6
use std::lang::ast;
7 +
use std::lang::il;
7 8
use std::lang::module;
8 9
use std::lang::resolver;
9 10
use std::lang::resolver::tests;
10 11
11 12
/// Backing storage for the node of the error payloads.
150 151
    try testing::expect(second == referenceHash("Second"));
151 152
    try testing::expect(word == referenceHash("u32"));
152 153
    try testing::expect(first <> second);
153 154
    try testing::expect(again == first);
154 155
}
156 +
157 +
/// A mixed union case copies the pointer field without a second copy of the union.
158 +
@test unsafe fn testMixedUnionFieldSnapshot() throws (testing::TestError) {
159 +
    let mut res = tests::testResolver();
160 +
    let result = try tests::resolveProgramStr(
161 +
        &mut res,
162 +
        "union U: Copy { A(*u32), B(u32) } fn f(xs: &[U]) -> u32 { match xs[0] { case U::A(p) => return *p, case U::B(n) => return n, } }"
163 +
    );
164 +
    try tests::expectNoErrors(&result);
165 +
    let program = try super::lower(res, result.root, "test", heap::over(
166 +
        &mut FN_STORAGE[..]
167 +
    )) catch {
168 +
        throw testing::TestError::Failed;
169 +
    };
170 +
    let mut reads: u32 = 0;
171 +
    let mut copies: u32 = 0;
172 +
    for func in program.fns {
173 +
        for block in func.blocks {
174 +
            for instr in block.instrs {
175 +
                if let case il::Instr::Blit { layout, .. } = instr {
176 +
                    for slot in program.layouts[layout].slots {
177 +
                        if let case il::SlotKind::Union { .. } = slot.kind {
178 +
                            set copies += 1;
179 +
                        }
180 +
                    }
181 +
                }
182 +
                if let case il::Instr::UnionGet { .. } = instr {
183 +
                    set reads += 1;
184 +
                }
185 +
            }
186 +
        }
187 +
    }
188 +
    assert reads == 1;
189 +
    assert copies == 0;
190 +
}
lib/std/lang/resolver.rad +192 -14
39 39
/// Maximum number of symbols stored within a module scope.
40 40
export constant MAX_MODULE_SYMBOLS: u32 = 512;
41 41
42 42
/// Initial capacity of `Resolver.symbols`. The slice grows past it when a
43 43
/// package has more symbols, but each growth copies every symbol, so the
44 -
/// capacity covers a typical package.
45 -
export constant INITIAL_SYMBOL_CAPACITY: u32 = 16384;
44 +
/// capacity covers the standard library with its tests, which has 33000 symbols. A growth copy
45 +
/// keeps the old table in the arena, so a smaller capacity costs more memory than this one.
46 +
export constant INITIAL_SYMBOL_CAPACITY: u32 = 36864;
46 47
/// Maximum number of symbols stored within a local scope.
47 48
export constant MAX_LOCAL_SYMBOLS: u32 = 32;
48 49
/// Maximum declared parameters of a function or method. The receiver of a
49 50
/// method is not declared, so it does not count.
50 51
export constant MAX_FN_PARAMS: u32 = 8;
214 215
    declaredCopy: bool,
215 216
}
216 217
217 218
/// Union nominal type.
218 219
export record UnionType: Copy {
220 +
    /// Whether variant payloads need a protected union slot.
221 +
    mixed: bool,
219 222
    variants: *[UnionVariant],
220 223
    /// Cached layout.
221 224
    layout: Layout,
222 225
    /// Cached payload offset within the union aggregate.
223 226
    valOffset: u32,
570 573
    /// Slice `.take()` moves out of an owned `*mut [T]` place, not a borrowed slice.
571 574
    SliceNotOwned,
572 575
    /// A slice method that changes the header was called on an immutable slice, or on a slice
573 576
    /// in a local that `set` cannot assign.
574 577
    SliceNotMutable,
575 -
    /// A safe static or storage parameter holds a slice or trait object, or a pointer that
576 -
    /// reaches one, which the verifier refuses in mutable data.
578 +
    /// A safe static or storage parameter holds a slice, a trait object or a union that mixes
579 +
    /// pointer and plain payloads, or a pointer that reaches one, which the verifier refuses in
580 +
    /// mutable data.
577 581
    MutableDataHoldsSlice,
582 +
    /// A pattern binds a payload of a union that mixes pointer and plain payloads by reference.
583 +
    MixedUnionByReference,
578 584
    /// A method with an owned receiver was called on storage that does not outlive the
579 585
    /// program: a local, a parameter, a temporary, or a place reached through a reference.
580 586
    ReceiverNotOwned,
581 587
    /// Expected a compile-time constant expression.
582 588
    ConstExprRequired,
1178 1184
    /// The allocation error, declared with `@language`. Every declaration of it is this type.
1179 1185
    allocError: ?NominalId,
1180 1186
    /// The heap types declared with `@language`, indexed by `HeapKind`. Every declaration of
1181 1187
    /// one of them is this type.
1182 1188
    heaps: [?NominalId; HEAP_KINDS],
1189 +
    /// Whether values of each nominal type have slots, by `NominalId`. Nil until first needed.
1190 +
    slotMemo: *mut [?bool],
1183 1191
}
1184 1192
1185 1193
/// Internal error sentinel thrown when analysis cannot proceed.
1186 1194
export union ResolveError: Copy {
1187 1195
    Failure,
1368 1376
        moduleScopes,
1369 1377
        instances,
1370 1378
        methods,
1371 1379
        allocError: nil,
1372 1380
        heaps: [nil; HEAP_KINDS],
1381 +
        slotMemo: &mut [],
1373 1382
    };
1374 1383
}
1375 1384
1376 1385
/// Capture the current errors in an immutable arena allocation.
1377 1386
/// The allocation must remain valid while the diagnostics are used.
4264 4273
            try ensureMutableDataType(self, paramNodes[i], *target);
4265 4274
        }
4266 4275
    }
4267 4276
}
4268 4277
4269 -
/// Whether a value of `ty` reaches a slice or trait object: it holds one, or a pointer whose
4270 -
/// target reaches one. These are the slots of two words that the verifier refuses in mutable data.
4278 +
/// Whether a value of `ty` is a single slot: a pointer or slice that the verifier tracks, a
4279 +
/// trait object, or a function value. Unsafe pointers and pointers to `opaque` are plain data.
4280 +
export fn isSlotType(ty: Type) -> bool {
4281 +
    match ty {
4282 +
        case Type::Pointer { class, target, .. } =>
4283 +
            return class <> types::PointerClass::Unsafe and *target <> Type::Opaque,
4284 +
        case Type::Slice { class, item, .. } =>
4285 +
            return class <> types::PointerClass::Unsafe and *item <> Type::Opaque,
4286 +
        case Type::Fn(_)              => return true,
4287 +
        case Type::TraitObject { .. } => return isTraitSlot(ty),
4288 +
        case Type::Optional(inner)    => return isNullableType(*inner) and isSlotType(*inner),
4289 +
        else                          => return false,
4290 +
    }
4291 +
}
4292 +
4293 +
/// Whether a trait object type is a trait object slot. An unsafe trait object is
4294 +
/// plain data, since its receiver is.
4295 +
export fn isTraitSlot(ty: Type) -> bool {
4296 +
    if let case Type::TraitObject { class, .. } = ty {
4297 +
        return class <> types::PointerClass::Unsafe;
4298 +
    }
4299 +
    return false;
4300 +
}
4301 +
4302 +
/// Whether values of `ty` contain slots. A union has slots when a payload does.
4303 +
export fn hasSlots(self: &mut Resolver, ty: Type) -> bool {
4304 +
    if isSlotType(ty) {
4305 +
        return true;
4306 +
    }
4307 +
    match ty {
4308 +
        case Type::Array(array) => return array.length > 0 and hasSlots(self, *array.item),
4309 +
        case Type::Optional(inner) => {
4310 +
            // An optional pointer that is not a slot is plain data.
4311 +
            return not isNullableType(*inner) and hasSlots(self, *inner);
4312 +
        }
4313 +
        case Type::Nominal(id) => {
4314 +
            if self.slotMemo.len <= *id {
4315 +
                // Grow geometrically, since the arena keeps every old table. Without room for
4316 +
                // the memo, the answer is found again each time.
4317 +
                try self.slotMemo.resize(self.nominals.len * 2, nil, self.arena) catch {};
4318 +
            }
4319 +
            let memo = *id < self.slotMemo.len;
4320 +
            if memo {
4321 +
                if let known = self.slotMemo[*id] {
4322 +
                    return known;
4323 +
                }
4324 +
            }
4325 +
            let mut found = false;
4326 +
            match self.nominals[*id] {
4327 +
                case NominalType::Record(recordType) => {
4328 +
                    for field in recordType.fields {
4329 +
                        if hasSlots(self, field.fieldType) {
4330 +
                            set found = true;
4331 +
                            break;
4332 +
                        }
4333 +
                    }
4334 +
                }
4335 +
                case NominalType::Union(unionType) => {
4336 +
                    for variant in unionType.variants {
4337 +
                        if hasSlots(self, variant.valueType) {
4338 +
                            set found = true;
4339 +
                            break;
4340 +
                        }
4341 +
                    }
4342 +
                }
4343 +
                // A body that is not resolved yet has no answer to keep.
4344 +
                case NominalType::Placeholder(_) => return false,
4345 +
            }
4346 +
            if memo {
4347 +
                set self.slotMemo[*id] = found;
4348 +
            }
4349 +
            return found;
4350 +
        }
4351 +
        else => return false,
4352 +
    }
4353 +
}
4354 +
4355 +
/// Payload types that share the payload region of a union or result.
4356 +
export record PayloadScan: Copy {
4357 +
    /// The first payload type. Nil while there is none.
4358 +
    first: ?Type,
4359 +
    /// Whether all payload types seen so far have the same shape.
4360 +
    same: bool,
4361 +
}
4362 +
4363 +
/// Whether two types describe the same bytes: they are equal, or they are records whose
4364 +
/// fields have the same offsets and the same shapes, or arrays or optionals of the same
4365 +
/// shape. The payload of a union variant is a record of its own, so two variants with equal
4366 +
/// payload types still have different record types.
4367 +
fn sameShape(self: &Resolver, a: Type, b: Type) -> bool {
4368 +
    if typesEqual(a, b) {
4369 +
        return true;
4370 +
    }
4371 +
    match a {
4372 +
        case Type::Array(x) => {
4373 +
            let case Type::Array(y) = b else return false;
4374 +
            return x.length == y.length and sameShape(self, *x.item, *y.item);
4375 +
        }
4376 +
        case Type::Optional(x) => {
4377 +
            let case Type::Optional(y) = b else return false;
4378 +
            return sameShape(self, *x, *y);
4379 +
        }
4380 +
        case Type::Nominal(x) => {
4381 +
            let case Type::Nominal(y) = b else return false;
4382 +
            let case NominalType::Record(left) = self.nominals[*x] else return false;
4383 +
            let case NominalType::Record(right) = self.nominals[*y] else return false;
4384 +
            if left.fields.len <> right.fields.len {
4385 +
                return false;
4386 +
            }
4387 +
            for i in 0 .. left.fields.len {
4388 +
                if left.fields[i].offset <> right.fields[i].offset
4389 +
                    or not sameShape(self, left.fields[i].fieldType, right.fields[i].fieldType)
4390 +
                {
4391 +
                    return false;
4392 +
                }
4393 +
            }
4394 +
            return true;
4395 +
        }
4396 +
        else => return false,
4397 +
    }
4398 +
}
4399 +
4400 +
/// Add a payload type to a scan. Types without a value are left out.
4401 +
export fn scanPayload(self: &Resolver, scan: &mut PayloadScan, ty: Type) {
4402 +
    if ty == Type::Void or ty == Type::Never {
4403 +
        return;
4404 +
    }
4405 +
    if let first = scan.first {
4406 +
        if not sameShape(self, first, ty) {
4407 +
            set scan.same = false;
4408 +
        }
4409 +
    } else {
4410 +
        set scan.first = ty;
4411 +
    }
4412 +
}
4413 +
4414 +
/// Check whether variant payloads need a protected union slot.
4415 +
fn mixedPayload(self: &mut Resolver, unionType: UnionType) -> bool {
4416 +
    let mut scan = PayloadScan { first: nil, same: true };
4417 +
    for variant in unionType.variants {
4418 +
        scanPayload(self, &mut scan, variant.valueType);
4419 +
    }
4420 +
    if scan.same {
4421 +
        return false;
4422 +
    }
4423 +
    for variant in unionType.variants {
4424 +
        if hasSlots(self, variant.valueType) {
4425 +
            return true;
4426 +
        }
4427 +
    }
4428 +
    return false;
4429 +
}
4430 +
4431 +
/// Whether a value of `ty` reaches a slice, trait object or mixed union: it holds one, or a pointer
4432 +
/// whose target reaches one. These are the slots that the verifier refuses in mutable data.
4271 4433
/// Unsafe pointers and pointers to `opaque` are plain data. `seen` holds the nominal types that
4272 4434
/// the search visited, which ends it at a recursive record.
4273 4435
fn reachesSlice(
4274 4436
    self: &mut Resolver, ty: Type, site: *ast::Node, seen: &mut *mut [NominalId]
4275 4437
) -> bool throws (ResolveError) {
4301 4463
                            return true;
4302 4464
                        }
4303 4465
                    }
4304 4466
                }
4305 4467
                case NominalType::Union(unionType) => {
4468 +
                    if unionType.mixed {
4469 +
                        return true;
4470 +
                    }
4306 4471
                    for variant in unionType.variants {
4307 4472
                        if try reachesSlice(self, variant.valueType, site, seen) {
4308 4473
                            return true;
4309 4474
                        }
4310 4475
                    }
4316 4481
        else => return false,
4317 4482
    }
4318 4483
}
4319 4484
4320 4485
/// Reject a type that safe mutable data cannot hold, because the verifier would refuse it: several
4321 -
/// contexts can write mutable data, and a racing writer could tear a slot of two words.
4486 +
/// contexts can write mutable data, and a racing writer could tear a slot that is written as a
4487 +
/// whole, such as a slice.
4322 4488
fn ensureMutableDataType(self: &mut Resolver, node: *ast::Node, ty: Type) throws (ResolveError) {
4323 4489
    let mut seen: *mut [NominalId] = &mut [];
4324 4490
    if try reachesSlice(self, ty, node, &mut seen) {
4325 4491
        throw emitError(self, node, ErrorKind::MutableDataHoldsSlice);
4326 4492
    }
5394 5560
    // Create a temporary nominal type to replace the placeholder.This prevents infinite recursion
5395 5561
    // when a variant references this union type (e.g. record payloads with `*[Self]`).
5396 5562
    // TODO: It would be best to have a resolving state eg. `Visiting` for this situation.
5397 5563
    let markers = try resolveOwnershipMarkers(self, decl.derives);
5398 5564
    set self.nominals[*nominalTy] = NominalType::Union(UnionType {
5565 +
        mixed: false,
5399 5566
        variants: &[],
5400 5567
        layout: Layout { size: 0, alignment: 0 },
5401 5568
        valOffset: 0,
5402 5569
        isAllVoid: true,
5403 5570
        declaredLinear: markers.linear,
5456 5623
        }
5457 5624
    }
5458 5625
    let info = computeUnionLayout(self, &variants[..]);
5459 5626
5460 5627
    // Update the nominal type with the resolved variants.
5461 -
    set self.nominals[*nominalTy] = NominalType::Union(UnionType {
5628 +
    let mut unionType = UnionType {
5629 +
        mixed: false,
5462 5630
        variants: &variants[..],
5463 5631
        layout: info.layout,
5464 5632
        valOffset: info.valOffset,
5465 5633
        isAllVoid: info.isAllVoid,
5466 5634
        declaredLinear: markers.linear,
5467 5635
        declaredCopy: markers.copy,
5468 -
    });
5636 +
    };
5637 +
    set unionType.mixed = mixedPayload(self, unionType);
5638 +
    set self.nominals[*nominalTy] = NominalType::Union(unionType);
5469 5639
}
5470 5640
5471 5641
/// Check if a module should be analyzed based on its attributes and build configuration.
5472 5642
fn shouldAnalyzeModule(self: &Resolver, attrs: ?ast::Attributes) -> bool {
5473 5643
    if let attributes = attrs {
6697 6867
    pattern: *ast::Node,
6698 6868
    subjectTy: Type,
6699 6869
    unionType: UnionType,
6700 6870
    matchBy: MatchBy
6701 6871
) throws (ResolveError) {
6872 +
    // The payload of a mixed union is read as a whole, so a reference cannot point into it.
6873 +
    if matchBy <> MatchBy::Value
6874 +
        and casePatternIntroducesBindings(pattern, false)
6875 +
        and unionType.mixed
6876 +
    {
6877 +
        throw emitError(self, pattern, ErrorKind::MixedUnionByReference);
6878 +
    }
6702 6879
    match pattern.value {
6703 6880
        case ast::NodeValue::ScopeAccess(access) =>
6704 6881
            try resolveUnionScopePattern(self, pattern, access, subjectTy, unionType),
6705 6882
        case ast::NodeValue::Call(call) =>
6706 6883
            try resolveUnionCallPattern(self, pattern, call, subjectTy, unionType, matchBy),
8568 8745
/// slot when they are declared, so the root variable must be marked here.
8569 8746
fn markAddressTakenRoot(self: &mut Resolver, target: *ast::Node) {
8570 8747
    match target.value {
8571 8748
        case ast::NodeValue::Ident(name) => {
8572 8749
            if let sym = findValueSymbol(self, self.scope, name) {
8573 -
                match &mut self.symbols[*sym].data {
8574 -
                    case SymbolData::Value { addressTaken, .. } => {
8575 -
                        set *addressTaken = true;
8576 -
                    }
8577 -
                    else => {}
8750 +
                if let case SymbolData::Value { mutable, alignment, type, .. } =
8751 +
                    self.symbols[*sym].data
8752 +
                {
8753 +
                    set self.symbols[*sym].data = SymbolData::Value {
8754 +
                        mutable, alignment, type, addressTaken: true
8755 +
                    };
8578 8756
                }
8579 8757
            }
8580 8758
        }
8581 8759
        case ast::NodeValue::FieldAccess(access) => {
8582 8760
            if let parentTy = typeFor(self, access.parent) {
lib/std/lang/resolver/printer.rad +6 -1
490 490
        case super::ErrorKind::SliceNotOwned => {
491 491
            io::print("slice take requires an owned mutable slice, not a borrowed one");
492 492
        }
493 493
        case super::ErrorKind::MutableDataHoldsSlice => {
494 494
            io::print(
495 -
                "mutable data cannot hold a slice or trait object, or point to one, because a racing writer could tear it; use a `constant`, an `unsafe static` or an `unsafe` default function"
495 +
                "mutable data cannot hold a slice, a trait object or a union that mixes pointer and plain payloads, or point to one, because a racing writer could tear it; use a `constant`, an `unsafe static` or an `unsafe` default function"
496 +
            );
497 +
        }
498 +
        case super::ErrorKind::MixedUnionByReference => {
499 +
            io::print(
500 +
                "a union that mixes pointer and plain payloads binds its payloads by value; replace the whole value to change it"
496 501
            );
497 502
        }
498 503
        case super::ErrorKind::SliceNotMutable => {
499 504
            io::print(
500 505
                "this method changes the slice header, so the receiver must be a `*mut [T]` parameter, mutable variable or mutable field"
lib/std/lang/resolver/tests.rad +1 -1
27 27
export fn program(parts: &[*[u8]]) -> *[u8] {
28 28
    return try! alloc::concatBytes(&PROGRAM_HEAP, parts);
29 29
}
30 30
31 31
/// Resolver arena storage used by resolver tests.
32 -
export static ARENA_STORAGE: [u8; 4194304] = [0; 4194304];
32 +
export static ARENA_STORAGE: [u8; 8388608] = [0; 8388608];
33 33
34 34
/// Node metadata storage used by resolver tests.
35 35
export unsafe static NODE_DATA_STORAGE: [super::NodeData; 256] = undefined;
36 36
37 37
/// Diagnostic storage used by resolver tests.
lib/std/lang/resolver/tests/core.rad +107 -2
748 748
        let result = try resolveProgramStr(&mut a, program);
749 749
        try expectNoErrors(&result);
750 750
    }
751 751
}
752 752
753 +
/// Whether the first union of `program` is mixed.
754 +
unsafe fn isMixed(program: *[u8]) -> bool throws (testing::TestError) {
755 +
    let mut a = testResolver();
756 +
    let result = try resolveProgramStr(&mut a, program);
757 +
    try expectNoErrors(&result);
758 +
    for nominal in &a.nominals[..] {
759 +
        if let case resolver::NominalType::Union(unionType) = nominal {
760 +
            return unionType.mixed;
761 +
        }
762 +
    }
763 +
    throw testing::TestError::Failed;
764 +
}
765 +
766 +
/// A union is mixed when its payloads do not share one shape and one of them has a slot. A union
767 +
/// that is all void, all plain, or has payloads of one shape is not.
768 +
@test unsafe fn testMixedUnionPredicate() throws (testing::TestError) {
769 +
    for program in [
770 +
        "union U { A(*u8), B(u32) }",
771 +
        "union U { A(*[u8]), B(u32), C }",
772 +
        "union U { A(*u8), B(*u32) }",
773 +
        "union U { A(?*u8), B(*u8) }",
774 +
        "union U { A([*u8; 2]), B([u32; 2]) }",
775 +
        "record R { p: *u8 } union U { A(R), B(u32) }",
776 +
        "union U { A(u32, *u8), B(*u8, u32) }",
777 +
        "union U: Copy { A(fn() -> u32), B(u32) }",
778 +
    ] {
779 +
        try testing::expect(try isMixed(program));
780 +
    }
781 +
    for program in [
782 +
        "union U { A(*u8), B(*u8) }",
783 +
        "union U { A(*u8), B }",
784 +
        "union U { A(*u8), B, C }",
785 +
        "union U { A(u32), B(u64) }",
786 +
        "union U { A, B }",
787 +
        "union U { A(*u8, u32), B(*u8, u32) }",
788 +
        "union U { A([*u8; 0]), B(u32) }",
789 +
    ] {
790 +
        try testing::expect(not try isMixed(program));
791 +
    }
792 +
}
793 +
794 +
/// A pattern of a mixed union binds its payloads by value, whatever the kind of reference.
795 +
@test unsafe fn testMixedUnionByReference() throws (testing::TestError) {
796 +
    for program in [
797 +
        "union U { A(*u8), B(u32) } fn f(u: &U) { match u { case U::B(n) => {} else => {} } }",
798 +
        "union U { A(*u8), B(u32) } fn f(u: &mut U) { match u { case U::B(n) => {} else => {} } }",
799 +
        "union U { A(*u8), B(u32) } fn f(u: &U) { match u { case U::A(p) => {} else => {} } }",
800 +
        "union U { A(*u8), B(u32) } fn f() { let mut u = U::B(1); match &mut u { case U::B(n) => {} else => {} } }",
801 +
        "union U { A(*u8), B(u32) } fn f() { let u = U::B(1); if let case U::B(n) = &u { } }",
802 +
        "union U { A(*u8), B(u32) } fn f() { let u = U::B(1); let case U::B(n) = &u else { return; }; }",
803 +
        "union U { A(*u8), B(u32) } fn f() { let u = U::B(1); while let case U::B(n) = &u { } }",
804 +
        "union U { A(*u8), B { n: u32 } } fn f(u: &U) { match u { case U::B { n } => {} else => {} } }",
805 +
        "union U { A(*u8), B(u32, u32) } fn f(u: &U) { match u { case U::B(1, n) => {} else => {} } }",
806 +
        "union U { A(*u8), B(u32) } record R { u: U } fn f(r: &R) { match r { case R { u: U::B(n) } => {} else => {} } }",
807 +
    ] {
808 +
        let mut a = testResolver();
809 +
        let result = try resolveProgramStr(&mut a, program);
810 +
        try expectErrorKind(&result, resolver::ErrorKind::MixedUnionByReference);
811 +
    }
812 +
    // By value, without bindings, and for unions that are not mixed, a reference is fine.
813 +
    for program in [
814 +
        "union U { A(*u8), B(u32) } fn f(u: U) { match u { case U::B(n) => {} case U::A(p) => {} } }",
815 +
        "union U { A(*u8), B(u32) } fn f(u: &U) { match u { case U::B(_) => {} else => {} } }",
816 +
        "union U { A(*u8), B(u32) } fn f(u: &U) { match u { case U::B(7) => {} else => {} } }",
817 +
        "union U { A(*u8), B(u32), C } fn f(u: &U) { match u { case U::C => {} else => {} } }",
818 +
        "union U { A(*u8), B(*u8) } fn f(u: &mut U) { match u { case U::B(p) => {} else => {} } }",
819 +
        "union U { A(u32), B(u64) } fn f(u: &mut U) { match u { case U::B(n) => {} else => {} } }",
820 +
        "union U { A(*u8), B } fn f(u: &mut U) { match u { case U::A(p) => {} else => {} } }",
821 +
    ] {
822 +
        let mut a = testResolver();
823 +
        let result = try resolveProgramStr(&mut a, program);
824 +
        try expectNoErrors(&result);
825 +
    }
826 +
}
827 +
828 +
/// Safe mutable data cannot hold a mixed union, but a constant can, since the verifier accepts
829 +
/// read-only data that holds one. Unsafe statics and unions that are not mixed can be mutable.
830 +
@test unsafe fn testMixedUnionData() throws (testing::TestError) {
831 +
    for program in [
832 +
        "union U { A(*u8), B(u32) } static S: U = U::B(1);",
833 +
        "union U { A(*u8), B(u32) } static S: ?*U = nil;",
834 +
        "union U { A(*u8), B(u32) } record R { u: U } static S: [R; 2] = undefined;",
835 +
        "union U { A(u32), B(*u8) } @default fn main(a: *mut U) { }",
836 +
    ] {
837 +
        let mut a = testResolver();
838 +
        let result = try resolveProgramStr(&mut a, program);
839 +
        try expectErrorKind(&result, resolver::ErrorKind::MutableDataHoldsSlice);
840 +
    }
841 +
    for program in [
842 +
        "union U { A(*u8), B(u32) } unsafe static S: U = undefined;",
843 +
        "union U { A(*u8), B(u32) } fn f(u: U) -> U { return u; }",
844 +
        "union U { A(*u8), B(*u8) } static S: ?*u32 = nil; constant C: u32 = 1;",
845 +
        "union U { A(u32), B(u64) } static S: U = U::B(1); constant C: U = U::A(1);",
846 +
        "union U { A, B(u32) } constant C: U = U::B(1);",
847 +
        "union U { A(*u8), B(u32) } constant C: U = U::B(1);",
848 +
        "union U { A(*u8), B(u32) } constant C: [U; 1] = [U::B(1)];",
849 +
        "union U { A(*u8), B(u32) } constant C: *[U] = &[U::B(1)];",
850 +
        "union U { A(*u8), B(u32) } constant C: ?U = nil;",
851 +
    ] {
852 +
        let mut a = testResolver();
853 +
        let result = try resolveProgramStr(&mut a, program);
854 +
        try expectNoErrors(&result);
855 +
    }
856 +
}
857 +
753 858
/// Growing a heap throws `AllocError`, so the program must declare it.
754 859
@test unsafe fn testHeapGrowthNeedsAllocError() throws (testing::TestError) {
755 860
    let mut a = testResolver();
756 861
    let result = try resolveProgramStr(
757 862
        &mut a,
827 932
        "@default unsafe fn main(a: *mut *mut [u8]) -> i32 { return 0; }",
828 933
        "@default unsafe fn main(a: *mut [*mut [u32]; 4]) -> i32 { return 0; }",
829 934
        // Unions whose tag 0 variant has no payload or a zero-valid one.
830 935
        "union U { A, B } @default fn main(a: *mut [U; 4]) -> i32 { return 0; }",
831 936
        "union U { A, B(*u8) } @default fn main(a: *mut U) -> i32 { return 0; }",
832 -
        "union U { A(u32), B(*u8) } @default fn main(a: *mut U) -> i32 { return 0; }",
833 -
        "union U { A(?*u8), B(*u8) } @default fn main(a: *mut U) -> i32 { return 0; }",
937 +
        "union U { A(u32), B(*u8) } @default unsafe fn main(a: *mut U) -> i32 { return 0; }",
938 +
        "union U { A(?*u8), B(*u8) } @default unsafe fn main(a: *mut U) -> i32 { return 0; }",
834 939
        "union U { A, B = 5 } @default fn main(a: *mut U) -> i32 { return 0; }",
835 940
        "union U { A = 0b10, B = 0 } @default fn main(a: *mut U) -> i32 { return 0; }",
836 941
        "union U { A = 2, B = 0, C(*u8) } @default fn main(a: *mut U) -> i32 { return 0; }",
837 942
        // Records of zero-valid fields, nested records, and mixed storage.
838 943
        "record R { ok: u8, flag: bool } @default fn main(a: *mut [R; 4]) -> i32 { return 0; }",
lib/std/lang/resolver/tests/safety.rad +3 -2
1557 1557
    try expectAnalyzeOk(
1558 1558
        "union U: Copy { A(u64), B(u64) } fn run() { let mut u = U::A(7); if let case U::A(p) = &u { *p; } else { set u = U::A(1); } set u = U::B(1); }"
1559 1559
    );
1560 1560
}
1561 1561
1562 -
/// Replacing a borrowed pointer payload cannot forge an address.
1562 +
/// Replacing a borrowed pointer payload cannot forge an address, because a union that mixes
1563 +
/// pointer and plain payloads binds its payloads by value.
1563 1564
@test unsafe fn testBorrowedPointerPayloadReplacementRejected() throws (testing::TestError) {
1564 1565
    let programs = &[
1565 1566
        "static DATA: u8 = 7; union U: Copy { A(*u8), B(u64) } fn run() -> u8 { let mut u = U::A(&DATA); match &u { case U::A(p) => { set u = U::B(1); return **p; } else => return 0, } }",
1566 1567
        "static DATA: u8 = 7; union U: Copy { A(*u8), B(u64) } unsafe fn run() -> u8 { let mut u = U::A(&DATA); match &u { case U::A(p) => { set u = U::B(1); return **p; } else => return 0, } }",
1567 1568
    ];
1568 1569
    for program in programs {
1569 1570
        let mut a = testResolver();
1570 1571
        let result = try resolveProgramStr(&mut a, program);
1571 -
        try expectErrorKind(&result, resolver::ErrorKind::BorrowConflict("u"));
1572 +
        try expectErrorKind(&result, resolver::ErrorKind::MixedUnionByReference);
1572 1573
    }
1573 1574
}
1574 1575
1575 1576
/// Guards, nested patterns, and unsafe calls must preserve pattern source storage.
1576 1577
@test unsafe fn testPatternLoanIndirectMutationRejected() throws (testing::TestError) {
test/integration/boot.rad +2 -1
12 12
use super::harness::Expect;
13 13
use std::process::Outcome;
14 14
use super::kernel::Embedded;
15 15
16 16
/// Hostile packages the generator writes, with the names of their arrays.
17 -
constant HOSTILE: [Embedded; 13] = [
17 +
constant HOSTILE: [Embedded; 14] = [
18 18
    Embedded { name: "HOSTILE_FORGED",    file: "forged" },
19 19
    Embedded { name: "HOSTILE_OVERWRITE", file: "overwrite" },
20 20
    Embedded { name: "HOSTILE_LEAK",      file: "leak" },
21 21
    Embedded { name: "HOSTILE_EXTERN",    file: "extern" },
22 22
    Embedded { name: "HOSTILE_DEPENDENT", file: "dependent" },
24 24
    Embedded { name: "HOSTILE_HEAPREAD",  file: "heapread" },
25 25
    Embedded { name: "HOSTILE_HEAPSLICE", file: "heapslice" },
26 26
    Embedded { name: "HOSTILE_HEAPFORGE", file: "heapforge" },
27 27
    Embedded { name: "HOSTILE_HEAPTYPED", file: "heaptyped" },
28 28
    Embedded { name: "HOSTILE_HEAPRESET", file: "heapreset" },
29 +
    Embedded { name: "HOSTILE_MIXED",     file: "mixed" },
29 30
    Embedded { name: "HOSTILE_ZEROCAP",   file: "zerocap" },
30 31
    Embedded { name: "HOSTILE_OMITCAP",   file: "omitcap" },
31 32
];
32 33
/// Exit status of the hosted loaded package.
33 34
constant LOADED_STATUS: i32 = 43;
test/integration/verify.rad +1 -20
18 18
use std::process::Command;
19 19
20 20
/// Separator between a path and its verdict in the checker's report.
21 21
constant SEPARATOR: *[u8] = ": ";
22 22
23 -
/// Fixtures with no `unsafe` that the verifier rejects, because the compiler accepts unions that
24 -
/// mix pointer and plain payloads. A safe program must pass verification, so this list must
25 -
/// become empty.
26 -
constant KNOWN_UNVERIFIABLE: [*[u8]; 2] = ["layout.union", "match.variant.fields.bind"];
27 -
28 23
/// Whether `source` has the keyword `unsafe`. A comment or string that mentions it does not count.
29 24
fn usesUnsafe(source: *[u8], pool: &mut strings::Pool) -> bool {
30 25
    let mut s = scanner::scanner(scanner::SourceLoc::String, source, pool);
31 26
    loop {
32 27
        match scanner::next(&mut s, pool).kind {
42 37
/// the verifier refuses. Each item of `rejected` starts with the name of a fixture.
43 38
fn checkSafeRejections(h: &mut Harness, rejected: &[*[u8]]) throws (sys::Error) {
44 39
    let mut table: *mut [*[u8]] = &mut [];
45 40
    try! table.resize(strings::TABLE_SIZE, "", h.arena);
46 41
    let mut pool = strings::freshPool(table);
47 -
    let mut known: u32 = 0;
48 42
    for item in rejected {
49 43
        let end = mem::find(item, " ") else panic "checkSafeRejections: no verdict";
50 44
        let name = &item[.. end];
51 45
        let source = try h.load(h.join(&["test/tests/", name, ".rad"]));
52 46
        if harness::marker(source, "//! uses-std") <> nil or usesUnsafe(source, &mut pool) {
53 47
            continue;
54 48
        }
55 -
        let mut listed = false;
56 -
        for entry in &KNOWN_UNVERIFIABLE[..] {
57 -
            if mem::eq(entry, name) {
58 -
                set listed = true;
59 -
            }
60 -
        }
61 -
        if listed {
62 -
            set known += 1;
63 -
        } else {
64 -
            h.fail("verify", h.join(&["safe fixture fails verification: ", item]));
65 -
        }
66 -
    }
67 -
    if known <> KNOWN_UNVERIFIABLE.len {
68 -
        h.fail("verify", "a fixture in KNOWN_UNVERIFIABLE now passes; remove it from the list");
49 +
        h.fail("verify", h.join(&["safe fixture fails verification: ", item]));
69 50
    }
70 51
}
71 52
72 53
/// Print the items of `from` that `other` lacks, each after `mark`, on
73 54
/// standard error. Returns the number of items printed.
test/loader/hostile.rad +20 -0
23 23
constant SLICECELL: u32 = 3;
24 24
25 25
/// Layout of a typed heap handle slot.
26 26
constant HEAPCELL: u32 = 4;
27 27
28 +
/// Layout of a union of sixteen bytes that mixes a pointer cell and plain words.
29 +
constant MIXED: u32 = 5;
30 +
28 31
/// Storage for the IL of one package.
29 32
static BUILD: [u8; 65536] = [0; 65536];
30 33
/// Storage for the encoding of one package.
31 34
static OUT: [u8; 65536] = [0; 65536];
32 35
65 68
    try! table.append(il::Layout { size: 16, alignment: 8, slots: sliceCells }, arena);
66 69
    let handle = only(arena, il::Slot {
67 70
        offset: 0, kind: il::SlotKind::Heap(il::HeapType::Typed)
68 71
    });
69 72
    try! table.append(il::Layout { size: 8, alignment: 8, slots: handle }, arena);
73 +
    let mut variants: *mut [il::UnionVariant] = &mut [];
74 +
    try! variants.append(il::UnionVariant { tag: 0, layout: CELL }, arena);
75 +
    try! variants.append(il::UnionVariant { tag: 1, layout: PLAIN }, arena);
76 +
    let mixed = only(arena, il::Slot {
77 +
        offset: 0, kind: il::SlotKind::Union { offset: 8, size: 16, variants: &variants[..] }
78 +
    });
79 +
    try! table.append(il::Layout { size: 16, alignment: 8, slots: mixed }, arena);
70 80
    return table;
71 81
}
72 82
73 83
/// A function of one block.
74 84
fn function(arena: &heap::Heap, name: *[u8], instrs: &[il::Instr], isExtern: bool) -> il::Fn {
428 438
            done(),
429 439
        ],
430 440
        false,
431 441
        &["hostile", ENTRY, "hostile::heap"]
432 442
    );
443 +
    // An integer is stored over the pointer payload of a union that mixes pointers and data.
444 +
    emit(
445 +
        directory,
446 +
        "mixed",
447 +
        none,
448 +
        &[],
449 +
        &[reserve(0, MIXED), store64(il::Val::Imm(0x80000000), 0, 8), done()],
450 +
        false,
451 +
        plain
452 +
    );
433 453
    return 0;
434 454
}
test/loader/kernel/dispatchcheck.rad +1 -0
176 176
    rejected(authority, source, &inputs::HOSTILE_HEAPREAD[..]);
177 177
    rejected(authority, source, &inputs::HOSTILE_HEAPSLICE[..]);
178 178
    rejected(authority, source, &inputs::HOSTILE_HEAPFORGE[..]);
179 179
    rejected(authority, source, &inputs::HOSTILE_HEAPTYPED[..]);
180 180
    rejected(authority, source, &inputs::HOSTILE_HEAPRESET[..]);
181 +
    rejected(authority, source, &inputs::HOSTILE_MIXED[..]);
181 182
    rejected(authority, source, &inputs::HOSTILE_ZEROCAP[..]);
182 183
    rejected(authority, source, &inputs::HOSTILE_OMITCAP[..]);
183 184
}
test/tests/const.union.nested.mixed.rad added +38 -0
1 +
//! returns: 0
2 +
//! Nested mixed union constants preserve each active variant.
3 +
4 +
/// A pointer or a number.
5 +
union Inner: Copy {
6 +
    /// Pointer payload.
7 +
    A(*u8),
8 +
    /// Numeric payload.
9 +
    B(u32),
10 +
    /// Slice payload.
11 +
    S(*[u8]),
12 +
}
13 +
14 +
/// A nested union or a number.
15 +
union Outer: Copy {
16 +
    /// Nested payload.
17 +
    X(Inner),
18 +
    /// Numeric payload.
19 +
    Y(u64),
20 +
}
21 +
22 +
/// Nested numeric constant.
23 +
constant C: Outer = Outer::X(Inner::B(5));
24 +
25 +
/// Nested slice constant.
26 +
constant S: Outer = Outer::X(Inner::S("nested"));
27 +
28 +
/// Check the nested numeric and slice payloads.
29 +
@default fn main() -> i32 {
30 +
    let case Outer::X(inner) = C else return 1;
31 +
    let case Inner::B(value) = inner else return 2;
32 +
    assert value == 5;
33 +
    let case Outer::X(slice) = S else return 3;
34 +
    let case Inner::S(text) = slice else return 4;
35 +
    assert text.len == 6;
36 +
    assert text[5] == 'd';
37 +
    return 0;
38 +
}
test/tests/error.multi.mixed.union.rad added +124 -0
1 +
//! returns: 0
2 +
//! Mixed union errors retain their slots with different error shapes.
3 +
4 +
/// An error with numeric or slice data.
5 +
union E1: Copy {
6 +
    /// Numeric error code.
7 +
    Code(u32),
8 +
    /// Error name.
9 +
    Name(*[u8]),
10 +
}
11 +
12 +
/// An error without pointer slots.
13 +
union E2: Copy {
14 +
    /// Numeric error code.
15 +
    Code(u32),
16 +
}
17 +
18 +
/// Return a named error.
19 +
fn fail() throws (E1, E2) {
20 +
    throw E1::Name("name");
21 +
}
22 +
23 +
/// An additional slice error.
24 +
union E3: Copy {
25 +
    /// Error name.
26 +
    Name(*[u8]),
27 +
}
28 +
29 +
/// Produce each error shape or a slice success value.
30 +
fn choose(choice: u32) -> *[u8] throws (E1, E2) {
31 +
    match choice {
32 +
        case 1 => throw E1::Name("name"),
33 +
        case 2 => throw E1::Code(42),
34 +
        case 3 => throw E2::Code(7),
35 +
        else   => return "ok",
36 +
    }
37 +
}
38 +
39 +
/// Produce an error in a shared error region.
40 +
fn single() -> *[u8] throws (E1) {
41 +
    throw E1::Name("name");
42 +
}
43 +
44 +
/// Propagate errors into a larger throw list with a different order.
45 +
fn forward(choice: u32) -> *[u8] throws (E2, E3, E1) {
46 +
    if choice == 4 {
47 +
        throw E3::Name("third");
48 +
    }
49 +
    if choice == 5 {
50 +
        return try single();
51 +
    }
52 +
    return try choose(choice);
53 +
}
54 +
55 +
/// Check typed error extraction and a slice success value after propagation.
56 +
fn checkForward(choice: u32) {
57 +
    let mut caught = false;
58 +
    let value = try forward(choice) catch e as E1 {
59 +
        set caught = true;
60 +
        if let case E1::Code(code) = e {
61 +
            assert choice == 2;
62 +
            assert code == 42;
63 +
        } else {
64 +
            if let case E1::Name(s) = e; s.len == 4 {
65 +
                assert s[0] == 'n';
66 +
            } else {
67 +
                assert false;
68 +
            }
69 +
            let case E1::Name(s) = e else {
70 +
                assert false;
71 +
                return;
72 +
            };
73 +
            assert s.len == 4;
74 +
            let mut current = e;
75 +
            let mut count: u32 = 0;
76 +
            while let case E1::Name(name) = current {
77 +
                assert name[3] == 'e';
78 +
                set count += 1;
79 +
                set current = E1::Code(0);
80 +
            }
81 +
            assert count == 1;
82 +
        }
83 +
    } catch e as E2 {
84 +
        set caught = true;
85 +
        let case E2::Code(code) = e else {
86 +
            assert false;
87 +
            return;
88 +
        };
89 +
        assert choice == 3;
90 +
        assert code == 7;
91 +
    } catch e as E3 {
92 +
        set caught = true;
93 +
        let case E3::Name(name) = e else {
94 +
            assert false;
95 +
            return;
96 +
        };
97 +
        assert choice == 4;
98 +
        assert name.len == 5;
99 +
        assert name[0] == 't';
100 +
    };
101 +
    assert caught == (choice <> 0);
102 +
    if choice == 0 {
103 +
        assert value.len == 2;
104 +
        assert value[0] == 'o';
105 +
    }
106 +
}
107 +
108 +
/// Check direct catches and propagated errors.
109 +
@default fn main() -> i32 {
110 +
    let mut length: u32 = 0;
111 +
    try fail() catch e as E1 {
112 +
        if let case E1::Name(s) = e {
113 +
            set length = s.len;
114 +
            assert s[0] == 'n';
115 +
        }
116 +
    } catch e as E2 {
117 +
        return 1;
118 +
    };
119 +
    assert length == 4;
120 +
    for choice in 0 .. 6 {
121 +
        checkForward(choice);
122 +
    }
123 +
    return 0;
124 +
}
test/tests/layout.union.ril +10 -3
11 11
    slot 0 ptr own const $L0;
12 12
}
13 13
layout $L6 size 16 align 8 {
14 14
    slot 8 sub $L5;
15 15
}
16 +
layout $L7 size 8 align 8 {
17 +
    slot 0 ptr own const $L0;
18 +
}
19 +
layout $L8 size 16 align 8 {
20 +
    slot 0 union offset 8 size 16 0:$L7 1:$L0;
21 +
}
16 22
17 23
fn void $find(ptr ref mut $L1 %0, ptr own const $L0 %1, w8 %2) {
18 24
  @entry0
19 25
    br.ne w32 %2 0 @then1 @merge2;
20 26
  @then1
55 61
fn w32 $build(ptr own const $L0 %0, ptr own const $L0 %1) {
56 62
  @entry0
57 63
    reserve %2 $L6;
58 64
    store w8 0 %2 0;
59 65
    store.ptr %0 %2 8;
60 -
    reserve %3 $L4;
61 -
    store w8 0 %3 0;
62 -
    store.ptr %1 %3 8;
66 +
    reserve %3 $L8;
67 +
    reserve %4 $L7;
68 +
    store.ptr %1 %4 0;
69 +
    union.set %3 0 8 %4 $L7;
63 70
    ret 0;
64 71
}
test/tests/mutable.data.slice.reject.rad +2 -2
1 -
//! rejects: 15:43: mutable data cannot hold a slice or trait object, or point to one, because a racing writer could tear it; use a `constant`, an `unsafe static` or an `unsafe` default function
2 -
//! rejects: 19:43: mutable data cannot hold a slice or trait object, or point to one, because a racing writer could tear it; use a `constant`, an `unsafe static` or an `unsafe` default function
1 +
//! rejects: 15:43: mutable data cannot hold a slice, a trait object or a union that mixes pointer and plain payloads, or point to one, because a racing writer could tear it; use a `constant`, an `unsafe static` or an `unsafe` default function
2 +
//! rejects: 19:43: mutable data cannot hold a slice, a trait object or a union that mixes pointer and plain payloads, or point to one, because a racing writer could tear it; use a `constant`, an `unsafe static` or an `unsafe` default function
3 3
//! The verifier refuses a slice in mutable data, and a pointer that reaches one, so the compiler
4 4
//! refuses them in a safe storage parameter.
5 5
6 6
/// A record that holds a slice.
7 7
record Label {
test/tests/mutable.static.slice.reject.rad +1 -1
1 -
//! rejects: 3:18: mutable data cannot hold a slice or trait object, or point to one, because a racing writer could tear it; use a `constant`, an `unsafe static` or an `unsafe` default function
1 +
//! rejects: 3:18: mutable data cannot hold a slice, a trait object or a union that mixes pointer and plain payloads, or point to one, because a racing writer could tear it; use a `constant`, an `unsafe static` or an `unsafe` default function
2 2
//! The verifier refuses a slice in mutable data, so the compiler refuses it in a safe static.
3 3
static NAME: *[u8] = "x";
4 4
@default fn main() -> i32 { return 0; }
test/tests/optional.union.variant.owned.rad +8 -7
31 31
        return 5;
32 32
    };
33 33
    return x;
34 34
}
35 35
36 -
/// Read the number through a reference.
37 -
fn byRef(o: &?Item) -> u32 {
38 -
    if let case Item::Num(x) = o {
39 -
        return *x;
36 +
/// Test for a number through a reference. A union that mixes pointer and plain payloads binds
37 +
/// its payloads by value, so the pattern binds nothing.
38 +
fn byRef(o: &?Item) -> bool {
39 +
    if let case Item::Num(_) = o {
40 +
        return true;
40 41
    }
41 -
    return 7;
42 +
    return false;
42 43
}
43 44
44 45
@default fn main() -> i32 {
45 46
    assert read(num(4)) == 4;
46 47
    assert read(text("abc")) == 3;
48 49
    assert read(nil) == 2000;
49 50
    assert letElse(num(9)) == 9;
50 51
    assert letElse(text("abc")) == 5;
51 52
    assert letElse(nil) == 5;
52 53
    let m = num(6);
53 -
    assert byRef(&m) == 6;
54 +
    assert byRef(&m);
54 55
    let t = text("x");
55 -
    assert byRef(&t) == 7;
56 +
    assert not byRef(&t);
56 57
    return 0;
57 58
}
test/tests/static.reference.call.reject.rad +5 -5
2 2
//! rejects: 27:9: cannot mutate a static outside unsafe code
3 3
//! A static may hold a mutable pointer, but safe code cannot replace it while
4 4
//! a reference to it is live, since safe code cannot write a static. So a
5 5
//! reference into a static stays valid across a call.
6 6
7 -
/// Union whose payload is a pointer in one variant and a number in the other.
7 +
/// Union with a pointer in one variant and nothing in the other.
8 8
union Slot {
9 9
    /// Pointer variant.
10 10
    Ptr(*mut u32),
11 -
    /// Number variant.
12 -
    Num(u64),
11 +
    /// Empty variant.
12 +
    Empty,
13 13
}
14 14
15 15
/// Target of the pointer.
16 16
static TARGET: [u32; 1] = [7];
17 17
18 18
/// Slot that holds either variant.
19 -
static SLOT: Slot = Slot::Num(0);
19 +
static SLOT: Slot = Slot::Empty;
20 20
21 21
/// Change the variant of the slot.
22 22
fn clobber() {
23 -
    set SLOT = Slot::Num(0xdead0000);
23 +
    set SLOT = Slot::Empty;
24 24
}
25 25
26 26
@default fn main() -> i32 {
27 27
    set SLOT = Slot::Ptr(&mut TARGET[0]);
28 28
    let s: &mut Slot = &mut SLOT;
test/tests/union.mixed.alias.rad added +34 -0
1 +
//! returns: 133
2 +
//! A pointer or slice in a union that mixes pointer and plain payloads is read with `union.get`,
3 +
//! which checks the tag byte as it copies the payload. Unsafe code holds a second pointer to the
4 +
//! union and overwrites its tag while a reference is live. The last prong of the exhaustive match
5 +
//! runs without a tag test, so only the check of the read stops it from taking the payload of the
6 +
//! wrong variant: the program traps. Without the check it would return 3.
7 +
8 +
/// Mixed union.
9 +
union Val: Copy {
10 +
    /// Text.
11 +
    Text(*[u8]),
12 +
    /// Number.
13 +
    Num(u32),
14 +
    /// Wide number.
15 +
    Big(u64),
16 +
}
17 +
18 +
/// Overwrite the tag byte of the union through a second pointer.
19 +
unsafe fn forge(p: *unsafe mut Val, tag: u8) {
20 +
    let bytes = p as *unsafe mut opaque as *unsafe mut u8;
21 +
    set *bytes = tag;
22 +
}
23 +
24 +
@default unsafe fn main() -> i32 {
25 +
    let mut v = Val::Text("abc");
26 +
    let alias = &mut v as *unsafe mut Val;
27 +
    let r: &Val = &v;
28 +
    forge(alias, 9);
29 +
    match *r {
30 +
        case Val::Num(_)  => return 1,
31 +
        case Val::Big(_)  => return 2,
32 +
        case Val::Text(s) => return s.len as i32,
33 +
    }
34 +
}
test/tests/union.mixed.rad added +313 -0
1 +
//! returns: 0
2 +
//! A union that mixes pointer and plain payloads is a protected slot: only its constructors write
3 +
//! it, and its payloads are read as a whole, so the program passes verification. Test every way
4 +
//! to build, read, compare and replace one.
5 +
6 +
/// Mixed union that is `Copy`, with explicit tags on the void variants, so that tags differ from
7 +
/// the positions of the variants.
8 +
union Val: Copy {
9 +
    /// Nothing.
10 +
    None = 40,
11 +
    /// Text.
12 +
    Text(*[u8]),
13 +
    /// Small number.
14 +
    Num(u32),
15 +
    /// Number with a flag.
16 +
    Flag { n: u32, on: bool },
17 +
    /// Wide number.
18 +
    Big(u64),
19 +
    /// Slice, number and array, each read from the payload on its own.
20 +
    Both { s: *[u8], n: u32, arr: [u8; 3] },
21 +
    /// Also nothing.
22 +
    Void = 7,
23 +
}
24 +
25 +
/// Mixed union that owns a mutable array, so it is moved and not copied.
26 +
union Cell {
27 +
    /// Nothing.
28 +
    Zero,
29 +
    /// Owned array.
30 +
    Buf(*mut [u32; 4]),
31 +
    /// Number.
32 +
    Num(u32),
33 +
    /// Two numbers.
34 +
    Pair(u32, u8),
35 +
}
36 +
37 +
/// Mixed union that holds a mixed union.
38 +
union Node {
39 +
    /// Leaf with a number.
40 +
    Leaf(u32),
41 +
    /// Wrapper of a value.
42 +
    Wrap(Val),
43 +
    /// Empty.
44 +
    Nil,
45 +
}
46 +
47 +
/// Record that holds a mixed union.
48 +
record Holder: Copy {
49 +
    /// Value.
50 +
    v: Val,
51 +
    /// Other field.
52 +
    n: u32,
53 +
}
54 +
55 +
/// Constant table of values, which is read-only data that holds the tags and payloads.
56 +
constant TABLE: [Val; 4] = [
57 +
    Val::Num(7), Val::Text("hello"), Val::None, Val::Flag { n: 5, on: true }
58 +
];
59 +
60 +
/// Total of a value: the length of text, or the number.
61 +
fn total(v: Val) -> u64 {
62 +
    match v {
63 +
        case Val::None       => return 1000,
64 +
        case Val::Text(s)    => return s.len as u64,
65 +
        case Val::Num(n)     => return n as u64,
66 +
        case Val::Flag { n, on } => return n as u64 + (100 if on else 0),
67 +
        case Val::Big(b)     => return b,
68 +
        case Val::Both { .. } => return both(v) as u64,
69 +
        case Val::Void       => return 2000,
70 +
    }
71 +
}
72 +
73 +
/// Read the fields of a payload one by one, or only some, or only test one.
74 +
fn both(v: Val) -> u32 {
75 +
    match v {
76 +
        case Val::Both { n: 99, .. }      => return 99,
77 +
        case Val::Both { s, arr, .. }     => return s.len + arr[0] as u32 + arr[2] as u32,
78 +
        case Val::Text(_)                 => return 1,
79 +
        else                              => return 0,
80 +
    }
81 +
}
82 +
83 +
/// Match with guards, literals and alternatives.
84 +
fn classify(v: Val) -> u32 {
85 +
    match v {
86 +
        case Val::Num(0)                 => return 1,
87 +
        case Val::Num(n) if n > 100      => return 2,
88 +
        case Val::Num(_)                 => return 3,
89 +
        case Val::Text(s) if s.len == 0  => return 4,
90 +
        case Val::Text(_)                => return 5,
91 +
        case Val::Flag { on: true, .. } => return 6,
92 +
        case Val::Flag { n: 9, .. }      => return 7,
93 +
        case Val::None, Val::Void        => return 8,
94 +
        else                             => return 9,
95 +
    }
96 +
}
97 +
98 +
/// Bind with `if let case`.
99 +
fn ifLet(v: Val) -> u32 {
100 +
    if let case Val::Num(n) = v {
101 +
        return n;
102 +
    }
103 +
    if let case Val::Flag { n, on } = v; on {
104 +
        return n + 1;
105 +
    }
106 +
    return 0;
107 +
}
108 +
109 +
/// Bind with `let case ... else`.
110 +
fn letElse(v: Val) -> u32 {
111 +
    let case Val::Text(s) = v else {
112 +
        return 7;
113 +
    };
114 +
    return s.len;
115 +
}
116 +
117 +
/// Read a value, or `None` past the end.
118 +
fn at(items: &[Val], i: u32) -> Val {
119 +
    if i < items.len {
120 +
        return items[i];
121 +
    }
122 +
    return Val::None;
123 +
}
124 +
125 +
/// Add the numbers at the start of a list with `while let case`.
126 +
fn numbers(items: &[Val]) -> u32 {
127 +
    let mut sum: u32 = 0;
128 +
    let mut i: u32 = 0;
129 +
    while let case Val::Num(n) = at(items, i) {
130 +
        set sum += n;
131 +
        set i += 1;
132 +
    }
133 +
    return sum;
134 +
}
135 +
136 +
/// Read a node, through nested patterns.
137 +
fn node(n: Node) -> u32 {
138 +
    match n {
139 +
        case Node::Leaf(x)                     => return x,
140 +
        case Node::Wrap(Val::Num(x))           => return x + 1000,
141 +
        case Node::Wrap(Val::Text("ab"))       => return 2000,
142 +
        case Node::Wrap(Val::Flag { n: x, .. }) => return x + 3000,
143 +
        case Node::Wrap(v)                     => return total(v) as u32 + 4000,
144 +
        case Node::Nil                         => return 5000,
145 +
    }
146 +
}
147 +
148 +
/// Read an optional value.
149 +
fn optional(o: ?Val) -> u64 {
150 +
    match o {
151 +
        case Val::Num(n)  => return n as u64,
152 +
        case Val::Text(s) => return s.len as u64 + 10,
153 +
        case Val::None    => return 20,
154 +
        case nil          => return 30,
155 +
        else              => return 40,
156 +
    }
157 +
}
158 +
159 +
/// Read an optional value with `if let case`.
160 +
fn optionalLet(o: ?Val) -> u32 {
161 +
    if let case Val::Num(n) = o {
162 +
        return n;
163 +
    }
164 +
    return 0;
165 +
}
166 +
167 +
/// Read a value in a record, and in an array of records.
168 +
fn holder(h: Holder) -> u64 {
169 +
    match h.v {
170 +
        case Val::Num(n) => return n as u64 + h.n as u64,
171 +
        else             => return total(h.v) + h.n as u64,
172 +
    }
173 +
}
174 +
175 +
/// Read a cell that owns an array, which moves out of the cell.
176 +
fn cell(c: Cell) -> u32 {
177 +
    match c {
178 +
        case Cell::Zero    => return 0,
179 +
        case Cell::Buf(b)  => {
180 +
            set b[1] = 9;
181 +
            return b[0] + b[1] + b[3];
182 +
        }
183 +
        case Cell::Num(n)  => return n,
184 +
        case Cell::Pair(a, b) => return a + b as u32,
185 +
    }
186 +
}
187 +
188 +
/// Replace the whole value, and read what was read before.
189 +
fn replace(v: Val) -> u64 {
190 +
    let mut cur = v;
191 +
    let before = total(cur);
192 +
    set cur = Val::Big(5);
193 +
    let mid = total(cur);
194 +
    set cur = Val::Text("hello");
195 +
    return before * 1000000 + mid * 1000 + total(cur);
196 +
}
197 +
198 +
/// Replace the elements of an array one by one.
199 +
fn fill(items: &mut [Val; 3]) {
200 +
    set items[0] = Val::Num(1);
201 +
    set items[1] = Val::Text("xy");
202 +
    set items[2] = Val::Flag { n: 3, on: true };
203 +
}
204 +
205 +
/// Build a cell from a number, and give it back.
206 +
fn make(n: u32, store: *mut [u32; 4]) -> Cell {
207 +
    if n == 0 {
208 +
        return Cell::Zero;
209 +
    }
210 +
    if n == 1 {
211 +
        return Cell::Buf(store);
212 +
    }
213 +
    if n == 2 {
214 +
        return Cell::Pair(n, 4);
215 +
    }
216 +
    return Cell::Num(n);
217 +
}
218 +
219 +
@default fn main(store: *mut [u32; 4]) -> i32 {
220 +
    // Constants and literals shared as read-only data.
221 +
    assert total(TABLE[0]) == 7 and total(TABLE[1]) == 5 and total(TABLE[2]) == 1000;
222 +
    assert total(TABLE[3]) == 105 and classify(TABLE[3]) == 6;
223 +
    let shared: *[Val] = &[Val::Big(9), Val::Text("ab")];
224 +
    assert total(shared[0]) == 9 and total(shared[1]) == 2;
225 +
    // Fields that are slices, arrays and numbers.
226 +
    let b = Val::Both { s: "abc", n: 4, arr: [1, 2, 3] };
227 +
    assert both(b) == 3 + 1 + 3 and total(b) == 7;
228 +
    assert both(Val::Both { s: "", n: 99, arr: [0, 0, 0] }) == 99;
229 +
    assert both(Val::Text("x")) == 1 and both(Val::None) == 0;
230 +
    // Constructors.
231 +
    assert total(Val::Num(5)) == 5;
232 +
    assert total(Val::Text("abc")) == 3;
233 +
    assert total(Val::Flag { n: 4, on: true }) == 104;
234 +
    assert total(Val::Flag { n: 4, on: false }) == 4;
235 +
    assert total(Val::Big(0x123456789)) == 0x123456789;
236 +
    assert total(Val::None) == 1000;
237 +
    assert total(Val::Void) == 2000;
238 +
    // Match.
239 +
    assert classify(Val::Num(0)) == 1;
240 +
    assert classify(Val::Num(101)) == 2;
241 +
    assert classify(Val::Num(50)) == 3;
242 +
    assert classify(Val::Text("")) == 4;
243 +
    assert classify(Val::Text("a")) == 5;
244 +
    assert classify(Val::Flag { n: 1, on: true }) == 6;
245 +
    assert classify(Val::Flag { n: 9, on: false }) == 7;
246 +
    assert classify(Val::Flag { n: 8, on: false }) == 9;
247 +
    assert classify(Val::None) == 8;
248 +
    assert classify(Val::Void) == 8;
249 +
    assert classify(Val::Big(1)) == 9;
250 +
    // If-let, let-else.
251 +
    assert ifLet(Val::Num(6)) == 6;
252 +
    assert ifLet(Val::Flag { n: 6, on: true }) == 7;
253 +
    assert ifLet(Val::Flag { n: 6, on: false }) == 0;
254 +
    assert ifLet(Val::None) == 0;
255 +
    assert letElse(Val::Text("four")) == 4;
256 +
    assert letElse(Val::Num(4)) == 7;
257 +
    // While-let.
258 +
    let list = [Val::Num(1), Val::Num(2), Val::Num(4), Val::Text("x"), Val::Num(8)];
259 +
    assert numbers(&list[..]) == 7;
260 +
    assert numbers(&list[3 ..]) == 0;
261 +
    assert numbers(&list[4 ..]) == 8;
262 +
    // Nested unions.
263 +
    assert node(Node::Leaf(3)) == 3;
264 +
    assert node(Node::Wrap(Val::Num(5))) == 1005;
265 +
    assert node(Node::Wrap(Val::Text("ab"))) == 2000;
266 +
    assert node(Node::Wrap(Val::Text("abc"))) == 4003;
267 +
    assert node(Node::Wrap(Val::Flag { n: 6, on: false })) == 3006;
268 +
    assert node(Node::Wrap(Val::None)) == 5000;
269 +
    assert node(Node::Nil) == 5000;
270 +
    // Optionals.
271 +
    let some: ?Val = Val::Num(3);
272 +
    let none: ?Val = nil;
273 +
    assert optional(some) == 3;
274 +
    assert optional(Val::Text("abcd")) == 14;
275 +
    assert optional(Val::None) == 20;
276 +
    assert optional(none) == 30;
277 +
    assert optional(Val::Big(1)) == 40;
278 +
    assert optionalLet(some) == 3;
279 +
    assert optionalLet(none) == 0;
280 +
    assert optionalLet(Val::Void) == 0;
281 +
    // Records and arrays of records.
282 +
    let h = Holder { v: Val::Num(4), n: 5 };
283 +
    assert holder(h) == 9;
284 +
    assert holder(Holder { v: Val::Text("ab"), n: 5 }) == 7;
285 +
    let hs = [h, Holder { v: Val::None, n: 1 }];
286 +
    assert holder(hs[0]) + holder(hs[1]) == 9 + 1001;
287 +
    // Equality.
288 +
    assert Val::Num(3) == Val::Num(3);
289 +
    assert Val::Num(3) <> Val::Num(4);
290 +
    assert Val::Num(3) <> Val::Big(3);
291 +
    assert Val::None == Val::None;
292 +
    assert Val::None <> Val::Void;
293 +
    assert Val::Flag { n: 1, on: true } == Val::Flag { n: 1, on: true };
294 +
    assert Val::Flag { n: 1, on: true } <> Val::Flag { n: 1, on: false };
295 +
    assert Val::Text("ab") <> Val::Num(2);
296 +
    assert h == Holder { v: Val::Num(4), n: 5 };
297 +
    assert h <> Holder { v: Val::Num(4), n: 6 };
298 +
    assert some == some and some <> none;
299 +
    assert Val::Void == Val::Void;
300 +
    // Slices and replacement.
301 +
    let mut three = [Val::None, Val::None, Val::None];
302 +
    fill(&mut three);
303 +
    assert total(three[0]) == 1 and total(three[1]) == 2 and total(three[2]) == 103;
304 +
    assert replace(Val::Num(2)) == 2005005;
305 +
    assert replace(Val::Text("abc")) == 3005005;
306 +
    // Cells move their owned array in and out.
307 +
    set store[0] = 5;
308 +
    set store[3] = 6;
309 +
    assert cell(make(1, store)) == 20;
310 +
    assert cell(Cell::Zero) == 0;
311 +
    assert cell(Cell::Pair(2, 3)) == 5;
312 +
    return 0;
313 +
}
test/tests/union.mixed.snapshot.rad added +67 -0
1 +
//! returns: 0
2 +
//! Values bound from a mixed union keep their bytes when the source changes.
3 +
4 +
/// Values with pointer and plain payloads.
5 +
union Value: Copy {
6 +
    /// Text.
7 +
    Text(*[u8]),
8 +
    /// Inline bytes.
9 +
    Bytes([u8; 3]),
10 +
    /// A number.
11 +
    Num(u32),
12 +
}
13 +
14 +
/// Replace the source and let a guard continue.
15 +
fn clear(v: &mut Value) -> bool {
16 +
    set *v = Value::Num(9);
17 +
    return true;
18 +
}
19 +
20 +
/// Read an array from a mutable source, then replace that source.
21 +
fn unguarded() -> u8 {
22 +
    let mut v = Value::Bytes([1, 2, 3]);
23 +
    match v {
24 +
        case Value::Bytes(bytes) => {
25 +
            set v = Value::Num(0xffffffff);
26 +
            return bytes[0] + bytes[1] + bytes[2];
27 +
        }
28 +
        else => return 0,
29 +
    }
30 +
}
31 +
32 +
/// Later arms use the subject value from before a guard changes its source.
33 +
fn guarded() -> u32 {
34 +
    let mut v = Value::Text("abc");
35 +
    match v {
36 +
        case Value::Text(s) if not clear(&mut v) => return 100,
37 +
        case Value::Text(s)                      => return s.len,
38 +
        else                                     => return 200,
39 +
    }
40 +
}
41 +
42 +
/// Conditional bindings retain their payload through guards and source writes.
43 +
fn conditional() -> u32 {
44 +
    let mut v = Value::Text("abcd");
45 +
    let mut n: u32 = 0;
46 +
    if let case Value::Text(s) = v; clear(&mut v) {
47 +
        set n += s.len;
48 +
    }
49 +
    set v = Value::Text("xy");
50 +
    let case Value::Text(s) = v else return 100;
51 +
    set v = Value::Num(1);
52 +
    set n += s.len;
53 +
    set v = Value::Text("hello");
54 +
    while let case Value::Text(s) = v {
55 +
        set v = Value::Num(2);
56 +
        set n += s.len;
57 +
    }
58 +
    return n;
59 +
}
60 +
61 +
/// Check snapshots across case forms and source writes.
62 +
@default fn main() -> i32 {
63 +
    assert unguarded() == 6;
64 +
    assert guarded() == 3;
65 +
    assert conditional() == 11;
66 +
    return 0;
67 +
}
test/verify/expected +2 -3
10 10
builtin.sliceof.mut Type
11 11
builtin.sliceof Type
12 12
call.clobber Type
13 13
call.stack.args.method Type
14 14
cast.basic View
15 -
cond.match.guard.regalloc View
15 +
cond.match.guard.regalloc Type
16 16
data.optional.nil Data
17 17
data.optional.value Data
18 18
ecall.i64 Slot
19 19
edge.cases.4 Type
20 20
edge.cases.6 Data
29 29
error.slice.bounds Type
30 30
fn.callback.nested Type
31 31
fn.unsafe.callbacks Type
32 32
heap.rewind.static Symbol
33 33
index.u8 Type
34 -
layout.union Slot
35 34
linear.unsafe Type
36 35
match.alternatives.subject Type
37 36
match.mutref.push Type
38 37
match.nested.deref Type
39 38
match.nested.enum.byref Type
40 39
match.nested.guard.field Type
41 -
match.variant.fields.bind Slot
42 40
match.variant.fields.deref Type
43 41
method.multiple Type
44 42
method.with.trait Type
45 43
mutref.call.result Type
46 44
mutref.loop Type
113 111
trait.throws Type
114 112
trait.writer Type
115 113
undefined.merge.pointer Type
116 114
union-tag Type
117 115
union.edge.case.3 Type
116 +
union.mixed.alias Type
118 117
union.payload.mutref Type
119 118
unsafe.block Type