public void loadOrStoreVariable(BytecodeVariable variable, boolean useReferenceDirectly) {
    CompileStack compileStack = controller.getCompileStack();

    if (compileStack.isLHS()) {
      storeVar(variable);
    } else {
      MethodVisitor mv = controller.getMethodVisitor();
      int idx = variable.getIndex();
      ClassNode type = variable.getType();

      if (variable.isHolder()) {
        mv.visitVarInsn(ALOAD, idx);
        if (!useReferenceDirectly) {
          mv.visitMethodInsn(
              INVOKEVIRTUAL, "groovy/lang/Reference", "get", "()Ljava/lang/Object;", false);
          BytecodeHelper.doCast(mv, type);
          push(type);
        } else {
          push(ClassHelper.REFERENCE_TYPE);
        }
      } else {
        load(type, idx);
      }
    }
  }
  public static void loadReference(String name, WriterController controller) {
    CompileStack compileStack = controller.getCompileStack();
    MethodVisitor mv = controller.getMethodVisitor();
    ClassNode classNode = controller.getClassNode();
    AsmClassGenerator acg = controller.getAcg();

    // compileStack.containsVariable(name) means to ask if the variable is already declared
    // compileStack.getScope().isReferencedClassVariable(name) means to ask if the variable is a
    // field
    // If it is no field and is not yet declared, then it is either a closure shared variable or
    // an already declared variable.
    if (!compileStack.containsVariable(name)
        && compileStack.getScope().isReferencedClassVariable(name)) {
      acg.visitFieldExpression(new FieldExpression(classNode.getDeclaredField(name)));
    } else {
      BytecodeVariable v =
          compileStack.getVariable(name, !classNodeUsesReferences(controller.getClassNode()));
      if (v == null) {
        // variable is not on stack because we are
        // inside a nested Closure and this variable
        // was not used before
        // then load it from the Closure field
        FieldNode field = classNode.getDeclaredField(name);
        mv.visitVarInsn(ALOAD, 0);
        mv.visitFieldInsn(
            GETFIELD,
            controller.getInternalClassName(),
            name,
            BytecodeHelper.getTypeDescription(field.getType()));
      } else {
        mv.visitVarInsn(ALOAD, v.getIndex());
      }
      controller.getOperandStack().push(ClassHelper.REFERENCE_TYPE);
    }
  }
  private VariableSlotLoader loadWithSubscript(Expression expression) {
    final OperandStack operandStack = controller.getOperandStack();
    // if we have a BinaryExpression, let us check if it is with
    // subscription
    if (expression instanceof BinaryExpression) {
      BinaryExpression be = (BinaryExpression) expression;
      if (be.getOperation().getType() == Types.LEFT_SQUARE_BRACKET) {
        // right expression is the subscript expression
        // we store the result of the subscription on the stack
        Expression subscript = be.getRightExpression();
        subscript.visit(controller.getAcg());
        ClassNode subscriptType = operandStack.getTopOperand();
        int id =
            controller.getCompileStack().defineTemporaryVariable("$subscript", subscriptType, true);
        VariableSlotLoader subscriptExpression =
            new VariableSlotLoader(subscriptType, id, operandStack);
        // do modified visit
        BinaryExpression newBe =
            new BinaryExpression(be.getLeftExpression(), be.getOperation(), subscriptExpression);
        newBe.copyNodeMetaData(be);
        newBe.setSourcePosition(be);
        newBe.visit(controller.getAcg());
        return subscriptExpression;
      }
    }

    // normal loading of expression
    expression.visit(controller.getAcg());
    return null;
  }
  private void evaluatePrefixMethod(int op, String method, Expression expression, Expression orig) {
    // load Expressions
    VariableSlotLoader usesSubscript = loadWithSubscript(expression);

    // execute Method
    execMethodAndStoreForSubscriptOperator(op, method, expression, usesSubscript, orig);

    // new value is already on stack, so nothing to do here
    if (usesSubscript != null) controller.getCompileStack().removeVar(usesSubscript.getIndex());
  }
  private void evaluateElvisOperatorExpression(ElvisOperatorExpression expression) {
    MethodVisitor mv = controller.getMethodVisitor();
    CompileStack compileStack = controller.getCompileStack();
    OperandStack operandStack = controller.getOperandStack();
    TypeChooser typeChooser = controller.getTypeChooser();

    Expression boolPart = expression.getBooleanExpression().getExpression();
    Expression falsePart = expression.getFalseExpression();

    ClassNode truePartType = typeChooser.resolveType(boolPart, controller.getClassNode());
    ClassNode falsePartType = typeChooser.resolveType(falsePart, controller.getClassNode());
    ClassNode common = WideningCategories.lowestUpperBound(truePartType, falsePartType);

    // x?:y is equal to x?x:y, which evals to
    //      var t=x; boolean(t)?t:y
    // first we load x, dup it, convert the dupped to boolean, then
    // jump depending on the value. For true we are done, for false we
    // have to load y, thus we first remove x and then load y.
    // But since x and y may have different stack lengths, this cannot work
    // Thus we have to have to do the following:
    // Be X the type of x, Y the type of y and S the common supertype of
    // X and Y, then we have to see x?:y as
    //      var t=x;boolean(t)?S(t):S(y)
    // so we load x, dup it, store the value in a local variable (t), then
    // do boolean conversion. In the true part load t and cast it to S,
    // in the false part load y and cast y to S

    // load x, dup it, store one in $t and cast the remaining one to boolean
    int mark = operandStack.getStackLength();
    boolPart.visit(controller.getAcg());
    operandStack.dup();
    if (ClassHelper.isPrimitiveType(truePartType)
        && !ClassHelper.isPrimitiveType(operandStack.getTopOperand())) {
      truePartType = ClassHelper.getWrapper(truePartType);
    }
    int retValueId = compileStack.defineTemporaryVariable("$t", truePartType, true);
    operandStack.castToBool(mark, true);

    Label l0 = operandStack.jump(IFEQ);
    // true part: load $t and cast to S
    operandStack.load(truePartType, retValueId);
    operandStack.doGroovyCast(common);
    Label l1 = new Label();
    mv.visitJumpInsn(GOTO, l1);

    // false part: load false expression and cast to S
    mv.visitLabel(l0);
    falsePart.visit(controller.getAcg());
    operandStack.doGroovyCast(common);

    // finish and cleanup
    mv.visitLabel(l1);
    compileStack.removeVar(retValueId);
    controller.getOperandStack().replace(common, 2);
  }
  protected void evaluateBinaryExpression(String message, BinaryExpression binExp) {
    CompileStack compileStack = controller.getCompileStack();

    Expression receiver = binExp.getLeftExpression();
    Expression arguments = binExp.getRightExpression();

    // ensure VariableArguments are read, not stored
    compileStack.pushLHS(false);
    controller.getInvocationWriter().makeSingleArgumentCall(receiver, message, arguments);
    compileStack.popLHS();
  }
  protected void evaluateBinaryExpressionWithAssignment(
      String method, BinaryExpression expression) {
    Expression leftExpression = expression.getLeftExpression();
    AsmClassGenerator acg = controller.getAcg();
    OperandStack operandStack = controller.getOperandStack();

    if (leftExpression instanceof BinaryExpression) {
      BinaryExpression leftBinExpr = (BinaryExpression) leftExpression;
      if (leftBinExpr.getOperation().getType() == Types.LEFT_SQUARE_BRACKET) {
        evaluateArrayAssignmentWithOperator(method, expression, leftBinExpr);
        return;
      }
    }

    evaluateBinaryExpression(method, expression);

    // br to leave a copy of rvalue on the stack. see also isPopRequired()
    operandStack.dup();

    controller.getCompileStack().pushLHS(true);
    leftExpression.visit(acg);
    controller.getCompileStack().popLHS();
  }
  private void execMethodAndStoreForSubscriptOperator(
      int op,
      String method,
      Expression expression,
      VariableSlotLoader usesSubscript,
      Expression orig) {
    final OperandStack operandStack = controller.getOperandStack();
    writePostOrPrefixMethod(op, method, expression, orig);

    // we need special code for arrays to store the result (like for a[1]++)
    if (usesSubscript != null) {
      CompileStack compileStack = controller.getCompileStack();
      BinaryExpression be = (BinaryExpression) expression;

      ClassNode methodResultType = operandStack.getTopOperand();
      final int resultIdx =
          compileStack.defineTemporaryVariable("postfix_" + method, methodResultType, true);
      BytecodeExpression methodResultLoader =
          new VariableSlotLoader(methodResultType, resultIdx, operandStack);

      // execute the assignment, this will leave the right side
      // (here the method call result) on the stack
      assignToArray(be, be.getLeftExpression(), usesSubscript, methodResultLoader);

      compileStack.removeVar(resultIdx);
    }
    // here we handle a.b++ and a++
    else if (expression instanceof VariableExpression
        || expression instanceof FieldExpression
        || expression instanceof PropertyExpression) {
      operandStack.dup();
      controller.getCompileStack().pushLHS(true);
      expression.visit(controller.getAcg());
      controller.getCompileStack().popLHS();
    }
    // other cases don't need storing, so nothing to be done for them
  }
  public void writeClosure(ClosureExpression expression) {
    CompileStack compileStack = controller.getCompileStack();
    MethodVisitor mv = controller.getMethodVisitor();
    ClassNode classNode = controller.getClassNode();
    AsmClassGenerator acg = controller.getAcg();

    // generate closure as public class to make sure it can be properly invoked by classes of the
    // Groovy runtime without circumventing JVM access checks (see CachedMethod for example).
    ClassNode closureClass = getOrAddClosureClass(expression, ACC_PUBLIC);
    String closureClassinternalName = BytecodeHelper.getClassInternalName(closureClass);
    List constructors = closureClass.getDeclaredConstructors();
    ConstructorNode node = (ConstructorNode) constructors.get(0);

    Parameter[] localVariableParams = node.getParameters();

    mv.visitTypeInsn(NEW, closureClassinternalName);
    mv.visitInsn(DUP);
    if (controller.isStaticMethod() || compileStack.isInSpecialConstructorCall()) {
      (new ClassExpression(classNode)).visit(acg);
      (new ClassExpression(controller.getOutermostClass())).visit(acg);
    } else {
      mv.visitVarInsn(ALOAD, 0);
      controller.getOperandStack().push(ClassHelper.OBJECT_TYPE);
      loadThis();
    }

    // now let's load the various parameters we're passing
    // we start at index 2 because the first variable we pass
    // is the owner instance and at this point it is already
    // on the stack
    for (int i = 2; i < localVariableParams.length; i++) {
      Parameter param = localVariableParams[i];
      String name = param.getName();
      loadReference(name, controller);
      if (param.getNodeMetaData(ClosureWriter.UseExistingReference.class) == null) {
        param.setNodeMetaData(ClosureWriter.UseExistingReference.class, Boolean.TRUE);
      }
    }

    // we may need to pass in some other constructors
    // cv.visitMethodInsn(INVOKESPECIAL, innerClassinternalName, "<init>", prototype + ")V");
    mv.visitMethodInsn(
        INVOKESPECIAL,
        closureClassinternalName,
        "<init>",
        BytecodeHelper.getMethodDescriptor(ClassHelper.VOID_TYPE, localVariableParams),
        false);
    controller.getOperandStack().replace(ClassHelper.CLOSURE_TYPE, localVariableParams.length);
  }
  private void evaluatePostfixMethod(
      int op, String method, Expression expression, Expression orig) {
    CompileStack compileStack = controller.getCompileStack();
    final OperandStack operandStack = controller.getOperandStack();

    // load Expressions
    VariableSlotLoader usesSubscript = loadWithSubscript(expression);

    // save copy for later
    operandStack.dup();
    ClassNode expressionType = operandStack.getTopOperand();
    int tempIdx = compileStack.defineTemporaryVariable("postfix_" + method, expressionType, true);

    // execute Method
    execMethodAndStoreForSubscriptOperator(op, method, expression, usesSubscript, orig);

    // remove the result of the method call
    operandStack.pop();

    // reload saved value
    operandStack.load(expressionType, tempIdx);
    compileStack.removeVar(tempIdx);
    if (usesSubscript != null) compileStack.removeVar(usesSubscript.getIndex());
  }
  public void eval(BinaryExpression expression) {
    switch (expression.getOperation().getType()) {
      case EQUAL: // = assignment
        evaluateEqual(expression, false);
        break;

      case COMPARE_EQUAL: // ==
        evaluateCompareExpression(compareEqualMethod, expression);
        break;

      case COMPARE_NOT_EQUAL:
        evaluateCompareExpression(compareNotEqualMethod, expression);
        break;

      case COMPARE_TO:
        evaluateCompareTo(expression);
        break;

      case COMPARE_GREATER_THAN:
        evaluateCompareExpression(compareGreaterThanMethod, expression);
        break;

      case COMPARE_GREATER_THAN_EQUAL:
        evaluateCompareExpression(compareGreaterThanEqualMethod, expression);
        break;

      case COMPARE_LESS_THAN:
        evaluateCompareExpression(compareLessThanMethod, expression);
        break;

      case COMPARE_LESS_THAN_EQUAL:
        evaluateCompareExpression(compareLessThanEqualMethod, expression);
        break;

      case LOGICAL_AND:
        evaluateLogicalAndExpression(expression);
        break;

      case LOGICAL_OR:
        evaluateLogicalOrExpression(expression);
        break;

      case BITWISE_AND:
        evaluateBinaryExpression("and", expression);
        break;

      case BITWISE_AND_EQUAL:
        evaluateBinaryExpressionWithAssignment("and", expression);
        break;

      case BITWISE_OR:
        evaluateBinaryExpression("or", expression);
        break;

      case BITWISE_OR_EQUAL:
        evaluateBinaryExpressionWithAssignment("or", expression);
        break;

      case BITWISE_XOR:
        evaluateBinaryExpression("xor", expression);
        break;

      case BITWISE_XOR_EQUAL:
        evaluateBinaryExpressionWithAssignment("xor", expression);
        break;

      case PLUS:
        evaluateBinaryExpression("plus", expression);
        break;

      case PLUS_EQUAL:
        evaluateBinaryExpressionWithAssignment("plus", expression);
        break;

      case MINUS:
        evaluateBinaryExpression("minus", expression);
        break;

      case MINUS_EQUAL:
        evaluateBinaryExpressionWithAssignment("minus", expression);
        break;

      case MULTIPLY:
        evaluateBinaryExpression("multiply", expression);
        break;

      case MULTIPLY_EQUAL:
        evaluateBinaryExpressionWithAssignment("multiply", expression);
        break;

      case DIVIDE:
        evaluateBinaryExpression("div", expression);
        break;

      case DIVIDE_EQUAL:
        // SPG don't use divide since BigInteger implements directly
        // and we want to dispatch through DefaultGroovyMethods to get a BigDecimal result
        evaluateBinaryExpressionWithAssignment("div", expression);
        break;

      case INTDIV:
        evaluateBinaryExpression("intdiv", expression);
        break;

      case INTDIV_EQUAL:
        evaluateBinaryExpressionWithAssignment("intdiv", expression);
        break;

      case MOD:
        evaluateBinaryExpression("mod", expression);
        break;

      case MOD_EQUAL:
        evaluateBinaryExpressionWithAssignment("mod", expression);
        break;

      case POWER:
        evaluateBinaryExpression("power", expression);
        break;

      case POWER_EQUAL:
        evaluateBinaryExpressionWithAssignment("power", expression);
        break;

      case LEFT_SHIFT:
        evaluateBinaryExpression("leftShift", expression);
        break;

      case LEFT_SHIFT_EQUAL:
        evaluateBinaryExpressionWithAssignment("leftShift", expression);
        break;

      case RIGHT_SHIFT:
        evaluateBinaryExpression("rightShift", expression);
        break;

      case RIGHT_SHIFT_EQUAL:
        evaluateBinaryExpressionWithAssignment("rightShift", expression);
        break;

      case RIGHT_SHIFT_UNSIGNED:
        evaluateBinaryExpression("rightShiftUnsigned", expression);
        break;

      case RIGHT_SHIFT_UNSIGNED_EQUAL:
        evaluateBinaryExpressionWithAssignment("rightShiftUnsigned", expression);
        break;

      case KEYWORD_INSTANCEOF:
        evaluateInstanceof(expression);
        break;

      case FIND_REGEX:
        evaluateCompareExpression(findRegexMethod, expression);
        break;

      case MATCH_REGEX:
        evaluateCompareExpression(matchRegexMethod, expression);
        break;

      case LEFT_SQUARE_BRACKET:
        if (controller.getCompileStack().isLHS()) {
          evaluateEqual(expression, false);
        } else {
          evaluateBinaryExpression("getAt", expression);
        }
        break;

      case KEYWORD_IN:
        evaluateCompareExpression(isCaseMethod, expression);
        break;

      case COMPARE_IDENTICAL:
      case COMPARE_NOT_IDENTICAL:
        Token op = expression.getOperation();
        Throwable cause =
            new SyntaxException(
                "Operator " + op + " not supported",
                op.getStartLine(),
                op.getStartColumn(),
                op.getStartLine(),
                op.getStartColumn() + 3);
        throw new GroovyRuntimeException(cause);

      default:
        throw new GroovyBugError("Operation: " + expression.getOperation() + " not supported");
    }
  }
  public void evaluateEqual(BinaryExpression expression, boolean defineVariable) {
    AsmClassGenerator acg = controller.getAcg();
    CompileStack compileStack = controller.getCompileStack();
    OperandStack operandStack = controller.getOperandStack();
    Expression rightExpression = expression.getRightExpression();
    Expression leftExpression = expression.getLeftExpression();
    ClassNode lhsType =
        controller.getTypeChooser().resolveType(leftExpression, controller.getClassNode());

    if (defineVariable
        && rightExpression instanceof EmptyExpression
        && !(leftExpression instanceof TupleExpression)) {
      VariableExpression ve = (VariableExpression) leftExpression;
      BytecodeVariable var =
          compileStack.defineVariable(
              ve, controller.getTypeChooser().resolveType(ve, controller.getClassNode()), false);
      operandStack.loadOrStoreVariable(var, false);
      return;
    }

    // let's evaluate the RHS and store the result
    ClassNode rhsType;
    if (rightExpression instanceof ListExpression && lhsType.isArray()) {
      ListExpression list = (ListExpression) rightExpression;
      ArrayExpression array =
          new ArrayExpression(lhsType.getComponentType(), list.getExpressions());
      array.setSourcePosition(list);
      array.visit(acg);
    } else if (rightExpression instanceof EmptyExpression) {
      rhsType = leftExpression.getType();
      loadInitValue(rhsType);
    } else {
      rightExpression.visit(acg);
    }
    rhsType = operandStack.getTopOperand();

    boolean directAssignment = defineVariable && !(leftExpression instanceof TupleExpression);
    int rhsValueId;
    if (directAssignment) {
      VariableExpression var = (VariableExpression) leftExpression;
      if (var.isClosureSharedVariable() && ClassHelper.isPrimitiveType(rhsType)) {
        // GROOVY-5570: if a closure shared variable is a primitive type, it must be boxed
        rhsType = ClassHelper.getWrapper(rhsType);
        operandStack.box();
      }

      // ensure we try to unbox null to cause a runtime NPE in case we assign
      // null to a primitive typed variable, even if it is used only in boxed
      // form as it is closure shared
      if (var.isClosureSharedVariable()
          && ClassHelper.isPrimitiveType(var.getOriginType())
          && isNull(rightExpression)) {
        operandStack.doGroovyCast(var.getOriginType());
        // these two are never reached in bytecode and only there
        // to avoid verifyerrors and compiler infrastructure hazzle
        operandStack.box();
        operandStack.doGroovyCast(lhsType);
      }
      // normal type transformation
      if (!ClassHelper.isPrimitiveType(lhsType) && isNull(rightExpression)) {
        operandStack.replace(lhsType);
      } else {
        operandStack.doGroovyCast(lhsType);
      }
      rhsType = lhsType;
      rhsValueId = compileStack.defineVariable(var, lhsType, true).getIndex();
    } else {
      rhsValueId = compileStack.defineTemporaryVariable("$rhs", rhsType, true);
    }
    // TODO: if rhs is VariableSlotLoader already, then skip crating a new one
    BytecodeExpression rhsValueLoader = new VariableSlotLoader(rhsType, rhsValueId, operandStack);

    // assignment for subscript
    if (leftExpression instanceof BinaryExpression) {
      BinaryExpression leftBinExpr = (BinaryExpression) leftExpression;
      if (leftBinExpr.getOperation().getType() == Types.LEFT_SQUARE_BRACKET) {
        assignToArray(
            expression,
            leftBinExpr.getLeftExpression(),
            leftBinExpr.getRightExpression(),
            rhsValueLoader);
      }
      compileStack.removeVar(rhsValueId);
      return;
    }

    compileStack.pushLHS(true);

    // multiple declaration
    if (leftExpression instanceof TupleExpression) {
      TupleExpression tuple = (TupleExpression) leftExpression;
      int i = 0;
      for (Expression e : tuple.getExpressions()) {
        VariableExpression var = (VariableExpression) e;
        MethodCallExpression call =
            new MethodCallExpression(
                rhsValueLoader, "getAt", new ArgumentListExpression(new ConstantExpression(i)));
        call.visit(acg);
        i++;
        if (defineVariable) {
          operandStack.doGroovyCast(var);
          compileStack.defineVariable(var, true);
          operandStack.remove(1);
        } else {
          acg.visitVariableExpression(var);
        }
      }
    }
    // single declaration
    else if (defineVariable) {
      rhsValueLoader.visit(acg);
      operandStack.remove(1);
      compileStack.popLHS();
      return;
    }
    // normal assignment
    else {
      int mark = operandStack.getStackLength();
      // to leave a copy of the rightExpression value on the stack after the assignment.
      rhsValueLoader.visit(acg);
      TypeChooser typeChooser = controller.getTypeChooser();
      ClassNode targetType = typeChooser.resolveType(leftExpression, controller.getClassNode());
      operandStack.doGroovyCast(targetType);
      leftExpression.visit(acg);
      operandStack.remove(operandStack.getStackLength() - mark);
    }
    compileStack.popLHS();

    // return value of assignment
    rhsValueLoader.visit(acg);
    compileStack.removeVar(rhsValueId);
  }