1 // Copyright 2009 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.
8 #include "../ld/textflag.h"
10 static Node* walkprint(Node*, NodeList**);
11 static Node* writebarrierfn(char*, Type*, Type*);
12 static Node* applywritebarrier(Node*, NodeList**);
13 static Node* mapfn(char*, Type*);
14 static Node* mapfndel(char*, Type*);
15 static Node* ascompatee1(int, Node*, Node*, NodeList**);
16 static NodeList* ascompatee(int, NodeList*, NodeList*, NodeList**);
17 static NodeList* ascompatet(int, NodeList*, Type**, int, NodeList**);
18 static NodeList* ascompatte(int, Node*, int, Type**, NodeList*, int, NodeList**);
19 static Node* convas(Node*, NodeList**);
20 static void heapmoves(void);
21 static NodeList* paramstoheap(Type **argin, int out);
22 static NodeList* reorder1(NodeList*);
23 static NodeList* reorder3(NodeList*);
24 static Node* addstr(Node*, NodeList**);
25 static Node* appendslice(Node*, NodeList**);
26 static Node* append(Node*, NodeList**);
27 static Node* copyany(Node*, NodeList**, int);
28 static Node* sliceany(Node*, NodeList**);
29 static void walkcompare(Node**, NodeList**);
30 static void walkrotate(Node**);
31 static void walkmul(Node**, NodeList**);
32 static void walkdiv(Node**, NodeList**);
33 static int bounded(Node*, int64);
35 static void walkprintfunc(Node**, NodeList**);
47 snprint(s, sizeof(s), "\nbefore %S", curfn->nname->sym);
48 dumplist(s, curfn->nbody);
53 // Final typecheck for any unused variables.
54 // It's hard to be on the heap when not-used, but best to be consistent about &~PHEAP here and below.
55 for(l=fn->dcl; l; l=l->next)
56 if(l->n->op == ONAME && (l->n->class&~PHEAP) == PAUTO)
57 typecheck(&l->n, Erv | Easgn);
59 // Propagate the used flag for typeswitch variables up to the NONAME in it's definition.
60 for(l=fn->dcl; l; l=l->next)
61 if(l->n->op == ONAME && (l->n->class&~PHEAP) == PAUTO && l->n->defn && l->n->defn->op == OTYPESW && l->n->used)
62 l->n->defn->left->used++;
64 for(l=fn->dcl; l; l=l->next) {
65 if(l->n->op != ONAME || (l->n->class&~PHEAP) != PAUTO || l->n->sym->name[0] == '&' || l->n->used)
67 if(l->n->defn && l->n->defn->op == OTYPESW) {
68 if(l->n->defn->left->used)
70 lineno = l->n->defn->left->lineno;
71 yyerror("%S declared and not used", l->n->sym);
72 l->n->defn->left->used = 1; // suppress repeats
74 lineno = l->n->lineno;
75 yyerror("%S declared and not used", l->n->sym);
82 walkstmtlist(curfn->nbody);
84 snprint(s, sizeof(s), "after walk %S", curfn->nname->sym);
85 dumplist(s, curfn->nbody);
88 if(debug['W'] && curfn->enter != nil) {
89 snprint(s, sizeof(s), "enter %S", curfn->nname->sym);
90 dumplist(s, curfn->enter);
96 walkstmtlist(NodeList *l)
103 samelist(NodeList *a, NodeList *b)
105 for(; a && b; a=a->next, b=b->next)
112 paramoutheap(Node *fn)
116 for(l=fn->dcl; l; l=l->next) {
117 switch(l->n->class) {
119 case PPARAMOUT|PHEAP:
120 return l->n->addrtaken;
123 // stop early - parameters are over
141 if(n->dodata == 2) // don't walk, generated by anylit.
146 walkstmtlist(n->ninit);
151 yyerror("%S is not a top level statement", n->sym);
153 yyerror("%O is not a top level statement", n->op);
177 if(n->typecheck == 0)
178 fatal("missing typecheck: %+N", n);
183 if((*np)->op == OCOPY && n->op == OCONVNOP)
184 n->op = OEMPTY; // don't leave plain values as statements.
188 // special case for a receive where we throw away
189 // the value received.
190 if(n->typecheck == 0)
191 fatal("missing typecheck: %+N", n);
195 walkexpr(&n->left, &init);
196 n = mkcall1(chanfn("chanrecv1", 2, n->left->type), T, &init, typename(n->left->type), n->left, nodnil());
215 walkstmtlist(n->list);
219 yyerror("case statement out of place");
227 switch(n->left->op) {
230 walkprintfunc(&n->left, &n->ninit);
233 n->left = copyany(n->left, &n->ninit, 1);
236 walkexpr(&n->left, &n->ninit);
243 walkstmtlist(n->ntest->ninit);
244 init = n->ntest->ninit;
245 n->ntest->ninit = nil;
246 walkexpr(&n->ntest, &init);
247 addinit(&n->ntest, init);
250 walkstmtlist(n->nbody);
254 walkexpr(&n->ntest, &n->ninit);
255 walkstmtlist(n->nbody);
256 walkstmtlist(n->nelse);
260 switch(n->left->op) {
263 walkprintfunc(&n->left, &n->ninit);
266 n->left = copyany(n->left, &n->ninit, 1);
269 walkexpr(&n->left, &n->ninit);
275 walkexprlist(n->list, &n->ninit);
278 if((curfn->type->outnamed && count(n->list) > 1) || paramoutheap(curfn)) {
279 // assign to the function out parameters,
280 // so that reorder3 can fix up conflicts
282 for(ll=curfn->dcl; ll != nil; ll=ll->next) {
283 cl = ll->n->class & ~PHEAP;
287 rl = list(rl, ll->n);
289 if(samelist(rl, n->list)) {
290 // special return in disguise
294 if(count(n->list) == 1 && count(rl) > 1) {
295 // OAS2FUNC in disguise
297 if(f->op != OCALLFUNC && f->op != OCALLMETH && f->op != OCALLINTER)
298 fatal("expected return of call, have %N", f);
299 n->list = concat(list1(f), ascompatet(n->op, rl, &f->type, 0, &n->ninit));
303 // move function calls out, to make reorder3's job easier.
304 walkexprlistsafe(n->list, &n->ninit);
305 ll = ascompatee(n->op, rl, n->list, &n->ninit);
306 n->list = reorder3(ll);
309 ll = ascompatte(n->op, nil, 0, getoutarg(curfn->type), n->list, 1, &n->ninit);
329 yyerror("fallthrough statement out of place");
335 fatal("walkstmt ended up with name: %+N", n);
342 * walk the whole tree of the body of an
343 * expression or simple statement.
344 * the types expressions are calculated.
345 * compile-time constants are evaluated.
346 * complex side effects like statements are appended to init
350 walkexprlist(NodeList *l, NodeList **init)
353 walkexpr(&l->n, init);
357 walkexprlistsafe(NodeList *l, NodeList **init)
359 for(; l; l=l->next) {
360 l->n = safeexpr(l->n, init);
361 walkexpr(&l->n, init);
366 walkexpr(Node **np, NodeList **init)
368 Node *r, *l, *var, *a;
372 int et, old_safemode;
375 Node *n, *fn, *n1, *n2;
384 if(init == &n->ninit) {
385 // not okay to use n->ninit when walking n,
386 // because we might replace n with some other node
387 // and would lose the init list.
388 fatal("walkexpr init == &n->ninit");
391 if(n->ninit != nil) {
392 walkstmtlist(n->ninit);
393 *init = concat(*init, n->ninit);
397 // annoying case - not typechecked
399 walkexpr(&n->left, init);
400 walkexpr(&n->right, init);
407 dump("walk-before", n);
409 if(n->typecheck != 1)
410 fatal("missed typecheck: %+N\n", n);
415 fatal("walkexpr: switch 1 unknown op %+hN", n);
432 walkexpr(&n->left, init);
436 walkexpr(&n->left, init);
441 walkexpr(&n->left, init);
446 if(n->op == ODOTPTR && n->left->type->type->width == 0) {
447 // No actual copy will be generated, so emit an explicit nil check.
448 n->left = cheapexpr(n->left, init);
449 checknil(n->left, init);
451 walkexpr(&n->left, init);
455 walkexpr(&n->left, init);
456 walkexpr(&n->right, init);
461 walkexpr(&n->left, init);
466 walkexpr(&n->left, init);
468 // replace len(*[10]int) with 10.
469 // delayed until now to preserve side effects.
473 if(isfixedarray(t)) {
474 safeexpr(n->left, init);
475 nodconst(n, n->type, t->bound);
482 walkexpr(&n->left, init);
483 walkexpr(&n->right, init);
485 n->bounded = bounded(n->right, 8*t->width);
486 if(debug['m'] && n->etype && !isconst(n->right, CTINT))
487 warn("shift bounds check elided");
500 // Use results from call expression as arguments for complex.
501 if(n->op == OCOMPLEX && n->left == N && n->right == N) {
502 n->left = n->list->n;
503 n->right = n->list->next->n;
505 walkexpr(&n->left, init);
506 walkexpr(&n->right, init);
511 walkexpr(&n->left, init);
512 walkexpr(&n->right, init);
518 walkexpr(&n->left, init);
519 walkexpr(&n->right, init);
520 // Disable safemode while compiling this code: the code we
521 // generate internally can refer to unsafe.Pointer.
522 // In this case it can happen if we need to generate an ==
523 // for a struct containing a reflect.Value, which itself has
524 // an unexported field of type unsafe.Pointer.
525 old_safemode = safemode;
527 walkcompare(&n, init);
528 safemode = old_safemode;
533 walkexpr(&n->left, init);
534 // cannot put side effects from n->right on init,
535 // because they cannot run before n->left is checked.
536 // save elsewhere and store on the eventual n->right.
538 walkexpr(&n->right, &ll);
539 addinit(&n->right, ll);
544 walkexprlist(n->list, init);
545 n = walkprint(n, init);
549 n = mkcall("gopanic", T, init, n->left);
553 n = mkcall("gorecover", n->type, init, nod(OADDR, nodfp, N));
566 if(!(n->class & PHEAP) && n->class != PPARAMREF)
572 if(n->list && n->list->n->op == OAS)
574 walkexpr(&n->left, init);
575 walkexprlist(n->list, init);
576 ll = ascompatte(n->op, n, n->isddd, getinarg(t), n->list, 0, init);
577 n->list = reorder1(ll);
582 if(n->list && n->list->n->op == OAS)
585 walkexpr(&n->left, init);
586 walkexprlist(n->list, init);
588 ll = ascompatte(n->op, n, n->isddd, getinarg(t), n->list, 0, init);
589 n->list = reorder1(ll);
594 if(n->list && n->list->n->op == OAS)
596 walkexpr(&n->left, init);
597 walkexprlist(n->list, init);
598 ll = ascompatte(n->op, n, 0, getthis(t), list1(n->left->left), 0, init);
599 lr = ascompatte(n->op, n, n->isddd, getinarg(t), n->list, 0, init);
603 n->list = reorder1(ll);
607 *init = concat(*init, n->ninit);
610 walkexpr(&n->left, init);
611 n->left = safeexpr(n->left, init);
616 if(n->right == N || iszero(n->right) && !flag_race)
619 switch(n->right->op) {
621 walkexpr(&n->right, init);
625 // x = <-c; n->left is x, n->right->left is c.
626 // orderstmt made sure x is addressable.
627 walkexpr(&n->right->left, init);
628 n1 = nod(OADDR, n->left, N);
629 r = n->right->left; // the channel
630 n = mkcall1(chanfn("chanrecv1", 2, r->type), T, init, typename(r->type), r, n1);
635 if(n->left != N && n->right != N) {
636 r = convas(nod(OAS, n->left, n->right), init);
637 r->dodata = n->dodata;
639 n = applywritebarrier(n, init);
645 *init = concat(*init, n->ninit);
647 walkexprlistsafe(n->list, init);
648 walkexprlistsafe(n->rlist, init);
649 ll = ascompatee(OAS, n->list, n->rlist, init);
651 for(lr = ll; lr != nil; lr = lr->next)
652 lr->n = applywritebarrier(lr->n, init);
658 *init = concat(*init, n->ninit);
661 walkexprlistsafe(n->list, init);
664 ll = ascompatet(n->op, n->list, &r->type, 0, init);
665 for(lr = ll; lr != nil; lr = lr->next)
666 lr->n = applywritebarrier(lr->n, init);
667 n = liststmt(concat(list1(r), ll));
672 // orderstmt made sure x is addressable.
673 *init = concat(*init, n->ninit);
676 walkexprlistsafe(n->list, init);
677 walkexpr(&r->left, init);
678 if(isblank(n->list->n))
681 n1 = nod(OADDR, n->list->n, N);
682 n1->etype = 1; // addr does not escape
683 fn = chanfn("chanrecv2", 2, r->left->type);
684 r = mkcall1(fn, n->list->next->n->type, init, typename(r->left->type), r->left, n1);
685 n = nod(OAS, n->list->next->n, r);
691 *init = concat(*init, n->ninit);
694 walkexprlistsafe(n->list, init);
695 walkexpr(&r->left, init);
696 walkexpr(&r->right, init);
699 if(t->type->width <= 128) { // Check ../../runtime/hashmap.c:MAXVALUESIZE before changing.
700 switch(simsimtype(t->down)) {
703 p = "mapaccess2_fast32";
707 p = "mapaccess2_fast64";
710 p = "mapaccess2_faststr";
715 // fast versions take key by value
718 // standard version takes key by reference
719 // orderexpr made sure key is addressable.
720 key = nod(OADDR, r->right, N);
727 // var,b = mapaccess2*(t, m, i)
730 var = temp(ptrto(t->type));
733 r = mkcall1(fn, getoutargx(fn->type), init, typename(t), r->left, key);
735 // mapaccess2* returns a typed bool, but due to spec changes,
736 // the boolean result of i.(T) is now untyped so we make it the
737 // same type as the variable on the lhs.
738 if(!isblank(n->list->next->n))
739 r->type->type->down->type = n->list->next->n->type;
744 *init = list(*init, n);
745 n = nod(OAS, a, nod(OIND, var, N));
748 // mapaccess needs a zero value to be at least this big.
749 if(zerosize < t->type->width)
750 zerosize = t->type->width;
751 // TODO: ptr is always non-nil, so disable nil check for this OIND op.
755 *init = concat(*init, n->ninit);
758 key = n->list->next->n;
759 walkexpr(&map, init);
760 walkexpr(&key, init);
761 // orderstmt made sure key is addressable.
762 key = nod(OADDR, key, N);
764 n = mkcall1(mapfndel("mapdelete", t), T, init, typename(t), map, key);
769 *init = concat(*init, n->ninit);
772 walkexprlistsafe(n->list, init);
773 if(isblank(n->list->n) && !isinter(r->type)) {
774 strcpy(buf, "assert");
776 if(isnilinter(r->left->type))
786 fn = syslook(buf, 1);
788 // runtime.assert(E|I)2TOK returns a typed bool, but due
789 // to spec changes, the boolean result of i.(T) is now untyped
790 // so we make it the same type as the variable on the lhs.
791 if(!isblank(n->list->next->n))
792 fn->type->type->down->type->type = n->list->next->n->type;
793 ll = list1(typename(r->type));
794 ll = list(ll, r->left);
795 argtype(fn, r->left->type);
796 n1 = nod(OCALL, fn, N);
798 n = nod(OAS, n->list->next->n, n1);
806 ll = ascompatet(n->op, n->list, &r->type, 0, init);
807 n = liststmt(concat(list1(r), ll));
812 // Build name of function: assertI2E2 etc.
813 strcpy(buf, "assert");
815 if(isnilinter(n->left->type))
820 if(isnilinter(n->type))
822 else if(isinter(n->type))
826 if(n->op == ODOTTYPE2)
830 fn = syslook(buf, 1);
831 ll = list1(typename(n->type));
832 ll = list(ll, n->left);
833 argtype(fn, n->left->type);
834 argtype(fn, n->type);
835 n = nod(OCALL, fn, N);
837 typecheck(&n, Erv | Efnstruct);
842 walkexpr(&n->left, init);
844 // Optimize convT2E as a two-word copy when T is uintptr-shaped.
845 if(isnilinter(n->type) && isdirectiface(n->left->type) && n->left->type->width == widthptr && isint[simsimtype(n->left->type)]) {
846 l = nod(OEFACE, typename(n->left->type), n->left);
848 l->typecheck = n->typecheck;
853 // Build name of function: convI2E etc.
854 // Not all names are possible
855 // (e.g., we'll never generate convE2E or convE2I).
858 if(isnilinter(n->left->type))
860 else if(isinter(n->left->type))
865 if(isnilinter(n->type))
871 fn = syslook(buf, 1);
873 if(!isinter(n->left->type))
874 ll = list(ll, typename(n->left->type));
875 if(!isnilinter(n->type))
876 ll = list(ll, typename(n->type));
877 if(!isinter(n->left->type) && !isnilinter(n->type)){
878 sym = pkglookup(smprint("%-T.%-T", n->left->type, n->type), itabpkg);
880 l = nod(ONAME, N, N);
882 l->type = ptrto(types[TUINT8]);
887 ggloblsym(sym, widthptr, DUPOK|NOPTR);
889 l = nod(OADDR, sym->def, N);
893 if(isdirectiface(n->left->type) && n->left->type->width == widthptr && isint[simsimtype(n->left->type)]) {
894 /* For pointer types, we can make a special form of optimization
896 * These statements are put onto the expression init list:
897 * Itab *tab = atomicloadtype(&cache);
899 * tab = typ2Itab(type, itype, &cache);
901 * The CONVIFACE expression is replaced with this:
904 l = temp(ptrto(types[TUINT8]));
906 n1 = nod(OAS, l, sym->def);
907 typecheck(&n1, Etop);
908 *init = list(*init, n1);
910 fn = syslook("typ2Itab", 1);
911 n1 = nod(OCALL, fn, N);
917 n2->ntest = nod(OEQ, l, nodnil());
918 n2->nbody = list1(nod(OAS, l, n1));
920 typecheck(&n2, Etop);
921 *init = list(*init, n2);
923 l = nod(OEFACE, l, n->left);
924 l->typecheck = n->typecheck;
930 if(isinter(n->left->type)) {
931 ll = list(ll, n->left);
933 // regular types are passed by reference to avoid C vararg calls
934 // orderexpr arranged for n->left to be a temporary for all
935 // the conversions it could see. comparison of an interface
936 // with a non-interface, especially in a switch on interface value
937 // with non-interface cases, is not visible to orderstmt, so we
938 // have to fall back on allocating a temp here.
939 if(islvalue(n->left))
940 ll = list(ll, nod(OADDR, n->left, N));
942 ll = list(ll, nod(OADDR, copyexpr(n->left, n->left->type, init), N));
944 argtype(fn, n->left->type);
945 argtype(fn, n->type);
947 n = nod(OCALL, fn, N);
956 if(isfloat[n->left->type->etype]) {
957 if(n->type->etype == TINT64) {
958 n = mkcall("float64toint64", n->type, init, conv(n->left, types[TFLOAT64]));
961 if(n->type->etype == TUINT64) {
962 n = mkcall("float64touint64", n->type, init, conv(n->left, types[TFLOAT64]));
966 if(isfloat[n->type->etype]) {
967 if(n->left->type->etype == TINT64) {
968 n = mkcall("int64tofloat64", n->type, init, conv(n->left, types[TINT64]));
971 if(n->left->type->etype == TUINT64) {
972 n = mkcall("uint64tofloat64", n->type, init, conv(n->left, types[TUINT64]));
977 walkexpr(&n->left, init);
981 walkexpr(&n->left, init);
983 n->right = nod(OCOM, n->right, N);
984 typecheck(&n->right, Erv);
985 walkexpr(&n->right, init);
989 walkexpr(&n->left, init);
990 walkexpr(&n->right, init);
996 walkexpr(&n->left, init);
997 walkexpr(&n->right, init);
999 * rewrite complex div into function call.
1001 et = n->left->type->etype;
1002 if(iscomplex[et] && n->op == ODIV) {
1004 n = mkcall("complex128div", types[TCOMPLEX128], init,
1005 conv(n->left, types[TCOMPLEX128]),
1006 conv(n->right, types[TCOMPLEX128]));
1010 // Nothing to do for float divisions.
1014 // Try rewriting as shifts or magic multiplies.
1018 * rewrite 64-bit div and mod into function calls
1019 * on 32-bit architectures.
1024 if(widthreg >= 8 || (et != TUINT64 && et != TINT64))
1027 strcpy(namebuf, "int64");
1029 strcpy(namebuf, "uint64");
1031 strcat(namebuf, "div");
1033 strcat(namebuf, "mod");
1034 n = mkcall(namebuf, n->type, init,
1035 conv(n->left, types[et]), conv(n->right, types[et]));
1043 walkexpr(&n->left, init);
1044 // save the original node for bounds checking elision.
1045 // If it was a ODIV/OMOD walk might rewrite it.
1047 walkexpr(&n->right, init);
1049 // if range of type cannot exceed static array bound,
1050 // disable bounds check.
1054 if(t != T && isptr[t->etype])
1056 if(isfixedarray(t)) {
1057 n->bounded = bounded(r, t->bound);
1058 if(debug['m'] && n->bounded && !isconst(n->right, CTINT))
1059 warn("index bounds check elided");
1060 if(smallintconst(n->right) && !n->bounded)
1061 yyerror("index out of bounds");
1062 } else if(isconst(n->left, CTSTR)) {
1063 n->bounded = bounded(r, n->left->val.u.sval->len);
1064 if(debug['m'] && n->bounded && !isconst(n->right, CTINT))
1065 warn("index bounds check elided");
1066 if(smallintconst(n->right)) {
1068 yyerror("index out of bounds");
1070 // replace "abc"[1] with 'b'.
1071 // delayed until now because "abc"[1] is not
1072 // an ideal constant.
1073 v = mpgetfix(n->right->val.u.xval);
1074 nodconst(n, n->type, n->left->val.u.sval->s[v]);
1080 if(isconst(n->right, CTINT))
1081 if(mpcmpfixfix(n->right->val.u.xval, &mpzero) < 0 ||
1082 mpcmpfixfix(n->right->val.u.xval, maxintval[TINT]) > 0)
1083 yyerror("index out of bounds");
1089 walkexpr(&n->left, init);
1090 walkexpr(&n->right, init);
1094 if(t->type->width <= 128) { // Check ../../runtime/hashmap.c:MAXVALUESIZE before changing.
1095 switch(simsimtype(t->down)) {
1098 p = "mapaccess1_fast32";
1102 p = "mapaccess1_fast64";
1105 p = "mapaccess1_faststr";
1110 // fast versions take key by value
1113 // standard version takes key by reference.
1114 // orderexpr made sure key is addressable.
1115 key = nod(OADDR, n->right, N);
1118 n = mkcall1(mapfn(p, t), ptrto(t->type), init, typename(t), n->left, key);
1119 n = nod(OIND, n, N);
1122 // mapaccess needs a zero value to be at least this big.
1123 if(zerosize < t->type->width)
1124 zerosize = t->type->width;
1128 fatal("walkexpr ORECV"); // should see inside OAS only
1131 if(n->right != N && n->right->left == N && n->right->right == N) { // noop
1132 walkexpr(&n->left, init);
1139 if(n->right == N) // already processed
1142 walkexpr(&n->left, init);
1143 // cgen_slice can't handle string literals as source
1144 // TODO the OINDEX case is a bug elsewhere that needs to be traced. it causes a crash on ([2][]int{ ... })[1][lo:hi]
1145 if((n->op == OSLICESTR && n->left->op == OLITERAL) || (n->left->op == OINDEX))
1146 n->left = copyexpr(n->left, n->left->type, init);
1148 n->left = safeexpr(n->left, init);
1149 walkexpr(&n->right->left, init);
1150 n->right->left = safeexpr(n->right->left, init);
1151 walkexpr(&n->right->right, init);
1152 n->right->right = safeexpr(n->right->right, init);
1153 n = sliceany(n, init); // chops n->right, sets n->list
1158 if(n->right == N) // already processed
1161 walkexpr(&n->left, init);
1162 // TODO the OINDEX case is a bug elsewhere that needs to be traced. it causes a crash on ([2][]int{ ... })[1][lo:hi]
1163 // TODO the comment on the previous line was copied from case OSLICE. it might not even be true.
1164 if(n->left->op == OINDEX)
1165 n->left = copyexpr(n->left, n->left->type, init);
1167 n->left = safeexpr(n->left, init);
1168 walkexpr(&n->right->left, init);
1169 n->right->left = safeexpr(n->right->left, init);
1170 walkexpr(&n->right->right->left, init);
1171 n->right->right->left = safeexpr(n->right->right->left, init);
1172 walkexpr(&n->right->right->right, init);
1173 n->right->right->right = safeexpr(n->right->right->right, init);
1174 n = sliceany(n, init); // chops n->right, sets n->list
1178 walkexpr(&n->left, init);
1182 if(n->esc == EscNone && n->type->type->width < (1<<16)) {
1183 r = temp(n->type->type);
1184 r = nod(OAS, r, N); // zero temp
1185 typecheck(&r, Etop);
1186 *init = list(*init, r);
1187 r = nod(OADDR, r->left, N);
1191 n = callnew(n->type->type);
1196 // If one argument to the comparison is an empty string,
1197 // comparing the lengths instead will yield the same result
1198 // without the function call.
1199 if((isconst(n->left, CTSTR) && n->left->val.u.sval->len == 0) ||
1200 (isconst(n->right, CTSTR) && n->right->val.u.sval->len == 0)) {
1201 r = nod(n->etype, nod(OLEN, n->left, N), nod(OLEN, n->right, N));
1209 // s + "badgerbadgerbadger" == "badgerbadgerbadger"
1210 if((n->etype == OEQ || n->etype == ONE) &&
1211 isconst(n->right, CTSTR) &&
1212 n->left->op == OADDSTR && count(n->left->list) == 2 &&
1213 isconst(n->left->list->next->n, CTSTR) &&
1214 cmpslit(n->right, n->left->list->next->n) == 0) {
1215 r = nod(n->etype, nod(OLEN, n->left->list->n, N), nodintconst(0));
1223 if(n->etype == OEQ || n->etype == ONE) {
1224 // prepare for rewrite below
1225 n->left = cheapexpr(n->left, init);
1226 n->right = cheapexpr(n->right, init);
1228 r = mkcall("eqstring", types[TBOOL], init,
1229 conv(n->left, types[TSTRING]),
1230 conv(n->right, types[TSTRING]));
1232 // quick check of len before full compare for == or !=
1233 if(n->etype == OEQ) {
1234 // len(left) == len(right) && eqstring(left, right)
1235 r = nod(OANDAND, nod(OEQ, nod(OLEN, n->left, N), nod(OLEN, n->right, N)), r);
1237 // len(left) != len(right) || !eqstring(left, right)
1238 r = nod(ONOT, r, N);
1239 r = nod(OOROR, nod(ONE, nod(OLEN, n->left, N), nod(OLEN, n->right, N)), r);
1244 // sys_cmpstring(s1, s2) :: 0
1245 r = mkcall("cmpstring", types[TINT], init,
1246 conv(n->left, types[TSTRING]),
1247 conv(n->right, types[TSTRING]));
1248 r = nod(n->etype, r, nodintconst(0));
1252 if(n->type->etype != TBOOL) fatal("cmp %T", n->type);
1258 n = addstr(n, init);
1263 n = appendslice(n, init); // also works for append(slice, string).
1265 n = append(n, init);
1269 n = copyany(n, init, flag_race);
1273 // cannot use chanfn - closechan takes any, not chan any
1274 fn = syslook("closechan", 1);
1275 argtype(fn, n->left->type);
1276 n = mkcall1(fn, T, init, n->left);
1280 n = mkcall1(chanfn("makechan", 1, n->type), n->type, init,
1282 conv(n->left, types[TINT64]));
1288 fn = syslook("makemap", 1);
1289 argtype(fn, t->down); // any-1
1290 argtype(fn, t->type); // any-2
1292 n = mkcall1(fn, n->type, init,
1294 conv(n->left, types[TINT64]));
1301 l = r = safeexpr(l, init);
1303 if(n->esc == EscNone
1304 && smallintconst(l) && smallintconst(r)
1305 && (t->type->width == 0 || mpgetfix(r->val.u.xval) < (1ULL<<16) / t->type->width)) {
1308 t = aindex(r, t->type); // [r]T
1310 a = nod(OAS, var, N); // zero temp
1311 typecheck(&a, Etop);
1312 *init = list(*init, a);
1313 r = nod(OSLICE, var, nod(OKEY, N, l)); // arr[:l]
1314 r = conv(r, n->type); // in case n->type is named.
1319 // makeslice(t *Type, nel int64, max int64) (ary []any)
1320 fn = syslook("makeslice", 1);
1321 argtype(fn, t->type); // any-1
1322 n = mkcall1(fn, n->type, init,
1324 conv(l, types[TINT64]),
1325 conv(r, types[TINT64]));
1331 n = mkcall("intstring", n->type, init,
1332 conv(n->left, types[TINT64]));
1336 // slicebytetostring([]byte) string;
1337 n = mkcall("slicebytetostring", n->type, init, n->left);
1340 case OARRAYBYTESTRTMP:
1341 // slicebytetostringtmp([]byte) string;
1342 n = mkcall("slicebytetostringtmp", n->type, init, n->left);
1346 // slicerunetostring([]rune) string;
1347 n = mkcall("slicerunetostring", n->type, init, n->left);
1351 // stringtoslicebyte(string) []byte;
1352 n = mkcall("stringtoslicebyte", n->type, init, conv(n->left, types[TSTRING]));
1356 // stringtoslicerune(string) []rune
1357 n = mkcall("stringtoslicerune", n->type, init, n->left);
1361 // ifaceeq(i1 any-1, i2 any-2) (ret bool);
1362 if(!eqtype(n->left->type, n->right->type))
1363 fatal("ifaceeq %O %T %T", n->op, n->left->type, n->right->type);
1364 if(isnilinter(n->left->type))
1365 fn = syslook("efaceeq", 1);
1367 fn = syslook("ifaceeq", 1);
1369 n->right = cheapexpr(n->right, init);
1370 n->left = cheapexpr(n->left, init);
1371 argtype(fn, n->right->type);
1372 argtype(fn, n->left->type);
1373 r = mkcall1(fn, n->type, init, n->left, n->right);
1375 r = nod(ONOT, r, N);
1377 // check itable/type before full compare.
1379 r = nod(OANDAND, nod(OEQ, nod(OITAB, n->left, N), nod(OITAB, n->right, N)), r);
1381 r = nod(OOROR, nod(ONE, nod(OITAB, n->left, N), nod(OITAB, n->right, N)), r);
1392 var = temp(n->type);
1393 anylit(0, n, var, init);
1399 n1 = assignconv(n1, n->left->type->type, "chan send");
1400 walkexpr(&n1, init);
1401 n1 = nod(OADDR, n1, N);
1402 n = mkcall1(chanfn("chansend1", 2, n->left->type), T, init, typename(n->left->type), n->left, n1);
1406 n = walkclosure(n, init);
1410 n = walkpartialcall(n, init);
1413 fatal("missing switch %O", n->op);
1416 // Expressions that are constant at run time but not
1417 // considered const by the language spec are not turned into
1418 // constants until walk. For example, if n is y%1 == 0, the
1419 // walk of y%1 may have replaced it by 0.
1420 // Check whether n with its updated args is itself now a constant.
1424 if(n->op == OLITERAL)
1429 if(debug['w'] && n != N)
1437 ascompatee1(int op, Node *l, Node *r, NodeList **init)
1442 // convas will turn map assigns into function calls,
1443 // making it impossible for reorder3 to work.
1445 if(l->op == OINDEXMAP)
1448 return convas(n, init);
1452 ascompatee(int op, NodeList *nl, NodeList *nr, NodeList **init)
1454 NodeList *ll, *lr, *nn;
1457 * check assign expression list to
1458 * a expression list. called in
1459 * expr-list = expr-list
1462 // ensure order of evaluation for function calls
1463 for(ll=nl; ll; ll=ll->next)
1464 ll->n = safeexpr(ll->n, init);
1465 for(lr=nr; lr; lr=lr->next)
1466 lr->n = safeexpr(lr->n, init);
1469 for(ll=nl, lr=nr; ll && lr; ll=ll->next, lr=lr->next) {
1470 // Do not generate 'x = x' during return. See issue 4014.
1471 if(op == ORETURN && ll->n == lr->n)
1473 nn = list(nn, ascompatee1(op, ll->n, lr->n, init));
1476 // cannot happen: caller checked that lists had same length
1478 yyerror("error in shape across %+H %O %+H / %d %d [%s]", nl, op, nr, count(nl), count(nr), curfn->nname->sym->name);
1483 * l is an lv and rt is the type of an rv
1484 * return 1 if this implies a function call
1485 * evaluating the lv or a function call
1486 * in the conversion of the types
1489 fncall(Node *l, Type *rt)
1493 if(l->ullman >= UINF || l->op == OINDEXMAP)
1495 memset(&r, 0, sizeof r);
1496 if(needwritebarrier(l, &r))
1498 if(eqtype(l->type, rt))
1504 ascompatet(int op, NodeList *nl, Type **nr, int fp, NodeList **init)
1516 * check assign type list to
1517 * a expression list. called in
1518 * expr-list = func()
1520 r = structfirst(&saver, nr);
1524 for(ll=nl; ll; ll=ll->next) {
1529 r = structnext(&saver);
1533 // any lv that causes a fn call must be
1534 // deferred until all the return arguments
1535 // have been pulled from the output arguments
1536 if(fncall(l, r->type)) {
1537 tmp = temp(r->type);
1538 typecheck(&tmp, Erv);
1539 a = nod(OAS, l, tmp);
1540 a = convas(a, init);
1545 a = nod(OAS, l, nodarg(r, fp));
1546 a = convas(a, init);
1548 if(a->ullman >= UINF) {
1549 dump("ascompatet ucount", a);
1553 r = structnext(&saver);
1556 if(ll != nil || r != T)
1557 yyerror("ascompatet: assignment count mismatch: %d = %d",
1558 count(nl), structcount(*nr));
1561 fatal("ascompatet: too many function calls evaluating parameters");
1562 return concat(nn, mm);
1566 * package all the arguments that match a ... T parameter into a []T.
1569 mkdotargslice(NodeList *lr0, NodeList *nn, Type *l, int fp, NodeList **init, Node *ddd)
1579 tslice = typ(TARRAY);
1580 tslice->type = l->type->type;
1583 if(count(lr0) == 0) {
1587 n = nod(OCOMPLIT, N, typenod(tslice));
1589 n->alloc = ddd->alloc; // temporary to use
1594 fatal("mkdotargslice: typecheck failed");
1598 a = nod(OAS, nodarg(l, fp), n);
1599 nn = list(nn, convas(a, init));
1604 * helpers for shape errors
1607 dumptypes(Type **nl, char *what)
1615 fmtprint(&fmt, "\t");
1617 for(l = structfirst(&savel, nl); l != T; l = structnext(&savel)) {
1621 fmtprint(&fmt, ", ");
1622 fmtprint(&fmt, "%T", l);
1625 fmtprint(&fmt, "[no arguments %s]", what);
1626 return fmtstrflush(&fmt);
1630 dumpnodetypes(NodeList *l, char *what)
1637 fmtprint(&fmt, "\t");
1639 for(; l; l=l->next) {
1644 fmtprint(&fmt, ", ");
1645 fmtprint(&fmt, "%T", r->type);
1648 fmtprint(&fmt, "[no arguments %s]", what);
1649 return fmtstrflush(&fmt);
1653 * check assign expression list to
1654 * a type list. called in
1659 ascompatte(int op, Node *call, int isddd, Type **nl, NodeList *lr, int fp, NodeList **init)
1663 NodeList *nn, *lr0, *alist;
1668 l = structfirst(&savel, nl);
1674 // f(g()) where g has multiple return values
1675 if(r != N && lr->next == nil && r->type->etype == TSTRUCT && r->type->funarg) {
1676 // optimization - can do block copy
1677 if(eqtypenoname(r->type, *nl)) {
1678 a = nodarg(*nl, fp);
1679 r = nod(OCONVNOP, r, N);
1681 nn = list1(convas(nod(OAS, a, r), init));
1685 // conversions involved.
1686 // copy into temporaries.
1688 for(l=structfirst(&savel, &r->type); l; l=structnext(&savel)) {
1690 alist = list(alist, a);
1692 a = nod(OAS2, N, N);
1695 typecheck(&a, Etop);
1697 *init = list(*init, a);
1700 l = structfirst(&savel, nl);
1704 if(l != T && l->isddd) {
1705 // the ddd parameter must be last
1706 ll = structnext(&savel);
1708 yyerror("... must be last argument");
1711 // only if we are assigning a single ddd
1712 // argument to a ddd parameter then it is
1713 // passed thru unencapsulated
1714 if(r != N && lr->next == nil && isddd && eqtype(l->type, r->type)) {
1715 a = nod(OAS, nodarg(l, fp), r);
1716 a = convas(a, init);
1721 // normal case -- make a slice of all
1722 // remaining arguments and pass it to
1723 // the ddd parameter.
1724 nn = mkdotargslice(lr, nn, l, fp, init, call->right);
1728 if(l == T || r == N) {
1729 if(l != T || r != N) {
1730 l1 = dumptypes(nl, "expected");
1731 l2 = dumpnodetypes(lr0, "given");
1733 yyerror("not enough arguments to %O\n%s\n%s", op, l1, l2);
1735 yyerror("too many arguments to %O\n%s\n%s", op, l1, l2);
1740 a = nod(OAS, nodarg(l, fp), r);
1741 a = convas(a, init);
1744 l = structnext(&savel);
1752 for(lr=nn; lr; lr=lr->next)
1753 lr->n->typecheck = 1;
1757 // generate code for print
1759 walkprint(Node *nn, NodeList **init)
1766 int notfirst, et, op;
1775 for(l=all; l; l=l->next) {
1777 calls = list(calls, mkcall("printsp", T, init));
1779 notfirst = op == OPRINTN;
1782 if(n->op == OLITERAL) {
1783 switch(n->val.ctype) {
1785 defaultlit(&n, runetype);
1788 defaultlit(&n, types[TINT64]);
1791 defaultlit(&n, types[TFLOAT64]);
1795 if(n->op != OLITERAL && n->type && n->type->etype == TIDEAL)
1796 defaultlit(&n, types[TINT64]);
1797 defaultlit(&n, nil);
1799 if(n->type == T || n->type->etype == TFORW)
1803 et = n->type->etype;
1804 if(isinter(n->type)) {
1805 if(isnilinter(n->type))
1806 on = syslook("printeface", 1);
1808 on = syslook("printiface", 1);
1809 argtype(on, n->type); // any-1
1810 } else if(isptr[et] || et == TCHAN || et == TMAP || et == TFUNC || et == TUNSAFEPTR) {
1811 on = syslook("printpointer", 1);
1812 argtype(on, n->type); // any-1
1813 } else if(isslice(n->type)) {
1814 on = syslook("printslice", 1);
1815 argtype(on, n->type); // any-1
1816 } else if(isint[et]) {
1818 if((t->sym->pkg == runtimepkg || compiling_runtime) && strcmp(t->sym->name, "hex") == 0)
1819 on = syslook("printhex", 0);
1821 on = syslook("printuint", 0);
1823 on = syslook("printint", 0);
1824 } else if(isfloat[et]) {
1825 on = syslook("printfloat", 0);
1826 } else if(iscomplex[et]) {
1827 on = syslook("printcomplex", 0);
1828 } else if(et == TBOOL) {
1829 on = syslook("printbool", 0);
1830 } else if(et == TSTRING) {
1831 on = syslook("printstring", 0);
1833 badtype(OPRINT, n->type, T);
1837 t = *getinarg(on->type);
1843 if(!eqtype(t, n->type)) {
1844 n = nod(OCONV, n, N);
1848 r = nod(OCALL, on, N);
1850 calls = list(calls, r);
1854 calls = list(calls, mkcall("printnl", T, nil));
1855 typechecklist(calls, Etop);
1856 walkexprlist(calls, init);
1858 r = nod(OEMPTY, N, N);
1859 typecheck(&r, Etop);
1871 fn = syslook("newobject", 1);
1873 return mkcall1(fn, ptrto(t), nil, typename(t));
1879 while(n->op == ODOT || n->op == OPAREN || n->op == OCONVNOP || n->op == OINDEX && isfixedarray(n->left->type))
1884 // OINDREG only ends up in walk if it's indirect of SP.
1903 while(n->op == ODOT || n->op == OPAREN || n->op == OCONVNOP || n->op == OINDEX && isfixedarray(n->left->type))
1918 // Do we need a write barrier for the assignment l = r?
1920 needwritebarrier(Node *l, Node *r)
1922 if(!use_writebarrier)
1925 if(l == N || isblank(l))
1928 // No write barrier for write of non-pointers.
1930 if(!haspointers(l->type))
1933 // No write barrier for write to stack.
1937 // No write barrier for implicit or explicit zeroing.
1938 if(r == N || iszero(r))
1941 // No write barrier for initialization to constant.
1942 if(r->op == OLITERAL)
1945 // No write barrier for storing static (read-only) data.
1946 if(r->op == ONAME && strncmp(r->sym->name, "statictmp_", 10) == 0)
1949 // No write barrier for storing address of stack values,
1950 // which are guaranteed only to be written to the stack.
1951 if(r->op == OADDR && isstack(r->left))
1954 // No write barrier for storing address of global, which
1955 // is live no matter what.
1956 if(r->op == OADDR && isglobal(r->left))
1959 // No write barrier for reslice: x = x[0:y] or x = append(x, ...).
1960 // Both are compiled to modify x directly.
1961 // In the case of append, a write barrier may still be needed
1962 // if the underlying array grows, but the append code can
1963 // generate the write barrier directly in that case.
1964 // (It does not yet, but the cost of the write barrier will be
1965 // small compared to the cost of the allocation.)
1974 dump("bad reslice-l", l);
1975 dump("bad reslice-r", r);
1981 // Otherwise, be conservative and use write barrier.
1985 // TODO(rsc): Perhaps componentgen should run before this.
1987 applywritebarrier(Node *n, NodeList **init)
1992 if(n->left && n->right && needwritebarrier(n->left, n->right)) {
1994 l = nod(OADDR, n->left, N);
1995 l->etype = 1; // addr does not escape
1996 if(t->width == widthptr) {
1997 n = mkcall1(writebarrierfn("writebarrierptr", t, n->right->type), T, init,
1999 } else if(t->etype == TSTRING) {
2000 n = mkcall1(writebarrierfn("writebarrierstring", t, n->right->type), T, init,
2002 } else if(isslice(t)) {
2003 n = mkcall1(writebarrierfn("writebarrierslice", t, n->right->type), T, init,
2005 } else if(isinter(t)) {
2006 n = mkcall1(writebarrierfn("writebarrieriface", t, n->right->type), T, init,
2008 } else if(t->width == 2*widthptr) {
2009 n = mkcall1(writebarrierfn("writebarrierfat2", t, n->right->type), T, init,
2010 l, nodnil(), n->right);
2011 } else if(t->width == 3*widthptr) {
2012 n = mkcall1(writebarrierfn("writebarrierfat3", t, n->right->type), T, init,
2013 l, nodnil(), n->right);
2014 } else if(t->width == 4*widthptr) {
2015 n = mkcall1(writebarrierfn("writebarrierfat4", t, n->right->type), T, init,
2016 l, nodnil(), n->right);
2019 while(r->op == OCONVNOP)
2021 r = nod(OADDR, r, N);
2022 r->etype = 1; // addr does not escape
2023 //warnl(n->lineno, "writebarrierfat %T %N", t, r);
2024 n = mkcall1(writebarrierfn("writebarrierfat", t, r->left->type), T, init,
2032 convas(Node *n, NodeList **init)
2035 Node *map, *key, *val;
2038 fatal("convas: not OAS %O", n->op);
2042 if(n->left == N || n->right == N)
2046 rt = n->right->type;
2047 if(lt == T || rt == T)
2050 if(isblank(n->left)) {
2051 defaultlit(&n->right, T);
2055 if(n->left->op == OINDEXMAP) {
2056 map = n->left->left;
2057 key = n->left->right;
2059 walkexpr(&map, init);
2060 walkexpr(&key, init);
2061 walkexpr(&val, init);
2062 // orderexpr made sure key and val are addressable.
2063 key = nod(OADDR, key, N);
2064 val = nod(OADDR, val, N);
2065 n = mkcall1(mapfn("mapassign1", map->type), T, init,
2066 typename(map->type), map, key, val);
2070 if(!eqtype(lt, rt)) {
2071 n->right = assignconv(n->right, lt, "assignment");
2072 walkexpr(&n->right, init);
2082 * evaluating actual function arguments.
2084 * if there is exactly one function expr,
2085 * then it is done first. otherwise must
2086 * make temp variables
2089 reorder1(NodeList *all)
2092 NodeList *l, *r, *g;
2095 c = 0; // function calls
2096 t = 0; // total parameters
2098 for(l=all; l; l=l->next) {
2102 if(n->ullman >= UINF)
2105 if(c == 0 || t == 1)
2108 g = nil; // fncalls assigned to tempnames
2109 f = N; // last fncall assigned to stack
2110 r = nil; // non fncalls and tempnames assigned to stack
2112 for(l=all; l; l=l->next) {
2114 if(n->ullman < UINF) {
2124 // make assignment of fncall to tempname
2125 a = temp(n->right->type);
2126 a = nod(OAS, a, n->right);
2129 // put normal arg assignment on list
2130 // with fncall replaced by tempname
2137 return concat(g, r);
2140 static void reorder3save(Node**, NodeList*, NodeList*, NodeList**);
2141 static int aliased(Node*, NodeList*, NodeList*);
2146 * simultaneous assignment. there cannot
2147 * be later use of an earlier lvalue.
2149 * function calls have been removed.
2152 reorder3(NodeList *all)
2154 NodeList *list, *early, *mapinit;
2157 // If a needed expression may be affected by an
2158 // earlier assignment, make an early copy of that
2159 // expression and use the copy instead.
2162 for(list=all; list; list=list->next) {
2165 // Save subexpressions needed on left side.
2166 // Drill through non-dereferences.
2168 if(l->op == ODOT || l->op == OPAREN) {
2172 if(l->op == OINDEX && isfixedarray(l->left->type)) {
2173 reorder3save(&l->right, all, list, &early);
2181 fatal("reorder3 unexpected lvalue %#O", l->op);
2186 reorder3save(&l->left, all, list, &early);
2187 reorder3save(&l->right, all, list, &early);
2188 if(l->op == OINDEXMAP)
2189 list->n = convas(list->n, &mapinit);
2193 reorder3save(&l->left, all, list, &early);
2196 // Save expression on right side.
2197 reorder3save(&list->n->right, all, list, &early);
2200 early = concat(mapinit, early);
2201 return concat(early, all);
2204 static int vmatch2(Node*, Node*);
2205 static int varexpr(Node*);
2208 * if the evaluation of *np would be affected by the
2209 * assignments in all up to but not including stop,
2210 * copy into a temporary during *early and
2211 * replace *np with that temp.
2214 reorder3save(Node **np, NodeList *all, NodeList *stop, NodeList **early)
2219 if(!aliased(n, all, stop))
2224 typecheck(&q, Etop);
2225 *early = list(*early, q);
2230 * what's the outer value that a write to n affects?
2231 * outer value means containing struct or array.
2237 if(n->op == ODOT || n->op == OPAREN) {
2241 if(n->op == OINDEX && isfixedarray(n->left->type)) {
2251 * Is it possible that the computation of n might be
2252 * affected by writes in as up to but not including stop?
2255 aliased(Node *n, NodeList *all, NodeList *stop)
2257 int memwrite, varwrite;
2264 // Look for obvious aliasing: a variable being assigned
2265 // during the all list and appearing in n.
2266 // Also record whether there are any writes to main memory.
2267 // Also record whether there are any writes to variables
2268 // whose addresses have been taken.
2271 for(l=all; l!=stop; l=l->next) {
2272 a = outervalue(l->n->left);
2273 if(a->op != ONAME) {
2295 // The variables being written do not appear in n.
2296 // However, n might refer to computed addresses
2297 // that are being written.
2299 // If no computed addresses are affected by the writes, no aliasing.
2300 if(!memwrite && !varwrite)
2303 // If n does not refer to computed addresses
2304 // (that is, if n only refers to variables whose addresses
2305 // have not been taken), no aliasing.
2309 // Otherwise, both the writes and n refer to computed memory addresses.
2310 // Assume that they might conflict.
2315 * does the evaluation of n only refer to variables
2316 * whose addresses have not been taken?
2317 * (and no other memory)
2355 case ODOT: // but not ODOTPTR
2360 return varexpr(n->left) && varexpr(n->right);
2368 * is the name l mentioned in r?
2371 vmatch2(Node *l, Node *r)
2379 // match each right given left
2384 if(vmatch2(l, r->left))
2386 if(vmatch2(l, r->right))
2388 for(ll=r->list; ll; ll=ll->next)
2389 if(vmatch2(l, ll->n))
2395 * is any name mentioned in l also mentioned in r?
2399 vmatch1(Node *l, Node *r)
2404 * isolate all left sides
2406 if(l == N || r == N)
2416 // assignment to non-stack variable
2417 // must be delayed if right has function calls.
2418 if(r->ullman >= UINF)
2422 return vmatch2(l, r);
2426 if(vmatch1(l->left, r))
2428 if(vmatch1(l->right, r))
2430 for(ll=l->list; ll; ll=ll->next)
2431 if(vmatch1(ll->n, r))
2437 * walk through argin parameters.
2438 * generate and return code to allocate
2439 * copies of escaped parameters to the heap.
2442 paramstoheap(Type **argin, int out)
2450 for(t = structfirst(&savet, argin); t != T; t = structnext(&savet)) {
2452 if(v && v->sym && v->sym->name[0] == '~' && v->sym->name[1] == 'r') // unnamed result
2454 // In precisestack mode, the garbage collector assumes results
2455 // are always live, so zero them always.
2456 if(out && (precisestack_enabled || (v == N && hasdefer))) {
2457 // Defer might stop a panic and show the
2458 // return values as they exist at the time of panic.
2459 // Make sure to zero them on entry to the function.
2460 nn = list(nn, nod(OAS, nodarg(t, 1), N));
2462 if(v == N || !(v->class & PHEAP))
2465 // generate allocation & copying code
2466 if(compiling_runtime)
2467 yyerror("%N escapes to heap, not allowed in runtime.", v);
2469 v->alloc = callnew(v->type);
2470 nn = list(nn, nod(OAS, v->heapaddr, v->alloc));
2471 if((v->class & ~PHEAP) != PPARAMOUT)
2472 nn = list(nn, nod(OAS, v, v->stackparam));
2478 * walk through argout parameters copying back to stack
2481 returnsfromheap(Type **argin)
2489 for(t = structfirst(&savet, argin); t != T; t = structnext(&savet)) {
2491 if(v == N || v->class != (PHEAP|PPARAMOUT))
2493 nn = list(nn, nod(OAS, v->stackparam, v));
2499 * take care of migrating any function in/out args
2500 * between the stack and the heap. adds code to
2501 * curfn's before and after lists.
2510 lineno = curfn->lineno;
2511 nn = paramstoheap(getthis(curfn->type), 0);
2512 nn = concat(nn, paramstoheap(getinarg(curfn->type), 0));
2513 nn = concat(nn, paramstoheap(getoutarg(curfn->type), 1));
2514 curfn->enter = concat(curfn->enter, nn);
2515 lineno = curfn->endlineno;
2516 curfn->exit = returnsfromheap(getoutarg(curfn->type));
2521 vmkcall(Node *fn, Type *t, NodeList **init, va_list va)
2527 if(fn->type == T || fn->type->etype != TFUNC)
2528 fatal("mkcall %N %T", fn, fn->type);
2531 n = fn->type->intuple;
2533 args = list(args, va_arg(va, Node*));
2535 r = nod(OCALL, fn, N);
2537 if(fn->type->outtuple > 0)
2538 typecheck(&r, Erv | Efnstruct);
2540 typecheck(&r, Etop);
2547 mkcall(char *name, Type *t, NodeList **init, ...)
2553 r = vmkcall(syslook(name, 0), t, init, va);
2559 mkcall1(Node *fn, Type *t, NodeList **init, ...)
2565 r = vmkcall(fn, t, init, va);
2571 conv(Node *n, Type *t)
2573 if(eqtype(n->type, t))
2575 n = nod(OCONV, n, N);
2582 chanfn(char *name, int n, Type *t)
2587 if(t->etype != TCHAN)
2588 fatal("chanfn %T", t);
2589 fn = syslook(name, 1);
2591 argtype(fn, t->type);
2596 mapfn(char *name, Type *t)
2600 if(t->etype != TMAP)
2601 fatal("mapfn %T", t);
2602 fn = syslook(name, 1);
2603 argtype(fn, t->down);
2604 argtype(fn, t->type);
2605 argtype(fn, t->down);
2606 argtype(fn, t->type);
2611 mapfndel(char *name, Type *t)
2615 if(t->etype != TMAP)
2616 fatal("mapfn %T", t);
2617 fn = syslook(name, 1);
2618 argtype(fn, t->down);
2619 argtype(fn, t->type);
2620 argtype(fn, t->down);
2625 writebarrierfn(char *name, Type *l, Type *r)
2629 fn = syslook(name, 1);
2636 addstr(Node *n, NodeList **init)
2638 Node *r, *cat, *slice;
2643 // orderexpr rewrote OADDSTR to have a list of strings.
2646 yyerror("addstr count %d too small", c);
2648 // build list of string arguments
2650 for(l=n->list; l != nil; l=l->next)
2651 args = list(args, conv(l->n, types[TSTRING]));
2654 // small numbers of strings use direct runtime helpers.
2655 // note: orderexpr knows this cutoff too.
2656 snprint(namebuf, sizeof(namebuf), "concatstring%d", c);
2658 // large numbers of strings are passed to the runtime as a slice.
2659 strcpy(namebuf, "concatstrings");
2661 t->type = types[TSTRING];
2663 slice = nod(OCOMPLIT, N, typenod(t));
2664 slice->alloc = n->alloc;
2666 slice->esc = EscNone;
2667 args = list1(slice);
2669 cat = syslook(namebuf, 1);
2670 r = nod(OCALL, cat, N);
2679 // expand append(l1, l2...) to
2682 // if n := len(l1) + len(l2) - cap(s); n > 0 {
2683 // s = growslice(s, n)
2685 // s = s[:len(l1)+len(l2)]
2686 // memmove(&s[len(l1)], &l2[0], len(l2)*sizeof(T))
2690 // l2 is allowed to be a string.
2692 appendslice(Node *n, NodeList **init)
2695 Node *l1, *l2, *nt, *nif, *fn;
2696 Node *nptr1, *nptr2, *nwid;
2699 walkexprlistsafe(n->list, init);
2701 // walkexprlistsafe will leave OINDEX (s[n]) alone if both s
2702 // and n are name or literal, but those may index the slice we're
2703 // modifying here. Fix explicitly.
2704 for(l=n->list; l; l=l->next)
2705 l->n = cheapexpr(l->n, init);
2708 l2 = n->list->next->n;
2710 s = temp(l1->type); // var s []T
2712 l = list(l, nod(OAS, s, l1)); // s = l1
2714 nt = temp(types[TINT]);
2715 nif = nod(OIF, N, N);
2716 // n := len(s) + len(l2) - cap(s)
2717 nif->ninit = list1(nod(OAS, nt,
2718 nod(OSUB, nod(OADD, nod(OLEN, s, N), nod(OLEN, l2, N)), nod(OCAP, s, N))));
2719 nif->ntest = nod(OGT, nt, nodintconst(0));
2720 // instantiate growslice(Type*, []any, int64) []any
2721 fn = syslook("growslice", 1);
2722 argtype(fn, s->type->type);
2723 argtype(fn, s->type->type);
2725 // s = growslice(T, s, n)
2726 nif->nbody = list1(nod(OAS, s, mkcall1(fn, s->type, &nif->ninit,
2729 conv(nt, types[TINT64]))));
2734 // rely on runtime to instrument copy.
2735 // copy(s[len(l1):len(l1)+len(l2)], l2)
2736 nptr1 = nod(OSLICE, s, nod(OKEY,
2738 nod(OADD, nod(OLEN, l1, N), nod(OLEN, l2, N))));
2741 if(l2->type->etype == TSTRING)
2742 fn = syslook("slicestringcopy", 1);
2744 fn = syslook("slicecopy", 1);
2745 argtype(fn, l1->type);
2746 argtype(fn, l2->type);
2747 nt = mkcall1(fn, types[TINT], &l,
2749 nodintconst(s->type->type->width));
2752 // memmove(&s[len(l1)], &l2[0], len(l2)*sizeof(T))
2753 nptr1 = nod(OINDEX, s, nod(OLEN, l1, N));
2755 nptr1 = nod(OADDR, nptr1, N);
2757 nptr2 = nod(OSPTR, l2, N);
2759 fn = syslook("memmove", 1);
2760 argtype(fn, s->type->type); // 1 old []any
2761 argtype(fn, s->type->type); // 2 ret []any
2763 nwid = cheapexpr(conv(nod(OLEN, l2, N), types[TUINTPTR]), &l);
2764 nwid = nod(OMUL, nwid, nodintconst(s->type->type->width));
2765 nt = mkcall1(fn, T, &l, nptr1, nptr2, nwid);
2769 // s = s[:len(l1)+len(l2)]
2770 nt = nod(OADD, nod(OLEN, l1, N), nod(OLEN, l2, N));
2771 nt = nod(OSLICE, s, nod(OKEY, N, nt));
2773 l = list(l, nod(OAS, s, nt));
2775 typechecklist(l, Etop);
2777 *init = concat(*init, l);
2781 // expand append(src, a [, b]* ) to
2785 // const argc = len(args) - 1
2786 // if cap(s) - len(s) < argc {
2787 // s = growslice(s, argc)
2797 append(Node *n, NodeList **init)
2800 Node *nsrc, *ns, *nn, *na, *nx, *fn;
2803 walkexprlistsafe(n->list, init);
2805 // walkexprlistsafe will leave OINDEX (s[n]) alone if both s
2806 // and n are name or literal, but those may index the slice we're
2807 // modifying here. Fix explicitly.
2808 for(l=n->list; l; l=l->next)
2809 l->n = cheapexpr(l->n, init);
2813 // Resolve slice type of multi-valued return.
2814 if(istype(nsrc->type, TSTRUCT))
2815 nsrc->type = nsrc->type->type->type;
2816 argc = count(n->list) - 1;
2823 ns = temp(nsrc->type);
2824 l = list(l, nod(OAS, ns, nsrc)); // s = src
2826 na = nodintconst(argc); // const argc
2827 nx = nod(OIF, N, N); // if cap(s) - len(s) < argc
2828 nx->ntest = nod(OLT, nod(OSUB, nod(OCAP, ns, N), nod(OLEN, ns, N)), na);
2830 fn = syslook("growslice", 1); // growslice(<type>, old []T, n int64) (ret []T)
2831 argtype(fn, ns->type->type); // 1 old []any
2832 argtype(fn, ns->type->type); // 2 ret []any
2834 nx->nbody = list1(nod(OAS, ns, mkcall1(fn, ns->type, &nx->ninit,
2837 conv(na, types[TINT64]))));
2840 nn = temp(types[TINT]);
2841 l = list(l, nod(OAS, nn, nod(OLEN, ns, N))); // n = len(s)
2843 nx = nod(OSLICE, ns, nod(OKEY, N, nod(OADD, nn, na))); // ...s[:n+argc]
2845 l = list(l, nod(OAS, ns, nx)); // s = s[:n+argc]
2847 for (a = n->list->next; a != nil; a = a->next) {
2848 nx = nod(OINDEX, ns, nn); // s[n] ...
2850 l = list(l, nod(OAS, nx, a->n)); // s[n] = arg
2852 l = list(l, nod(OAS, nn, nod(OADD, nn, nodintconst(1)))); // n = n + 1
2855 typechecklist(l, Etop);
2857 *init = concat(*init, l);
2861 // Lower copy(a, b) to a memmove call or a runtime call.
2865 // if n > len(b) { n = len(b) }
2866 // memmove(a.ptr, b.ptr, n*sizeof(elem(a)))
2870 // Also works if b is a string.
2873 copyany(Node *n, NodeList **init, int runtimecall)
2875 Node *nl, *nr, *nfrm, *nto, *nif, *nlen, *nwid, *fn;
2879 if(n->right->type->etype == TSTRING)
2880 fn = syslook("slicestringcopy", 1);
2882 fn = syslook("slicecopy", 1);
2883 argtype(fn, n->left->type);
2884 argtype(fn, n->right->type);
2885 return mkcall1(fn, n->type, init,
2887 nodintconst(n->left->type->type->width));
2889 walkexpr(&n->left, init);
2890 walkexpr(&n->right, init);
2891 nl = temp(n->left->type);
2892 nr = temp(n->right->type);
2894 l = list(l, nod(OAS, nl, n->left));
2895 l = list(l, nod(OAS, nr, n->right));
2897 nfrm = nod(OSPTR, nr, N);
2898 nto = nod(OSPTR, nl, N);
2900 nlen = temp(types[TINT]);
2902 l = list(l, nod(OAS, nlen, nod(OLEN, nl, N)));
2903 // if n > len(frm) { n = len(frm) }
2904 nif = nod(OIF, N, N);
2905 nif->ntest = nod(OGT, nlen, nod(OLEN, nr, N));
2906 nif->nbody = list(nif->nbody,
2907 nod(OAS, nlen, nod(OLEN, nr, N)));
2911 fn = syslook("memmove", 1);
2912 argtype(fn, nl->type->type);
2913 argtype(fn, nl->type->type);
2914 nwid = temp(types[TUINTPTR]);
2915 l = list(l, nod(OAS, nwid, conv(nlen, types[TUINTPTR])));
2916 nwid = nod(OMUL, nwid, nodintconst(nl->type->type->width));
2917 l = list(l, mkcall1(fn, T, init, nto, nfrm, nwid));
2919 typechecklist(l, Etop);
2921 *init = concat(*init, l);
2925 // Generate frontend part for OSLICE[3][ARR|STR]
2928 sliceany(Node* n, NodeList **init)
2930 int bounded, slice3;
2931 Node *src, *lb, *hb, *cb, *bound, *chk, *chk0, *chk1, *chk2;
2932 int64 lbv, hbv, cbv, bv, w;
2935 // print("before sliceany: %+N\n", n);
2938 lb = n->right->left;
2939 slice3 = n->op == OSLICE3 || n->op == OSLICE3ARR;
2941 hb = n->right->right->left;
2942 cb = n->right->right->right;
2944 hb = n->right->right;
2950 if(n->op == OSLICESTR)
2951 bound = nod(OLEN, src, N);
2953 bound = nod(OCAP, src, N);
2955 typecheck(&bound, Erv);
2956 walkexpr(&bound, init); // if src is an array, bound will be a const now.
2958 // static checks if possible
2960 if(isconst(bound, CTINT)) {
2961 if(!smallintconst(bound))
2962 yyerror("array len too large");
2964 bv = mpgetfix(bound->val.u.xval);
2967 if(isconst(cb, CTINT)) {
2968 cbv = mpgetfix(cb->val.u.xval);
2969 if(cbv < 0 || cbv > bv)
2970 yyerror("slice index out of bounds");
2972 if(isconst(hb, CTINT)) {
2973 hbv = mpgetfix(hb->val.u.xval);
2974 if(hbv < 0 || hbv > bv)
2975 yyerror("slice index out of bounds");
2977 if(isconst(lb, CTINT)) {
2978 lbv = mpgetfix(lb->val.u.xval);
2979 if(lbv < 0 || lbv > bv) {
2980 yyerror("slice index out of bounds");
2987 // Checking src[lb:hb:cb] or src[lb:hb].
2988 // if chk0 || chk1 || chk2 { panicslice() }
2990 chk0 = N; // cap(src) < cb
2991 chk1 = N; // cb < hb for src[lb:hb:cb]; cap(src) < hb for src[lb:hb]
2992 chk2 = N; // hb < lb
2994 // All comparisons are unsigned to avoid testing < 0.
2995 bt = types[simtype[TUINT]];
2996 if(cb != N && cb->type->width > 4)
2997 bt = types[TUINT64];
2998 if(hb != N && hb->type->width > 4)
2999 bt = types[TUINT64];
3000 if(lb != N && lb->type->width > 4)
3001 bt = types[TUINT64];
3003 bound = cheapexpr(conv(bound, bt), init);
3006 cb = cheapexpr(conv(cb, bt), init);
3008 chk0 = nod(OLT, bound, cb);
3010 // When we figure out what this means, implement it.
3011 fatal("slice3 with cb == N"); // rejected by parser
3015 hb = cheapexpr(conv(hb, bt), init);
3018 chk1 = nod(OLT, cb, hb);
3020 chk1 = nod(OLT, bound, hb);
3023 // When we figure out what this means, implement it.
3024 fatal("slice3 with hb == N"); // rejected by parser
3025 } else if(n->op == OSLICEARR) {
3028 hb = nod(OLEN, src, N);
3029 typecheck(&hb, Erv);
3030 walkexpr(&hb, init);
3031 hb = cheapexpr(conv(hb, bt), init);
3035 lb = cheapexpr(conv(lb, bt), init);
3037 chk2 = nod(OLT, hb, lb);
3040 if(chk0 != N || chk1 != N || chk2 != N) {
3041 chk = nod(OIF, N, N);
3042 chk->nbody = list1(mkcall("panicslice", T, init));
3050 chk->ntest = nod(OOROR, chk->ntest, chk1);
3056 chk->ntest = nod(OOROR, chk->ntest, chk2);
3058 typecheck(&chk, Etop);
3060 *init = concat(*init, chk->ninit);
3062 *init = list(*init, chk);
3065 // prepare new cap, len and offs for backend cgen_slice
3066 // cap = bound [ - lo ]
3072 bound = conv(cb, types[simtype[TUINT]]);
3074 bound = nod(OSUB, conv(cb, types[simtype[TUINT]]), conv(lb, types[simtype[TUINT]]));
3075 typecheck(&bound, Erv);
3076 walkexpr(&bound, init);
3077 n->list = list(n->list, bound);
3081 hb = conv(hb, types[simtype[TUINT]]);
3083 hb = nod(OSUB, conv(hb, types[simtype[TUINT]]), conv(lb, types[simtype[TUINT]]));
3084 typecheck(&hb, Erv);
3085 walkexpr(&hb, init);
3086 n->list = list(n->list, hb);
3088 // offs = [width *] lo, but omit if zero
3090 if(n->op == OSLICESTR)
3093 w = n->type->type->width;
3094 lb = conv(lb, types[TUINTPTR]);
3096 lb = nod(OMUL, nodintconst(w), lb);
3097 typecheck(&lb, Erv);
3098 walkexpr(&lb, init);
3099 n->list = list(n->list, lb);
3102 // print("after sliceany: %+N\n", n);
3115 // Should only arrive here with large memory or
3116 // a struct/array containing a non-memory field/element.
3117 // Small memory is handled inline, and single non-memory
3118 // is handled during type check (OCMPSTR etc).
3119 a = algtype1(t, nil);
3120 if(a != AMEM && a != -1)
3121 fatal("eqfor %T", t);
3124 n = syslook("memequal", 1);
3130 sym = typesymprefix(".eq", t);
3133 ntype = nod(OTFUNC, N, N);
3134 ntype->list = list(ntype->list, nod(ODCLFIELD, N, typenod(ptrto(t))));
3135 ntype->list = list(ntype->list, nod(ODCLFIELD, N, typenod(ptrto(t))));
3136 ntype->list = list(ntype->list, nod(ODCLFIELD, N, typenod(types[TUINTPTR])));
3137 ntype->rlist = list(ntype->rlist, nod(ODCLFIELD, N, typenod(types[TBOOL])));
3138 typecheck(&ntype, Etype);
3139 n->type = ntype->type;
3150 for(t1=t->type; t1!=T; t1=t1->down)
3156 walkcompare(Node **np, NodeList **init)
3158 Node *n, *l, *r, *call, *a, *li, *ri, *expr, *cmpl, *cmpr;
3164 // Must be comparison of array or struct.
3165 // Otherwise back end handles it.
3179 while(cmpl != N && cmpl->op == OCONVNOP)
3182 while(cmpr != N && cmpr->op == OCONVNOP)
3185 if(!islvalue(cmpl) || !islvalue(cmpr)) {
3186 fatal("arguments of comparison must be lvalues - %N %N", cmpl, cmpr);
3190 a = nod(OAS, l, nod(OADDR, cmpl, N));
3191 a->right->etype = 1; // addr does not escape
3192 typecheck(&a, Etop);
3193 *init = list(*init, a);
3196 a = nod(OAS, r, nod(OADDR, cmpr, N));
3197 a->right->etype = 1; // addr does not escape
3198 typecheck(&a, Etop);
3199 *init = list(*init, a);
3206 if(t->etype == TARRAY &&
3208 issimple[t->type->etype]) {
3209 // Four or fewer elements of a basic type.
3210 // Unroll comparisons.
3211 for(i=0; i<t->bound; i++) {
3212 li = nod(OINDEX, l, nodintconst(i));
3213 ri = nod(OINDEX, r, nodintconst(i));
3214 a = nod(n->op, li, ri);
3218 expr = nod(andor, expr, a);
3221 expr = nodbool(n->op == OEQ);
3226 if(t->etype == TSTRUCT && countfield(t) <= 4) {
3227 // Struct of four or fewer fields.
3228 // Inline comparisons.
3229 for(t1=t->type; t1; t1=t1->down) {
3230 if(isblanksym(t1->sym))
3232 li = nod(OXDOT, l, newname(t1->sym));
3233 ri = nod(OXDOT, r, newname(t1->sym));
3234 a = nod(n->op, li, ri);
3238 expr = nod(andor, expr, a);
3241 expr = nodbool(n->op == OEQ);
3246 // Chose not to inline. Call equality function directly.
3247 call = nod(OCALL, eqfor(t), N);
3248 call->list = list(call->list, l);
3249 call->list = list(call->list, r);
3250 call->list = list(call->list, nodintconst(t->width));
3253 r = nod(ONOT, r, N);
3259 if(r->type != n->type) {
3260 r = nod(OCONVNOP, r, N);
3269 samecheap(Node *a, Node *b)
3272 while(a != N && b != N && a->op == b->op) {
3282 if(ar->op != ONAME || br->op != ONAME || ar->sym != br->sym)
3288 if(!isconst(ar, CTINT) || !isconst(br, CTINT) || mpcmpfixfix(ar->val.u.xval, br->val.u.xval) != 0)
3299 walkrotate(Node **np)
3310 // Want << | >> or >> | << or << ^ >> or >> ^ << on unsigned value.
3313 if((n->op != OOR && n->op != OXOR) ||
3314 (l->op != OLSH && l->op != ORSH) ||
3315 (r->op != OLSH && r->op != ORSH) ||
3316 n->type == T || issigned[n->type->etype] ||
3321 // Want same, side effect-free expression on lhs of both shifts.
3322 if(!samecheap(l->left, r->left))
3325 // Constants adding to width?
3326 w = l->type->width * 8;
3327 if(smallintconst(l->right) && smallintconst(r->right)) {
3328 if((sl=mpgetfix(l->right->val.u.xval)) >= 0 && (sr=mpgetfix(r->right->val.u.xval)) >= 0 && sl+sr == w)
3333 // TODO: Could allow s and 32-s if s is bounded (maybe s&31 and 32-s&31).
3337 // Rewrite left shift half to left rotate.
3344 // Remove rotate 0 and rotate w.
3345 s = mpgetfix(n->right->val.u.xval);
3346 if(s == 0 || s == w)
3354 * walkmul rewrites integer multiplication by powers of two as shifts.
3357 walkmul(Node **np, NodeList **init)
3363 if(!isint[n->type->etype])
3366 if(n->right->op == OLITERAL) {
3369 } else if(n->left->op == OLITERAL) {
3377 // x*0 is 0 (and side effects of x).
3378 if(mpgetfix(nr->val.u.xval) == 0) {
3379 cheapexpr(nl, init);
3380 nodconst(n, n->type, 0);
3384 // nr is a constant.
3389 // negative power of 2, like -16
3394 w = nl->type->width*8;
3395 if(pow+1 >= w)// too big, shouldn't happen
3398 nl = cheapexpr(nl, init);
3406 n = nod(OLSH, nl, nodintconst(pow));
3410 n = nod(OMINUS, n, N);
3418 * walkdiv rewrites division by a constant as less expensive
3422 walkdiv(Node **np, NodeList **init)
3424 Node *n, *nl, *nr, *nc;
3425 Node *n1, *n2, *n3, *n4;
3426 int pow; // if >= 0, nr is 1<<pow
3427 int s; // 1 if nr is negative.
3437 if(n->right->op != OLITERAL)
3439 // nr is a constant.
3440 nl = cheapexpr(n->left, init);
3443 // special cases of mod/div
3445 w = nl->type->width*8;
3449 // negative power of 2
3455 // divisor too large.
3466 nodconst(n, n->type, 0);
3477 if(issigned[n->type->etype]) {
3479 // signed modulo 2^pow is like ANDing
3480 // with the last pow bits, but if nl < 0,
3481 // nl & (2^pow-1) is (nl+1)%2^pow - 1.
3482 nc = nod(OXXX, N, N);
3483 nodconst(nc, types[simtype[TUINT]], w-1);
3484 n1 = nod(ORSH, nl, nc); // n1 = -1 iff nl < 0.
3486 typecheck(&n1, Erv);
3487 n1 = cheapexpr(n1, init);
3488 // n = (nl+ε)&1 -ε where ε=1 iff nl<0.
3489 n2 = nod(OSUB, nl, n1);
3490 nc = nod(OXXX, N, N);
3491 nodconst(nc, nl->type, 1);
3492 n3 = nod(OAND, n2, nc);
3493 n = nod(OADD, n3, n1);
3495 // n = (nl+ε)&(nr-1) - ε where ε=2^pow-1 iff nl<0.
3496 nc = nod(OXXX, N, N);
3497 nodconst(nc, nl->type, (1LL<<pow)-1);
3498 n2 = nod(OAND, n1, nc); // n2 = 2^pow-1 iff nl<0.
3499 typecheck(&n2, Erv);
3500 n2 = cheapexpr(n2, init);
3502 n3 = nod(OADD, nl, n2);
3503 n4 = nod(OAND, n3, nc);
3504 n = nod(OSUB, n4, n2);
3508 // arithmetic right shift does not give the correct rounding.
3509 // if nl >= 0, nl >> n == nl / nr
3510 // if nl < 0, we want to add 2^n-1 first.
3511 nc = nod(OXXX, N, N);
3512 nodconst(nc, types[simtype[TUINT]], w-1);
3513 n1 = nod(ORSH, nl, nc); // n1 = -1 iff nl < 0.
3516 n->left = nod(OSUB, nl, n1);
3518 // Do a logical right right on -1 to keep pow bits.
3519 nc = nod(OXXX, N, N);
3520 nodconst(nc, types[simtype[TUINT]], w-pow);
3521 n2 = nod(ORSH, conv(n1, tounsigned(nl->type)), nc);
3522 n->left = nod(OADD, nl, conv(n2, nl->type));
3524 // n = (nl + 2^pow-1) >> pow
3526 nc = nod(OXXX, N, N);
3527 nodconst(nc, types[simtype[TUINT]], pow);
3532 n = nod(OMINUS, n, N);
3535 nc = nod(OXXX, N, N);
3539 nodconst(nc, nl->type, mpgetfix(nr->val.u.xval)-1);
3543 nodconst(nc, types[simtype[TUINT]], pow);
3552 // try to do division by multiply by (2^w)/d
3553 // see hacker's delight chapter 10
3554 // TODO: support 64-bit magic multiply here.
3556 if(issigned[nl->type->etype]) {
3557 m.sd = mpgetfix(nr->val.u.xval);
3560 m.ud = mpgetfix(nr->val.u.xval);
3566 // We have a quick division method so use it
3571 switch(simtype[nl->type->etype]) {
3578 // n1 = nl * magic >> w (HMUL)
3579 nc = nod(OXXX, N, N);
3580 nodconst(nc, nl->type, m.um);
3581 n1 = nod(OMUL, nl, nc);
3582 typecheck(&n1, Erv);
3585 // Select a Go type with (at least) twice the width.
3586 switch(simtype[nl->type->etype]) {
3591 twide = types[TUINT32];
3594 twide = types[TUINT64];
3598 twide = types[TINT32];
3601 twide = types[TINT64];
3605 // add numerator (might overflow).
3607 n2 = nod(OADD, conv(n1, twide), conv(nl, twide));
3610 nc = nod(OXXX, N, N);
3611 nodconst(nc, types[TUINT], m.s);
3612 n = conv(nod(ORSH, n2, nc), nl->type);
3615 nc = nod(OXXX, N, N);
3616 nodconst(nc, types[TUINT], m.s);
3617 n = nod(ORSH, n1, nc);
3624 // n1 = nl * magic >> w
3625 nc = nod(OXXX, N, N);
3626 nodconst(nc, nl->type, m.sm);
3627 n1 = nod(OMUL, nl, nc);
3628 typecheck(&n1, Erv);
3631 // add the numerator.
3632 n1 = nod(OADD, n1, nl);
3635 nc = nod(OXXX, N, N);
3636 nodconst(nc, types[TUINT], m.s);
3637 n2 = conv(nod(ORSH, n1, nc), nl->type);
3638 // add 1 iff n1 is negative.
3639 nc = nod(OXXX, N, N);
3640 nodconst(nc, types[TUINT], w-1);
3641 n3 = nod(ORSH, nl, nc); // n4 = -1 iff n1 is negative.
3642 n = nod(OSUB, n2, n3);
3645 n = nod(OMINUS, n, N);
3651 // rewrite as A%B = A - (A/B*B).
3652 n1 = nod(ODIV, nl, nr);
3653 n2 = nod(OMUL, n1, nr);
3654 n = nod(OSUB, nl, n2);
3663 // return 1 if integer n must be in range [0, max), 0 otherwise
3665 bounded(Node *n, int64 max)
3671 if(n->type == T || !isint[n->type->etype])
3674 sign = issigned[n->type->etype];
3675 bits = 8*n->type->width;
3677 if(smallintconst(n)) {
3678 v = mpgetfix(n->val.u.xval);
3679 return 0 <= v && v < max;
3685 if(smallintconst(n->left)) {
3686 v = mpgetfix(n->left->val.u.xval);
3687 } else if(smallintconst(n->right)) {
3688 v = mpgetfix(n->right->val.u.xval);
3690 if(0 <= v && v < max)
3695 if(!sign && smallintconst(n->right)) {
3696 v = mpgetfix(n->right->val.u.xval);
3697 if(0 <= v && v <= max)
3703 if(!sign && smallintconst(n->right)) {
3704 v = mpgetfix(n->right->val.u.xval);
3705 while(bits > 0 && v >= 2) {
3713 if(!sign && smallintconst(n->right)) {
3714 v = mpgetfix(n->right->val.u.xval);
3722 if(!sign && bits <= 62 && (1LL<<bits) <= max)
3733 if(!fieldtrack_enabled)
3738 fatal("usefield %O", n->op);
3744 field = n->paramfld;
3746 fatal("usefield %T %S without paramfld", n->left->type, n->right->sym);
3747 if(field->note == nil || strstr(field->note->s, "go:\"track\"") == nil)
3751 if(field->lastfn == curfn)
3753 field->lastfn = curfn;
3754 field->outer = n->left->type;
3755 if(isptr[field->outer->etype])
3756 field->outer = field->outer->type;
3757 if(field->outer->sym == S)
3758 yyerror("tracked field must be in named struct type");
3759 if(!exportname(field->sym->name))
3760 yyerror("tracked field must be exported (upper case)");
3764 l->down = curfn->paramfld;
3765 curfn->paramfld = l;
3769 candiscardlist(NodeList *l)
3772 if(!candiscard(l->n))
3839 // Discardable as long as the subpieces are.
3844 // Discardable as long as we know it's not division by zero.
3845 if(isconst(n->right, CTINT) && mpcmpfixc(n->right->val.u.xval, 0) != 0)
3847 if(isconst(n->right, CTFLT) && mpcmpfltc(n->right->val.u.fval, 0) != 0)
3853 // Discardable as long as we know it won't fail because of a bad size.
3854 if(isconst(n->left, CTINT) && mpcmpfixc(n->left->val.u.xval, 0) == 0)
3859 // Difficult to tell what sizes are okay.
3863 if(!candiscard(n->left) ||
3864 !candiscard(n->right) ||
3865 !candiscard(n->ntest) ||
3866 !candiscard(n->nincr) ||
3867 !candiscardlist(n->ninit) ||
3868 !candiscardlist(n->nbody) ||
3869 !candiscardlist(n->nelse) ||
3870 !candiscardlist(n->list) ||
3871 !candiscardlist(n->rlist)) {
3881 // func(a1, a2, a3) {
3882 // print(a1, a2, a3)
3884 // and same for println.
3886 walkprintfunc(Node **np, NodeList **init)
3889 Node *a, *fn, *t, *oldfn;
3890 NodeList *l, *printargs;
3897 if(n->ninit != nil) {
3898 walkstmtlist(n->ninit);
3899 *init = concat(*init, n->ninit);
3903 t = nod(OTFUNC, N, N);
3906 for(l=n->list; l != nil; l=l->next) {
3907 snprint(buf, sizeof buf, "a%d", num++);
3908 a = nod(ODCLFIELD, newname(lookup(buf)), typenod(l->n->type));
3909 t->list = list(t->list, a);
3910 printargs = list(printargs, a->left);
3913 fn = nod(ODCLFUNC, N, N);
3914 snprint(buf, sizeof buf, "print·%d", ++prgen);
3915 fn->nname = newname(lookup(buf));
3916 fn->nname->defn = fn;
3917 fn->nname->ntype = t;
3918 declare(fn->nname, PFUNC);
3924 a = nod(n->op, N, N);
3925 a->list = printargs;
3926 typecheck(&a, Etop);
3929 fn->nbody = list1(a);
3933 typecheck(&fn, Etop);
3934 typechecklist(fn->nbody, Etop);
3935 xtop = list(xtop, fn);
3938 a = nod(OCALL, N, N);
3939 a->left = fn->nname;
3941 typecheck(&a, Etop);