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,
74 functionBody: new(functionBody),
76 fn.initHTML(prog.PrintFunc)
78 fn.addSpilledParam(recv, nil)
79 createParams(fn, start)
81 indices := sel.Index()
83 var v Value = fn.Locals[0] // spilled receiver
84 if isPointer(sel.Recv()) {
85 v = emitLoad(fn, v, nil)
87 // For simple indirection wrappers, perform an informative nil-check:
88 // "value method (T).f called using nil *T pointer"
89 if len(indices) == 1 && !isPointer(recvType(obj)) {
91 c.Call.Value = &Builtin{
92 name: "ir:wrapnilchk",
93 sig: types.NewSignature(nil,
94 types.NewTuple(anonVar(sel.Recv()), anonVar(tString), anonVar(tString)),
95 types.NewTuple(anonVar(sel.Recv())), false),
97 c.Call.Args = []Value{
99 emitConst(fn, stringConst(deref(sel.Recv()).String())),
100 emitConst(fn, stringConst(sel.Obj().Name())),
107 // Invariant: v is a pointer, either
108 // value of *A receiver param, or
109 // address of A spilled receiver.
111 // We use pointer arithmetic (FieldAddr possibly followed by
112 // Load) in preference to value extraction (Field possibly
113 // preceded by Load).
115 v = emitImplicitSelections(fn, v, indices[:len(indices)-1], nil)
117 // Invariant: v is a pointer, either
118 // value of implicit *C field, or
119 // address of implicit C field.
122 if r := recvType(obj); !isInterface(r) { // concrete method
124 v = emitLoad(fn, v, nil)
126 c.Call.Value = prog.declaredFunc(obj)
127 c.Call.Args = append(c.Call.Args, v)
130 c.Call.Value = emitLoad(fn, v, nil)
132 for _, arg := range fn.Params[1:] {
133 c.Call.Args = append(c.Call.Args, arg)
135 emitTailCall(fn, &c, nil)
140 // createParams creates parameters for wrapper method fn based on its
141 // Signature.Params, which do not include the receiver.
142 // start is the index of the first regular parameter to use.
144 func createParams(fn *Function, start int) {
145 tparams := fn.Signature.Params()
146 for i, n := start, tparams.Len(); i < n; i++ {
147 fn.addParamObj(tparams.At(i), nil)
151 // -- bounds -----------------------------------------------------------
153 // makeBound returns a bound method wrapper (or "bound"), a synthetic
154 // function that delegates to a concrete or interface method denoted
155 // by obj. The resulting function has no receiver, but has one free
156 // variable which will be used as the method's receiver in the
159 // Use MakeClosure with such a wrapper to construct a bound method
162 // type T int or: type T interface { meth() }
166 // f() // calls t.meth()
168 // f is a closure of a synthetic wrapper defined as if by:
170 // f := func() { return t.meth() }
172 // Unlike makeWrapper, makeBound need perform no indirection or field
173 // selections because that can be done before the closure is
176 // EXCLUSIVE_LOCKS_ACQUIRED(meth.Prog.methodsMu)
178 func makeBound(prog *Program, obj *types.Func) *Function {
179 prog.methodsMu.Lock()
180 defer prog.methodsMu.Unlock()
181 fn, ok := prog.bounds[obj]
183 description := fmt.Sprintf("bound method wrapper for %s", obj)
184 if prog.mode&LogSource != 0 {
185 defer logStack("%s", description)()
188 name: obj.Name() + "$bound",
190 Signature: changeRecv(obj.Type().(*types.Signature), nil), // drop receiver
191 Synthetic: description,
193 functionBody: new(functionBody),
195 fn.initHTML(prog.PrintFunc)
197 fv := &FreeVar{name: "recv", typ: recvType(obj), parent: fn}
198 fn.FreeVars = []*FreeVar{fv}
203 if !isInterface(recvType(obj)) { // concrete
204 c.Call.Value = prog.declaredFunc(obj)
205 c.Call.Args = []Value{fv}
210 for _, arg := range fn.Params {
211 c.Call.Args = append(c.Call.Args, arg)
213 emitTailCall(fn, &c, nil)
216 prog.bounds[obj] = fn
221 // -- thunks -----------------------------------------------------------
223 // makeThunk returns a thunk, a synthetic function that delegates to a
224 // concrete or interface method denoted by sel.Obj(). The resulting
225 // function has no receiver, but has an additional (first) regular
228 // Precondition: sel.Kind() == types.MethodExpr.
230 // type T int or: type T interface { meth() }
234 // f(t) // calls t.meth()
236 // f is a synthetic wrapper defined as if by:
238 // f := func(t T) { return t.meth() }
240 // TODO(adonovan): opt: currently the stub is created even when used
241 // directly in a function call: C.f(i, 0). This is less efficient
242 // than inlining the stub.
244 // EXCLUSIVE_LOCKS_ACQUIRED(meth.Prog.methodsMu)
246 func makeThunk(prog *Program, sel *types.Selection) *Function {
247 if sel.Kind() != types.MethodExpr {
255 index: fmt.Sprint(sel.Index()),
256 indirect: sel.Indirect(),
259 prog.methodsMu.Lock()
260 defer prog.methodsMu.Unlock()
262 // Canonicalize key.recv to avoid constructing duplicate thunks.
263 canonRecv, ok := prog.canon.At(key.recv).(types.Type)
266 prog.canon.Set(key.recv, canonRecv)
270 fn, ok := prog.thunks[key]
272 fn = makeWrapper(prog, sel)
273 if fn.Signature.Recv() != nil {
274 panic(fn) // unexpected receiver
276 prog.thunks[key] = fn
281 func changeRecv(s *types.Signature, recv *types.Var) *types.Signature {
282 return types.NewSignature(recv, s.Params(), s.Results(), s.Variadic())
285 // selectionKey is like types.Selection but a usable map key.
286 type selectionKey struct {
287 kind types.SelectionKind
288 recv types.Type // canonicalized via Program.canon