Add basic globals implementation

This commit is contained in:
Sasha Koshka 2024-01-27 01:49:18 +00:00
parent 417c7772e4
commit 14a02f5e22
2 changed files with 79 additions and 4 deletions

61
llvm/global.go Normal file
View File

@ -0,0 +1,61 @@
package llvm
import "fmt"
import "strings"
type Global struct {
Ty Type
GlobalName string
Constant bool
Initial Const
AddressSpace AddressSpace
// TODO complete this
}
func (this *Global) Type () Type {
return &TypePointer {
AddressSpace: this.AddressSpace,
}
}
func (this *Global) Named () bool {
return this.GlobalName != ""
}
func (this *Global) Name () string {
return this.GlobalName
}
func (this *Global) Identifier () string {
return EncodeGlobalName(this.Name())
}
func (this *Global) SetName (name string) {
this.GlobalName = name
}
func (this *Global) String () string {
return fmt.Sprintf("%v %v", this.Ty, this.Identifier())
}
func (this *Global) LLString () string {
buffer := &strings.Builder { }
buffer.WriteString(this.Name())
buffer.WriteString(" = ")
if this.AddressSpace != 0 {
fmt.Fprintf(buffer, " %v", this.AddressSpace)
}
if this.Constant {
buffer.WriteString(" constant")
} else {
buffer.WriteString(" global")
}
fmt.Fprintf(buffer, " %v", this.Ty)
if this.Initial != nil {
fmt.Fprintf(buffer, " %v", this.Initial)
}
buffer.WriteString("\n")
return buffer.String()
}

View File

@ -5,6 +5,7 @@ import "fmt"
type Module struct {
Types []Type
Globals []*Global
Functions []*Function
}
@ -17,6 +18,10 @@ func (this *Module) WriteTo (writer io.Writer) (wrote int64, err error) {
err = write(fmt.Fprintf(writer, "%v = type %v\n", ty, ty.LLString()))
if err != nil { return wrote, err }
}
for _, global := range this.Globals {
err = write(fmt.Fprint(writer, global.LLString()))
if err != nil { return wrote, err }
}
for _, function := range this.Functions {
err = write(fmt.Fprint(writer, function.LLString()))
if err != nil { return wrote, err }
@ -25,6 +30,12 @@ func (this *Module) WriteTo (writer io.Writer) (wrote int64, err error) {
return wrote, err
}
func (this *Module) NewType (name string, ty Type) Type {
ty.SetName(name)
this.Types = append(this.Types, ty)
return ty
}
func (this *Module) NewFunction (name string, retur Type, parameters ...*Parameter) *Function {
paramTypes := make([]Type, len(parameters))
for index, parameter := range parameters {
@ -43,10 +54,13 @@ func (this *Module) NewFunction (name string, retur Type, parameters ...*Paramet
return function
}
func (this *Module) NewType (name string, ty Type) Type {
ty.SetName(name)
this.Types = append(this.Types, ty)
return ty
func (this *Module) NewGlobal (name string, ty Type) *Global {
global := &Global {
Ty: ty,
GlobalName: name,
}
this.Globals = append(this.Globals, global)
return global
}
type Align uint64