src/compiler/SemanticAnalysis.cpp
author David Anderson <dvander@alliedmods.net>
Sun Jan 27 17:34:30 2013 -0800 (2013-01-27)
changeset 261 219b49bf4a03
parent 259 99ab8b19f0b9
child 262 c4b1341297e5
permissions -rw-r--r--
Add support for importing enum types and enum values (as constexprs).
     1 /* vim: set ts=4 sw=4 tw=99 et:
     2  *
     3  * Copyright (C) 2012 David Anderson
     4  *
     5  * This file is part of SourcePawn.
     6  *
     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)
    10  * any later version.
    11  * 
    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.
    15  *
    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/.
    18  */
    19 #include <assert.h>
    20 #include "../Zone.h"
    21 #include "../Strings.h"
    22 #include "../NativeTable.h"
    23 #include "../TypeManager.h"
    24 #include "../Modules.h"
    25 #include "../Code.h"
    26 #include "SemanticAnalysis.h"
    27 #include "../Heap-inl.h"
    28 
    29 using namespace ke;
    30 
    31 #define __ emitter_.
    32 
    33 typedef BytecodeEmitter::Label Label;
    34 
    35 class AutoEnterScope
    36 {
    37   public:
    38     AutoEnterScope(Scope **prevp, Scope *scope)
    39       : prevp_(prevp),
    40         prev_(*prevp),
    41         scope_(scope)
    42     {
    43         if (!scope_)
    44             return;
    45         prev_ = *prevp_;
    46         *prevp_ = scope;
    47         assert(prev_ == scope->enclosing());
    48     }
    49     ~AutoEnterScope()
    50     {
    51         if (scope_)
    52             *prevp_ = prev_;
    53     }
    54   private:
    55     Scope **prevp_;
    56     Scope *prev_;
    57     Scope *scope_;
    58 };
    59 
    60 SemanticAnalysis::SemanticAnalysis(Zone *zone, CompileContext &cc, TranslationUnit *unit)
    61   : zone_(zone),
    62     pool_(zone->pool()),
    63     cc_(cc),
    64     unit_(unit),
    65     hir_(NULL),
    66     emitter_(pool_),
    67     loop_(NULL)
    68 {
    69 }
    70 
    71 SemanticAnalysis::SemanticAnalysis(SemanticAnalysis *parent, Handle<FunctionType> fun)
    72   : zone_(parent->zone_),
    73     pool_(parent->pool_),
    74     cc_(parent->cc_),
    75     unit_(parent->unit_),
    76     hir_(NULL),
    77     scope_(parent->scope_),
    78     emitter_(pool_),
    79     fun_(fun),
    80     loop_(NULL),
    81     control_(NULL)
    82 {
    83 
    84 }
    85 
    86 void
    87 SemanticAnalysis::analyze()
    88 {
    89     scope_ = unit_->globalScope();
    90 
    91     for (size_t i = 0; i < unit_->tree()->statements()->length(); i++) {
    92         Statement *stmt = unit_->tree()->statements()->at(i);
    93         stmt->accept(this);
    94     }
    95 
    96     Local<Code> code(zone_, __ finish());
    97     if (!code)
    98         return;
    99     code->setModule(unit_->module());
   100     unit_->module()->setCode(code);
   101 
   102 #ifndef NDEBUG
   103 //    Disassemble(code, stdout);
   104 #endif
   105 }
   106 
   107 void
   108 SemanticAnalysis::visitFunctionStatement(FunctionStatement *stmt)
   109 {
   110     FunctionSymbol *sym = stmt->sym();
   111     Local<FunctionType> type(zone_, sym->type());
   112 
   113     assert(scope_->kind() == Scope::GLOBAL);
   114 
   115     if (stmt->token() == TOK_NATIVE) {
   116         // Define the native now.
   117         size_t index;
   118         if (!zone_->nativeTable()->add(stmt->name(), &index))
   119             return;
   120 
   121         Local<Native> native(zone_, Native::New(zone_, type, index));
   122         if (!native)
   123             return;
   124 
   125         __ object(native);
   126         __ setglobal(sym);
   127         __ pop();
   128     }
   129 
   130     // If the function is a forward or native, we don't have to do anything.
   131     if (stmt->token() == TOK_NATIVE || stmt->token() == TOK_FORWARD)
   132         return;
   133 
   134     SemanticAnalysis child(this, type);
   135     Local<Function> funobj(zone_, child.compile(stmt));
   136     if (!funobj)
   137         return;
   138 
   139     __ object(funobj);
   140     __ setglobal(sym);
   141     if (stmt->token() == TOK_PUBLIC)
   142         __ public_();
   143     else
   144         __ pop();
   145 }
   146 
   147 Function *
   148 SemanticAnalysis::compile(FunctionStatement *stmt)
   149 {
   150     __ setFirstLine(stmt->pos().line);
   151 
   152     AutoEnterScope argScope(&scope_, stmt->argScope());
   153 
   154     for (size_t i = 0; i < stmt->signature().parameters()->length(); i++) {
   155         Parameter *param = stmt->signature().parameters()->at(i);
   156         param->sym()->allocate(VariableSymbol::Arg, i);
   157     }
   158 
   159     AutoEnterScope varScope(&scope_, stmt->varScope());
   160     ControlStatus status = visitForControl(stmt->body());
   161 
   162     if (!fun_->returnType()->isVoid()) {
   163         // If the function is not void, report if not all paths return a value.
   164         // All other incorrect return cases have been caught already.
   165         if (status.returns() == Returns_Sometimes) {
   166             cc_.reportError(stmt->pos(), Message_NotAllPathsReturnValue);
   167             return NULL;
   168         }
   169 
   170         if (status.returns() == Returns_Never) {
   171             cc_.reportError(stmt->pos(), Message_MissingReturnValue);
   172             return NULL;
   173         }
   174     }
   175 
   176     Local<Code> code(zone_, __ finish());
   177     if (!code)
   178         return NULL;
   179     code->setModule(unit_->module());
   180 
   181     Local<Function> fun(zone_, Function::New(zone_, code, fun_, stmt->name(), stmt->pos()));
   182     if (!fun)
   183         return NULL;
   184 
   185 #ifndef NDEBUG
   186 //    Disassemble(code, stdout);
   187 #endif
   188 
   189     return fun;
   190 }
   191 
   192 void 
   193 SemanticAnalysis::visitBlockStatement(BlockStatement *node)
   194 {
   195     AutoEnterScope scope(&scope_, node->scope());
   196 
   197     for (size_t i = 0; i < node->statements()->length(); i++) {
   198         Statement *stmt = node->statements()->at(i);
   199         __ note_position(stmt->pos());
   200         stmt->accept(this);
   201         assert(__ stackDepth() == 0);
   202     }
   203 }
   204 
   205 void
   206 SemanticAnalysis::visitEnumStatement(EnumStatement *node)
   207 {
   208 }
   209 
   210 void
   211 SemanticAnalysis::visitExpressionStatement(ExpressionStatement *node)
   212 {
   213     // While building HIR, we enter new pool and root scopes, since HIR
   214     // creation is purely temporary.
   215     PoolScope poolScope(zone_->pool());
   216     RootScope rootScope(zone_);
   217 
   218     HIR *hir = eval(node->expression());
   219     if (!hir)
   220         return;
   221 
   222     discharge(hir);
   223     if (!hir->type()->isVoid())
   224         __ pop();
   225 }
   226 
   227 void
   228 SemanticAnalysis::ControlScope::merge(const ControlStatus &left, const ControlStatus &right)
   229 {
   230     // If both sides terminate in a return, we consider this a return as well.
   231     if (left.returns() == Returns_Always && right.returns() == Returns_Always) {
   232         terminate(Returns_Always);
   233         return;
   234     }
   235 
   236     ReturnStatus status = (left.returns() == Returns_Never && right.returns() == Returns_Never)
   237                           ? Returns_Never
   238                           : Returns_Sometimes;
   239 
   240     if (left.terminates() && right.terminates())
   241         terminate(status);
   242     else
   243         returns(status);
   244 }
   245 
   246 SemanticAnalysis::ControlStatus
   247 SemanticAnalysis::visitForControl(Statement *statement)
   248 {
   249     ControlScope scope(&control_);
   250     statement->accept(this);
   251     return scope.status();
   252 }
   253 
   254 void
   255 SemanticAnalysis::visitIfStatement(IfStatement *node)
   256 {
   257     Label join;
   258 
   259     ControlStatus trueBranch;
   260     ControlStatus falseBranch(false, Returns_Never);
   261 
   262     if (!node->ifFalse()) {
   263         Label success;
   264 
   265         visitForTest(node->condition(), &success, &join, &success);
   266         __ bind(&success);
   267         trueBranch = visitForControl(node->ifTrue());
   268     } else {
   269         Label success, next;
   270 
   271         visitForTest(node->condition(), &success, &next, &success);
   272         __ bind(&success);
   273         trueBranch = visitForControl(node->ifTrue());
   274         __ jump(&join);
   275         __ bind(&next);
   276         falseBranch = visitForControl(node->ifFalse());
   277     }
   278 
   279     __ bind(&join);
   280 
   281     control_->merge(trueBranch, falseBranch);
   282 }
   283 
   284 void
   285 SemanticAnalysis::requireLifoStack()
   286 {
   287     if (!loop_)
   288         return;
   289 
   290     loop_->setUsesLifoStack();
   291 }
   292 
   293 SemanticAnalysis::ControlStatus
   294 SemanticAnalysis::visitLoopBody(Statement *stmt)
   295 {
   296     // We always mark off a loop body, so on each edge, we can balance the
   297     // LIFO stack. Right now, we don't have the ability to budget the LIFO
   298     // stack ahead of time. If we turn out to never need the LIFO stack, we
   299     // mark it as unnecessary. (The interpreter can't really make use of this,
   300     // but the JIT can).
   301     //
   302     // Note that balancing the LIFO stack isn't even necessary, so this
   303     // feature may be removed. All this mechanism does is mitigate the
   304     // possibility that a long-running loop will overflow the LIFO region
   305     // and therefore start requiring nursery allocations.
   306     int pos = __ enterloop();
   307     ControlStatus status = visitForControl(stmt);
   308     __ leaveloop();
   309 
   310     if (loop_->usesLifoStack())
   311         __ setLoopUsesLifoStack(pos);
   312 
   313     return status;
   314 }
   315 
   316 void
   317 SemanticAnalysis::visitForStatement(ForStatement *node)
   318 {
   319     AutoEnterScope scope(&scope_, node->scope());
   320     PoolScope poolScope(zone_->pool());
   321     RootScope rootScope(zone_);
   322 
   323     Label join, update;
   324     LoopScope loop(scope_, &join, &update, &loop_);
   325 
   326     if (node->initialization())
   327         node->initialization()->accept(this);
   328 
   329     Label header, test;
   330     if (node->condition())
   331         __ jump(&test);
   332 
   333     __ bind(&header);
   334     ControlStatus status = visitLoopBody(node->body());
   335 
   336     __ bind(&update);
   337     if (node->update())
   338         node->update()->accept(this);
   339 
   340     if (node->condition()) {
   341         __ bind(&test);
   342         visitForTest(node->condition(), &header, &join, &join);
   343     } else {
   344         __ jump(&header);
   345     }
   346 
   347     __ bind(&join);
   348     
   349     // If there was a condition, we treat this like a while loop. Otherwise,
   350     // the join point is only reachable if the loop contains a break. The
   351     // termination status doesn't tell us anything yet.
   352     if (node->condition() || loop.breaks())
   353         control_->merge(status, ControlStatus(false, Returns_Never));
   354     else
   355         control_->terminate(status.returns());
   356 
   357     assert(__ stackDepth() == 0);
   358 }
   359 
   360 void
   361 SemanticAnalysis::visitWhileStatement(WhileStatement *node)
   362 {
   363     PoolScope poolScope(zone_->pool());
   364     RootScope rootScope(zone_);
   365 
   366     Label header, join;
   367 
   368     __ bind(&header);
   369 
   370     ControlStatus status;
   371 
   372     LoopScope loop(scope_, &join, &header, &loop_);
   373     if (node->token() == TOK_WHILE) {
   374         Label body;
   375         visitForTest(node->condition(), &body, &join, &body);
   376         status = visitLoopBody(node->body());
   377         __ jump(&header);
   378     } else {
   379         status = visitLoopBody(node->body());
   380         visitForTest(node->condition(), &header, &join, &join);
   381     }
   382 
   383     __ bind(&join);
   384 
   385     // Detect loops that will always have a fork in the contro-flow graph.
   386     // This will be a |while| loop, or a |do-while| loop whose body does
   387     // not terminate. For now, we treat these as an |if| regardless of the
   388     // direction the branch can take. That means the control-flow is always
   389     // conditional.
   390     if (node->token() == TOK_WHILE || status.terminates() || loop.breaks()) {
   391         control_->merge(status, ControlStatus(false, Returns_Never));
   392     } else {
   393         // At this point, we've got a do-while loop with a |return| or
   394         // |continue|, meaning that the rest of the block is unreachable.
   395         control_->terminate(status.returns());
   396     }
   397 
   398     assert(__ stackDepth() == 0);
   399 }
   400 
   401 static inline Heap::Tenure
   402 InferTenure(Symbol *sym)
   403 {
   404     if (sym->scope()->kind() == Scope::GLOBAL)
   405         return Heap::Tenure_Old;
   406 
   407     // SP2's array semantics allow any array kind to escape, so we must use
   408     // the normal heap. (Hopefully escape analysis can ease this pain later).
   409     if (sym->type()->isArray())
   410         return Heap::Tenure_Default;
   411 
   412     return Heap::Tenure_Default;
   413 }
   414 
   415 void
   416 SemanticAnalysis::visitVariableDeclaration(VariableDeclaration *node)
   417 {
   418     PoolScope poolScope(zone_->pool());
   419     RootScope rootScope(zone_);
   420 
   421     Local<Type> type(zone_, node->sym()->type());
   422 
   423     if (node->sym()->type()->isVoid()) {
   424         cc_.reportError(node->type()->pos(), Message_CannotDeclareVoid);
   425         return;
   426     }
   427 
   428     if (node->initialization()) {
   429         HIR *hir = NULL;
   430 
   431         if ((hir = eval(node->initialization())) == NULL)
   432             return;
   433         if ((hir = coerce(hir, type, Coerce_Decl)) == NULL)
   434             return;
   435 
   436         discharge(hir);
   437     } else {
   438         if (type->isInt32() || type->isEnum() ||
   439             type->isChar() || type->isBool())
   440         {
   441             __ int_(0);
   442         } else if (type->isFloat()) {
   443             __ float_(0);
   444         } else if (type->isArray()) {
   445             Local<ArrayType> atype(zone_, ArrayType::cast(type));
   446             Local<ArrayMap> map(zone_, atype->newMap());
   447             if (!map)
   448                 return;
   449 
   450             if (atype->isFixedLength()) {
   451                 __ newarray(OP_NEWFIXED, map, InferTenure(node->sym()));
   452             } else if (node->dims()->at(0)) {
   453                 // This may not be true if we allow typedefing, so :TODO:
   454                 // figure out proper semantics.
   455                 assert(node->dims()->length() == atype->levels());
   456 
   457                 Local<Type> i32(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
   458                 for (size_t i = 0; i < node->dims()->length(); i++) {
   459                     Expression *expr = node->dims()->at(i);
   460                     if (expr) {
   461                         HIR *hir = eval(expr);
   462                         if (!hir || ((hir = coerce(hir, i32, Coerce_Arg)) == NULL))
   463                             return;
   464                         discharge(hir);
   465                     } else {
   466                         __ int_(0);
   467                     }
   468                 }
   469                 __ newarray(OP_NEWSIZED, map, InferTenure(node->sym()));
   470             } else {
   471                 __ newarray(OP_NEWEMPTY, map, InferTenure(node->sym()));
   472             }
   473         } else {
   474             assert(false);
   475         }
   476     }
   477 
   478     if (node->sym()->scope()->kind() != Scope::GLOBAL) {
   479         if (!__ allocate(node->sym()))
   480             return;
   481     }
   482 
   483     set(node->sym());
   484     __ pop();
   485 }
   486 
   487 void
   488 SemanticAnalysis::visitReturnStatement(ReturnStatement *node)
   489 {
   490     control_->returns(Returns_Always);
   491 
   492     if (!node->expression()) {
   493         if (!fun_->returnType()->isVoid()) {
   494             cc_.reportError(node->pos(), Message_MissingReturnValue);
   495             return;
   496         }
   497 
   498         __ returnvoid();
   499         return;
   500     }
   501 
   502     if (fun_->returnType()->isVoid()) {
   503         cc_.reportError(node->pos(), Message_UsedVoidReturn);
   504         return;
   505     }
   506 
   507     PoolScope poolScope(zone_->pool());
   508     RootScope rootScope(zone_);
   509 
   510     HIR *hir = eval(node->expression());
   511     if (!hir)
   512         return;
   513 
   514     Local<Type> returnType(zone_, fun_->returnType());
   515     if ((hir = coerce(hir, returnType, Coerce_Return)) == NULL)
   516         return;
   517 
   518     discharge(hir);
   519 
   520     if (hir->type()->isVoid())
   521         __ returnvoid();
   522     else
   523         __ return_();
   524 }
   525 
   526 void
   527 SemanticAnalysis::visitBinaryExpression(BinaryExpression *node)
   528 {
   529     HIR *left = eval(node->left());
   530     HIR *right = eval(node->right());
   531     if (!left || !right)
   532         return;
   533 
   534     hir_ = binary(node, node->token(), left, right);
   535 }
   536 
   537 bool
   538 SemanticAnalysis::checkArgumentCount(Handle<FunctionType> type, unsigned actual)
   539 {
   540     if (type->parameters()->length() == actual)
   541         return true;
   542 
   543     if (actual > type->parameters()->length()) {
   544         if (!type->isNative() || !type->isNativeVariadic())
   545             return false;
   546         return true;
   547     }
   548 
   549     if (!type->defaults())
   550         return false;
   551 
   552     // Missing arguments. See if there's a default argument for each missing
   553     // actual.
   554     for (unsigned i = actual; i < type->parameters()->length(); i++) {
   555         if (!type->defaults()->at(i))
   556             return false;
   557     }
   558 
   559     return true;
   560 }
   561 
   562 static unsigned
   563 BindImplicitName(Module *from, ImplicitSymbol *sym)
   564 {
   565     if (sym->bound())
   566         return sym->fieldIndex();
   567 
   568     Module *module = Module::cast(from->getImportAt(sym->index()));
   569     StructMap *map = module->globals()->map();
   570 
   571     unsigned fieldIndex;
   572     Descriptor *desc = map->type()->lookupField(sym->name(), &fieldIndex);
   573     assert(desc && desc->type() == sym->type());
   574 
   575     sym->bind(fieldIndex);
   576     return fieldIndex;
   577 }
   578 
   579 void
   580 SemanticAnalysis::visitNameProxy(NameProxy *proxy)
   581 {
   582     Symbol *sym = proxy->sym();
   583 
   584     switch (sym->kind()) {
   585       case Symbol::kImport:
   586       {
   587         ImportSymbol *import = sym->toImport();
   588         hir_ = new (pool_) HImport(proxy, sym->type(), import->index());
   589         break;
   590       }
   591 
   592       case Symbol::kImplicit:
   593       {
   594         ImplicitSymbol *import = sym->toImplicit();
   595         unsigned fieldIndex = BindImplicitName(unit_->module(), import);
   596 
   597         hir_ = new (pool_) HImport(proxy, zone_->types()->getImportable(), import->index());
   598         hir_ = new (pool_) HField(proxy, hir_, sym->type(), fieldIndex);
   599         break;
   600       }
   601 
   602       case Symbol::kConstant:
   603       {
   604         ConstantSymbol *val = sym->toConstant();
   605         hir_ = new (pool_) HInteger(proxy, sym->type(), val->value().toInt());
   606         break;
   607       }
   608       
   609       // This is kind of screwy. Symbol::kFunction is like a constant we can't
   610       // evaluate yet. Maybe we should extract the GLOBAL case and say that
   611       // kFunction is only used for global functions (and use const vars for
   612       // local functions).
   613       case Symbol::kFunction:
   614       case Symbol::kVariable:
   615       {
   616         Scope *in = sym->scope();
   617         switch (in->kind()) {
   618           case Scope::GLOBAL:
   619             hir_ = new (pool_) HGlobal(proxy, sym);
   620             break;
   621 
   622           case Scope::FUNCTION:
   623           {
   624             VariableSymbol *var = sym->toVariable();
   625             assert(var->storage() == VariableSymbol::Arg);
   626             hir_ = new (pool_) HLocal(proxy, var);
   627             break;
   628           }
   629 
   630           default:
   631           {
   632             VariableSymbol *var = sym->toVariable();
   633             assert(in->kind() == Scope::BLOCK);
   634             assert(var->storage() == VariableSymbol::Local);
   635             hir_ = new (pool_) HLocal(proxy, var);
   636             break;
   637           }
   638         }
   639         break;
   640       }
   641 
   642       default:
   643         // :TODO:
   644         assert(false);
   645     }
   646 }
   647 
   648 void
   649 SemanticAnalysis::visitBooleanLiteral(BooleanLiteral *node)
   650 {
   651     Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
   652     hir_ = new (pool_) HBoolean(node, type, node->token() == TOK_TRUE);
   653 }
   654 
   655 void
   656 SemanticAnalysis::visitIntegerLiteral(IntegerLiteral *lit)
   657 {
   658     Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
   659     hir_ = new (pool_) HInteger(lit, type, lit->value());
   660 }
   661 
   662 void
   663 SemanticAnalysis::visitFloatLiteral(FloatLiteral *node)
   664 {
   665     Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Float));
   666     hir_ = new (pool_) HFloat(node, type, (float)node->value());
   667 }
   668 
   669 void
   670 SemanticAnalysis::visitStringLiteral(StringLiteral *node)
   671 {
   672     Type *type = zone_->types()->getString();
   673     hir_ = new (pool_) HString(node, type, node->string());
   674 }
   675 
   676 void
   677 SemanticAnalysis::visitCallExpression(CallExpression *node)
   678 {
   679     HIR *callee = eval(node->callee());
   680     if (!callee)
   681         return;
   682 
   683     if (!callee->type()->isFunction()) {
   684         cc_.reportError(node->pos(), Message_CalleeNotFunction);
   685         return;
   686     }
   687 
   688     Local<FunctionType> fun(zone_, FunctionType::cast(callee->type()));
   689     
   690     if (!checkArgumentCount(fun, node->arguments()->length())) {
   691         cc_.reportError(node->pos(), Message_ArgumentCountMismatch);
   692         return;
   693     }
   694 
   695     if (fun->isForward()) {
   696         cc_.reportError(node->pos(), Message_ForwardNotImplemented, fun->name()->chars());
   697         return;
   698     }
   699 
   700     HIRList *args = new (pool_) HIRList;
   701     for (unsigned i = 0; i < node->arguments()->length(); i++) {
   702         Expression *expression = node->arguments()->at(i);
   703         HIR *arg = eval(expression);
   704         if (!arg)
   705             return;
   706 
   707         Handle<Type> given = arg->type();
   708         
   709         bool mustComputeReference;
   710         if (i >= fun->parameters()->length()) {
   711             // Special handling for natives. Arguments past the formal must
   712             // always have references computed. However, arrays are already
   713             // references for natives.
   714             assert(fun->isNative() && fun->isNativeVariadic());
   715             mustComputeReference = !given->isReference() &&
   716                                    !given->isArray();
   717         } else {
   718             Local<Type> actual(zone_, fun->parameterAt(i));
   719 
   720             if (expression->isIndexExpression() && arg->isIndex()) {
   721                 // If the expression is the form x[y], and this produced a
   722                 // normal array indexing operation, then we apply some 
   723                 // special rules.
   724 
   725                 if (actual->isReference()) {
   726                     // Disabled, since this doesn't have easily definable or
   727                     // sensible semantics with SP2 arrays, but we don't want
   728                     // to silently break SP1 semantics.
   729                     cc_.reportError(expression->pos(), Message_CannotComputeIndexRef);
   730                     return;
   731                 }
   732 
   733                 // As a special rule to account for SP1 semantics, we allow x[y]
   734                 // to automatically compute a sliced, read-only array view if
   735                 // the desired type is an array of one more dimension than x[y]
   736                 // would return.
   737                 //
   738                 // As an additional restriction, this is only allowed for
   739                 // one-level char arrays, to minimize potential issues until
   740                 // we determine whether more compatibility is needed.
   741                 //
   742                 // Internally, for sanity, the dependent array operation does
   743                 // not necessarily create a dependent array. For extensible
   744                 // arrays, we instead create a duplicate arrary of just the
   745                 // sliced portion, rather than deal with the complexity of the
   746                 // source array being resized.
   747                 //
   748                 // Note that we don't really know whether a dependent array
   749                 // will be dependent at compile-time, so the dependent type's
   750                 // just inherits from the source.
   751                 if (actual->isArray()) {
   752                     HIndex *index = arg->toIndex();
   753                     Local<ArrayType> basetype(zone_, ArrayType::cast(index->base()->type()));
   754                     Local<ArrayType> atype(zone_, ArrayType::cast(actual));
   755 
   756                     if (atype->isCharArray() && basetype->isCharArray()) {
   757                         // There is no possible way this will type check, so
   758                         // it's safe to just try something completely
   759                         // different.
   760                         Local<Type> slicetype(zone_);
   761                         if (basetype->isFixedLength()) {
   762                             // If the base type is fixed length, we need to
   763                             // compute a new dynamic array type based on the
   764                             // fixed array's contents and qualifiers.
   765                             Local<Type> contained(zone_, basetype->contained());
   766                             slicetype = zone_->types()->newArray(contained, ArrayType::DYNAMIC_ARRAY_SIZE);
   767                             if (!slicetype)
   768                                 return;
   769                             slicetype = zone_->types()->qualify(slicetype, basetype->quals());
   770                             if (!slicetype)
   771                                 return;
   772                         } else {
   773                             slicetype = basetype;
   774                         }
   775                         arg = new (pool_) HNewDependentArray(expression, slicetype, index->base(), index->index());
   776                         given = arg->type();
   777                     }
   778                 }
   779             }
   780 
   781             if (actual->isReference()) {
   782                 // If the actual is a reference, the coercion rules are much
   783                 // stricter; the contained types must be identical.
   784                 // :TODO: make this not an assert
   785                 assert(ReferenceType::cast(actual)->contained() == arg->type());
   786             } else {
   787                 // When we start overloading, coercion will have to happen later.
   788                 arg = coerce(arg, actual, Coerce_Arg);
   789                 if (!arg)
   790                     return;
   791             }
   792 
   793             mustComputeReference = actual->isReference() && !given->isReference();
   794         }
   795 
   796         if (mustComputeReference) {
   797             // Refs always use the LIFO stack if they can.
   798             arg = new (pool_) HToRef(arg->node(), arg->type(), arg);
   799             requireLifoStack();
   800         }
   801 
   802         if (!args->append(arg))
   803             return;
   804     }
   805 
   806     hir_ = new (pool_) HCall(node, fun->returnType(), callee, args);
   807 }
   808 
   809 void
   810 SemanticAnalysis::visitAssignment(Assignment *node)
   811 {
   812     HLValue *lval = lvalue(node->lvalue());
   813     if (!lval)
   814         return;
   815 
   816     if (lval->type()->quals() & TypeQual_Const) {
   817         cc_.reportError(node->pos(), Message_CannotModifyConst);
   818         return;
   819     }
   820 
   821     HIR *hir = eval(node->expression());
   822     if (!hir)
   823         return;
   824     if ((hir = coerce(hir, lval->type(), Coerce_Assign)) == NULL)
   825         return;
   826 
   827     hir_ = new (pool_) HStore(node, node->token(), lval, hir);
   828 }
   829 
   830 void
   831 SemanticAnalysis::visitBreakStatement(BreakStatement *node)
   832 {
   833     if (!loop_) {
   834         cc_.reportError(node->pos(), Message_BreakOutsideLoop);
   835         return;
   836     }
   837 
   838     loop_->setBreaks();
   839     __ j(OP_BREAK, loop_->break_());
   840 }
   841 
   842 void
   843 SemanticAnalysis::visitContinueStatement(ContinueStatement *node)
   844 {
   845     if (!loop_) {
   846         cc_.reportError(node->pos(), Message_ContinueOutsideLoop);
   847         return;
   848     }
   849 
   850     __ j(OP_CONTINUE, loop_->continue_());
   851 }
   852 
   853 void
   854 SemanticAnalysis::visitIndexExpression(IndexExpression *node)
   855 {
   856     HIR *left = eval(node->left());
   857     if (!left)
   858         return;
   859 
   860     HIR *right = eval(node->right());
   861     if (!right)
   862         return;
   863 
   864     // Hrm... yes, for now, let's coerce here.
   865     Local<Type> i32(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
   866     if ((right = coerce(right, i32, Coerce_Arg)) == NULL)
   867         return;
   868     
   869     // Do not coerce here, there's no reason to yet.
   870     if (!left->type()->isArray()) {
   871         cc_.reportError(node->left()->pos(), Message_IndexBaseMustBeArray);
   872         return;
   873     }
   874 
   875     hir_ = new (pool_) HIndex(node,
   876                               ArrayType::cast(left->type())->contained(),
   877                               left,
   878                               right);
   879 }
   880 
   881 void
   882 SemanticAnalysis::visitIncDecExpression(IncDecExpression *node)
   883 {
   884     HLValue *lval = lvalue(node->expression());
   885     if (!lval)
   886         return;
   887 
   888     if (!lval->type()->isInt32() && !lval->type()->isFloat()) {
   889         assert(false);
   890         return;
   891     }
   892 
   893     HIR *rval;
   894     if (lval->type()->isInt32())
   895         rval = new (pool_) HInteger(node, lval->type(), 1);
   896     else
   897         rval = new (pool_) HFloat(node, lval->type(), 1.0);
   898 
   899     if (node->postfix())
   900         hir_ = new (pool_) HPostIncDec(node, node->token(), lval, rval);
   901     else
   902         hir_ = new (pool_) HStore(node, node->token(), lval, rval);
   903 }
   904 
   905 Type *
   906 SemanticAnalysis::coercionType(TokenKind token, HIR *left, HIR *right)
   907 {
   908     Local<Type> l(zone_, left->type());
   909     Local<Type> r(zone_, right->type());
   910 
   911     if (l->isPod())
   912         l = l->unqualified();
   913     if (r->isPod())
   914         r = r->unqualified();
   915 
   916     if ((token >= TOK_PLUS && token <= TOK_SLASH) ||
   917         (token >= TOK_EQUALS && token <= TOK_GE))
   918     {
   919         // We allow: [float|int32] + [float|int32]
   920         if (l->isFloat() && r->isInt32())
   921             return l;
   922         if (l->isInt32() && r->isFloat())
   923             return r;
   924         if (l->isInt32() && r->isInt32())
   925             return l;
   926 
   927         if (l->isChar() && r->isInt32())
   928              return r;
   929         if (l->isInt32() && r->isChar())
   930             return l;
   931     }
   932 
   933     // :TODO: remove
   934     assert(*l == *r);
   935 
   936     return left->type();
   937 }
   938 
   939 HIR *
   940 SemanticAnalysis::typeCheckArray(const SourcePosition &pos,
   941                                  HIR *from,
   942                                  Handle<ArrayType> argActual,
   943                                  CoercionKind kind)
   944 {
   945     Local<Type> argGiven(zone_, from->type());
   946 
   947     // Special case: if we receive a string literal, and this is a char array,
   948     // we allow a coercion.
   949     if (from->isString() &&
   950         argGiven->isString() &&
   951         argActual->isArray() &&
   952         ArrayType::cast(argActual)->isCharArray())
   953     {
   954         HString *hir = from->toString();
   955         Local<ArrayType> actual(zone_, ArrayType::cast(argActual));
   956 
   957         if (actual->isFixedLength()) {
   958             if (hir->string()->length() + 1 > actual->fixedLength()) {
   959                 cc_.reportError(pos, Message_ArrayAssignmentTooBig);
   960                 return NULL;
   961             }
   962         }
   963 
   964         // Transform the string literal into an array literal. We give it the
   965         // type of the left-hand side. The constness of the destination type
   966         // will determine whether HArray duplicates it or not.
   967         Local<ArrayMap> map(zone_, actual->newMap());
   968         if (!map)
   969             return NULL;
   970 
   971         Local<Array> array(zone_);
   972         array = Array::NewString(zone_,
   973                                  map,
   974                                  hir->string()->chars(),
   975                                  hir->string()->length(),
   976                                  Heap::Tenure_Old);
   977         if (!array)
   978             return NULL;
   979 
   980         // Since we're creating a canonical copy of the char array, we have to
   981         // be careful that it doesn't get mutated. There are two cases where
   982         // we know it can't be mutated, and therefore don't need to specify
   983         // that it be cloned after pushing it onto the stack.
   984         //
   985         //  (1) The array type is const.
   986         //  (2) The array type is fixed-length, and the coercion is for
   987         //      assignment, meaning it will be immediately copied.
   988         //
   989         // We treat declaration separately from assignment, since for
   990         // declaration we can just immediately use the cloned version.
   991         bool shouldDuplicate = true;
   992         if ((actual->quals() & TypeQual_Const) ||
   993             (actual->isFixedLength() && kind == Coerce_Assign))
   994         {
   995             shouldDuplicate = false;
   996         }
   997 
   998         return new (pool_) HArray(hir->node(), actual, array, shouldDuplicate);
   999     }
  1000 
  1001     if (!argGiven->isArray()) {
  1002         cc_.reportError(pos, Message_ExpectedArray);
  1003         return NULL;
  1004     }
  1005 
  1006     Local<ArrayType> actual(zone_, ArrayType::cast(argActual));
  1007     Local<ArrayType> given(zone_, ArrayType::cast(argGiven));
  1008 
  1009     if (actual->levels() != given->levels()) {
  1010         cc_.reportError(pos, Message_ArrayDimensionsMismatch);
  1011         return NULL;
  1012     }
  1013 
  1014     unsigned level = 1;
  1015     while (true) {
  1016         if (actual->isFixedLength()) {
  1017             if (!given->isFixedLength()) {
  1018                 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
  1019                 return NULL;
  1020             }
  1021 
  1022             if (actual->isCharArray()) {
  1023                 // String assignment can have a truncated |given|.
  1024                 if (given->fixedLength() > actual->fixedLength()) {
  1025                     cc_.reportError(pos, Message_ArrayAssignmentTooBig);
  1026                     return NULL;
  1027                 }
  1028             } else {
  1029                 if (given->fixedLength() != actual->fixedLength()) {
  1030                     cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
  1031                     return NULL;
  1032                 }
  1033             }
  1034         } else if (given->isFixedLength()) {
  1035             // We do not allow assignments in the form:
  1036             //  [][] = [][Y]
  1037             //
  1038             // Otherwise, the following code could break the size guarantees
  1039             // of the right-hand side:
  1040             //
  1041             //  new x[][5];
  1042             //  new y[][];
  1043             //  new z[3];
  1044             //
  1045             //
  1046             //  y = x;
  1047             //  y[0] = z;
  1048             //
  1049             // Now |x[0]| contains a 3-length array.
  1050             if (level > 1) {
  1051                 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
  1052                 return NULL;
  1053             }
  1054         }
  1055 
  1056         if (!given->contained()->isArray() || !actual->contained()->isArray())
  1057             break;
  1058 
  1059         given = ArrayType::cast(given->contained());
  1060         actual = ArrayType::cast(actual->contained());
  1061     }
  1062 
  1063     bool givenConst = !!(given->contained()->quals() & TypeQual_Const);
  1064     bool actualConst = !!(actual->contained()->quals() & TypeQual_Const);
  1065 
  1066     // These arrays must contain the same innermost type.
  1067     if (given->contained()->unqualified() != actual->contained()->unqualified() ||
  1068         (givenConst && !actualConst))
  1069     {
  1070         char aname[255];
  1071         char gname[255];
  1072         cc_.reportError(pos, Message_TypeMismatch,
  1073                         GetTypeName(argActual, aname, sizeof(aname)),
  1074                         GetTypeName(argGiven, gname, sizeof(gname)));
  1075         return NULL;
  1076     }
  1077 
  1078     return from;
  1079 }
  1080 
  1081 HIR *
  1082 SemanticAnalysis::typeFailure(const SourcePosition &pos, Handle<Type> from, Handle<Type> to)
  1083 {
  1084     char fname[255];
  1085     char tname[255];
  1086     cc_.reportError(pos, Message_InvalidCoercion,
  1087                     GetTypeName(from, fname, sizeof(fname)),
  1088                     GetTypeName(to, tname, sizeof(tname)));
  1089     return NULL;
  1090 }
  1091 
  1092 HIR *
  1093 SemanticAnalysis::coerce(HIR *hir, Handle<Type> to, CoercionKind kind)
  1094 {
  1095     Local<Type> from(zone_, hir->type());
  1096 
  1097     // If the source is *ever* an importable, we just fail.
  1098     if (from->isImportable())
  1099         return typeFailure(hir->node()->pos(), from, to);
  1100 
  1101     if (from->isInt32() && to->isFloat())
  1102         return new (pool_) HConvert(hir->node(), to, OP_CVT_I2F, hir);
  1103     if (from->isInt32() && to->isBool())
  1104         return new (pool_) HConvert(hir->node(), to, OP_CVT_I2B, hir);
  1105 
  1106     if (to->isEnum() && from->unqualified() != to->unqualified())
  1107         return typeFailure(hir->node()->pos(), from, to);
  1108     
  1109     if (to->isArray()) {
  1110         Local<ArrayType> atype(zone_, ArrayType::cast(to));
  1111         return typeCheckArray(hir->node()->pos(), hir, atype, kind);
  1112     }
  1113     
  1114     return hir;
  1115 }
  1116 
  1117 void
  1118 SemanticAnalysis::set(VariableSymbol *sym)
  1119 {
  1120     if (sym->scope()->kind() == Scope::GLOBAL) {
  1121         __ setglobal(sym);
  1122     } else {
  1123         assert(sym->storage() == VariableSymbol::Local);
  1124         __ setlocal(sym);
  1125     }
  1126 }
  1127 
  1128 HIR *
  1129 SemanticAnalysis::binary(AstNode *node, TokenKind token, HIR *left, HIR *right)
  1130 {
  1131     Local<Type> coercion(zone_, coercionType(token, left, right));
  1132     if (!coercion)
  1133         return NULL;
  1134     if ((left = coerce(left, coercion, Coerce_Arg)) == NULL)
  1135         return NULL;
  1136     if ((right = coerce(right, coercion, Coerce_Arg)) == NULL)
  1137         return NULL;
  1138     
  1139     switch (token) {
  1140      case TOK_PLUS:
  1141       case TOK_MINUS:
  1142       case TOK_STAR:
  1143       case TOK_SLASH:
  1144       case TOK_PERCENT:
  1145       case TOK_AMPERSAND:
  1146       case TOK_BITOR:
  1147       case TOK_BITXOR:
  1148       case TOK_SHR:
  1149       case TOK_USHR:
  1150       case TOK_SHL:
  1151         return new (pool_) HBinary(node, left->type(), token, left, right);
  1152 
  1153       case TOK_EQUALS:
  1154       case TOK_NOTEQUALS:
  1155       case TOK_LT:
  1156       case TOK_LE:
  1157       case TOK_GT:
  1158       case TOK_GE:
  1159       case TOK_AND:
  1160       case TOK_OR:
  1161       {
  1162         Local<Type> result(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
  1163         return new (pool_) HBinary(node, result, token, left, right);
  1164       }
  1165 
  1166       default:
  1167         assert(false);
  1168         return NULL;
  1169     }
  1170 }
  1171 
  1172 static inline bool
  1173 IsValidUncheckedType(Type *type)
  1174 {
  1175     return type->isEnum() ||
  1176            type->isFloat() ||
  1177            type->isInt32() ||
  1178            type->isChar() ||
  1179            type->isUnchecked() ||
  1180            type->isBool();
  1181 }
  1182 
  1183 void
  1184 SemanticAnalysis::visitUnaryExpression(UnaryExpression *node)
  1185 {
  1186     HIR *hir = eval(node->expression());
  1187     if (!hir)
  1188         return;
  1189 
  1190     switch (node->token()) {
  1191       case TOK_TILDE:
  1192       {
  1193         if (!hir->type()->isInt32() && !hir->type()->isEnum()) {
  1194             char name[255];
  1195             cc_.reportError(node->pos(), Message_InvalidUnaryType,
  1196                             "~",
  1197                             GetTypeName(hir->type(), name, sizeof(name)));
  1198         }
  1199         Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
  1200         hir_ = new (pool_) HUnary(node, hir->type(), TOK_TILDE, hir);
  1201         return;
  1202       }
  1203 
  1204       case TOK_MINUS:
  1205       {
  1206         if (hir->type()->isInt32() || hir->type()->isEnum()) {
  1207             Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
  1208             hir_ = new (pool_) HUnary(node, type, TOK_MINUS, hir);
  1209             return;
  1210         }
  1211         if (hir->type()->isFloat()) {
  1212             hir_ = new (pool_) HUnary(node, hir->type(), TOK_MINUS, hir);
  1213             return;
  1214         }
  1215 
  1216         char name[255];
  1217         cc_.reportError(node->pos(), Message_InvalidUnaryType,
  1218                         "-",
  1219                         GetTypeName(hir->type(), name, sizeof(name)));
  1220         break;
  1221       }
  1222 
  1223       default:
  1224       {
  1225         assert(node->token() == TOK_LABEL);
  1226 
  1227         TypeSymbol *sym = node->tag()->sym()->asType();
  1228         if (!sym) {
  1229             cc_.reportError(node->pos(), Message_IdentifierIsNotAType,
  1230                             sym->name()->chars());
  1231             return;
  1232         }
  1233 
  1234         if (!IsValidUncheckedType(sym->effective())) {
  1235             char name[255];
  1236             cc_.reportError(node->pos(), Message_InvalidUncheckedCastTo,
  1237                             GetTypeName(sym->type(), name, sizeof(name)));
  1238             return;
  1239         }
  1240         if (!IsValidUncheckedType(hir->type())) {
  1241             char name[255];
  1242             cc_.reportError(node->pos(), Message_InvalidUncheckedCastFrom,
  1243                             GetTypeName(hir->type(), name, sizeof(name)));
  1244             return;
  1245         }
  1246 
  1247         hir_ = new (pool_) HUnary(node, sym->effective(), TOK_LABEL, hir);
  1248         break;
  1249       }
  1250     }
  1251 }
  1252 
  1253 void
  1254 SemanticAnalysis::import(HIR *hir, FieldExpression *node)
  1255 {
  1256     // Note that we don't care if the hir type is "importable", since we
  1257     // can only do anything if the important has a constant binding.
  1258     unsigned index = hir->toImport()->index();
  1259     Local<Importable> importable(zone_, unit_->module()->getImportAt(index));
  1260 
  1261     if (importable->isPackage()) {
  1262         // Look at what's already loaded and see if anything exists. We
  1263         // can't create stuff on-demand here since it's too late to add
  1264         // new translation units to the CompileContext.
  1265         Local<Package> package(zone_, Package::cast(importable));
  1266         Local<Importable> found(zone_, package->import(node->field()));
  1267         if (!found) {
  1268             cc_.reportError(node->pos(), Message_PackageDoesNotHaveMember, node->field()->chars());
  1269             return;
  1270         }
  1271 
  1272         // If we did find something, make sure it is in our import list.
  1273         // If we didn't explicitly import it, we have no right to use it.
  1274         for (index = 0; index < unit_->module()->imports(); index++) {
  1275             if (unit_->module()->getImportAt(index) == importable)
  1276                 break;
  1277         }
  1278 
  1279         if (index == unit_->module()->imports()) {
  1280             cc_.reportError(node->pos(), Message_ImportWasNeverImported, node->field()->chars());
  1281             return;
  1282         }
  1283 
  1284         // Just create a new HImport.
  1285         hir_ = new (pool_) HImport(node, hir->type(), index);
  1286     } else {
  1287         // Modules can never have sub-modules or sub-packages.
  1288         unsigned index;
  1289         Local<Module> module(zone_, Module::cast(importable));
  1290         Local<StructMap> map(zone_, module->globals()->map());
  1291         Local<Descriptor> desc(zone_, map->type()->lookupField(node->field(), &index));
  1292         if (!desc) {
  1293             cc_.reportError(node->pos(), Message_FieldNotFound, node->field()->chars());
  1294             return;
  1295         }
  1296         hir_ = new (pool_) HField(node, hir, desc->type(), index);
  1297     }
  1298 }
  1299 
  1300 void
  1301 SemanticAnalysis::visitFieldExpression(FieldExpression *node)
  1302 {
  1303     HIR *hir = eval(node->left());
  1304     if (!hir)
  1305         return;
  1306 
  1307     if (hir->isImport()) {
  1308         import(hir, node);
  1309         return;
  1310     }
  1311 
  1312     char name[255];
  1313     cc_.reportError(node->pos(), Message_InvalidFieldExpression,
  1314                     GetTypeName(hir->type(), name, sizeof(name)));
  1315 }
  1316 
  1317 static inline TokenKind
  1318 ToCompare(Expression *expr)
  1319 {
  1320     if (expr->isBinaryExpression()) {
  1321         BinaryExpression *b = expr->toBinaryExpression();
  1322         if (b->token() >= TOK_EQUALS && b->token() <= TOK_OR)
  1323             return b->token();
  1324     } else if (expr->isUnaryExpression()) {
  1325         UnaryExpression *u = expr->toUnaryExpression();
  1326         if (u->token() == TOK_NOT)
  1327             return TOK_NOT;
  1328     }
  1329     return TOK_EOF;
  1330 }
  1331 
  1332 void
  1333 SemanticAnalysis::visitForTest(Expression *expr,
  1334                                Label *trueBranch,
  1335                                Label *falseBranch,
  1336                                Label *fallthrough)
  1337 {
  1338     Local<Type> boolType(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
  1339 
  1340     TokenKind token = ToCompare(expr);
  1341     if (token == TOK_EOF || token == TOK_NOT) {
  1342         HIR *hir;
  1343         if (token == TOK_EOF)
  1344             hir = eval(expr);
  1345         else
  1346             hir = eval(expr->toUnaryExpression()->expression());
  1347         if (!hir)
  1348             return;
  1349         if ((hir = coerce(hir, boolType, Coerce_Arg)) == NULL)
  1350             return;
  1351 
  1352         discharge(hir);
  1353 
  1354         bool jumpOnTrue = (fallthrough == falseBranch) ^ (token == TOK_NOT);
  1355         Opcode op = jumpOnTrue ? OP_JT : OP_JF;
  1356         
  1357         if (fallthrough == falseBranch)
  1358             __ j(op, trueBranch);
  1359         else
  1360             __ j(op, falseBranch);
  1361         return;
  1362     }
  1363 
  1364     BinaryExpression *bin = expr->toBinaryExpression();
  1365     if (token == TOK_AND || token == TOK_OR) {
  1366         Label next;
  1367         if (token == TOK_AND)
  1368             visitForTest(bin->left(), &next, falseBranch, &next);
  1369         else
  1370             visitForTest(bin->left(), trueBranch, &next, &next);
  1371         __ bind(&next);
  1372         visitForTest(bin->right(), trueBranch, falseBranch, fallthrough);
  1373         return;
  1374     }
  1375 
  1376     HIR *left = eval(bin->left());
  1377     HIR *right = eval(bin->right());
  1378     if (!left || !right)
  1379         return;
  1380 
  1381     HIR *hir = binary(bin, bin->token(), left, right);
  1382     if (!hir)
  1383         return;
  1384     if ((hir = coerce(hir, boolType, Coerce_Arg)) == NULL)
  1385         return;
  1386 
  1387     discharge(hir);
  1388     if (fallthrough == trueBranch)
  1389         __ j(OP_JF, falseBranch);
  1390     else
  1391         __ j(OP_JT, trueBranch);
  1392 }
  1393 
  1394 HLValue *
  1395 SemanticAnalysis::lvalue(Expression *expr)
  1396 {
  1397     HIR *hir = eval(expr);
  1398     if (!hir)
  1399         return NULL;
  1400     
  1401     if (!hir->isLValue()) {
  1402         cc_.reportError(expr->pos(), Message_ExpectedLValue);
  1403         return NULL;
  1404     }
  1405 
  1406     return static_cast<HLValue *>(hir);
  1407 }
  1408 
  1409 HIR *
  1410 SemanticAnalysis::eval(Expression *expr)
  1411 {
  1412     assert(!hir_);
  1413     expr->accept(this);
  1414 
  1415     HIR *hir = hir_;
  1416     hir_ = NULL;
  1417 
  1418     return hir;
  1419 }
  1420 
  1421 void
  1422 SemanticAnalysis::discharge(HIR *hir)
  1423 {
  1424     EmitHIR(zone_, emitter_, hir);
  1425 }