Implemented callbacks.
1 /* vim: set ts=4 sw=4 tw=99 et:
3 * Copyright (C) 2012 David Anderson
5 * This file is part of JITCraft.
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)
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.
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/.
20 #include "BytecodeCompiler.h"
27 #include "Environments.h"
33 typedef BytecodeEmitter::Label Label;
37 BytecodeCompiler::BytecodeCompiler(Zone *zone, ParseTree *tree, ModuleData *module)
40 emitter_(zone->pool()),
48 static inline TokenKind
49 ToCompare(Expression *expr)
51 if (expr->isBinaryExpression()) {
52 BinaryExpression *b = expr->toBinaryExpression();
53 if (b->token() >= TOK_EQUALS && b->token() <= TOK_OR)
55 } else if (expr->isUnaryExpression()) {
56 UnaryExpression *u = expr->toUnaryExpression();
57 if (u->token() == TOK_NOT)
64 CompareTokenToJump(TokenKind kind)
78 assert(kind == TOK_LE);
84 TokenToOpcode(TokenKind kind)
120 assert(kind == TOK_BITXOR);
126 BytecodeCompiler::recordLifoSlot(Scope *scope)
131 if (Variable *var = scope->lifoSlot()) {
132 locals_->set(zone_, var->slot(), var->type());
133 __ savelifo(var->slot());
138 BytecodeCompiler::unwindTo(Scope *scope)
140 // Note: we only need to unwind to the outermost scope's LIFO slot.
141 Variable *var = NULL;
142 for (Scope *current = scope_; current != scope; current = current->enclosing()) {
143 if (Variable *slot = current->lifoSlot())
148 __ unwindlifo(var->slot());
152 BytecodeCompiler::visit(NameProxy *name)
154 switch (name->binding()->kind()) {
155 case BoundName::VARIABLE:
157 Variable *var = name->binding()->toVariable();
159 if (var->location() == Variable::STACK) {
161 assert(!name->type()->isReference());
162 } else if (var->location() == Variable::ENVIRONMENT) {
165 assert(var->location() == Variable::PARAMETER);
168 // If this argument is actually a reference, dereference it now.
169 if (var->type()->isReference())
170 __ getref(var->type()->contained());
175 case BoundName::FUNCTION:
177 NamedFunction *fun = name->binding()->toNamedFunction();
179 __ getmodule_fn(fun->slot());
185 NamedConstant *constant = name->binding()->toNamedConstant();
186 __ int_(constant->value().toInt());
193 BytecodeCompiler::visit(ExpressionStatement *node)
195 // Expressions leave their value on the top of the stack, so we make sure
196 // to balance the stack if they're used as a statement.
197 node->expression()->accept(this);
198 if (!node->expression()->type()->isVoid())
203 BytecodeCompiler::visit(Assignment *node)
205 Local<Type> type(zone_, node->expression()->type());
207 // The first step is three sub-steps:
209 // (1) Bind the left-hand side.
210 // -- If a cumulative operation (+=, etc):
211 // (2) Save a copy of the binding on the stack.
212 // (3) Dereference the binding to get a value.
214 if (node->lvalue()->isNameProxy()) {
215 NameProxy *proxy = node->lvalue()->toNameProxy();
216 Variable *var = proxy->binding()->toVariable();
219 if (var->type()->isReference() ||
220 var->type()->isArray() ||
221 var->type()->isStruct())
226 // Get the value if needed.
227 if (node->token() != TOK_ASSIGN) {
228 // += etc is not allowed on arrays.
229 assert(!var->type()->isArray());
231 if (var->type()->isReference()) {
233 __ getref(var->type()->contained());
238 } else if (node->lvalue()->isFieldExpression()) {
239 FieldExpression *expr = node->lvalue()->toFieldExpression();
240 __ note_position(expr->pos());
242 expr->left()->accept(this);
244 if (node->token() != TOK_ASSIGN)
247 if (node->token() != TOK_ASSIGN || (type->isStruct() || type->isArray()))
248 __ getfield(expr->fieldIndex(), expr->type());
250 IndexExpression *index = node->lvalue()->toIndexExpression();
251 __ note_position(index->pos());
253 index->left()->accept(this);
254 index->right()->accept(this);
256 if (node->token() != TOK_ASSIGN)
259 if (node->token() != TOK_ASSIGN || (type->isStruct() || type->isArray()))
260 __ getelem(index->type());
263 if (node->token() == TOK_ASSIGN) {
264 node->expression()->accept(this);
266 visitForALU(node->type(), node->expression());
268 TokenKind alu = TokenKind(int(node->token()) - (TOK_ASSIGN_ADD - TOK_PLUS));
269 __ note_position(node->pos());
270 __ binary(TokenToOpcode(alu));
274 if (type->isArray()) {
275 // Unlike references, which can only be computed from a NamePRoxy,
276 // arrays can be computed from multiple lvalue types.
277 __ note_position(node->pos());
279 } else if (type->isStruct()) {
280 // Structs have value semantics, so emit a full copy. We don't break
281 // this down into u-ops, to avoid unnecessary bytecode explosion.
282 __ note_position(node->pos());
284 } else if (node->lvalue()->isNameProxy()) {
285 NameProxy *proxy = node->lvalue()->toNameProxy();
286 Variable *var = proxy->binding()->toVariable();
288 if (var->type()->isReference())
289 __ setref(var->type()->contained());
292 } else if (node->lvalue()->isFieldExpression()) {
293 FieldExpression *expr = node->lvalue()->toFieldExpression();
294 __ setfield(expr->fieldIndex(), expr->type());
296 IndexExpression *index = node->lvalue()->toIndexExpression();
297 __ setelem(index->type());
302 BytecodeCompiler::visit(IncDecExpression *node)
304 // In the postfix case, the logic looks like:
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
314 // In the prefix case, the logic looks like:
316 // (2) Dup -> REF REF
317 // (3) Fetch -> REF VAL
320 // (6) Add -> REF VAL+1
321 // (7) Store -> VAL+1
324 // This is squirrely enough such that we don't bother sharing too much
327 // Note: We simulate a "Pick" operation with a dup2+pop.
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();
336 if (var->location() == Variable::ENVIRONMENT)
338 else if (var->type()->isReference() || var->type()->isArray())
342 if (var->type()->isReference()) {
344 __ getref(node->type());
345 if (node->postfix()) {
350 assert(!var->type()->isArray());
351 if (var->location() != Variable::ENVIRONMENT)
356 } else if (expr->isFieldExpression()) {
357 FieldExpression *field = expr->toFieldExpression();
359 field->left()->accept(this);
361 __ getfield(field->fieldIndex(), field->type());
363 if (node->postfix()) {
364 // The stack looks like this now:
366 __ swap(); // VALUE OBJECT
367 __ pick2(); // VALUE OBJECT VALUE
370 IndexExpression *index = expr->toIndexExpression();
371 __ note_position(index->pos());
373 index->left()->accept(this);
374 index->right()->accept(this);
376 assert(!node->type()->isArray());
378 __ getelem(node->type());
380 if (node->postfix()) {
381 // The stack looks like this now:
384 // So we must use a PICK operation to rotate the stack into position.
385 __ roll3(); // INDEX VALUE ARRAY
386 __ roll3(); // VALUE ARRAY INDEX
387 __ pick3(); // VALUE ARRAY INDEX VALUE
392 if (node->type()->isFloat()) {
395 assert(node->type()->isInt32());
399 __ note_position(node->pos());
400 if (node->token() == TOK_INCREMENT)
406 if (expr->isNameProxy()) {
407 NameProxy *proxy = expr->toNameProxy();
408 Variable *var = proxy->binding()->toVariable();
410 if (var->type()->isReference())
411 __ setref(node->type());
412 else if (var->location() == Variable::ENVIRONMENT)
416 } else if (expr->isFieldExpression()) {
417 FieldExpression *field = expr->toFieldExpression();
418 __ setfield(field->fieldIndex(), field->type());
420 assert(expr->isIndexExpression());
421 __ setelem(node->type());
430 BytecodeCompiler::visitForALU(Type *needed, Expression *node)
433 if (needed->isFloat() && !node->type()->isFloat())
436 assert(needed->primitive() == node->type()->primitive());
440 GetCoercionType(TokenKind tok, Type *left, Type *right)
448 BytecodeCompiler::visit(UnaryExpression *node)
450 Local<Type> out(zone_, ((Expression *)node)->type());
452 switch (node->token()) {
455 Local<Type> type(zone_, node->expression()->type());
456 node->expression()->accept(this);
467 Local<Type> type(zone_, node->expression()->type());
468 node->expression()->accept(this);
479 Local<Type> from(zone_, node->expression()->type());
481 node->expression()->accept(this);
482 if (!from->isFloat() && out->isFloat())
484 else if (from->isFloat() && !out->isFloat())
490 assert(node->token() == TOK_TILDE);
491 node->expression()->accept(this);
498 BytecodeCompiler::visit(BinaryExpression *node)
500 if (node->token() == TOK_AND || node->token() == TOK_OR) {
501 Label success, failure, done;
502 visitForTest(node, &success, &failure, &success);
505 __ drop(1); // Otherwise, the stack depth will be +1 too much.
513 Local<Type> leftType(zone_, node->left()->type());
514 Local<Type> rightType(zone_, node->right()->type());
515 Local<Type> coerce(zone_, GetCoercionType(node->token(), leftType, rightType));
517 visitForALU(coerce, node->left());
518 visitForALU(coerce, node->right());
520 Opcode op = TokenToOpcode(node->token());
521 if (node->type()->isFloat())
522 op = (Opcode)(int(op) + (OP_ADD_F - OP_ADD));
524 __ note_position(node->pos());
529 BytecodeCompiler::visit(IndexExpression *node)
531 node->left()->accept(this);
532 node->right()->accept(this);
533 __ note_position(node->pos());
534 __ getelem(node->type());
538 BytecodeCompiler::visit(FieldExpression *node)
540 node->left()->accept(this);
541 __ getfield(node->fieldIndex(), node->type());
545 BytecodeCompiler::visit(ReturnStatement *node)
547 if (node->expression()) {
548 node->expression()->accept(this);
556 BytecodeCompiler::visitForTest(Expression *expression,
561 TokenKind token = ToCompare(expression);
562 if (token == TOK_EOF || token == TOK_NOT) {
563 if (token == TOK_EOF)
564 expression->accept(this);
566 expression->toUnaryExpression()->expression()->accept(this);
568 bool jumpOnTrue = (fallthrough == falseBranch) ^ (token == TOK_NOT);
570 Opcode op = jumpOnTrue ? OP_JT : OP_JF;
571 if (expression->type()->isFloat())
572 op = (Opcode)(int(op) + (OP_JL_F - OP_JL));
574 if (fallthrough == falseBranch)
575 __ j(op, trueBranch);
577 __ j(op, falseBranch);
581 BinaryExpression *binary = expression->toBinaryExpression();
583 if (token == TOK_AND || token == TOK_OR) {
585 if (token == TOK_AND)
586 visitForTest(binary->left(), &next, falseBranch, &next);
588 visitForTest(binary->left(), trueBranch, &next, &next);
590 visitForTest(binary->right(), trueBranch, falseBranch, fallthrough);
594 Opcode op = CompareTokenToJump(token);
595 if (fallthrough == trueBranch)
598 Local<Type> leftType(zone_, binary->left()->type());
599 Local<Type> rightType(zone_, binary->right()->type());
600 Local<Type> coerce(zone_, GetCoercionType(binary->token(), leftType, rightType));
602 visitForALU(coerce, binary->left());
603 visitForALU(coerce, binary->right());
604 if (coerce->isFloat())
605 op = (Opcode)(int(op) + (OP_JL_F - OP_JL));
607 if (fallthrough == trueBranch)
608 __ j(op, falseBranch);
610 __ j(op, trueBranch);
614 BytecodeCompiler::visit(ForStatement *node)
616 AutoEnterScope forScope(this, node->scope());
618 recordLifoSlot(node->scope());
621 LoopScope loop(scope_, &join, &update, &loop_);
623 if (node->initialization())
624 node->initialization()->accept(this);
627 if (node->condition())
631 node->body()->accept(this);
635 node->update()->accept(this);
637 if (node->condition()) {
639 visitForTest(node->condition(), &header, &join, &join);
647 unwindTo(node->scope()->enclosing());
648 assert(__ stackDepth() == 0);
652 BytecodeCompiler::visit(WhileStatement *node)
658 LoopScope loop(scope_, &join, &header, &loop_);
660 if (node->token() == TOK_WHILE) {
663 visitForTest(node->condition(), &body, &join, &body);
665 node->body()->accept(this);
668 node->body()->accept(this);
669 visitForTest(node->condition(), &header, &join, &join);
676 BytecodeCompiler::visit(BreakStatement *node)
678 unwindTo(loop_->scope());
679 __ jump(loop_->break_());
683 BytecodeCompiler::visit(ContinueStatement *node)
685 unwindTo(loop_->scope());
686 __ jump(loop_->continue_());
690 BytecodeCompiler::visit(BlockStatement *node)
692 AutoEnterScope blockScope(this, node->scope());
694 recordLifoSlot(node->scope());
696 for (size_t i = 0; i < node->statements()->length(); i++) {
697 Statement *statement = node->statements()->at(i);
698 statement->accept(this);
699 assert(__ stackDepth() == 0);
702 // We don't bother emitting an "unwind" instruction for function scopes,
703 // since this is taken care of by the calling convention.
704 if (node->scope() && node->scope()->enclosing()->kind() != Scope::FUNCTION)
705 unwindTo(node->scope()->enclosing());
709 BytecodeCompiler::visit(IntegerLiteral *node)
711 __ int_(node->value());
715 BytecodeCompiler::visit(BooleanLiteral *node)
717 if (node->token() == TOK_TRUE)
724 BytecodeCompiler::visit(FloatLiteral *node)
726 __ float_((float)node->value());
730 BytecodeCompiler::visit(StringLiteral *node)
732 Local<Type> type(zone_, node->type());
733 Local<ArrayMap> map(zone_, ArrayMap::Attach(zone_, type));
737 Local<Array> array(zone_,
738 Array::NewString(zone_,
740 node->string()->raw(),
741 node->string()->length(),
746 __ note_position(node->pos());
751 BytecodeCompiler::getEnvSlot(Variable *var)
753 assert(var->scope()->kind() == Scope::GLOBAL);
758 BytecodeCompiler::setEnvSlot(Variable *var)
760 assert(var->scope()->kind() == Scope::GLOBAL);
765 BytecodeCompiler::visit(VariableDeclaration *node)
767 Variable *var = node->variable();
769 Local<Type> type(zone_, var->type());
770 if (type->isArray()) {
771 Local<ArrayMap> map(zone_, ArrayMap::Attach(zone_, type));
772 __ note_position(node->pos());
773 if (var->scope()->kind() == Scope::GLOBAL)
774 __ newarray(map, Heap::Tenure_Old);
775 else if (var->needsHeapAllocation())
776 __ newarray(map, Heap::Tenure_Default);
778 __ newarray(map, Heap::Tenure_Stack);
780 if (node->initialization()) {
781 node->initialization()->accept(this);
782 __ note_position(node->pos());
785 } else if (type->isStruct()) {
786 Local<Map> map(zone_, type->newMap());
787 if (var->scope()->kind() == Scope::GLOBAL)
788 __ newstruct(map, Heap::Tenure_Old);
789 else if (var->needsHeapAllocation())
790 __ newstruct(map, Heap::Tenure_Default);
792 __ newstruct(map, Heap::Tenure_Stack);
794 if (node->initialization()) {
795 node->initialization()->accept(this);
797 if (type->isInt32OrEnum() || type->isBool()) {
800 assert(type->isFloat());
806 if (var->location() == Variable::STACK) {
808 locals_->set(zone_, var->slot(), var->type());
810 assert(var->location() == Variable::ENVIRONMENT);
818 BytecodeCompiler::visit(CallExpression *node)
820 Local<Type> funType(zone_, node->callee()->type());
822 // Sniff out natives, which have a specific opcode and are guaranteed to
823 // be called via name proxy.
824 NamedFunction *native = NULL;
825 if (funType->isNative()) {
826 native = node->callee()->toNameProxy()->binding()->toNamedFunction();
829 Local<Type> given(zone_);
830 for (size_t i = node->arguments()->length() - 1; i < node->arguments()->length(); i--) {
831 Expression *arg = node->arguments()->at(i);
835 // We need to compute a reference if the parameter was in the form:
837 // Note this form does not allow: f({})
839 // We also need to compute references for all variadic native
840 // arguments, but arrays and references are already in the
842 bool mustPushReference = false;
843 if (i >= funType->parameters()->length()) {
844 assert(funType->isNative() && funType->isNativeVariadic());
845 mustPushReference = !given->isArray() && !given->isReference();
846 } else if (funType->parameterAt(i)->isReference()) {
847 mustPushReference = !given->isReference();
850 // If a native is passed to a native, it must only be one level deep.
851 assert(!funType->isNative() || !given->isArray() || given->levels() == 1);
853 if (mustPushReference) {
854 if (arg->isNameProxy()) {
855 // :TODO: test with functions and globals
856 // Compute a reference to the name.
857 Variable *var = arg->toNameProxy()->binding()->toVariable();
858 __ note_position(node->pos());
860 } else if (arg->isIndexExpression()) {
861 IndexExpression *expr = arg->toIndexExpression();
862 expr->left()->accept(this);
863 expr->right()->accept(this);
864 __ note_position(expr->pos());
866 } else if (arg->isFieldExpression()) {
867 FieldExpression *expr = arg->toFieldExpression();
868 expr->left()->accept(this);
869 __ note_position(expr->pos());
870 __ fieldref_lifo(expr->fieldIndex());
872 // We don't know how to, or can't, build a direct reference to
873 // this type. Make an indirect one, by taking the top of the
874 // stack and boxing it up.
876 __ note_position(node->pos());
884 unsigned argc = node->arguments()->length();
886 // If there are missing arguments, then we're not done and have to push
887 // default parameters.
888 Local<Box> box(zone_);
889 Local<Array> array(zone_);
890 Local<ArrayMap> map(zone_);
891 for (size_t i = node->arguments()->length(); i < funType->parameters()->length(); i++) {
892 box = Box::cast(funType->defaults()->at(i));
894 if (box->type()->isPod()) {
895 if (box->type()->pod() == PrimitiveType_Int32)
896 __ int_(box->toInt32());
897 else if (box->type()->pod() == PrimitiveType_Float)
898 __ float_(box->toFloat());
902 if (funType->parameterAt(i)->isReference()) {
903 __ note_position(node->pos());
907 assert(box->type()->isArray());
909 array = Array::cast(box->toObject());
910 if (funType->parameterAt(i)->isConst()) {
913 // We need to copy the array since it's mutable. Note that
914 // although COPYARRAY returns its left-hand side, this may
915 // change in the future, we do the same thing and dupe the
916 // newly allocated array.
917 map = ArrayMap::cast(array->map());
918 __ newarray(map, Heap::Tenure_Stack);
929 __ note_position(node->pos());
931 __ callnative(native->slot(), argc);
934 node->callee()->accept(this);
941 BytecodeCompiler::visit(TernaryExpression *node)
943 Label success, failure, join;
945 visitForTest(node->condition(), &success, &failure, &success);
947 node->left()->accept(this);
951 node->right()->accept(this);
956 BytecodeCompiler::visit(IfStatement *node)
959 if (!node->ifFalse()) {
962 visitForTest(node->condition(), &success, &join, &success);
964 node->ifTrue()->accept(this);
968 visitForTest(node->condition(), &success, &next, &success);
970 node->ifTrue()->accept(this);
973 node->ifFalse()->accept(this);
980 BytecodeCompiler::tableswitch(SwitchStatement *node)
982 CaseValueList *values = node->caseValueList();
984 if (values->length() < 3)
987 // Find the delta between the largest and smallest value.
988 int hi = values->at(values->length() - 1).box.toInt();
989 int lo = values->at(0).box.toInt();
992 unsigned tablesize = TableSwitchEntries(lo, hi);
993 if (tablesize > MAX_TABLESWITCH_ENTRIES)
998 // Create the list of labels that each statement will bind to.
999 Label *labels = new Label[node->cases()->length()];
1001 // Create the table of labels we'll use for each case.
1002 Label **table = new Label *[tablesize];
1004 // Link all cases, by default, to the default label.
1005 for (size_t i = 0; i < tablesize; i++)
1008 // Now patch actual cases to their correct labels.
1009 for (size_t i = 0; i < values->length(); i++) {
1010 CaseValue &v = values->at(i);
1011 assert(v.statement < node->cases()->length());
1013 unsigned index = unsigned(v.box.toInt() - lo);
1014 assert(index < tablesize);
1016 table[index] = &labels[v.statement];
1019 // Emit the tableswitch opcode and the jump table.
1020 __ tableswitch(lo, hi, &def, table);
1022 // We're done with the jump table now.
1025 // Emit each statement.
1026 for (size_t i = 0; i < node->cases()->length(); i++) {
1027 Statement *stmt = node->cases()->at(i)->statement();
1029 __ bind(&labels[i]);
1034 // We're done with the statement labels.
1037 // Emit the default case.
1039 if (node->defaultCase())
1040 node->defaultCase()->accept(this);
1048 BytecodeCompiler::visit(SwitchStatement *node)
1050 node->expression()->accept(this);
1052 if (tableswitch(node))
1057 for (size_t i = 0; i < node->cases()->length(); i++) {
1058 Case *c = node->cases()->at(i);
1060 Label success, fail;
1062 for (size_t j = 0; j < c->others()->length(); j++) {
1063 Expression *expr = c->others()->at(j);
1067 __ j(OP_JEQ, &success);
1073 c->expression()->accept(this);
1074 __ j(OP_JNE, &fail);
1076 c->statement()->accept(this);
1081 if (node->defaultCase())
1082 node->defaultCase()->accept(this);
1089 BytecodeCompiler::visit(FunctionStatement *node)
1091 if (!node->fun()->used())
1094 if (node->fun()->isNative()) {
1095 assert(!moduleData_->natives->at(node->fun()->slot()));
1097 Local<Type> type(zone_, node->fun()->type());
1098 Local<String> name(zone_, node->fun()->name());
1099 Local<Native> native(zone_, Native::New(zone_, type, name));
1103 moduleData_->natives->set(zone_, node->fun()->slot(), native);
1107 // If the function has no body, then it's just a declaration.
1108 if (!node->body()) {
1109 assert(node->fun()->isForward() || node->fun()->isPublic());
1113 BytecodeCompiler child(zone_, tree_, moduleData_);
1114 Local<Function> fun(zone_, child.compileFunction(moduleData_, node));
1118 assert(!moduleData_->module->getFunction(node->fun()->slot()));
1119 moduleData_->module->setFunction(zone_, node->fun()->slot(), fun);
1123 BytecodeCompiler::visit(FunctionTypeStatement *node)
1128 BytecodeCompiler::visit(EnumStatement *node)
1133 BytecodeCompiler::visit(StructureStatement *node)
1138 BytecodeCompiler::compileCode(Scope *scope, unsigned lineno)
1140 // STOP doubles as RETURNVOID.
1143 if (__ oom() || zone_->hasPendingException())
1146 Local<ByteArray> bytes(zone_, ByteArray::New(zone_, __ length() * sizeof(bytecode), Heap::Tenure_Old));
1149 memcpy(bytes->raw(), __ buffer(), __ length());
1151 for (size_t i = 0; i < scope->maxContainedLocals(); i++)
1152 assert(locals_->at(i));
1154 Local<FixedArray> objects(zone_, FixedArray::New(zone_, __ objects()->length(), Heap::Tenure_Old));
1158 for (size_t i = 0; i < __ objects()->length(); i++)
1159 objects->set(zone_, i, *(__ objects()->at(i)));
1161 Local<ByteArray> safepoints(zone_);
1163 // If any stack slots hold gc pointers at potential failure points in the
1164 // bytecode, record them now. We do this by building a list of tuples;
1165 // each tuple contains the pc offset, and a bitset containing which stack
1166 // slots must be scanned by the gc.
1167 if (__ oopRecords()->length()) {
1168 size_t bytesPerSafepoint = Code::BytesPerSafepoint(__ maxStackDepth());
1169 size_t gcmapSize = bytesPerSafepoint * __ oopRecords()->length();
1170 safepoints = ByteArray::New(zone_, gcmapSize, Heap::Tenure_Old);
1174 Address cursor = safepoints->raw();
1175 for (size_t i = 0; i < __ oopRecords()->length(); i++) {
1176 OopRecord *record = __ oopRecords()->at(i);
1177 assert(record->depth <= __ maxStackDepth());
1179 *reinterpret_cast<unsigned *>(cursor) = record->offset;
1181 unsigned char *bits = reinterpret_cast<unsigned char *>(cursor + sizeof(unsigned));
1182 for (unsigned i = 0; i < record->depth; i++)
1183 bits[i / 8] |= (1 << (i % 8));
1185 cursor += bytesPerSafepoint;
1188 assert(cursor == safepoints->raw() + gcmapSize);
1191 Local<ByteArray> sourcemap(zone_);
1192 if (__ sourcemapLength()) {
1193 sourcemap = ByteArray::New(zone_, __ sourcemapLength(), Heap::Tenure_Old);
1197 memcpy(sourcemap->raw(), __ sourcemap(), __ sourcemapLength());
1200 Local<Code> code(zone_);
1202 code = Code::New(zone_,
1207 moduleData_->module,
1215 BytecodeCompiler::compileFunction(ModuleData *module, FunctionStatement *node)
1217 // Note: No need to record a life slot here, since it's part of the Frame.
1218 AutoEnterScope functionScope(this, node->scope());
1220 // Set the initial line, because line mappings are deltas.
1221 __ setFirstLine(node->pos().line);
1222 locals_ = FixedArray::New(zone_, node->scope()->maxContainedLocals(), Heap::Tenure_Old);
1224 node->body()->accept(this);
1226 unsigned nargs = node->scope()->numArguments();
1227 Local<FixedArray> args(zone_, FixedArray::New(zone_, nargs, Heap::Tenure_Old));
1231 for (size_t i = 0; i < node->scope()->numArguments(); i++)
1232 args->set(zone_, i, node->scope()->getArgument(i)->type());
1235 Local<Code> code(zone_, compileCode(node->scope(), node->pos().line));
1239 Local<Type> type(zone_, node->fun()->type());
1240 Local<String> name(zone_, node->fun()->name());
1241 Local<Function> fun(zone_, Function::New(zone_, code, type, name, node->pos()));
1245 // If this function had a forward, export it as a named public.
1246 if (node->fun()->isPublic()) {
1247 assert(node->fun()->isPublic());
1248 ScopedRoot<Function> root(fun);
1251 if (!moduleData_->publics.append(root))
1256 Disassemble(code, stdout);
1263 BytecodeCompiler::compile()
1265 AutoEnterScope scope(this, tree_->scope());
1267 ModuleData moduleData;
1269 moduleData_ = &moduleData;
1270 moduleData_->module = Module::New(zone_, tree_->scope()->numFunctions());
1275 moduleData_->natives = FixedArray::New(zone_, tree_->scope()->numNatives(), Heap::Tenure_Old);
1276 if (!moduleData_->natives)
1279 for (size_t i = 0; i < tree_->statements()->length(); i++) {
1280 Statement *statement = tree_->statements()->at(i);
1281 statement->accept(this);
1284 if (zone_->hasPendingException())
1288 for (size_t i = 0; i < tree_->scope()->numFunctions(); i++)
1289 assert(moduleData_->module->getFunction(i));
1290 for (size_t i = 0; i < tree_->scope()->numNatives(); i++)
1291 assert(moduleData_->natives->at(i));
1294 if (moduleData_->publics.length()) {
1295 Local<Function> fun(zone_);
1296 Local<FixedArray> list(zone_, FixedArray::New(zone_, moduleData_->publics.length(),
1301 for (size_t i = 0; i < moduleData_->publics.length(); i++)
1302 list->set(zone_, i, moduleData_->publics[i]);
1304 moduleData_->module->setPublics(list);
1307 moduleData_->module->setNatives(moduleData_->natives);
1309 if (scope_->numEnvironmentVars()) {
1310 Local<EnvironmentMap> globalMap(zone_, scope_->createEnvironmentMap(zone_));
1314 Local<Environment> environment(zone_, Environment::New(zone_, globalMap));
1318 moduleData_->module->setEnvironment(environment);
1321 Local<Code> code(zone_, compileCode(tree_->scope(), 1));
1325 Disassemble(code, stdout);
1327 moduleData_->module->setCode(code);
1329 return moduleData_->module;