Allow void to compare to void.
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"
32 typedef BytecodeEmitter::Label Label;
36 BytecodeCompiler::BytecodeCompiler(Zone *zone, ParseTree *tree, ModuleData *module)
39 emitter_(zone->pool()),
47 static inline TokenKind
48 ToCompare(Expression *expr)
50 if (expr->isBinaryExpression()) {
51 BinaryExpression *b = expr->toBinaryExpression();
52 if (b->token() >= TOK_EQUALS && b->token() <= TOK_OR)
54 } else if (expr->isUnaryExpression()) {
55 UnaryExpression *u = expr->toUnaryExpression();
56 if (u->token() == TOK_NOT)
63 CompareTokenToJump(TokenKind kind)
77 assert(kind == TOK_LE);
83 TokenToOpcode(TokenKind kind)
119 assert(kind == TOK_BITXOR);
125 BytecodeCompiler::recordLifoSlot(Scope *scope)
130 if (Variable *var = scope->lifoSlot()) {
131 locals_->set(zone_, var->slot(), var->type());
132 __ savelifo(var->slot());
137 BytecodeCompiler::unwindTo(Scope *scope)
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())
147 __ unwindlifo(var->slot());
151 BytecodeCompiler::visit(NameProxy *name)
153 switch (name->binding()->kind()) {
154 case BoundName::VARIABLE:
156 Variable *var = name->binding()->toVariable();
158 if (var->location() == Variable::STACK) {
160 assert(!name->type()->isReference());
161 } else if (var->location() == Variable::ENVIRONMENT) {
164 assert(var->location() == Variable::PARAMETER);
167 // If this argument is actually a reference, dereference it now.
168 if (var->type()->isReference())
169 __ getref(var->type()->contained()->primitive());
174 case BoundName::FUNCTION:
176 NamedFunction *fun = name->binding()->toNamedFunction();
178 __ getmodule_fn(fun->slot());
184 NamedConstant *constant = name->binding()->toNamedConstant();
185 __ int_(constant->value().toInt());
192 BytecodeCompiler::visit(ExpressionStatement *node)
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())
202 BytecodeCompiler::visit(Assignment *node)
204 // The first step is three sub-steps:
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.
211 if (node->lvalue()->isNameProxy()) {
212 NameProxy *proxy = node->lvalue()->toNameProxy();
213 Variable *var = proxy->binding()->toVariable();
216 if (var->type()->isReference() || var->type()->isArray())
219 // Get the value if needed.
220 if (node->token() != TOK_ASSIGN) {
221 // += etc is not allowed on arrays.
222 assert(!var->type()->isArray());
224 if (var->type()->isReference()) {
226 __ getref(var->type()->contained()->primitive());
232 IndexExpression *index = node->lvalue()->toIndexExpression();
233 __ note_position(index->pos());
235 // Note: Eventually, watch out for a whole here. An expression like:
237 // (a[4] = (5, a = []))
239 // Could shrink array, so we need to either bind a[i] to a Reference,
240 // or keep the bounds check near the set. This is just a semantic
242 index->left()->accept(this);
243 index->right()->accept(this);
245 if (node->token() != TOK_ASSIGN) {
248 if (node->type()->isArray())
251 __ getarray(node->type()->primitive());
255 if (node->token() == TOK_ASSIGN) {
256 node->expression()->accept(this);
258 visitForALU(node->type(), node->expression());
260 TokenKind alu = TokenKind(int(node->token()) - (TOK_ASSIGN_ADD - TOK_PLUS));
261 __ note_position(node->pos());
262 __ binary(TokenToOpcode(alu));
266 if (node->expression()->type()->isArray()) {
267 // Unlike references, which can only be computed from a NamePRoxy,
268 // arrays can be computed from multiple lvalue types.
269 __ note_position(node->pos());
271 } else if (node->lvalue()->isNameProxy()) {
272 NameProxy *proxy = node->lvalue()->toNameProxy();
273 Variable *var = proxy->binding()->toVariable();
275 if (var->type()->isReference())
276 __ setref(var->type()->contained()->primitive());
280 IndexExpression *index = node->lvalue()->toIndexExpression();
281 // :TODO: get rid of the BOUNDS instruction, embed it in g/setarray*?
282 // We can't emit it here because the stack is slightly out of position.
284 __ setarray(index->left()->type()->contained()->primitive());
289 BytecodeCompiler::visit(IncDecExpression *node)
291 // In the postfix case, the logic looks like:
293 // (2) Dup -> REF REF
294 // (3) Fetch -> REF VAL
295 // (4) Swap -> VAL REF
296 // (5) Pick -> VAL REF VAL
297 // (6) Add -> VAL REF VAL+1
298 // (7) Store -> VAL VAL+1
301 // In the prefix case, the logic looks like:
303 // (2) Dup -> REF REF
304 // (3) Fetch -> REF VAL
307 // (6) Add -> REF VAL+1
308 // (7) Store -> VAL+1
311 // This is squirrely enough such that we don't bother sharing too much
314 // Note: We simulate a "Pick" operation with a dup2+pop.
316 // This is steps (1) to (5).
317 Expression *expr = node->expression();
318 if (expr->isNameProxy()) {
319 NameProxy *proxy = expr->toNameProxy();
320 Variable *var = proxy->binding()->toVariable();
323 if (var->type()->isReference() || var->type()->isArray())
327 if (var->type()->isReference()) {
329 __ getref(node->type()->primitive());
330 if (node->postfix()) {
335 assert(!var->type()->isArray());
341 IndexExpression *index = expr->toIndexExpression();
342 __ note_position(index->pos());
344 index->left()->accept(this);
345 index->right()->accept(this);
347 assert(!node->type()->isArray());
350 __ getarray(node->type()->primitive());
352 if (node->postfix()) {
353 // The stack looks like this now:
356 // So we must use a PICK operation to rotate the stack into position.
357 __ roll3(); // INDEX VALUE ARRAY
358 __ roll3(); // VALUE ARRAY INDEX
359 __ pick3(); // VALUE ARRAY INDEX VALUE
364 if (node->type()->isFloat()) {
367 assert(node->type()->isInt32());
371 __ note_position(node->pos());
372 if (node->token() == TOK_INCREMENT)
378 if (expr->isNameProxy()) {
379 NameProxy *proxy = expr->toNameProxy();
380 Variable *var = proxy->binding()->toVariable();
382 if (var->type()->isReference())
383 __ setref(node->type()->primitive());
387 __ setarray(node->type()->primitive());
396 BytecodeCompiler::visitForALU(Type *needed, Expression *node)
399 if (needed->isFloat() && !node->type()->isFloat())
402 assert(needed->primitive() == node->type()->primitive());
406 GetCoercionType(TokenKind tok, Type *left, Type *right)
414 BytecodeCompiler::visit(UnaryExpression *node)
416 switch (node->token()) {
419 Local<Type> type(zone_, node->expression()->type());
420 node->expression()->accept(this);
422 if (node->type()->isFloat())
431 Local<Type> type(zone_, node->expression()->type());
432 node->expression()->accept(this);
434 if (node->type()->isFloat())
442 assert(node->token() == TOK_TILDE);
443 node->expression()->accept(this);
450 BytecodeCompiler::visit(BinaryExpression *node)
452 if (node->token() == TOK_AND || node->token() == TOK_OR) {
453 Label success, failure, done;
454 visitForTest(node, &success, &failure, &success);
457 __ drop(1); // Otherwise, the stack depth will be +1 too much.
465 Local<Type> leftType(zone_, node->left()->type());
466 Local<Type> rightType(zone_, node->right()->type());
467 Local<Type> coerce(zone_, GetCoercionType(node->token(), leftType, rightType));
469 visitForALU(coerce, node->left());
470 visitForALU(coerce, node->right());
472 Opcode op = TokenToOpcode(node->token());
473 if (node->type()->isFloat())
474 op = (Opcode)(int(op) + (OP_ADD_F - OP_ADD));
476 __ note_position(node->pos());
481 BytecodeCompiler::visit(IndexExpression *node)
483 node->left()->accept(this);
484 node->right()->accept(this);
485 __ note_position(node->pos());
488 if (node->type()->isArray())
491 __ getarray(node->type()->primitive());
495 BytecodeCompiler::visit(ReturnStatement *node)
497 if (node->expression()) {
498 node->expression()->accept(this);
506 BytecodeCompiler::visitForTest(Expression *expression,
511 TokenKind token = ToCompare(expression);
512 if (token == TOK_EOF || token == TOK_NOT) {
513 if (token == TOK_EOF)
514 expression->accept(this);
516 expression->toUnaryExpression()->expression()->accept(this);
518 bool jumpOnTrue = (fallthrough == falseBranch) ^ (token == TOK_NOT);
520 Opcode op = jumpOnTrue ? OP_JT : OP_JF;
521 if (expression->type()->isFloat())
522 op = (Opcode)(int(op) + (OP_JL_F - OP_JL));
524 if (fallthrough == falseBranch)
525 __ j(op, trueBranch);
527 __ j(op, falseBranch);
531 BinaryExpression *binary = expression->toBinaryExpression();
533 if (token == TOK_AND || token == TOK_OR) {
535 if (token == TOK_AND)
536 visitForTest(binary->left(), &next, falseBranch, &next);
538 visitForTest(binary->left(), trueBranch, &next, &next);
540 visitForTest(binary->right(), trueBranch, falseBranch, fallthrough);
544 Opcode op = CompareTokenToJump(token);
545 if (fallthrough == trueBranch)
548 Local<Type> leftType(zone_, binary->left()->type());
549 Local<Type> rightType(zone_, binary->right()->type());
550 Local<Type> coerce(zone_, GetCoercionType(binary->token(), leftType, rightType));
552 visitForALU(coerce, binary->left());
553 visitForALU(coerce, binary->right());
554 if (coerce->isFloat())
555 op = (Opcode)(int(op) + (OP_JL_F - OP_JL));
557 if (fallthrough == trueBranch)
558 __ j(op, falseBranch);
560 __ j(op, trueBranch);
564 BytecodeCompiler::visit(ForStatement *node)
566 AutoEnterScope forScope(this, node->scope());
568 recordLifoSlot(node->scope());
571 LoopScope loop(scope_, &join, &update, &loop_);
573 if (node->initialization())
574 node->initialization()->accept(this);
577 if (node->condition())
581 node->body()->accept(this);
585 node->update()->accept(this);
587 if (node->condition()) {
589 visitForTest(node->condition(), &header, &join, &join);
597 unwindTo(node->scope()->enclosing());
598 assert(__ stackDepth() == 0);
602 BytecodeCompiler::visit(WhileStatement *node)
608 LoopScope loop(scope_, &join, &header, &loop_);
610 if (node->token() == TOK_WHILE) {
613 visitForTest(node->condition(), &body, &join, &body);
615 node->body()->accept(this);
618 node->body()->accept(this);
619 visitForTest(node->condition(), &header, &join, &join);
626 BytecodeCompiler::visit(BreakStatement *node)
628 unwindTo(loop_->scope());
629 __ jump(loop_->break_());
633 BytecodeCompiler::visit(ContinueStatement *node)
635 unwindTo(loop_->scope());
636 __ jump(loop_->continue_());
640 BytecodeCompiler::visit(BlockStatement *node)
642 AutoEnterScope blockScope(this, node->scope());
644 recordLifoSlot(node->scope());
646 for (size_t i = 0; i < node->statements()->length(); i++) {
647 Statement *statement = node->statements()->at(i);
648 statement->accept(this);
649 assert(__ stackDepth() == 0);
652 // We don't bother emitting an "unwind" instruction for function scopes,
653 // since this is taken care of by the calling convention.
654 if (node->scope() && node->scope()->enclosing()->kind() != Scope::FUNCTION)
655 unwindTo(node->scope()->enclosing());
659 BytecodeCompiler::visit(IntegerLiteral *node)
661 __ int_(node->value());
665 BytecodeCompiler::visit(FloatLiteral *node)
667 __ float_((float)node->value());
670 static inline ArrayMap *
671 BuildArrayMap(Zone *zone, Handle<Type> type)
673 Local<ArrayMap> contained(zone);
674 if (type->levels() > 1) {
675 Local<Type> containedType(zone, type->contained());
676 contained = BuildArrayMap(zone, containedType);
681 return ArrayMap::New(zone, type, contained);
685 BytecodeCompiler::visit(StringLiteral *node)
687 Local<Type> type(zone_, node->type());
688 Local<ArrayMap> map(zone_, BuildArrayMap(zone_, type));
692 Local<Array> array(zone_, Array::New(zone_, map, node->string()->length(), Heap::Tenure_Old));
696 assert(array->nelements() >= node->string()->length());
697 memcpy(array->chars(), node->string()->raw(), node->string()->length() * sizeof(char));
699 __ note_position(node->pos());
704 BytecodeCompiler::getEnvSlot(Variable *var)
706 assert(var->scope()->kind() == Scope::GLOBAL);
711 BytecodeCompiler::setEnvSlot(Variable *var)
713 assert(var->scope()->kind() == Scope::GLOBAL);
718 BytecodeCompiler::visit(VariableDeclaration *node)
720 Variable *var = node->variable();
722 Local<Type> type(zone_, var->type());
723 if (type->isArray()) {
724 Local<ArrayMap> map(zone_, BuildArrayMap(zone_, type));
725 __ note_position(node->pos());
726 if (var->scope()->kind() == Scope::GLOBAL)
727 __ newarray(map, Heap::Tenure_Old);
728 else if (var->needsHeapAllocation())
729 __ newarray(map, Heap::Tenure_Default);
731 __ newarray(map, Heap::Tenure_Stack);
733 if (node->initialization()) {
734 node->initialization()->accept(this);
735 __ note_position(node->pos());
739 if (node->initialization()) {
740 node->initialization()->accept(this);
742 if (!node->postDimensions())
747 if (var->location() == Variable::STACK) {
749 locals_->set(zone_, var->slot(), var->type());
751 assert(var->location() == Variable::ENVIRONMENT);
759 BytecodeCompiler::visit(CallExpression *node)
761 Local<Type> funType(zone_, node->callee()->type());
763 // Sniff out natives, which have a specific opcode and are guaranteed to
764 // be called via name proxy.
765 NamedFunction *native = NULL;
766 if (funType->isNative()) {
767 native = node->callee()->toNameProxy()->binding()->toNamedFunction();
770 for (size_t i = node->arguments()->length() - 1; i < node->arguments()->length(); i--) {
771 Expression *arg = node->arguments()->at(i);
773 // We need to compute a reference if the parameter was in the form:
775 // Note this form does not allow: f({})
777 // We also need to compute references for all variadic native
778 // arguments, but arrays and references are already in the
780 Local<Type> given(zone_, arg->type());
781 bool mustPushReference = false;
782 if (i >= funType->parameters()->length()) {
783 assert(funType->isNative() && funType->isNativeVariadic());
784 mustPushReference = !given->isArray() && !given->isReference();
785 } else if (funType->parameterAt(i)->isReference()) {
786 mustPushReference = !given->isReference();
789 // If a native is passed to a native, it must only be one level deep.
790 assert(!funType->isNative() || !given->isArray() || given->levels() == 1);
792 if (mustPushReference) {
793 if (arg->isNameProxy()) {
794 // :TODO: test with functions and globals
795 // Compute a reference to the name.
796 Variable *var = arg->toNameProxy()->binding()->toVariable();
797 __ note_position(node->pos());
799 } else if (arg->isIndexExpression()) {
800 IndexExpression *expr = arg->toIndexExpression();
801 expr->left()->accept(this);
802 expr->right()->accept(this);
803 __ note_position(expr->pos());
807 // We don't know how to, or can't, build a direct reference to
808 // this type. Make an indirect one, by taking the top of the
809 // stack and boxing it up.
811 __ note_position(node->pos());
819 __ note_position(node->pos());
821 __ callnative(native->slot(), node->arguments()->length());
822 __ drop(node->arguments()->length());
824 node->callee()->accept(this);
826 __ drop(node->arguments()->length() + 1);
831 BytecodeCompiler::visit(TernaryExpression *node)
833 Label success, failure, join;
835 visitForTest(node->condition(), &success, &failure, &success);
837 node->left()->accept(this);
841 node->right()->accept(this);
846 BytecodeCompiler::visit(IfStatement *node)
849 if (!node->ifFalse()) {
852 visitForTest(node->condition(), &success, &join, &success);
854 node->ifTrue()->accept(this);
858 visitForTest(node->condition(), &success, &next, &success);
860 node->ifTrue()->accept(this);
863 node->ifFalse()->accept(this);
870 BytecodeCompiler::visit(FunctionStatement *node)
872 if (node->fun()->isNative()) {
873 assert(!moduleData_->natives->at(node->fun()->slot()));
875 Local<Type> type(zone_, node->fun()->type());
876 Local<String> name(zone_, node->fun()->name());
877 Local<Native> native(zone_, Native::New(zone_, type, name));
881 moduleData_->natives->set(zone_, node->fun()->slot(), native);
885 // If the function has no body, then it's just a declaration.
887 assert(node->fun()->isForward() || node->fun()->isPublic());
891 BytecodeCompiler child(zone_, tree_, moduleData_);
892 Local<Function> fun(zone_, child.compileFunction(moduleData_, node));
896 assert(!moduleData_->module->getFunction(node->fun()->slot()));
897 moduleData_->module->setFunction(zone_, node->fun()->slot(), fun);
901 BytecodeCompiler::visit(EnumStatement *node)
903 // :TODO: eventually, we'll export these.
907 BytecodeCompiler::compileCode(Scope *scope, unsigned lineno)
909 // STOP doubles as RETURNVOID.
912 if (__ oom() || zone_->hasPendingException())
915 Local<ByteArray> bytes(zone_, ByteArray::New(zone_, __ length() * sizeof(bytecode), Heap::Tenure_Old));
918 memcpy(bytes->raw(), __ buffer(), __ length());
920 for (size_t i = 0; i < scope->maxContainedLocals(); i++)
921 assert(locals_->at(i));
923 Local<FixedArray> objects(zone_, FixedArray::New(zone_, __ objects()->length(), Heap::Tenure_Old));
927 for (size_t i = 0; i < __ objects()->length(); i++)
928 objects->set(zone_, i, *(__ objects()->at(i)));
930 Local<ByteArray> safepoints(zone_);
932 // If any stack slots hold gc pointers at potential failure points in the
933 // bytecode, record them now. We do this by building a list of tuples;
934 // each tuple contains the pc offset, and a bitset containing which stack
935 // slots must be scanned by the gc.
936 if (__ oopRecords()->length()) {
937 size_t bytesPerSafepoint = Code::BytesPerSafepoint(__ maxStackDepth());
938 size_t gcmapSize = bytesPerSafepoint * __ oopRecords()->length();
939 safepoints = ByteArray::New(zone_, gcmapSize, Heap::Tenure_Old);
943 Address cursor = safepoints->raw();
944 for (size_t i = 0; i < __ oopRecords()->length(); i++) {
945 OopRecord *record = __ oopRecords()->at(i);
946 assert(record->depth <= __ maxStackDepth());
948 *reinterpret_cast<unsigned *>(cursor) = record->offset;
950 unsigned char *bits = reinterpret_cast<unsigned char *>(cursor + sizeof(unsigned));
951 for (unsigned i = 0; i < record->depth; i++)
952 bits[i / 8] |= (1 << (i % 8));
954 cursor += bytesPerSafepoint;
957 assert(cursor == safepoints->raw() + gcmapSize);
960 Local<ByteArray> sourcemap(zone_);
961 if (__ sourcemapLength()) {
962 sourcemap = ByteArray::New(zone_, __ sourcemapLength(), Heap::Tenure_Old);
966 memcpy(sourcemap->raw(), __ sourcemap(), __ sourcemapLength());
969 Local<Code> code(zone_);
971 code = Code::New(zone_,
984 BytecodeCompiler::compileFunction(ModuleData *module, FunctionStatement *node)
986 // Note: No need to record a life slot here, since it's part of the Frame.
987 AutoEnterScope functionScope(this, node->scope());
989 // Set the initial line, because line mappings are deltas.
990 __ setFirstLine(node->pos().line);
991 locals_ = FixedArray::New(zone_, node->scope()->maxContainedLocals(), Heap::Tenure_Old);
993 node->body()->accept(this);
995 unsigned nargs = node->scope()->numArguments();
996 Local<FixedArray> args(zone_, FixedArray::New(zone_, nargs, Heap::Tenure_Old));
1000 for (size_t i = 0; i < node->scope()->numArguments(); i++)
1001 args->set(zone_, i, node->scope()->getArgument(i)->type());
1004 Local<Code> code(zone_, compileCode(node->scope(), node->pos().line));
1008 Local<Type> type(zone_, node->fun()->type());
1009 Local<String> name(zone_, node->fun()->name());
1010 Local<Function> fun(zone_, Function::New(zone_, code, type, name, node->pos()));
1014 // If this function had a forward, export it as a named public.
1015 if (node->fun()->isPublic()) {
1016 assert(node->fun()->isPublic());
1017 ScopedRoot<Function> root(fun);
1020 if (!moduleData_->publics.append(root))
1024 Disassemble(code, stdout);
1030 BytecodeCompiler::compile()
1032 AutoEnterScope scope(this, tree_->scope());
1034 ModuleData moduleData;
1036 moduleData_ = &moduleData;
1037 moduleData_->module = Module::New(zone_, tree_->scope()->numFunctions());
1042 moduleData_->natives = FixedArray::New(zone_, tree_->scope()->numNatives(), Heap::Tenure_Old);
1043 if (!moduleData_->natives)
1046 for (size_t i = 0; i < tree_->statements()->length(); i++) {
1047 Statement *statement = tree_->statements()->at(i);
1048 statement->accept(this);
1051 if (zone_->hasPendingException())
1055 for (size_t i = 0; i < tree_->scope()->numFunctions(); i++)
1056 assert(moduleData_->module->getFunction(i));
1057 for (size_t i = 0; i < tree_->scope()->numNatives(); i++)
1058 assert(moduleData_->natives->at(i));
1061 if (moduleData_->publics.length()) {
1062 Local<Function> fun(zone_);
1063 Local<FixedArray> list(zone_, FixedArray::New(zone_, moduleData_->publics.length(),
1068 for (size_t i = 0; i < moduleData_->publics.length(); i++)
1069 list->set(zone_, i, moduleData_->publics[i]);
1071 moduleData_->module->setPublics(list);
1074 moduleData_->module->setNatives(moduleData_->natives);
1076 if (scope_->numEnvironmentVars()) {
1077 Local<EnvironmentMap> globalMap(zone_, scope_->createEnvironmentMap(zone_));
1081 Local<Environment> environment(zone_, Environment::New(zone_, globalMap));
1085 moduleData_->module->setEnvironment(environment);
1088 Local<Code> code(zone_, compileCode(tree_->scope(), 1));
1092 Disassemble(code, stdout);
1094 moduleData_->module->setCode(code);
1096 return moduleData_->module;