]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/walk/switch.go
cmd/compile: improve interface type switches
[gostls13.git] / src / cmd / compile / internal / walk / switch.go
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package walk
6
7 import (
8         "fmt"
9         "go/constant"
10         "go/token"
11         "math/bits"
12         "sort"
13
14         "cmd/compile/internal/base"
15         "cmd/compile/internal/ir"
16         "cmd/compile/internal/objw"
17         "cmd/compile/internal/reflectdata"
18         "cmd/compile/internal/ssagen"
19         "cmd/compile/internal/typecheck"
20         "cmd/compile/internal/types"
21         "cmd/internal/obj"
22         "cmd/internal/src"
23 )
24
25 // walkSwitch walks a switch statement.
26 func walkSwitch(sw *ir.SwitchStmt) {
27         // Guard against double walk, see #25776.
28         if sw.Walked() {
29                 return // Was fatal, but eliminating every possible source of double-walking is hard
30         }
31         sw.SetWalked(true)
32
33         if sw.Tag != nil && sw.Tag.Op() == ir.OTYPESW {
34                 walkSwitchType(sw)
35         } else {
36                 walkSwitchExpr(sw)
37         }
38 }
39
40 // walkSwitchExpr generates an AST implementing sw.  sw is an
41 // expression switch.
42 func walkSwitchExpr(sw *ir.SwitchStmt) {
43         lno := ir.SetPos(sw)
44
45         cond := sw.Tag
46         sw.Tag = nil
47
48         // convert switch {...} to switch true {...}
49         if cond == nil {
50                 cond = ir.NewBool(base.Pos, true)
51                 cond = typecheck.Expr(cond)
52                 cond = typecheck.DefaultLit(cond, nil)
53         }
54
55         // Given "switch string(byteslice)",
56         // with all cases being side-effect free,
57         // use a zero-cost alias of the byte slice.
58         // Do this before calling walkExpr on cond,
59         // because walkExpr will lower the string
60         // conversion into a runtime call.
61         // See issue 24937 for more discussion.
62         if cond.Op() == ir.OBYTES2STR && allCaseExprsAreSideEffectFree(sw) {
63                 cond := cond.(*ir.ConvExpr)
64                 cond.SetOp(ir.OBYTES2STRTMP)
65         }
66
67         cond = walkExpr(cond, sw.PtrInit())
68         if cond.Op() != ir.OLITERAL && cond.Op() != ir.ONIL {
69                 cond = copyExpr(cond, cond.Type(), &sw.Compiled)
70         }
71
72         base.Pos = lno
73
74         s := exprSwitch{
75                 pos:      lno,
76                 exprname: cond,
77         }
78
79         var defaultGoto ir.Node
80         var body ir.Nodes
81         for _, ncase := range sw.Cases {
82                 label := typecheck.AutoLabel(".s")
83                 jmp := ir.NewBranchStmt(ncase.Pos(), ir.OGOTO, label)
84
85                 // Process case dispatch.
86                 if len(ncase.List) == 0 {
87                         if defaultGoto != nil {
88                                 base.Fatalf("duplicate default case not detected during typechecking")
89                         }
90                         defaultGoto = jmp
91                 }
92
93                 for i, n1 := range ncase.List {
94                         var rtype ir.Node
95                         if i < len(ncase.RTypes) {
96                                 rtype = ncase.RTypes[i]
97                         }
98                         s.Add(ncase.Pos(), n1, rtype, jmp)
99                 }
100
101                 // Process body.
102                 body.Append(ir.NewLabelStmt(ncase.Pos(), label))
103                 body.Append(ncase.Body...)
104                 if fall, pos := endsInFallthrough(ncase.Body); !fall {
105                         br := ir.NewBranchStmt(base.Pos, ir.OBREAK, nil)
106                         br.SetPos(pos)
107                         body.Append(br)
108                 }
109         }
110         sw.Cases = nil
111
112         if defaultGoto == nil {
113                 br := ir.NewBranchStmt(base.Pos, ir.OBREAK, nil)
114                 br.SetPos(br.Pos().WithNotStmt())
115                 defaultGoto = br
116         }
117
118         s.Emit(&sw.Compiled)
119         sw.Compiled.Append(defaultGoto)
120         sw.Compiled.Append(body.Take()...)
121         walkStmtList(sw.Compiled)
122 }
123
124 // An exprSwitch walks an expression switch.
125 type exprSwitch struct {
126         pos      src.XPos
127         exprname ir.Node // value being switched on
128
129         done    ir.Nodes
130         clauses []exprClause
131 }
132
133 type exprClause struct {
134         pos    src.XPos
135         lo, hi ir.Node
136         rtype  ir.Node // *runtime._type for OEQ node
137         jmp    ir.Node
138 }
139
140 func (s *exprSwitch) Add(pos src.XPos, expr, rtype, jmp ir.Node) {
141         c := exprClause{pos: pos, lo: expr, hi: expr, rtype: rtype, jmp: jmp}
142         if types.IsOrdered[s.exprname.Type().Kind()] && expr.Op() == ir.OLITERAL {
143                 s.clauses = append(s.clauses, c)
144                 return
145         }
146
147         s.flush()
148         s.clauses = append(s.clauses, c)
149         s.flush()
150 }
151
152 func (s *exprSwitch) Emit(out *ir.Nodes) {
153         s.flush()
154         out.Append(s.done.Take()...)
155 }
156
157 func (s *exprSwitch) flush() {
158         cc := s.clauses
159         s.clauses = nil
160         if len(cc) == 0 {
161                 return
162         }
163
164         // Caution: If len(cc) == 1, then cc[0] might not an OLITERAL.
165         // The code below is structured to implicitly handle this case
166         // (e.g., sort.Slice doesn't need to invoke the less function
167         // when there's only a single slice element).
168
169         if s.exprname.Type().IsString() && len(cc) >= 2 {
170                 // Sort strings by length and then by value. It is
171                 // much cheaper to compare lengths than values, and
172                 // all we need here is consistency. We respect this
173                 // sorting below.
174                 sort.Slice(cc, func(i, j int) bool {
175                         si := ir.StringVal(cc[i].lo)
176                         sj := ir.StringVal(cc[j].lo)
177                         if len(si) != len(sj) {
178                                 return len(si) < len(sj)
179                         }
180                         return si < sj
181                 })
182
183                 // runLen returns the string length associated with a
184                 // particular run of exprClauses.
185                 runLen := func(run []exprClause) int64 { return int64(len(ir.StringVal(run[0].lo))) }
186
187                 // Collapse runs of consecutive strings with the same length.
188                 var runs [][]exprClause
189                 start := 0
190                 for i := 1; i < len(cc); i++ {
191                         if runLen(cc[start:]) != runLen(cc[i:]) {
192                                 runs = append(runs, cc[start:i])
193                                 start = i
194                         }
195                 }
196                 runs = append(runs, cc[start:])
197
198                 // We have strings of more than one length. Generate an
199                 // outer switch which switches on the length of the string
200                 // and an inner switch in each case which resolves all the
201                 // strings of the same length. The code looks something like this:
202
203                 // goto outerLabel
204                 // len5:
205                 //   ... search among length 5 strings ...
206                 //   goto endLabel
207                 // len8:
208                 //   ... search among length 8 strings ...
209                 //   goto endLabel
210                 // ... other lengths ...
211                 // outerLabel:
212                 // switch len(s) {
213                 //   case 5: goto len5
214                 //   case 8: goto len8
215                 //   ... other lengths ...
216                 // }
217                 // endLabel:
218
219                 outerLabel := typecheck.AutoLabel(".s")
220                 endLabel := typecheck.AutoLabel(".s")
221
222                 // Jump around all the individual switches for each length.
223                 s.done.Append(ir.NewBranchStmt(s.pos, ir.OGOTO, outerLabel))
224
225                 var outer exprSwitch
226                 outer.exprname = ir.NewUnaryExpr(s.pos, ir.OLEN, s.exprname)
227                 outer.exprname.SetType(types.Types[types.TINT])
228
229                 for _, run := range runs {
230                         // Target label to jump to when we match this length.
231                         label := typecheck.AutoLabel(".s")
232
233                         // Search within this run of same-length strings.
234                         pos := run[0].pos
235                         s.done.Append(ir.NewLabelStmt(pos, label))
236                         stringSearch(s.exprname, run, &s.done)
237                         s.done.Append(ir.NewBranchStmt(pos, ir.OGOTO, endLabel))
238
239                         // Add length case to outer switch.
240                         cas := ir.NewInt(pos, runLen(run))
241                         jmp := ir.NewBranchStmt(pos, ir.OGOTO, label)
242                         outer.Add(pos, cas, nil, jmp)
243                 }
244                 s.done.Append(ir.NewLabelStmt(s.pos, outerLabel))
245                 outer.Emit(&s.done)
246                 s.done.Append(ir.NewLabelStmt(s.pos, endLabel))
247                 return
248         }
249
250         sort.Slice(cc, func(i, j int) bool {
251                 return constant.Compare(cc[i].lo.Val(), token.LSS, cc[j].lo.Val())
252         })
253
254         // Merge consecutive integer cases.
255         if s.exprname.Type().IsInteger() {
256                 consecutive := func(last, next constant.Value) bool {
257                         delta := constant.BinaryOp(next, token.SUB, last)
258                         return constant.Compare(delta, token.EQL, constant.MakeInt64(1))
259                 }
260
261                 merged := cc[:1]
262                 for _, c := range cc[1:] {
263                         last := &merged[len(merged)-1]
264                         if last.jmp == c.jmp && consecutive(last.hi.Val(), c.lo.Val()) {
265                                 last.hi = c.lo
266                         } else {
267                                 merged = append(merged, c)
268                         }
269                 }
270                 cc = merged
271         }
272
273         s.search(cc, &s.done)
274 }
275
276 func (s *exprSwitch) search(cc []exprClause, out *ir.Nodes) {
277         if s.tryJumpTable(cc, out) {
278                 return
279         }
280         binarySearch(len(cc), out,
281                 func(i int) ir.Node {
282                         return ir.NewBinaryExpr(base.Pos, ir.OLE, s.exprname, cc[i-1].hi)
283                 },
284                 func(i int, nif *ir.IfStmt) {
285                         c := &cc[i]
286                         nif.Cond = c.test(s.exprname)
287                         nif.Body = []ir.Node{c.jmp}
288                 },
289         )
290 }
291
292 // Try to implement the clauses with a jump table. Returns true if successful.
293 func (s *exprSwitch) tryJumpTable(cc []exprClause, out *ir.Nodes) bool {
294         const minCases = 8   // have at least minCases cases in the switch
295         const minDensity = 4 // use at least 1 out of every minDensity entries
296
297         if base.Flag.N != 0 || !ssagen.Arch.LinkArch.CanJumpTable || base.Ctxt.Retpoline {
298                 return false
299         }
300         if len(cc) < minCases {
301                 return false // not enough cases for it to be worth it
302         }
303         if cc[0].lo.Val().Kind() != constant.Int {
304                 return false // e.g. float
305         }
306         if s.exprname.Type().Size() > int64(types.PtrSize) {
307                 return false // 64-bit switches on 32-bit archs
308         }
309         min := cc[0].lo.Val()
310         max := cc[len(cc)-1].hi.Val()
311         width := constant.BinaryOp(constant.BinaryOp(max, token.SUB, min), token.ADD, constant.MakeInt64(1))
312         limit := constant.MakeInt64(int64(len(cc)) * minDensity)
313         if constant.Compare(width, token.GTR, limit) {
314                 // We disable jump tables if we use less than a minimum fraction of the entries.
315                 // i.e. for switch x {case 0: case 1000: case 2000:} we don't want to use a jump table.
316                 return false
317         }
318         jt := ir.NewJumpTableStmt(base.Pos, s.exprname)
319         for _, c := range cc {
320                 jmp := c.jmp.(*ir.BranchStmt)
321                 if jmp.Op() != ir.OGOTO || jmp.Label == nil {
322                         panic("bad switch case body")
323                 }
324                 for i := c.lo.Val(); constant.Compare(i, token.LEQ, c.hi.Val()); i = constant.BinaryOp(i, token.ADD, constant.MakeInt64(1)) {
325                         jt.Cases = append(jt.Cases, i)
326                         jt.Targets = append(jt.Targets, jmp.Label)
327                 }
328         }
329         out.Append(jt)
330         return true
331 }
332
333 func (c *exprClause) test(exprname ir.Node) ir.Node {
334         // Integer range.
335         if c.hi != c.lo {
336                 low := ir.NewBinaryExpr(c.pos, ir.OGE, exprname, c.lo)
337                 high := ir.NewBinaryExpr(c.pos, ir.OLE, exprname, c.hi)
338                 return ir.NewLogicalExpr(c.pos, ir.OANDAND, low, high)
339         }
340
341         // Optimize "switch true { ...}" and "switch false { ... }".
342         if ir.IsConst(exprname, constant.Bool) && !c.lo.Type().IsInterface() {
343                 if ir.BoolVal(exprname) {
344                         return c.lo
345                 } else {
346                         return ir.NewUnaryExpr(c.pos, ir.ONOT, c.lo)
347                 }
348         }
349
350         n := ir.NewBinaryExpr(c.pos, ir.OEQ, exprname, c.lo)
351         n.RType = c.rtype
352         return n
353 }
354
355 func allCaseExprsAreSideEffectFree(sw *ir.SwitchStmt) bool {
356         // In theory, we could be more aggressive, allowing any
357         // side-effect-free expressions in cases, but it's a bit
358         // tricky because some of that information is unavailable due
359         // to the introduction of temporaries during order.
360         // Restricting to constants is simple and probably powerful
361         // enough.
362
363         for _, ncase := range sw.Cases {
364                 for _, v := range ncase.List {
365                         if v.Op() != ir.OLITERAL {
366                                 return false
367                         }
368                 }
369         }
370         return true
371 }
372
373 // endsInFallthrough reports whether stmts ends with a "fallthrough" statement.
374 func endsInFallthrough(stmts []ir.Node) (bool, src.XPos) {
375         if len(stmts) == 0 {
376                 return false, src.NoXPos
377         }
378         i := len(stmts) - 1
379         return stmts[i].Op() == ir.OFALL, stmts[i].Pos()
380 }
381
382 // walkSwitchType generates an AST that implements sw, where sw is a
383 // type switch.
384 func walkSwitchType(sw *ir.SwitchStmt) {
385         var s typeSwitch
386         s.srcName = sw.Tag.(*ir.TypeSwitchGuard).X
387         s.srcName = walkExpr(s.srcName, sw.PtrInit())
388         s.srcName = copyExpr(s.srcName, s.srcName.Type(), &sw.Compiled)
389         s.okName = typecheck.TempAt(base.Pos, ir.CurFunc, types.Types[types.TBOOL])
390         s.itabName = typecheck.TempAt(base.Pos, ir.CurFunc, types.Types[types.TUINT8].PtrTo())
391
392         // Get interface descriptor word.
393         // For empty interfaces this will be the type.
394         // For non-empty interfaces this will be the itab.
395         srcItab := ir.NewUnaryExpr(base.Pos, ir.OITAB, s.srcName)
396         srcData := ir.NewUnaryExpr(base.Pos, ir.OIDATA, s.srcName)
397         srcData.SetType(types.Types[types.TUINT8].PtrTo())
398         srcData.SetTypecheck(1)
399
400         // For empty interfaces, do:
401         //     if e._type == nil {
402         //         do nil case if it exists, otherwise default
403         //     }
404         //     h := e._type.hash
405         // Use a similar strategy for non-empty interfaces.
406         ifNil := ir.NewIfStmt(base.Pos, nil, nil, nil)
407         ifNil.Cond = ir.NewBinaryExpr(base.Pos, ir.OEQ, srcItab, typecheck.NodNil())
408         base.Pos = base.Pos.WithNotStmt() // disable statement marks after the first check.
409         ifNil.Cond = typecheck.Expr(ifNil.Cond)
410         ifNil.Cond = typecheck.DefaultLit(ifNil.Cond, nil)
411         // ifNil.Nbody assigned later.
412         sw.Compiled.Append(ifNil)
413
414         // Load hash from type or itab.
415         dotHash := typeHashFieldOf(base.Pos, srcItab)
416         s.hashName = copyExpr(dotHash, dotHash.Type(), &sw.Compiled)
417
418         // Make a label for each case body.
419         labels := make([]*types.Sym, len(sw.Cases))
420         for i := range sw.Cases {
421                 labels[i] = typecheck.AutoLabel(".s")
422         }
423
424         // "jump" to execute if no case matches.
425         br := ir.NewBranchStmt(base.Pos, ir.OBREAK, nil)
426
427         // Assemble a list of all the types we're looking for.
428         // This pass flattens the case lists, as well as handles
429         // some unusual cases, like default and nil cases.
430         type oneCase struct {
431                 pos src.XPos
432                 jmp ir.Node // jump to body of selected case
433
434                 // The case we're matching. Normally the type we're looking for
435                 // is typ.Type(), but when typ is ODYNAMICTYPE the actual type
436                 // we're looking for is not a compile-time constant (typ.Type()
437                 // will be its shape).
438                 typ ir.Node
439         }
440         var cases []oneCase
441         var defaultGoto, nilGoto ir.Node
442         for i, ncase := range sw.Cases {
443                 jmp := ir.NewBranchStmt(ncase.Pos(), ir.OGOTO, labels[i])
444                 if len(ncase.List) == 0 { // default:
445                         if defaultGoto != nil {
446                                 base.Fatalf("duplicate default case not detected during typechecking")
447                         }
448                         defaultGoto = jmp
449                 }
450                 for _, n1 := range ncase.List {
451                         if ir.IsNil(n1) { // case nil:
452                                 if nilGoto != nil {
453                                         base.Fatalf("duplicate nil case not detected during typechecking")
454                                 }
455                                 nilGoto = jmp
456                                 continue
457                         }
458                         if n1.Op() == ir.ODYNAMICTYPE {
459                                 // Convert dynamic to static, if the dynamic is actually static.
460                                 // TODO: why isn't this OTYPE to begin with?
461                                 dt := n1.(*ir.DynamicType)
462                                 if dt.RType != nil && dt.RType.Op() == ir.OADDR {
463                                         addr := dt.RType.(*ir.AddrExpr)
464                                         if addr.X.Op() == ir.OLINKSYMOFFSET {
465                                                 n1 = ir.TypeNode(n1.Type())
466                                         }
467                                 }
468                                 if dt.ITab != nil && dt.ITab.Op() == ir.OADDR {
469                                         addr := dt.ITab.(*ir.AddrExpr)
470                                         if addr.X.Op() == ir.OLINKSYMOFFSET {
471                                                 n1 = ir.TypeNode(n1.Type())
472                                         }
473                                 }
474                         }
475                         cases = append(cases, oneCase{
476                                 pos: ncase.Pos(),
477                                 typ: n1,
478                                 jmp: jmp,
479                         })
480                 }
481         }
482         if defaultGoto == nil {
483                 defaultGoto = br
484         }
485         if nilGoto == nil {
486                 nilGoto = defaultGoto
487         }
488         ifNil.Body = []ir.Node{nilGoto}
489
490         // Now go through the list of cases, processing groups as we find them.
491         var concreteCases []oneCase
492         var interfaceCases []oneCase
493         flush := func() {
494                 // Process all the concrete types first. Because we handle shadowing
495                 // below, it is correct to do all the concrete types before all of
496                 // the interface types.
497                 // The concrete cases can all be handled without a runtime call.
498                 if len(concreteCases) > 0 {
499                         var clauses []typeClause
500                         for _, c := range concreteCases {
501                                 as := ir.NewAssignListStmt(c.pos, ir.OAS2,
502                                         []ir.Node{ir.BlankNode, s.okName},                               // _, ok =
503                                         []ir.Node{ir.NewTypeAssertExpr(c.pos, s.srcName, c.typ.Type())}) // iface.(type)
504                                 nif := ir.NewIfStmt(c.pos, s.okName, []ir.Node{c.jmp}, nil)
505                                 clauses = append(clauses, typeClause{
506                                         hash: types.TypeHash(c.typ.Type()),
507                                         body: []ir.Node{typecheck.Stmt(as), typecheck.Stmt(nif)},
508                                 })
509                         }
510                         s.flush(clauses, &sw.Compiled)
511                         concreteCases = concreteCases[:0]
512                 }
513
514                 // The "any" case, if it exists, must be the last interface case, because
515                 // it would shadow all subsequent cases. Strip it off here so the runtime
516                 // call only needs to handle non-empty interfaces.
517                 var anyGoto ir.Node
518                 if len(interfaceCases) > 0 && interfaceCases[len(interfaceCases)-1].typ.Type().IsEmptyInterface() {
519                         anyGoto = interfaceCases[len(interfaceCases)-1].jmp
520                         interfaceCases = interfaceCases[:len(interfaceCases)-1]
521                 }
522
523                 // Next, process all the interface types with a single call to the runtime.
524                 if len(interfaceCases) > 0 {
525
526                         // Build an internal/abi.InterfaceSwitch descriptor to pass to the runtime.
527                         lsym := types.LocalPkg.Lookup(fmt.Sprintf(".interfaceSwitch.%d", interfaceSwitchGen)).LinksymABI(obj.ABI0)
528                         interfaceSwitchGen++
529                         off := 0
530                         off = objw.Uintptr(lsym, off, uint64(len(interfaceCases)))
531                         for _, c := range interfaceCases {
532                                 off = objw.SymPtr(lsym, off, reflectdata.TypeSym(c.typ.Type()).Linksym(), 0)
533                         }
534                         // Note: it has pointers, just not ones the GC cares about.
535                         objw.Global(lsym, int32(off), obj.LOCAL|obj.NOPTR)
536
537                         // Call runtime to do switch
538                         // case, itab = runtime.interfaceSwitch(&descriptor, typeof(arg))
539                         var typeArg ir.Node
540                         if s.srcName.Type().IsEmptyInterface() {
541                                 typeArg = ir.NewConvExpr(base.Pos, ir.OCONVNOP, types.Types[types.TUINT8].PtrTo(), srcItab)
542                         } else {
543                                 typeArg = itabType(srcItab)
544                         }
545                         caseVar := typecheck.TempAt(base.Pos, ir.CurFunc, types.Types[types.TINT])
546                         isw := ir.NewInterfaceSwitchStmt(base.Pos, caseVar, s.itabName, typeArg, lsym)
547                         sw.Compiled.Append(isw)
548
549                         // Switch on the result of the call.
550                         var newCases []*ir.CaseClause
551                         for i, c := range interfaceCases {
552                                 newCases = append(newCases, &ir.CaseClause{
553                                         List: []ir.Node{ir.NewInt(base.Pos, int64(i))},
554                                         Body: []ir.Node{c.jmp},
555                                 })
556                         }
557                         // TODO: add len(newCases) case, mark switch as bounded
558                         sw2 := ir.NewSwitchStmt(base.Pos, caseVar, newCases)
559                         sw.Compiled.Append(typecheck.Stmt(sw2))
560                         interfaceCases = interfaceCases[:0]
561                 }
562
563                 if anyGoto != nil {
564                         // We've already handled the nil case, so everything
565                         // that reaches here matches the "any" case.
566                         sw.Compiled.Append(anyGoto)
567                 }
568         }
569 caseLoop:
570         for _, c := range cases {
571                 if c.typ.Op() == ir.ODYNAMICTYPE {
572                         flush() // process all previous cases
573                         dt := c.typ.(*ir.DynamicType)
574                         dot := ir.NewDynamicTypeAssertExpr(c.pos, ir.ODYNAMICDOTTYPE, s.srcName, dt.RType)
575                         dot.ITab = dt.ITab
576                         dot.SetType(c.typ.Type())
577                         dot.SetTypecheck(1)
578
579                         as := ir.NewAssignListStmt(c.pos, ir.OAS2, nil, nil)
580                         as.Lhs = []ir.Node{ir.BlankNode, s.okName} // _, ok =
581                         as.Rhs = []ir.Node{dot}
582                         typecheck.Stmt(as)
583
584                         nif := ir.NewIfStmt(c.pos, s.okName, []ir.Node{c.jmp}, nil)
585                         sw.Compiled.Append(as, nif)
586                         continue
587                 }
588
589                 // Check for shadowing (a case that will never fire because
590                 // a previous case would have always fired first). This check
591                 // allows us to reorder concrete and interface cases.
592                 // (TODO: these should be vet failures, maybe?)
593                 for _, ic := range interfaceCases {
594                         // An interface type case will shadow all
595                         // subsequent types that implement that interface.
596                         if typecheck.Implements(c.typ.Type(), ic.typ.Type()) {
597                                 continue caseLoop
598                         }
599                         // Note that we don't need to worry about:
600                         // 1. Two concrete types shadowing each other. That's
601                         //    disallowed by the spec.
602                         // 2. A concrete type shadowing an interface type.
603                         //    That can never happen, as interface types can
604                         //    be satisfied by an infinite set of concrete types.
605                         // The correctness of this step also depends on handling
606                         // the dynamic type cases separately, as we do above.
607                 }
608
609                 if c.typ.Type().IsInterface() {
610                         interfaceCases = append(interfaceCases, c)
611                 } else {
612                         concreteCases = append(concreteCases, c)
613                 }
614         }
615         flush()
616
617         sw.Compiled.Append(defaultGoto) // if none of the cases matched
618
619         // Now generate all the case bodies
620         for i, ncase := range sw.Cases {
621                 sw.Compiled.Append(ir.NewLabelStmt(ncase.Pos(), labels[i]))
622                 if caseVar := ncase.Var; caseVar != nil {
623                         val := s.srcName
624                         if len(ncase.List) == 1 {
625                                 // single type. We have to downcast the input value to the target type.
626                                 if ncase.List[0].Op() == ir.OTYPE { // single compile-time known type
627                                         t := ncase.List[0].Type()
628                                         if t.IsInterface() {
629                                                 // This case is an interface. Build case value from input interface.
630                                                 // The data word will always be the same, but the itab/type changes.
631                                                 if t.IsEmptyInterface() {
632                                                         var typ ir.Node
633                                                         if s.srcName.Type().IsEmptyInterface() {
634                                                                 // E->E, nothing to do, type is already correct.
635                                                                 typ = srcItab
636                                                         } else {
637                                                                 // I->E, load type out of itab
638                                                                 typ = itabType(srcItab)
639                                                                 typ.SetPos(ncase.Pos())
640                                                         }
641                                                         val = ir.NewBinaryExpr(ncase.Pos(), ir.OMAKEFACE, typ, srcData)
642                                                 } else {
643                                                         // The itab we need was returned by a runtime.interfaceSwitch call.
644                                                         val = ir.NewBinaryExpr(ncase.Pos(), ir.OMAKEFACE, s.itabName, srcData)
645                                                 }
646                                         } else {
647                                                 // This case is a concrete type, just read its value out of the interface.
648                                                 val = ifaceData(ncase.Pos(), s.srcName, t)
649                                         }
650                                 } else if ncase.List[0].Op() == ir.ODYNAMICTYPE { // single runtime known type
651                                         dt := ncase.List[0].(*ir.DynamicType)
652                                         x := ir.NewDynamicTypeAssertExpr(ncase.Pos(), ir.ODYNAMICDOTTYPE, val, dt.RType)
653                                         x.ITab = dt.ITab
654                                         val = x
655                                 } else if ir.IsNil(ncase.List[0]) {
656                                 } else {
657                                         base.Fatalf("unhandled type switch case %v", ncase.List[0])
658                                 }
659                                 val.SetType(caseVar.Type())
660                                 val.SetTypecheck(1)
661                         }
662                         l := []ir.Node{
663                                 ir.NewDecl(ncase.Pos(), ir.ODCL, caseVar),
664                                 ir.NewAssignStmt(ncase.Pos(), caseVar, val),
665                         }
666                         typecheck.Stmts(l)
667                         sw.Compiled.Append(l...)
668                 }
669                 sw.Compiled.Append(ncase.Body...)
670                 sw.Compiled.Append(br)
671         }
672
673         walkStmtList(sw.Compiled)
674         sw.Tag = nil
675         sw.Cases = nil
676 }
677
678 var interfaceSwitchGen int
679
680 // typeHashFieldOf returns an expression to select the type hash field
681 // from an interface's descriptor word (whether a *runtime._type or
682 // *runtime.itab pointer).
683 func typeHashFieldOf(pos src.XPos, itab *ir.UnaryExpr) *ir.SelectorExpr {
684         if itab.Op() != ir.OITAB {
685                 base.Fatalf("expected OITAB, got %v", itab.Op())
686         }
687         var hashField *types.Field
688         if itab.X.Type().IsEmptyInterface() {
689                 // runtime._type's hash field
690                 if rtypeHashField == nil {
691                         rtypeHashField = runtimeField("hash", int64(2*types.PtrSize), types.Types[types.TUINT32])
692                 }
693                 hashField = rtypeHashField
694         } else {
695                 // runtime.itab's hash field
696                 if itabHashField == nil {
697                         itabHashField = runtimeField("hash", int64(2*types.PtrSize), types.Types[types.TUINT32])
698                 }
699                 hashField = itabHashField
700         }
701         return boundedDotPtr(pos, itab, hashField)
702 }
703
704 var rtypeHashField, itabHashField *types.Field
705
706 // A typeSwitch walks a type switch.
707 type typeSwitch struct {
708         // Temporary variables (i.e., ONAMEs) used by type switch dispatch logic:
709         srcName  ir.Node // value being type-switched on
710         hashName ir.Node // type hash of the value being type-switched on
711         okName   ir.Node // boolean used for comma-ok type assertions
712         itabName ir.Node // itab value to use for first word of non-empty interface
713 }
714
715 type typeClause struct {
716         hash uint32
717         body ir.Nodes
718 }
719
720 func (s *typeSwitch) flush(cc []typeClause, compiled *ir.Nodes) {
721         if len(cc) == 0 {
722                 return
723         }
724
725         sort.Slice(cc, func(i, j int) bool { return cc[i].hash < cc[j].hash })
726
727         // Combine adjacent cases with the same hash.
728         merged := cc[:1]
729         for _, c := range cc[1:] {
730                 last := &merged[len(merged)-1]
731                 if last.hash == c.hash {
732                         last.body.Append(c.body.Take()...)
733                 } else {
734                         merged = append(merged, c)
735                 }
736         }
737         cc = merged
738
739         if s.tryJumpTable(cc, compiled) {
740                 return
741         }
742         binarySearch(len(cc), compiled,
743                 func(i int) ir.Node {
744                         return ir.NewBinaryExpr(base.Pos, ir.OLE, s.hashName, ir.NewInt(base.Pos, int64(cc[i-1].hash)))
745                 },
746                 func(i int, nif *ir.IfStmt) {
747                         // TODO(mdempsky): Omit hash equality check if
748                         // there's only one type.
749                         c := cc[i]
750                         nif.Cond = ir.NewBinaryExpr(base.Pos, ir.OEQ, s.hashName, ir.NewInt(base.Pos, int64(c.hash)))
751                         nif.Body.Append(c.body.Take()...)
752                 },
753         )
754 }
755
756 // Try to implement the clauses with a jump table. Returns true if successful.
757 func (s *typeSwitch) tryJumpTable(cc []typeClause, out *ir.Nodes) bool {
758         const minCases = 5 // have at least minCases cases in the switch
759         if base.Flag.N != 0 || !ssagen.Arch.LinkArch.CanJumpTable || base.Ctxt.Retpoline {
760                 return false
761         }
762         if len(cc) < minCases {
763                 return false // not enough cases for it to be worth it
764         }
765         hashes := make([]uint32, len(cc))
766         // b = # of bits to use. Start with the minimum number of
767         // bits possible, but try a few larger sizes if needed.
768         b0 := bits.Len(uint(len(cc) - 1))
769         for b := b0; b < b0+3; b++ {
770         pickI:
771                 for i := 0; i <= 32-b; i++ { // starting bit position
772                         // Compute the hash we'd get from all the cases,
773                         // selecting b bits starting at bit i.
774                         hashes = hashes[:0]
775                         for _, c := range cc {
776                                 h := c.hash >> i & (1<<b - 1)
777                                 hashes = append(hashes, h)
778                         }
779                         // Order by increasing hash.
780                         sort.Slice(hashes, func(j, k int) bool {
781                                 return hashes[j] < hashes[k]
782                         })
783                         for j := 1; j < len(hashes); j++ {
784                                 if hashes[j] == hashes[j-1] {
785                                         // There is a duplicate hash; try a different b/i pair.
786                                         continue pickI
787                                 }
788                         }
789
790                         // All hashes are distinct. Use these values of b and i.
791                         h := s.hashName
792                         if i != 0 {
793                                 h = ir.NewBinaryExpr(base.Pos, ir.ORSH, h, ir.NewInt(base.Pos, int64(i)))
794                         }
795                         h = ir.NewBinaryExpr(base.Pos, ir.OAND, h, ir.NewInt(base.Pos, int64(1<<b-1)))
796                         h = typecheck.Expr(h)
797
798                         // Build jump table.
799                         jt := ir.NewJumpTableStmt(base.Pos, h)
800                         jt.Cases = make([]constant.Value, 1<<b)
801                         jt.Targets = make([]*types.Sym, 1<<b)
802                         out.Append(jt)
803
804                         // Start with all hashes going to the didn't-match target.
805                         noMatch := typecheck.AutoLabel(".s")
806                         for j := 0; j < 1<<b; j++ {
807                                 jt.Cases[j] = constant.MakeInt64(int64(j))
808                                 jt.Targets[j] = noMatch
809                         }
810                         // This statement is not reachable, but it will make it obvious that we don't
811                         // fall through to the first case.
812                         out.Append(ir.NewBranchStmt(base.Pos, ir.OGOTO, noMatch))
813
814                         // Emit each of the actual cases.
815                         for _, c := range cc {
816                                 h := c.hash >> i & (1<<b - 1)
817                                 label := typecheck.AutoLabel(".s")
818                                 jt.Targets[h] = label
819                                 out.Append(ir.NewLabelStmt(base.Pos, label))
820                                 out.Append(c.body...)
821                                 // We reach here if the hash matches but the type equality test fails.
822                                 out.Append(ir.NewBranchStmt(base.Pos, ir.OGOTO, noMatch))
823                         }
824                         // Emit point to go to if type doesn't match any case.
825                         out.Append(ir.NewLabelStmt(base.Pos, noMatch))
826                         return true
827                 }
828         }
829         // Couldn't find a perfect hash. Fall back to binary search.
830         return false
831 }
832
833 // binarySearch constructs a binary search tree for handling n cases,
834 // and appends it to out. It's used for efficiently implementing
835 // switch statements.
836 //
837 // less(i) should return a boolean expression. If it evaluates true,
838 // then cases before i will be tested; otherwise, cases i and later.
839 //
840 // leaf(i, nif) should setup nif (an OIF node) to test case i. In
841 // particular, it should set nif.Cond and nif.Body.
842 func binarySearch(n int, out *ir.Nodes, less func(i int) ir.Node, leaf func(i int, nif *ir.IfStmt)) {
843         const binarySearchMin = 4 // minimum number of cases for binary search
844
845         var do func(lo, hi int, out *ir.Nodes)
846         do = func(lo, hi int, out *ir.Nodes) {
847                 n := hi - lo
848                 if n < binarySearchMin {
849                         for i := lo; i < hi; i++ {
850                                 nif := ir.NewIfStmt(base.Pos, nil, nil, nil)
851                                 leaf(i, nif)
852                                 base.Pos = base.Pos.WithNotStmt()
853                                 nif.Cond = typecheck.Expr(nif.Cond)
854                                 nif.Cond = typecheck.DefaultLit(nif.Cond, nil)
855                                 out.Append(nif)
856                                 out = &nif.Else
857                         }
858                         return
859                 }
860
861                 half := lo + n/2
862                 nif := ir.NewIfStmt(base.Pos, nil, nil, nil)
863                 nif.Cond = less(half)
864                 base.Pos = base.Pos.WithNotStmt()
865                 nif.Cond = typecheck.Expr(nif.Cond)
866                 nif.Cond = typecheck.DefaultLit(nif.Cond, nil)
867                 do(lo, half, &nif.Body)
868                 do(half, hi, &nif.Else)
869                 out.Append(nif)
870         }
871
872         do(0, n, out)
873 }
874
875 func stringSearch(expr ir.Node, cc []exprClause, out *ir.Nodes) {
876         if len(cc) < 4 {
877                 // Short list, just do brute force equality checks.
878                 for _, c := range cc {
879                         nif := ir.NewIfStmt(base.Pos.WithNotStmt(), typecheck.DefaultLit(typecheck.Expr(c.test(expr)), nil), []ir.Node{c.jmp}, nil)
880                         out.Append(nif)
881                         out = &nif.Else
882                 }
883                 return
884         }
885
886         // The strategy here is to find a simple test to divide the set of possible strings
887         // that might match expr approximately in half.
888         // The test we're going to use is to do an ordered comparison of a single byte
889         // of expr to a constant. We will pick the index of that byte and the value we're
890         // comparing against to make the split as even as possible.
891         //   if expr[3] <= 'd' { ... search strings with expr[3] at 'd' or lower  ... }
892         //   else              { ... search strings with expr[3] at 'e' or higher ... }
893         //
894         // To add complication, we will do the ordered comparison in the signed domain.
895         // The reason for this is to prevent CSE from merging the load used for the
896         // ordered comparison with the load used for the later equality check.
897         //   if expr[3] <= 'd' { ... if expr[0] == 'f' && expr[1] == 'o' && expr[2] == 'o' && expr[3] == 'd' { ... } }
898         // If we did both expr[3] loads in the unsigned domain, they would be CSEd, and that
899         // would in turn defeat the combining of expr[0]...expr[3] into a single 4-byte load.
900         // See issue 48222.
901         // By using signed loads for the ordered comparison and unsigned loads for the
902         // equality comparison, they don't get CSEd and the equality comparisons will be
903         // done using wider loads.
904
905         n := len(ir.StringVal(cc[0].lo)) // Length of the constant strings.
906         bestScore := int64(0)            // measure of how good the split is.
907         bestIdx := 0                     // split using expr[bestIdx]
908         bestByte := int8(0)              // compare expr[bestIdx] against bestByte
909         for idx := 0; idx < n; idx++ {
910                 for b := int8(-128); b < 127; b++ {
911                         le := 0
912                         for _, c := range cc {
913                                 s := ir.StringVal(c.lo)
914                                 if int8(s[idx]) <= b {
915                                         le++
916                                 }
917                         }
918                         score := int64(le) * int64(len(cc)-le)
919                         if score > bestScore {
920                                 bestScore = score
921                                 bestIdx = idx
922                                 bestByte = b
923                         }
924                 }
925         }
926
927         // The split must be at least 1:n-1 because we have at least 2 distinct strings; they
928         // have to be different somewhere.
929         // TODO: what if the best split is still pretty bad?
930         if bestScore == 0 {
931                 base.Fatalf("unable to split string set")
932         }
933
934         // Convert expr to a []int8
935         slice := ir.NewConvExpr(base.Pos, ir.OSTR2BYTESTMP, types.NewSlice(types.Types[types.TINT8]), expr)
936         slice.SetTypecheck(1) // legacy typechecker doesn't handle this op
937         slice.MarkNonNil()
938         // Load the byte we're splitting on.
939         load := ir.NewIndexExpr(base.Pos, slice, ir.NewInt(base.Pos, int64(bestIdx)))
940         // Compare with the value we're splitting on.
941         cmp := ir.Node(ir.NewBinaryExpr(base.Pos, ir.OLE, load, ir.NewInt(base.Pos, int64(bestByte))))
942         cmp = typecheck.DefaultLit(typecheck.Expr(cmp), nil)
943         nif := ir.NewIfStmt(base.Pos, cmp, nil, nil)
944
945         var le []exprClause
946         var gt []exprClause
947         for _, c := range cc {
948                 s := ir.StringVal(c.lo)
949                 if int8(s[bestIdx]) <= bestByte {
950                         le = append(le, c)
951                 } else {
952                         gt = append(gt, c)
953                 }
954         }
955         stringSearch(expr, le, &nif.Body)
956         stringSearch(expr, gt, &nif.Else)
957         out.Append(nif)
958
959         // TODO: if expr[bestIdx] has enough different possible values, use a jump table.
960 }