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
5package ir
6
7// This file defines synthesis of Functions that delegate to declared
8// methods; they come in three kinds:
9//
10// (1) wrappers: methods that wrap declared methods, performing
11//     implicit pointer indirections and embedded field selections.
12//
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.
16//
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.
21
22import (
23	"fmt"
24
25	"go/types"
26)
27
28// -- wrappers -----------------------------------------------------------
29
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.
33//
34// The resulting method's receiver type is meth.Recv().
35//
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.
42//
43// EXCLUSIVE_LOCKS_REQUIRED(prog.methodsMu)
44//
45func 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
48
49	var recv *types.Var // wrapper's receiver or thunk's params[0]
50	name := obj.Name()
51	var description string
52	var start int // first regular param
53	if sel.Kind() == types.MethodExpr {
54		name += "$thunk"
55		description = "thunk"
56		recv = sig.Params().At(0)
57		start = 1
58	} else {
59		description = "wrapper"
60		recv = sig.Recv()
61	}
62
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())()
66	}
67	fn := &Function{
68		name:         name,
69		method:       sel,
70		object:       obj,
71		Signature:    sig,
72		Synthetic:    description,
73		Prog:         prog,
74		functionBody: new(functionBody),
75	}
76	fn.initHTML(prog.PrintFunc)
77	fn.startBody()
78	fn.addSpilledParam(recv, nil)
79	createParams(fn, start)
80
81	indices := sel.Index()
82
83	var v Value = fn.Locals[0] // spilled receiver
84	if isPointer(sel.Recv()) {
85		v = emitLoad(fn, v, nil)
86
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)) {
90			var c Call
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),
96			}
97			c.Call.Args = []Value{
98				v,
99				emitConst(fn, stringConst(deref(sel.Recv()).String())),
100				emitConst(fn, stringConst(sel.Obj().Name())),
101			}
102			c.setType(v.Type())
103			v = fn.emit(&c, nil)
104		}
105	}
106
107	// Invariant: v is a pointer, either
108	//   value of *A receiver param, or
109	// address of  A spilled receiver.
110
111	// We use pointer arithmetic (FieldAddr possibly followed by
112	// Load) in preference to value extraction (Field possibly
113	// preceded by Load).
114
115	v = emitImplicitSelections(fn, v, indices[:len(indices)-1], nil)
116
117	// Invariant: v is a pointer, either
118	//   value of implicit *C field, or
119	// address of implicit  C field.
120
121	var c Call
122	if r := recvType(obj); !isInterface(r) { // concrete method
123		if !isPointer(r) {
124			v = emitLoad(fn, v, nil)
125		}
126		c.Call.Value = prog.declaredFunc(obj)
127		c.Call.Args = append(c.Call.Args, v)
128	} else {
129		c.Call.Method = obj
130		c.Call.Value = emitLoad(fn, v, nil)
131	}
132	for _, arg := range fn.Params[1:] {
133		c.Call.Args = append(c.Call.Args, arg)
134	}
135	emitTailCall(fn, &c, nil)
136	fn.finishBody()
137	return fn
138}
139
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.
143//
144func 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)
148	}
149}
150
151// -- bounds -----------------------------------------------------------
152
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
157// tail-call.
158//
159// Use MakeClosure with such a wrapper to construct a bound method
160// closure.  e.g.:
161//
162//   type T int          or:  type T interface { meth() }
163//   func (t T) meth()
164//   var t T
165//   f := t.meth
166//   f() // calls t.meth()
167//
168// f is a closure of a synthetic wrapper defined as if by:
169//
170//   f := func() { return t.meth() }
171//
172// Unlike makeWrapper, makeBound need perform no indirection or field
173// selections because that can be done before the closure is
174// constructed.
175//
176// EXCLUSIVE_LOCKS_ACQUIRED(meth.Prog.methodsMu)
177//
178func makeBound(prog *Program, obj *types.Func) *Function {
179	prog.methodsMu.Lock()
180	defer prog.methodsMu.Unlock()
181	fn, ok := prog.bounds[obj]
182	if !ok {
183		description := fmt.Sprintf("bound method wrapper for %s", obj)
184		if prog.mode&LogSource != 0 {
185			defer logStack("%s", description)()
186		}
187		fn = &Function{
188			name:         obj.Name() + "$bound",
189			object:       obj,
190			Signature:    changeRecv(obj.Type().(*types.Signature), nil), // drop receiver
191			Synthetic:    description,
192			Prog:         prog,
193			functionBody: new(functionBody),
194		}
195		fn.initHTML(prog.PrintFunc)
196
197		fv := &FreeVar{name: "recv", typ: recvType(obj), parent: fn}
198		fn.FreeVars = []*FreeVar{fv}
199		fn.startBody()
200		createParams(fn, 0)
201		var c Call
202
203		if !isInterface(recvType(obj)) { // concrete
204			c.Call.Value = prog.declaredFunc(obj)
205			c.Call.Args = []Value{fv}
206		} else {
207			c.Call.Value = fv
208			c.Call.Method = obj
209		}
210		for _, arg := range fn.Params {
211			c.Call.Args = append(c.Call.Args, arg)
212		}
213		emitTailCall(fn, &c, nil)
214		fn.finishBody()
215
216		prog.bounds[obj] = fn
217	}
218	return fn
219}
220
221// -- thunks -----------------------------------------------------------
222
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
226// parameter.
227//
228// Precondition: sel.Kind() == types.MethodExpr.
229//
230//   type T int          or:  type T interface { meth() }
231//   func (t T) meth()
232//   f := T.meth
233//   var t T
234//   f(t) // calls t.meth()
235//
236// f is a synthetic wrapper defined as if by:
237//
238//   f := func(t T) { return t.meth() }
239//
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.
243//
244// EXCLUSIVE_LOCKS_ACQUIRED(meth.Prog.methodsMu)
245//
246func makeThunk(prog *Program, sel *types.Selection) *Function {
247	if sel.Kind() != types.MethodExpr {
248		panic(sel)
249	}
250
251	key := selectionKey{
252		kind:     sel.Kind(),
253		recv:     sel.Recv(),
254		obj:      sel.Obj(),
255		index:    fmt.Sprint(sel.Index()),
256		indirect: sel.Indirect(),
257	}
258
259	prog.methodsMu.Lock()
260	defer prog.methodsMu.Unlock()
261
262	// Canonicalize key.recv to avoid constructing duplicate thunks.
263	canonRecv, ok := prog.canon.At(key.recv).(types.Type)
264	if !ok {
265		canonRecv = key.recv
266		prog.canon.Set(key.recv, canonRecv)
267	}
268	key.recv = canonRecv
269
270	fn, ok := prog.thunks[key]
271	if !ok {
272		fn = makeWrapper(prog, sel)
273		if fn.Signature.Recv() != nil {
274			panic(fn) // unexpected receiver
275		}
276		prog.thunks[key] = fn
277	}
278	return fn
279}
280
281func changeRecv(s *types.Signature, recv *types.Var) *types.Signature {
282	return types.NewSignature(recv, s.Params(), s.Results(), s.Variadic())
283}
284
285// selectionKey is like types.Selection but a usable map key.
286type selectionKey struct {
287	kind     types.SelectionKind
288	recv     types.Type // canonicalized via Program.canon
289	obj      types.Object
290	index    string
291	indirect bool
292}
293