Files
llgo/ssa/package.go

604 lines
14 KiB
Go
Raw Normal View History

2024-04-15 04:00:38 +08:00
/*
* Copyright (c) 2024 The GoPlus Authors (goplus.org). All rights reserved.
*
* 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.
*/
2024-04-15 17:12:30 +08:00
package ssa
2024-04-15 04:00:38 +08:00
import (
2024-05-05 18:48:09 +08:00
"go/token"
2024-04-15 04:00:38 +08:00
"go/types"
2024-04-15 05:48:48 +08:00
"github.com/goplus/llvm"
2024-05-06 00:17:39 +08:00
"golang.org/x/tools/go/types/typeutil"
2024-04-15 04:00:38 +08:00
)
const (
PkgPython = "github.com/goplus/llgo/py"
PkgRuntime = "github.com/goplus/llgo/internal/runtime"
)
2024-04-21 16:04:05 +08:00
// -----------------------------------------------------------------------------
2024-04-21 15:12:57 +08:00
type dbgFlags = int
const (
DbgFlagInstruction dbgFlags = 1 << iota
DbgFlagAll = DbgFlagInstruction
)
var (
debugInstr bool
)
// SetDebug sets debug flags.
func SetDebug(dbgFlags dbgFlags) {
debugInstr = (dbgFlags & DbgFlagInstruction) != 0
}
2024-04-19 00:05:57 +08:00
// -----------------------------------------------------------------------------
2024-04-20 23:57:55 +08:00
// InitFlags is a set of flags for initializing the LLVM library.
2024-04-19 00:05:57 +08:00
type InitFlags int
const (
InitNativeTarget InitFlags = 1 << iota
InitAllTargets
InitAllTargetInfos
InitAllTargetMCs
InitNativeAsmPrinter
InitAllAsmPrinters
InitAllAsmParsers
InitNative = InitNativeTarget | InitNativeAsmPrinter
InitAll = InitAllTargets | InitAllAsmParsers | InitAllAsmPrinters | InitAllTargetInfos | InitAllTargetMCs
)
2024-04-20 23:57:55 +08:00
// Initialize initializes the LLVM library.
2024-04-19 00:05:57 +08:00
func Initialize(flags InitFlags) {
if flags&InitAllTargetInfos != 0 {
llvm.InitializeAllTargetInfos()
}
if flags&InitAllTargets != 0 {
llvm.InitializeAllTargets()
}
if flags&InitAllTargetMCs != 0 {
llvm.InitializeAllTargetMCs()
}
if flags&InitAllAsmParsers != 0 {
llvm.InitializeAllAsmParsers()
}
if flags&InitAllAsmPrinters != 0 {
llvm.InitializeAllAsmPrinters()
}
if flags&InitNativeTarget != 0 {
llvm.InitializeNativeTarget()
}
if flags&InitNativeAsmPrinter != 0 {
llvm.InitializeNativeAsmPrinter()
}
}
// -----------------------------------------------------------------------------
2024-04-18 01:23:01 +08:00
type aProgram struct {
2024-05-05 12:11:51 +08:00
ctx llvm.Context
typs typeutil.Map // rawType -> Type
gocvt goTypes
2024-04-15 17:12:30 +08:00
rt *types.Package
2024-04-27 17:39:25 +08:00
rtget func() *types.Package
2024-04-27 13:57:21 +08:00
py *types.Package
pyget func() *types.Package
2024-04-15 17:12:30 +08:00
target *Target
td llvm.TargetData
2024-04-16 00:43:29 +08:00
// tm llvm.TargetMachine
2024-05-11 12:03:02 +08:00
named map[string]llvm.Type
2024-04-15 04:00:38 +08:00
intType llvm.Type
2024-04-18 15:03:10 +08:00
int1Type llvm.Type
2024-04-15 04:00:38 +08:00
int8Type llvm.Type
int16Type llvm.Type
int32Type llvm.Type
int64Type llvm.Type
2024-04-16 03:05:20 +08:00
voidType llvm.Type
voidPtrTy llvm.Type
2024-04-18 15:03:10 +08:00
2024-05-04 07:47:18 +08:00
rtStringTy llvm.Type
rtIfaceTy llvm.Type
rtSliceTy llvm.Type
rtMapTy llvm.Type
2024-04-27 18:13:16 +08:00
2024-04-28 07:08:01 +08:00
anyTy Type
voidTy Type
2024-05-03 23:10:02 +08:00
voidPtr Type
2024-04-28 07:08:01 +08:00
boolTy Type
cstrTy Type
stringTy Type
2024-04-28 07:08:01 +08:00
uintptrTy Type
intTy Type
f64Ty Type
pyObjPtr Type
pyObjPPtr Type
2024-05-11 23:38:21 +08:00
pyImpTy *types.Signature
2024-05-12 00:24:56 +08:00
callNoArgs *types.Signature
2024-05-11 23:38:21 +08:00
callOneArg *types.Signature
2024-05-12 18:27:23 +08:00
loadPyModS *types.Signature
2024-04-29 00:49:17 +08:00
2024-05-12 15:42:50 +08:00
NeedRuntime bool
NeedPyInit bool
2024-04-15 04:00:38 +08:00
}
2024-04-20 23:57:55 +08:00
// A Program presents a program.
2024-04-18 01:23:01 +08:00
type Program = *aProgram
2024-04-18 01:18:41 +08:00
2024-04-20 23:57:55 +08:00
// NewProgram creates a new program.
2024-04-18 01:18:41 +08:00
func NewProgram(target *Target) Program {
2024-04-15 17:12:30 +08:00
if target == nil {
target = &Target{}
}
2024-04-15 04:00:38 +08:00
ctx := llvm.NewContext()
2024-04-15 17:12:30 +08:00
td := llvm.NewTargetData("") // TODO(xsw): target config
2024-05-03 23:10:02 +08:00
/*
arch := target.GOARCH
if arch == "" {
arch = runtime.GOARCH
}
sizes := types.SizesFor("gc", arch)
// TODO(xsw): Finalize may cause panic, so comment it.
ctx.Finalize()
*/
2024-05-11 12:03:02 +08:00
return &aProgram{ctx: ctx, gocvt: newGoTypes(), target: target, td: td, named: make(map[string]llvm.Type)}
2024-04-15 04:00:38 +08:00
}
// SetPython sets the Python package.
// Its type can be *types.Package or func() *types.Package.
func (p Program) SetPython(py any) {
switch v := py.(type) {
case *types.Package:
p.py = v
case func() *types.Package:
p.pyget = v
}
}
2024-04-27 17:39:25 +08:00
// SetRuntime sets the runtime.
// Its type can be *types.Package or func() *types.Package.
func (p Program) SetRuntime(runtime any) {
switch v := runtime.(type) {
case *types.Package:
p.rt = v
case func() *types.Package:
p.rtget = v
}
2024-04-27 13:57:21 +08:00
}
func (p Program) runtime() *types.Package {
2024-04-27 13:57:21 +08:00
if p.rt == nil {
p.rt = p.rtget()
2024-04-27 13:57:21 +08:00
}
2024-05-12 15:42:50 +08:00
p.NeedRuntime = true
2024-04-27 13:57:21 +08:00
return p.rt
}
func (p Program) python() *types.Package {
if p.py == nil {
p.py = p.pyget()
}
return p.py
}
2024-04-27 18:13:16 +08:00
func (p Program) rtNamed(name string) *types.Named {
2024-05-05 12:11:51 +08:00
t := p.runtime().Scope().Lookup(name).Type().(*types.Named)
t, _ = p.gocvt.cvtNamed(t)
return t
2024-04-27 17:39:25 +08:00
}
func (p Program) pyNamed(name string) *types.Named {
// TODO(xsw): does python type need to convert?
t := p.python().Scope().Lookup(name).Type().(*types.Named)
return t
}
2024-04-27 18:13:16 +08:00
func (p Program) rtType(name string) Type {
2024-05-05 12:11:51 +08:00
return p.rawType(p.rtNamed(name))
2024-04-27 18:13:16 +08:00
}
func (p Program) rtIface() llvm.Type {
if p.rtIfaceTy.IsNil() {
p.rtIfaceTy = p.rtType("Interface").ll
}
return p.rtIfaceTy
}
2024-05-01 07:26:51 +08:00
func (p Program) rtMap() llvm.Type {
if p.rtMapTy.IsNil() {
p.rtMapTy = p.rtType("Map").ll
}
return p.rtMapTy
}
2024-04-27 18:13:16 +08:00
func (p Program) rtSlice() llvm.Type {
if p.rtSliceTy.IsNil() {
p.rtSliceTy = p.rtType("Slice").ll
}
return p.rtSliceTy
}
func (p Program) rtString() llvm.Type {
if p.rtStringTy.IsNil() {
p.rtStringTy = p.rtType("String").ll
}
return p.rtStringTy
}
2024-04-20 23:57:55 +08:00
// NewPackage creates a new package.
2024-04-18 15:03:10 +08:00
func (p Program) NewPackage(name, pkgPath string) Package {
2024-04-15 05:48:48 +08:00
mod := p.ctx.NewModule(pkgPath)
// TODO(xsw): Finalize may cause panic, so comment it.
// mod.Finalize()
2024-04-21 15:12:57 +08:00
gbls := make(map[string]Global)
2024-05-05 18:48:09 +08:00
fns := make(map[string]Function)
stubs := make(map[string]Function)
2024-05-12 18:27:23 +08:00
pyobjs := make(map[string]PyObject)
2024-05-12 11:11:19 +08:00
pymods := make(map[string]Global)
2024-05-12 15:42:50 +08:00
p.NeedRuntime = false
2024-05-12 11:11:19 +08:00
// Don't need reset p.needPyInit here
// p.needPyInit = false
2024-05-12 18:27:23 +08:00
return &aPackage{mod, gbls, fns, stubs, pyobjs, pymods, p}
2024-04-18 01:18:41 +08:00
}
// PyObjectPtrPtr returns the **py.Object type.
func (p Program) PyObjectPtrPtr() Type {
if p.pyObjPPtr == nil {
p.pyObjPPtr = p.Pointer(p.PyObjectPtr())
}
return p.pyObjPPtr
}
// PyObjectPtr returns the *py.Object type.
func (p Program) PyObjectPtr() Type {
if p.pyObjPtr == nil {
objPtr := types.NewPointer(p.pyNamed("Object"))
p.pyObjPtr = p.rawType(objPtr)
}
return p.pyObjPtr
}
2024-04-20 23:57:55 +08:00
// Void returns void type.
2024-04-19 00:05:57 +08:00
func (p Program) Void() Type {
if p.voidTy == nil {
2024-05-05 12:11:51 +08:00
p.voidTy = &aType{p.tyVoid(), rawType{types.Typ[types.Invalid]}, vkInvalid}
2024-04-19 00:05:57 +08:00
}
return p.voidTy
}
2024-05-03 23:10:02 +08:00
func (p Program) VoidPtr() Type {
if p.voidPtr == nil {
2024-05-05 12:11:51 +08:00
p.voidPtr = p.rawType(types.Typ[types.UnsafePointer])
2024-05-03 23:10:02 +08:00
}
return p.voidPtr
}
2024-04-20 23:57:55 +08:00
// Bool returns bool type.
2024-04-18 15:03:10 +08:00
func (p Program) Bool() Type {
if p.boolTy == nil {
2024-05-05 12:11:51 +08:00
p.boolTy = p.rawType(types.Typ[types.Bool])
2024-04-18 15:03:10 +08:00
}
return p.boolTy
}
2024-04-30 08:23:55 +08:00
func (p Program) CStr() Type {
if p.cstrTy == nil { // *int8
2024-05-05 12:11:51 +08:00
p.cstrTy = p.rawType(types.NewPointer(types.Typ[types.Int8]))
}
return p.cstrTy
}
func (p Program) String() Type {
if p.stringTy == nil {
2024-05-05 12:11:51 +08:00
p.stringTy = p.rawType(types.Typ[types.String])
}
return p.stringTy
}
2024-04-27 21:32:48 +08:00
// Any returns any type.
2024-04-27 13:57:21 +08:00
func (p Program) Any() Type {
if p.anyTy == nil {
2024-05-05 12:11:51 +08:00
p.anyTy = p.rawType(tyAny)
2024-04-27 13:57:21 +08:00
}
return p.anyTy
}
2024-04-20 23:57:55 +08:00
// Int returns int type.
2024-04-18 15:03:10 +08:00
func (p Program) Int() Type {
if p.intTy == nil {
2024-05-05 12:11:51 +08:00
p.intTy = p.rawType(types.Typ[types.Int])
2024-04-18 15:03:10 +08:00
}
return p.intTy
}
2024-04-28 07:08:01 +08:00
// Uintptr returns uintptr type.
func (p Program) Uintptr() Type {
if p.uintptrTy == nil {
2024-05-05 12:11:51 +08:00
p.uintptrTy = p.rawType(types.Typ[types.Uintptr])
2024-04-28 07:08:01 +08:00
}
return p.uintptrTy
}
2024-04-20 23:57:55 +08:00
// Float64 returns float64 type.
2024-04-18 15:03:10 +08:00
func (p Program) Float64() Type {
if p.f64Ty == nil {
2024-05-05 12:11:51 +08:00
p.f64Ty = p.rawType(types.Typ[types.Float64])
2024-04-18 15:03:10 +08:00
}
return p.f64Ty
2024-04-15 04:00:38 +08:00
}
2024-04-19 00:05:57 +08:00
// -----------------------------------------------------------------------------
2024-04-15 04:00:38 +08:00
// A Package is a single analyzed Go package containing Members for
// all package-level functions, variables, constants and types it
// declares. These may be accessed directly via Members, or via the
// type-specific accessor methods Func, Type, Var and Const.
//
// Members also contains entries for "init" (the synthetic package
// initializer) and "init#%d", the nth declared init function,
// and unspecified other things too.
2024-04-18 01:23:01 +08:00
type aPackage struct {
2024-05-12 11:11:19 +08:00
mod llvm.Module
vars map[string]Global
fns map[string]Function
stubs map[string]Function
2024-05-12 18:27:23 +08:00
pyobjs map[string]PyObject
2024-05-12 11:11:19 +08:00
pymods map[string]Global
Prog Program
2024-04-15 04:00:38 +08:00
}
2024-04-18 01:23:01 +08:00
type Package = *aPackage
2024-04-18 01:18:41 +08:00
/*
2024-04-25 21:44:23 +08:00
// NewConst creates a new named constant.
2024-04-18 15:03:10 +08:00
func (p Package) NewConst(name string, val constant.Value) NamedConst {
2024-04-18 01:23:01 +08:00
return &aNamedConst{}
2024-04-15 04:00:38 +08:00
}
*/
2024-04-15 04:00:38 +08:00
2024-04-27 17:39:25 +08:00
func (p Package) rtFunc(fnName string) Expr {
fn := p.Prog.runtime().Scope().Lookup(fnName).(*types.Func)
2024-04-27 17:39:25 +08:00
name := FullName(fn.Pkg(), fnName)
2024-05-05 12:11:51 +08:00
sig := fn.Type().(*types.Signature)
return p.NewFunc(name, sig, InGo).Expr
}
2024-05-11 23:38:21 +08:00
func (p Package) pyFunc(fullName string, sig *types.Signature) Expr {
2024-05-12 15:42:50 +08:00
p.Prog.NeedPyInit = true
return p.NewFunc(fullName, sig, InC).Expr
}
2024-05-05 18:48:09 +08:00
func (p Package) closureStub(b Builder, t *types.Struct, v Expr) Expr {
name := v.impl.Name()
prog := b.Prog
nilVal := prog.Null(prog.VoidPtr()).impl
if fn, ok := p.stubs[name]; ok {
v = fn.Expr
} else {
sig := v.raw.Type.(*types.Signature)
n := sig.Params().Len()
2024-05-05 19:44:16 +08:00
nret := sig.Results().Len()
2024-05-05 18:48:09 +08:00
ctx := types.NewParam(token.NoPos, nil, ClosureCtx, types.Typ[types.UnsafePointer])
sig = FuncAddCtx(ctx, sig)
fn := p.NewFunc(ClosureStub+name, sig, InC)
2024-05-06 00:17:39 +08:00
fn.impl.SetLinkage(llvm.LinkOnceAnyLinkage)
2024-05-05 18:48:09 +08:00
args := make([]Expr, n)
for i := 0; i < n; i++ {
args[i] = fn.Param(i + 1)
}
b := fn.MakeBody(1)
2024-05-05 19:44:16 +08:00
call := b.Call(v, args...)
2024-05-06 16:40:52 +08:00
call.impl.SetTailCall(true)
2024-05-05 19:44:16 +08:00
switch nret {
case 0:
b.impl.CreateRetVoid()
default: // TODO(xsw): support multiple return values
b.impl.CreateRet(call.impl)
}
2024-05-05 18:48:09 +08:00
p.stubs[name] = fn
v = fn.Expr
}
return b.aggregateValue(prog.rawType(t), v.impl, nilVal)
}
2024-04-21 15:12:57 +08:00
// -----------------------------------------------------------------------------
2024-04-20 23:57:55 +08:00
// String returns a string representation of the package.
2024-04-18 15:03:10 +08:00
func (p Package) String() string {
2024-04-16 00:43:29 +08:00
return p.mod.String()
}
/*
2024-04-15 17:12:30 +08:00
type CodeGenFileType = llvm.CodeGenFileType
const (
AssemblyFile = llvm.AssemblyFile
ObjectFile = llvm.ObjectFile
)
func (p *Package) CodeGen(ft CodeGenFileType) (ret []byte, err error) {
buf, err := p.prog.targetMachine().EmitToMemoryBuffer(p.mod, ft)
if err != nil {
return
}
ret = buf.Bytes()
buf.Dispose()
return
}
func (p *Package) Bitcode() []byte {
2024-04-15 04:00:38 +08:00
buf := llvm.WriteBitcodeToMemoryBuffer(p.mod)
2024-04-15 05:48:48 +08:00
ret := buf.Bytes()
buf.Dispose()
return ret
}
func (p *Package) WriteTo(w io.Writer) (int64, error) {
2024-04-15 17:12:30 +08:00
n, err := w.Write(p.Bitcode())
2024-04-15 04:00:38 +08:00
return int64(n), err
}
func (p *Package) WriteFile(file string) (err error) {
f, err := os.Create(file)
if err != nil {
return
}
defer f.Close()
return llvm.WriteBitcodeToFile(p.mod, f)
}
2024-04-16 00:43:29 +08:00
*/
2024-04-19 00:05:57 +08:00
// -----------------------------------------------------------------------------
func (p Program) tyImportPyModule() *types.Signature {
if p.pyImpTy == nil {
charPtr := types.NewPointer(types.Typ[types.Int8])
objPtr := p.PyObjectPtr().raw.Type
params := types.NewTuple(types.NewParam(token.NoPos, nil, "", charPtr))
results := types.NewTuple(types.NewParam(token.NoPos, nil, "", objPtr))
p.pyImpTy = types.NewSignatureType(nil, nil, nil, params, results, false)
}
return p.pyImpTy
}
2024-05-12 00:24:56 +08:00
func (p Program) tyCallNoArgs() *types.Signature {
if p.callNoArgs == nil {
2024-05-11 23:38:21 +08:00
objPtr := p.PyObjectPtr().raw.Type
paramObjPtr := types.NewParam(token.NoPos, nil, "", objPtr)
params := types.NewTuple(paramObjPtr)
2024-05-12 00:24:56 +08:00
p.callNoArgs = types.NewSignatureType(nil, nil, nil, params, params, false)
2024-05-11 23:38:21 +08:00
}
2024-05-12 00:24:56 +08:00
return p.callNoArgs
2024-05-11 23:38:21 +08:00
}
func (p Program) tyCallOneArg() *types.Signature {
if p.callOneArg == nil {
objPtr := p.PyObjectPtr().raw.Type
paramObjPtr := types.NewParam(token.NoPos, nil, "", objPtr)
params := types.NewTuple(paramObjPtr, paramObjPtr)
results := types.NewTuple(paramObjPtr)
p.callOneArg = types.NewSignatureType(nil, nil, nil, params, results, false)
}
return p.callOneArg
}
2024-05-12 18:27:23 +08:00
func (p Program) tyLoadPyModSyms() *types.Signature {
if p.loadPyModS == nil {
objPtr := p.PyObjectPtr().raw.Type
paramObjPtr := types.NewParam(token.NoPos, nil, "mod", objPtr)
params := types.NewTuple(paramObjPtr, VArg())
p.loadPyModS = types.NewSignatureType(nil, nil, nil, params, nil, false)
}
return p.loadPyModS
}
2024-05-12 11:11:19 +08:00
// PyInit initializes Python for a main package.
func (p Package) PyInit() bool {
if fn := p.FuncOf("main"); fn != nil {
b := fn.NewBuilder()
b.SetBlockEx(fn.Block(0), AtStart).CallPyInit()
b.Dispose()
return true
}
return false
2024-05-11 21:55:50 +08:00
}
// NewPyModVar creates a new global variable for a Python module.
2024-05-12 18:27:23 +08:00
func (p Package) NewPyModVar(name string, doInit bool) Global {
2024-05-12 11:11:19 +08:00
if v, ok := p.pymods[name]; ok {
return v
}
prog := p.Prog
objPtr := prog.PyObjectPtrPtr().raw.Type
g := p.NewVar(name, objPtr, InC)
2024-05-12 18:27:23 +08:00
if doInit {
g.Init(prog.Null(g.Type))
g.impl.SetLinkage(llvm.LinkOnceAnyLinkage)
}
2024-05-12 11:11:19 +08:00
p.pymods[name] = g
return g
}
2024-05-12 11:11:19 +08:00
// ImportPyMod imports a Python module.
func (b Builder) ImportPyMod(path string) Expr {
pkg := b.Func.Pkg
fnImp := pkg.pyFunc("PyImport_ImportModule", b.Prog.tyImportPyModule())
return b.Call(fnImp, b.CStr(path))
}
2024-05-12 18:27:23 +08:00
// LoadPyModSyms loads python objects from specified module.
func (b Builder) LoadPyModSyms(modName string, objs ...PyObject) Expr {
pkg := b.Func.Pkg
fnLoad := pkg.pyFunc("llgoLoadPyModSyms", b.Prog.tyLoadPyModSyms())
modPtr := pkg.NewPyModVar(modName, false).Expr
mod := b.Load(modPtr)
2024-05-12 20:03:27 +08:00
args := make([]Expr, 1, len(objs)*2+2)
2024-05-12 18:27:23 +08:00
args[0] = mod
2024-05-12 20:03:27 +08:00
nbase := len(modName) + 1
2024-05-12 18:27:23 +08:00
for _, o := range objs {
2024-05-12 20:03:27 +08:00
fullName := o.impl.Name()
name := fullName[nbase:]
args = append(args, b.CStr(name))
2024-05-12 18:27:23 +08:00
args = append(args, o.Expr)
}
2024-05-12 20:03:27 +08:00
prog := b.Prog
args = append(args, prog.Null(prog.CStr()))
2024-05-12 18:27:23 +08:00
return b.Call(fnLoad, args...)
}
2024-05-11 23:38:21 +08:00
func (b Builder) pyCall(fn Expr, args []Expr) (ret Expr) {
prog := b.Prog
pkg := b.Func.Pkg
sig := fn.raw.Type.(*types.Signature)
params := sig.Params()
n := params.Len()
switch n {
case 0:
2024-05-12 00:24:56 +08:00
call := pkg.pyFunc("PyObject_CallNoArgs", prog.tyCallNoArgs())
2024-05-11 23:38:21 +08:00
ret = b.Call(call, fn)
case 1:
call := pkg.pyFunc("PyObject_CallOneArg", prog.tyCallOneArg())
ret = b.Call(call, fn, args[0])
default:
panic("todo")
}
return
}
2024-05-12 11:11:19 +08:00
// CallPyInit calls Py_Initialize.
func (b Builder) CallPyInit() (ret Expr) {
fn := b.Func.Pkg.pyFunc("Py_Initialize", NoArgsNoRet)
return b.Call(fn)
}
var (
NoArgsNoRet = types.NewSignatureType(nil, nil, nil, nil, nil, false)
)
// -----------------------------------------------------------------------------