• Dmitry Vyukov's avatar
    cmd/gc: capture variables by value · 0e80b2e0
    Dmitry Vyukov authored
    Language specification says that variables are captured by reference.
    And that is what gc compiler does. However, in lots of cases it is
    possible to capture variables by value under the hood without
    affecting visible behavior of programs. For example, consider
    the following typical pattern:
    
    	func (o *Obj) requestMany(urls []string) []Result {
    		wg := new(sync.WaitGroup)
    		wg.Add(len(urls))
    		res := make([]Result, len(urls))
    		for i := range urls {
    			i := i
    			go func() {
    				res[i] = o.requestOne(urls[i])
    				wg.Done()
    			}()
    		}
    		wg.Wait()
    		return res
    	}
    
    Currently o, wg, res, and i are captured by reference causing 3+len(urls)
    allocations (e.g. PPARAM o is promoted to PPARAMREF and moved to heap).
    But all of them can be captured by value without changing behavior.
    
    This change implements simple strategy for capturing by value:
    if a captured variable is not addrtaken and never assigned to,
    then it is captured by value (it is effectively const).
    This simple strategy turned out to be very effective:
    ~80% of all captures in std lib are turned into value captures.
    The remaining 20% are mostly in defers and non-escaping closures,
    that is, they do not cause allocations anyway.
    
    benchmark                                    old allocs     new allocs     delta
    BenchmarkCompressedZipGarbage                153            126            -17.65%
    BenchmarkEncodeDigitsSpeed1e4                91             69             -24.18%
    BenchmarkEncodeDigitsSpeed1e5                178            129            -27.53%
    BenchmarkEncodeDigitsSpeed1e6                1510           1051           -30.40%
    BenchmarkEncodeDigitsDefault1e4              100            75             -25.00%
    BenchmarkEncodeDigitsDefault1e5              193            139            -27.98%
    BenchmarkEncodeDigitsDefault1e6              1420           985            -30.63%
    BenchmarkEncodeDigitsCompress1e4             100            75             -25.00%
    BenchmarkEncodeDigitsCompress1e5             193            139            -27.98%
    BenchmarkEncodeDigitsCompress1e6             1420           985            -30.63%
    BenchmarkEncodeTwainSpeed1e4                 109            81             -25.69%
    BenchmarkEncodeTwainSpeed1e5                 211            151            -28.44%
    BenchmarkEncodeTwainSpeed1e6                 1588           1097           -30.92%
    BenchmarkEncodeTwainDefault1e4               103            77             -25.24%
    BenchmarkEncodeTwainDefault1e5               199            143            -28.14%
    BenchmarkEncodeTwainDefault1e6               1324           917            -30.74%
    BenchmarkEncodeTwainCompress1e4              103            77             -25.24%
    BenchmarkEncodeTwainCompress1e5              190            137            -27.89%
    BenchmarkEncodeTwainCompress1e6              1327           919            -30.75%
    BenchmarkConcurrentDBExec                    16223          16220          -0.02%
    BenchmarkConcurrentStmtQuery                 17687          16182          -8.51%
    BenchmarkConcurrentStmtExec                  5191           5186           -0.10%
    BenchmarkConcurrentTxQuery                   17665          17661          -0.02%
    BenchmarkConcurrentTxExec                    15154          15150          -0.03%
    BenchmarkConcurrentTxStmtQuery               17661          16157          -8.52%
    BenchmarkConcurrentTxStmtExec                3677           3673           -0.11%
    BenchmarkConcurrentRandom                    14000          13614          -2.76%
    BenchmarkManyConcurrentQueries               25             22             -12.00%
    BenchmarkDecodeComplex128Slice               318            252            -20.75%
    BenchmarkDecodeFloat64Slice                  318            252            -20.75%
    BenchmarkDecodeInt32Slice                    318            252            -20.75%
    BenchmarkDecodeStringSlice                   2318           2252           -2.85%
    BenchmarkDecode                              11             8              -27.27%
    BenchmarkEncodeGray                          64             56             -12.50%
    BenchmarkEncodeNRGBOpaque                    64             56             -12.50%
    BenchmarkEncodeNRGBA                         67             58             -13.43%
    BenchmarkEncodePaletted                      68             60             -11.76%
    BenchmarkEncodeRGBOpaque                     64             56             -12.50%
    BenchmarkGoLookupIP                          153            139            -9.15%
    BenchmarkGoLookupIPNoSuchHost                508            466            -8.27%
    BenchmarkGoLookupIPWithBrokenNameServer      245            226            -7.76%
    BenchmarkClientServer                        62             59             -4.84%
    BenchmarkClientServerParallel4               62             59             -4.84%
    BenchmarkClientServerParallel64              62             59             -4.84%
    BenchmarkClientServerParallelTLS4            79             76             -3.80%
    BenchmarkClientServerParallelTLS64           112            109            -2.68%
    BenchmarkCreateGoroutinesCapture             10             6              -40.00%
    BenchmarkAfterFunc                           1006           1005           -0.10%
    
    Fixes #6632.
    
    Change-Id: I0cd51e4d356331d7f3c5f447669080cd19b0d2ca
    Reviewed-on: https://go-review.googlesource.com/3166Reviewed-by: default avatarRuss Cox <rsc@golang.org>
    0e80b2e0
closure.c 13.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/*
 * function literals aka closures
 */

#include <u.h>
#include <libc.h>
#include "go.h"

void
closurehdr(Node *ntype)
{
	Node *n, *name, *a;
	NodeList *l;

	n = nod(OCLOSURE, N, N);
	n->ntype = ntype;
	n->funcdepth = funcdepth;

	funchdr(n);

	// steal ntype's argument names and
	// leave a fresh copy in their place.
	// references to these variables need to
	// refer to the variables in the external
	// function declared below; see walkclosure.
	n->list = ntype->list;
	n->rlist = ntype->rlist;
	ntype->list = nil;
	ntype->rlist = nil;
	for(l=n->list; l; l=l->next) {
		name = l->n->left;
		if(name)
			name = newname(name->sym);
		a = nod(ODCLFIELD, name, l->n->right);
		a->isddd = l->n->isddd;
		if(name)
			name->isddd = a->isddd;
		ntype->list = list(ntype->list, a);
	}
	for(l=n->rlist; l; l=l->next) {
		name = l->n->left;
		if(name)
			name = newname(name->sym);
		ntype->rlist = list(ntype->rlist, nod(ODCLFIELD, name, l->n->right));
	}
}

Node*
closurebody(NodeList *body)
{
	Node *func, *v;
	NodeList *l;

	if(body == nil)
		body = list1(nod(OEMPTY, N, N));

	func = curfn;
	func->nbody = body;
	func->endlineno = lineno;
	funcbody(func);

	// closure-specific variables are hanging off the
	// ordinary ones in the symbol table; see oldname.
	// unhook them.
	// make the list of pointers for the closure call.
	for(l=func->cvars; l; l=l->next) {
		v = l->n;
		v->closure->closure = v->outer;
		v->outerexpr = oldname(v->sym);
	}

	return func;
}

static Node* makeclosure(Node *func);

void
typecheckclosure(Node *func, int top)
{
	Node *oldfn, *n;
	NodeList *l;
	int olddd;

	for(l=func->cvars; l; l=l->next) {
		n = l->n->closure;
		if(!n->captured) {
			n->captured = 1;
			if(n->decldepth == 0)
				fatal("typecheckclosure: var %hN does not have decldepth assigned", n);
			// Ignore assignments to the variable in straightline code
			// preceding the first capturing by a closure.
			if(n->decldepth == decldepth)
				n->assigned = 0;
		}
	}

	for(l=func->dcl; l; l=l->next)
		if(l->n->op == ONAME && (l->n->class == PPARAM || l->n->class == PPARAMOUT))
			l->n->decldepth = 1;

	oldfn = curfn;
	typecheck(&func->ntype, Etype);
	func->type = func->ntype->type;

	// Type check the body now, but only if we're inside a function.
	// At top level (in a variable initialization: curfn==nil) we're not
	// ready to type check code yet; we'll check it later, because the
	// underlying closure function we create is added to xtop.
	if(curfn && func->type != T) {
		curfn = func;
		olddd = decldepth;
		decldepth = 1;
		typechecklist(func->nbody, Etop);
		decldepth = olddd;
		curfn = oldfn;
	}

	// Remember closure context for capturevars.
	func->etype = (top & (Ecall|Eproc)) == Ecall;

	// Create top-level function 
	xtop = list(xtop, makeclosure(func));
}

static Node*
makeclosure(Node *func)
{
	Node *xtype, *xfunc;
	static int closgen;

	/*
	 * wrap body in external function
	 * that begins by reading closure parameters.
	 */
	xtype = nod(OTFUNC, N, N);
	xtype->list = func->list;
	xtype->rlist = func->rlist;

	// create the function
	xfunc = nod(ODCLFUNC, N, N);
	snprint(namebuf, sizeof namebuf, "func·%.3d", ++closgen);
	xfunc->nname = newname(lookup(namebuf));
	xfunc->nname->sym->flags |= SymExported; // disable export
	xfunc->nname->ntype = xtype;
	xfunc->nname->defn = xfunc;
	declare(xfunc->nname, PFUNC);
	xfunc->nname->funcdepth = func->funcdepth;
	xfunc->funcdepth = func->funcdepth;
	xfunc->endlineno = func->endlineno;

	xfunc->nbody = func->nbody;
	xfunc->dcl = concat(func->dcl, xfunc->dcl);
	if(xfunc->nbody == nil)
		fatal("empty body - won't generate any code");
	typecheck(&xfunc, Etop);

	xfunc->closure = func;
	func->closure = xfunc;
	
	func->nbody = nil;
	func->list = nil;
	func->rlist = nil;

	return xfunc;
}

// capturevars is called in a separate phase after all typechecking is done.
// It decides whether each variable captured by a closure should be captured
// by value or by reference.
// We use value capturing for values <= 128 bytes that are never reassigned
// after declaration.
void
capturevars(Node *xfunc)
{
	Node *func, *v, *addr, *cv, *outer;
	NodeList *l, *body;
	char *p;
	vlong offset;
	int nvar, lno;

	lno = lineno;
	lineno = xfunc->lineno;

	nvar = 0;
	body = nil;
	offset = widthptr;
	func = xfunc->closure;
	func->enter = nil;
	for(l=func->cvars; l; l=l->next) {
		v = l->n;
		if(v->type == T) {
			// if v->type is nil, it means v looked like it was
			// going to be used in the closure but wasn't.
			// this happens because when parsing a, b, c := f()
			// the a, b, c gets parsed as references to older
			// a, b, c before the parser figures out this is a
			// declaration.
			v->op = OXXX;
			continue;
		}
		nvar++;

		// type check the & of closed variables outside the closure,
		// so that the outer frame also grabs them and knows they escape.
		dowidth(v->type);
		outer = v->outerexpr;
		v->outerexpr = N;
		if(!v->closure->addrtaken && !v->closure->assigned && v->type->width <= 128)
			v->byval = 1;
		else {
			outer = nod(OADDR, outer, N);
			// For a closure that is called in place, but not
			// inside a go statement, avoid moving variables to the heap.
			outer->etype = func->etype;
		}
		if(debug['m'] > 1)
			warnl(v->lineno, "%S capturing by %s: %S (addr=%d assign=%d width=%d)",
				(v->curfn && v->curfn->nname) ? v->curfn->nname->sym : S, v->byval ? "value" : "ref",
				v->sym, v->closure->addrtaken, v->closure->assigned, (int32)v->type->width);
		typecheck(&outer, Erv);
		func->enter = list(func->enter, outer);

		// declare variables holding addresses taken from closure
		// and initialize in entry prologue.
		addr = nod(ONAME, N, N);
		p = smprint("&%s", v->sym->name);
		addr->sym = lookup(p);
		free(p);
		addr->ntype = nod(OIND, typenod(v->type), N);
		addr->class = PAUTO;
		addr->addable = 1;
		addr->ullman = 1;
		addr->used = 1;
		addr->curfn = xfunc;
		xfunc->dcl = list(xfunc->dcl, addr);
		v->heapaddr = addr;
		cv = nod(OCLOSUREVAR, N, N);
		if(v->byval) {
			cv->type = v->type;
			offset = rnd(offset, v->type->align);
			cv->xoffset = offset;
			offset += v->type->width;
			body = list(body, nod(OAS, addr, nod(OADDR, cv, N)));
		} else {
			v->closure->addrtaken = 1;
			cv->type = ptrto(v->type);
			offset = rnd(offset, widthptr);
			cv->xoffset = offset;
			offset += widthptr;
			body = list(body, nod(OAS, addr, cv));
		}
	}
	typechecklist(body, Etop);
	walkstmtlist(body);
	xfunc->enter = body;
	xfunc->needctxt = nvar > 0;
	func->etype = 0;

	lineno = lno;
}

Node*
walkclosure(Node *func, NodeList **init)
{
	Node *clos, *typ, *typ1, *v;
	NodeList *l;

	// If no closure vars, don't bother wrapping.
	if(func->cvars == nil)
		return func->closure->nname;

	// Create closure in the form of a composite literal.
	// supposing the closure captures an int i and a string s
	// and has one float64 argument and no results,
	// the generated code looks like:
	//
	//	clos = &struct{F uintptr; A0 *int; A1 *string}{func·001, &i, &s}
	//
	// The use of the struct provides type information to the garbage
	// collector so that it can walk the closure. We could use (in this case)
	// [3]unsafe.Pointer instead, but that would leave the gc in the dark.
	// The information appears in the binary in the form of type descriptors;
	// the struct is unnamed so that closures in multiple packages with the
	// same struct type can share the descriptor.

	typ = nod(OTSTRUCT, N, N);
	typ->list = list1(nod(ODCLFIELD, newname(lookup("F")), typenod(types[TUINTPTR])));
	for(l=func->cvars; l; l=l->next) {
		v = l->n;
		if(v->op == OXXX)
			continue;
		typ1 = typenod(v->type);
		if(!v->byval)
			typ1 = nod(OIND, typ1, N);
		typ->list = list(typ->list, nod(ODCLFIELD, newname(v->sym), typ1));
	}

	clos = nod(OCOMPLIT, N, nod(OIND, typ, N));
	clos->esc = func->esc;
	clos->right->implicit = 1;
	clos->list = concat(list1(nod(OCFUNC, func->closure->nname, N)), func->enter);

	// Force type conversion from *struct to the func type.
	clos = nod(OCONVNOP, clos, N);
	clos->type = func->type;

	typecheck(&clos, Erv);
	// typecheck will insert a PTRLIT node under CONVNOP,
	// tag it with escape analysis result.
	clos->left->esc = func->esc;
	// non-escaping temp to use, if any.
	// orderexpr did not compute the type; fill it in now.
	if(func->alloc != N) {
		func->alloc->type = clos->left->left->type;
		func->alloc->orig->type = func->alloc->type;
		clos->left->right = func->alloc;
		func->alloc = N;
	}
	walkexpr(&clos, init);

	return clos;
}

static Node *makepartialcall(Node*, Type*, Node*);

void
typecheckpartialcall(Node *fn, Node *sym)
{
	switch(fn->op) {
	case ODOTINTER:
	case ODOTMETH:
		break;
	default:
		fatal("invalid typecheckpartialcall");
	}

	// Create top-level function.
	fn->nname = makepartialcall(fn, fn->type, sym);
	fn->right = sym;
	fn->op = OCALLPART;
	fn->type = fn->nname->type;
}

static Node*
makepartialcall(Node *fn, Type *t0, Node *meth)
{
	Node *ptr, *n, *fld, *call, *xtype, *xfunc, *cv, *savecurfn;
	Type *rcvrtype, *basetype, *t;
	NodeList *body, *l, *callargs, *retargs;
	char *p;
	Sym *sym;
	Pkg *spkg;
	static Pkg* gopkg;
	int i, ddd;

	// TODO: names are not right
	rcvrtype = fn->left->type;
	if(exportname(meth->sym->name))
		p = smprint("%-hT.%s·fm", rcvrtype, meth->sym->name);
	else
		p = smprint("%-hT.(%-S)·fm", rcvrtype, meth->sym);
	basetype = rcvrtype;
	if(isptr[rcvrtype->etype])
		basetype = basetype->type;
	if(basetype->etype != TINTER && basetype->sym == S)
		fatal("missing base type for %T", rcvrtype);

	spkg = nil;
	if(basetype->sym != S)
		spkg = basetype->sym->pkg;
	if(spkg == nil) {
		if(gopkg == nil)
			gopkg = mkpkg(newstrlit("go"));
		spkg = gopkg;
	}
	sym = pkglookup(p, spkg);
	free(p);
	if(sym->flags & SymUniq)
		return sym->def;
	sym->flags |= SymUniq;
	
	savecurfn = curfn;
	curfn = N;

	xtype = nod(OTFUNC, N, N);
	i = 0;
	l = nil;
	callargs = nil;
	ddd = 0;
	xfunc = nod(ODCLFUNC, N, N);
	curfn = xfunc;
	for(t = getinargx(t0)->type; t; t = t->down) {
		snprint(namebuf, sizeof namebuf, "a%d", i++);
		n = newname(lookup(namebuf));
		n->class = PPARAM;
		xfunc->dcl = list(xfunc->dcl, n);
		callargs = list(callargs, n);
		fld = nod(ODCLFIELD, n, typenod(t->type));
		if(t->isddd) {
			fld->isddd = 1;
			ddd = 1;
		}
		l = list(l, fld);
	}
	xtype->list = l;
	i = 0;
	l = nil;
	retargs = nil;
	for(t = getoutargx(t0)->type; t; t = t->down) {
		snprint(namebuf, sizeof namebuf, "r%d", i++);
		n = newname(lookup(namebuf));
		n->class = PPARAMOUT;
		xfunc->dcl = list(xfunc->dcl, n);
		retargs = list(retargs, n);
		l = list(l, nod(ODCLFIELD, n, typenod(t->type)));
	}
	xtype->rlist = l;

	xfunc->dupok = 1;
	xfunc->nname = newname(sym);
	xfunc->nname->sym->flags |= SymExported; // disable export
	xfunc->nname->ntype = xtype;
	xfunc->nname->defn = xfunc;
	declare(xfunc->nname, PFUNC);

	// Declare and initialize variable holding receiver.
	body = nil;
	xfunc->needctxt = 1;
	cv = nod(OCLOSUREVAR, N, N);
	cv->xoffset = widthptr;
	cv->type = rcvrtype;
	if(cv->type->align > widthptr)
		cv->xoffset = cv->type->align;
	ptr = nod(ONAME, N, N);
	ptr->sym = lookup("rcvr");
	ptr->class = PAUTO;
	ptr->addable = 1;
	ptr->ullman = 1;
	ptr->used = 1;
	ptr->curfn = xfunc;
	xfunc->dcl = list(xfunc->dcl, ptr);
	if(isptr[rcvrtype->etype] || isinter(rcvrtype)) {
		ptr->ntype = typenod(rcvrtype);
		body = list(body, nod(OAS, ptr, cv));
	} else {
		ptr->ntype = typenod(ptrto(rcvrtype));
		body = list(body, nod(OAS, ptr, nod(OADDR, cv, N)));
	}

	call = nod(OCALL, nod(OXDOT, ptr, meth), N);
	call->list = callargs;
	call->isddd = ddd;
	if(t0->outtuple == 0) {
		body = list(body, call);
	} else {
		n = nod(OAS2, N, N);
		n->list = retargs;
		n->rlist = list1(call);
		body = list(body, n);
		n = nod(ORETURN, N, N);
		body = list(body, n);
	}

	xfunc->nbody = body;

	typecheck(&xfunc, Etop);
	sym->def = xfunc;
	xtop = list(xtop, xfunc);
	curfn = savecurfn;

	return xfunc;
}

Node*
walkpartialcall(Node *n, NodeList **init)
{
	Node *clos, *typ;

	// Create closure in the form of a composite literal.
	// For x.M with receiver (x) type T, the generated code looks like:
	//
	//	clos = &struct{F uintptr; R T}{M.T·f, x}
	//
	// Like walkclosure above.

	if(isinter(n->left->type)) {
		// Trigger panic for method on nil interface now.
		// Otherwise it happens in the wrapper and is confusing.
		n->left = cheapexpr(n->left, init);
		checknil(n->left, init);
	}

	typ = nod(OTSTRUCT, N, N);
	typ->list = list1(nod(ODCLFIELD, newname(lookup("F")), typenod(types[TUINTPTR])));
	typ->list = list(typ->list, nod(ODCLFIELD, newname(lookup("R")), typenod(n->left->type)));

	clos = nod(OCOMPLIT, N, nod(OIND, typ, N));
	clos->esc = n->esc;
	clos->right->implicit = 1;
	clos->list = list1(nod(OCFUNC, n->nname->nname, N));
	clos->list = list(clos->list, n->left);

	// Force type conversion from *struct to the func type.
	clos = nod(OCONVNOP, clos, N);
	clos->type = n->type;

	typecheck(&clos, Erv);
	// typecheck will insert a PTRLIT node under CONVNOP,
	// tag it with escape analysis result.
	clos->left->esc = n->esc;
	// non-escaping temp to use, if any.
	// orderexpr did not compute the type; fill it in now.
	if(n->alloc != N) {
		n->alloc->type = clos->left->left->type;
		n->alloc->orig->type = n->alloc->type;
		clos->left->right = n->alloc;
		n->alloc = N;
	}
	walkexpr(&clos, init);

	return clos;
}