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