TranslateProject/sources/tech/20200619 How to dump the GOSSAFUNC graph for a method.md
2020-06-22 08:56:09 +08:00

4.1 KiB
Raw Blame History

How to dump the GOSSAFUNC graph for a method

The Go compilers SSA backend contains a facility to produce HTML debugging output of the compilation phases. This post covers how to print the SSA output for function and methods.

Lets start with a sample program which contains a function, a value method, and a pointer method:

package main

import (
    "fmt"
)

type Numbers struct {
    vals []int
}

func (n *Numbers) Add(v int) {
    n.vals = append(n.vals, v)
}

func (n Numbers) Average() float64 {
    sum := 0.0
    for _, num := range n.vals {
        sum += float64(num)
    }
    return sum / float64(len(n.vals))
}


func main() {
    var numbers Numbers
    numbers.Add(200)
    numbers.Add(43)
    numbers.Add(-6)
    fmt.Println(numbers.Average())
}

Control of the SSA debugging output is via the GOSSAFUNC environment variable. This variable takes the name of the function to dump. This is not the functions fully qualified name. For func main above the name of the function is main not main.main.

% env GOSSAFUNC=main go build
runtime
dumped SSA to ../../go/src/runtime/ssa.html
t
dumped SSA to ./ssa.html

In this example GOSSAFUNC=main matched both main.main and a function called runtime.main.1 This is a little unfortunate, but in practice probably not a big deal as, if youre performance tuning your code, it wont be in a giant spaghetti blob in func main.

What is more likely is your code will be in a method, so youve probably landed on this post looking for the correct incantation to dump the SSA output for a method.

To print the SSA debug for the pointer method func (n *Numbers) Add, the equivalent function name is(*Numbers).Add:2

% env "GOSSAFUNC=(*Numbers).Add" go build
t
dumped SSA to ./ssa.html

To print the SSA debug for a value method func (n Numbers) Average, the equivalent function name is (*Numbers).Average even though this is a value method:

% env "GOSSAFUNC=(*Numbers).Average" go build
t
dumped SSA to ./ssa.html
  1. If you didnt build Go from source then the path to the runtime package may be read only and you might receive an error. Please dont use the sudo hammer to fix this.
  2. Please pay attention to the shell quoting.
  1. Accidental method value
  2. Never edit a method, always rewrite it
  3. How to find out which Go version built your binary
  4. Declaration scopes in Go

via: https://dave.cheney.net/2020/06/19/how-to-dump-the-gossafunc-graph-for-a-method

作者:Dave Cheney 选题:lujun9972 译者:译者ID 校对:校对者ID

本文由 LCTT 原创编译,Linux中国 荣誉推出