src/BytecodeCompiler.cpp
author David Anderson <dvander@alliedmods.net>
Sat Aug 04 21:23:39 2012 -0700 (2012-08-04)
changeset 150 457110815c87
parent 149 b01ee7446984
child 151 bb419abf0df4
permissions -rw-r--r--
Treat IndexExpression's type field similar to a FieldExpression.
     1 /* vim: set ts=4 sw=4 tw=99 et:
     2  *
     3  * Copyright (C) 2012 David Anderson
     4  *
     5  * This file is part of JITCraft.
     6  *
     7  * JITCraft is free software: you can redistribute it and/or modify it under
     8  * the terms of the GNU General Public License as published by the Free
     9  * Software Foundation, either version 3 of the License, or (at your option)
    10  * any later version.
    11  * 
    12  * Foobar is distributed in the hope that it will be useful, but WITHOUT ANY
    13  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
    14  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
    15  *
    16  * You should have received a copy of the GNU General Public License along with
    17  * JITCraft. If not, see http://www.gnu.org/licenses/.
    18  */
    19 #include <string.h>
    20 #include "BytecodeCompiler.h"
    21 #include "Scopes.h"
    22 #include "Modules.h"
    23 #include "Types.h"
    24 #include "Array.h"
    25 #include "Strings.h"
    26 #include "Zone.h"
    27 #include "Environments.h"
    28 #include "Heap-inl.h"
    29 
    30 using namespace ke;
    31 
    32 typedef BytecodeEmitter::Label Label;
    33 
    34 #define __ emitter_.
    35 
    36 BytecodeCompiler::BytecodeCompiler(Zone *zone, ParseTree *tree, ModuleData *module)
    37   : zone_(zone),
    38     tree_(tree),
    39     emitter_(zone->pool()),
    40     locals_(NULL),
    41     scope_(NULL),
    42     moduleData_(module),
    43     loop_(NULL)
    44 {
    45 }
    46 
    47 static inline TokenKind
    48 ToCompare(Expression *expr)
    49 {
    50     if (expr->isBinaryExpression()) {
    51         BinaryExpression *b = expr->toBinaryExpression();
    52         if (b->token() >= TOK_EQUALS && b->token() <= TOK_OR)
    53             return b->token();
    54     } else if (expr->isUnaryExpression()) {
    55         UnaryExpression *u = expr->toUnaryExpression();
    56         if (u->token() == TOK_NOT)
    57             return TOK_NOT;
    58     }
    59     return TOK_EOF;
    60 }
    61 
    62 static inline Opcode
    63 CompareTokenToJump(TokenKind kind)
    64 {
    65     switch (kind) {
    66       case TOK_EQUALS:
    67         return OP_JEQ;
    68       case TOK_NOTEQUALS:
    69         return OP_JNE;
    70       case TOK_GT:
    71         return OP_JG;
    72       case TOK_GE:
    73         return OP_JGE;
    74       case TOK_LT:
    75         return OP_JL;
    76       default:
    77         assert(kind == TOK_LE);
    78         return OP_JLE;
    79     }
    80 }
    81 
    82 static inline Opcode
    83 TokenToOpcode(TokenKind kind)
    84 {
    85     switch (kind) {
    86       case TOK_PLUS:
    87         return OP_ADD;
    88       case TOK_MINUS:
    89         return OP_SUB;
    90       case TOK_STAR:
    91         return OP_MUL;
    92       case TOK_SLASH:
    93         return OP_DIV;
    94       case TOK_PERCENT:
    95         return OP_MOD;
    96       case TOK_SHR:
    97         return OP_SHR;
    98       case TOK_USHR:
    99         return OP_USHR;
   100       case TOK_SHL:
   101         return OP_SHL;
   102       case TOK_BITAND:
   103         return OP_BITAND;
   104       case TOK_BITOR:
   105         return OP_BITOR;
   106       case TOK_GT:
   107           return OP_GT;
   108       case TOK_GE:
   109           return OP_GE;
   110       case TOK_LT:
   111           return OP_LT;
   112       case TOK_LE:
   113           return OP_LE;
   114       case TOK_EQUALS:
   115           return OP_EQ;
   116       case TOK_NOTEQUALS:
   117           return OP_NE;
   118       default:
   119         assert(kind == TOK_BITXOR);
   120         return OP_BITXOR;
   121     }
   122 }
   123 
   124 void
   125 BytecodeCompiler::recordLifoSlot(Scope *scope)
   126 {
   127     if (!scope)
   128         return;
   129 
   130     if (Variable *var = scope->lifoSlot()) {
   131         locals_->set(zone_, var->slot(), var->type());
   132         __ savelifo(var->slot());
   133     }
   134 }
   135 
   136 void
   137 BytecodeCompiler::unwindTo(Scope *scope)
   138 {
   139     // Note: we only need to unwind to the outermost scope's LIFO slot.
   140     Variable *var = NULL;
   141     for (Scope *current = scope_; current != scope; current = current->enclosing()) {
   142         if (Variable *slot = current->lifoSlot())
   143             var = slot;
   144     }
   145 
   146     if (var)
   147         __ unwindlifo(var->slot());
   148 }
   149 
   150 void
   151 BytecodeCompiler::visit(NameProxy *name)
   152 {
   153     switch (name->binding()->kind()) {
   154       case BoundName::VARIABLE:
   155       {
   156         Variable *var = name->binding()->toVariable();
   157 
   158         if (var->location() == Variable::STACK) {
   159             __ getlocal(var);
   160             assert(!name->type()->isReference());
   161         } else if (var->location() == Variable::ENVIRONMENT) {
   162             getEnvSlot(var);
   163         } else {
   164             assert(var->location() == Variable::PARAMETER);
   165             __ getarg(var);
   166 
   167             // If this argument is actually a reference, dereference it now.
   168             if (var->type()->isReference())
   169                 __ getref(var->type()->contained());
   170         }
   171         break;
   172       }
   173 
   174       case BoundName::FUNCTION:
   175       {
   176         NamedFunction *fun = name->binding()->toNamedFunction();
   177         __ module();
   178         __ getmodule_fn(fun->slot());
   179         break;
   180       }
   181 
   182       default:
   183       {
   184         NamedConstant *constant = name->binding()->toNamedConstant();
   185         __ int_(constant->value().toInt());
   186         break;
   187       }
   188     }
   189 }
   190 
   191 void
   192 BytecodeCompiler::visit(ExpressionStatement *node)
   193 {
   194     // Expressions leave their value on the top of the stack, so we make sure
   195     // to balance the stack if they're used as a statement.
   196     node->expression()->accept(this);
   197     if (!node->expression()->type()->isVoid())
   198         __ pop();
   199 }
   200 
   201 void
   202 BytecodeCompiler::visit(Assignment *node)
   203 {
   204     // The first step is three sub-steps:
   205     //
   206     //   (1) Bind the left-hand side.
   207     //   -- If a cumulative operation (+=, etc):
   208     //   (2) Save a copy of the binding on the stack.
   209     //   (3) Dereference the binding to get a value.
   210     //
   211     if (node->lvalue()->isNameProxy()) {
   212         NameProxy *proxy = node->lvalue()->toNameProxy();
   213         Variable *var = proxy->binding()->toVariable();
   214 
   215         // Bind.
   216         if (var->type()->isReference() || var->type()->isArray())
   217             __ get(var);
   218 
   219         // Get the value if needed.
   220         if (node->token() != TOK_ASSIGN) {
   221             // += etc is not allowed on arrays.
   222             assert(!var->type()->isArray());
   223 
   224             if (var->type()->isReference()) {
   225                 __ dup();
   226                 __ getref(var->type()->contained());
   227             } else {
   228                 __ get(var);
   229             }
   230         }
   231     } else if (node->lvalue()->isFieldExpression()) {
   232         FieldExpression *expr = node->lvalue()->toFieldExpression();
   233         __ note_position(expr->pos());
   234 
   235         expr->left()->accept(this);
   236 
   237         if (node->token() != TOK_ASSIGN) {
   238             __ dup();
   239             __ getfield(expr->fieldIndex(), expr->type());
   240         }
   241     } else {
   242         IndexExpression *index = node->lvalue()->toIndexExpression();
   243         __ note_position(index->pos());
   244 
   245         // Note: Eventually, watch out for a whole here. An expression like:
   246         //
   247         //   (a[4] = (5, a = []))
   248         //
   249         // Could shrink array, so we need to either bind a[i] to a Reference,
   250         // or keep the bounds check near the set. This is just a semantic
   251         // decision.
   252         index->left()->accept(this);
   253         index->right()->accept(this);
   254 
   255         if (node->token() != TOK_ASSIGN) {
   256             __ dup2();
   257             __ bounds();
   258             if (node->type()->isArray())
   259                 __ getarray_o();
   260             else
   261                 __ getarray(node->type());
   262         }
   263     }
   264 
   265     if (node->token() == TOK_ASSIGN) {
   266         node->expression()->accept(this);
   267     } else {
   268         visitForALU(node->type(), node->expression());
   269 
   270         TokenKind alu = TokenKind(int(node->token()) - (TOK_ASSIGN_ADD - TOK_PLUS));
   271         __ note_position(node->pos());
   272         __ binary(TokenToOpcode(alu));
   273     }
   274 
   275     // Emit the store.
   276     if (node->expression()->type()->isArray()) {
   277         // Unlike references, which can only be computed from a NamePRoxy,
   278         // arrays can be computed from multiple lvalue types.
   279         __ note_position(node->pos());
   280         __ arraycopy();
   281     } else if (node->lvalue()->isNameProxy()) {
   282         NameProxy *proxy = node->lvalue()->toNameProxy();
   283         Variable *var = proxy->binding()->toVariable();
   284 
   285         if (var->type()->isReference())
   286             __ setref(var->type()->contained());
   287         else
   288             __ set(var);
   289     } else if (node->lvalue()->isFieldExpression()) {
   290         FieldExpression *expr = node->lvalue()->toFieldExpression();
   291         __ setfield(expr->fieldIndex(), expr->type());
   292     } else {
   293         IndexExpression *index = node->lvalue()->toIndexExpression();
   294         // :TODO: get rid of the BOUNDS instruction, embed it in g/setarray*?
   295         // We can't emit it here because the stack is slightly out of position.
   296         // __ bounds();
   297         __ setarray(index->left()->type());
   298     }
   299 }
   300 
   301 void
   302 BytecodeCompiler::visit(IncDecExpression *node)
   303 {
   304     // In the postfix case, the logic looks like:
   305     //      (1) Bind       -> REF
   306     //      (2) Dup        -> REF REF
   307     //      (3) Fetch      -> REF VAL
   308     //      (4) Swap       -> VAL REF
   309     //      (5) Pick       -> VAL REF VAL
   310     //      (6) Add        -> VAL REF VAL+1
   311     //      (7) Store      -> VAL VAL+1
   312     //      (8) Drop       -> VAL
   313     //
   314     // In the prefix case, the logic looks like:
   315     //      (1) Bind       -> REF
   316     //      (2) Dup        -> REF REF
   317     //      (3) Fetch      -> REF VAL
   318     //      --
   319     //      --
   320     //      (6) Add        -> REF VAL+1
   321     //      (7) Store      -> VAL+1
   322     //      --
   323     //
   324     // This is squirrely enough such that we don't bother sharing too much
   325     // with the above.
   326     // 
   327     // Note: We simulate a "Pick" operation with a dup2+pop.
   328 
   329     // This is steps (1) to (5).
   330     Expression *expr = node->expression();
   331     if (expr->isNameProxy()) {
   332         NameProxy *proxy = expr->toNameProxy();
   333         Variable *var = proxy->binding()->toVariable();
   334 
   335         // Bind.
   336         if (var->type()->isReference() || var->type()->isArray())
   337             __ get(var);
   338 
   339         // Dup and fetch.
   340         if (var->type()->isReference()) {
   341             __ dup();
   342             __ getref(node->type());
   343             if (node->postfix()) {
   344                 __ swap();
   345                 __ pick2();
   346             }
   347         } else {
   348             assert(!var->type()->isArray());
   349             __ get(var);
   350             if (node->postfix())
   351                 __ dup();
   352         }
   353     } else if (expr->isFieldExpression()) {
   354         FieldExpression *field = expr->toFieldExpression();
   355 
   356         field->left()->accept(this);
   357         __ dup();
   358         __ getfield(field->fieldIndex(), field->type());
   359 
   360         if (node->postfix()) {
   361             // The stack looks like this now:
   362             // OBJECT VALUE
   363             __ swap();          // VALUE OBJECT
   364             __ pick2();         // VALUE OBJECT VALUE
   365         }
   366     } else {
   367         IndexExpression *index = expr->toIndexExpression();
   368         __ note_position(index->pos());
   369 
   370         index->left()->accept(this);
   371         index->right()->accept(this);
   372 
   373         assert(!node->type()->isArray());
   374         __ bounds();
   375         __ dup2();
   376         __ getarray(node->type());
   377 
   378         if (node->postfix()) {
   379             // The stack looks like this now:
   380             // ARRAY INDEX VALUE
   381             //
   382             // So we must use a PICK operation to rotate the stack into position.
   383             __ roll3();         // INDEX VALUE ARRAY
   384             __ roll3();         // VALUE ARRAY INDEX
   385             __ pick3();         // VALUE ARRAY INDEX VALUE
   386         }
   387     }
   388 
   389     // Perform step (6).
   390     if (node->type()->isFloat()) {
   391         __ float_(1.0);
   392     } else {
   393         assert(node->type()->isInt32());
   394         __ int_(1);
   395     }
   396 
   397     __ note_position(node->pos());
   398     if (node->token() == TOK_INCREMENT)
   399         __ binary(OP_ADD);
   400     else
   401         __ binary(OP_SUB);
   402 
   403     // Perform step (7).
   404     if (expr->isNameProxy()) {
   405         NameProxy *proxy = expr->toNameProxy();
   406         Variable *var = proxy->binding()->toVariable();
   407 
   408         if (var->type()->isReference())
   409             __ setref(node->type());
   410         else
   411             __ set(var);
   412     } else if (expr->isFieldExpression()) {
   413         FieldExpression *field = expr->toFieldExpression();
   414         __ setfield(field->fieldIndex(), field->type());
   415     } else {
   416         assert(expr->isIndexExpression());
   417         __ setarray(node->type());
   418     }
   419 
   420     // Perform step (8).
   421     if (node->postfix())
   422         __ pop();
   423 }
   424 
   425 void
   426 BytecodeCompiler::visitForALU(Type *needed, Expression *node)
   427 {
   428     node->accept(this);
   429     if (needed->isFloat() && !node->type()->isFloat())
   430         __ cvt_i2f();
   431     else
   432         assert(needed->primitive() == node->type()->primitive());
   433 }
   434 
   435 static inline Type *
   436 GetCoercionType(TokenKind tok, Type *left, Type *right)
   437 {
   438     if (left->isFloat())
   439         return left;
   440     return right;
   441 }
   442 
   443 void
   444 BytecodeCompiler::visit(UnaryExpression *node)
   445 {
   446     Local<Type> out(zone_, ((Expression *)node)->type());
   447 
   448     switch (node->token()) {
   449       case TOK_MINUS:
   450       {
   451         Local<Type> type(zone_, node->expression()->type());
   452         node->expression()->accept(this);
   453         
   454         if (out->isFloat())
   455             __ neg_f();
   456         else
   457             __ neg();
   458         break;
   459       }
   460 
   461       case TOK_NOT:
   462       {
   463         Local<Type> type(zone_, node->expression()->type());
   464         node->expression()->accept(this);
   465         
   466         if (out->isFloat())
   467             __ not_f();
   468         else
   469             __ not_();
   470         break;
   471       }
   472 
   473       case TOK_LABEL:
   474       {
   475         Local<Type> from(zone_, node->expression()->type());
   476 
   477         node->expression()->accept(this);
   478         if (!from->isFloat() && out->isFloat())
   479             __ bits_f2i();
   480         else if (from->isFloat() && !out->isFloat())
   481             __ bits_i2f();
   482         break;
   483       }
   484 
   485       default:
   486         assert(node->token() == TOK_TILDE);
   487         node->expression()->accept(this);
   488         __ bitnot();
   489         break;
   490     }
   491 }
   492 
   493 void
   494 BytecodeCompiler::visit(BinaryExpression *node)
   495 {
   496     if (node->token() == TOK_AND || node->token() == TOK_OR) {
   497         Label success, failure, done;
   498         visitForTest(node, &success, &failure, &success);
   499         __ bind(&success);
   500         __ int_(1);
   501         __ drop(1);         // Otherwise, the stack depth will be +1 too much.
   502         __ jump(&done);
   503         __ bind(&failure);
   504         __ int_(0);
   505         __ bind(&done);
   506         return;
   507     }
   508 
   509     Local<Type> leftType(zone_, node->left()->type());
   510     Local<Type> rightType(zone_, node->right()->type());
   511     Local<Type> coerce(zone_, GetCoercionType(node->token(), leftType, rightType));
   512 
   513     visitForALU(coerce, node->left());
   514     visitForALU(coerce, node->right());
   515 
   516     Opcode op = TokenToOpcode(node->token());
   517     if (node->type()->isFloat())
   518         op = (Opcode)(int(op) + (OP_ADD_F - OP_ADD));
   519 
   520     __ note_position(node->pos());
   521     __ binary(op);
   522 }
   523 
   524 void
   525 BytecodeCompiler::visit(IndexExpression *node)
   526 {
   527     node->left()->accept(this);
   528     node->right()->accept(this);
   529     __ note_position(node->pos());
   530     __ bounds();
   531 
   532     if (node->type()->isArray())
   533         __ getarray_o();
   534     else
   535         __ getarray(node->type());
   536 }
   537 
   538 void
   539 BytecodeCompiler::visit(FieldExpression *node)
   540 {
   541     node->left()->accept(this);
   542     __ getfield(node->fieldIndex(), node->type());
   543 }
   544 
   545 void
   546 BytecodeCompiler::visit(ReturnStatement *node)
   547 {
   548     if (node->expression()) {
   549         node->expression()->accept(this);
   550         __ return_();
   551     } else {
   552         __ returnvoid();
   553     }
   554 }
   555 
   556 void
   557 BytecodeCompiler::visitForTest(Expression *expression,
   558                                Label *trueBranch,
   559                                Label *falseBranch,
   560                                Label *fallthrough)
   561 {
   562     TokenKind token = ToCompare(expression);
   563     if (token == TOK_EOF || token == TOK_NOT) {
   564         if (token == TOK_EOF)
   565             expression->accept(this);
   566         else
   567             expression->toUnaryExpression()->expression()->accept(this);
   568         
   569         bool jumpOnTrue = (fallthrough == falseBranch) ^ (token == TOK_NOT);
   570 
   571         Opcode op = jumpOnTrue ? OP_JT : OP_JF;
   572         if (expression->type()->isFloat())
   573             op = (Opcode)(int(op) + (OP_JL_F - OP_JL));
   574 
   575         if (fallthrough == falseBranch)
   576             __ j(op, trueBranch);
   577         else
   578             __ j(op, falseBranch); 
   579         return;
   580     }
   581 
   582     BinaryExpression *binary = expression->toBinaryExpression();
   583 
   584     if (token == TOK_AND || token == TOK_OR) {
   585         Label next;
   586         if (token == TOK_AND)
   587             visitForTest(binary->left(), &next, falseBranch, &next);
   588         else
   589             visitForTest(binary->left(), trueBranch, &next, &next);
   590         __ bind(&next);
   591         visitForTest(binary->right(), trueBranch, falseBranch, fallthrough);
   592         return;
   593     }
   594 
   595     Opcode op = CompareTokenToJump(token);
   596     if (fallthrough == trueBranch)
   597         op = Invert(op);
   598 
   599     Local<Type> leftType(zone_, binary->left()->type());
   600     Local<Type> rightType(zone_, binary->right()->type());
   601     Local<Type> coerce(zone_, GetCoercionType(binary->token(), leftType, rightType));
   602 
   603     visitForALU(coerce, binary->left());
   604     visitForALU(coerce, binary->right());
   605     if (coerce->isFloat())
   606         op = (Opcode)(int(op) + (OP_JL_F - OP_JL));
   607 
   608     if (fallthrough == trueBranch)
   609         __ j(op, falseBranch);
   610     else
   611         __ j(op, trueBranch);
   612 }
   613 
   614 void
   615 BytecodeCompiler::visit(ForStatement *node)
   616 {
   617     AutoEnterScope forScope(this, node->scope());
   618 
   619     recordLifoSlot(node->scope());
   620 
   621     Label join, update;
   622     LoopScope loop(scope_, &join, &update, &loop_);
   623 
   624     if (node->initialization())
   625         node->initialization()->accept(this);
   626 
   627     Label header, test;
   628     if (node->condition())
   629         __ jump(&test);
   630 
   631     __ bind(&header);
   632     node->body()->accept(this);
   633 
   634     __ bind(&update);
   635     if (node->update())
   636         node->update()->accept(this);
   637 
   638     if (node->condition()) {
   639         __ bind(&test);
   640         visitForTest(node->condition(), &header, &join, &join);
   641     } else {
   642         __ jump(&header);
   643     }
   644 
   645     __ bind(&join);
   646 
   647     if (node->scope())
   648         unwindTo(node->scope()->enclosing());
   649     assert(__ stackDepth() == 0);
   650 }
   651 
   652 void
   653 BytecodeCompiler::visit(WhileStatement *node)
   654 {
   655     Label header, join;
   656 
   657     __ bind(&header);
   658 
   659     LoopScope loop(scope_, &join, &header, &loop_);
   660 
   661     if (node->token() == TOK_WHILE) {
   662         Label body;
   663 
   664         visitForTest(node->condition(), &body, &join, &body);
   665         __ bind(&body);
   666         node->body()->accept(this);
   667         __ jump(&header);
   668     } else {
   669         node->body()->accept(this);
   670         visitForTest(node->condition(), &header, &join, &join);
   671     }
   672 
   673     __ bind(&join);
   674 }
   675 
   676 void
   677 BytecodeCompiler::visit(BreakStatement *node)
   678 {
   679     unwindTo(loop_->scope());
   680     __ jump(loop_->break_());
   681 }
   682 
   683 void
   684 BytecodeCompiler::visit(ContinueStatement *node)
   685 {
   686     unwindTo(loop_->scope());
   687     __ jump(loop_->continue_());
   688 }
   689 
   690 void
   691 BytecodeCompiler::visit(BlockStatement *node)
   692 {
   693     AutoEnterScope blockScope(this, node->scope());
   694 
   695     recordLifoSlot(node->scope());
   696 
   697     for (size_t i = 0; i < node->statements()->length(); i++) {
   698         Statement *statement = node->statements()->at(i);
   699         statement->accept(this);
   700         assert(__ stackDepth() == 0);
   701     }
   702 
   703     // We don't bother emitting an "unwind" instruction for function scopes,
   704     // since this is taken care of by the calling convention.
   705     if (node->scope() && node->scope()->enclosing()->kind() != Scope::FUNCTION)
   706         unwindTo(node->scope()->enclosing());
   707 }
   708 
   709 void
   710 BytecodeCompiler::visit(IntegerLiteral *node)
   711 {
   712     __ int_(node->value());
   713 }
   714 
   715 void
   716 BytecodeCompiler::visit(BooleanLiteral *node)
   717 {
   718     if (node->token() == TOK_TRUE)
   719         __ true_();
   720     else
   721         __ false_();
   722 }
   723 
   724 void
   725 BytecodeCompiler::visit(FloatLiteral *node)
   726 {
   727     __ float_((float)node->value());
   728 }
   729 
   730 static inline ArrayMap *
   731 BuildArrayMap(Zone *zone, Handle<Type> type)
   732 {
   733     Local<ArrayMap> contained(zone);
   734     if (type->levels() > 1) {
   735         Local<Type> containedType(zone, type->contained());
   736         contained = BuildArrayMap(zone, containedType);
   737         if (!contained)
   738             return NULL;
   739     }
   740 
   741     return ArrayMap::New(zone, type, contained);
   742 }
   743 
   744 void
   745 BytecodeCompiler::visit(StringLiteral *node)
   746 {
   747     Local<Type> type(zone_, node->type());
   748     Local<ArrayMap> map(zone_, BuildArrayMap(zone_, type));
   749     if (!map)
   750         return;
   751 
   752     Local<Array> array(zone_, Array::New(zone_, map, node->string()->length(), Heap::Tenure_Old));
   753     if (!array)
   754         return;
   755 
   756     assert(array->nelements() >= node->string()->length());
   757     memcpy(array->chars(), node->string()->raw(), node->string()->length() * sizeof(char));
   758 
   759     __ note_position(node->pos());
   760     __ object(array);
   761 }
   762 
   763 void
   764 BytecodeCompiler::getEnvSlot(Variable *var)
   765 {
   766     assert(var->scope()->kind() == Scope::GLOBAL);
   767     __ getglobal(var);
   768 }
   769 
   770 void
   771 BytecodeCompiler::setEnvSlot(Variable *var)
   772 {
   773     assert(var->scope()->kind() == Scope::GLOBAL);
   774     __ setglobal(var);
   775 }
   776 
   777 void
   778 BytecodeCompiler::visit(VariableDeclaration *node)
   779 {
   780     Variable *var = node->variable();
   781     
   782     Local<Type> type(zone_, var->type());
   783     if (type->isArray()) {
   784         Local<ArrayMap> map(zone_, BuildArrayMap(zone_, type));
   785         __ note_position(node->pos());
   786         if (var->scope()->kind() == Scope::GLOBAL)
   787             __ newarray(map, Heap::Tenure_Old);
   788         else if (var->needsHeapAllocation())
   789             __ newarray(map, Heap::Tenure_Default);
   790         else
   791             __ newarray(map, Heap::Tenure_Stack);
   792 
   793         if (node->initialization()) {
   794             node->initialization()->accept(this);
   795             __ note_position(node->pos());
   796             __ arraycopy();
   797         }
   798     } else if (type->isStruct()) {
   799         Local<Map> map(zone_, type->newMap());
   800         if (var->scope()->kind() == Scope::GLOBAL)
   801             __ newstruct(map, Heap::Tenure_Old);
   802         else if (var->needsHeapAllocation())
   803             __ newstruct(map, Heap::Tenure_Default);
   804         else
   805             __ newstruct(map, Heap::Tenure_Stack);
   806     } else {
   807         if (node->initialization()) {
   808             node->initialization()->accept(this);
   809         } else {
   810             if (type->isInt32OrEnum() || type->isBool()) {
   811                 __ int_(0);
   812             } else {
   813                 assert(type->isFloat());
   814                 __ float_(0);
   815             }
   816         }
   817     }
   818 
   819     if (var->location() == Variable::STACK) {
   820         __ setlocal(var);
   821         locals_->set(zone_, var->slot(), var->type());
   822     } else {
   823         assert(var->location() == Variable::ENVIRONMENT);
   824         setEnvSlot(var);
   825     }
   826 
   827     __ pop();
   828 }
   829 
   830 void
   831 BytecodeCompiler::visit(CallExpression *node)
   832 {
   833     Local<Type> funType(zone_, node->callee()->type());
   834 
   835     // Sniff out natives, which have a specific opcode and are guaranteed to
   836     // be called via name proxy.
   837     NamedFunction *native = NULL;
   838     if (funType->isNative()) {
   839         native = node->callee()->toNameProxy()->binding()->toNamedFunction();
   840     }
   841 
   842     for (size_t i = node->arguments()->length() - 1; i < node->arguments()->length(); i--) {
   843         Expression *arg = node->arguments()->at(i);
   844 
   845         // We need to compute a reference if the parameter was in the form:
   846         //  f(&a)
   847         // Note this form does not allow: f({})
   848         // 
   849         // We also need to compute references for all variadic native
   850         // arguments, but arrays and references are already in the
   851         // appropriate form.
   852         Local<Type> given(zone_, arg->type());
   853         bool mustPushReference = false;
   854         if (i >= funType->parameters()->length()) {
   855             assert(funType->isNative() && funType->isNativeVariadic());
   856             mustPushReference = !given->isArray() && !given->isReference();
   857         } else if (funType->parameterAt(i)->isReference()) {
   858             mustPushReference = !given->isReference();
   859         }
   860 
   861         // If a native is passed to a native, it must only be one level deep.
   862         assert(!funType->isNative() || !given->isArray() || given->levels() == 1);
   863 
   864         if (mustPushReference) {
   865             if (arg->isNameProxy()) {
   866                 // :TODO: test with functions and globals
   867                 // Compute a reference to the name.
   868                 Variable *var = arg->toNameProxy()->binding()->toVariable();
   869                 __ note_position(node->pos());
   870                 __ newref(var);
   871             } else if (arg->isIndexExpression()) {
   872                 IndexExpression *expr = arg->toIndexExpression();
   873                 expr->left()->accept(this);
   874                 expr->right()->accept(this);
   875                 __ note_position(expr->pos());
   876                 __ bounds();
   877                 __ arrayref_lifo();
   878             } else {
   879                 // We don't know how to, or can't, build a direct reference to
   880                 // this type. Make an indirect one, by taking the top of the
   881                 // stack and boxing it up.
   882                 arg->accept(this);
   883                 __ note_position(node->pos());
   884                 __ slotref_lifo();
   885             }
   886         } else {
   887             arg->accept(this);
   888         }
   889     }
   890 
   891     __ note_position(node->pos());
   892     if (native) {
   893         __ callnative(native->slot(), node->arguments()->length());
   894         __ drop(node->arguments()->length());
   895     } else {
   896         node->callee()->accept(this);
   897         __ call(funType);
   898         __ drop(node->arguments()->length() + 1);
   899     }
   900 }
   901 
   902 void
   903 BytecodeCompiler::visit(TernaryExpression *node)
   904 {
   905     Label success, failure, join;
   906 
   907     visitForTest(node->condition(), &success, &failure, &success);
   908     __ bind(&success);
   909     node->left()->accept(this);
   910     __ drop(1);
   911     __ jump(&join);
   912     __ bind(&failure);
   913     node->right()->accept(this);
   914     __ bind(&join);
   915 }
   916 
   917 void
   918 BytecodeCompiler::visit(IfStatement *node)
   919 {
   920     Label join;
   921     if (!node->ifFalse()) {
   922         Label success;
   923 
   924         visitForTest(node->condition(), &success, &join, &success);
   925         __ bind(&success);
   926         node->ifTrue()->accept(this);
   927     } else {
   928         Label success, next;
   929 
   930         visitForTest(node->condition(), &success, &next, &success);
   931         __ bind(&success);
   932         node->ifTrue()->accept(this);
   933         __ jump(&join);
   934         __ bind(&next);
   935         node->ifFalse()->accept(this);
   936     }
   937 
   938     __ bind(&join);
   939 }
   940 
   941 void
   942 BytecodeCompiler::visit(FunctionStatement *node)
   943 {
   944     if (!node->fun()->used())
   945         return;
   946 
   947     if (node->fun()->isNative()) {
   948         assert(!moduleData_->natives->at(node->fun()->slot()));
   949 
   950         Local<Type> type(zone_, node->fun()->type());
   951         Local<String> name(zone_, node->fun()->name());
   952         Local<Native> native(zone_, Native::New(zone_, type, name));
   953         if (!native)
   954             return;
   955 
   956         moduleData_->natives->set(zone_, node->fun()->slot(), native);
   957         return;
   958     }
   959 
   960     // If the function has no body, then it's just a declaration.
   961     if (!node->body()) {
   962         assert(node->fun()->isForward() || node->fun()->isPublic());
   963         return;
   964     }
   965 
   966     BytecodeCompiler child(zone_, tree_, moduleData_);
   967     Local<Function> fun(zone_, child.compileFunction(moduleData_, node));
   968     if (!fun)
   969         return;
   970     
   971     assert(!moduleData_->module->getFunction(node->fun()->slot()));
   972     moduleData_->module->setFunction(zone_, node->fun()->slot(), fun);
   973 }
   974 
   975 void
   976 BytecodeCompiler::visit(EnumStatement *node)
   977 {
   978     // :TODO: eventually, we'll export these.
   979 }
   980 
   981 void
   982 BytecodeCompiler::visit(StructureStatement *node)
   983 {
   984 }
   985 
   986 Code *
   987 BytecodeCompiler::compileCode(Scope *scope, unsigned lineno)
   988 {
   989     // STOP doubles as RETURNVOID.
   990     __ stop();
   991 
   992     if (__ oom() || zone_->hasPendingException())
   993         return NULL;
   994 
   995     Local<ByteArray> bytes(zone_, ByteArray::New(zone_, __ length() * sizeof(bytecode), Heap::Tenure_Old));
   996     if (!bytes)
   997         return NULL;
   998     memcpy(bytes->raw(), __ buffer(), __ length());
   999 
  1000     for (size_t i = 0; i < scope->maxContainedLocals(); i++)
  1001         assert(locals_->at(i));
  1002 
  1003     Local<FixedArray> objects(zone_, FixedArray::New(zone_, __ objects()->length(), Heap::Tenure_Old));
  1004     if (!objects)
  1005         return NULL;
  1006 
  1007     for (size_t i = 0; i < __ objects()->length(); i++)
  1008         objects->set(zone_, i, *(__ objects()->at(i)));
  1009 
  1010     Local<ByteArray> safepoints(zone_);
  1011 
  1012     // If any stack slots hold gc pointers at potential failure points in the
  1013     // bytecode, record them now. We do this by building a list of tuples;
  1014     // each tuple contains the pc offset, and a bitset containing which stack
  1015     // slots must be scanned by the gc.
  1016     if (__ oopRecords()->length()) {
  1017         size_t bytesPerSafepoint = Code::BytesPerSafepoint(__ maxStackDepth());
  1018         size_t gcmapSize = bytesPerSafepoint * __ oopRecords()->length();
  1019         safepoints = ByteArray::New(zone_, gcmapSize, Heap::Tenure_Old);
  1020         if (!safepoints)
  1021             return NULL;
  1022 
  1023         Address cursor = safepoints->raw();
  1024         for (size_t i = 0; i < __ oopRecords()->length(); i++) {
  1025             OopRecord *record = __ oopRecords()->at(i);
  1026             assert(record->depth <= __ maxStackDepth());
  1027 
  1028             *reinterpret_cast<unsigned *>(cursor) = record->offset;
  1029 
  1030             unsigned char *bits = reinterpret_cast<unsigned char *>(cursor + sizeof(unsigned));
  1031             for (unsigned i = 0; i < record->depth; i++)
  1032                 bits[i / 8] |= (1 << (i % 8));
  1033 
  1034             cursor += bytesPerSafepoint;
  1035         }
  1036 
  1037         assert(cursor == safepoints->raw() + gcmapSize);
  1038     }
  1039 
  1040     Local<ByteArray> sourcemap(zone_);
  1041     if (__ sourcemapLength()) {
  1042         sourcemap = ByteArray::New(zone_, __ sourcemapLength(), Heap::Tenure_Old);
  1043         if (!sourcemap)
  1044             return NULL;
  1045 
  1046         memcpy(sourcemap->raw(), __ sourcemap(), __ sourcemapLength());
  1047     }
  1048 
  1049     Local<Code> code(zone_);
  1050 
  1051     code = Code::New(zone_,
  1052                      bytes,
  1053                      locals_,
  1054                      objects,
  1055                      __ maxStackDepth(),
  1056                      moduleData_->module,
  1057                      safepoints,
  1058                      sourcemap,
  1059                      lineno);
  1060     return code;
  1061 }
  1062 
  1063 Function *
  1064 BytecodeCompiler::compileFunction(ModuleData *module, FunctionStatement *node)
  1065 {
  1066     // Note: No need to record a life slot here, since it's part of the Frame.
  1067     AutoEnterScope functionScope(this, node->scope());
  1068 
  1069     // Set the initial line, because line mappings are deltas.
  1070     __ setFirstLine(node->pos().line);
  1071     locals_ = FixedArray::New(zone_, node->scope()->maxContainedLocals(), Heap::Tenure_Old);
  1072 
  1073     node->body()->accept(this);
  1074 
  1075     unsigned nargs = node->scope()->numArguments();
  1076     Local<FixedArray> args(zone_, FixedArray::New(zone_, nargs, Heap::Tenure_Old));
  1077     if (!args)
  1078         return NULL;
  1079 
  1080     for (size_t i = 0; i < node->scope()->numArguments(); i++)
  1081         args->set(zone_, i, node->scope()->getArgument(i)->type());
  1082 
  1083 
  1084     Local<Code> code(zone_, compileCode(node->scope(), node->pos().line));
  1085     if (!code)
  1086         return NULL;
  1087 
  1088     Local<Type> type(zone_, node->fun()->type());
  1089     Local<String> name(zone_, node->fun()->name());
  1090     Local<Function> fun(zone_, Function::New(zone_, code, type, name, node->pos()));
  1091     if (!fun)
  1092         return NULL;
  1093 
  1094     // If this function had a forward, export it as a named public.
  1095     if (node->fun()->isPublic()) {
  1096         assert(node->fun()->isPublic());
  1097         ScopedRoot<Function> root(fun);
  1098         if (!root)
  1099             return NULL;
  1100         if (!moduleData_->publics.append(root))
  1101             return NULL;
  1102     }
  1103 
  1104     Disassemble(code, stdout);
  1105     
  1106     return fun;
  1107 }
  1108 
  1109 Module *
  1110 BytecodeCompiler::compile()
  1111 {
  1112     AutoEnterScope scope(this, tree_->scope());
  1113 
  1114     ModuleData moduleData;
  1115 
  1116     moduleData_ = &moduleData;
  1117     moduleData_->module = Module::New(zone_, tree_->scope()->numFunctions());
  1118 
  1119     if (!moduleData_)
  1120         return NULL;
  1121     
  1122     moduleData_->natives = FixedArray::New(zone_, tree_->scope()->numNatives(), Heap::Tenure_Old);
  1123     if (!moduleData_->natives)
  1124         return NULL;
  1125 
  1126     for (size_t i = 0; i < tree_->statements()->length(); i++) {
  1127         Statement *statement = tree_->statements()->at(i);
  1128         statement->accept(this);
  1129     }
  1130 
  1131     if (zone_->hasPendingException())
  1132         return NULL;
  1133 
  1134 #ifndef NDEBUG
  1135     for (size_t i = 0; i < tree_->scope()->numFunctions(); i++)
  1136         assert(moduleData_->module->getFunction(i));
  1137     for (size_t i = 0; i < tree_->scope()->numNatives(); i++)
  1138         assert(moduleData_->natives->at(i));
  1139 #endif
  1140 
  1141     if (moduleData_->publics.length()) {
  1142         Local<Function> fun(zone_);
  1143         Local<FixedArray> list(zone_, FixedArray::New(zone_, moduleData_->publics.length(),
  1144                                Heap::Tenure_Old));
  1145         if (!list)
  1146             return NULL;
  1147 
  1148         for (size_t i = 0; i < moduleData_->publics.length(); i++)
  1149             list->set(zone_, i, moduleData_->publics[i]);
  1150 
  1151         moduleData_->module->setPublics(list);
  1152     }
  1153 
  1154     moduleData_->module->setNatives(moduleData_->natives);
  1155 
  1156     if (scope_->numEnvironmentVars()) {
  1157         Local<EnvironmentMap> globalMap(zone_, scope_->createEnvironmentMap(zone_));
  1158         if (!globalMap)
  1159             return NULL;
  1160 
  1161         Local<Environment> environment(zone_, Environment::New(zone_, globalMap));
  1162         if (!environment)
  1163             return NULL;
  1164 
  1165         moduleData_->module->setEnvironment(environment);
  1166     }
  1167 
  1168     Local<Code> code(zone_, compileCode(tree_->scope(), 1));
  1169     if (!code)
  1170         return NULL;
  1171 
  1172     Disassemble(code, stdout);
  1173 
  1174     moduleData_->module->setCode(code);
  1175 
  1176     return moduleData_->module;
  1177 }