]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/ssagen/abi.go
8103b08ce51a7b1d5ef85b4f323a0296a898557e
[gostls13.git] / src / cmd / compile / internal / ssagen / abi.go
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package ssagen
6
7 import (
8         "fmt"
9         "io/ioutil"
10         "log"
11         "os"
12         "strings"
13
14         "cmd/compile/internal/base"
15         "cmd/compile/internal/ir"
16         "cmd/compile/internal/staticdata"
17         "cmd/compile/internal/typecheck"
18         "cmd/compile/internal/types"
19         "cmd/internal/obj"
20         "cmd/internal/objabi"
21 )
22
23 // SymABIs records information provided by the assembler about symbol
24 // definition ABIs and reference ABIs.
25 type SymABIs struct {
26         defs map[string]obj.ABI
27         refs map[string]obj.ABISet
28
29         localPrefix string
30 }
31
32 func NewSymABIs(myimportpath string) *SymABIs {
33         var localPrefix string
34         if myimportpath != "" {
35                 localPrefix = objabi.PathToPrefix(myimportpath) + "."
36         }
37
38         return &SymABIs{
39                 defs:        make(map[string]obj.ABI),
40                 refs:        make(map[string]obj.ABISet),
41                 localPrefix: localPrefix,
42         }
43 }
44
45 // canonicalize returns the canonical name used for a linker symbol in
46 // s's maps. Symbols in this package may be written either as "".X or
47 // with the package's import path already in the symbol. This rewrites
48 // both to `"".`, which matches compiler-generated linker symbol names.
49 func (s *SymABIs) canonicalize(linksym string) string {
50         // If the symbol is already prefixed with localPrefix,
51         // rewrite it to start with "" so it matches the
52         // compiler's internal symbol names.
53         if s.localPrefix != "" && strings.HasPrefix(linksym, s.localPrefix) {
54                 return `"".` + linksym[len(s.localPrefix):]
55         }
56         return linksym
57 }
58
59 // ReadSymABIs reads a symabis file that specifies definitions and
60 // references of text symbols by ABI.
61 //
62 // The symabis format is a set of lines, where each line is a sequence
63 // of whitespace-separated fields. The first field is a verb and is
64 // either "def" for defining a symbol ABI or "ref" for referencing a
65 // symbol using an ABI. For both "def" and "ref", the second field is
66 // the symbol name and the third field is the ABI name, as one of the
67 // named cmd/internal/obj.ABI constants.
68 func (s *SymABIs) ReadSymABIs(file string) {
69         data, err := ioutil.ReadFile(file)
70         if err != nil {
71                 log.Fatalf("-symabis: %v", err)
72         }
73
74         for lineNum, line := range strings.Split(string(data), "\n") {
75                 lineNum++ // 1-based
76                 line = strings.TrimSpace(line)
77                 if line == "" || strings.HasPrefix(line, "#") {
78                         continue
79                 }
80
81                 parts := strings.Fields(line)
82                 switch parts[0] {
83                 case "def", "ref":
84                         // Parse line.
85                         if len(parts) != 3 {
86                                 log.Fatalf(`%s:%d: invalid symabi: syntax is "%s sym abi"`, file, lineNum, parts[0])
87                         }
88                         sym, abistr := parts[1], parts[2]
89                         abi, valid := obj.ParseABI(abistr)
90                         if !valid {
91                                 log.Fatalf(`%s:%d: invalid symabi: unknown abi "%s"`, file, lineNum, abistr)
92                         }
93
94                         sym = s.canonicalize(sym)
95
96                         // Record for later.
97                         if parts[0] == "def" {
98                                 s.defs[sym] = abi
99                         } else {
100                                 s.refs[sym] |= obj.ABISetOf(abi)
101                         }
102                 default:
103                         log.Fatalf(`%s:%d: invalid symabi type "%s"`, file, lineNum, parts[0])
104                 }
105         }
106 }
107
108 // GenABIWrappers applies ABI information to Funcs and generates ABI
109 // wrapper functions where necessary.
110 func (s *SymABIs) GenABIWrappers() {
111         // For cgo exported symbols, we tell the linker to export the
112         // definition ABI to C. That also means that we don't want to
113         // create ABI wrappers even if there's a linkname.
114         //
115         // TODO(austin): Maybe we want to create the ABI wrappers, but
116         // ensure the linker exports the right ABI definition under
117         // the unmangled name?
118         cgoExports := make(map[string][]*[]string)
119         for i, prag := range typecheck.Target.CgoPragmas {
120                 switch prag[0] {
121                 case "cgo_export_static", "cgo_export_dynamic":
122                         symName := s.canonicalize(prag[1])
123                         pprag := &typecheck.Target.CgoPragmas[i]
124                         cgoExports[symName] = append(cgoExports[symName], pprag)
125                 }
126         }
127
128         // Apply ABI defs and refs to Funcs and generate wrappers.
129         //
130         // This may generate new decls for the wrappers, but we
131         // specifically *don't* want to visit those, lest we create
132         // wrappers for wrappers.
133         for _, fn := range typecheck.Target.Decls {
134                 if fn.Op() != ir.ODCLFUNC {
135                         continue
136                 }
137                 fn := fn.(*ir.Func)
138                 nam := fn.Nname
139                 if ir.IsBlank(nam) {
140                         continue
141                 }
142                 sym := nam.Sym()
143                 var symName string
144                 if sym.Linkname != "" {
145                         symName = s.canonicalize(sym.Linkname)
146                 } else {
147                         // These names will already be canonical.
148                         symName = sym.Pkg.Prefix + "." + sym.Name
149                 }
150
151                 // Apply definitions.
152                 defABI, hasDefABI := s.defs[symName]
153                 if hasDefABI {
154                         fn.ABI = defABI
155                 }
156
157                 if fn.Pragma&ir.CgoUnsafeArgs != 0 {
158                         // CgoUnsafeArgs indicates the function (or its callee) uses
159                         // offsets to dispatch arguments, which currently using ABI0
160                         // frame layout. Pin it to ABI0.
161                         fn.ABI = obj.ABI0
162                 }
163
164                 // If cgo-exported, add the definition ABI to the cgo
165                 // pragmas.
166                 cgoExport := cgoExports[symName]
167                 for _, pprag := range cgoExport {
168                         // The export pragmas have the form:
169                         //
170                         //   cgo_export_* <local> [<remote>]
171                         //
172                         // If <remote> is omitted, it's the same as
173                         // <local>.
174                         //
175                         // Expand to
176                         //
177                         //   cgo_export_* <local> <remote> <ABI>
178                         if len(*pprag) == 2 {
179                                 *pprag = append(*pprag, (*pprag)[1])
180                         }
181                         // Add the ABI argument.
182                         *pprag = append(*pprag, fn.ABI.String())
183                 }
184
185                 // Apply references.
186                 if abis, ok := s.refs[symName]; ok {
187                         fn.ABIRefs |= abis
188                 }
189                 // Assume all functions are referenced at least as
190                 // ABIInternal, since they may be referenced from
191                 // other packages.
192                 fn.ABIRefs.Set(obj.ABIInternal, true)
193
194                 // If a symbol is defined in this package (either in
195                 // Go or assembly) and given a linkname, it may be
196                 // referenced from another package, so make it
197                 // callable via any ABI. It's important that we know
198                 // it's defined in this package since other packages
199                 // may "pull" symbols using linkname and we don't want
200                 // to create duplicate ABI wrappers.
201                 //
202                 // However, if it's given a linkname for exporting to
203                 // C, then we don't make ABI wrappers because the cgo
204                 // tool wants the original definition.
205                 hasBody := len(fn.Body) != 0
206                 if sym.Linkname != "" && (hasBody || hasDefABI) && len(cgoExport) == 0 {
207                         fn.ABIRefs |= obj.ABISetCallable
208                 }
209
210                 // Double check that cgo-exported symbols don't get
211                 // any wrappers.
212                 if len(cgoExport) > 0 && fn.ABIRefs&^obj.ABISetOf(fn.ABI) != 0 {
213                         base.Fatalf("cgo exported function %s cannot have ABI wrappers", fn)
214                 }
215
216                 if !objabi.Experiment.RegabiWrappers {
217                         // We'll generate ABI aliases instead of
218                         // wrappers once we have LSyms in InitLSym.
219                         continue
220                 }
221
222                 forEachWrapperABI(fn, makeABIWrapper)
223         }
224 }
225
226 // InitLSym defines f's obj.LSym and initializes it based on the
227 // properties of f. This includes setting the symbol flags and ABI and
228 // creating and initializing related DWARF symbols.
229 //
230 // InitLSym must be called exactly once per function and must be
231 // called for both functions with bodies and functions without bodies.
232 // For body-less functions, we only create the LSym; for functions
233 // with bodies call a helper to setup up / populate the LSym.
234 func InitLSym(f *ir.Func, hasBody bool) {
235         if f.LSym != nil {
236                 base.FatalfAt(f.Pos(), "InitLSym called twice on %v", f)
237         }
238
239         if nam := f.Nname; !ir.IsBlank(nam) {
240                 f.LSym = nam.LinksymABI(f.ABI)
241                 if f.Pragma&ir.Systemstack != 0 {
242                         f.LSym.Set(obj.AttrCFunc, true)
243                 }
244                 if f.ABI == obj.ABIInternal || !objabi.Experiment.RegabiWrappers {
245                         // Function values can only point to
246                         // ABIInternal entry points. This will create
247                         // the funcsym for either the defining
248                         // function or its wrapper as appropriate.
249                         //
250                         // If we're using ABI aliases instead of
251                         // wrappers, we only InitLSym for the defining
252                         // ABI of a function, so we make the funcsym
253                         // when we see that.
254                         staticdata.NeedFuncSym(f)
255                 }
256                 if !objabi.Experiment.RegabiWrappers {
257                         // Create ABI aliases instead of wrappers.
258                         forEachWrapperABI(f, makeABIAlias)
259                 }
260         }
261         if hasBody {
262                 setupTextLSym(f, 0)
263         }
264 }
265
266 func forEachWrapperABI(fn *ir.Func, cb func(fn *ir.Func, wrapperABI obj.ABI)) {
267         need := fn.ABIRefs &^ obj.ABISetOf(fn.ABI)
268         if need == 0 {
269                 return
270         }
271
272         for wrapperABI := obj.ABI(0); wrapperABI < obj.ABICount; wrapperABI++ {
273                 if !need.Get(wrapperABI) {
274                         continue
275                 }
276                 cb(fn, wrapperABI)
277         }
278 }
279
280 // makeABIAlias creates a new ABI alias so calls to f via wrapperABI
281 // will be resolved directly to f's ABI by the linker.
282 func makeABIAlias(f *ir.Func, wrapperABI obj.ABI) {
283         // These LSyms have the same name as the native function, so
284         // we create them directly rather than looking them up.
285         // The uniqueness of f.lsym ensures uniqueness of asym.
286         asym := &obj.LSym{
287                 Name: f.LSym.Name,
288                 Type: objabi.SABIALIAS,
289                 R:    []obj.Reloc{{Sym: f.LSym}}, // 0 size, so "informational"
290         }
291         asym.SetABI(wrapperABI)
292         asym.Set(obj.AttrDuplicateOK, true)
293         base.Ctxt.ABIAliases = append(base.Ctxt.ABIAliases, asym)
294 }
295
296 // makeABIWrapper creates a new function that will be called with
297 // wrapperABI and calls "f" using f.ABI.
298 func makeABIWrapper(f *ir.Func, wrapperABI obj.ABI) {
299         if base.Debug.ABIWrap != 0 {
300                 fmt.Fprintf(os.Stderr, "=-= %v to %v wrapper for %v\n", wrapperABI, f.ABI, f)
301         }
302
303         // Q: is this needed?
304         savepos := base.Pos
305         savedclcontext := typecheck.DeclContext
306         savedcurfn := ir.CurFunc
307
308         base.Pos = base.AutogeneratedPos
309         typecheck.DeclContext = ir.PEXTERN
310
311         // At the moment we don't support wrapping a method, we'd need machinery
312         // below to handle the receiver. Panic if we see this scenario.
313         ft := f.Nname.Ntype.Type()
314         if ft.NumRecvs() != 0 {
315                 panic("makeABIWrapper support for wrapping methods not implemented")
316         }
317
318         // Manufacture a new func type to use for the wrapper.
319         var noReceiver *ir.Field
320         tfn := ir.NewFuncType(base.Pos,
321                 noReceiver,
322                 typecheck.NewFuncParams(ft.Params(), true),
323                 typecheck.NewFuncParams(ft.Results(), false))
324
325         // Reuse f's types.Sym to create a new ODCLFUNC/function.
326         fn := typecheck.DeclFunc(f.Nname.Sym(), tfn)
327         fn.ABI = wrapperABI
328
329         fn.SetABIWrapper(true)
330         fn.SetDupok(true)
331
332         // ABI0-to-ABIInternal wrappers will be mainly loading params from
333         // stack into registers (and/or storing stack locations back to
334         // registers after the wrapped call); in most cases they won't
335         // need to allocate stack space, so it should be OK to mark them
336         // as NOSPLIT in these cases. In addition, my assumption is that
337         // functions written in assembly are NOSPLIT in most (but not all)
338         // cases. In the case of an ABIInternal target that has too many
339         // parameters to fit into registers, the wrapper would need to
340         // allocate stack space, but this seems like an unlikely scenario.
341         // Hence: mark these wrappers NOSPLIT.
342         //
343         // ABIInternal-to-ABI0 wrappers on the other hand will be taking
344         // things in registers and pushing them onto the stack prior to
345         // the ABI0 call, meaning that they will always need to allocate
346         // stack space. If the compiler marks them as NOSPLIT this seems
347         // as though it could lead to situations where the linker's
348         // nosplit-overflow analysis would trigger a link failure. On the
349         // other hand if they not tagged NOSPLIT then this could cause
350         // problems when building the runtime (since there may be calls to
351         // asm routine in cases where it's not safe to grow the stack). In
352         // most cases the wrapper would be (in effect) inlined, but are
353         // there (perhaps) indirect calls from the runtime that could run
354         // into trouble here.
355         // FIXME: at the moment all.bash does not pass when I leave out
356         // NOSPLIT for these wrappers, so all are currently tagged with NOSPLIT.
357         fn.Pragma |= ir.Nosplit
358
359         // Generate call. Use tail call if no params and no returns,
360         // but a regular call otherwise.
361         //
362         // Note: ideally we would be using a tail call in cases where
363         // there are params but no returns for ABI0->ABIInternal wrappers,
364         // provided that all params fit into registers (e.g. we don't have
365         // to allocate any stack space). Doing this will require some
366         // extra work in typecheck/walk/ssa, might want to add a new node
367         // OTAILCALL or something to this effect.
368         tailcall := tfn.Type().NumResults() == 0 && tfn.Type().NumParams() == 0 && tfn.Type().NumRecvs() == 0
369         if base.Ctxt.Arch.Name == "ppc64le" && base.Ctxt.Flag_dynlink {
370                 // cannot tailcall on PPC64 with dynamic linking, as we need
371                 // to restore R2 after call.
372                 tailcall = false
373         }
374         if base.Ctxt.Arch.Name == "amd64" && wrapperABI == obj.ABIInternal {
375                 // cannot tailcall from ABIInternal to ABI0 on AMD64, as we need
376                 // to special registers (X15) when returning to ABIInternal.
377                 tailcall = false
378         }
379
380         var tail ir.Node
381         if tailcall {
382                 tail = ir.NewTailCallStmt(base.Pos, f.Nname)
383         } else {
384                 call := ir.NewCallExpr(base.Pos, ir.OCALL, f.Nname, nil)
385                 call.Args = ir.ParamNames(tfn.Type())
386                 call.IsDDD = tfn.Type().IsVariadic()
387                 tail = call
388                 if tfn.Type().NumResults() > 0 {
389                         n := ir.NewReturnStmt(base.Pos, nil)
390                         n.Results = []ir.Node{call}
391                         tail = n
392                 }
393         }
394         fn.Body.Append(tail)
395
396         typecheck.FinishFuncBody()
397         if base.Debug.DclStack != 0 {
398                 types.CheckDclstack()
399         }
400
401         typecheck.Func(fn)
402         ir.CurFunc = fn
403         typecheck.Stmts(fn.Body)
404
405         typecheck.Target.Decls = append(typecheck.Target.Decls, fn)
406
407         // Restore previous context.
408         base.Pos = savepos
409         typecheck.DeclContext = savedclcontext
410         ir.CurFunc = savedcurfn
411 }
412
413 // setupTextLsym initializes the LSym for a with-body text symbol.
414 func setupTextLSym(f *ir.Func, flag int) {
415         if f.Dupok() {
416                 flag |= obj.DUPOK
417         }
418         if f.Wrapper() {
419                 flag |= obj.WRAPPER
420         }
421         if f.ABIWrapper() {
422                 flag |= obj.ABIWRAPPER
423         }
424         if f.Needctxt() {
425                 flag |= obj.NEEDCTXT
426         }
427         if f.Pragma&ir.Nosplit != 0 {
428                 flag |= obj.NOSPLIT
429         }
430         if f.ReflectMethod() {
431                 flag |= obj.REFLECTMETHOD
432         }
433
434         // Clumsy but important.
435         // For functions that could be on the path of invoking a deferred
436         // function that can recover (runtime.reflectcall, reflect.callReflect,
437         // and reflect.callMethod), we want the panic+recover special handling.
438         // See test/recover.go for test cases and src/reflect/value.go
439         // for the actual functions being considered.
440         //
441         // runtime.reflectcall is an assembly function which tailcalls
442         // WRAPPER functions (runtime.callNN). Its ABI wrapper needs WRAPPER
443         // flag as well.
444         fnname := f.Sym().Name
445         if base.Ctxt.Pkgpath == "runtime" && fnname == "reflectcall" {
446                 flag |= obj.WRAPPER
447         } else if base.Ctxt.Pkgpath == "reflect" {
448                 switch fnname {
449                 case "callReflect", "callMethod":
450                         flag |= obj.WRAPPER
451                 }
452         }
453
454         base.Ctxt.InitTextSym(f.LSym, flag)
455 }