forked from go-llvm/llgo
/
compiler.go
312 lines (271 loc) · 8.54 KB
/
compiler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
// Copyright 2011 The llgo Authors.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package llgo
import (
"fmt"
"go/ast"
"go/token"
"log"
"runtime"
"strings"
llgobuild "github.com/go-llvm/llgo/build"
llgoimporter "github.com/go-llvm/llgo/importer"
"github.com/go-llvm/llvm"
"code.google.com/p/go.tools/go/loader"
"code.google.com/p/go.tools/go/ssa"
"code.google.com/p/go.tools/go/types"
)
func assert(cond bool) {
if !cond {
_, file, line, ok := runtime.Caller(1)
if !ok {
panic("assertion failed")
}
panic(fmt.Sprintf("assertion failed [%s:%d]", file, line))
}
}
type Module struct {
llvm.Module
Name string
disposed bool
}
func (m *Module) Dispose() {
if m.disposed {
return
}
m.Module.Dispose()
m.disposed = true
}
///////////////////////////////////////////////////////////////////////////////
type CompilerOptions struct {
// TargetTriple is the LLVM triple for the target.
TargetTriple string
// GenerateDebug decides whether debug data is
// generated in the output module.
GenerateDebug bool
// Logger is a logger used for tracing compilation.
Logger *log.Logger
// OrderedCompilation attempts to do some sorting to compile
// functions in a deterministic order
OrderedCompilation bool
}
type Compiler struct {
opts CompilerOptions
dataLayout string
pnacl bool
}
func NewCompiler(opts CompilerOptions) (*Compiler, error) {
compiler := &Compiler{opts: opts}
if strings.ToLower(compiler.opts.TargetTriple) == "pnacl" {
compiler.opts.TargetTriple = PNaClTriple
compiler.pnacl = true
}
dataLayout, err := llvmDataLayout(compiler.opts.TargetTriple)
if err != nil {
return nil, err
}
compiler.dataLayout = dataLayout
return compiler, nil
}
func (c *Compiler) Compile(filenames []string, importpath string) (m *Module, err error) {
target := llvm.NewTargetData(c.dataLayout)
compiler := &compiler{
CompilerOptions: c.opts,
dataLayout: c.dataLayout,
target: target,
pnacl: c.pnacl,
llvmtypes: NewLLVMTypeMap(target),
}
return compiler.compile(filenames, importpath)
}
type compiler struct {
CompilerOptions
builder llvm.Builder
module *Module
dataLayout string
target llvm.TargetData
fileset *token.FileSet
runtime *runtimeInterface
llvmtypes *llvmTypeMap
types *TypeMap
// runtimetypespkg is the type-checked runtime/types.go file,
// which is used for evaluating the types of runtime functions.
runtimetypespkg *types.Package
// pnacl is set to true if the target triple was originally
// specified as "pnacl". This is necessary, as the TargetTriple
// field will have been updated to the true triple used to
// compile PNaCl modules.
pnacl bool
debug debugInfo
}
func (c *compiler) logf(format string, v ...interface{}) {
if c.Logger != nil {
c.Logger.Printf(format, v...)
}
}
func (compiler *compiler) compile(filenames []string, importpath string) (m *Module, err error) {
buildctx, err := llgobuild.ContextFromTriple(compiler.TargetTriple)
if err != nil {
return nil, err
}
impcfg := &loader.Config{
Fset: token.NewFileSet(),
TypeChecker: types.Config{
Import: llgoimporter.NewImporter(buildctx).Import,
Sizes: compiler.llvmtypes,
},
Build: &buildctx.Context,
}
// Must use parseFiles, so we retain comments;
// this is important for annotation processing.
astFiles, err := parseFiles(impcfg.Fset, filenames)
if err != nil {
return nil, err
}
// If no import path is specified, or the package's
// name (not path) is "main", then set the import
// path to be the same as the package's name.
if pkgname := astFiles[0].Name.String(); importpath == "" || pkgname == "main" {
importpath = pkgname
}
impcfg.CreateFromFiles(importpath, astFiles...)
// Create a "runtime" package too, so we can reference
// its types and functions in the compiler and generated
// code.
if importpath != "runtime" {
astFiles, err := parseRuntime(&buildctx.Context, impcfg.Fset)
if err != nil {
return nil, err
}
impcfg.CreateFromFiles("runtime", astFiles...)
}
iprog, err := impcfg.Load()
if err != nil {
return nil, err
}
program := ssa.Create(iprog, 0)
var mainPkginfo, runtimePkginfo *loader.PackageInfo
if pkgs := iprog.InitialPackages(); len(pkgs) == 1 {
mainPkginfo, runtimePkginfo = pkgs[0], pkgs[0]
} else {
mainPkginfo, runtimePkginfo = pkgs[0], pkgs[1]
}
mainPkg := program.CreatePackage(mainPkginfo)
// Create a Module, which contains the LLVM bitcode.
modulename := importpath
compiler.module = &Module{Module: llvm.NewModule(modulename), Name: modulename}
compiler.module.SetTarget(compiler.TargetTriple)
compiler.module.SetDataLayout(compiler.dataLayout)
// Create a new translation unit.
unit := newUnit(compiler, mainPkg)
// Create the runtime interface.
compiler.runtime, err = newRuntimeInterface(
runtimePkginfo.Pkg,
compiler.module.Module,
compiler.llvmtypes,
FuncResolver(unit),
)
if err != nil {
return nil, err
}
// Create a struct responsible for mapping static types to LLVM types,
// and to runtime/dynamic type values.
compiler.types = NewTypeMap(
importpath,
compiler.llvmtypes,
compiler.module.Module,
compiler.runtime,
MethodResolver(unit),
)
// Create a Builder, for building LLVM instructions.
compiler.builder = llvm.GlobalContext().NewBuilder()
defer compiler.builder.Dispose()
// Initialise debugging.
compiler.debug.module = compiler.module.Module
compiler.debug.Fset = impcfg.Fset
compiler.debug.Sizes = compiler.llvmtypes
mainPkg.Build()
unit.translatePackage(mainPkg)
compiler.processAnnotations(unit, mainPkginfo)
if runtimePkginfo != mainPkginfo {
compiler.processAnnotations(unit, runtimePkginfo)
}
// Finalise debugging.
for _, cu := range compiler.debug.cu {
compiler.module.AddNamedMetadataOperand(
"llvm.dbg.cu",
compiler.debug.MDNode(cu),
)
}
// Export runtime type information.
var exportedTypes []types.Type
for _, m := range mainPkg.Members {
if t, ok := m.(*ssa.Type); ok && ast.IsExported(t.Name()) {
exportedTypes = append(exportedTypes, t.Type())
}
}
compiler.exportRuntimeTypes(exportedTypes, importpath == "runtime")
if importpath == "main" {
// Wrap "main.main" in a call to runtime.main.
if err = compiler.createMainFunction(); err != nil {
return nil, fmt.Errorf("failed to create main.main: %v", err)
}
} else {
if err := llgoimporter.Export(buildctx, mainPkg.Object); err != nil {
return nil, fmt.Errorf("failed to export package data: %v", err)
}
}
return compiler.module, nil
}
func (c *compiler) createMainFunction() error {
// In a PNaCl program (plugin), there should not be a "main.main";
// instead, we expect a "main.CreateModule" function.
// See pkg/nacl/ppapi/ppapi.go for more details.
mainMain := c.module.NamedFunction("main.main")
/*
if c.pnacl {
// PNaCl's libppapi_stub.a implements "main", which simply
// calls through to PpapiPluginMain. We define our own "main"
// so that we can capture argc/argv.
if !mainMain.IsNil() {
return fmt.Errorf("Found main.main")
}
pluginMain := c.RuntimeFunction("PpapiPluginMain", "func() int32")
// Synthesise a main which has no return value. We could cast
// PpapiPluginMain, but this is potentially unsafe as its
// calling convention is unspecified.
ftyp := llvm.FunctionType(llvm.VoidType(), nil, false)
mainMain = llvm.AddFunction(c.module.Module, "main.main", ftyp)
entry := llvm.AddBasicBlock(mainMain, "entry")
c.builder.SetInsertPointAtEnd(entry)
c.builder.CreateCall(pluginMain, nil, "")
c.builder.CreateRetVoid()
} else */{
mainMain = c.module.NamedFunction("main.main")
}
if mainMain.IsNil() {
return fmt.Errorf("Could not find main.main")
}
// runtime.main is called by main, with argc, argv, argp,
// and a pointer to main.main, which must be a niladic
// function with no result.
runtimeMain := c.runtime.main.LLVMValue()
ptrptr := llvm.PointerType(llvm.PointerType(llvm.Int8Type(), 0), 0)
ftyp := llvm.FunctionType(llvm.Int32Type(), []llvm.Type{llvm.Int32Type(), ptrptr, ptrptr}, true)
main := llvm.AddFunction(c.module.Module, "main", ftyp)
c.builder.SetCurrentDebugLocation(c.debug.MDNode(nil))
entry := llvm.AddBasicBlock(main, "entry")
c.builder.SetInsertPointAtEnd(entry)
runtimeMainParamTypes := runtimeMain.Type().ElementType().ParamTypes()
args := []llvm.Value{
main.Param(0), // argc
main.Param(1), // argv
main.Param(2), // argp
c.builder.CreateBitCast(mainMain, runtimeMainParamTypes[3], ""),
}
result := c.builder.CreateCall(runtimeMain, args, "")
c.builder.CreateRet(result)
return nil
}
// vim: set ft=go :