gitee.com/wgliang/goreporter@v0.0.0-20180902115603-df1b20f7c5d0/linters/simpler/ssa/func.go (about) 1 // Copyright 2013 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 // +build go1.5 6 7 package ssa 8 9 // This file implements the Function and BasicBlock types. 10 11 import ( 12 "bytes" 13 "fmt" 14 "go/ast" 15 "go/token" 16 "go/types" 17 "io" 18 "os" 19 "strings" 20 ) 21 22 // addEdge adds a control-flow graph edge from from to to. 23 func addEdge(from, to *BasicBlock) { 24 from.Succs = append(from.Succs, to) 25 to.Preds = append(to.Preds, from) 26 } 27 28 // Parent returns the function that contains block b. 29 func (b *BasicBlock) Parent() *Function { return b.parent } 30 31 // String returns a human-readable label of this block. 32 // It is not guaranteed unique within the function. 33 // 34 func (b *BasicBlock) String() string { 35 return fmt.Sprintf("%d", b.Index) 36 } 37 38 // emit appends an instruction to the current basic block. 39 // If the instruction defines a Value, it is returned. 40 // 41 func (b *BasicBlock) emit(i Instruction) Value { 42 i.setBlock(b) 43 b.Instrs = append(b.Instrs, i) 44 v, _ := i.(Value) 45 return v 46 } 47 48 // predIndex returns the i such that b.Preds[i] == c or panics if 49 // there is none. 50 func (b *BasicBlock) predIndex(c *BasicBlock) int { 51 for i, pred := range b.Preds { 52 if pred == c { 53 return i 54 } 55 } 56 panic(fmt.Sprintf("no edge %s -> %s", c, b)) 57 } 58 59 // hasPhi returns true if b.Instrs contains φ-nodes. 60 func (b *BasicBlock) hasPhi() bool { 61 _, ok := b.Instrs[0].(*Phi) 62 return ok 63 } 64 65 func (b *BasicBlock) Phis() []Instruction { 66 return b.phis() 67 } 68 69 // phis returns the prefix of b.Instrs containing all the block's φ-nodes. 70 func (b *BasicBlock) phis() []Instruction { 71 for i, instr := range b.Instrs { 72 if _, ok := instr.(*Phi); !ok { 73 return b.Instrs[:i] 74 } 75 } 76 return nil // unreachable in well-formed blocks 77 } 78 79 // replacePred replaces all occurrences of p in b's predecessor list with q. 80 // Ordinarily there should be at most one. 81 // 82 func (b *BasicBlock) replacePred(p, q *BasicBlock) { 83 for i, pred := range b.Preds { 84 if pred == p { 85 b.Preds[i] = q 86 } 87 } 88 } 89 90 // replaceSucc replaces all occurrences of p in b's successor list with q. 91 // Ordinarily there should be at most one. 92 // 93 func (b *BasicBlock) replaceSucc(p, q *BasicBlock) { 94 for i, succ := range b.Succs { 95 if succ == p { 96 b.Succs[i] = q 97 } 98 } 99 } 100 101 func (b *BasicBlock) RemovePred(p *BasicBlock) { 102 b.removePred(p) 103 } 104 105 // removePred removes all occurrences of p in b's 106 // predecessor list and φ-nodes. 107 // Ordinarily there should be at most one. 108 // 109 func (b *BasicBlock) removePred(p *BasicBlock) { 110 phis := b.phis() 111 112 // We must preserve edge order for φ-nodes. 113 j := 0 114 for i, pred := range b.Preds { 115 if pred != p { 116 b.Preds[j] = b.Preds[i] 117 // Strike out φ-edge too. 118 for _, instr := range phis { 119 phi := instr.(*Phi) 120 phi.Edges[j] = phi.Edges[i] 121 } 122 j++ 123 } 124 } 125 // Nil out b.Preds[j:] and φ-edges[j:] to aid GC. 126 for i := j; i < len(b.Preds); i++ { 127 b.Preds[i] = nil 128 for _, instr := range phis { 129 instr.(*Phi).Edges[i] = nil 130 } 131 } 132 b.Preds = b.Preds[:j] 133 for _, instr := range phis { 134 phi := instr.(*Phi) 135 phi.Edges = phi.Edges[:j] 136 } 137 } 138 139 // Destinations associated with unlabelled for/switch/select stmts. 140 // We push/pop one of these as we enter/leave each construct and for 141 // each BranchStmt we scan for the innermost target of the right type. 142 // 143 type targets struct { 144 tail *targets // rest of stack 145 _break *BasicBlock 146 _continue *BasicBlock 147 _fallthrough *BasicBlock 148 } 149 150 // Destinations associated with a labelled block. 151 // We populate these as labels are encountered in forward gotos or 152 // labelled statements. 153 // 154 type lblock struct { 155 _goto *BasicBlock 156 _break *BasicBlock 157 _continue *BasicBlock 158 } 159 160 // labelledBlock returns the branch target associated with the 161 // specified label, creating it if needed. 162 // 163 func (f *Function) labelledBlock(label *ast.Ident) *lblock { 164 lb := f.lblocks[label.Obj] 165 if lb == nil { 166 lb = &lblock{_goto: f.newBasicBlock(label.Name)} 167 if f.lblocks == nil { 168 f.lblocks = make(map[*ast.Object]*lblock) 169 } 170 f.lblocks[label.Obj] = lb 171 } 172 return lb 173 } 174 175 // addParam adds a (non-escaping) parameter to f.Params of the 176 // specified name, type and source position. 177 // 178 func (f *Function) addParam(name string, typ types.Type, pos token.Pos) *Parameter { 179 v := &Parameter{ 180 name: name, 181 typ: typ, 182 pos: pos, 183 parent: f, 184 } 185 f.Params = append(f.Params, v) 186 return v 187 } 188 189 func (f *Function) addParamObj(obj types.Object) *Parameter { 190 name := obj.Name() 191 if name == "" { 192 name = fmt.Sprintf("arg%d", len(f.Params)) 193 } 194 param := f.addParam(name, obj.Type(), obj.Pos()) 195 param.object = obj 196 return param 197 } 198 199 // addSpilledParam declares a parameter that is pre-spilled to the 200 // stack; the function body will load/store the spilled location. 201 // Subsequent lifting will eliminate spills where possible. 202 // 203 func (f *Function) addSpilledParam(obj types.Object) { 204 param := f.addParamObj(obj) 205 spill := &Alloc{Comment: obj.Name()} 206 spill.setType(types.NewPointer(obj.Type())) 207 spill.setPos(obj.Pos()) 208 f.objects[obj] = spill 209 f.Locals = append(f.Locals, spill) 210 f.emit(spill) 211 f.emit(&Store{Addr: spill, Val: param}) 212 } 213 214 // startBody initializes the function prior to generating SSA code for its body. 215 // Precondition: f.Type() already set. 216 // 217 func (f *Function) startBody() { 218 f.currentBlock = f.newBasicBlock("entry") 219 f.objects = make(map[types.Object]Value) // needed for some synthetics, e.g. init 220 } 221 222 // createSyntacticParams populates f.Params and generates code (spills 223 // and named result locals) for all the parameters declared in the 224 // syntax. In addition it populates the f.objects mapping. 225 // 226 // Preconditions: 227 // f.startBody() was called. 228 // Postcondition: 229 // len(f.Params) == len(f.Signature.Params) + (f.Signature.Recv() ? 1 : 0) 230 // 231 func (f *Function) createSyntacticParams(recv *ast.FieldList, functype *ast.FuncType) { 232 // Receiver (at most one inner iteration). 233 if recv != nil { 234 for _, field := range recv.List { 235 for _, n := range field.Names { 236 f.addSpilledParam(f.Pkg.info.Defs[n]) 237 } 238 // Anonymous receiver? No need to spill. 239 if field.Names == nil { 240 f.addParamObj(f.Signature.Recv()) 241 } 242 } 243 } 244 245 // Parameters. 246 if functype.Params != nil { 247 n := len(f.Params) // 1 if has recv, 0 otherwise 248 for _, field := range functype.Params.List { 249 for _, n := range field.Names { 250 f.addSpilledParam(f.Pkg.info.Defs[n]) 251 } 252 // Anonymous parameter? No need to spill. 253 if field.Names == nil { 254 f.addParamObj(f.Signature.Params().At(len(f.Params) - n)) 255 } 256 } 257 } 258 259 // Named results. 260 if functype.Results != nil { 261 for _, field := range functype.Results.List { 262 // Implicit "var" decl of locals for named results. 263 for _, n := range field.Names { 264 f.namedResults = append(f.namedResults, f.addLocalForIdent(n)) 265 } 266 } 267 } 268 } 269 270 // numberRegisters assigns numbers to all SSA registers 271 // (value-defining Instructions) in f, to aid debugging. 272 // (Non-Instruction Values are named at construction.) 273 // 274 func numberRegisters(f *Function) { 275 v := 0 276 for _, b := range f.Blocks { 277 for _, instr := range b.Instrs { 278 switch instr.(type) { 279 case Value: 280 instr.(interface { 281 setNum(int) 282 }).setNum(v) 283 v++ 284 } 285 } 286 } 287 } 288 289 // buildReferrers populates the def/use information in all non-nil 290 // Value.Referrers slice. 291 // Precondition: all such slices are initially empty. 292 func buildReferrers(f *Function) { 293 var rands []*Value 294 for _, b := range f.Blocks { 295 for _, instr := range b.Instrs { 296 rands = instr.Operands(rands[:0]) // recycle storage 297 for _, rand := range rands { 298 if r := *rand; r != nil { 299 if ref := r.Referrers(); ref != nil { 300 *ref = append(*ref, instr) 301 } 302 } 303 } 304 } 305 } 306 } 307 308 // finishBody() finalizes the function after SSA code generation of its body. 309 func (f *Function) finishBody() { 310 f.objects = nil 311 f.currentBlock = nil 312 f.lblocks = nil 313 314 // Don't pin the AST in memory (except in debug mode). 315 if n := f.syntax; n != nil && !f.debugInfo() { 316 f.syntax = extentNode{n.Pos(), n.End()} 317 } 318 319 // Remove from f.Locals any Allocs that escape to the heap. 320 j := 0 321 for _, l := range f.Locals { 322 if !l.Heap { 323 f.Locals[j] = l 324 j++ 325 } 326 } 327 // Nil out f.Locals[j:] to aid GC. 328 for i := j; i < len(f.Locals); i++ { 329 f.Locals[i] = nil 330 } 331 f.Locals = f.Locals[:j] 332 333 optimizeBlocks(f) 334 335 buildReferrers(f) 336 337 buildDomTree(f) 338 339 if f.Prog.mode&NaiveForm == 0 { 340 // For debugging pre-state of lifting pass: 341 // numberRegisters(f) 342 // f.WriteTo(os.Stderr) 343 lift(f) 344 } 345 346 f.namedResults = nil // (used by lifting) 347 348 numberRegisters(f) 349 350 if f.Prog.mode&PrintFunctions != 0 { 351 printMu.Lock() 352 f.WriteTo(os.Stdout) 353 printMu.Unlock() 354 } 355 356 if f.Prog.mode&SanityCheckFunctions != 0 { 357 mustSanityCheck(f, nil) 358 } 359 } 360 361 func (f *Function) RemoveNilBlocks() { 362 f.removeNilBlocks() 363 } 364 365 // removeNilBlocks eliminates nils from f.Blocks and updates each 366 // BasicBlock.Index. Use this after any pass that may delete blocks. 367 // 368 func (f *Function) removeNilBlocks() { 369 j := 0 370 for _, b := range f.Blocks { 371 if b != nil { 372 b.Index = j 373 f.Blocks[j] = b 374 j++ 375 } 376 } 377 // Nil out f.Blocks[j:] to aid GC. 378 for i := j; i < len(f.Blocks); i++ { 379 f.Blocks[i] = nil 380 } 381 f.Blocks = f.Blocks[:j] 382 } 383 384 // SetDebugMode sets the debug mode for package pkg. If true, all its 385 // functions will include full debug info. This greatly increases the 386 // size of the instruction stream, and causes Functions to depend upon 387 // the ASTs, potentially keeping them live in memory for longer. 388 // 389 func (pkg *Package) SetDebugMode(debug bool) { 390 // TODO(adonovan): do we want ast.File granularity? 391 pkg.debug = debug 392 } 393 394 // debugInfo reports whether debug info is wanted for this function. 395 func (f *Function) debugInfo() bool { 396 return f.Pkg != nil && f.Pkg.debug 397 } 398 399 // addNamedLocal creates a local variable, adds it to function f and 400 // returns it. Its name and type are taken from obj. Subsequent 401 // calls to f.lookup(obj) will return the same local. 402 // 403 func (f *Function) addNamedLocal(obj types.Object) *Alloc { 404 l := f.addLocal(obj.Type(), obj.Pos()) 405 l.Comment = obj.Name() 406 f.objects[obj] = l 407 return l 408 } 409 410 func (f *Function) addLocalForIdent(id *ast.Ident) *Alloc { 411 return f.addNamedLocal(f.Pkg.info.Defs[id]) 412 } 413 414 // addLocal creates an anonymous local variable of type typ, adds it 415 // to function f and returns it. pos is the optional source location. 416 // 417 func (f *Function) addLocal(typ types.Type, pos token.Pos) *Alloc { 418 v := &Alloc{} 419 v.setType(types.NewPointer(typ)) 420 v.setPos(pos) 421 f.Locals = append(f.Locals, v) 422 f.emit(v) 423 return v 424 } 425 426 // lookup returns the address of the named variable identified by obj 427 // that is local to function f or one of its enclosing functions. 428 // If escaping, the reference comes from a potentially escaping pointer 429 // expression and the referent must be heap-allocated. 430 // 431 func (f *Function) lookup(obj types.Object, escaping bool) Value { 432 if v, ok := f.objects[obj]; ok { 433 if alloc, ok := v.(*Alloc); ok && escaping { 434 alloc.Heap = true 435 } 436 return v // function-local var (address) 437 } 438 439 // Definition must be in an enclosing function; 440 // plumb it through intervening closures. 441 if f.parent == nil { 442 panic("no ssa.Value for " + obj.String()) 443 } 444 outer := f.parent.lookup(obj, true) // escaping 445 v := &FreeVar{ 446 name: obj.Name(), 447 typ: outer.Type(), 448 pos: outer.Pos(), 449 outer: outer, 450 parent: f, 451 } 452 f.objects[obj] = v 453 f.FreeVars = append(f.FreeVars, v) 454 return v 455 } 456 457 // emit emits the specified instruction to function f. 458 func (f *Function) emit(instr Instruction) Value { 459 return f.currentBlock.emit(instr) 460 } 461 462 // RelString returns the full name of this function, qualified by 463 // package name, receiver type, etc. 464 // 465 // The specific formatting rules are not guaranteed and may change. 466 // 467 // Examples: 468 // "math.IsNaN" // a package-level function 469 // "(*bytes.Buffer).Bytes" // a declared method or a wrapper 470 // "(*bytes.Buffer).Bytes$thunk" // thunk (func wrapping method; receiver is param 0) 471 // "(*bytes.Buffer).Bytes$bound" // bound (func wrapping method; receiver supplied by closure) 472 // "main.main$1" // an anonymous function in main 473 // "main.init#1" // a declared init function 474 // "main.init" // the synthesized package initializer 475 // 476 // When these functions are referred to from within the same package 477 // (i.e. from == f.Pkg.Object), they are rendered without the package path. 478 // For example: "IsNaN", "(*Buffer).Bytes", etc. 479 // 480 // All non-synthetic functions have distinct package-qualified names. 481 // (But two methods may have the same name "(T).f" if one is a synthetic 482 // wrapper promoting a non-exported method "f" from another package; in 483 // that case, the strings are equal but the identifiers "f" are distinct.) 484 // 485 func (f *Function) RelString(from *types.Package) string { 486 // Anonymous? 487 if f.parent != nil { 488 // An anonymous function's Name() looks like "parentName$1", 489 // but its String() should include the type/package/etc. 490 parent := f.parent.RelString(from) 491 for i, anon := range f.parent.AnonFuncs { 492 if anon == f { 493 return fmt.Sprintf("%s$%d", parent, 1+i) 494 } 495 } 496 497 return f.name // should never happen 498 } 499 500 // Method (declared or wrapper)? 501 if recv := f.Signature.Recv(); recv != nil { 502 return f.relMethod(from, recv.Type()) 503 } 504 505 // Thunk? 506 if f.method != nil { 507 return f.relMethod(from, f.method.Recv()) 508 } 509 510 // Bound? 511 if len(f.FreeVars) == 1 && strings.HasSuffix(f.name, "$bound") { 512 return f.relMethod(from, f.FreeVars[0].Type()) 513 } 514 515 // Package-level function? 516 // Prefix with package name for cross-package references only. 517 if p := f.pkg(); p != nil && p != from { 518 return fmt.Sprintf("%s.%s", p.Path(), f.name) 519 } 520 521 // Unknown. 522 return f.name 523 } 524 525 func (f *Function) relMethod(from *types.Package, recv types.Type) string { 526 return fmt.Sprintf("(%s).%s", relType(recv, from), f.name) 527 } 528 529 // writeSignature writes to buf the signature sig in declaration syntax. 530 func writeSignature(buf *bytes.Buffer, from *types.Package, name string, sig *types.Signature, params []*Parameter) { 531 buf.WriteString("func ") 532 if recv := sig.Recv(); recv != nil { 533 buf.WriteString("(") 534 if n := params[0].Name(); n != "" { 535 buf.WriteString(n) 536 buf.WriteString(" ") 537 } 538 types.WriteType(buf, params[0].Type(), types.RelativeTo(from)) 539 buf.WriteString(") ") 540 } 541 buf.WriteString(name) 542 types.WriteSignature(buf, sig, types.RelativeTo(from)) 543 } 544 545 func (f *Function) pkg() *types.Package { 546 if f.Pkg != nil { 547 return f.Pkg.Pkg 548 } 549 return nil 550 } 551 552 var _ io.WriterTo = (*Function)(nil) // *Function implements io.Writer 553 554 func (f *Function) WriteTo(w io.Writer) (int64, error) { 555 var buf bytes.Buffer 556 WriteFunction(&buf, f) 557 n, err := w.Write(buf.Bytes()) 558 return int64(n), err 559 } 560 561 // WriteFunction writes to buf a human-readable "disassembly" of f. 562 func WriteFunction(buf *bytes.Buffer, f *Function) { 563 fmt.Fprintf(buf, "# Name: %s\n", f.String()) 564 if f.Pkg != nil { 565 fmt.Fprintf(buf, "# Package: %s\n", f.Pkg.Pkg.Path()) 566 } 567 if syn := f.Synthetic; syn != "" { 568 fmt.Fprintln(buf, "# Synthetic:", syn) 569 } 570 if pos := f.Pos(); pos.IsValid() { 571 fmt.Fprintf(buf, "# Location: %s\n", f.Prog.Fset.Position(pos)) 572 } 573 574 if f.parent != nil { 575 fmt.Fprintf(buf, "# Parent: %s\n", f.parent.Name()) 576 } 577 578 if f.Recover != nil { 579 fmt.Fprintf(buf, "# Recover: %s\n", f.Recover) 580 } 581 582 from := f.pkg() 583 584 if f.FreeVars != nil { 585 buf.WriteString("# Free variables:\n") 586 for i, fv := range f.FreeVars { 587 fmt.Fprintf(buf, "# % 3d:\t%s %s\n", i, fv.Name(), relType(fv.Type(), from)) 588 } 589 } 590 591 if len(f.Locals) > 0 { 592 buf.WriteString("# Locals:\n") 593 for i, l := range f.Locals { 594 fmt.Fprintf(buf, "# % 3d:\t%s %s\n", i, l.Name(), relType(deref(l.Type()), from)) 595 } 596 } 597 writeSignature(buf, from, f.Name(), f.Signature, f.Params) 598 buf.WriteString(":\n") 599 600 if f.Blocks == nil { 601 buf.WriteString("\t(external)\n") 602 } 603 604 // NB. column calculations are confused by non-ASCII 605 // characters and assume 8-space tabs. 606 const punchcard = 80 // for old time's sake. 607 const tabwidth = 8 608 for _, b := range f.Blocks { 609 if b == nil { 610 // Corrupt CFG. 611 fmt.Fprintf(buf, ".nil:\n") 612 continue 613 } 614 n, _ := fmt.Fprintf(buf, "%d:", b.Index) 615 bmsg := fmt.Sprintf("%s P:%d S:%d", b.Comment, len(b.Preds), len(b.Succs)) 616 fmt.Fprintf(buf, "%*s%s\n", punchcard-1-n-len(bmsg), "", bmsg) 617 618 if false { // CFG debugging 619 fmt.Fprintf(buf, "\t# CFG: %s --> %s --> %s\n", b.Preds, b, b.Succs) 620 } 621 for _, instr := range b.Instrs { 622 buf.WriteString("\t") 623 switch v := instr.(type) { 624 case Value: 625 l := punchcard - tabwidth 626 // Left-align the instruction. 627 if name := v.Name(); name != "" { 628 n, _ := fmt.Fprintf(buf, "%s = ", name) 629 l -= n 630 } 631 n, _ := buf.WriteString(instr.String()) 632 l -= n 633 // Right-align the type if there's space. 634 if t := v.Type(); t != nil { 635 buf.WriteByte(' ') 636 ts := relType(t, from) 637 l -= len(ts) + len(" ") // (spaces before and after type) 638 if l > 0 { 639 fmt.Fprintf(buf, "%*s", l, "") 640 } 641 buf.WriteString(ts) 642 } 643 case nil: 644 // Be robust against bad transforms. 645 buf.WriteString("<deleted>") 646 default: 647 buf.WriteString(instr.String()) 648 } 649 buf.WriteString("\n") 650 } 651 } 652 fmt.Fprintf(buf, "\n") 653 } 654 655 // newBasicBlock adds to f a new basic block and returns it. It does 656 // not automatically become the current block for subsequent calls to emit. 657 // comment is an optional string for more readable debugging output. 658 // 659 func (f *Function) newBasicBlock(comment string) *BasicBlock { 660 b := &BasicBlock{ 661 Index: len(f.Blocks), 662 Comment: comment, 663 parent: f, 664 } 665 b.Succs = b.succs2[:0] 666 f.Blocks = append(f.Blocks, b) 667 return b 668 } 669 670 // NewFunction returns a new synthetic Function instance belonging to 671 // prog, with its name and signature fields set as specified. 672 // 673 // The caller is responsible for initializing the remaining fields of 674 // the function object, e.g. Pkg, Params, Blocks. 675 // 676 // It is practically impossible for clients to construct well-formed 677 // SSA functions/packages/programs directly, so we assume this is the 678 // job of the Builder alone. NewFunction exists to provide clients a 679 // little flexibility. For example, analysis tools may wish to 680 // construct fake Functions for the root of the callgraph, a fake 681 // "reflect" package, etc. 682 // 683 // TODO(adonovan): think harder about the API here. 684 // 685 func (prog *Program) NewFunction(name string, sig *types.Signature, provenance string) *Function { 686 return &Function{Prog: prog, name: name, Signature: sig, Synthetic: provenance} 687 } 688 689 type extentNode [2]token.Pos 690 691 func (n extentNode) Pos() token.Pos { return n[0] } 692 func (n extentNode) End() token.Pos { return n[1] } 693 694 // Syntax returns an ast.Node whose Pos/End methods provide the 695 // lexical extent of the function if it was defined by Go source code 696 // (f.Synthetic==""), or nil otherwise. 697 // 698 // If f was built with debug information (see Package.SetDebugRef), 699 // the result is the *ast.FuncDecl or *ast.FuncLit that declared the 700 // function. Otherwise, it is an opaque Node providing only position 701 // information; this avoids pinning the AST in memory. 702 // 703 func (f *Function) Syntax() ast.Node { return f.syntax }