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.
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"
23 // SymABIs records information provided by the assembler about symbol
24 // definition ABIs and reference ABIs.
26 defs map[string]obj.ABI
27 refs map[string]obj.ABISet
32 func NewSymABIs(myimportpath string) *SymABIs {
33 var localPrefix string
34 if myimportpath != "" {
35 localPrefix = objabi.PathToPrefix(myimportpath) + "."
39 defs: make(map[string]obj.ABI),
40 refs: make(map[string]obj.ABISet),
41 localPrefix: localPrefix,
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):]
59 // ReadSymABIs reads a symabis file that specifies definitions and
60 // references of text symbols by ABI.
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)
71 log.Fatalf("-symabis: %v", err)
74 for lineNum, line := range strings.Split(string(data), "\n") {
76 line = strings.TrimSpace(line)
77 if line == "" || strings.HasPrefix(line, "#") {
81 parts := strings.Fields(line)
86 log.Fatalf(`%s:%d: invalid symabi: syntax is "%s sym abi"`, file, lineNum, parts[0])
88 sym, abistr := parts[1], parts[2]
89 abi, valid := obj.ParseABI(abistr)
91 log.Fatalf(`%s:%d: invalid symabi: unknown abi "%s"`, file, lineNum, abistr)
94 sym = s.canonicalize(sym)
97 if parts[0] == "def" {
100 s.refs[sym] |= obj.ABISetOf(abi)
103 log.Fatalf(`%s:%d: invalid symabi type "%s"`, file, lineNum, parts[0])
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.
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 {
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)
128 // Apply ABI defs and refs to Funcs and generate wrappers.
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 {
144 if sym.Linkname != "" {
145 symName = s.canonicalize(sym.Linkname)
147 // These names will already be canonical.
148 symName = sym.Pkg.Prefix + "." + sym.Name
151 // Apply definitions.
152 defABI, hasDefABI := s.defs[symName]
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.
164 // If cgo-exported, add the definition ABI to the cgo
166 cgoExport := cgoExports[symName]
167 for _, pprag := range cgoExport {
168 // The export pragmas have the form:
170 // cgo_export_* <local> [<remote>]
172 // If <remote> is omitted, it's the same as
177 // cgo_export_* <local> <remote> <ABI>
178 if len(*pprag) == 2 {
179 *pprag = append(*pprag, (*pprag)[1])
181 // Add the ABI argument.
182 *pprag = append(*pprag, fn.ABI.String())
186 if abis, ok := s.refs[symName]; ok {
189 // Assume all functions are referenced at least as
190 // ABIInternal, since they may be referenced from
192 fn.ABIRefs.Set(obj.ABIInternal, true)
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.
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
210 // Double check that cgo-exported symbols don't get
212 if len(cgoExport) > 0 && fn.ABIRefs&^obj.ABISetOf(fn.ABI) != 0 {
213 base.Fatalf("cgo exported function %s cannot have ABI wrappers", fn)
216 if !objabi.Experiment.RegabiWrappers {
217 // We'll generate ABI aliases instead of
218 // wrappers once we have LSyms in InitLSym.
222 forEachWrapperABI(fn, makeABIWrapper)
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.
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) {
236 base.FatalfAt(f.Pos(), "InitLSym called twice on %v", f)
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)
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.
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
254 staticdata.NeedFuncSym(f)
256 if !objabi.Experiment.RegabiWrappers {
257 // Create ABI aliases instead of wrappers.
258 forEachWrapperABI(f, makeABIAlias)
266 func forEachWrapperABI(fn *ir.Func, cb func(fn *ir.Func, wrapperABI obj.ABI)) {
267 need := fn.ABIRefs &^ obj.ABISetOf(fn.ABI)
272 for wrapperABI := obj.ABI(0); wrapperABI < obj.ABICount; wrapperABI++ {
273 if !need.Get(wrapperABI) {
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.
288 Type: objabi.SABIALIAS,
289 R: []obj.Reloc{{Sym: f.LSym}}, // 0 size, so "informational"
291 asym.SetABI(wrapperABI)
292 asym.Set(obj.AttrDuplicateOK, true)
293 base.Ctxt.ABIAliases = append(base.Ctxt.ABIAliases, asym)
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)
303 // Q: is this needed?
305 savedclcontext := typecheck.DeclContext
306 savedcurfn := ir.CurFunc
308 base.Pos = base.AutogeneratedPos
309 typecheck.DeclContext = ir.PEXTERN
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")
318 // Manufacture a new func type to use for the wrapper.
319 var noReceiver *ir.Field
320 tfn := ir.NewFuncType(base.Pos,
322 typecheck.NewFuncParams(ft.Params(), true),
323 typecheck.NewFuncParams(ft.Results(), false))
325 // Reuse f's types.Sym to create a new ODCLFUNC/function.
326 fn := typecheck.DeclFunc(f.Nname.Sym(), tfn)
329 fn.SetABIWrapper(true)
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.
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
359 // Generate call. Use tail call if no params and no returns,
360 // but a regular call otherwise.
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.
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.
382 tail = ir.NewTailCallStmt(base.Pos, f.Nname)
384 call := ir.NewCallExpr(base.Pos, ir.OCALL, f.Nname, nil)
385 call.Args = ir.ParamNames(tfn.Type())
386 call.IsDDD = tfn.Type().IsVariadic()
388 if tfn.Type().NumResults() > 0 {
389 n := ir.NewReturnStmt(base.Pos, nil)
390 n.Results = []ir.Node{call}
396 typecheck.FinishFuncBody()
397 if base.Debug.DclStack != 0 {
398 types.CheckDclstack()
403 typecheck.Stmts(fn.Body)
405 typecheck.Target.Decls = append(typecheck.Target.Decls, fn)
407 // Restore previous context.
409 typecheck.DeclContext = savedclcontext
410 ir.CurFunc = savedcurfn
413 // setupTextLsym initializes the LSym for a with-body text symbol.
414 func setupTextLSym(f *ir.Func, flag int) {
422 flag |= obj.ABIWRAPPER
427 if f.Pragma&ir.Nosplit != 0 {
430 if f.ReflectMethod() {
431 flag |= obj.REFLECTMETHOD
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.
441 // runtime.reflectcall is an assembly function which tailcalls
442 // WRAPPER functions (runtime.callNN). Its ABI wrapper needs WRAPPER
444 fnname := f.Sym().Name
445 if base.Ctxt.Pkgpath == "runtime" && fnname == "reflectcall" {
447 } else if base.Ctxt.Pkgpath == "reflect" {
449 case "callReflect", "callMethod":
454 base.Ctxt.InitTextSym(f.LSym, flag)