Re-introduce definite return analysis.
1 /* vim: set ts=4 sw=4 tw=99 et:
3 * Copyright (C) 2012 David Anderson
5 * This file is part of SourcePawn.
7 * SourcePawn 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 * SourcePawn 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 * SourcePawn. If not, see http://www.gnu.org/licenses/.
21 #include "../Strings.h"
22 #include "../NativeTable.h"
23 #include "../TypeManager.h"
24 #include "../Modules.h"
26 #include "SemanticAnalysis.h"
27 #include "../Heap-inl.h"
33 typedef BytecodeEmitter::Label Label;
38 AutoEnterScope(Scope **prevp, Scope *scope)
47 assert(prev_ == scope->enclosing());
60 SemanticAnalysis::SemanticAnalysis(Zone *zone, CompileContext &cc, TranslationUnit *unit)
72 SemanticAnalysis::SemanticAnalysis(SemanticAnalysis *parent, Handle<FunctionType> fun)
73 : zone_(parent->zone_),
78 scope_(parent->scope_),
80 module_(parent->module_),
89 SemanticAnalysis::analyze()
91 scope_ = unit_->globalScope();
93 module_ = Module::New(zone_);
95 for (size_t i = 0; i < unit_->tree()->statements()->length(); i++) {
96 Statement *stmt = unit_->tree()->statements()->at(i);
100 Local<Struct> globals(zone_, unit_->globalScope()->build(zone_));
103 module_->setGlobals(globals);
105 Local<Code> code(zone_, __ finish());
108 code->setModule(module_);
109 module_->setCode(code);
112 // Disassemble(code, stdout);
115 unit_->module_ = module_;
119 SemanticAnalysis::visitFunctionStatement(FunctionStatement *stmt)
121 FunctionSymbol *sym = stmt->sym();
122 Local<FunctionType> type(zone_, sym->type());
124 assert(scope_->kind() == Scope::GLOBAL);
126 if (stmt->token() == TOK_NATIVE) {
127 // Define the native now.
129 if (!zone_->nativeTable()->add(stmt->name(), &index))
132 Local<Native> native(zone_, Native::New(zone_, type, index));
141 // If the function is a forward or native, we don't have to do anything.
142 if (stmt->token() == TOK_NATIVE || stmt->token() == TOK_FORWARD)
145 SemanticAnalysis child(this, type);
146 Local<Function> funobj(zone_, child.compile(stmt));
152 if (stmt->token() == TOK_PUBLIC)
159 SemanticAnalysis::compile(FunctionStatement *stmt)
161 __ setFirstLine(stmt->pos().line);
163 AutoEnterScope argScope(&scope_, stmt->argScope());
165 for (size_t i = 0; i < stmt->signature().parameters()->length(); i++) {
166 Parameter *param = stmt->signature().parameters()->at(i);
167 param->sym()->allocate(VariableSymbol::Arg, i);
170 AutoEnterScope varScope(&scope_, stmt->varScope());
171 ControlStatus status = visitForControl(stmt->body());
173 if (!fun_->returnType()->isVoid()) {
174 // If the function is not void, report if not all paths return a value.
175 // All other incorrect return cases have been caught already.
176 if (status.returns() == Returns_Sometimes) {
177 cc_.reportError(stmt->pos(), Message_NotAllPathsReturnValue);
181 if (status.returns() == Returns_Never) {
182 cc_.reportError(stmt->pos(), Message_MissingReturnValue);
187 Local<Code> code(zone_, __ finish());
190 code->setModule(module_);
192 Local<Function> fun(zone_, Function::New(zone_, code, fun_, stmt->name(), stmt->pos()));
197 // Disassemble(code, stdout);
204 SemanticAnalysis::visitBlockStatement(BlockStatement *node)
206 AutoEnterScope scope(&scope_, node->scope());
208 for (size_t i = 0; i < node->statements()->length(); i++) {
209 Statement *stmt = node->statements()->at(i);
210 __ note_position(stmt->pos());
212 assert(__ stackDepth() == 0);
217 SemanticAnalysis::visitExpressionStatement(ExpressionStatement *node)
219 // While building HIR, we enter new pool and root scopes, since HIR
220 // creation is purely temporary.
221 PoolScope poolScope(zone_->pool());
222 RootScope rootScope(zone_);
224 HIR *hir = eval(node->expression());
229 if (!hir->type()->isVoid())
234 SemanticAnalysis::ControlScope::merge(const ControlStatus &left, const ControlStatus &right)
236 // If both sides terminate in a return, we consider this a return as well.
237 if (left.returns() == Returns_Always && right.returns() == Returns_Always) {
238 terminate(Returns_Always);
242 ReturnStatus status = (left.returns() == Returns_Never && right.returns() == Returns_Never)
246 if (left.terminates() && right.terminates())
252 SemanticAnalysis::ControlStatus
253 SemanticAnalysis::visitForControl(Statement *statement)
255 ControlScope scope(&control_);
256 statement->accept(this);
257 return scope.status();
261 SemanticAnalysis::visitIfStatement(IfStatement *node)
265 ControlStatus trueBranch;
266 ControlStatus falseBranch(false, Returns_Never);
268 if (!node->ifFalse()) {
271 visitForTest(node->condition(), &success, &join, &success);
273 trueBranch = visitForControl(node->ifTrue());
277 visitForTest(node->condition(), &success, &next, &success);
279 trueBranch = visitForControl(node->ifTrue());
282 falseBranch = visitForControl(node->ifFalse());
287 control_->merge(trueBranch, falseBranch);
291 SemanticAnalysis::requireLifoStack()
296 loop_->setUsesLifoStack();
299 SemanticAnalysis::ControlStatus
300 SemanticAnalysis::visitLoopBody(Statement *stmt)
302 // We always mark off a loop body, so on each edge, we can balance the
303 // LIFO stack. Right now, we don't have the ability to budget the LIFO
304 // stack ahead of time. If we turn out to never need the LIFO stack, we
305 // mark it as unnecessary. (The interpreter can't really make use of this,
308 // Note that balancing the LIFO stack isn't even necessary, so this
309 // feature may be removed. All this mechanism does is mitigate the
310 // possibility that a long-running loop will overflow the LIFO region
311 // and therefore start requiring nursery allocations.
312 int pos = __ enterloop();
313 ControlStatus status = visitForControl(stmt);
316 if (loop_->usesLifoStack())
317 __ setLoopUsesLifoStack(pos);
323 SemanticAnalysis::visitForStatement(ForStatement *node)
325 AutoEnterScope scope(&scope_, node->scope());
326 PoolScope poolScope(zone_->pool());
327 RootScope rootScope(zone_);
330 LoopScope loop(scope_, &join, &update, &loop_);
332 if (node->initialization())
333 node->initialization()->accept(this);
336 if (node->condition())
340 ControlStatus status = visitLoopBody(node->body());
344 node->update()->accept(this);
346 if (node->condition()) {
348 visitForTest(node->condition(), &header, &join, &join);
355 // If there was a condition, we treat this like a while loop. Otherwise,
356 // the join point is only reachable if the loop contains a break. The
357 // termination status doesn't tell us anything yet.
358 if (node->condition() || loop.breaks())
359 control_->merge(status, ControlStatus(false, Returns_Never));
361 control_->terminate(status.returns());
363 assert(__ stackDepth() == 0);
367 SemanticAnalysis::visitWhileStatement(WhileStatement *node)
369 PoolScope poolScope(zone_->pool());
370 RootScope rootScope(zone_);
376 ControlStatus status;
378 LoopScope loop(scope_, &join, &header, &loop_);
379 if (node->token() == TOK_WHILE) {
381 visitForTest(node->condition(), &body, &join, &body);
382 status = visitLoopBody(node->body());
385 status = visitLoopBody(node->body());
386 visitForTest(node->condition(), &header, &join, &join);
391 // Detect loops that will always have a fork in the contro-flow graph.
392 // This will be a |while| loop, or a |do-while| loop whose body does
393 // not terminate. For now, we treat these as an |if| regardless of the
394 // direction the branch can take. That means the control-flow is always
396 if (node->token() == TOK_WHILE || status.terminates() || loop.breaks()) {
397 control_->merge(status, ControlStatus(false, Returns_Never));
399 // At this point, we've got a do-while loop with a |return| or
400 // |continue|, meaning that the rest of the block is unreachable.
401 control_->terminate(status.returns());
404 assert(__ stackDepth() == 0);
407 static inline Heap::Tenure
408 InferTenure(Symbol *sym)
410 if (sym->scope()->kind() == Scope::GLOBAL)
411 return Heap::Tenure_Old;
413 // SP2's array semantics allow any array kind to escape, so we must use
414 // the normal heap. (Hopefully escape analysis can ease this pain later).
415 if (sym->type()->isArray())
416 return Heap::Tenure_Default;
418 return Heap::Tenure_Default;
422 SemanticAnalysis::visitVariableDeclaration(VariableDeclaration *node)
424 PoolScope poolScope(zone_->pool());
425 RootScope rootScope(zone_);
427 if (node->initialization()) {
430 if ((hir = eval(node->initialization())) == NULL)
432 if ((hir = coerce(hir, node->sym()->type(), Coerce_Assign)) == NULL)
437 if (node->sym()->type()->isInt32() ||
438 node->sym()->type()->isEnum() ||
439 node->sym()->type()->isChar() ||
440 node->sym()->type()->isBool())
443 } else if (node->sym()->type()->isFloat()) {
445 } else if (node->sym()->type()->isArray()) {
446 Local<ArrayType> type(zone_, ArrayType::cast(node->sym()->type()));
447 Local<ArrayMap> map(zone_, ArrayMap::Attach(zone_, type));
451 if (type->isFixedLength()) {
452 __ newarray(OP_NEWFIXED, map, InferTenure(node->sym()));
453 } else if (node->dims()) {
455 __ newarray(OP_NEWSIZED, map, InferTenure(node->sym()));
457 __ newarray(OP_NEWEMPTY, map, InferTenure(node->sym()));
462 if (!__ allocate(node->sym()))
470 SemanticAnalysis::visitReturnStatement(ReturnStatement *node)
472 control_->returns(Returns_Always);
474 if (!node->expression()) {
475 if (!fun_->returnType()->isVoid()) {
476 cc_.reportError(node->pos(), Message_MissingReturnValue);
484 if (fun_->returnType()->isVoid()) {
485 cc_.reportError(node->pos(), Message_UsedVoidReturn);
489 PoolScope poolScope(zone_->pool());
490 RootScope rootScope(zone_);
492 HIR *hir = eval(node->expression());
496 Local<Type> returnType(zone_, fun_->returnType());
497 if ((hir = coerce(hir, returnType, Coerce_Return)) == NULL)
502 if (hir->type()->isVoid())
509 SemanticAnalysis::visitBinaryExpression(BinaryExpression *node)
511 HIR *left = eval(node->left());
512 HIR *right = eval(node->right());
516 hir_ = binary(node, node->token(), left, right);
520 SemanticAnalysis::checkArgumentCount(Handle<FunctionType> type, unsigned actual)
522 if (type->parameters()->length() == actual)
525 if (actual > type->parameters()->length()) {
526 if (!type->isNative() || !type->isNativeVariadic())
531 if (!type->defaults())
534 // Missing arguments. See if there's a default argument for each missing
536 for (unsigned i = actual; i < type->parameters()->length(); i++) {
537 if (!type->defaults()->at(i))
545 SemanticAnalysis::visitNameProxy(NameProxy *proxy)
547 Symbol *sym = proxy->sym();
548 VariableSymbol *var = sym->asVariable();
550 Scope *in = sym->scope();
551 switch (in->kind()) {
553 hir_ = new (pool_) HGlobal(proxy, sym);
556 case Scope::FUNCTION:
557 assert(var->storage() == VariableSymbol::Arg);
558 hir_ = new (pool_) HLocal(proxy, var);
562 assert(in->kind() == Scope::BLOCK);
563 assert(var->storage() == VariableSymbol::Local);
564 hir_ = new (pool_) HLocal(proxy, var);
570 SemanticAnalysis::visitIntegerLiteral(IntegerLiteral *lit)
572 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
573 hir_ = new (pool_) HInteger(lit, type, lit->value());
577 SemanticAnalysis::visitFloatLiteral(FloatLiteral *node)
579 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Float));
580 hir_ = new (pool_) HFloat(node, type, (float)node->value());
584 SemanticAnalysis::visitCallExpression(CallExpression *node)
586 HIR *callee = eval(node->callee());
590 if (!callee->type()->isFunction()) {
591 cc_.reportError(node->pos(), Message_CalleeNotFunction);
595 Local<FunctionType> fun(zone_, FunctionType::cast(callee->type()));
597 if (!checkArgumentCount(fun, node->arguments()->length())) {
598 cc_.reportError(node->pos(), Message_ArgumentCountMismatch);
602 if (fun->isForward()) {
603 cc_.reportError(node->pos(), Message_ForwardNotImplemented, fun->name()->chars());
607 HIRList *args = new (pool_) HIRList;
608 for (unsigned i = 0; i < node->arguments()->length(); i++) {
609 Expression *expression = node->arguments()->at(i);
610 HIR *arg = eval(expression);
614 Handle<Type> given = arg->type();
616 bool mustComputeReference;
617 if (i >= fun->parameters()->length()) {
618 // Special handling for natives. Arguments past the formal must
619 // always have references computed. However, arrays are already
620 // references for natives.
621 assert(fun->isNative() && fun->isNativeVariadic());
622 mustComputeReference = !given->isReference() &&
625 Local<Type> actual(zone_, fun->parameterAt(i));
627 if (expression->isIndexExpression()) {
628 // Temporarily disabled.
629 assert(!actual->isArray());
630 if (actual->isReference()) {
631 cc_.reportError(expression->pos(), Message_CannotComputeIndexRef);
636 if (actual->isReference()) {
637 // If the actual is a reference, the coercion rules are much
638 // stricter; the contained types must be identical.
639 // :TODO: make this not an assert
640 assert(ReferenceType::cast(actual)->contained() == arg->type());
642 // When we start overloading, coercion will have to happen later.
643 arg = coerce(arg, actual, Coerce_Arg);
648 mustComputeReference = actual->isReference() && !given->isReference();
651 if (mustComputeReference) {
652 // Refs always use the LIFO stack if they can.
653 arg = new (pool_) HToRef(arg->node(), arg->type(), arg);
657 if (!args->append(arg))
661 hir_ = new (pool_) HCall(node, fun->returnType(), callee, args);
665 SemanticAnalysis::visitAssignment(Assignment *node)
667 HLValue *lval = lvalue(node->lvalue());
671 HIR *hir = eval(node->expression());
672 if ((hir = coerce(hir, lval->type(), Coerce_Assign)) == NULL)
675 hir_ = new (pool_) HStore(node, node->token(), lval, hir);
679 SemanticAnalysis::visitBreakStatement(BreakStatement *node)
682 cc_.reportError(node->pos(), Message_BreakOutsideLoop);
687 __ j(OP_BREAK, loop_->break_());
691 SemanticAnalysis::visitContinueStatement(ContinueStatement *node)
694 cc_.reportError(node->pos(), Message_ContinueOutsideLoop);
698 __ j(OP_CONTINUE, loop_->continue_());
702 SemanticAnalysis::visitIndexExpression(IndexExpression *node)
704 HIR *left = eval(node->left());
708 HIR *right = eval(node->right());
712 // Hrm... yes, for now, let's coerce here.
713 Local<Type> i32(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
714 if ((right = coerce(right, i32, Coerce_Arg)) == NULL)
717 // Do not coerce here, there's no reason to yet.
718 if (!left->type()->isArray()) {
719 cc_.reportError(node->left()->pos(), Message_IndexBaseMustBeArray);
723 hir_ = new (pool_) HIndex(node,
724 ArrayType::cast(left->type())->contained(),
730 SemanticAnalysis::visitIncDecExpression(IncDecExpression *node)
732 HLValue *lval = lvalue(node->expression());
736 if (!lval->type()->isInt32() && !lval->type()->isFloat()) {
742 if (lval->type()->isInt32())
743 rval = new (pool_) HInteger(node, lval->type(), 1);
745 rval = new (pool_) HFloat(node, lval->type(), 1.0);
748 hir_ = new (pool_) HPostIncDec(node, node->token(), lval, rval);
750 hir_ = new (pool_) HStore(node, node->token(), lval, rval);
754 SemanticAnalysis::coercionType(TokenKind token, HIR *left, HIR *right)
756 Handle<Type> l = left->type();
757 Handle<Type> r = right->type();
759 if (token >= TOK_PLUS && token <= TOK_SLASH) {
760 // We allow: [float|int32] + [float|int32]
761 if (l->isFloat() && r->isInt32())
763 if (l->isInt32() && r->isFloat())
765 if (l->isInt32() && r->isInt32())
776 SemanticAnalysis::typeCheckArray(const SourcePosition &pos,
777 Handle<Type> argGiven,
778 Handle<Type> argActual,
781 if (!argGiven->isArray()) {
782 cc_.reportError(pos, Message_ExpectedArray);
786 Local<ArrayType> actual(zone_, ArrayType::cast(argActual));
787 Local<ArrayType> given(zone_, ArrayType::cast(argGiven));
789 if (actual->levels() != given->levels()) {
790 cc_.reportError(pos, Message_ArrayDimensionsMismatch);
796 if (actual->isFixedLength()) {
797 if (kind == Coerce_Return || kind == Coerce_Assign) {
798 if (!given->isFixedLength()) {
799 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
803 if (actual->isCharArray()) {
804 // String assignment can have a truncated |given|.
805 if (given->fixedLength() > actual->fixedLength()) {
806 cc_.reportError(pos, Message_ArrayAssignmentTooBig);
810 if (given->fixedLength() != actual->fixedLength()) {
811 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
816 } else if (given->isFixedLength()) {
817 // We do not allow assignments in the form:
820 // Otherwise, the following code could break the size guarantees
821 // of the right-hand side:
831 // Now |x[0]| contains a 3-length array.
833 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
838 if (!given->contained()->isArray() || !actual->contained()->isArray())
841 given = ArrayType::cast(given->contained());
842 actual = ArrayType::cast(actual->contained());
845 // These arrays must contain the same innermost type.
846 if (given->contained() != actual->contained()) {
847 cc_.reportError(pos, Message_TypeMismatch,
848 GetTypeName(actual->contained()),
849 GetTypeName(given->contained()));
857 SemanticAnalysis::coerce(HIR *hir, Handle<Type> to, CoercionKind kind)
859 Handle<Type> from = hir->type();
861 if (from->isInt32() && to->isFloat())
862 return new (pool_) HConvert(hir->node(), to, OP_CVT_I2F, hir);
863 if (from->isInt32() && to->isBool())
864 return new (pool_) HConvert(hir->node(), to, OP_CVT_I2B, hir);
867 if (!typeCheckArray(SourcePosition(), from, to, kind))
876 SemanticAnalysis::set(VariableSymbol *sym)
878 if (sym->scope()->kind() == Scope::GLOBAL) {
881 assert(sym->storage() == VariableSymbol::Local);
887 SemanticAnalysis::binary(AstNode *node, TokenKind token, HIR *left, HIR *right)
889 Local<Type> coercion(zone_, coercionType(token, left, right));
892 if ((left = coerce(left, coercion, Coerce_Arg)) == NULL)
894 if ((right = coerce(right, coercion, Coerce_Arg)) == NULL)
909 return new (pool_) HBinary(node, left->type(), token, left, right);
920 Local<Type> result(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
921 return new (pool_) HBinary(node, result, token, left, right);
930 static inline TokenKind
931 ToCompare(Expression *expr)
933 if (expr->isBinaryExpression()) {
934 BinaryExpression *b = expr->toBinaryExpression();
935 if (b->token() >= TOK_EQUALS && b->token() <= TOK_OR)
937 } else if (expr->isUnaryExpression()) {
938 UnaryExpression *u = expr->toUnaryExpression();
939 if (u->token() == TOK_NOT)
946 SemanticAnalysis::visitForTest(Expression *expr,
951 Local<Type> boolType(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
953 TokenKind token = ToCompare(expr);
954 if (token == TOK_EOF || token == TOK_NOT) {
956 if (token == TOK_EOF)
959 hir = eval(expr->toUnaryExpression()->expression());
962 if ((hir = coerce(hir, boolType, Coerce_Assign)) == NULL)
967 bool jumpOnTrue = (fallthrough == falseBranch) ^ (token == TOK_NOT);
968 Opcode op = jumpOnTrue ? OP_JT : OP_JF;
970 if (fallthrough == falseBranch)
971 __ j(op, trueBranch);
973 __ j(op, falseBranch);
977 BinaryExpression *bin = expr->toBinaryExpression();
978 if (token == TOK_AND || token == TOK_OR) {
980 //visitForLogicTest(expr, trueBranch, falseBranch, fallthrough);
984 HIR *left = eval(bin->left());
985 HIR *right = eval(bin->right());
989 HIR *hir = binary(bin, bin->token(), left, right);
992 if ((hir = coerce(hir, boolType, Coerce_Assign)) == NULL)
996 if (fallthrough == trueBranch)
997 __ j(OP_JF, falseBranch);
999 __ j(OP_JT, trueBranch);
1003 SemanticAnalysis::lvalue(Expression *expr)
1005 HIR *hir = eval(expr);
1009 if (!hir->isLValue()) {
1010 cc_.reportError(expr->pos(), Message_ExpectedLValue);
1014 return static_cast<HLValue *>(hir);
1018 SemanticAnalysis::eval(Expression *expr)
1030 SemanticAnalysis::discharge(HIR *hir)
1032 EmitHIR(zone_, emitter_, hir);