wrappers.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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. tparams := fn.Signature.Params()
  128. for i, n := start, tparams.Len(); i < n; i++ {
  129. fn.addParamObj(tparams.At(i))
  130. }
  131. }
  132. // -- bounds -----------------------------------------------------------
  133. // makeBound returns a bound method wrapper (or "bound"), a synthetic
  134. // function that delegates to a concrete or interface method denoted
  135. // by obj. The resulting function has no receiver, but has one free
  136. // variable which will be used as the method's receiver in the
  137. // tail-call.
  138. //
  139. // Use MakeClosure with such a wrapper to construct a bound method
  140. // closure. e.g.:
  141. //
  142. // type T int or: type T interface { meth() }
  143. // func (t T) meth()
  144. // var t T
  145. // f := t.meth
  146. // f() // calls t.meth()
  147. //
  148. // f is a closure of a synthetic wrapper defined as if by:
  149. //
  150. // f := func() { return t.meth() }
  151. //
  152. // Unlike makeWrapper, makeBound need perform no indirection or field
  153. // selections because that can be done before the closure is
  154. // constructed.
  155. //
  156. // EXCLUSIVE_LOCKS_ACQUIRED(meth.Prog.methodsMu)
  157. //
  158. func makeBound(prog *Program, obj *types.Func) *Function {
  159. prog.methodsMu.Lock()
  160. defer prog.methodsMu.Unlock()
  161. fn, ok := prog.bounds[obj]
  162. if !ok {
  163. description := fmt.Sprintf("bound method wrapper for %s", obj)
  164. if prog.mode&LogSource != 0 {
  165. defer logStack("%s", description)()
  166. }
  167. fn = &Function{
  168. name: obj.Name() + "$bound",
  169. object: obj,
  170. Signature: changeRecv(obj.Type().(*types.Signature), nil), // drop receiver
  171. Synthetic: description,
  172. Prog: prog,
  173. pos: obj.Pos(),
  174. }
  175. fv := &FreeVar{name: "recv", typ: recvType(obj), parent: fn}
  176. fn.FreeVars = []*FreeVar{fv}
  177. fn.startBody()
  178. createParams(fn, 0)
  179. var c Call
  180. if !isInterface(recvType(obj)) { // concrete
  181. c.Call.Value = prog.declaredFunc(obj)
  182. c.Call.Args = []Value{fv}
  183. } else {
  184. c.Call.Value = fv
  185. c.Call.Method = obj
  186. }
  187. for _, arg := range fn.Params {
  188. c.Call.Args = append(c.Call.Args, arg)
  189. }
  190. emitTailCall(fn, &c)
  191. fn.finishBody()
  192. prog.bounds[obj] = fn
  193. }
  194. return fn
  195. }
  196. // -- thunks -----------------------------------------------------------
  197. // makeThunk returns a thunk, a synthetic function that delegates to a
  198. // concrete or interface method denoted by sel.Obj(). The resulting
  199. // function has no receiver, but has an additional (first) regular
  200. // parameter.
  201. //
  202. // Precondition: sel.Kind() == types.MethodExpr.
  203. //
  204. // type T int or: type T interface { meth() }
  205. // func (t T) meth()
  206. // f := T.meth
  207. // var t T
  208. // f(t) // calls t.meth()
  209. //
  210. // f is a synthetic wrapper defined as if by:
  211. //
  212. // f := func(t T) { return t.meth() }
  213. //
  214. // TODO(adonovan): opt: currently the stub is created even when used
  215. // directly in a function call: C.f(i, 0). This is less efficient
  216. // than inlining the stub.
  217. //
  218. // EXCLUSIVE_LOCKS_ACQUIRED(meth.Prog.methodsMu)
  219. //
  220. func makeThunk(prog *Program, sel *types.Selection) *Function {
  221. if sel.Kind() != types.MethodExpr {
  222. panic(sel)
  223. }
  224. key := selectionKey{
  225. kind: sel.Kind(),
  226. recv: sel.Recv(),
  227. obj: sel.Obj(),
  228. index: fmt.Sprint(sel.Index()),
  229. indirect: sel.Indirect(),
  230. }
  231. prog.methodsMu.Lock()
  232. defer prog.methodsMu.Unlock()
  233. // Canonicalize key.recv to avoid constructing duplicate thunks.
  234. canonRecv, ok := prog.canon.At(key.recv).(types.Type)
  235. if !ok {
  236. canonRecv = key.recv
  237. prog.canon.Set(key.recv, canonRecv)
  238. }
  239. key.recv = canonRecv
  240. fn, ok := prog.thunks[key]
  241. if !ok {
  242. fn = makeWrapper(prog, sel)
  243. if fn.Signature.Recv() != nil {
  244. panic(fn) // unexpected receiver
  245. }
  246. prog.thunks[key] = fn
  247. }
  248. return fn
  249. }
  250. func changeRecv(s *types.Signature, recv *types.Var) *types.Signature {
  251. return types.NewSignature(recv, s.Params(), s.Results(), s.Variadic())
  252. }
  253. // selectionKey is like types.Selection but a usable map key.
  254. type selectionKey struct {
  255. kind types.SelectionKind
  256. recv types.Type // canonicalized via Program.canon
  257. obj types.Object
  258. index string
  259. indirect bool
  260. }