Files
llgo/cl/compile.go

498 lines
12 KiB
Go
Raw Normal View History

2023-12-10 11:24:08 +08:00
/*
2024-04-20 15:58:34 +08:00
* Copyright (c) 2024 The GoPlus Authors (goplus.org). All rights reserved.
2023-12-10 11:24:08 +08:00
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cl
2024-04-20 15:58:34 +08:00
import (
2024-04-20 17:31:49 +08:00
"fmt"
2024-04-22 15:09:08 +08:00
"go/ast"
2024-04-25 14:25:14 +08:00
"go/constant"
2024-04-22 21:16:43 +08:00
"go/token"
2024-04-22 20:09:23 +08:00
"go/types"
2024-04-21 16:04:05 +08:00
"log"
2024-04-21 17:54:51 +08:00
"os"
2024-04-20 15:58:34 +08:00
"sort"
2024-04-26 02:40:36 +08:00
"strings"
2024-04-20 15:58:34 +08:00
llssa "github.com/goplus/llgo/ssa"
"golang.org/x/tools/go/ssa"
)
2024-04-21 16:04:05 +08:00
// -----------------------------------------------------------------------------
type dbgFlags = int
const (
DbgFlagInstruction dbgFlags = 1 << iota
2024-04-21 17:54:51 +08:00
DbgFlagGoSSA
2024-04-21 16:04:05 +08:00
2024-04-21 17:54:51 +08:00
DbgFlagAll = DbgFlagInstruction | DbgFlagGoSSA
2024-04-21 16:04:05 +08:00
)
var (
debugInstr bool
2024-04-21 17:54:51 +08:00
debugGoSSA bool
2024-04-21 16:04:05 +08:00
)
// SetDebug sets debug flags.
func SetDebug(dbgFlags dbgFlags) {
debugInstr = (dbgFlags & DbgFlagInstruction) != 0
2024-04-21 17:54:51 +08:00
debugGoSSA = (dbgFlags & DbgFlagGoSSA) != 0
}
// -----------------------------------------------------------------------------
const (
fnNormal = iota
fnHasVArg
2024-04-26 02:40:36 +08:00
fnIgnore
2024-04-21 17:54:51 +08:00
)
func funcKind(vfn ssa.Value) int {
if fn, ok := vfn.(*ssa.Function); ok && fn.Signature.Recv() == nil {
params := fn.Signature.Params()
n := params.Len()
2024-04-21 17:54:51 +08:00
if n == 0 {
2024-04-26 02:40:36 +08:00
if fn.Name() == "init" && ignorePkgInit(fn.Pkg.Pkg.Path()) {
return fnIgnore
2024-04-21 17:54:51 +08:00
}
} else {
last := params.At(n - 1)
2024-04-21 17:54:51 +08:00
if last.Name() == llssa.NameValist {
return fnHasVArg
}
}
}
return fnNormal
2024-04-20 15:58:34 +08:00
}
2024-04-26 02:40:36 +08:00
func ignorePkgInit(pkgPath string) bool {
switch pkgPath {
case "unsafe", "syscall", "runtime/cgo":
return true
}
return false
}
2024-04-26 04:44:49 +08:00
func ignoreName(name string) bool {
2024-04-26 02:40:36 +08:00
/* TODO(xsw): confirm this is not needed more
if name == "unsafe.init" {
return true
}
*/
2024-04-26 04:44:49 +08:00
if strings.HasPrefix(name, "internal/") || strings.HasPrefix(name, "crypto/") ||
strings.HasPrefix(name, "arena.") || strings.HasPrefix(name, "maps.") ||
strings.HasPrefix(name, "time.") || strings.HasPrefix(name, "syscall.") ||
strings.HasPrefix(name, "os.") || strings.HasPrefix(name, "plugin.") ||
strings.HasPrefix(name, "reflect.") || strings.HasPrefix(name, "errors.") {
return true // TODO(xsw)
2024-04-26 02:40:36 +08:00
}
2024-04-26 04:44:49 +08:00
return inPkg(name, "runtime") || inPkg(name, "sync")
}
func inPkg(name, pkg string) bool {
if len(name) > len(pkg) && strings.HasPrefix(name, pkg) {
c := name[len(pkg)]
return c == '.' || c == '/'
2024-04-26 02:40:36 +08:00
}
return false
}
2024-04-20 17:31:49 +08:00
// -----------------------------------------------------------------------------
2024-04-22 20:09:23 +08:00
type none = struct{}
2024-04-20 17:31:49 +08:00
type instrAndValue interface {
ssa.Instruction
ssa.Value
}
2024-04-20 15:58:34 +08:00
type context struct {
2024-04-22 20:09:23 +08:00
prog llssa.Program
pkg llssa.Package
fn llssa.Function
fset *token.FileSet
2024-04-25 21:44:23 +08:00
goProg *ssa.Program
2024-04-23 01:16:31 +08:00
goTyps *types.Package
2024-04-22 20:09:23 +08:00
goPkg *ssa.Package
2024-04-25 14:25:14 +08:00
link map[string]string // pkgPath.nameInPkg => linkname
loaded map[*types.Package]none // loaded packages
bvals map[ssa.Value]llssa.Expr // block values
vargs map[*ssa.Alloc][]llssa.Expr // varargs
2024-04-22 20:09:23 +08:00
inits []func()
}
2024-04-25 21:44:23 +08:00
func (p *context) compileType(pkg llssa.Package, t *ssa.Type) {
tn := t.Object().(*types.TypeName)
2024-04-26 04:44:49 +08:00
tnName := tn.Name()
2024-04-25 21:44:23 +08:00
typ := tn.Type()
2024-04-27 07:47:10 +08:00
name := llssa.FullName(tn.Pkg(), tnName)
2024-04-26 04:44:49 +08:00
if ignoreName(name) {
return
}
2024-04-25 21:44:23 +08:00
if debugInstr {
log.Println("==> NewType", name, typ)
}
2024-04-26 00:31:02 +08:00
p.compileMethods(pkg, typ)
p.compileMethods(pkg, types.NewPointer(typ))
}
func (p *context) compileMethods(pkg llssa.Package, typ types.Type) {
2024-04-25 21:44:23 +08:00
prog := p.goProg
mthds := prog.MethodSets.MethodSet(typ)
for i, n := 0, mthds.Len(); i < n; i++ {
mthd := mthds.At(i)
2024-04-26 04:44:49 +08:00
if ssaMthd := prog.MethodValue(mthd); ssaMthd != nil {
p.compileFunc(pkg, mthd.Obj().Pkg(), ssaMthd)
}
2024-04-25 21:44:23 +08:00
}
2024-04-20 15:58:34 +08:00
}
// Global variable.
2024-04-21 15:12:57 +08:00
func (p *context) compileGlobal(pkg llssa.Package, gbl *ssa.Global) {
2024-04-23 01:16:31 +08:00
typ := gbl.Type()
2024-04-27 07:47:10 +08:00
name := llssa.FullName(gbl.Pkg.Pkg, gbl.Name())
2024-04-26 04:44:49 +08:00
if ignoreName(name) || checkCgo(gbl.Name()) {
return
}
2024-04-21 16:04:05 +08:00
if debugInstr {
log.Println("==> NewVar", name, typ)
}
g := pkg.NewVar(name, typ)
2024-04-21 00:22:39 +08:00
g.Init(p.prog.Null(g.Type))
2024-04-20 15:58:34 +08:00
}
2024-04-26 00:31:02 +08:00
func (p *context) compileFunc(pkg llssa.Package, pkgTypes *types.Package, f *ssa.Function) {
sig := f.Signature
2024-04-26 04:44:49 +08:00
name, ok := p.funcName(pkgTypes, f, true)
if !ok { // ignored
2024-04-26 02:40:36 +08:00
return
}
2024-04-26 04:44:49 +08:00
if debugInstr {
2024-04-26 05:39:15 +08:00
log.Println("==> NewFunc", name, "type:", sig.Recv(), sig)
2024-04-26 04:44:49 +08:00
}
2024-04-26 00:31:02 +08:00
fn := pkg.NewFunc(name, sig)
2024-04-21 15:12:57 +08:00
p.inits = append(p.inits, func() {
p.fn = fn
defer func() {
p.fn = nil
}()
nblk := len(f.Blocks)
if nblk == 0 { // external function
return
}
2024-04-21 17:54:51 +08:00
if debugGoSSA {
f.WriteTo(os.Stderr)
}
2024-04-21 16:04:05 +08:00
if debugInstr {
log.Println("==> FuncBody", name)
}
2024-04-21 15:12:57 +08:00
fn.MakeBlocks(nblk)
b := fn.NewBuilder()
2024-04-22 00:03:49 +08:00
for i, block := range f.Blocks {
2024-04-22 15:09:08 +08:00
p.compileBlock(b, block, i == 0 && name == "main")
2024-04-21 15:12:57 +08:00
}
})
2024-04-20 17:31:49 +08:00
}
2024-04-20 15:58:34 +08:00
2024-04-22 00:03:49 +08:00
func (p *context) compileBlock(b llssa.Builder, block *ssa.BasicBlock, doInit bool) llssa.BasicBlock {
2024-04-20 22:05:45 +08:00
ret := p.fn.Block(block.Index)
b.SetBlock(ret)
2024-04-20 23:15:10 +08:00
p.bvals = make(map[ssa.Value]llssa.Expr)
2024-04-22 00:03:49 +08:00
if doInit {
2024-04-22 15:09:08 +08:00
fn := p.pkg.FuncOf("main.init")
2024-04-22 00:03:49 +08:00
b.Call(fn.Expr)
}
2024-04-20 17:31:49 +08:00
for _, instr := range block.Instrs {
p.compileInstr(b, instr)
2024-04-20 15:58:34 +08:00
}
2024-04-20 22:05:45 +08:00
return ret
2024-04-20 15:58:34 +08:00
}
2024-04-25 14:25:14 +08:00
func isAny(t types.Type) bool {
if t, ok := t.(*types.Interface); ok {
return t.Empty()
}
return false
}
func intVal(v ssa.Value) int64 {
if c, ok := v.(*ssa.Const); ok {
if iv, exact := constant.Int64Val(c.Value); exact {
return iv
}
}
panic("intVal: ssa.Value is not a const int")
}
func (p *context) isVArgs(vx ssa.Value) (ret []llssa.Expr, ok bool) {
if va, vok := vx.(*ssa.Alloc); vok {
ret, ok = p.vargs[va] // varargs: this is a varargs index
}
return
}
func (p *context) checkVArgs(v *ssa.Alloc, t types.Type) bool {
if v.Comment == "varargs" { // this is a varargs allocation
if t, ok := t.(*types.Pointer); ok {
if arr, ok := t.Elem().(*types.Array); ok {
if isAny(arr.Elem()) {
p.vargs[v] = make([]llssa.Expr, arr.Len())
return true
}
}
}
}
return false
}
2024-04-20 22:16:28 +08:00
func (p *context) compileInstrAndValue(b llssa.Builder, iv instrAndValue) (ret llssa.Expr) {
2024-04-20 23:15:10 +08:00
if v, ok := p.bvals[iv]; ok {
2024-04-20 22:16:28 +08:00
return v
}
2024-04-20 17:31:49 +08:00
switch v := iv.(type) {
2024-04-20 23:15:10 +08:00
case *ssa.Call:
2024-04-21 16:04:05 +08:00
call := v.Call
2024-04-26 00:31:02 +08:00
cv := call.Value
kind := funcKind(cv)
2024-04-26 02:40:36 +08:00
if kind == fnIgnore {
2024-04-21 17:54:51 +08:00
return
}
if debugGoSSA {
2024-04-26 00:31:02 +08:00
log.Println(">>> Call", cv, call.Args)
}
if builtin, ok := cv.(*ssa.Builtin); ok {
fn := builtin.Name()
if fn == "ssa:wrapnilchk" { // TODO(xsw): check nil ptr
arg := call.Args[0]
ret = p.compileValue(b, arg)
// log.Println("wrapnilchk:", ret.TypeOf())
} else {
args := p.compileValues(b, call.Args, kind)
ret = b.BuiltinCall(fn, args...)
}
} else {
fn := p.compileValue(b, cv)
args := p.compileValues(b, call.Args, kind)
ret = b.Call(fn, args...)
2024-04-21 17:54:51 +08:00
}
2024-04-20 23:15:10 +08:00
case *ssa.BinOp:
x := p.compileValue(b, v.X)
y := p.compileValue(b, v.Y)
ret = b.BinOp(v.Op, x, y)
2024-04-20 17:31:49 +08:00
case *ssa.UnOp:
x := p.compileValue(b, v.X)
2024-04-20 22:16:28 +08:00
ret = b.UnOp(v.Op, x)
2024-04-26 00:31:02 +08:00
case *ssa.ChangeType:
t := v.Type()
x := p.compileValue(b, v.X)
ret = b.ChangeType(p.prog.Type(t), x)
2024-04-27 07:47:10 +08:00
case *ssa.FieldAddr:
x := p.compileValue(b, v.X)
ret = b.FieldAddr(x, v.Field)
2024-04-21 15:12:57 +08:00
case *ssa.IndexAddr:
2024-04-25 14:25:14 +08:00
vx := v.X
if _, ok := p.isVArgs(vx); ok { // varargs: this is a varargs index
return
}
x := p.compileValue(b, vx)
2024-04-21 15:12:57 +08:00
idx := p.compileValue(b, v.Index)
ret = b.IndexAddr(x, idx)
2024-04-25 14:25:14 +08:00
case *ssa.Slice:
vx := v.X
if _, ok := p.isVArgs(vx); ok { // varargs: this is a varargs slice
return
}
panic("todo")
2024-04-21 15:12:57 +08:00
case *ssa.Alloc:
t := v.Type()
2024-04-25 14:25:14 +08:00
if p.checkVArgs(v, t) { // varargs: this is a varargs allocation
return
}
2024-04-21 15:12:57 +08:00
ret = b.Alloc(p.prog.Type(t), v.Heap)
2024-04-25 14:25:14 +08:00
case *ssa.MakeInterface:
t := v.Type()
if isAny(t) { // varargs: don't need to convert an expr to any
return
}
panic("todo")
2024-04-27 17:39:25 +08:00
case *ssa.TypeAssert:
x := p.compileValue(b, v.X)
ret = b.TypeAssert(x, p.prog.Type(v.AssertedType), v.CommaOk)
2024-04-20 22:16:28 +08:00
default:
panic(fmt.Sprintf("compileInstrAndValue: unknown instr - %T\n", iv))
2024-04-20 17:31:49 +08:00
}
2024-04-20 23:15:10 +08:00
p.bvals[iv] = ret
2024-04-20 22:16:28 +08:00
return ret
2023-12-10 13:43:44 +08:00
}
2024-04-20 17:31:49 +08:00
func (p *context) compileInstr(b llssa.Builder, instr ssa.Instruction) {
if iv, ok := instr.(instrAndValue); ok {
p.compileInstrAndValue(b, iv)
return
}
switch v := instr.(type) {
2024-04-20 22:05:45 +08:00
case *ssa.Store:
2024-04-25 14:25:14 +08:00
va := v.Addr
if va, ok := va.(*ssa.IndexAddr); ok {
if args, ok := p.isVArgs(va.X); ok { // varargs: this is a varargs store
idx := intVal(va.Index)
val := v.Val
if vi, ok := val.(*ssa.MakeInterface); ok {
val = vi.X
}
args[idx] = p.compileValue(b, val)
return
}
}
ptr := p.compileValue(b, va)
2024-04-20 22:05:45 +08:00
val := p.compileValue(b, v.Val)
b.Store(ptr, val)
case *ssa.Jump:
fn := p.fn
succs := v.Block().Succs
jmpb := fn.Block(succs[0].Index)
b.Jump(jmpb)
case *ssa.Return:
var results []llssa.Expr
if n := len(v.Results); n > 0 {
results = make([]llssa.Expr, n)
for i, r := range v.Results {
results[i] = p.compileValue(b, r)
}
}
b.Return(results...)
2024-04-20 17:31:49 +08:00
case *ssa.If:
2024-04-20 22:05:45 +08:00
fn := p.fn
cond := p.compileValue(b, v.Cond)
succs := v.Block().Succs
thenb := fn.Block(succs[0].Index)
elseb := fn.Block(succs[1].Index)
b.If(cond, thenb, elseb)
default:
panic(fmt.Sprintf("compileInstr: unknown instr - %T\n", instr))
2024-04-20 17:31:49 +08:00
}
2023-12-10 13:43:44 +08:00
}
2024-04-20 22:16:28 +08:00
func (p *context) compileValue(b llssa.Builder, v ssa.Value) llssa.Expr {
2024-04-20 22:05:45 +08:00
if iv, ok := v.(instrAndValue); ok {
2024-04-20 22:16:28 +08:00
return p.compileInstrAndValue(b, iv)
}
switch v := v.(type) {
2024-04-20 23:15:10 +08:00
case *ssa.Parameter:
fn := v.Parent()
for idx, param := range fn.Params {
if param == v {
return p.fn.Param(idx)
}
}
case *ssa.Function:
fn := p.funcOf(v)
2024-04-20 23:15:10 +08:00
return fn.Expr
2024-04-20 22:16:28 +08:00
case *ssa.Global:
2024-04-23 01:16:31 +08:00
g := p.varOf(v)
2024-04-20 22:16:28 +08:00
return g.Expr
case *ssa.Const:
2024-04-21 15:12:57 +08:00
t := v.Type()
return b.Const(v.Value, p.prog.Type(t))
2024-04-20 17:31:49 +08:00
}
2024-04-20 23:15:10 +08:00
panic(fmt.Sprintf("compileValue: unknown value - %T\n", v))
}
2024-04-21 17:54:51 +08:00
func (p *context) compileVArg(ret []llssa.Expr, b llssa.Builder, v ssa.Value) []llssa.Expr {
_ = b
switch v := v.(type) {
2024-04-25 14:25:14 +08:00
case *ssa.Slice: // varargs: this is a varargs slice
if args, ok := p.isVArgs(v.X); ok {
return append(ret, args...)
}
2024-04-21 17:54:51 +08:00
case *ssa.Const:
if v.Value == nil {
return ret
}
}
2024-04-25 14:25:14 +08:00
panic(fmt.Sprintf("compileVArg: unknown value - %T\n", v))
2024-04-21 17:54:51 +08:00
}
func (p *context) compileValues(b llssa.Builder, vals []ssa.Value, hasVArg int) []llssa.Expr {
n := len(vals) - hasVArg
ret := make([]llssa.Expr, n)
for i := 0; i < n; i++ {
ret[i] = p.compileValue(b, vals[i])
}
if hasVArg > 0 {
ret = p.compileVArg(ret, b, vals[n])
2024-04-20 23:15:10 +08:00
}
return ret
2023-12-10 13:43:44 +08:00
}
2024-04-20 17:31:49 +08:00
// -----------------------------------------------------------------------------
2023-12-10 13:43:44 +08:00
2024-04-20 17:31:49 +08:00
// NewPackage compiles a Go package to LLVM IR package.
2024-04-22 20:23:01 +08:00
func NewPackage(prog llssa.Program, pkg *ssa.Package, files []*ast.File) (ret llssa.Package, err error) {
2023-12-10 15:34:42 +08:00
type namedMember struct {
name string
val ssa.Member
}
members := make([]*namedMember, 0, len(pkg.Members))
2023-12-10 15:34:42 +08:00
for name, v := range pkg.Members {
members = append(members, &namedMember{name, v})
}
sort.Slice(members, func(i, j int) bool {
return members[i].name < members[j].name
2023-12-10 15:34:42 +08:00
})
2024-04-25 21:44:23 +08:00
pkgProg := pkg.Prog
2024-04-20 17:31:49 +08:00
pkgTypes := pkg.Pkg
2024-04-27 07:47:10 +08:00
pkgName, pkgPath := pkgTypes.Name(), llssa.PathOf(pkgTypes)
2024-04-25 00:14:02 +08:00
ret = prog.NewPackage(pkgName, pkgPath)
2024-04-20 17:31:49 +08:00
ctx := &context{
2024-04-22 20:09:23 +08:00
prog: prog,
pkg: ret,
2024-04-25 21:44:23 +08:00
fset: pkgProg.Fset,
goProg: pkgProg,
2024-04-23 01:16:31 +08:00
goTyps: pkgTypes,
2024-04-22 20:09:23 +08:00
goPkg: pkg,
link: make(map[string]string),
loaded: make(map[*types.Package]none),
2024-04-25 14:25:14 +08:00
vargs: make(map[*ssa.Alloc][]llssa.Expr),
2024-04-20 17:31:49 +08:00
}
2024-04-25 00:14:02 +08:00
ctx.initFiles(pkgPath, files)
2023-12-10 15:34:42 +08:00
for _, m := range members {
member := m.val
switch member := member.(type) {
case *ssa.Function:
if member.TypeParams() != nil {
// Do not try to build generic (non-instantiated) functions.
continue
}
2024-04-26 00:31:02 +08:00
ctx.compileFunc(ret, member.Pkg.Pkg, member)
2023-12-10 15:34:42 +08:00
case *ssa.Type:
2024-04-20 17:31:49 +08:00
ctx.compileType(ret, member)
2023-12-10 15:34:42 +08:00
case *ssa.Global:
2024-04-20 17:31:49 +08:00
ctx.compileGlobal(ret, member)
2023-12-10 15:34:42 +08:00
}
}
2024-04-21 15:12:57 +08:00
for _, ini := range ctx.inits {
ini()
}
2023-12-11 00:37:09 +08:00
return
}
2024-04-20 17:31:49 +08:00
// -----------------------------------------------------------------------------