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.
7 // This file defines synthesis of Functions that delegate to declared
8 // methods; they come in three kinds:
10 // (1) wrappers: methods that wrap declared methods, performing
11 // implicit pointer indirections and embedded field selections.
13 // (2) thunks: funcs that wrap declared methods. Like wrappers,
14 // thunks perform indirections and field selections. The thunk's
15 // first parameter is used as the receiver for the method call.
17 // (3) bounds: funcs that wrap declared methods. The bound's sole
18 // free variable, supplied by a closure, is used as the receiver
19 // for the method call. No indirections or field selections are
20 // performed since they can be done before the call.
28 // -- wrappers -----------------------------------------------------------
30 // makeWrapper returns a synthetic method that delegates to the
31 // declared method denoted by meth.Obj(), first performing any
32 // necessary pointer indirections or field selections implied by meth.
34 // The resulting method's receiver type is meth.Recv().
36 // This function is versatile but quite subtle! Consider the
37 // following axes of variation when making changes:
38 // - optional receiver indirection
39 // - optional implicit field selections
40 // - meth.Obj() may denote a concrete or an interface method
41 // - the result may be a thunk or a wrapper.
43 // EXCLUSIVE_LOCKS_REQUIRED(prog.methodsMu)
45 func makeWrapper(prog *Program, sel *types.Selection) *Function {
46 obj := sel.Obj().(*types.Func) // the declared function
47 sig := sel.Type().(*types.Signature) // type of this wrapper
49 var recv *types.Var // wrapper's receiver or thunk's params[0]
51 var description string
52 var start int // first regular param
53 if sel.Kind() == types.MethodExpr {
56 recv = sig.Params().At(0)
59 description = "wrapper"
63 description = fmt.Sprintf("%s for %s", description, sel.Obj())
64 if prog.mode&LogSource != 0 {
65 defer logStack("make %s to (%s)", description, recv.Type())()
72 Synthetic: description,
77 fn.addSpilledParam(recv)
78 createParams(fn, start)
80 indices := sel.Index()
82 var v Value = fn.Locals[0] // spilled receiver
83 if isPointer(sel.Recv()) {
86 // For simple indirection wrappers, perform an informative nil-check:
87 // "value method (T).f called using nil *T pointer"
88 if len(indices) == 1 && !isPointer(recvType(obj)) {
90 c.Call.Value = &Builtin{
91 name: "ssa:wrapnilchk",
92 sig: types.NewSignature(nil,
93 types.NewTuple(anonVar(sel.Recv()), anonVar(tString), anonVar(tString)),
94 types.NewTuple(anonVar(sel.Recv())), false),
96 c.Call.Args = []Value{
98 stringConst(deref(sel.Recv()).String()),
99 stringConst(sel.Obj().Name()),
106 // Invariant: v is a pointer, either
107 // value of *A receiver param, or
108 // address of A spilled receiver.
110 // We use pointer arithmetic (FieldAddr possibly followed by
111 // Load) in preference to value extraction (Field possibly
112 // preceded by Load).
114 v = emitImplicitSelections(fn, v, indices[:len(indices)-1])
116 // Invariant: v is a pointer, either
117 // value of implicit *C field, or
118 // address of implicit C field.
121 if r := recvType(obj); !isInterface(r) { // concrete method
125 c.Call.Value = prog.declaredFunc(obj)
126 c.Call.Args = append(c.Call.Args, v)
129 c.Call.Value = emitLoad(fn, v)
131 for _, arg := range fn.Params[1:] {
132 c.Call.Args = append(c.Call.Args, arg)
139 // createParams creates parameters for wrapper method fn based on its
140 // Signature.Params, which do not include the receiver.
141 // start is the index of the first regular parameter to use.
143 func createParams(fn *Function, start int) {
144 tparams := fn.Signature.Params()
145 for i, n := start, tparams.Len(); i < n; i++ {
146 fn.addParamObj(tparams.At(i))
150 // -- bounds -----------------------------------------------------------
152 // makeBound returns a bound method wrapper (or "bound"), a synthetic
153 // function that delegates to a concrete or interface method denoted
154 // by obj. The resulting function has no receiver, but has one free
155 // variable which will be used as the method's receiver in the
158 // Use MakeClosure with such a wrapper to construct a bound method
161 // type T int or: type T interface { meth() }
165 // f() // calls t.meth()
167 // f is a closure of a synthetic wrapper defined as if by:
169 // f := func() { return t.meth() }
171 // Unlike makeWrapper, makeBound need perform no indirection or field
172 // selections because that can be done before the closure is
175 // EXCLUSIVE_LOCKS_ACQUIRED(meth.Prog.methodsMu)
177 func makeBound(prog *Program, obj *types.Func) *Function {
178 prog.methodsMu.Lock()
179 defer prog.methodsMu.Unlock()
180 fn, ok := prog.bounds[obj]
182 description := fmt.Sprintf("bound method wrapper for %s", obj)
183 if prog.mode&LogSource != 0 {
184 defer logStack("%s", description)()
187 name: obj.Name() + "$bound",
189 Signature: changeRecv(obj.Type().(*types.Signature), nil), // drop receiver
190 Synthetic: description,
195 fv := &FreeVar{name: "recv", typ: recvType(obj), parent: fn}
196 fn.FreeVars = []*FreeVar{fv}
201 if !isInterface(recvType(obj)) { // concrete
202 c.Call.Value = prog.declaredFunc(obj)
203 c.Call.Args = []Value{fv}
208 for _, arg := range fn.Params {
209 c.Call.Args = append(c.Call.Args, arg)
214 prog.bounds[obj] = fn
219 // -- thunks -----------------------------------------------------------
221 // makeThunk returns a thunk, a synthetic function that delegates to a
222 // concrete or interface method denoted by sel.Obj(). The resulting
223 // function has no receiver, but has an additional (first) regular
226 // Precondition: sel.Kind() == types.MethodExpr.
228 // type T int or: type T interface { meth() }
232 // f(t) // calls t.meth()
234 // f is a synthetic wrapper defined as if by:
236 // f := func(t T) { return t.meth() }
238 // TODO(adonovan): opt: currently the stub is created even when used
239 // directly in a function call: C.f(i, 0). This is less efficient
240 // than inlining the stub.
242 // EXCLUSIVE_LOCKS_ACQUIRED(meth.Prog.methodsMu)
244 func makeThunk(prog *Program, sel *types.Selection) *Function {
245 if sel.Kind() != types.MethodExpr {
253 index: fmt.Sprint(sel.Index()),
254 indirect: sel.Indirect(),
257 prog.methodsMu.Lock()
258 defer prog.methodsMu.Unlock()
260 // Canonicalize key.recv to avoid constructing duplicate thunks.
261 canonRecv, ok := prog.canon.At(key.recv).(types.Type)
264 prog.canon.Set(key.recv, canonRecv)
268 fn, ok := prog.thunks[key]
270 fn = makeWrapper(prog, sel)
271 if fn.Signature.Recv() != nil {
272 panic(fn) // unexpected receiver
274 prog.thunks[key] = fn
279 func changeRecv(s *types.Signature, recv *types.Var) *types.Signature {
280 return types.NewSignature(recv, s.Params(), s.Results(), s.Variadic())
283 // selectionKey is like types.Selection but a usable map key.
284 type selectionKey struct {
285 kind types.SelectionKind
286 recv types.Type // canonicalized via Program.canon