You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

294 lines
8.1 KiB

  1. // Copyright 2013 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. package ssa
  5. // This file defines synthesis of Functions that delegate to declared
  6. // methods; they come in three kinds:
  7. //
  8. // (1) wrappers: methods that wrap declared methods, performing
  9. // implicit pointer indirections and embedded field selections.
  10. //
  11. // (2) thunks: funcs that wrap declared methods. Like wrappers,
  12. // thunks perform indirections and field selections. The thunk's
  13. // first parameter is used as the receiver for the method call.
  14. //
  15. // (3) bounds: funcs that wrap declared methods. The bound's sole
  16. // free variable, supplied by a closure, is used as the receiver
  17. // for the method call. No indirections or field selections are
  18. // performed since they can be done before the call.
  19. import (
  20. "fmt"
  21. "go/types"
  22. )
  23. // -- wrappers -----------------------------------------------------------
  24. // makeWrapper returns a synthetic method that delegates to the
  25. // declared method denoted by meth.Obj(), first performing any
  26. // necessary pointer indirections or field selections implied by meth.
  27. //
  28. // The resulting method's receiver type is meth.Recv().
  29. //
  30. // This function is versatile but quite subtle! Consider the
  31. // following axes of variation when making changes:
  32. // - optional receiver indirection
  33. // - optional implicit field selections
  34. // - meth.Obj() may denote a concrete or an interface method
  35. // - the result may be a thunk or a wrapper.
  36. //
  37. // EXCLUSIVE_LOCKS_REQUIRED(prog.methodsMu)
  38. //
  39. func makeWrapper(prog *Program, sel *types.Selection) *Function {
  40. obj := sel.Obj().(*types.Func) // the declared function
  41. sig := sel.Type().(*types.Signature) // type of this wrapper
  42. var recv *types.Var // wrapper's receiver or thunk's params[0]
  43. name := obj.Name()
  44. var description string
  45. var start int // first regular param
  46. if sel.Kind() == types.MethodExpr {
  47. name += "$thunk"
  48. description = "thunk"
  49. recv = sig.Params().At(0)
  50. start = 1
  51. } else {
  52. description = "wrapper"
  53. recv = sig.Recv()
  54. }
  55. description = fmt.Sprintf("%s for %s", description, sel.Obj())
  56. if prog.mode&LogSource != 0 {
  57. defer logStack("make %s to (%s)", description, recv.Type())()
  58. }
  59. fn := &Function{
  60. name: name,
  61. method: sel,
  62. object: obj,
  63. Signature: sig,
  64. Synthetic: description,
  65. Prog: prog,
  66. pos: obj.Pos(),
  67. }
  68. fn.startBody()
  69. fn.addSpilledParam(recv)
  70. createParams(fn, start)
  71. indices := sel.Index()
  72. var v Value = fn.Locals[0] // spilled receiver
  73. if isPointer(sel.Recv()) {
  74. v = emitLoad(fn, v)
  75. // For simple indirection wrappers, perform an informative nil-check:
  76. // "value method (T).f called using nil *T pointer"
  77. if len(indices) == 1 && !isPointer(recvType(obj)) {
  78. var c Call
  79. c.Call.Value = &Builtin{
  80. name: "ssa:wrapnilchk",
  81. sig: types.NewSignature(nil,
  82. types.NewTuple(anonVar(sel.Recv()), anonVar(tString), anonVar(tString)),
  83. types.NewTuple(anonVar(sel.Recv())), false),
  84. }
  85. c.Call.Args = []Value{
  86. v,
  87. stringConst(deref(sel.Recv()).String()),
  88. stringConst(sel.Obj().Name()),
  89. }
  90. c.setType(v.Type())
  91. v = fn.emit(&c)
  92. }
  93. }
  94. // Invariant: v is a pointer, either
  95. // value of *A receiver param, or
  96. // address of A spilled receiver.
  97. // We use pointer arithmetic (FieldAddr possibly followed by
  98. // Load) in preference to value extraction (Field possibly
  99. // preceded by Load).
  100. v = emitImplicitSelections(fn, v, indices[:len(indices)-1])
  101. // Invariant: v is a pointer, either
  102. // value of implicit *C field, or
  103. // address of implicit C field.
  104. var c Call
  105. if r := recvType(obj); !isInterface(r) { // concrete method
  106. if !isPointer(r) {
  107. v = emitLoad(fn, v)
  108. }
  109. c.Call.Value = prog.declaredFunc(obj)
  110. c.Call.Args = append(c.Call.Args, v)
  111. } else {
  112. c.Call.Method = obj
  113. c.Call.Value = emitLoad(fn, v)
  114. }
  115. for _, arg := range fn.Params[1:] {
  116. c.Call.Args = append(c.Call.Args, arg)
  117. }
  118. emitTailCall(fn, &c)
  119. fn.finishBody()
  120. return fn
  121. }
  122. // createParams creates parameters for wrapper method fn based on its
  123. // Signature.Params, which do not include the receiver.
  124. // start is the index of the first regular parameter to use.
  125. //
  126. func createParams(fn *Function, start int) {
  127. var last *Parameter
  128. tparams := fn.Signature.Params()
  129. for i, n := start, tparams.Len(); i < n; i++ {
  130. last = fn.addParamObj(tparams.At(i))
  131. }
  132. if fn.Signature.Variadic() {
  133. last.typ = types.NewSlice(last.typ)
  134. }
  135. }
  136. // -- bounds -----------------------------------------------------------
  137. // makeBound returns a bound method wrapper (or "bound"), a synthetic
  138. // function that delegates to a concrete or interface method denoted
  139. // by obj. The resulting function has no receiver, but has one free
  140. // variable which will be used as the method's receiver in the
  141. // tail-call.
  142. //
  143. // Use MakeClosure with such a wrapper to construct a bound method
  144. // closure. e.g.:
  145. //
  146. // type T int or: type T interface { meth() }
  147. // func (t T) meth()
  148. // var t T
  149. // f := t.meth
  150. // f() // calls t.meth()
  151. //
  152. // f is a closure of a synthetic wrapper defined as if by:
  153. //
  154. // f := func() { return t.meth() }
  155. //
  156. // Unlike makeWrapper, makeBound need perform no indirection or field
  157. // selections because that can be done before the closure is
  158. // constructed.
  159. //
  160. // EXCLUSIVE_LOCKS_ACQUIRED(meth.Prog.methodsMu)
  161. //
  162. func makeBound(prog *Program, obj *types.Func) *Function {
  163. prog.methodsMu.Lock()
  164. defer prog.methodsMu.Unlock()
  165. fn, ok := prog.bounds[obj]
  166. if !ok {
  167. description := fmt.Sprintf("bound method wrapper for %s", obj)
  168. if prog.mode&LogSource != 0 {
  169. defer logStack("%s", description)()
  170. }
  171. fn = &Function{
  172. name: obj.Name() + "$bound",
  173. object: obj,
  174. Signature: changeRecv(obj.Type().(*types.Signature), nil), // drop receiver
  175. Synthetic: description,
  176. Prog: prog,
  177. pos: obj.Pos(),
  178. }
  179. fv := &FreeVar{name: "recv", typ: recvType(obj), parent: fn}
  180. fn.FreeVars = []*FreeVar{fv}
  181. fn.startBody()
  182. createParams(fn, 0)
  183. var c Call
  184. if !isInterface(recvType(obj)) { // concrete
  185. c.Call.Value = prog.declaredFunc(obj)
  186. c.Call.Args = []Value{fv}
  187. } else {
  188. c.Call.Value = fv
  189. c.Call.Method = obj
  190. }
  191. for _, arg := range fn.Params {
  192. c.Call.Args = append(c.Call.Args, arg)
  193. }
  194. emitTailCall(fn, &c)
  195. fn.finishBody()
  196. prog.bounds[obj] = fn
  197. }
  198. return fn
  199. }
  200. // -- thunks -----------------------------------------------------------
  201. // makeThunk returns a thunk, a synthetic function that delegates to a
  202. // concrete or interface method denoted by sel.Obj(). The resulting
  203. // function has no receiver, but has an additional (first) regular
  204. // parameter.
  205. //
  206. // Precondition: sel.Kind() == types.MethodExpr.
  207. //
  208. // type T int or: type T interface { meth() }
  209. // func (t T) meth()
  210. // f := T.meth
  211. // var t T
  212. // f(t) // calls t.meth()
  213. //
  214. // f is a synthetic wrapper defined as if by:
  215. //
  216. // f := func(t T) { return t.meth() }
  217. //
  218. // TODO(adonovan): opt: currently the stub is created even when used
  219. // directly in a function call: C.f(i, 0). This is less efficient
  220. // than inlining the stub.
  221. //
  222. // EXCLUSIVE_LOCKS_ACQUIRED(meth.Prog.methodsMu)
  223. //
  224. func makeThunk(prog *Program, sel *types.Selection) *Function {
  225. if sel.Kind() != types.MethodExpr {
  226. panic(sel)
  227. }
  228. key := selectionKey{
  229. kind: sel.Kind(),
  230. recv: sel.Recv(),
  231. obj: sel.Obj(),
  232. index: fmt.Sprint(sel.Index()),
  233. indirect: sel.Indirect(),
  234. }
  235. prog.methodsMu.Lock()
  236. defer prog.methodsMu.Unlock()
  237. // Canonicalize key.recv to avoid constructing duplicate thunks.
  238. canonRecv, ok := prog.canon.At(key.recv).(types.Type)
  239. if !ok {
  240. canonRecv = key.recv
  241. prog.canon.Set(key.recv, canonRecv)
  242. }
  243. key.recv = canonRecv
  244. fn, ok := prog.thunks[key]
  245. if !ok {
  246. fn = makeWrapper(prog, sel)
  247. if fn.Signature.Recv() != nil {
  248. panic(fn) // unexpected receiver
  249. }
  250. prog.thunks[key] = fn
  251. }
  252. return fn
  253. }
  254. func changeRecv(s *types.Signature, recv *types.Var) *types.Signature {
  255. return types.NewSignature(recv, s.Params(), s.Results(), s.Variadic())
  256. }
  257. // selectionKey is like types.Selection but a usable map key.
  258. type selectionKey struct {
  259. kind types.SelectionKind
  260. recv types.Type // canonicalized via Program.canon
  261. obj types.Object
  262. index string
  263. indirect bool
  264. }