]> Cypherpunks repositories - gostls13.git/commitdiff
gc: compile s == "" as len(s) == 0
authorRuss Cox <rsc@golang.org>
Sun, 11 Apr 2010 22:24:44 +0000 (15:24 -0700)
committerRuss Cox <rsc@golang.org>
Sun, 11 Apr 2010 22:24:44 +0000 (15:24 -0700)
R=ken2
CC=golang-dev
https://golang.org/cl/840043

src/cmd/gc/walk.c

index ced798e6ba182f8b3c784b1cf8a50692cb4d11a2..34ac32436b79512d37b7e494341e99a90200deeb 100644 (file)
@@ -1053,6 +1053,30 @@ walkexpr(Node **np, NodeList **init)
                goto ret;
 
        case OCMPSTR:
+               // If one argument to the comparison is an empty string,
+               // comparing the lengths instead will yield the same result
+               // without the function call.
+               if((isconst(n->left, CTSTR) && n->left->val.u.sval->len == 0) ||
+                  (isconst(n->right, CTSTR) && n->right->val.u.sval->len == 0)) {
+                       r = nod(n->etype, nod(OLEN, n->left, N), nod(OLEN, n->right, N));
+                       typecheck(&r, Erv);
+                       walkexpr(&r, init);
+                       n = r;
+                       goto ret;
+               }
+
+               // s + "badgerbadgerbadger" == "badgerbadgerbadger"
+               if((n->etype == OEQ || n->etype == ONE) &&
+                  isconst(n->right, CTSTR) &&
+                  n->left->op == OADDSTR && isconst(n->left->right, CTSTR) &&
+                  cmpslit(n->right, n->left->right) == 0) {
+                       r = nod(n->etype, nod(OLEN, n->left->left, N), nodintconst(0));
+                       typecheck(&r, Erv);
+                       walkexpr(&r, init);
+                       n = r;
+                       goto ret;
+               }
+
                // sys_cmpstring(s1, s2) :: 0
                r = mkcall("cmpstring", types[TINT], init,
                        conv(n->left, types[TSTRING]),