| 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 ir |
| 6 |
|
| 7 |
// This file implements the Function type. |
| 8 |
|
| 9 |
import ( |
| 10 |
"bytes" |
| 11 |
"fmt" |
| 12 |
"go/ast" |
| 13 |
"go/token" |
| 14 |
"go/types" |
| 15 |
"io" |
| 16 |
"iter" |
| 17 |
"os" |
| 18 |
"strings" |
| 19 |
) |
| 20 |
|
| 21 |
// Like ObjectOf, but panics instead of returning nil. |
| 22 |
// Only valid during f's create and build phases. |
| 23 |
func (f *Function) objectOf(id *ast.Ident) types.Object { |
| 24 |
if o := f.info.ObjectOf(id); o != nil { |
| 25 |
return o |
| 26 |
} |
| 27 |
panic(fmt.Sprintf("no types.Object for ast.Ident %s @ %s", |
| 28 |
id.Name, f.Prog.Fset.Position(id.Pos()))) |
| 29 |
} |
| 30 |
|
| 31 |
// instrs returns an iterator that returns each reachable instruction of the SSA function. |
| 32 |
func (f *Function) instrs() iter.Seq[Instruction] { |
| 33 |
return func(yield func(i Instruction) bool) { |
| 34 |
for _, block := range f.Blocks { |
| 35 |
for _, instr := range block.Instrs { |
| 36 |
if !yield(instr) { |
| 37 |
return |
| 38 |
} |
| 39 |
} |
| 40 |
} |
| 41 |
} |
| 42 |
} |
| 43 |
|
| 44 |
// Like TypeOf, but panics instead of returning nil. |
| 45 |
// Only valid during f's create and build phases. |
| 46 |
func (f *Function) typeOf(e ast.Expr) types.Type { |
| 47 |
if T := f.info.TypeOf(e); T != nil { |
| 48 |
return f.typ(T) |
| 49 |
} |
| 50 |
panic(fmt.Sprintf("no type for %T @ %s", e, f.Prog.Fset.Position(e.Pos()))) |
| 51 |
} |
| 52 |
|
| 53 |
// typ is the locally instantiated type of T. |
| 54 |
// If f is not an instantiation, then f.typ(T)==T. |
| 55 |
func (f *Function) typ(T types.Type) types.Type { |
| 56 |
return f.subst.typ(T) |
| 57 |
} |
| 58 |
|
| 59 |
// If id is an Instance, returns info.Instances[id].Type. |
| 60 |
// Otherwise returns f.typeOf(id). |
| 61 |
func (f *Function) instanceType(id *ast.Ident) types.Type { |
| 62 |
if t, ok := f.info.Instances[id]; ok { |
| 63 |
return t.Type |
| 64 |
} |
| 65 |
return f.typeOf(id) |
| 66 |
} |
| 67 |
|
| 68 |
// selection returns a *selection corresponding to f.info.Selections[selector] |
| 69 |
// with potential updates for type substitution. |
| 70 |
func (f *Function) selection(selector *ast.SelectorExpr) *selection { |
| 71 |
sel := f.info.Selections[selector] |
| 72 |
if sel == nil { |
| 73 |
return nil |
| 74 |
} |
| 75 |
|
| 76 |
switch sel.Kind() { |
| 77 |
case types.MethodExpr, types.MethodVal: |
| 78 |
if recv := f.typ(sel.Recv()); recv != sel.Recv() { |
| 79 |
// recv changed during type substitution. |
| 80 |
pkg := f.declaredPackage().Pkg |
| 81 |
obj, index, indirect := types.LookupFieldOrMethod(recv, true, pkg, sel.Obj().Name()) |
| 82 |
|
| 83 |
// sig replaces sel.Type(). See (types.Selection).Typ() for details. |
| 84 |
sig := obj.Type().(*types.Signature) |
| 85 |
sig = changeRecv(sig, newVar(sig.Recv().Name(), recv)) |
| 86 |
if sel.Kind() == types.MethodExpr { |
| 87 |
sig = recvAsFirstArg(sig) |
| 88 |
} |
| 89 |
return &selection{ |
| 90 |
kind: sel.Kind(), |
| 91 |
recv: recv, |
| 92 |
typ: sig, |
| 93 |
obj: obj, |
| 94 |
index: index, |
| 95 |
indirect: indirect, |
| 96 |
} |
| 97 |
} |
| 98 |
} |
| 99 |
return toSelection(sel) |
| 100 |
} |
| 101 |
|
| 102 |
// Destinations associated with unlabelled for/switch/select stmts. |
| 103 |
// We push/pop one of these as we enter/leave each construct and for |
| 104 |
// each BranchStmt we scan for the innermost target of the right type. |
| 105 |
type targets struct { |
| 106 |
tail *targets // rest of stack |
| 107 |
_break *BasicBlock |
| 108 |
_continue *BasicBlock |
| 109 |
_fallthrough *BasicBlock |
| 110 |
} |
| 111 |
|
| 112 |
// Destinations associated with a labelled block. |
| 113 |
// We populate these as labels are encountered in forward gotos or |
| 114 |
// labelled statements. |
| 115 |
// Forward gotos are resolved once it is known which statement they |
| 116 |
// are associated with inside the Function. |
| 117 |
type lblock struct { |
| 118 |
label *types.Label // Label targeted by the blocks. |
| 119 |
resolved bool // _goto block encountered (back jump or resolved fwd jump) |
| 120 |
_goto *BasicBlock |
| 121 |
_break *BasicBlock |
| 122 |
_continue *BasicBlock |
| 123 |
} |
| 124 |
|
| 125 |
// label returns the symbol denoted by a label identifier. |
| 126 |
// |
| 127 |
// label should be a non-blank identifier (label.Name != "_"). |
| 128 |
func (f *Function) label(label *ast.Ident) *types.Label { |
| 129 |
return f.objectOf(label).(*types.Label) |
| 130 |
} |
| 131 |
|
| 132 |
// lblockOf returns the branch target associated with the |
| 133 |
// specified label, creating it if needed. |
| 134 |
func (f *Function) lblockOf(label *types.Label) *lblock { |
| 135 |
lb := f.lblocks[label] |
| 136 |
if lb == nil { |
| 137 |
lb = &lblock{ |
| 138 |
label: label, |
| 139 |
_goto: f.newBasicBlock(label.Name()), |
| 140 |
} |
| 141 |
if f.lblocks == nil { |
| 142 |
f.lblocks = make(map[*types.Label]*lblock) |
| 143 |
} |
| 144 |
f.lblocks[label] = lb |
| 145 |
} |
| 146 |
return lb |
| 147 |
} |
| 148 |
|
| 149 |
// labelledBlock searches f for the block of the specified label. |
| 150 |
// |
| 151 |
// If f is a yield function, it additionally searches ancestor Functions |
| 152 |
// corresponding to enclosing range-over-func statements within the |
| 153 |
// same source function, so the returned block may belong to a different Function. |
| 154 |
func labelledBlock(f *Function, label *types.Label, tok token.Token) *BasicBlock { |
| 155 |
if lb := f.lblocks[label]; lb != nil { |
| 156 |
var block *BasicBlock |
| 157 |
switch tok { |
| 158 |
case token.BREAK: |
| 159 |
block = lb._break |
| 160 |
case token.CONTINUE: |
| 161 |
block = lb._continue |
| 162 |
case token.GOTO: |
| 163 |
block = lb._goto |
| 164 |
} |
| 165 |
if block != nil { |
| 166 |
return block |
| 167 |
} |
| 168 |
} |
| 169 |
// Search ancestors if this is a yield function. |
| 170 |
if f.jump != nil { |
| 171 |
return labelledBlock(f.parent, label, tok) |
| 172 |
} |
| 173 |
return nil |
| 174 |
} |
| 175 |
|
| 176 |
// targetedBlock looks for the nearest block in f.targets |
| 177 |
// (and f's ancestors) that matches tok's type, and returns |
| 178 |
// the block and function it was found in. |
| 179 |
func targetedBlock(f *Function, tok token.Token) *BasicBlock { |
| 180 |
if f == nil { |
| 181 |
return nil |
| 182 |
} |
| 183 |
for t := f.targets; t != nil; t = t.tail { |
| 184 |
var block *BasicBlock |
| 185 |
switch tok { |
| 186 |
case token.BREAK: |
| 187 |
block = t._break |
| 188 |
case token.CONTINUE: |
| 189 |
block = t._continue |
| 190 |
case token.FALLTHROUGH: |
| 191 |
block = t._fallthrough |
| 192 |
} |
| 193 |
if block != nil { |
| 194 |
return block |
| 195 |
} |
| 196 |
} |
| 197 |
// Search f's ancestors (in case f is a yield function). |
| 198 |
return targetedBlock(f.parent, tok) |
| 199 |
} |
| 200 |
|
| 201 |
// addResultVar adds a result for a variable v to f.results and v to f.returnVars. |
| 202 |
func (f *Function) addResultVar(v *types.Var, source ast.Node) { |
| 203 |
name := v.Name() |
| 204 |
if name == "" { |
| 205 |
name = fmt.Sprintf("res.%d", len(f.results)) |
| 206 |
} |
| 207 |
result := emitLocalVar(f, v, source) |
| 208 |
result.comment = name |
| 209 |
f.results = append(f.results, result) |
| 210 |
f.returnVars = append(f.returnVars, v) |
| 211 |
} |
| 212 |
|
| 213 |
// addParamVar adds a parameter to f.Params. |
| 214 |
func (f *Function) addParamVar(v *types.Var, source ast.Node) *Parameter { |
| 215 |
name := v.Name() |
| 216 |
if name == "" { |
| 217 |
name = fmt.Sprintf("arg%d", len(f.Params)) |
| 218 |
} |
| 219 |
param := &Parameter{name: name, typ: f.typ(v.Type()), parent: f} |
| 220 |
param.setSource(source) |
| 221 |
param.object = v |
| 222 |
f.Params = append(f.Params, param) |
| 223 |
return param |
| 224 |
} |
| 225 |
|
| 226 |
// addSpilledParam declares a parameter that is pre-spilled to the |
| 227 |
// stack; the function body will load/store the spilled location. |
| 228 |
// Subsequent lifting will eliminate spills where possible. |
| 229 |
func (f *Function) addSpilledParam(obj *types.Var, source ast.Node) { |
| 230 |
param := f.addParamVar(obj, source) |
| 231 |
spill := emitLocalVar(f, obj, source) |
| 232 |
emitStore(f, spill, param, source) |
| 233 |
} |
| 234 |
|
| 235 |
// startBody initializes the function prior to generating IR code for its body. |
| 236 |
// Precondition: f.Type() already set. |
| 237 |
func (f *Function) startBody() { |
| 238 |
entry := f.newBasicBlock("entry") |
| 239 |
f.currentBlock = entry |
| 240 |
f.vars = make(map[*types.Var]Value) // needed for some synthetics, e.g. init |
| 241 |
} |
| 242 |
|
| 243 |
func (f *Function) blockset(i int) *BlockSet { |
| 244 |
bs := &f.blocksets[i] |
| 245 |
if len(bs.values) != len(f.Blocks) { |
| 246 |
if cap(bs.values) >= len(f.Blocks) { |
| 247 |
bs.values = bs.values[:len(f.Blocks)] |
| 248 |
bs.Clear() |
| 249 |
} else { |
| 250 |
bs.values = make([]bool, len(f.Blocks)) |
| 251 |
} |
| 252 |
} else { |
| 253 |
bs.Clear() |
| 254 |
} |
| 255 |
return bs |
| 256 |
} |
| 257 |
|
| 258 |
// createSyntacticParams populates f.Params and generates code (spills |
| 259 |
// and named result locals) for all the parameters declared in the |
| 260 |
// syntax. In addition it populates the f.objects mapping. |
| 261 |
// |
| 262 |
// Preconditions: |
| 263 |
// f.startBody() was called. f.info != nil. |
| 264 |
// Postcondition: |
| 265 |
// len(f.Params) == len(f.Signature.Params) + (f.Signature.Recv() ? 1 : 0) |
| 266 |
func (f *Function) createSyntacticParams(recv *ast.FieldList, functype *ast.FuncType) { |
| 267 |
// Receiver (at most one inner iteration). |
| 268 |
if recv != nil { |
| 269 |
for _, field := range recv.List { |
| 270 |
for _, n := range field.Names { |
| 271 |
f.addSpilledParam(identVar(f, n), n) |
| 272 |
} |
| 273 |
// Anonymous receiver? No need to spill. |
| 274 |
if field.Names == nil { |
| 275 |
f.addParamVar(f.Signature.Recv(), field) |
| 276 |
} |
| 277 |
} |
| 278 |
} |
| 279 |
|
| 280 |
// Parameters. |
| 281 |
if functype.Params != nil { |
| 282 |
n := len(f.Params) // 1 if has recv, 0 otherwise |
| 283 |
for _, field := range functype.Params.List { |
| 284 |
for _, n := range field.Names { |
| 285 |
f.addSpilledParam(identVar(f, n), n) |
| 286 |
} |
| 287 |
// Anonymous parameter? No need to spill. |
| 288 |
if field.Names == nil { |
| 289 |
f.addParamVar(f.Signature.Params().At(len(f.Params)-n), field) |
| 290 |
} |
| 291 |
} |
| 292 |
} |
| 293 |
|
| 294 |
// Results. |
| 295 |
if functype.Results != nil { |
| 296 |
for _, field := range functype.Results.List { |
| 297 |
// Implicit "var" decl of locals for named results. |
| 298 |
for _, n := range field.Names { |
| 299 |
v := identVar(f, n) |
| 300 |
f.addResultVar(v, n) |
| 301 |
} |
| 302 |
// Implicit "var" decl of local for an unnamed result. |
| 303 |
if field.Names == nil { |
| 304 |
v := f.Signature.Results().At(len(f.results)) |
| 305 |
f.addResultVar(v, field.Type) |
| 306 |
} |
| 307 |
} |
| 308 |
} |
| 309 |
} |
| 310 |
|
| 311 |
// createDeferStack initializes fn.deferstack to a local variable |
| 312 |
// initialized to a ssa:deferstack() call. |
| 313 |
func (fn *Function) createDeferStack() { |
| 314 |
// Each syntactic function makes a call to ssa:deferstack, |
| 315 |
// which is spilled to a local. Unused ones are later removed. |
| 316 |
fn.deferstack = newVar("defer$stack", tDeferStack) |
| 317 |
call := &Call{Call: CallCommon{Value: vDeferStack}} |
| 318 |
call.setType(tDeferStack) |
| 319 |
deferstack := fn.emit(call, nil) |
| 320 |
spill := emitLocalVar(fn, fn.deferstack, nil) |
| 321 |
emitStore(fn, spill, deferstack, nil) |
| 322 |
} |
| 323 |
|
| 324 |
func numberNodes(f *Function) { |
| 325 |
var base ID |
| 326 |
for _, b := range f.Blocks { |
| 327 |
for _, instr := range b.Instrs { |
| 328 |
if instr == nil { |
| 329 |
continue |
| 330 |
} |
| 331 |
base++ |
| 332 |
instr.setID(base) |
| 333 |
} |
| 334 |
} |
| 335 |
} |
| 336 |
|
| 337 |
func updateOperandsReferrers(instr Instruction, ops []*Value) { |
| 338 |
for _, op := range ops { |
| 339 |
if r := *op; r != nil { |
| 340 |
if refs := (*op).Referrers(); refs != nil { |
| 341 |
if len(*refs) == 0 { |
| 342 |
// per median, each value has two referrers, so we can avoid one call into growslice |
| 343 |
// |
| 344 |
// Note: we experimented with allocating |
| 345 |
// sequential scratch space, but we |
| 346 |
// couldn't find a value that gave better |
| 347 |
// performance than making many individual |
| 348 |
// allocations |
| 349 |
*refs = make([]Instruction, 1, 2) |
| 350 |
(*refs)[0] = instr |
| 351 |
} else { |
| 352 |
*refs = append(*refs, instr) |
| 353 |
} |
| 354 |
} |
| 355 |
} |
| 356 |
} |
| 357 |
} |
| 358 |
|
| 359 |
// buildReferrers populates the def/use information in all non-nil |
| 360 |
// Value.Referrers slice. |
| 361 |
// Precondition: all such slices are initially empty. |
| 362 |
func buildReferrers(f *Function) { |
| 363 |
var rands []*Value |
| 364 |
|
| 365 |
for _, b := range f.Blocks { |
| 366 |
for _, instr := range b.Instrs { |
| 367 |
rands = instr.Operands(rands[:0]) // recycle storage |
| 368 |
updateOperandsReferrers(instr, rands) |
| 369 |
} |
| 370 |
} |
| 371 |
} |
| 372 |
|
| 373 |
// finishBody() finalizes the contents of the function after IR code generation of its body. |
| 374 |
// |
| 375 |
// The function is not done being built until done() is called. |
| 376 |
func (f *Function) finishBody() { |
| 377 |
f.currentBlock = nil |
| 378 |
f.lblocks = nil |
| 379 |
f.returnVars = nil |
| 380 |
f.jump = nil |
| 381 |
f.source = nil |
| 382 |
f.exits = nil |
| 383 |
|
| 384 |
// Remove from f.Locals any Allocs that escape to the heap. |
| 385 |
j := 0 |
| 386 |
for _, l := range f.Locals { |
| 387 |
if !l.Heap { |
| 388 |
f.Locals[j] = l |
| 389 |
j++ |
| 390 |
} |
| 391 |
} |
| 392 |
// Nil out f.Locals[j:] to aid GC. |
| 393 |
for i := j; i < len(f.Locals); i++ { |
| 394 |
f.Locals[i] = nil |
| 395 |
} |
| 396 |
f.Locals = f.Locals[:j] |
| 397 |
|
| 398 |
optimizeBlocks(f) |
| 399 |
buildReferrers(f) |
| 400 |
buildDomTree(f) |
| 401 |
buildSCCs(f) |
| 402 |
|
| 403 |
if f.Prog.mode&NaiveForm == 0 { |
| 404 |
for lift(f) { |
| 405 |
} |
| 406 |
if doSimplifyConstantCompositeValues { |
| 407 |
for simplifyConstantCompositeValues(f) { |
| 408 |
} |
| 409 |
} |
| 410 |
} |
| 411 |
|
| 412 |
if f.debugInfo() { |
| 413 |
// Turn debug references into a map |
| 414 |
f.exprToValue = map[ast.Expr]struct { |
| 415 |
v Value |
| 416 |
isAddr bool |
| 417 |
}{} |
| 418 |
for _, b := range f.Blocks { |
| 419 |
newInstrs := b.Instrs[:0] |
| 420 |
for _, instr := range b.Instrs { |
| 421 |
if instr, ok := instr.(*debugRef); ok { |
| 422 |
if refs := instr.X.Referrers(); refs != nil { |
| 423 |
*refs = removeInstr(*refs, instr) |
| 424 |
} |
| 425 |
if _, ok := f.exprToValue[instr.Expr]; !ok { |
| 426 |
f.exprToValue[instr.Expr] = struct { |
| 427 |
v Value |
| 428 |
isAddr bool |
| 429 |
}{instr.X, instr.IsAddr} |
| 430 |
} |
| 431 |
continue |
| 432 |
} |
| 433 |
newInstrs = append(newInstrs, instr) |
| 434 |
} |
| 435 |
b.Instrs = newInstrs |
| 436 |
} |
| 437 |
} |
| 438 |
|
| 439 |
// clear remaining builder state |
| 440 |
f.results = nil // (used by lifting) |
| 441 |
f.deferstack = nil // (used by lifting) |
| 442 |
f.vars = nil // (used by lifting) |
| 443 |
|
| 444 |
numberNodes(f) |
| 445 |
|
| 446 |
// clear out other function state (keep consistent with buildParamsOnly) |
| 447 |
f.subst = nil |
| 448 |
|
| 449 |
numberNodes(f) |
| 450 |
} |
| 451 |
|
| 452 |
// done marks the building of f's SSA body complete, |
| 453 |
// along with any nested functions, and optionally prints them. |
| 454 |
func (f *Function) done() { |
| 455 |
assert(f.parent == nil, "done called on an anonymous function") |
| 456 |
|
| 457 |
var visit func(*Function) |
| 458 |
visit = func(f *Function) { |
| 459 |
for _, anon := range f.AnonFuncs { |
| 460 |
visit(anon) // anon is done building before f. |
| 461 |
} |
| 462 |
|
| 463 |
f.uniq = 0 // done with uniq |
| 464 |
f.build = nil // function is built |
| 465 |
|
| 466 |
if f.Prog.mode&PrintFunctions != 0 { |
| 467 |
printMu.Lock() |
| 468 |
f.WriteTo(os.Stdout) |
| 469 |
printMu.Unlock() |
| 470 |
} |
| 471 |
|
| 472 |
if f.Prog.mode&SanityCheckFunctions != 0 { |
| 473 |
mustSanityCheck(f, nil) |
| 474 |
} |
| 475 |
} |
| 476 |
visit(f) |
| 477 |
} |
| 478 |
|
| 479 |
func isUselessPhi(phi *Phi) (Value, bool) { |
| 480 |
var v0 Value |
| 481 |
if len(phi.Edges) == 0 { |
| 482 |
panic("φ with no edges") |
| 483 |
} |
| 484 |
for _, e := range phi.Edges { |
| 485 |
if e == nil { |
| 486 |
panic(fmt.Sprintf("φ has nil edge: %v", phi)) |
| 487 |
} |
| 488 |
if e == phi { |
| 489 |
continue |
| 490 |
} |
| 491 |
if v0 == nil { |
| 492 |
v0 = e |
| 493 |
} |
| 494 |
if v0 != e { |
| 495 |
if v0, ok := v0.(*Const); ok { |
| 496 |
if e, ok := e.(*Const); ok { |
| 497 |
if v0.typ == e.typ && v0.Value == e.Value { |
| 498 |
continue |
| 499 |
} |
| 500 |
} |
| 501 |
} |
| 502 |
return nil, false |
| 503 |
} |
| 504 |
} |
| 505 |
if v0 == nil { |
| 506 |
panic("trying to replace φ with nil") |
| 507 |
} |
| 508 |
return v0, true |
| 509 |
} |
| 510 |
|
| 511 |
// removeNilBlocks eliminates nils from f.Blocks and updates each |
| 512 |
// BasicBlock.Index. Use this after any pass that may delete blocks. |
| 513 |
func (f *Function) removeNilBlocks() { |
| 514 |
j := 0 |
| 515 |
for _, b := range f.Blocks { |
| 516 |
if b != nil { |
| 517 |
b.Index = j |
| 518 |
f.Blocks[j] = b |
| 519 |
j++ |
| 520 |
} |
| 521 |
} |
| 522 |
// Nil out f.Blocks[j:] to aid GC. |
| 523 |
for i := j; i < len(f.Blocks); i++ { |
| 524 |
f.Blocks[i] = nil |
| 525 |
} |
| 526 |
f.Blocks = f.Blocks[:j] |
| 527 |
} |
| 528 |
|
| 529 |
// SetDebugMode sets the debug mode for package pkg. If true, all its |
| 530 |
// functions will include full debug info. This greatly increases the |
| 531 |
// size of the instruction stream, and causes Functions to depend upon |
| 532 |
// the ASTs, potentially keeping them live in memory for longer. |
| 533 |
func (pkg *Package) SetDebugMode(debug bool) { |
| 534 |
pkg.debug = debug |
| 535 |
} |
| 536 |
|
| 537 |
// debugInfo reports whether debug info is wanted for this function. |
| 538 |
func (f *Function) debugInfo() bool { |
| 539 |
// debug info for instantiations follows the debug info of their origin. |
| 540 |
p := f.declaredPackage() |
| 541 |
return p != nil && p.debug |
| 542 |
} |
| 543 |
|
| 544 |
// lookup returns the address of the named variable identified by obj |
| 545 |
// that is local to function f or one of its enclosing functions. |
| 546 |
// If escaping, the reference comes from a potentially escaping pointer |
| 547 |
// expression and the referent must be heap-allocated. |
| 548 |
// We assume the referent is a *Alloc or *Phi. |
| 549 |
// (The only Phis at this stage are those created directly by go1.22 "for" loops.) |
| 550 |
func (f *Function) lookup(obj *types.Var, escaping bool) Value { |
| 551 |
if v, ok := f.vars[obj]; ok { |
| 552 |
if escaping { |
| 553 |
switch v := v.(type) { |
| 554 |
case *Alloc: |
| 555 |
v.Heap = true |
| 556 |
case *Phi: |
| 557 |
for _, edge := range v.Edges { |
| 558 |
if alloc, ok := edge.(*Alloc); ok { |
| 559 |
alloc.Heap = true |
| 560 |
} |
| 561 |
} |
| 562 |
} |
| 563 |
} |
| 564 |
return v // function-local var (address) |
| 565 |
} |
| 566 |
|
| 567 |
// Definition must be in an enclosing function; |
| 568 |
// plumb it through intervening closures. |
| 569 |
if f.parent == nil { |
| 570 |
panic("no ir.Value for " + obj.String()) |
| 571 |
} |
| 572 |
outer := f.parent.lookup(obj, true) // escaping |
| 573 |
v := &FreeVar{ |
| 574 |
name: obj.Name(), |
| 575 |
typ: outer.Type(), |
| 576 |
outer: outer, |
| 577 |
parent: f, |
| 578 |
} |
| 579 |
f.vars[obj] = v |
| 580 |
f.FreeVars = append(f.FreeVars, v) |
| 581 |
return v |
| 582 |
} |
| 583 |
|
| 584 |
// emit emits the specified instruction to function f. |
| 585 |
func (f *Function) emit(instr Instruction, source ast.Node) Value { |
| 586 |
return f.currentBlock.emit(instr, source) |
| 587 |
} |
| 588 |
|
| 589 |
// RelString returns the full name of this function, qualified by |
| 590 |
// package name, receiver type, etc. |
| 591 |
// |
| 592 |
// The specific formatting rules are not guaranteed and may change. |
| 593 |
// |
| 594 |
// Examples: |
| 595 |
// |
| 596 |
// "math.IsNaN" // a package-level function |
| 597 |
// "(*bytes.Buffer).Bytes" // a declared method or a wrapper |
| 598 |
// "(*bytes.Buffer).Bytes$thunk" // thunk (func wrapping method; receiver is param 0) |
| 599 |
// "(*bytes.Buffer).Bytes$bound" // bound (func wrapping method; receiver supplied by closure) |
| 600 |
// "main.main$1" // an anonymous function in main |
| 601 |
// "main.init#1" // a declared init function |
| 602 |
// "main.init" // the synthesized package initializer |
| 603 |
// |
| 604 |
// When these functions are referred to from within the same package |
| 605 |
// (i.e. from == f.Pkg.Object), they are rendered without the package path. |
| 606 |
// For example: "IsNaN", "(*Buffer).Bytes", etc. |
| 607 |
// |
| 608 |
// All non-synthetic functions have distinct package-qualified names. |
| 609 |
// (But two methods may have the same name "(T).f" if one is a synthetic |
| 610 |
// wrapper promoting a non-exported method "f" from another package; in |
| 611 |
// that case, the strings are equal but the identifiers "f" are distinct.) |
| 612 |
func (f *Function) RelString(from *types.Package) string { |
| 613 |
// Anonymous? |
| 614 |
if f.parent != nil { |
| 615 |
// An anonymous function's Name() looks like "parentName$1", |
| 616 |
// but its String() should include the type/package/etc. |
| 617 |
parent := f.parent.RelString(from) |
| 618 |
for i, anon := range f.parent.AnonFuncs { |
| 619 |
if anon == f { |
| 620 |
return fmt.Sprintf("%s$%d", parent, 1+i) |
| 621 |
} |
| 622 |
} |
| 623 |
|
| 624 |
return f.name // should never happen |
| 625 |
} |
| 626 |
|
| 627 |
// Method (declared or wrapper)? |
| 628 |
if recv := f.Signature.Recv(); recv != nil { |
| 629 |
return f.relMethod(from, recv.Type()) |
| 630 |
} |
| 631 |
|
| 632 |
// Thunk? |
| 633 |
if f.method != nil { |
| 634 |
return f.relMethod(from, f.method.recv) |
| 635 |
} |
| 636 |
|
| 637 |
// Bound? |
| 638 |
if len(f.FreeVars) == 1 && strings.HasSuffix(f.name, "$bound") { |
| 639 |
return f.relMethod(from, f.FreeVars[0].Type()) |
| 640 |
} |
| 641 |
|
| 642 |
// Package-level function? |
| 643 |
// Prefix with package name for cross-package references only. |
| 644 |
if p := f.relPkg(); p != nil && p != from { |
| 645 |
return fmt.Sprintf("%s.%s", p.Path(), f.name) |
| 646 |
} |
| 647 |
|
| 648 |
// Unknown. |
| 649 |
return f.name |
| 650 |
} |
| 651 |
|
| 652 |
func (f *Function) relMethod(from *types.Package, recv types.Type) string { |
| 653 |
return fmt.Sprintf("(%s).%s", relType(recv, from), f.name) |
| 654 |
} |
| 655 |
|
| 656 |
// writeSignature writes to buf the signature sig in declaration syntax. |
| 657 |
func writeSignature(buf *bytes.Buffer, from *types.Package, name string, sig *types.Signature) { |
| 658 |
buf.WriteString("func ") |
| 659 |
if recv := sig.Recv(); recv != nil { |
| 660 |
buf.WriteString("(") |
| 661 |
if name := recv.Name(); name != "" { |
| 662 |
buf.WriteString(name) |
| 663 |
buf.WriteString(" ") |
| 664 |
} |
| 665 |
types.WriteType(buf, recv.Type(), types.RelativeTo(from)) |
| 666 |
buf.WriteString(") ") |
| 667 |
} |
| 668 |
buf.WriteString(name) |
| 669 |
types.WriteSignature(buf, sig, types.RelativeTo(from)) |
| 670 |
} |
| 671 |
|
| 672 |
// declaredPackage returns the package fn is declared in or nil if the |
| 673 |
// function is not declared in a package. |
| 674 |
func (fn *Function) declaredPackage() *Package { |
| 675 |
switch { |
| 676 |
case fn.Pkg != nil: |
| 677 |
return fn.Pkg // non-generic function (does that follow??) |
| 678 |
case fn.topLevelOrigin != nil: |
| 679 |
return fn.topLevelOrigin.Pkg // instance of a named generic function |
| 680 |
case fn.parent != nil: |
| 681 |
return fn.parent.declaredPackage() // instance of an anonymous [generic] function |
| 682 |
default: |
| 683 |
return nil // function is not declared in a package, e.g. a wrapper. |
| 684 |
} |
| 685 |
} |
| 686 |
|
| 687 |
// relPkg returns types.Package fn is printed in relationship to. |
| 688 |
func (fn *Function) relPkg() *types.Package { |
| 689 |
if p := fn.declaredPackage(); p != nil { |
| 690 |
return p.Pkg |
| 691 |
} |
| 692 |
return nil |
| 693 |
} |
| 694 |
|
| 695 |
var _ io.WriterTo = (*Function)(nil) // *Function implements io.Writer |
| 696 |
|
| 697 |
func (f *Function) WriteTo(w io.Writer) (int64, error) { |
| 698 |
var buf bytes.Buffer |
| 699 |
WriteFunction(&buf, f) |
| 700 |
n, err := w.Write(buf.Bytes()) |
| 701 |
return int64(n), err |
| 702 |
} |
| 703 |
|
| 704 |
// WriteFunction writes to buf a human-readable "disassembly" of f. |
| 705 |
func WriteFunction(buf *bytes.Buffer, f *Function) { |
| 706 |
fmt.Fprintf(buf, "# Name: %s\n", f.String()) |
| 707 |
if f.Pkg != nil { |
| 708 |
fmt.Fprintf(buf, "# Package: %s\n", f.Pkg.Pkg.Path()) |
| 709 |
} |
| 710 |
if syn := f.Synthetic; syn != "" { |
| 711 |
fmt.Fprintln(buf, "# Synthetic:", syn) |
| 712 |
} |
| 713 |
if pos := f.Pos(); pos.IsValid() { |
| 714 |
fmt.Fprintf(buf, "# Location: %s\n", f.Prog.Fset.Position(pos)) |
| 715 |
} |
| 716 |
|
| 717 |
if f.parent != nil { |
| 718 |
fmt.Fprintf(buf, "# Parent: %s\n", f.parent.Name()) |
| 719 |
} |
| 720 |
|
| 721 |
from := f.relPkg() |
| 722 |
|
| 723 |
// NB. column calculations are confused by non-ASCII |
| 724 |
// characters |
| 725 |
const punchcard = 80 // for old time's sake. |
| 726 |
const padding = " " |
| 727 |
|
| 728 |
if f.FreeVars != nil { |
| 729 |
buf.WriteString("# Free variables:\n") |
| 730 |
for i, fv := range f.FreeVars { |
| 731 |
fmt.Fprintf(buf, "# % 3d:%s%s %s\n", i, padding, fv.Name(), relType(fv.Type(), from)) |
| 732 |
} |
| 733 |
} |
| 734 |
|
| 735 |
if len(f.Locals) > 0 { |
| 736 |
buf.WriteString("# Locals:\n") |
| 737 |
for i, l := range f.Locals { |
| 738 |
fmt.Fprintf(buf, "# % 3d:%s%s %s\n", i, padding, l.Name(), relType(deref(l.Type()), from)) |
| 739 |
} |
| 740 |
} |
| 741 |
writeSignature(buf, from, f.Name(), f.Signature) |
| 742 |
buf.WriteString(":\n") |
| 743 |
|
| 744 |
if f.Blocks == nil { |
| 745 |
buf.WriteString(padding) |
| 746 |
buf.WriteString("(external)\n") |
| 747 |
} |
| 748 |
|
| 749 |
for _, b := range f.Blocks { |
| 750 |
if b == nil { |
| 751 |
// Corrupt CFG. |
| 752 |
fmt.Fprintf(buf, ".nil:\n") |
| 753 |
continue |
| 754 |
} |
| 755 |
n, _ := fmt.Fprintf(buf, "%d:", b.Index) |
| 756 |
// (|predecessors|, |successors|, immediate dominator) |
| 757 |
bmsg := fmt.Sprintf("%s P:%d S:%d", b.Comment, len(b.Preds), len(b.Succs)) |
| 758 |
if b.Idom() != nil { |
| 759 |
bmsg = fmt.Sprintf("%s idom:%d", bmsg, b.Idom().Index) |
| 760 |
} |
| 761 |
fmt.Fprintf(buf, "%*s%s\n", punchcard-1-n-len(bmsg), "", bmsg) |
| 762 |
|
| 763 |
if false { // CFG debugging |
| 764 |
fmt.Fprintf(buf, "%s# CFG: %s --> %s --> %s\n", padding, b.Preds, b, b.Succs) |
| 765 |
} |
| 766 |
for _, instr := range b.Instrs { |
| 767 |
buf.WriteString(padding) |
| 768 |
switch v := instr.(type) { |
| 769 |
case Value: |
| 770 |
l := punchcard - len(padding) |
| 771 |
// Left-align the instruction. |
| 772 |
if name := v.Name(); name != "" { |
| 773 |
n, _ := fmt.Fprintf(buf, "%s = ", name) |
| 774 |
l -= n |
| 775 |
} |
| 776 |
n, _ := buf.WriteString(instr.String()) |
| 777 |
l -= n |
| 778 |
// Right-align the type if there's space. |
| 779 |
if t := v.Type(); t != nil { |
| 780 |
buf.WriteByte(' ') |
| 781 |
ts := relType(t, from) |
| 782 |
l -= len(ts) + len(" ") // (spaces before and after type) |
| 783 |
if l > 0 { |
| 784 |
fmt.Fprintf(buf, "%*s", l, "") |
| 785 |
} |
| 786 |
buf.WriteString(ts) |
| 787 |
} |
| 788 |
case nil: |
| 789 |
// Be robust against bad transforms. |
| 790 |
buf.WriteString("<deleted>") |
| 791 |
default: |
| 792 |
buf.WriteString(instr.String()) |
| 793 |
} |
| 794 |
// -mode=S: show line numbers |
| 795 |
if f.Prog.mode&LogSource != 0 { |
| 796 |
if pos := instr.Pos(); pos.IsValid() { |
| 797 |
fmt.Fprintf(buf, " L%d", f.Prog.Fset.Position(pos).Line) |
| 798 |
} |
| 799 |
} |
| 800 |
buf.WriteString("\n") |
| 801 |
} |
| 802 |
} |
| 803 |
buf.WriteString("\n") |
| 804 |
} |
| 805 |
|
| 806 |
// newBasicBlock adds to f a new basic block and returns it. It does |
| 807 |
// not automatically become the current block for subsequent calls to emit. |
| 808 |
// comment is an optional string for more readable debugging output. |
| 809 |
func (f *Function) newBasicBlock(comment string) *BasicBlock { |
| 810 |
b := &BasicBlock{ |
| 811 |
Index: len(f.Blocks), |
| 812 |
Comment: comment, |
| 813 |
parent: f, |
| 814 |
} |
| 815 |
b.Succs = b.succs2[:0] |
| 816 |
f.Blocks = append(f.Blocks, b) |
| 817 |
return b |
| 818 |
} |
| 819 |
|
| 820 |
// NewFunction returns a new synthetic Function instance belonging to |
| 821 |
// prog, with its name and signature fields set as specified. |
| 822 |
// |
| 823 |
// The caller is responsible for initializing the remaining fields of |
| 824 |
// the function object, e.g. Pkg, Params, Blocks. |
| 825 |
// |
| 826 |
// It is practically impossible for clients to construct well-formed |
| 827 |
// IR functions/packages/programs directly, so we assume this is the |
| 828 |
// job of the Builder alone. NewFunction exists to provide clients a |
| 829 |
// little flexibility. For example, analysis tools may wish to |
| 830 |
// construct fake Functions for the root of the callgraph, a fake |
| 831 |
// "reflect" package, etc. |
| 832 |
// |
| 833 |
// TODO(adonovan): think harder about the API here. |
| 834 |
func (prog *Program) NewFunction(name string, sig *types.Signature, provenance string) *Function { |
| 835 |
return &Function{Prog: prog, name: name, Signature: sig, Synthetic: provenance} |
| 836 |
} |
| 837 |
|
| 838 |
//lint:ignore U1000 we may make use of this for functions loaded from export data |
| 839 |
type extentNode [2]token.Pos |
| 840 |
|
| 841 |
func (n extentNode) Pos() token.Pos { return n[0] } |
| 842 |
func (n extentNode) End() token.Pos { return n[1] } |
| 843 |
|
| 844 |
func killInstruction(instr Instruction) { |
| 845 |
ops := instr.Operands(nil) |
| 846 |
for _, op := range ops { |
| 847 |
if refs := (*op).Referrers(); refs != nil { |
| 848 |
*refs = removeInstr(*refs, instr) |
| 849 |
} |
| 850 |
} |
| 851 |
} |
| 852 |
|
| 853 |
// Syntax returns the function's syntax (*ast.Func{Decl,Lit}) |
| 854 |
// if it was produced from syntax or an *ast.RangeStmt if |
| 855 |
// it is a range-over-func yield function. |
| 856 |
func (f *Function) Syntax() ast.Node { return f.syntax } |
| 857 |
|
| 858 |
// identVar returns the variable defined by id. |
| 859 |
func identVar(fn *Function, id *ast.Ident) *types.Var { |
| 860 |
return fn.info.Defs[id].(*types.Var) |
| 861 |
} |
| 862 |
|
| 863 |
// unique returns a unique positive int within the source tree of f. |
| 864 |
// The source tree of f includes all of f's ancestors by parent and all |
| 865 |
// of the AnonFuncs contained within these. |
| 866 |
func unique(f *Function) int64 { |
| 867 |
f.uniq++ |
| 868 |
return f.uniq |
| 869 |
} |
| 870 |
|
| 871 |
// exit is a change of control flow going from a range-over-func |
| 872 |
// yield function to an ancestor function caused by a break, continue, |
| 873 |
// goto, or return statement. |
| 874 |
// |
| 875 |
// There are 3 types of exits: |
| 876 |
// * return from the source function (from ReturnStmt), |
| 877 |
// * jump to a block (from break and continue statements [labelled/unlabelled]), |
| 878 |
// * go to a label (from goto statements). |
| 879 |
// |
| 880 |
// As the builder does one pass over the ast, it is unclear whether |
| 881 |
// a forward goto statement will leave a range-over-func body. |
| 882 |
// The function being exited to is unresolved until the end |
| 883 |
// of building the range-over-func body. |
| 884 |
type exit struct { |
| 885 |
id int64 // unique value for exit within from and to |
| 886 |
from *Function // the function the exit starts from |
| 887 |
to *Function // the function being exited to (nil if unresolved) |
| 888 |
source ast.Node |
| 889 |
|
| 890 |
block *BasicBlock // basic block within to being jumped to. |
| 891 |
label *types.Label // forward label being jumped to via goto. |
| 892 |
// block == nil && label == nil => return |
| 893 |
} |
| 894 |
|
| 895 |
// storeVar emits to function f code to store a value v to a *types.Var x. |
| 896 |
func storeVar(f *Function, x *types.Var, v Value, source ast.Node) { |
| 897 |
emitStore(f, f.lookup(x, true), v, source) |
| 898 |
} |
| 899 |
|
| 900 |
// labelExit creates a new exit to a yield fn to exit the function using a label. |
| 901 |
func labelExit(fn *Function, label *types.Label, source ast.Node) *exit { |
| 902 |
e := &exit{ |
| 903 |
id: unique(fn), |
| 904 |
from: fn, |
| 905 |
to: nil, |
| 906 |
source: source, |
| 907 |
label: label, |
| 908 |
} |
| 909 |
fn.exits = append(fn.exits, e) |
| 910 |
return e |
| 911 |
} |
| 912 |
|
| 913 |
// blockExit creates a new exit to a yield fn that jumps to a basic block. |
| 914 |
func blockExit(fn *Function, block *BasicBlock, source ast.Node) *exit { |
| 915 |
e := &exit{ |
| 916 |
id: unique(fn), |
| 917 |
from: fn, |
| 918 |
to: block.parent, |
| 919 |
source: source, |
| 920 |
block: block, |
| 921 |
} |
| 922 |
fn.exits = append(fn.exits, e) |
| 923 |
return e |
| 924 |
} |
| 925 |
|
| 926 |
// returnExit creates a new exit to a yield fn that returns to the source function. |
| 927 |
func returnExit(fn *Function, source ast.Node) *exit { |
| 928 |
e := &exit{ |
| 929 |
id: unique(fn), |
| 930 |
from: fn, |
| 931 |
to: fn.source, |
| 932 |
source: source, |
| 933 |
} |
| 934 |
fn.exits = append(fn.exits, e) |
| 935 |
return e |
| 936 |
} |