Commit ed85594ba0 for golang

commit ed85594ba030eb6ef4ba730e36b4dead61b03b7f
Author: Carlos Amedee <carlos@golang.org>
Date:   Mon Nov 16 16:15:00 2026 -0500

    cmd/internal/obj/wasm, cmd/link/internal/wasm: add Throw and TryTable

    Add the Wasm exception-handling instructions Throw (0x08) and
    TryTable (0x1F) for GOWASM=stackswitch. Later CLs use them to unwind
    to the host via a new $exit tag.

    Throw and TryTable require a constant tag operand for $exit; Suspend
    now requires one for $yield instead of hard-coding tag 0. TryTable
    uses the empty block type and a single catch $exit 0 clause branching
    to the enclosing Block. Preprocess requires TryTable to be directly
    inside a Block with no parameters or results; assemble rejects it in
    functions with a local SP.

    The linker adds $exit (tag 1) alongside $yield (tag 0), both with
    type () -> () at type index 1. Without GOWASM=stackswitch, output is
    unchanged and the stack-switching and exception-handling instructions
    are rejected.

    For #81963

    Cq-Include-Trybots: luci.golang.try:gotip-js-wasm-stackswitch,gotip-wasip1-wasm_wasmtime-stackswitch
    Change-Id: I2f930472bfc35d7162a54a530f637680e34b8aee
    Reviewed-on: https://go-review.googlesource.com/c/go/+/864381
    Reviewed-by: Cherry Mui <cherryyz@google.com>
    LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
    Auto-Submit: Carlos Amedee <carlos@golang.org>

diff --git a/src/cmd/asm/internal/asm/endtoend_test.go b/src/cmd/asm/internal/asm/endtoend_test.go
index 835347e915..26f1612f2d 100644
--- a/src/cmd/asm/internal/asm/endtoend_test.go
+++ b/src/cmd/asm/internal/asm/endtoend_test.go
@@ -598,5 +598,9 @@ func TestS390XEndToEnd(t *testing.T) {
 }

 func TestWasmEndToEnd(t *testing.T) {
+	// The test function uses stack-switching instructions.
+	defer func(old bool) { buildcfg.GOWASM.StackSwitch = old }(buildcfg.GOWASM.StackSwitch)
+	buildcfg.GOWASM.StackSwitch = true
+
 	testEndToEnd(t, "wasm", "wasm")
 }
diff --git a/src/cmd/asm/internal/asm/testdata/wasm.s b/src/cmd/asm/internal/asm/testdata/wasm.s
index eaba839b1a..e07e4dd80a 100644
--- a/src/cmd/asm/internal/asm/testdata/wasm.s
+++ b/src/cmd/asm/internal/asm/testdata/wasm.s
@@ -16,5 +16,8 @@ TEXT testWasm(SB), NOSPLIT, $0-0                          // 01017f23002101
 	RefIsNull                                         // d1
 	RefFunc testWasm(SB)                              // d2
 	ContNew                                           // e002
-	Suspend                                           // e20023002101
+	Suspend $0                                        // e20023002101
 	Resume                                            // e30201000000
+	Block                                             // 0240
+	Throw $1                                          // 0801
+	End                                               // 0b
diff --git a/src/cmd/internal/obj/wasm/a.out.go b/src/cmd/internal/obj/wasm/a.out.go
index 5f303949cc..8bad9b5ecf 100644
--- a/src/cmd/internal/obj/wasm/a.out.go
+++ b/src/cmd/internal/obj/wasm/a.out.go
@@ -34,6 +34,8 @@ const (
 	AIf
 	AElse

+	AThrow // opcode 0x08
+
 	AEnd // opcode 0x0B
 	ABr
 	ABrIf
@@ -47,6 +49,8 @@ const (
 	ADrop // opcode 0x1A
 	ASelect

+	ATryTable // opcode 0x1F
+
 	ALocalGet // opcode 0x20
 	ALocalSet
 	ALocalTee
diff --git a/src/cmd/internal/obj/wasm/anames.go b/src/cmd/internal/obj/wasm/anames.go
index 70e29cf08b..89350740f9 100644
--- a/src/cmd/internal/obj/wasm/anames.go
+++ b/src/cmd/internal/obj/wasm/anames.go
@@ -15,6 +15,7 @@ var Anames = []string{
 	"Loop",
 	"If",
 	"Else",
+	"Throw",
 	"End",
 	"Br",
 	"BrIf",
@@ -24,6 +25,7 @@ var Anames = []string{
 	"CallIndirect",
 	"Drop",
 	"Select",
+	"TryTable",
 	"LocalGet",
 	"LocalSet",
 	"LocalTee",
diff --git a/src/cmd/internal/obj/wasm/wasmobj.go b/src/cmd/internal/obj/wasm/wasmobj.go
index da9c553e1f..cd614de186 100644
--- a/src/cmd/internal/obj/wasm/wasmobj.go
+++ b/src/cmd/internal/obj/wasm/wasmobj.go
@@ -12,6 +12,7 @@ import (
 	"encoding/binary"
 	"fmt"
 	"internal/abi"
+	"internal/buildcfg"
 	"io"
 	"math"
 )
@@ -97,8 +98,9 @@ var Register = map[string]int16{
 	"PC_B": REG_PC_B,
 }

-// The index at which to insert special continuation and its block type, for WasmFX extension.
-const ContinuationTypeIndex = 2
+// GoFuncTypeIndex is the type section index of the Go function signature
+// (PC_B i32) -> (i32). Must match newTypes in cmd/link/internal/wasm.
+const GoFuncTypeIndex = 0

 // EmptyFuncTypeIndex is the type section index of the function signature
 // () -> (), used for all tags and as the underlying function type of
@@ -106,6 +108,47 @@ const ContinuationTypeIndex = 2
 // Must match initStackSwitchingTypes in cmd/link/internal/wasm.
 const EmptyFuncTypeIndex = 1

+// ContinuationTypeIndex is the type section index of the continuation type
+// (cont $EmptyFuncTypeIndex) under GOWASM=stackswitch.
+// Must match initStackSwitchingTypes in cmd/link/internal/wasm.
+const ContinuationTypeIndex = 2
+
+// Wasm tag indices declared by the linker under GOWASM=stackswitch. Throw and
+// TryTable take ExitTagIndex as a required constant operand; Suspend takes
+// YieldTagIndex.
+const (
+	// YieldTagIndex is the index of the $yield tag, which Suspend and
+	// Resume use to switch goroutine continuations.
+	YieldTagIndex = 0
+	// ExitTagIndex is the index of the $exit tag, which Throw raises to
+	// unwind to an enclosing TryTable and return to the host.
+	ExitTagIndex = 1
+	// NumTags is the number of Wasm tags declared under GOWASM=stackswitch.
+	NumTags = 2
+)
+
+// tagOperand validates and returns the tag index in p.From of instruction p
+// (Throw, TryTable, or Suspend), which must be wantTag. If the operand is
+// missing, non-constant, not wantTag, or followed by extra operands,
+// tagOperand reports a diagnostic and returns 0.
+func tagOperand(ctxt *obj.Link, p *obj.Prog, wantTag uint64) uint64 {
+	switch {
+	case p.From.Type == obj.TYPE_NONE:
+		ctxt.Diag("%v: missing tag operand", p)
+	case p.To.Type != obj.TYPE_NONE || p.Reg != 0 || len(p.RestArgs) > 0:
+		ctxt.Diag("%v: unexpected extra operand", p)
+	case p.From.Type != obj.TYPE_CONST:
+		ctxt.Diag("%v: tag operand must be a constant", p)
+	case p.From.Offset < 0 || p.From.Offset >= NumTags:
+		ctxt.Diag("%v: bad tag %d", p, p.From.Offset)
+	case uint64(p.From.Offset) != wantTag:
+		ctxt.Diag("%v: bad tag %d (want %d)", p, p.From.Offset, wantTag)
+	default:
+		return uint64(p.From.Offset)
+	}
+	return 0
+}
+
 var registerNames []string

 func init() {
@@ -140,7 +183,6 @@ var unaryDst = map[obj.As]bool{
 	AI64Store16:   true,
 	AI64Store32:   true,
 	AV128Store:    true,
-	ASuspend:      true,
 	ACALLNORESUME: true,
 }

@@ -321,8 +363,8 @@ func preprocess(ctxt *obj.Link, s *obj.LSym, newprog obj.ProgAlloc) {
 	// Introduce resume points for CALL instructions
 	// and collect other explicit resume points.
 	numResumePoints := 0
-	explicitBlockDepth := 0
-	pc := int64(0) // pc is only incremented when necessary, this avoids bloat of the BrTable instruction
+	var opens []*obj.Prog // explicit Block, Loop, If, or TryTable; innermost last
+	pc := int64(0)        // pc is only incremented when necessary, this avoids bloat of the BrTable instruction
 	var tableIdxs []uint64
 	tablePC := int64(0)
 	base := ctxt.PosTable.Pos(s.Func().Text.Pos).Base()
@@ -330,18 +372,32 @@ func preprocess(ctxt *obj.Link, s *obj.LSym, newprog obj.ProgAlloc) {
 		prevBase := base
 		base = ctxt.PosTable.Pos(p.Pos).Base()
 		switch p.As {
+		case ATryTable:
+			// TryTable's catch clause branches to label 0, the construct
+			// immediately enclosing the TryTable, which must be an explicit
+			// Block with the empty block type (no parameters, no results).
+			if n := len(opens); n == 0 || opens[n-1].As != ABlock || opens[n-1].From.Offset != 0 {
+				ctxt.Diag("%v: TryTable must be directly inside a Block with no parameters or results", p)
+			}
+			opens = append(opens, p)
+
 		case ABlock, ALoop, AIf:
-			explicitBlockDepth++
+			opens = append(opens, p)

 		case AEnd:
-			if explicitBlockDepth == 0 {
-				panic("End without block")
+			if len(opens) == 0 {
+				ctxt.Diag("%v: End without block", p)
+				continue
 			}
-			explicitBlockDepth--
+			opens = opens[:len(opens)-1]

 		case ARESUMEPOINT:
-			if explicitBlockDepth != 0 {
-				panic("RESUME can only be used on toplevel")
+			if len(opens) != 0 {
+				ctxt.Diag("%v: RESUMEPOINT can only be used on toplevel", p)
+				// Drop it: assemble runs despite errors (see obj.Flushplist)
+				// and cannot encode RESUMEPOINT.
+				p.As = obj.ANOP
+				continue
 			}
 			p.As = AEnd
 			for tablePC <= pc {
@@ -352,8 +408,11 @@ func preprocess(ctxt *obj.Link, s *obj.LSym, newprog obj.ProgAlloc) {
 			pc++

 		case obj.ACALL:
-			if explicitBlockDepth != 0 {
-				panic("CALL can only be used on toplevel, try CALLNORESUME instead")
+			if len(opens) != 0 {
+				ctxt.Diag("%v: CALL can only be used on toplevel, try CALLNORESUME instead", p)
+				// Drop it: lowering a CALL needs the resume point after it.
+				p.As = obj.ANOP
+				continue
 			}
 			appendp(p, ARESUMEPOINT)
 		}
@@ -375,6 +434,9 @@ func preprocess(ctxt *obj.Link, s *obj.LSym, newprog obj.ProgAlloc) {
 			}
 		}
 	}
+	if len(opens) != 0 {
+		ctxt.Diag("%v: unclosed %v", opens[len(opens)-1], opens[len(opens)-1].As)
+	}
 	tableIdxs = append(tableIdxs, uint64(numResumePoints))
 	s.Size = pc + 1
 	if ctxt.Arch.PtrSize == 4 {
@@ -450,7 +512,7 @@ func preprocess(ctxt *obj.Link, s *obj.LSym, newprog obj.ProgAlloc) {
 	currentExplicitDepth := 0
 	for p := s.Func().Text; p != nil; p = p.Link {
 		switch p.As {
-		case ABlock, ALoop, AIf:
+		case ABlock, ALoop, AIf, ATryTable:
 			currentExplicitDepth++
 		case AEnd:
 			// A resume point is an End at depth 0. Its Block is added later.
@@ -795,7 +857,7 @@ func preprocess(ctxt *obj.Link, s *obj.LSym, newprog obj.ProgAlloc) {
 	blockDepths := make(map[*obj.Prog]int)
 	for p := s.Func().Text; p != nil; p = p.Link {
 		switch p.As {
-		case ABlock, ALoop, AIf:
+		case ABlock, ALoop, AIf, ATryTable:
 			currentDepth++
 			blockDepths[p] = currentDepth
 		case AEnd:
@@ -1348,6 +1410,17 @@ func assemble(ctxt *obj.Link, s *obj.LSym, newprog obj.ProgAlloc) {
 			continue
 		}

+		switch p.As {
+		case ARefNull, AContNew, AResume, ASuspend, AThrow, ATryTable:
+			if !buildcfg.GOWASM.StackSwitch {
+				ctxt.Diag("%v: requires GOWASM=stackswitch", p)
+				continue
+			}
+		case AContBind, AResumeThrow, AResumeThrowRef, ASwitch:
+			ctxt.Diag("%v: unsupported instruction", p)
+			continue
+		}
+
 		writeOpcode(w, p.As)

 		switch p.As {
@@ -1514,28 +1587,42 @@ func assemble(ctxt *obj.Link, s *obj.LSym, newprog obj.ProgAlloc) {
 			w.WriteByte(ContinuationTypeIndex)

 		case ASuspend:
-			// Hard coded tag index: We only need one tag, call it "yield" for
-			// the WasmFX implementation of the goroutine scheduler.
-			w.WriteByte(0x00)
+			writeUleb128(w, tagOperand(ctxt, p, YieldTagIndex))
 			if hasLocalSP {
 				// The stack may have moved while suspended.
 				updateLocalSP(w)
 			}

-		case ASwitch:
-			panic("Unimplemented: Wasm Switch instruction.")
-
 		case AResume:
 			// As with ARefNull, there is only one type at which we use this instruction.
 			w.WriteByte(ContinuationTypeIndex) // Continuation type index.
 			w.WriteByte(0x01)                  // size of handler table
 			w.WriteByte(0x00)                  // "on" clause with handler, not switch
-			w.WriteByte(0x00)                  // tag 0 ->
+			writeUleb128(w, YieldTagIndex)     // tag $yield ->
 			w.WriteByte(0x00)                  //   label 0  (hard-coded for the implementation in asm_wasm.s)

 		case AMemoryCopy:
 			w.WriteByte(0x00)
 			w.WriteByte(0x00)
+
+		case AThrow:
+			writeUleb128(w, tagOperand(ctxt, p, ExitTagIndex))
+
+		case ATryTable:
+			if hasLocalSP {
+				ctxt.Diag("%v: TryTable cannot be used in a function with a local SP", p)
+			}
+			// Unlike Block, Loop, and If, whose From is a block type,
+			// TryTable's From is the tag it catches. It encodes as a
+			// try_table with the empty block type (0x40: no parameters,
+			// no results) and 1 catch clause (0x00 = catch $tag $label)
+			// branching to label 0: the end of the Block enclosing the
+			// TryTable (see preprocess).
+			w.WriteByte(0x40)
+			w.WriteByte(0x01)
+			w.WriteByte(0x00)
+			writeUleb128(w, tagOperand(ctxt, p, ExitTagIndex))
+			w.WriteByte(0x00)
 		}
 	}

@@ -1555,12 +1642,16 @@ func writeOpcode(w *bytes.Buffer, as obj.As) {
 	switch {
 	case as < AUnreachable:
 		panic(fmt.Sprintf("unexpected assembler op: %s", as))
-	case as < AEnd:
+	case as < AThrow:
 		w.WriteByte(byte(as - AUnreachable + 0x00))
+	case as < AEnd:
+		w.WriteByte(byte(as - AThrow + 0x08))
 	case as < ADrop:
 		w.WriteByte(byte(as - AEnd + 0x0B))
-	case as < ALocalGet:
+	case as < ATryTable:
 		w.WriteByte(byte(as - ADrop + 0x1A))
+	case as < ALocalGet:
+		w.WriteByte(byte(as - ATryTable + 0x1F))
 	case as < AI32Load:
 		w.WriteByte(byte(as - ALocalGet + 0x20))
 	case as < ARefNull:
diff --git a/src/cmd/internal/obj/wasm/wasmobj_test.go b/src/cmd/internal/obj/wasm/wasmobj_test.go
index 056eebb0de..19b095f16b 100644
--- a/src/cmd/internal/obj/wasm/wasmobj_test.go
+++ b/src/cmd/internal/obj/wasm/wasmobj_test.go
@@ -7,6 +7,10 @@ package wasm
 import (
 	"bytes"
 	"cmd/internal/obj"
+	"fmt"
+	"internal/buildcfg"
+	"slices"
+	"strings"
 	"testing"
 )

@@ -21,8 +25,10 @@ func TestWriteOpcode(t *testing.T) {
 		want []byte
 	}{
 		{AUnreachable, []byte{0x00}},
+		{AThrow, []byte{0x08}},
 		{AEnd, []byte{0x0B}},
 		{ADrop, []byte{0x1A}},
+		{ATryTable, []byte{0x1F}},
 		{ALocalGet, []byte{0x20}},
 		{ATableGet, []byte{0x25}},
 		{ATableSet, []byte{0x26}}, // last before the gap at 0x27
@@ -66,6 +72,7 @@ func TestWriteOpcode(t *testing.T) {
 // TestAssembleTableAndRef checks the encodings that assemble writes for
 // table, reference, and stack-switching instructions.
 func TestAssembleTableAndRef(t *testing.T) {
+	setStackSwitch(t, true)
 	tests := []struct {
 		name string
 		prog obj.Prog
@@ -78,9 +85,8 @@ func TestAssembleTableAndRef(t *testing.T) {
 		{"RefNull", obj.Prog{As: ARefNull}, []byte{0xD0, ContinuationTypeIndex}},
 		{"RefIsNull", obj.Prog{As: ARefIsNull}, []byte{0xD1}},
 		{"ContNew", obj.Prog{As: AContNew}, []byte{0xE0, ContinuationTypeIndex}},
-		{"Suspend", obj.Prog{As: ASuspend}, []byte{0xE2, 0x00}},
-		// Continuation type, then 1 handler: on-label clause (0x00), tag 0, label 0.
-		{"Resume", obj.Prog{As: AResume}, []byte{0xE3, ContinuationTypeIndex, 0x01, 0x00, 0x00, 0x00}},
+		// Continuation type, then 1 handler: on-label clause (0x00), $yield, label 0.
+		{"Resume", obj.Prog{As: AResume}, []byte{0xE3, ContinuationTypeIndex, 0x01, 0x00, YieldTagIndex, 0x00}},
 	}
 	for _, tt := range tests {
 		t.Run(tt.name, func(t *testing.T) {
@@ -91,14 +97,305 @@ func TestAssembleTableAndRef(t *testing.T) {
 	}
 }

+// TestAssembleTagOperands checks the tag operands of Throw, TryTable, and
+// Suspend, and the diagnostics for bad operands, missing GOWASM=stackswitch,
+// and unsupported stack-switching instructions.
+func TestAssembleTagOperands(t *testing.T) {
+	setStackSwitch(t, true)
+	tests := []struct {
+		name string
+		prog obj.Prog
+		want []byte
+	}{
+		{"Throw $exit", obj.Prog{As: AThrow, From: constAddr(ExitTagIndex)}, []byte{0x08, ExitTagIndex}},
+		{"TryTable $exit", obj.Prog{As: ATryTable, From: constAddr(ExitTagIndex)}, []byte{0x1F, 0x40, 0x01, 0x00, ExitTagIndex, 0x00}},
+		{"Suspend $yield", obj.Prog{As: ASuspend, From: constAddr(YieldTagIndex)}, []byte{0xE2, YieldTagIndex}},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if got := assembleOne(t, &tt.prog); !bytes.Equal(got, tt.want) {
+				t.Errorf("got % x, want % x", got, tt.want)
+			}
+		})
+	}
+
+	bad := []struct {
+		name string
+		prog obj.Prog
+		diag string
+	}{
+		{"Throw", obj.Prog{As: AThrow}, "missing tag operand"},
+		{"TryTable", obj.Prog{As: ATryTable}, "missing tag operand"},
+		{"Suspend", obj.Prog{As: ASuspend}, "missing tag operand"},
+		{"Throw extra To", obj.Prog{As: AThrow, From: constAddr(ExitTagIndex), To: constAddr(0)}, "unexpected extra operand"},
+		{"TryTable extra To", obj.Prog{As: ATryTable, From: constAddr(ExitTagIndex), To: constAddr(0)}, "unexpected extra operand"},
+		{"Suspend extra To", obj.Prog{As: ASuspend, From: constAddr(YieldTagIndex), To: constAddr(0)}, "unexpected extra operand"},
+		{"Throw R0", obj.Prog{As: AThrow, From: regAddr(REG_R0)}, "tag operand must be a constant"},
+		{"Throw $2", obj.Prog{As: AThrow, From: constAddr(NumTags)}, "bad tag 2"},
+		{"Suspend $-1", obj.Prog{As: ASuspend, From: constAddr(-1)}, "bad tag -1"},
+		{"Throw $yield", obj.Prog{As: AThrow, From: constAddr(YieldTagIndex)}, "bad tag 0 (want 1)"},
+		{"TryTable $yield", obj.Prog{As: ATryTable, From: constAddr(YieldTagIndex)}, "bad tag 0 (want 1)"},
+		{"Suspend $exit", obj.Prog{As: ASuspend, From: constAddr(ExitTagIndex)}, "bad tag 1 (want 0)"},
+		{"ContBind", obj.Prog{As: AContBind}, "unsupported instruction"},
+		{"ResumeThrow", obj.Prog{As: AResumeThrow}, "unsupported instruction"},
+		{"ResumeThrowRef", obj.Prog{As: AResumeThrowRef}, "unsupported instruction"},
+		{"Switch", obj.Prog{As: ASwitch}, "unsupported instruction"},
+	}
+	for _, tt := range bad {
+		t.Run(tt.name, func(t *testing.T) {
+			diags := assembleOneDiag(t, &tt.prog)
+			if len(diags) != 1 || !strings.Contains(diags[0], tt.diag) {
+				t.Errorf("diagnostics = %q, want one containing %q", diags, tt.diag)
+			}
+		})
+	}
+
+	t.Run("TryTable with local SP", func(t *testing.T) {
+		ctxt := obj.Linknew(&Linkwasm)
+		var diags []string
+		ctxt.DiagFunc = func(format string, args ...any) {
+			diags = append(diags, fmt.Sprintf(format, args...))
+		}
+		s := &obj.LSym{Name: "test.f"} // Standard Go function with a local SP cache.
+		s.NewFuncInfo()
+		s.Func().Text = &obj.Prog{Ctxt: ctxt, As: ATryTable, From: constAddr(ExitTagIndex)}
+		assemble(ctxt, s, nil)
+		if len(diags) != 1 || !strings.Contains(diags[0], "TryTable cannot be used in a function with a local SP") {
+			t.Errorf("diagnostics = %q, want one about local SP", diags)
+		}
+	})
+
+	t.Run("without GOWASM=stackswitch", func(t *testing.T) {
+		setStackSwitch(t, false)
+		gated := []obj.Prog{
+			{As: ARefNull},
+			{As: AContNew},
+			{As: AResume},
+			{As: ASuspend, From: constAddr(YieldTagIndex)},
+			{As: AThrow, From: constAddr(ExitTagIndex)},
+			{As: ATryTable, From: constAddr(ExitTagIndex)},
+		}
+		for _, prog := range gated {
+			p := prog
+			diags := assembleOneDiag(t, &p)
+			if len(diags) != 1 || !strings.Contains(diags[0], "requires GOWASM=stackswitch") {
+				t.Errorf("%v: diagnostics = %q, want one about GOWASM=stackswitch", prog.As, diags)
+			}
+		}
+	})
+}
+
+// TestPreprocessTryTable checks that preprocess counts a TryTable as a
+// block when it resolves branch labels, requires it to be directly inside a
+// Block with no parameters or results, and rejects CALL inside it without
+// panicking.
+func TestPreprocessTryTable(t *testing.T) {
+	setStackSwitch(t, true)
+
+	// Block; TryTable; Br <Block>; End; End: the Br leaves the TryTable
+	// and the Block, so its depth is 1.
+	block := &obj.Prog{As: ABlock}
+	br := &obj.Prog{As: ABr, To: obj.Addr{Type: obj.TYPE_BRANCH, Val: block}}
+	_, diags := preprocessTest(t, block,
+		&obj.Prog{As: ATryTable, From: constAddr(ExitTagIndex)},
+		br,
+		&obj.Prog{As: AEnd},
+		&obj.Prog{As: AEnd})
+	if len(*diags) > 0 {
+		t.Fatalf("unexpected diagnostics: %v", *diags)
+	}
+	if br.To.Type != obj.TYPE_CONST || br.To.Offset != 1 {
+		t.Errorf("Br to the Block has depth %v, want 1", br.To.Offset)
+	}
+
+	bad := []struct {
+		name  string
+		progs []*obj.Prog
+		diag  string
+	}{
+		{
+			"top level",
+			[]*obj.Prog{
+				{As: ATryTable, From: constAddr(ExitTagIndex)},
+				{As: AEnd},
+			},
+			"TryTable must be directly inside a Block with no parameters or results",
+		},
+		{
+			"Loop parent",
+			[]*obj.Prog{
+				{As: ALoop},
+				{As: ATryTable, From: constAddr(ExitTagIndex)},
+				{As: AEnd},
+				{As: AEnd},
+			},
+			"TryTable must be directly inside a Block with no parameters or results",
+		},
+		{
+			"Block Loop parent",
+			[]*obj.Prog{
+				{As: ABlock},
+				{As: ALoop},
+				{As: ATryTable, From: constAddr(ExitTagIndex)},
+				{As: AEnd},
+				{As: AEnd},
+				{As: AEnd},
+			},
+			"TryTable must be directly inside a Block with no parameters or results",
+		},
+		{
+			"If parent",
+			[]*obj.Prog{
+				{As: AIf},
+				{As: ATryTable, From: constAddr(ExitTagIndex)},
+				{As: AEnd},
+				{As: AEnd},
+			},
+			"TryTable must be directly inside a Block with no parameters or results",
+		},
+		{
+			"nested TryTable",
+			[]*obj.Prog{
+				{As: ABlock},
+				{As: ATryTable, From: constAddr(ExitTagIndex)},
+				{As: ATryTable, From: constAddr(ExitTagIndex)},
+				{As: AEnd},
+				{As: AEnd},
+				{As: AEnd},
+			},
+			"TryTable must be directly inside a Block with no parameters or results",
+		},
+		{
+			"Block with result parent",
+			[]*obj.Prog{
+				{As: ABlock, From: constAddr(1)},
+				{As: ATryTable, From: constAddr(ExitTagIndex)},
+				{As: AEnd},
+				{As: AEnd},
+			},
+			"TryTable must be directly inside a Block with no parameters or results",
+		},
+		{
+			"CALL inside TryTable",
+			[]*obj.Prog{
+				{As: ABlock},
+				{As: ATryTable, From: constAddr(ExitTagIndex)},
+				{As: obj.ACALL, To: obj.Addr{Type: obj.TYPE_MEM, Name: obj.NAME_EXTERN, Sym: &obj.LSym{Name: "test.g"}}},
+				{As: AEnd},
+				{As: AEnd},
+			},
+			"CALL can only be used on toplevel",
+		},
+	}
+	for _, tt := range bad {
+		t.Run(tt.name, func(t *testing.T) {
+			_, diags := preprocessTest(t, tt.progs...)
+			if len(*diags) != 1 || !strings.Contains((*diags)[0], tt.diag) {
+				t.Errorf("diagnostics = %q, want one containing %q", *diags, tt.diag)
+			}
+		})
+	}
+}
+
+// preprocessTest runs preprocess on a zero-frame NOSPLIT function containing
+// progs followed by RET, and returns the link context and reported diagnostics.
+func preprocessTest(t *testing.T, progs ...*obj.Prog) (*obj.Link, *[]string) {
+	t.Helper()
+	ctxt := obj.Linknew(&Linkwasm)
+	diags := new([]string)
+	ctxt.DiagFunc = func(format string, args ...any) {
+		*diags = append(*diags, fmt.Sprintf(format, args...))
+	}
+	s := ctxt.Lookup("test.f")
+	s.NewFuncInfo()
+	s.Set(obj.AttrNoSplit, true)
+	text := &obj.Prog{Ctxt: ctxt, As: obj.ATEXT, From: obj.Addr{Type: obj.TYPE_MEM, Name: obj.NAME_EXTERN, Sym: s}, To: obj.Addr{Type: obj.TYPE_TEXTSIZE, Val: int32(0)}}
+	s.Func().Text = text
+	last := text
+	for _, p := range append(progs, &obj.Prog{As: obj.ARET}) {
+		p.Ctxt = ctxt
+		last.Link = p
+		last = p
+	}
+	preprocess(ctxt, s, ctxt.NewProg)
+	return ctxt, diags
+}
+
+// setStackSwitch sets the process-global buildcfg.GOWASM.StackSwitch for the
+// duration of t. Tests calling setStackSwitch must not use t.Parallel.
+func setStackSwitch(t *testing.T, on bool) {
+	old := buildcfg.GOWASM.StackSwitch
+	buildcfg.GOWASM.StackSwitch = on
+	t.Cleanup(func() { buildcfg.GOWASM.StackSwitch = old })
+}
+
+// TestPreprocessErrorNoPanic checks that after preprocess reports an error,
+// assemble does not panic: obj.Flushplist calls Assemble before it checks
+// ctxt.Errors.
+func TestPreprocessErrorNoPanic(t *testing.T) {
+	for _, tt := range []struct {
+		name        string
+		stackSwitch bool
+		progs       []*obj.Prog
+		diag        string
+	}{
+		{
+			"RESUMEPOINT in Block",
+			false,
+			[]*obj.Prog{
+				{As: ABlock},
+				{As: ARESUMEPOINT},
+				{As: AEnd},
+				{As: obj.ARET},
+			},
+			"RESUMEPOINT can only be used on toplevel",
+		},
+		{
+			"CALL ending unclosed Block",
+			false,
+			[]*obj.Prog{
+				{As: ABlock},
+				{As: obj.ACALL, To: obj.Addr{Type: obj.TYPE_MEM, Name: obj.NAME_EXTERN, Sym: &obj.LSym{Name: "test.g"}}},
+			},
+			"CALL can only be used on toplevel",
+		},
+	} {
+		t.Run(tt.name, func(t *testing.T) {
+			setStackSwitch(t, tt.stackSwitch)
+			ctxt := obj.Linknew(&Linkwasm)
+			var diags []string
+			ctxt.DiagFunc = func(format string, args ...any) {
+				diags = append(diags, fmt.Sprintf(format, args...))
+			}
+			s := ctxt.Lookup("test.f")
+			s.NewFuncInfo()
+			s.Set(obj.AttrNoSplit, true)
+			text := &obj.Prog{Ctxt: ctxt, As: obj.ATEXT, From: obj.Addr{Type: obj.TYPE_MEM, Name: obj.NAME_EXTERN, Sym: s}, To: obj.Addr{Type: obj.TYPE_TEXTSIZE, Val: int32(0)}}
+			s.Func().Text = text
+			last := text
+			for _, p := range tt.progs {
+				p.Ctxt = ctxt
+				last.Link = p
+				last = p
+			}
+			preprocess(ctxt, s, ctxt.NewProg)
+			assemble(ctxt, s, nil)
+			if !slices.ContainsFunc(diags, func(d string) bool { return strings.Contains(d, tt.diag) }) {
+				t.Errorf("diagnostics = %q, want one containing %q", diags, tt.diag)
+			}
+		})
+	}
+}
+
 // TestAssembleSuspendUpdatesLocalSP verifies that ASuspend refreshes the
 // function's cached local SP from global SP when hasLocalSP is true.
 func TestAssembleSuspendUpdatesLocalSP(t *testing.T) {
+	setStackSwitch(t, true)
 	ctxt := obj.Linknew(&Linkwasm)
 	ctxt.DiagFunc = t.Errorf
 	s := &obj.LSym{Name: "test.f"} // Standard Go function with a local SP cache.
 	s.NewFuncInfo()
-	s.Func().Text = &obj.Prog{Ctxt: ctxt, As: ASuspend}
+	s.Func().Text = &obj.Prog{Ctxt: ctxt, As: ASuspend, From: constAddr(YieldTagIndex)}
 	assemble(ctxt, s, nil)

 	want := []byte{
@@ -138,3 +435,21 @@ func assembleOne(t *testing.T, p *obj.Prog) []byte {
 	}
 	return s.P[1 : len(s.P)-1]
 }
+
+// assembleOneDiag assembles a single instruction p and returns the diagnostics
+// reported by assemble.
+func assembleOneDiag(t *testing.T, p *obj.Prog) []string {
+	t.Helper()
+	ctxt, s := newTestFunc()
+	var diags []string
+	ctxt.DiagFunc = func(format string, args ...any) {
+		diags = append(diags, fmt.Sprintf(format, args...))
+	}
+	p.Ctxt = ctxt
+	s.Func().Text = p
+	assemble(ctxt, s, nil)
+	if len(s.P) < 2 || s.P[0] != 0x00 || s.P[len(s.P)-1] != 0x0B {
+		t.Fatalf("unexpected function framing: % x", s.P)
+	}
+	return diags
+}
diff --git a/src/cmd/link/internal/wasm/asm.go b/src/cmd/link/internal/wasm/asm.go
index 15a1e66d8a..0a2fca563e 100644
--- a/src/cmd/link/internal/wasm/asm.go
+++ b/src/cmd/link/internal/wasm/asm.go
@@ -491,31 +491,31 @@ func lookupType(sig *wasmFuncType, types *[]*wasmFuncType) uint32 {
 const contTableInitialSize = 1024

 // newTypes returns the initial function type table, seeded with the Go
-// function signature (PC_B i32) -> (i32) at index 0.
+// function signature (PC_B i32) -> (i32) at wasm.GoFuncTypeIndex (0).
 func newTypes() []*wasmFuncType {
 	return []*wasmFuncType{
 		// For normal Go functions, the single parameter is PC_B,
 		// the return value is
 		// 0 if the function returned normally or
 		// 1 if the stack needs to be unwound.
-		{Params: []byte{I32}, Results: []byte{I32}},
+		wasm.GoFuncTypeIndex: {Params: []byte{I32}, Results: []byte{I32}},
 	}
 }

-// initStackSwitchingTypes registers the fixed-index WasmFX continuation types
-// at the top of types so their indices remain constant across all Go programs.
+// initStackSwitchingTypes reserves the fixed-index stack-switching types at
+// the start of the type section (after wasm.GoFuncTypeIndex) so their indices
+// remain constant across all Go programs; subsequent lookupType calls
+// deduplicate against them.
 func initStackSwitchingTypes(types *[]*wasmFuncType) {
-	// Force () -> () function type to be at index 1 (wasm.EmptyFuncTypeIndex).
-	emptyFuncType := lookupType(&wasmFuncType{Params: []byte{}, Results: []byte{}}, types)
-	if emptyFuncType != wasm.EmptyFuncTypeIndex {
-		panic("wasm: EmptyFuncTypeIndex is not at the expected index")
+	if len(*types) != wasm.EmptyFuncTypeIndex {
+		panic(fmt.Sprintf("wasm: initStackSwitchingTypes called with %d types, want %d (must be called immediately after newTypes)", len(*types), wasm.EmptyFuncTypeIndex))
 	}
-
-	// Continuation type (cont $emptyFuncType) at index 2 (wasm.ContinuationTypeIndex).
-	if uint32(len(*types)) != wasm.ContinuationTypeIndex {
-		panic("wasm: ContinuationTypeIndex is not at the expected index")
-	}
-	*types = append(*types, &wasmFuncType{isCont: true, contOf: emptyFuncType})
+	*types = append(*types,
+		// wasm.EmptyFuncTypeIndex (1): () -> (), used for tags and continuations.
+		&wasmFuncType{Params: []byte{}, Results: []byte{}},
+		// wasm.ContinuationTypeIndex (2): (cont $EmptyFuncTypeIndex).
+		&wasmFuncType{isCont: true, contOf: wasm.EmptyFuncTypeIndex},
+	)
 }

 func writeSecHeader(ctxt *ld.Link, id uint8) int64 {
@@ -673,21 +673,29 @@ func writeMemorySec(ctxt *ld.Link, ldr *loader.Loader) {
 	writeSecSize(ctxt, sizeOffset)
 }

-// writeTagSec writes the Wasm Tag section (ID 13) declaring effect tags
-// used to implement goroutines with stack-switching instructions (suspend/resume).
+// writeTagSec writes the Wasm tag section (ID 13) declaring the effect and
+// exception tags used under GOWASM=stackswitch:
+//   - tag 0 ($yield, wasm.YieldTagIndex): used by Suspend and Resume to switch continuations.
+//   - tag 1 ($exit, wasm.ExitTagIndex): thrown to unwind to a TryTable and return to the host.
 func writeTagSec(ctxt *ld.Link) {
 	if !buildcfg.GOWASM.StackSwitch {
 		return
 	}
 	sizeOffset := writeSecHeader(ctxt, sectionTag)
-
-	writeUleb128(ctxt.Out, 1) // number of tags
-	ctxt.Out.WriteByte(0x00)  // A tag we will call $yield, index 0
-	ctxt.Out.WriteByte(0x01)  // the tag's function type (forced at index 1 by initStackSwitchingTypes)
-
+	writeTags(ctxt.Out)
 	writeSecSize(ctxt, sizeOffset)
 }

+// writeTags writes the contents of the tag section. Every tag has the type
+// () -> (), which initStackSwitchingTypes puts at wasm.EmptyFuncTypeIndex.
+func writeTags(w io.ByteWriter) {
+	writeUleb128(w, wasm.NumTags) // number of tags
+	for range wasm.NumTags {
+		w.WriteByte(0x00)                        // attribute 0: exception
+		writeUleb128(w, wasm.EmptyFuncTypeIndex) // type () -> ()
+	}
+}
+
 // writeGlobalSec writes the section that declares global variables.
 func writeGlobalSec(ctxt *ld.Link) {
 	sizeOffset := writeSecHeader(ctxt, sectionGlobal)
diff --git a/src/cmd/link/internal/wasm/asm_test.go b/src/cmd/link/internal/wasm/asm_test.go
index aa95791917..9f5c137212 100644
--- a/src/cmd/link/internal/wasm/asm_test.go
+++ b/src/cmd/link/internal/wasm/asm_test.go
@@ -68,3 +68,18 @@ func TestWriteValTypesContRef(t *testing.T) {
 		t.Errorf("got % x, want % x", w.Bytes(), want)
 	}
 }
+
+// TestTags checks the contents of the tag section under GOWASM=stackswitch:
+// $yield and $exit, both tags with attribute 0 and type () -> ().
+func TestTags(t *testing.T) {
+	var buf bytes.Buffer
+	writeTags(&buf)
+	want := []byte{
+		0x02,
+		0x00, 0x01, // tag 0 ($yield): exception attribute, type () -> ()
+		0x00, 0x01, // tag 1 ($exit): exception attribute, type () -> ()
+	}
+	if got := buf.Bytes(); !bytes.Equal(got, want) {
+		t.Errorf("tag section = % x, want % x", got, want)
+	}
+}