order.c 31.2 KB
Newer Older
Russ Cox's avatar
Russ Cox committed
1 2 3 4 5 6 7
// Copyright 2012 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.

// Rewrite tree to use separate statements to enforce
// order of evaluation.  Makes walk easier, because it
// can (after this runs) reorder at will within an expression.
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
//
// Rewrite x op= y into x = x op y.
//
// Introduce temporaries as needed by runtime routines.
// For example, the map runtime routines take the map key
// by reference, so make sure all map keys are addressable
// by copying them to temporaries as needed.
// The same is true for channel operations.
//
// Arrange that map index expressions only appear in direct
// assignments x = m[k] or m[k] = x, never in larger expressions.
//
// Arrange that receive expressions only appear in direct assignments
// x = <-c or as standalone statements <-c, never in larger expressions.

23 24 25 26
// TODO(rsc): The temporary introduction during multiple assignments
// should be moved into this file, so that the temporaries can be cleaned
// and so that conversions implicit in the OAS2FUNC and OAS2RECV
// nodes can be made explicit and then have their temporaries cleaned.
27 28 29 30 31 32 33

// TODO(rsc): Goto and multilevel break/continue can jump over
// inserted VARKILL annotations. Work out a way to handle these.
// The current implementation is safe, in that it will execute correctly.
// But it won't reuse temporaries as aggressively as it might, and
// it can result in unnecessary zeroing of those variables in the function
// prologue.
Russ Cox's avatar
Russ Cox committed
34 35 36 37 38

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

39 40 41 42 43 44 45 46 47 48 49
// Order holds state during the ordering process.
typedef struct Order Order;
struct Order
{
	NodeList *out; // list of generated statements
	NodeList *temp; // head of stack of temporary variables
	NodeList *free; // free list of NodeList* structs (for use in temp)
};

static void	orderstmt(Node*, Order*);
static void	orderstmtlist(NodeList*, Order*);
50
static void	orderblock(NodeList **l);
51 52 53 54
static void	orderexpr(Node**, Order*);
static void orderexprinplace(Node**, Order*);
static void	orderexprlist(NodeList*, Order*);
static void	orderexprlistinplace(NodeList*, Order*);
Russ Cox's avatar
Russ Cox committed
55

56 57
// Order rewrites fn->nbody to apply the ordering constraints
// described in the comment at the top of the file.
Russ Cox's avatar
Russ Cox committed
58 59 60
void
order(Node *fn)
{
61 62 63 64 65 66 67
	char s[50];

	if(debug['W'] > 1) {
		snprint(s, sizeof(s), "\nbefore order %S", fn->nname->sym);
		dumplist(s, fn->nbody);
	}

68
	orderblock(&fn->nbody);
Russ Cox's avatar
Russ Cox committed
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
// Ordertemp allocates a new temporary with the given type,
// pushes it onto the temp stack, and returns it.
// If clear is true, ordertemp emits code to zero the temporary.
static Node*
ordertemp(Type *t, Order *order, int clear)
{
	Node *var, *a;
	NodeList *l;

	var = temp(t);
	if(clear) {
		a = nod(OAS, var, N);
		typecheck(&a, Etop);
		order->out = list(order->out, a);
	}
	if((l = order->free) == nil)
		l = mal(sizeof *l);
	order->free = l->next;
	l->next = order->temp;
	l->n = var;
	order->temp = l;
	return var;
}

// Ordercopyexpr behaves like ordertemp but also emits
// code to initialize the temporary to the value n.
//
// The clear argument is provided for use when the evaluation
// of tmp = n turns into a function call that is passed a pointer
// to the temporary as the output space. If the call blocks before
// tmp has been written, the garbage collector will still treat the
// temporary as live, so we must zero it before entering that call.
// Today, this only happens for channel receive operations.
// (The other candidate would be map access, but map access
// returns a pointer to the result data instead of taking a pointer
// to be filled in.)
static Node*
ordercopyexpr(Node *n, Type *t, Order *order, int clear)
{
	Node *a, *var;

	var = ordertemp(t, order, clear);
	a = nod(OAS, var, n);
	typecheck(&a, Etop);
	order->out = list(order->out, a);
	return var;
}

// Ordercheapexpr returns a cheap version of n.
// The definition of cheap is that n is a variable or constant.
// If not, ordercheapexpr allocates a new tmp, emits tmp = n,
// and then returns tmp.
static Node*
ordercheapexpr(Node *n, Order *order)
{
	switch(n->op) {
	case ONAME:
	case OLITERAL:
		return n;
	}
	return ordercopyexpr(n, n->type, order, 0);
}

// Ordersafeexpr returns a safe version of n.
// The definition of safe is that n can appear multiple times
// without violating the semantics of the original program,
// and that assigning to the safe version has the same effect
// as assigning to the original n.
//
// The intended use is to apply to x when rewriting x += y into x = x + y.
static Node*
ordersafeexpr(Node *n, Order *order)
{
	Node *l, *r, *a;
	
	switch(n->op) {
	case ONAME:
	case OLITERAL:
		return n;

	case ODOT:
		l = ordersafeexpr(n->left, order);
		if(l == n->left)
			return n;
		a = nod(OXXX, N, N);
		*a = *n;
		a->orig = a;
		a->left = l;
		typecheck(&a, Erv);
		return a;

	case ODOTPTR:
	case OIND:
		l = ordercheapexpr(n->left, order);
		if(l == n->left)
			return n;
		a = nod(OXXX, N, N);
		*a = *n;
		a->orig = a;
		a->left = l;
		typecheck(&a, Erv);
		return a;
		
	case OINDEX:
	case OINDEXMAP:
		if(isfixedarray(n->left->type))
			l = ordersafeexpr(n->left, order);
		else
			l = ordercheapexpr(n->left, order);
		r = ordercheapexpr(n->right, order);
		if(l == n->left && r == n->right)
			return n;
		a = nod(OXXX, N, N);
		*a = *n;
		a->orig = a;
		a->left = l;
		a->right = r;
		typecheck(&a, Erv);
		return a;
	}
191 192 193

	fatal("ordersafeexpr %O", n->op);
	return nil; // not reached
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
}		

// Istemp reports whether n is a temporary variable.
static int
istemp(Node *n)
{
	if(n->op != ONAME)
		return 0;
	return strncmp(n->sym->name, "autotmp_", 8) == 0;
}

// Isaddrokay reports whether it is okay to pass n's address to runtime routines.
// Taking the address of a variable makes the liveness and optimization analyses
// lose track of where the variable's lifetime ends. To avoid hurting the analyses
// of ordinary stack variables, those are not 'isaddrokay'. Temporaries are okay,
// because we emit explicit VARKILL instructions marking the end of those
// temporaries' lifetimes.
static int
isaddrokay(Node *n)
{
	return islvalue(n) && (n->op != ONAME || n->class == PEXTERN || istemp(n));
}

// Orderaddrtemp ensures that *np is okay to pass by address to runtime routines.
// If the original argument *np is not okay, orderaddrtemp creates a tmp, emits
// tmp = *np, and then sets *np to the tmp variable.
static void
orderaddrtemp(Node **np, Order *order)
{
	Node *n;
	
	n = *np;
	if(isaddrokay(n))
		return;
	*np = ordercopyexpr(n, n->type, order, 0);
}

// Marktemp returns the top of the temporary variable stack.
static NodeList*
marktemp(Order *order)
{
	return order->temp;
}

// Poptemp pops temporaries off the stack until reaching the mark,
// which must have been returned by marktemp.
static void
poptemp(NodeList *mark, Order *order)
{
	NodeList *l;

	while((l = order->temp) != mark) {
		order->temp = l->next;
		l->next = order->free;
		order->free = l;
	}
}

252
// Cleantempnopop emits to *out VARKILL instructions for each temporary
253 254 255
// above the mark on the temporary stack, but it does not pop them
// from the stack.
static void
256
cleantempnopop(NodeList *mark, Order *order, NodeList **out)
257 258 259 260 261 262 263
{
	NodeList *l;
	Node *kill;

	for(l=order->temp; l != mark; l=l->next) {
		kill = nod(OVARKILL, l->n, N);
		typecheck(&kill, Etop);
264
		*out = list(*out, kill);
265 266 267 268 269 270 271 272
	}
}

// Cleantemp emits VARKILL instructions for each temporary above the
// mark on the temporary stack and removes them from the stack.
static void
cleantemp(NodeList *top, Order *order)
{
273
	cleantempnopop(top, order, &order->out);
274 275 276 277
	poptemp(top, order);
}

// Orderstmtlist orders each of the statements in the list.
Russ Cox's avatar
Russ Cox committed
278
static void
279
orderstmtlist(NodeList *l, Order *order)
Russ Cox's avatar
Russ Cox committed
280 281
{
	for(; l; l=l->next)
282
		orderstmt(l->n, order);
Russ Cox's avatar
Russ Cox committed
283 284
}

285 286
// Orderblock orders the block of statements *l onto a new list,
// and then replaces *l with that list.
Russ Cox's avatar
Russ Cox committed
287 288 289
static void
orderblock(NodeList **l)
{
290
	Order order;
291
	NodeList *mark;
Russ Cox's avatar
Russ Cox committed
292
	
293
	memset(&order, 0, sizeof order);
294
	mark = marktemp(&order);
295
	orderstmtlist(*l, &order);
296
	cleantemp(mark, &order);
297
	*l = order.out;
Russ Cox's avatar
Russ Cox committed
298 299
}

300 301
// Orderexprinplace orders the side effects in *np and
// leaves them as the init list of the final *np.
Russ Cox's avatar
Russ Cox committed
302
static void
303
orderexprinplace(Node **np, Order *outer)
Russ Cox's avatar
Russ Cox committed
304 305
{
	Node *n;
306
	NodeList **lp;
307
	Order order;
Russ Cox's avatar
Russ Cox committed
308 309
	
	n = *np;
310 311 312 313
	memset(&order, 0, sizeof order);
	orderexpr(&n, &order);
	addinit(&n, order.out);
	
314 315 316 317 318 319 320 321
	// insert new temporaries from order
	// at head of outer list.
	lp = &order.temp;
	while(*lp != nil)
		lp = &(*lp)->next;
	*lp = outer->temp;
	outer->temp = order.temp;

322 323 324 325 326
	*np = n;
}

// Orderstmtinplace orders the side effects of the single statement *np
// and replaces it with the resulting statement list.
Russ Cox's avatar
Russ Cox committed
327
void
Russ Cox's avatar
Russ Cox committed
328 329 330
orderstmtinplace(Node **np)
{
	Node *n;
331
	Order order;
332 333
	NodeList *mark;
	
Russ Cox's avatar
Russ Cox committed
334
	n = *np;
335
	memset(&order, 0, sizeof order);
336
	mark = marktemp(&order);
337
	orderstmt(n, &order);
338
	cleantemp(mark, &order);
339
	*np = liststmt(order.out);
Russ Cox's avatar
Russ Cox committed
340 341
}

342
// Orderinit moves n's init list to order->out.
Russ Cox's avatar
Russ Cox committed
343
static void
344
orderinit(Node *n, Order *order)
Russ Cox's avatar
Russ Cox committed
345
{
346
	orderstmtlist(n->ninit, order);
Russ Cox's avatar
Russ Cox committed
347 348 349
	n->ninit = nil;
}

350 351
// Ismulticall reports whether the list l is f() for a multi-value function.
// Such an f() could appear as the lone argument to a multi-arg function.
Russ Cox's avatar
Russ Cox committed
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
static int
ismulticall(NodeList *l)
{
	Node *n;
	
	// one arg only
	if(l == nil || l->next != nil)
		return 0;
	n = l->n;
	
	// must be call
	switch(n->op) {
	default:
		return 0;
	case OCALLFUNC:
	case OCALLMETH:
	case OCALLINTER:
		break;
	}
	
	// call must return multiple values
	return n->left->type->outtuple > 1;
}

376 377
// Copyret emits t1, t2, ... = n, where n is a function call,
// and then returns the list t1, t2, ....
Russ Cox's avatar
Russ Cox committed
378
static NodeList*
379
copyret(Node *n, Order *order)
Russ Cox's avatar
Russ Cox committed
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
{
	Type *t;
	Node *tmp, *as;
	NodeList *l1, *l2;
	Iter tl;
	
	if(n->type->etype != TSTRUCT || !n->type->funarg)
		fatal("copyret %T %d", n->type, n->left->type->outtuple);

	l1 = nil;
	l2 = nil;
	for(t=structfirst(&tl, &n->type); t; t=structnext(&tl)) {
		tmp = temp(t->type);
		l1 = list(l1, tmp);
		l2 = list(l2, tmp);
	}
	
	as = nod(OAS2, N, N);
	as->list = l1;
	as->rlist = list1(n);
	typecheck(&as, Etop);
401
	orderstmt(as, order);
Russ Cox's avatar
Russ Cox committed
402 403 404 405

	return l2;
}

406
// Ordercallargs orders the list of call arguments *l.
Russ Cox's avatar
Russ Cox committed
407
static void
408
ordercallargs(NodeList **l, Order *order)
Russ Cox's avatar
Russ Cox committed
409 410 411
{
	if(ismulticall(*l)) {
		// return f() where f() is multiple values.
412
		*l = copyret((*l)->n, order);
Russ Cox's avatar
Russ Cox committed
413
	} else {
414
		orderexprlist(*l, order);
Russ Cox's avatar
Russ Cox committed
415 416 417
	}
}

418
// Ordercall orders the call expression n.
Russ Cox's avatar
Russ Cox committed
419
// n->op is OCALLMETH/OCALLFUNC/OCALLINTER or a builtin like OCOPY.
Russ Cox's avatar
Russ Cox committed
420
static void
Russ Cox's avatar
Russ Cox committed
421
ordercall(Node *n, Order *order)
Russ Cox's avatar
Russ Cox committed
422
{
423
	orderexpr(&n->left, order);
Russ Cox's avatar
Russ Cox committed
424
	orderexpr(&n->right, order); // ODDDARG temp
425
	ordercallargs(&n->list, order);
Russ Cox's avatar
Russ Cox committed
426 427
}

428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
// Ordermapassign appends n to order->out, introducing temporaries
// to make sure that all map assignments have the form m[k] = x,
// where x is adressable.
// (Orderexpr has already been called on n, so we know k is addressable.)
//
// If n is m[k] = x where x is not addressable, the rewrite is:
//	tmp = x
//	m[k] = tmp
//
// If n is the multiple assignment form ..., m[k], ... = ..., the rewrite is
//	t1 = m
//	t2 = k
//	...., t3, ... = x
//	t1[t2] = t3
//
// The temporaries t1, t2 are needed in case the ... being assigned
// contain m or k. They are usually unnecessary, but in the unnecessary
// cases they are also typically registerizable, so not much harm done.
// And this only applies to the multiple-assignment form.
// We could do a more precise analysis if needed, like in walk.c.
448 449 450
//
// Ordermapassign also inserts these temporaries if needed for
// calling writebarrierfat with a pointer to n->right.
Russ Cox's avatar
Russ Cox committed
451
static void
452
ordermapassign(Node *n, Order *order)
Russ Cox's avatar
Russ Cox committed
453
{
454
	Node *m, *a;
Russ Cox's avatar
Russ Cox committed
455
	NodeList *l;
456 457 458 459 460 461 462 463
	NodeList *post;

	switch(n->op) {
	default:
		fatal("ordermapassign %O", n->op);

	case OAS:
		order->out = list(order->out, n);
464 465
		// We call writebarrierfat only for values > 4 pointers long. See walk.c.
		if((n->left->op == OINDEXMAP || (needwritebarrier(n->left, n->right) && n->left->type->width > 4*widthptr)) && !isaddrokay(n->right)) {
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
			m = n->left;
			n->left = ordertemp(m->type, order, 0);
			a = nod(OAS, m, n->left);
			typecheck(&a, Etop);
			order->out = list(order->out, a);
		}
		break;

	case OAS2:
	case OAS2DOTTYPE:
	case OAS2MAPR:
	case OAS2FUNC:
		post = nil;
		for(l=n->list; l != nil; l=l->next) {
			if(l->n->op == OINDEXMAP) {
				m = l->n;
				if(!istemp(m->left))
					m->left = ordercopyexpr(m->left, m->left->type, order, 0);
				if(!istemp(m->right))
485
					m->right = ordercopyexpr(m->right, m->right->type, order, 0);
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
				l->n = ordertemp(m->type, order, 0);
				a = nod(OAS, m, l->n);
				typecheck(&a, Etop);
				post = list(post, a);
			}
		}
		order->out = list(order->out, n);
		order->out = concat(order->out, post);
		break;
	}
}

// Orderstmt orders the statement n, appending to order->out.
// Temporaries created during the statement are cleaned
// up using VARKILL instructions as possible.
static void
orderstmt(Node *n, Order *order)
{
	int lno;
	NodeList *l, *t, *t1;
	Node *r, *tmp1, *tmp2, **np;
507
	Type *ch, *typ;
Russ Cox's avatar
Russ Cox committed
508 509 510 511 512

	if(n == N)
		return;

	lno = setlineno(n);
513

514
	orderinit(n, order);
515

Russ Cox's avatar
Russ Cox committed
516 517 518 519
	switch(n->op) {
	default:
		fatal("orderstmt %O", n->op);

520 521 522 523
	case OVARKILL:
		order->out = list(order->out, n);
		break;

524
	case OAS:
Russ Cox's avatar
Russ Cox committed
525 526 527 528 529 530 531
	case OAS2:
	case OCLOSE:
	case OCOPY:
	case OPRINT:
	case OPRINTN:
	case ORECOVER:
	case ORECV:
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
		t = marktemp(order);
		orderexpr(&n->left, order);
		orderexpr(&n->right, order);
		orderexprlist(n->list, order);
		orderexprlist(n->rlist, order);
		switch(n->op) {
		case OAS:
		case OAS2:
		case OAS2DOTTYPE:
			ordermapassign(n, order);
			break;
		default:
			order->out = list(order->out, n);
			break;
		}
		cleantemp(t, order);
Russ Cox's avatar
Russ Cox committed
548
		break;
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564

	case OASOP:
		// Special: rewrite l op= r into l = l op r.
		// This simplies quite a few operations;
		// most important is that it lets us separate
		// out map read from map write when l is
		// a map index expression.
		t = marktemp(order);
		orderexpr(&n->left, order);
		n->left = ordersafeexpr(n->left, order);
		tmp1 = treecopy(n->left);
		if(tmp1->op == OINDEXMAP)
			tmp1->etype = 0; // now an rvalue not an lvalue
		tmp1 = ordercopyexpr(tmp1, n->left->type, order, 0);
		n->right = nod(n->etype, tmp1, n->right);
		typecheck(&n->right, Erv);
565
		orderexpr(&n->right, order);
566 567 568 569 570 571 572 573 574 575 576
		n->etype = 0;
		n->op = OAS;
		ordermapassign(n, order);
		cleantemp(t, order);
		break;

	case OAS2MAPR:
		// Special: make sure key is addressable,
		// and make sure OINDEXMAP is not copied out.
		t = marktemp(order);
		orderexprlist(n->list, order);
577 578 579 580 581 582 583
		r = n->rlist->n;
		orderexpr(&r->left, order);
		orderexpr(&r->right, order);
		// See case OINDEXMAP below.
		if(r->right->op == OARRAYBYTESTR)
			r->right->op = OARRAYBYTESTRTMP;
		orderaddrtemp(&r->right, order);
584 585 586 587
		ordermapassign(n, order);
		cleantemp(t, order);
		break;

Russ Cox's avatar
Russ Cox committed
588 589
	case OAS2FUNC:
		// Special: avoid copy of func call n->rlist->n.
590 591
		t = marktemp(order);
		orderexprlist(n->list, order);
Russ Cox's avatar
Russ Cox committed
592
		ordercall(n->rlist->n, order);
593 594
		ordermapassign(n, order);
		cleantemp(t, order);
Russ Cox's avatar
Russ Cox committed
595 596
		break;

597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
	case OAS2DOTTYPE:
		// Special: use temporary variables to hold result,
		// so that assertI2Tetc can take address of temporary.
		// No temporary for blank assignment.
		t = marktemp(order);
		orderexprlist(n->list, order);
		orderexpr(&n->rlist->n->left, order);  // i in i.(T)
		if(isblank(n->list->n))
			order->out = list(order->out, n);
		else {
			typ = n->rlist->n->type;
			tmp1 = ordertemp(typ, order, haspointers(typ));
			order->out = list(order->out, n);
			r = nod(OAS, n->list->n, tmp1);
			typecheck(&r, Etop);
			ordermapassign(r, order);
			n->list = list(list1(tmp1), n->list->next->n);
		}
		cleantemp(t, order);
		break;

Russ Cox's avatar
Russ Cox committed
618
	case OAS2RECV:
619
		// Special: use temporary variables to hold result,
620 621 622 623 624 625
		// so that chanrecv can take address of temporary.
		t = marktemp(order);
		orderexprlist(n->list, order);
		orderexpr(&n->rlist->n->left, order);  // arg to recv
		ch = n->rlist->n->left->type;
		tmp1 = ordertemp(ch->type, order, haspointers(ch->type));
626 627 628 629
		if(!isblank(n->list->next->n))
			tmp2 = ordertemp(n->list->next->n->type, order, 0);
		else
			tmp2 = ordertemp(types[TBOOL], order, 0);
630 631 632 633 634 635 636 637 638
		order->out = list(order->out, n);
		r = nod(OAS, n->list->n, tmp1);
		typecheck(&r, Etop);
		ordermapassign(r, order);
		r = nod(OAS, n->list->next->n, tmp2);
		typecheck(&r, Etop);
		ordermapassign(r, order);
		n->list = list(list1(tmp1), tmp2);
		cleantemp(t, order);
Russ Cox's avatar
Russ Cox committed
639 640 641 642 643
		break;

	case OBLOCK:
	case OEMPTY:
		// Special: does not save n onto out.
644
		orderstmtlist(n->list, order);
Russ Cox's avatar
Russ Cox committed
645 646 647 648 649 650 651 652
		break;

	case OBREAK:
	case OCONTINUE:
	case ODCL:
	case ODCLCONST:
	case ODCLTYPE:
	case OFALL:
653
	case OXFALL:
Russ Cox's avatar
Russ Cox committed
654 655
	case OGOTO:
	case OLABEL:
656
	case ORETJMP:
Russ Cox's avatar
Russ Cox committed
657
		// Special: n->left is not an expression; save as is.
658
		order->out = list(order->out, n);
Russ Cox's avatar
Russ Cox committed
659 660 661 662 663 664
		break;

	case OCALLFUNC:
	case OCALLINTER:
	case OCALLMETH:
		// Special: handle call arguments.
665
		t = marktemp(order);
Russ Cox's avatar
Russ Cox committed
666
		ordercall(n, order);
667 668
		order->out = list(order->out, n);
		cleantemp(t, order);
Russ Cox's avatar
Russ Cox committed
669 670 671 672 673
		break;

	case ODEFER:
	case OPROC:
		// Special: order arguments to inner call but not call itself.
674 675 676 677 678 679 680 681 682 683 684 685 686
		t = marktemp(order);
		switch(n->left->op) {
		case ODELETE:
			// Delete will take the address of the key.
			// Copy key into new temp and do not clean it
			// (it persists beyond the statement).
			orderexprlist(n->left->list, order);
			t1 = marktemp(order);
			np = &n->left->list->next->n; // map key
			*np = ordercopyexpr(*np, (*np)->type, order, 0);
			poptemp(t1, order);
			break;
		default:
Russ Cox's avatar
Russ Cox committed
687
			ordercall(n->left, order);
688 689 690 691 692 693 694 695 696 697 698 699 700
			break;
		}
		order->out = list(order->out, n);
		cleantemp(t, order);
		break;

	case ODELETE:
		t = marktemp(order);
		orderexpr(&n->list->n, order);
		orderexpr(&n->list->next->n, order);
		orderaddrtemp(&n->list->next->n, order); // map key
		order->out = list(order->out, n);
		cleantemp(t, order);
Russ Cox's avatar
Russ Cox committed
701 702 703
		break;

	case OFOR:
704 705 706
		// Clean temporaries from condition evaluation at
		// beginning of loop body and after for statement.
		t = marktemp(order);
707
		orderexprinplace(&n->ntest, order);
708 709 710
		l = nil;
		cleantempnopop(t, order, &l);
		n->nbody = concat(l, n->nbody);
Russ Cox's avatar
Russ Cox committed
711
		orderblock(&n->nbody);
712
		orderstmtinplace(&n->nincr);
713
		order->out = list(order->out, n);
714
		cleantemp(t, order);
Russ Cox's avatar
Russ Cox committed
715 716 717
		break;
		
	case OIF:
718 719 720
		// Clean temporaries from condition at
		// beginning of both branches.
		t = marktemp(order);
721
		orderexprinplace(&n->ntest, order);
722 723 724 725 726 727 728
		l = nil;
		cleantempnopop(t, order, &l);
		n->nbody = concat(l, n->nbody);
		l = nil;
		cleantempnopop(t, order, &l);
		n->nelse = concat(l, n->nelse);
		poptemp(t, order);
Russ Cox's avatar
Russ Cox committed
729 730
		orderblock(&n->nbody);
		orderblock(&n->nelse);
731
		order->out = list(order->out, n);
Russ Cox's avatar
Russ Cox committed
732 733
		break;

734 735 736 737 738 739 740 741 742 743 744
	case OPANIC:
		// Special: argument will be converted to interface using convT2E
		// so make sure it is an addressable temporary.
		t = marktemp(order);
		orderexpr(&n->left, order);
		if(!isinter(n->left->type))
			orderaddrtemp(&n->left, order);
		order->out = list(order->out, n);
		cleantemp(t, order);
		break;

Russ Cox's avatar
Russ Cox committed
745
	case ORANGE:
746 747 748 749 750 751 752 753 754
		// n->right is the expression being ranged over.
		// order it, and then make a copy if we need one.
		// We almost always do, to ensure that we don't
		// see any value changes made during the loop.
		// Usually the copy is cheap (e.g., array pointer, chan, slice, string are all tiny).
		// The exception is ranging over an array value (not a slice, not a pointer to array),
		// which must make a copy to avoid seeing updates made during
		// the range body. Ranging over an array value is uncommon though.
		t = marktemp(order);
755
		orderexpr(&n->right, order);
756 757 758 759
		switch(n->type->etype) {
		default:
			fatal("orderstmt range %T", n->type);
		case TARRAY:
760 761 762 763
			// Mark []byte(str) range expression to reuse string backing storage.
			// It is safe because the storage cannot be mutated.
			if(n->right->op == OSTRARRAYBYTE)
				n->right->op = OSTRARRAYBYTETMP;
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
			if(count(n->list) < 2 || isblank(n->list->next->n)) {
				// for i := range x will only use x once, to compute len(x).
				// No need to copy it.
				break;
			}
			// fall through
		case TCHAN:
		case TSTRING:
			// chan, string, slice, array ranges use value multiple times.
			// make copy.
			r = n->right;
			if(r->type->etype == TSTRING && r->type != types[TSTRING]) {
				r = nod(OCONV, r, N);
				r->type = types[TSTRING];
				typecheck(&r, Erv);
			}
			n->right = ordercopyexpr(r, r->type, order, 0);
			break;
		case TMAP:
			// copy the map value in case it is a map literal.
			// TODO(rsc): Make tmp = literal expressions reuse tmp.
			// For maps tmp is just one word so it hardly matters.
			r = n->right;
			n->right = ordercopyexpr(r, r->type, order, 0);
788 789
			// n->alloc is the temp for the iterator.
			n->alloc = ordertemp(types[TUINT8], order, 1);
790 791
			break;
		}
Russ Cox's avatar
Russ Cox committed
792
		for(l=n->list; l; l=l->next)
793
			orderexprinplace(&l->n, order);
Russ Cox's avatar
Russ Cox committed
794
		orderblock(&n->nbody);
795
		order->out = list(order->out, n);
796
		cleantemp(t, order);
Russ Cox's avatar
Russ Cox committed
797 798 799
		break;

	case ORETURN:
800 801
		ordercallargs(&n->list, order);
		order->out = list(order->out, n);
Russ Cox's avatar
Russ Cox committed
802
		break;
803
	
Russ Cox's avatar
Russ Cox committed
804
	case OSELECT:
805 806 807
		// Special: clean case temporaries in each block entry.
		// Select must enter one of its blocks, so there is no
		// need for a cleaning at the end.
808 809 810 811 812 813
		// Doubly special: evaluation order for select is stricter
		// than ordinary expressions. Even something like p.c
		// has to be hoisted into a temporary, so that it cannot be
		// reordered after the channel evaluation for a different
		// case (if p were nil, then the timing of the fault would
		// give this away).
814
		t = marktemp(order);
Russ Cox's avatar
Russ Cox committed
815 816 817 818
		for(l=n->list; l; l=l->next) {
			if(l->n->op != OXCASE)
				fatal("order select case %O", l->n->op);
			r = l->n->left;
819 820 821 822 823
			setlineno(l->n);
			// Append any new body prologue to ninit.
			// The next loop will insert ninit into nbody.
			if(l->n->ninit != nil)
				fatal("order select ninit");
824 825
			if(r != nil) {
				switch(r->op) {
826 827 828 829 830
				default:
					yyerror("unknown op in select %O", r->op);
					dump("select case", r);
					break;

831 832
				case OSELRECV:
				case OSELRECV2:
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
					// If this is case x := <-ch or case x, y := <-ch, the case has
					// the ODCL nodes to declare x and y. We want to delay that
					// declaration (and possible allocation) until inside the case body.
					// Delete the ODCL nodes here and recreate them inside the body below.
					if(r->colas) {
						t = r->ninit;
						if(t != nil && t->n->op == ODCL && t->n->left == r->left)
							t = t->next;
						if(t != nil && t->n->op == ODCL && t->n->left == r->ntest)
							t = t->next;
						if(t == nil)
							r->ninit = nil;
					}
					if(r->ninit != nil) {
						yyerror("ninit on select recv");
						dumplist("ninit", r->ninit);
					}
850 851 852 853 854 855
					// case x = <-c
					// case x, ok = <-c
					// r->left is x, r->ntest is ok, r->right is ORECV, r->right->left is c.
					// r->left == N means 'case <-c'.
					// c is always evaluated; x and ok are only evaluated when assigned.
					orderexpr(&r->right->left, order);
856 857
					if(r->right->left->op != ONAME)
						r->right->left = ordercopyexpr(r->right->left, r->right->left->type, order, 0);
858 859 860 861 862 863 864 865 866 867 868 869 870 871

					// Introduce temporary for receive and move actual copy into case body.
					// avoids problems with target being addressed, as usual.
					// NOTE: If we wanted to be clever, we could arrange for just one
					// temporary per distinct type, sharing the temp among all receives
					// with that temp. Similarly one ok bool could be shared among all
					// the x,ok receives. Not worth doing until there's a clear need.
					if(r->left != N && isblank(r->left))
						r->left = N;
					if(r->left != N) {
						// use channel element type for temporary to avoid conversions,
						// such as in case interfacevalue = <-intchan.
						// the conversion happens in the OAS instead.
						tmp1 = r->left;
872 873 874 875 876
						if(r->colas) {
							tmp2 = nod(ODCL, tmp1, N);
							typecheck(&tmp2, Etop);
							l->n->ninit = list(l->n->ninit, tmp2);
						}
877 878 879 880 881 882 883 884 885
						r->left = ordertemp(r->right->left->type->type, order, haspointers(r->right->left->type->type));
						tmp2 = nod(OAS, tmp1, r->left);
						typecheck(&tmp2, Etop);
						l->n->ninit = list(l->n->ninit, tmp2);
					}
					if(r->ntest != N && isblank(r->ntest))
						r->ntest = N;
					if(r->ntest != N) {
						tmp1 = r->ntest;
886 887 888 889 890
						if(r->colas) {
							tmp2 = nod(ODCL, tmp1, N);
							typecheck(&tmp2, Etop);
							l->n->ninit = list(l->n->ninit, tmp2);
						}
891 892 893 894 895 896
						r->ntest = ordertemp(tmp1->type, order, 0);
						tmp2 = nod(OAS, tmp1, r->ntest);
						typecheck(&tmp2, Etop);
						l->n->ninit = list(l->n->ninit, tmp2);
					}
					orderblock(&l->n->ninit);
897
					break;
898

899
				case OSEND:
900 901 902 903
					if(r->ninit != nil) {
						yyerror("ninit on select send");
						dumplist("ninit", r->ninit);
					}
904 905 906 907 908 909 910 911
					// case c <- x
					// r->left is c, r->right is x, both are always evaluated.
					orderexpr(&r->left, order);
					if(!istemp(r->left))
						r->left = ordercopyexpr(r->left, r->left->type, order, 0);
					orderexpr(&r->right, order);
					if(!istemp(r->right))
						r->right = ordercopyexpr(r->right, r->right->type, order, 0);
912 913
					break;
				}
Russ Cox's avatar
Russ Cox committed
914
			}
915
			orderblock(&l->n->nbody);
Russ Cox's avatar
Russ Cox committed
916
		}
917 918 919 920 921 922 923 924
		// Now that we have accumulated all the temporaries, clean them.
		// Also insert any ninit queued during the previous loop.
		// (The temporary cleaning must follow that ninit work.)
		for(l=n->list; l; l=l->next) {
			cleantempnopop(t, order, &l->n->ninit);
			l->n->nbody = concat(l->n->ninit, l->n->nbody);
			l->n->ninit = nil;
		}
925
		order->out = list(order->out, n);
926
		poptemp(t, order);
927 928 929 930 931 932 933 934 935 936
		break;

	case OSEND:
		// Special: value being sent is passed as a pointer; make it addressable.
		t = marktemp(order);
		orderexpr(&n->left, order);
		orderexpr(&n->right, order);
		orderaddrtemp(&n->right, order);
		order->out = list(order->out, n);
		cleantemp(t, order);
Russ Cox's avatar
Russ Cox committed
937 938 939
		break;

	case OSWITCH:
940 941 942 943 944 945 946 947
		// TODO(rsc): Clean temporaries more aggressively.
		// Note that because walkswitch will rewrite some of the
		// switch into a binary search, this is not as easy as it looks.
		// (If we ran that code here we could invoke orderstmt on
		// the if-else chain instead.)
		// For now just clean all the temporaries at the end.
		// In practice that's fine.
		t = marktemp(order);
948
		orderexpr(&n->ntest, order);
Russ Cox's avatar
Russ Cox committed
949 950 951
		for(l=n->list; l; l=l->next) {
			if(l->n->op != OXCASE)
				fatal("order switch case %O", l->n->op);
952 953
			orderexprlistinplace(l->n->list, order);
			orderblock(&l->n->nbody);
Russ Cox's avatar
Russ Cox committed
954
		}
955
		order->out = list(order->out, n);
956
		cleantemp(t, order);
Russ Cox's avatar
Russ Cox committed
957 958 959 960 961 962
		break;
	}
	
	lineno = lno;
}

963
// Orderexprlist orders the expression list l into order.
Russ Cox's avatar
Russ Cox committed
964
static void
965
orderexprlist(NodeList *l, Order *order)
Russ Cox's avatar
Russ Cox committed
966 967
{
	for(; l; l=l->next)
968
		orderexpr(&l->n, order);
Russ Cox's avatar
Russ Cox committed
969 970
}

971 972
// Orderexprlist orders the expression list l but saves
// the side effects on the individual expression ninit lists.
Russ Cox's avatar
Russ Cox committed
973
static void
974 975 976 977 978 979 980 981 982 983
orderexprlistinplace(NodeList *l, Order *order)
{
	for(; l; l=l->next)
		orderexprinplace(&l->n, order);
}

// Orderexpr orders a single expression, appending side
// effects to order->out as needed.
static void
orderexpr(Node **np, Order *order)
Russ Cox's avatar
Russ Cox committed
984 985
{
	Node *n;
986
	NodeList *mark, *l;
987
	Type *t;
988
	int lno, haslit, hasbyte;
Russ Cox's avatar
Russ Cox committed
989 990 991 992 993 994

	n = *np;
	if(n == N)
		return;

	lno = setlineno(n);
995
	orderinit(n, order);
Russ Cox's avatar
Russ Cox committed
996 997 998

	switch(n->op) {
	default:
999 1000 1001 1002 1003 1004
		orderexpr(&n->left, order);
		orderexpr(&n->right, order);
		orderexprlist(n->list, order);
		orderexprlist(n->rlist, order);
		break;
	
1005 1006 1007 1008 1009 1010 1011 1012 1013
	case OADDSTR:
		// Addition of strings turns into a function call.
		// Allocate a temporary to hold the strings.
		// Fewer than 5 strings use direct runtime helpers.
		orderexprlist(n->list, order);
		if(count(n->list) > 5) {
			t = typ(TARRAY);
			t->bound = count(n->list);
			t->type = types[TSTRING];
1014
			n->alloc = ordertemp(t, order, 0);
1015
		}
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035

		// Mark string(byteSlice) arguments to reuse byteSlice backing
		// buffer during conversion. String concatenation does not
		// memorize the strings for later use, so it is safe.
		// However, we can do it only if there is at least one non-empty string literal.
		// Otherwise if all other arguments are empty strings,
		// concatstrings will return the reference to the temp string
		// to the caller.
		hasbyte = 0;
		haslit = 0;
		for(l=n->list; l != nil; l=l->next) {
			hasbyte |= l->n->op == OARRAYBYTESTR;
			haslit |= l->n->op == OLITERAL && l->n->val.u.sval->len != 0;
		}
		if(haslit && hasbyte) {
			for(l=n->list; l != nil; l=l->next) {
				if(l->n->op == OARRAYBYTESTR)
					l->n->op = OARRAYBYTESTRTMP;
			}
		}
1036 1037
		break;

1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
	case OCMPSTR:
		orderexpr(&n->left, order);
		orderexpr(&n->right, order);
		// Mark string(byteSlice) arguments to reuse byteSlice backing
		// buffer during conversion. String comparison does not
		// memorize the strings for later use, so it is safe.
		if(n->left->op == OARRAYBYTESTR)
			n->left->op = OARRAYBYTESTRTMP;
		if(n->right->op == OARRAYBYTESTR)
			n->right->op = OARRAYBYTESTRTMP;
		break;

1050 1051 1052 1053
	case OINDEXMAP:
		// key must be addressable
		orderexpr(&n->left, order);
		orderexpr(&n->right, order);
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067

		// For x = m[string(k)] where k is []byte, the allocation of
		// backing bytes for the string can be avoided by reusing
		// the []byte backing array. This is a special case that it
		// would be nice to handle more generally, but because
		// there are no []byte-keyed maps, this specific case comes
		// up in important cases in practice. See issue 3512.
		// Nothing can change the []byte we are not copying before
		// the map index, because the map access is going to
		// be forced to happen immediately following this
		// conversion (by the ordercopyexpr a few lines below).
		if(n->etype == 0 && n->right->op == OARRAYBYTESTR)
			n->right->op = OARRAYBYTESTRTMP;

1068 1069 1070 1071 1072 1073
		orderaddrtemp(&n->right, order);
		if(n->etype == 0) {
			// use of value (not being assigned);
			// make copy in temporary.
			n = ordercopyexpr(n, n->type, order, 0);
		}
Russ Cox's avatar
Russ Cox committed
1074 1075
		break;
	
1076 1077 1078 1079 1080 1081 1082 1083
	case OCONVIFACE:
		// concrete type (not interface) argument must be addressable
		// temporary to pass to runtime.
		orderexpr(&n->left, order);
		if(!isinter(n->left->type))
			orderaddrtemp(&n->left, order);
		break;
	
Russ Cox's avatar
Russ Cox committed
1084 1085
	case OANDAND:
	case OOROR:
1086
		mark = marktemp(order);
1087
		orderexpr(&n->left, order);
1088 1089 1090 1091 1092 1093
		// Clean temporaries from first branch at beginning of second.
		// Leave them on the stack so that they can be killed in the outer
		// context in case the short circuit is taken.
		l = nil;
		cleantempnopop(mark, order, &l);
		n->right->ninit = concat(l, n->right->ninit);
1094
		orderexprinplace(&n->right, order);
Russ Cox's avatar
Russ Cox committed
1095 1096
		break;
	
1097
	case OAPPEND:
Russ Cox's avatar
Russ Cox committed
1098 1099
	case OCALLFUNC:
	case OCALLINTER:
1100 1101
	case OCALLMETH:
	case OCAP:
1102
	case OCOMPLEX:
1103 1104 1105 1106 1107 1108 1109 1110 1111
	case OCOPY:
	case OIMAG:
	case OLEN:
	case OMAKECHAN:
	case OMAKEMAP:
	case OMAKESLICE:
	case ONEW:
	case OREAL:
	case ORECOVER:
Russ Cox's avatar
Russ Cox committed
1112
		ordercall(n, order);
1113
		n = ordercopyexpr(n, n->type, order, 0);
Russ Cox's avatar
Russ Cox committed
1114 1115
		break;

1116
	case OCLOSURE:
1117 1118
		if(n->noescape && n->cvars != nil)
			n->alloc = ordertemp(types[TUINT8], order, 0); // walk will fill in correct type
1119
		break;
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130

	case OARRAYLIT:
	case OCALLPART:
		orderexpr(&n->left, order);
		orderexpr(&n->right, order);
		orderexprlist(n->list, order);
		orderexprlist(n->rlist, order);
		if(n->noescape)
			n->alloc = ordertemp(types[TUINT8], order, 0); // walk will fill in correct type
		break;

1131 1132 1133 1134 1135 1136
	case ODDDARG:
		if(n->noescape) {
			// The ddd argument does not live beyond the call it is created for.
			// Allocate a temporary that will be cleaned up when this statement
			// completes. We could be more aggressive and try to arrange for it
			// to be cleaned up when the call completes.
1137
			n->alloc = ordertemp(n->type->type, order, 0);
1138 1139 1140
		}
		break;

Russ Cox's avatar
Russ Cox committed
1141
	case ORECV:
1142
	case ODOTTYPE:
Russ Cox's avatar
Russ Cox committed
1143
		orderexpr(&n->left, order);
1144
		n = ordercopyexpr(n, n->type, order, 1);
Russ Cox's avatar
Russ Cox committed
1145
		break;
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158

	case OEQ:
	case ONE:
		orderexpr(&n->left, order);
		orderexpr(&n->right, order);
		t = n->left->type;
		if(t->etype == TSTRUCT || isfixedarray(t)) {
			// for complex comparisons, we need both args to be
			// addressable so we can pass them to the runtime.
			orderaddrtemp(&n->left, order);
			orderaddrtemp(&n->right, order);
		}
		break;
Russ Cox's avatar
Russ Cox committed
1159 1160 1161 1162 1163 1164
	}
	
	lineno = lno;

	*np = n;
}