Commit 8a70545b authored by Ken Thompson's avatar Ken Thompson

unsafe.Sizeof and unsafe.Offsetof

R=r
OCL=24639
CL=24639
parent bcf48076
...@@ -1483,3 +1483,54 @@ loop: ...@@ -1483,3 +1483,54 @@ loop:
c = listnext(&citer); c = listnext(&citer);
goto loop; goto loop;
} }
/*
* look for
* unsafe.Sizeof
* unsafe.Offsetof
* rewrite with a constant
*/
Node*
unsafenmagic(Node *l, Node *r)
{
Node *n;
Sym *s;
long v;
Val val;
if(l == N || r == N)
goto no;
if(l->op != ONAME)
goto no;
s = l->sym;
if(s == S)
goto no;
if(strcmp(s->opackage, "unsafe") != 0)
goto no;
if(strcmp(s->name, "Sizeof") == 0) {
walktype(r, Erv);
if(r->type == T)
goto no;
v = r->type->width;
goto yes;
}
if(strcmp(s->name, "Offsetof") == 0) {
if(r->op != ODOT && r->op != ODOTPTR)
goto no;
walktype(r, Erv);
v = n->xoffset;
goto yes;
}
no:
return N;
yes:
val.ctype = CTINT;
val.u.xval = mal(sizeof(*n->val.u.xval));
mpmovecfix(val.u.xval, v);
n = nod(OLITERAL, N, N);
n->val = val;
return n;
}
...@@ -763,6 +763,7 @@ void constiter(Node*, Type*, Node*); ...@@ -763,6 +763,7 @@ void constiter(Node*, Type*, Node*);
void funclit0(Type*); void funclit0(Type*);
Node* funclit1(Type*, Node*); Node* funclit1(Type*, Node*);
Node* unsafenmagic(Node*, Node*);
/* /*
* export.c * export.c
......
...@@ -804,6 +804,8 @@ pexpr: ...@@ -804,6 +804,8 @@ pexpr:
} }
| pexpr '(' oexpr_list ')' | pexpr '(' oexpr_list ')'
{ {
$$ = unsafenmagic($1, $3);
if($$ == N)
$$ = nod(OCALL, $1, $3); $$ = nod(OCALL, $1, $3);
} }
| LLEN '(' expr ')' | LLEN '(' expr ')'
......
...@@ -6,3 +6,5 @@ ...@@ -6,3 +6,5 @@
package PACKAGE package PACKAGE
type Pointer *any; type Pointer *any;
func Offsetof(any) int;
func Sizeof(any) int;
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment