From 6ab2b30984bf618737205300cb750e073e9c2d39 Mon Sep 17 00:00:00 2001 From: Ayke van Laethem Date: Wed, 12 Sep 2018 19:11:50 +0200 Subject: [PATCH] compiler: move output file type selection to main.go --- compiler.go | 42 +++++++++++++++++++++++++----------------- main.go | 15 ++++++++++----- 2 files changed, 35 insertions(+), 22 deletions(-) diff --git a/compiler.go b/compiler.go index 4e1973e1..0cedbb4c 100644 --- a/compiler.go +++ b/compiler.go @@ -3048,29 +3048,37 @@ func (c *Compiler) Optimize(optLevel, sizeLevel int, inlinerThreshold uint) { modPasses.Run(c.mod) } +// Emit object file (.o). func (c *Compiler) EmitObject(path string) error { - // Generate output - var buf []byte - if strings.HasSuffix(path, ".o") { - llvmBuf, err := c.machine.EmitToMemoryBuffer(c.mod, llvm.ObjectFile) - if err != nil { - return err - } - buf = llvmBuf.Bytes() - } else if strings.HasSuffix(path, ".bc") { - buf = llvm.WriteBitcodeToMemoryBuffer(c.mod).Bytes() - } else if strings.HasSuffix(path, ".ll") { - buf = []byte(c.mod.String()) - } else { - return errors.New("unknown output file extension") + llvmBuf, err := c.machine.EmitToMemoryBuffer(c.mod, llvm.ObjectFile) + if err != nil { + return err } + return c.writeFile(llvmBuf.Bytes(), path) +} +// Emit LLVM bitcode file (.bc). +func (c *Compiler) EmitBitcode(path string) error { + data := llvm.WriteBitcodeToMemoryBuffer(c.mod).Bytes() + return c.writeFile(data, path) +} + +// Emit LLVM IR source file (.ll). +func (c *Compiler) EmitText(path string) error { + data := []byte(c.mod.String()) + return c.writeFile(data, path) +} + +// Write the data to the file specified by path. +func (c *Compiler) writeFile(data []byte, path string) error { // Write output to file f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0666) if err != nil { return err } - f.Write(buf) - f.Close() - return nil + _, err = f.Write(data) + if err != nil { + return err + } + return f.Close() } diff --git a/main.go b/main.go index dbdf3995..7f1ed5b0 100644 --- a/main.go +++ b/main.go @@ -6,6 +6,7 @@ import ( "fmt" "os" "runtime" + "strings" "github.com/aykevl/llvm/bindings/go/llvm" ) @@ -58,12 +59,16 @@ func Compile(pkgName, runtimePath, outpath, target string, printIR, dumpSSA bool return err } - err = c.EmitObject(outpath) - if err != nil { - return err + // Generate output. + if strings.HasSuffix(outpath, ".o") { + return c.EmitObject(outpath) + } else if strings.HasSuffix(outpath, ".bc") { + return c.EmitBitcode(outpath) + } else if strings.HasSuffix(outpath, ".ll") { + return c.EmitText(outpath) + } else { + return errors.New("unknown output file extension") } - - return nil } // Run the specified package directly (using JIT or interpretation).