Implement re-tag unary expression.
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())
443 Local<Type> from(zone_, node->expression()->type());
444 Local<Type> to(zone_, node->type());
446 node->expression()->accept(this);
447 if (!from->isFloat() && to->isFloat())
449 else if (from->isFloat() && !to->isFloat())
455 assert(node->token() == TOK_TILDE);
456 node->expression()->accept(this);
463 BytecodeCompiler::visit(BinaryExpression *node)
465 if (node->token() == TOK_AND || node->token() == TOK_OR) {
466 Label success, failure, done;
467 visitForTest(node, &success, &failure, &success);
470 __ drop(1); // Otherwise, the stack depth will be +1 too much.
478 Local<Type> leftType(zone_, node->left()->type());
479 Local<Type> rightType(zone_, node->right()->type());
480 Local<Type> coerce(zone_, GetCoercionType(node->token(), leftType, rightType));
482 visitForALU(coerce, node->left());
483 visitForALU(coerce, node->right());
485 Opcode op = TokenToOpcode(node->token());
486 if (node->type()->isFloat())
487 op = (Opcode)(int(op) + (OP_ADD_F - OP_ADD));
489 __ note_position(node->pos());
494 BytecodeCompiler::visit(IndexExpression *node)
496 node->left()->accept(this);
497 node->right()->accept(this);
498 __ note_position(node->pos());
501 if (node->type()->isArray())
504 __ getarray(node->type()->primitive());
508 BytecodeCompiler::visit(ReturnStatement *node)
510 if (node->expression()) {
511 node->expression()->accept(this);
519 BytecodeCompiler::visitForTest(Expression *expression,
524 TokenKind token = ToCompare(expression);
525 if (token == TOK_EOF || token == TOK_NOT) {
526 if (token == TOK_EOF)
527 expression->accept(this);
529 expression->toUnaryExpression()->expression()->accept(this);
531 bool jumpOnTrue = (fallthrough == falseBranch) ^ (token == TOK_NOT);
533 Opcode op = jumpOnTrue ? OP_JT : OP_JF;
534 if (expression->type()->isFloat())
535 op = (Opcode)(int(op) + (OP_JL_F - OP_JL));
537 if (fallthrough == falseBranch)
538 __ j(op, trueBranch);
540 __ j(op, falseBranch);
544 BinaryExpression *binary = expression->toBinaryExpression();
546 if (token == TOK_AND || token == TOK_OR) {
548 if (token == TOK_AND)
549 visitForTest(binary->left(), &next, falseBranch, &next);
551 visitForTest(binary->left(), trueBranch, &next, &next);
553 visitForTest(binary->right(), trueBranch, falseBranch, fallthrough);
557 Opcode op = CompareTokenToJump(token);
558 if (fallthrough == trueBranch)
561 Local<Type> leftType(zone_, binary->left()->type());
562 Local<Type> rightType(zone_, binary->right()->type());
563 Local<Type> coerce(zone_, GetCoercionType(binary->token(), leftType, rightType));
565 visitForALU(coerce, binary->left());
566 visitForALU(coerce, binary->right());
567 if (coerce->isFloat())
568 op = (Opcode)(int(op) + (OP_JL_F - OP_JL));
570 if (fallthrough == trueBranch)
571 __ j(op, falseBranch);
573 __ j(op, trueBranch);
577 BytecodeCompiler::visit(ForStatement *node)
579 AutoEnterScope forScope(this, node->scope());
581 recordLifoSlot(node->scope());
584 LoopScope loop(scope_, &join, &update, &loop_);
586 if (node->initialization())
587 node->initialization()->accept(this);
590 if (node->condition())
594 node->body()->accept(this);
598 node->update()->accept(this);
600 if (node->condition()) {
602 visitForTest(node->condition(), &header, &join, &join);
610 unwindTo(node->scope()->enclosing());
611 assert(__ stackDepth() == 0);
615 BytecodeCompiler::visit(WhileStatement *node)
621 LoopScope loop(scope_, &join, &header, &loop_);
623 if (node->token() == TOK_WHILE) {
626 visitForTest(node->condition(), &body, &join, &body);
628 node->body()->accept(this);
631 node->body()->accept(this);
632 visitForTest(node->condition(), &header, &join, &join);
639 BytecodeCompiler::visit(BreakStatement *node)
641 unwindTo(loop_->scope());
642 __ jump(loop_->break_());
646 BytecodeCompiler::visit(ContinueStatement *node)
648 unwindTo(loop_->scope());
649 __ jump(loop_->continue_());
653 BytecodeCompiler::visit(BlockStatement *node)
655 AutoEnterScope blockScope(this, node->scope());
657 recordLifoSlot(node->scope());
659 for (size_t i = 0; i < node->statements()->length(); i++) {
660 Statement *statement = node->statements()->at(i);
661 statement->accept(this);
662 assert(__ stackDepth() == 0);
665 // We don't bother emitting an "unwind" instruction for function scopes,
666 // since this is taken care of by the calling convention.
667 if (node->scope() && node->scope()->enclosing()->kind() != Scope::FUNCTION)
668 unwindTo(node->scope()->enclosing());
672 BytecodeCompiler::visit(IntegerLiteral *node)
674 __ int_(node->value());
678 BytecodeCompiler::visit(FloatLiteral *node)
680 __ float_((float)node->value());
683 static inline ArrayMap *
684 BuildArrayMap(Zone *zone, Handle<Type> type)
686 Local<ArrayMap> contained(zone);
687 if (type->levels() > 1) {
688 Local<Type> containedType(zone, type->contained());
689 contained = BuildArrayMap(zone, containedType);
694 return ArrayMap::New(zone, type, contained);
698 BytecodeCompiler::visit(StringLiteral *node)
700 Local<Type> type(zone_, node->type());
701 Local<ArrayMap> map(zone_, BuildArrayMap(zone_, type));
705 Local<Array> array(zone_, Array::New(zone_, map, node->string()->length(), Heap::Tenure_Old));
709 assert(array->nelements() >= node->string()->length());
710 memcpy(array->chars(), node->string()->raw(), node->string()->length() * sizeof(char));
712 __ note_position(node->pos());
717 BytecodeCompiler::getEnvSlot(Variable *var)
719 assert(var->scope()->kind() == Scope::GLOBAL);
724 BytecodeCompiler::setEnvSlot(Variable *var)
726 assert(var->scope()->kind() == Scope::GLOBAL);
731 BytecodeCompiler::visit(VariableDeclaration *node)
733 Variable *var = node->variable();
735 Local<Type> type(zone_, var->type());
736 if (type->isArray()) {
737 Local<ArrayMap> map(zone_, BuildArrayMap(zone_, type));
738 __ note_position(node->pos());
739 if (var->scope()->kind() == Scope::GLOBAL)
740 __ newarray(map, Heap::Tenure_Old);
741 else if (var->needsHeapAllocation())
742 __ newarray(map, Heap::Tenure_Default);
744 __ newarray(map, Heap::Tenure_Stack);
746 if (node->initialization()) {
747 node->initialization()->accept(this);
748 __ note_position(node->pos());
752 if (node->initialization()) {
753 node->initialization()->accept(this);
755 if (!node->postDimensions())
760 if (var->location() == Variable::STACK) {
762 locals_->set(zone_, var->slot(), var->type());
764 assert(var->location() == Variable::ENVIRONMENT);
772 BytecodeCompiler::visit(CallExpression *node)
774 Local<Type> funType(zone_, node->callee()->type());
776 // Sniff out natives, which have a specific opcode and are guaranteed to
777 // be called via name proxy.
778 NamedFunction *native = NULL;
779 if (funType->isNative()) {
780 native = node->callee()->toNameProxy()->binding()->toNamedFunction();
783 for (size_t i = node->arguments()->length() - 1; i < node->arguments()->length(); i--) {
784 Expression *arg = node->arguments()->at(i);
786 // We need to compute a reference if the parameter was in the form:
788 // Note this form does not allow: f({})
790 // We also need to compute references for all variadic native
791 // arguments, but arrays and references are already in the
793 Local<Type> given(zone_, arg->type());
794 bool mustPushReference = false;
795 if (i >= funType->parameters()->length()) {
796 assert(funType->isNative() && funType->isNativeVariadic());
797 mustPushReference = !given->isArray() && !given->isReference();
798 } else if (funType->parameterAt(i)->isReference()) {
799 mustPushReference = !given->isReference();
802 // If a native is passed to a native, it must only be one level deep.
803 assert(!funType->isNative() || !given->isArray() || given->levels() == 1);
805 if (mustPushReference) {
806 if (arg->isNameProxy()) {
807 // :TODO: test with functions and globals
808 // Compute a reference to the name.
809 Variable *var = arg->toNameProxy()->binding()->toVariable();
810 __ note_position(node->pos());
812 } else if (arg->isIndexExpression()) {
813 IndexExpression *expr = arg->toIndexExpression();
814 expr->left()->accept(this);
815 expr->right()->accept(this);
816 __ note_position(expr->pos());
820 // We don't know how to, or can't, build a direct reference to
821 // this type. Make an indirect one, by taking the top of the
822 // stack and boxing it up.
824 __ note_position(node->pos());
832 __ note_position(node->pos());
834 __ callnative(native->slot(), node->arguments()->length());
835 __ drop(node->arguments()->length());
837 node->callee()->accept(this);
839 __ drop(node->arguments()->length() + 1);
844 BytecodeCompiler::visit(TernaryExpression *node)
846 Label success, failure, join;
848 visitForTest(node->condition(), &success, &failure, &success);
850 node->left()->accept(this);
854 node->right()->accept(this);
859 BytecodeCompiler::visit(IfStatement *node)
862 if (!node->ifFalse()) {
865 visitForTest(node->condition(), &success, &join, &success);
867 node->ifTrue()->accept(this);
871 visitForTest(node->condition(), &success, &next, &success);
873 node->ifTrue()->accept(this);
876 node->ifFalse()->accept(this);
883 BytecodeCompiler::visit(FunctionStatement *node)
885 if (!node->fun()->used())
888 if (node->fun()->isNative()) {
889 assert(!moduleData_->natives->at(node->fun()->slot()));
891 Local<Type> type(zone_, node->fun()->type());
892 Local<String> name(zone_, node->fun()->name());
893 Local<Native> native(zone_, Native::New(zone_, type, name));
897 moduleData_->natives->set(zone_, node->fun()->slot(), native);
901 // If the function has no body, then it's just a declaration.
903 assert(node->fun()->isForward() || node->fun()->isPublic());
907 BytecodeCompiler child(zone_, tree_, moduleData_);
908 Local<Function> fun(zone_, child.compileFunction(moduleData_, node));
912 assert(!moduleData_->module->getFunction(node->fun()->slot()));
913 moduleData_->module->setFunction(zone_, node->fun()->slot(), fun);
917 BytecodeCompiler::visit(EnumStatement *node)
919 // :TODO: eventually, we'll export these.
923 BytecodeCompiler::compileCode(Scope *scope, unsigned lineno)
925 // STOP doubles as RETURNVOID.
928 if (__ oom() || zone_->hasPendingException())
931 Local<ByteArray> bytes(zone_, ByteArray::New(zone_, __ length() * sizeof(bytecode), Heap::Tenure_Old));
934 memcpy(bytes->raw(), __ buffer(), __ length());
936 for (size_t i = 0; i < scope->maxContainedLocals(); i++)
937 assert(locals_->at(i));
939 Local<FixedArray> objects(zone_, FixedArray::New(zone_, __ objects()->length(), Heap::Tenure_Old));
943 for (size_t i = 0; i < __ objects()->length(); i++)
944 objects->set(zone_, i, *(__ objects()->at(i)));
946 Local<ByteArray> safepoints(zone_);
948 // If any stack slots hold gc pointers at potential failure points in the
949 // bytecode, record them now. We do this by building a list of tuples;
950 // each tuple contains the pc offset, and a bitset containing which stack
951 // slots must be scanned by the gc.
952 if (__ oopRecords()->length()) {
953 size_t bytesPerSafepoint = Code::BytesPerSafepoint(__ maxStackDepth());
954 size_t gcmapSize = bytesPerSafepoint * __ oopRecords()->length();
955 safepoints = ByteArray::New(zone_, gcmapSize, Heap::Tenure_Old);
959 Address cursor = safepoints->raw();
960 for (size_t i = 0; i < __ oopRecords()->length(); i++) {
961 OopRecord *record = __ oopRecords()->at(i);
962 assert(record->depth <= __ maxStackDepth());
964 *reinterpret_cast<unsigned *>(cursor) = record->offset;
966 unsigned char *bits = reinterpret_cast<unsigned char *>(cursor + sizeof(unsigned));
967 for (unsigned i = 0; i < record->depth; i++)
968 bits[i / 8] |= (1 << (i % 8));
970 cursor += bytesPerSafepoint;
973 assert(cursor == safepoints->raw() + gcmapSize);
976 Local<ByteArray> sourcemap(zone_);
977 if (__ sourcemapLength()) {
978 sourcemap = ByteArray::New(zone_, __ sourcemapLength(), Heap::Tenure_Old);
982 memcpy(sourcemap->raw(), __ sourcemap(), __ sourcemapLength());
985 Local<Code> code(zone_);
987 code = Code::New(zone_,
1000 BytecodeCompiler::compileFunction(ModuleData *module, FunctionStatement *node)
1002 // Note: No need to record a life slot here, since it's part of the Frame.
1003 AutoEnterScope functionScope(this, node->scope());
1005 // Set the initial line, because line mappings are deltas.
1006 __ setFirstLine(node->pos().line);
1007 locals_ = FixedArray::New(zone_, node->scope()->maxContainedLocals(), Heap::Tenure_Old);
1009 node->body()->accept(this);
1011 unsigned nargs = node->scope()->numArguments();
1012 Local<FixedArray> args(zone_, FixedArray::New(zone_, nargs, Heap::Tenure_Old));
1016 for (size_t i = 0; i < node->scope()->numArguments(); i++)
1017 args->set(zone_, i, node->scope()->getArgument(i)->type());
1020 Local<Code> code(zone_, compileCode(node->scope(), node->pos().line));
1024 Local<Type> type(zone_, node->fun()->type());
1025 Local<String> name(zone_, node->fun()->name());
1026 Local<Function> fun(zone_, Function::New(zone_, code, type, name, node->pos()));
1030 // If this function had a forward, export it as a named public.
1031 if (node->fun()->isPublic()) {
1032 assert(node->fun()->isPublic());
1033 ScopedRoot<Function> root(fun);
1036 if (!moduleData_->publics.append(root))
1040 Disassemble(code, stdout);
1046 BytecodeCompiler::compile()
1048 AutoEnterScope scope(this, tree_->scope());
1050 ModuleData moduleData;
1052 moduleData_ = &moduleData;
1053 moduleData_->module = Module::New(zone_, tree_->scope()->numFunctions());
1058 moduleData_->natives = FixedArray::New(zone_, tree_->scope()->numNatives(), Heap::Tenure_Old);
1059 if (!moduleData_->natives)
1062 for (size_t i = 0; i < tree_->statements()->length(); i++) {
1063 Statement *statement = tree_->statements()->at(i);
1064 statement->accept(this);
1067 if (zone_->hasPendingException())
1071 for (size_t i = 0; i < tree_->scope()->numFunctions(); i++)
1072 assert(moduleData_->module->getFunction(i));
1073 for (size_t i = 0; i < tree_->scope()->numNatives(); i++)
1074 assert(moduleData_->natives->at(i));
1077 if (moduleData_->publics.length()) {
1078 Local<Function> fun(zone_);
1079 Local<FixedArray> list(zone_, FixedArray::New(zone_, moduleData_->publics.length(),
1084 for (size_t i = 0; i < moduleData_->publics.length(); i++)
1085 list->set(zone_, i, moduleData_->publics[i]);
1087 moduleData_->module->setPublics(list);
1090 moduleData_->module->setNatives(moduleData_->natives);
1092 if (scope_->numEnvironmentVars()) {
1093 Local<EnvironmentMap> globalMap(zone_, scope_->createEnvironmentMap(zone_));
1097 Local<Environment> environment(zone_, Environment::New(zone_, globalMap));
1101 moduleData_->module->setEnvironment(environment);
1104 Local<Code> code(zone_, compileCode(tree_->scope(), 1));
1108 Disassemble(code, stdout);
1110 moduleData_->module->setCode(code);
1112 return moduleData_->module;