Optimize addition in generated bytecode

Use invokedynamic via a new "FallbackCallSite" class that can try various
methods in order and adjust at runtime to fall back to less-specific
methods. This makes it possible to try a set of efficient methods that
assume what their operand types and often arrive at the most efficient
after a few iterations.

Use this method to optimize the "add" operation for numbers and strings.

Also optimize the "OptRuntime.add" operation for better performance.

Taken together, in microbenchmarks, integer and float addition is about
twice as fast and string concatenation in a loop is about four times faster.
diff --git a/benchmarks/org/mozilla/javascript/benchmarks/MathBenchmark.java b/benchmarks/org/mozilla/javascript/benchmarks/MathBenchmark.java
new file mode 100644
index 0000000..3e5d0c7
--- /dev/null
+++ b/benchmarks/org/mozilla/javascript/benchmarks/MathBenchmark.java
@@ -0,0 +1,242 @@
+package org.mozilla.javascript.benchmarks;
+
+import java.io.FileReader;
+import java.io.IOException;
+import org.mozilla.javascript.Context;
+import org.mozilla.javascript.Function;
+import org.mozilla.javascript.ScriptRuntime;
+import org.mozilla.javascript.Scriptable;
+import org.mozilla.javascript.ScriptableObject;
+import org.openjdk.jmh.annotations.*;
+
+public class MathBenchmark {
+    @State(Scope.Thread)
+    public static class GenericState {
+        Context cx;
+        Scriptable scope;
+
+        public void setup() throws IOException {
+            cx = Context.enter();
+            cx.setOptimizationLevel(9);
+            cx.setLanguageVersion(Context.VERSION_ES6);
+            scope = cx.initStandardObjects();
+
+            try (FileReader rdr = new FileReader("testsrc/benchmarks/micro/math-benchmarks.js")) {
+                cx.evaluateReader(scope, rdr, "math-benchmarks.js", 1, null);
+            }
+        }
+
+        @TearDown(Level.Trial)
+        public void tearDown() {
+            cx.close();
+        }
+    }
+
+    @State(Scope.Thread)
+    public static class AddIntsState extends GenericState {
+        Function func;
+
+        @Setup(Level.Trial)
+        public void create() throws IOException {
+            super.setup();
+            func = (Function) ScriptableObject.getProperty(scope, "addInts");
+        }
+    }
+
+    @Benchmark
+    public Object addInts(AddIntsState state) {
+        return state.func.call(state.cx, state.scope, null, ScriptRuntime.emptyArgs);
+    }
+
+    @State(Scope.Thread)
+    public static class AddFloatsState extends GenericState {
+        Function func;
+
+        @Setup(Level.Trial)
+        public void create() throws IOException {
+            super.setup();
+            func = (Function) ScriptableObject.getProperty(scope, "addFloats");
+        }
+    }
+
+    @Benchmark
+    public Object addFloats(AddFloatsState state) {
+        return state.func.call(state.cx, state.scope, null, ScriptRuntime.emptyArgs);
+    }
+
+    @State(Scope.Thread)
+    public static class AddTwoFloatsState extends GenericState {
+        Function func;
+
+        @Setup(Level.Trial)
+        public void create() throws IOException {
+            super.setup();
+            func = (Function) ScriptableObject.getProperty(scope, "addTwoFloats");
+        }
+    }
+
+    @Benchmark
+    public Object addTwoFloats(AddTwoFloatsState state) {
+        return state.func.call(state.cx, state.scope, null, ScriptRuntime.emptyArgs);
+    }
+
+    @State(Scope.Thread)
+    public static class AddStringsInLoopState extends GenericState {
+        Function func;
+
+        @Setup(Level.Trial)
+        public void create() throws IOException {
+            super.setup();
+            func = (Function) ScriptableObject.getProperty(scope, "addStringsInLoop");
+        }
+    }
+
+    @Benchmark
+    public Object addStringsInLoop(AddStringsInLoopState state) {
+        return state.func.call(state.cx, state.scope, null, ScriptRuntime.emptyArgs);
+    }
+
+    @State(Scope.Thread)
+    public static class AddMixedStringsState extends GenericState {
+        Function func;
+
+        @Setup(Level.Trial)
+        public void create() throws IOException {
+            super.setup();
+            func = (Function) ScriptableObject.getProperty(scope, "addMixedStrings");
+        }
+    }
+
+    @Benchmark
+    public Object addMixedStrings(AddMixedStringsState state) {
+        return state.func.call(state.cx, state.scope, null, ScriptRuntime.emptyArgs);
+    }
+
+    @State(Scope.Thread)
+    public static class SubtractIntsState extends GenericState {
+        Function func;
+
+        @Setup(Level.Trial)
+        public void create() throws IOException {
+            super.setup();
+            func = (Function) ScriptableObject.getProperty(scope, "subtractInts");
+        }
+    }
+
+    @Benchmark
+    public Object subtractInts(SubtractIntsState state) {
+        return state.func.call(state.cx, state.scope, null, ScriptRuntime.emptyArgs);
+    }
+
+    @State(Scope.Thread)
+    public static class SubtractFloatsState extends GenericState {
+        Function func;
+
+        @Setup(Level.Trial)
+        public void create() throws IOException {
+            super.setup();
+            func = (Function) ScriptableObject.getProperty(scope, "subtractFloats");
+        }
+    }
+
+    @Benchmark
+    public Object subtractFloats(SubtractFloatsState state) {
+        return state.func.call(state.cx, state.scope, null, ScriptRuntime.emptyArgs);
+    }
+
+    @State(Scope.Thread)
+    public static class SubtractTwoFloatsState extends GenericState {
+        Function func;
+
+        @Setup(Level.Trial)
+        public void create() throws IOException {
+            super.setup();
+            func = (Function) ScriptableObject.getProperty(scope, "subtractTwoFloats");
+        }
+    }
+
+    @Benchmark
+    public Object subtractTwoFloats(SubtractTwoFloatsState state) {
+        return state.func.call(state.cx, state.scope, null, ScriptRuntime.emptyArgs);
+    }
+
+    @State(Scope.Thread)
+    public static class AndState extends GenericState {
+        Function func;
+
+        @Setup(Level.Trial)
+        public void create() throws IOException {
+            super.setup();
+            func = (Function) ScriptableObject.getProperty(scope, "bitwiseAnd");
+        }
+    }
+
+    @Benchmark
+    public Object bitwiseAnd(AndState state) {
+        return state.func.call(state.cx, state.scope, null, ScriptRuntime.emptyArgs);
+    }
+
+    @State(Scope.Thread)
+    public static class OrState extends GenericState {
+        Function func;
+
+        @Setup(Level.Trial)
+        public void create() throws IOException {
+            super.setup();
+            func = (Function) ScriptableObject.getProperty(scope, "bitwiseOr");
+        }
+    }
+
+    @Benchmark
+    public Object bitwiseOr(OrState state) {
+        return state.func.call(state.cx, state.scope, null, ScriptRuntime.emptyArgs);
+    }
+
+    @State(Scope.Thread)
+    public static class LshState extends GenericState {
+        Function func;
+
+        @Setup(Level.Trial)
+        public void create() throws IOException {
+            super.setup();
+            func = (Function) ScriptableObject.getProperty(scope, "bitwiseLsh");
+        }
+    }
+
+    @Benchmark
+    public Object bitwiseLsh(LshState state) {
+        return state.func.call(state.cx, state.scope, null, ScriptRuntime.emptyArgs);
+    }
+
+    @State(Scope.Thread)
+    public static class RshState extends GenericState {
+        Function func;
+
+        @Setup(Level.Trial)
+        public void create() throws IOException {
+            super.setup();
+            func = (Function) ScriptableObject.getProperty(scope, "bitwiseRsh");
+        }
+    }
+
+    @Benchmark
+    public Object bitwiseRsh(RshState state) {
+        return state.func.call(state.cx, state.scope, null, ScriptRuntime.emptyArgs);
+    }
+
+    @State(Scope.Thread)
+    public static class SignedRshState extends GenericState {
+        Function func;
+
+        @Setup(Level.Trial)
+        public void create() throws IOException {
+            super.setup();
+            func = (Function) ScriptableObject.getProperty(scope, "bitwiseSignedRsh");
+        }
+    }
+
+    @Benchmark
+    public Object bitwiseSignedRsh(SignedRshState state) {
+        return state.func.call(state.cx, state.scope, null, ScriptRuntime.emptyArgs);
+    }
+}
diff --git a/build.gradle b/build.gradle
index cbd80a3..5576ff1 100644
--- a/build.gradle
+++ b/build.gradle
@@ -108,10 +108,10 @@
 testBenchmark.dependsOn sunSpiderBenchmark
 testBenchmark.dependsOn v8Benchmark
 
-task builtinBenchmarks(type: JavaExec, description: 'JMH benchmarks') {
+task microBenchmark(type: JavaExec, description: 'JMH benchmarks') {
     classpath = sourceSets.jmh.runtimeClasspath
     main = 'org.openjdk.jmh.Main'
-    args '-f', '1', '-bm', 'avgt', '-tu', 'ns', 'Builtin'
+    args '-f', '1', '-bm', 'avgt', '-tu', 'ns', 'MathBenchmark'
 }
 
 task jmhHelp(type: JavaExec, description: 'JMH benchmarks') {
diff --git a/src/org/mozilla/javascript/ScriptRuntime.java b/src/org/mozilla/javascript/ScriptRuntime.java
index d24fd3e..3ecac5f 100644
--- a/src/org/mozilla/javascript/ScriptRuntime.java
+++ b/src/org/mozilla/javascript/ScriptRuntime.java
@@ -2855,7 +2855,7 @@
             throw ScriptRuntime.typeErrorById("msg.cant.convert.to.number", "BigInt");
         }
         if (val1 instanceof Number && val2 instanceof Number) {
-            return wrapNumber(((Number) val1).doubleValue() + ((Number) val2).doubleValue());
+            return ((Number) val1).doubleValue() + ((Number) val2).doubleValue();
         }
         if (val1 instanceof XMLObject) {
             Object test = ((XMLObject) val1).addValues(cx, true, val2);
diff --git a/src/org/mozilla/javascript/optimizer/BodyCodegen.java b/src/org/mozilla/javascript/optimizer/BodyCodegen.java
index a8e73f4..54db3fb 100644
--- a/src/org/mozilla/javascript/optimizer/BodyCodegen.java
+++ b/src/org/mozilla/javascript/optimizer/BodyCodegen.java
@@ -1195,19 +1195,23 @@
                             cfw.add(ByteCode.DADD);
                             break;
                         case Node.LEFT:
-                            addOptRuntimeInvoke("add", "(DLjava/lang/Object;)Ljava/lang/Object;");
+                            cfw.addALoad(contextLocal);
+                            addOptRuntimeInvoke(
+                                    "add",
+                                    "(DLjava/lang/Object;Lorg/mozilla/javascript/Context;)Ljava/lang/Object;");
                             break;
                         case Node.RIGHT:
-                            addOptRuntimeInvoke("add", "(Ljava/lang/Object;D)Ljava/lang/Object;");
+                            cfw.addALoad(contextLocal);
+                            addOptRuntimeInvoke(
+                                    "add",
+                                    "(Ljava/lang/Object;DLorg/mozilla/javascript/Context;)Ljava/lang/Object;");
                             break;
                         default:
                             cfw.addALoad(contextLocal);
-                            addScriptRuntimeInvoke(
-                                    "add",
-                                    "(Ljava/lang/Object;"
-                                            + "Ljava/lang/Object;"
-                                            + "Lorg/mozilla/javascript/Context;"
-                                            + ")Ljava/lang/Object;");
+                            cfw.addInvokeDynamic(
+                                    DynamicRuntime.ADD_OP,
+                                    DynamicRuntime.METHOD_SIGNATURE_OOC,
+                                    DynamicRuntime.BOOTSTRAP_HANDLE);
                     }
                 }
                 break;
diff --git a/src/org/mozilla/javascript/optimizer/DynamicRuntime.java b/src/org/mozilla/javascript/optimizer/DynamicRuntime.java
new file mode 100644
index 0000000..07bb395
--- /dev/null
+++ b/src/org/mozilla/javascript/optimizer/DynamicRuntime.java
@@ -0,0 +1,99 @@
+package org.mozilla.javascript.optimizer;
+
+import java.lang.invoke.CallSite;
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodType;
+import org.mozilla.classfile.ByteCode;
+import org.mozilla.classfile.ClassFileWriter.MHandle;
+import org.mozilla.javascript.ConsString;
+import org.mozilla.javascript.Context;
+import org.mozilla.javascript.Kit;
+import org.mozilla.javascript.ScriptRuntime;
+
+public class DynamicRuntime {
+    public static final String ADD_OP = "add";
+
+    public static final String BOOTSTRAP_SIGNATURE =
+            "(Ljava/lang/invoke/MethodHandles$Lookup;"
+                    + "Ljava/lang/String;"
+                    + "Ljava/lang/invoke/MethodType;"
+                    + ")Ljava/lang/invoke/CallSite;";
+    public static final String METHOD_SIGNATURE_OOC =
+            "(Ljava/lang/Object;Ljava/lang/Object;Lorg/mozilla/javascript/Context;)Ljava/lang/Object;";
+
+    public static final MHandle BOOTSTRAP_HANDLE =
+            new MHandle(
+                    ByteCode.MH_INVOKESTATIC,
+                    "org.mozilla.javascript.optimizer.DynamicRuntime",
+                    "bootstrap",
+                    DynamicRuntime.BOOTSTRAP_SIGNATURE);
+
+    /** Perform an add assuming both arguments are Integer objects and fail otherwise. */
+    public static Object addIntegers(Object o1, Object o2, Context cx) {
+        try {
+            return (Integer) o1 + (Integer) o2;
+        } catch (ClassCastException | NullPointerException e) {
+            throw new FallbackException();
+        }
+    }
+
+    /** Perform an add assuming both arguments are Double objects and fail otherwise. */
+    public static Object addFloats(Object o1, Object o2, Context cx) {
+        try {
+            return (Double) o1 + (Double) o2;
+        } catch (ClassCastException | NullPointerException e) {
+            throw new FallbackException();
+        }
+    }
+
+    /** Perform an add assuming both arguments are CharSequence objects and fail otherwise. */
+    public static Object addCharSequences(Object o1, Object o2, Context cx) {
+        try {
+            return new ConsString((CharSequence) o1, (CharSequence) o2);
+        } catch (ClassCastException | NullPointerException e) {
+            throw new FallbackException();
+        }
+    }
+
+    /**
+     * This will be called by the call site when one method fails -- it is expected to invoke the
+     * next one in the chain. A separate method is required for each call signature that we support.
+     */
+    public static Object fallbackOOC(
+            FallbackException fe,
+            Object arg1,
+            Object arg2,
+            Context cx,
+            FallbackCallSite site,
+            int nonce)
+            throws Throwable {
+        MethodHandle fallbackHandle = site.fallBack(nonce);
+        return fallbackHandle.invokeExact(arg1, arg2, cx);
+    }
+
+    /**
+     * This is the function that is the target of the actual "invokedynamic" instruction in the
+     * bytecode. The "name" parameter selects the actual function to set up.
+     */
+    @SuppressWarnings("unused")
+    public static CallSite bootstrap(MethodHandles.Lookup lookup, String name, MethodType mType)
+            throws NoSuchMethodException, IllegalAccessException {
+        switch (name) {
+            case ADD_OP:
+                // Implement "add" by trying fast paths for Integer, Double, and CharSequences,
+                // before finally falling back to regular old ScriptRuntime.
+                return new FallbackCallSite(
+                        lookup.findStatic(
+                                DynamicRuntime.class,
+                                "fallbackOOC",
+                                FallbackCallSite.makeFallbackCallType(mType)),
+                        lookup.findStatic(DynamicRuntime.class, "addIntegers", mType),
+                        lookup.findStatic(DynamicRuntime.class, "addFloats", mType),
+                        lookup.findStatic(DynamicRuntime.class, "addCharSequences", mType),
+                        lookup.findStatic(ScriptRuntime.class, "add", mType));
+            default:
+                throw Kit.codeBug("Invalid bootstrap op " + name);
+        }
+    }
+}
diff --git a/src/org/mozilla/javascript/optimizer/FallbackCallSite.java b/src/org/mozilla/javascript/optimizer/FallbackCallSite.java
new file mode 100644
index 0000000..e96fc26
--- /dev/null
+++ b/src/org/mozilla/javascript/optimizer/FallbackCallSite.java
@@ -0,0 +1,102 @@
+package org.mozilla.javascript.optimizer;
+
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodType;
+import java.lang.invoke.MutableCallSite;
+import org.mozilla.javascript.Kit;
+
+/*
+ * This class extends MutableCallSite to support a CallSite that goes through a list of candidate
+ * method handles. It always delegates to the next handle in the chain when a FallbackException
+ * is thrown. After a certain number of fallbacks, it pops a method from the chain and skips the failure.
+ *
+ * The idea of this class is to optimize call sites where prerequisites can be discarded. Generally
+ * a method will make assumptions about whether it can operate at the particular site and throw
+ * FallbackException if it can't.
+ *
+ * By eventually taking methods out of the chain when they have failed too many times, we can
+ * relatively quickly discover the most efficient method for a particular call site, or fail
+ * over to a generic method if, in the end, none will work.
+ */
+public class FallbackCallSite extends MutableCallSite {
+    private static final int MAX_FAILURES = 10;
+
+    private final MethodHandle fallbackHandle;
+    private final MethodHandle[] handles;
+    private int index = 0;
+    private int failures = 0;
+
+    /**
+     * This is a convenience method to turn the method signature of a regular call to one for the
+     * "fallbackHandle" argument to FallbackCallSite. By adding a FallbackException as the first
+     * parameter and FallbackCallSite and integer as the last. This makes it easier to construct the
+     * list of handles for the constructor.
+     */
+    public static MethodType makeFallbackCallType(MethodType mType) {
+        return mType.insertParameterTypes(0, FallbackException.class)
+                .appendParameterTypes(FallbackCallSite.class)
+                .appendParameterTypes(Integer.TYPE);
+    }
+
+    /**
+     * Create a new CallSite that will invoke each of the "targetHandles" in order. Any handle but
+     * the last may throw FallbackException to cause a fallback invocation of the next handle in the
+     * chain.
+     *
+     * <p>"fallbackHandle" must be a handle to a method with the same signature as all of the
+     * "targetHandles," but which takes a FallbackException as the first parameter and
+     * FallbackCallSite as the last. It must call "fallBack()" on this handle and use the returned
+     * MethodHandle to invoke the fallback method.
+     */
+    public FallbackCallSite(MethodHandle fallbackHandle, MethodHandle... targetHandles) {
+        super(targetHandles[0].type());
+        this.fallbackHandle = fallbackHandle;
+        this.handles = targetHandles;
+
+        // Wrap all but the last handle with an exception handler for FallbackException
+        // that will call the callback method.
+        // The last handle in the chain will not catch this special exception.
+        for (int i = 0; i < handles.length - 1; i++) {
+            convertHandle(i);
+        }
+        setTarget(handles[0]);
+    }
+
+    private void convertHandle(int ix) {
+        assert (ix < handles.length - 1);
+        MethodHandle fallbackMethod =
+                MethodHandles.insertArguments(
+                        fallbackHandle, fallbackHandle.type().parameterCount() - 2, this, ix + 1);
+        MethodHandle catchMethod =
+                MethodHandles.catchException(handles[ix], FallbackException.class, fallbackMethod);
+        handles[ix] = catchMethod;
+    }
+
+    /**
+     * Callers must call this in the "fallback" method to determine which method to invoke next. It
+     * returns a handle that can be used to invoke the next handle in the chain. Callers must call
+     * that handle.
+     *
+     * <p>The "nonce" parameter is passed to the fallback method and must be passed on to this
+     * method. It prevents us from prematurely falling back down the chain if there is an
+     * inconsistency because this method is being used in a multi-threaded situation.
+     *
+     * @param nonce this must be the integer that was supplied to the fallback method.
+     */
+    public MethodHandle fallBack(int nonce) {
+        failures++;
+        if (index < handles.length - 1) {
+            MethodHandle fallbackHandle = handles[nonce];
+            if (failures >= MAX_FAILURES && index < nonce) {
+                // Exceeded max failures, so change the target so that we now always
+                // invoke the next target handle in the chain directly
+                index = nonce;
+                failures = 0;
+                setTarget(fallbackHandle);
+            }
+            return fallbackHandle;
+        }
+        throw Kit.codeBug("Invalid fallback handle");
+    }
+}
diff --git a/src/org/mozilla/javascript/optimizer/FallbackException.java b/src/org/mozilla/javascript/optimizer/FallbackException.java
new file mode 100644
index 0000000..3659717
--- /dev/null
+++ b/src/org/mozilla/javascript/optimizer/FallbackException.java
@@ -0,0 +1,9 @@
+package org.mozilla.javascript.optimizer;
+
+/**
+ * Methods invoked using InvokeDynamic can throw this exception to indicate that they are not able
+ * to operate on the current call site and should be potentially replaced by a more generic method.
+ */
+public class FallbackException extends RuntimeException {
+    public FallbackException() {}
+}
diff --git a/src/org/mozilla/javascript/optimizer/OptRuntime.java b/src/org/mozilla/javascript/optimizer/OptRuntime.java
index 9b3efd0..f0a8676 100644
--- a/src/org/mozilla/javascript/optimizer/OptRuntime.java
+++ b/src/org/mozilla/javascript/optimizer/OptRuntime.java
@@ -6,7 +6,6 @@
 
 import org.mozilla.javascript.ArrowFunction;
 import org.mozilla.javascript.Callable;
-import org.mozilla.javascript.ConsString;
 import org.mozilla.javascript.Context;
 import org.mozilla.javascript.ContextFactory;
 import org.mozilla.javascript.ES6Generator;
@@ -74,16 +73,16 @@
         return f.call(cx, scope, thisObj, ScriptRuntime.emptyArgs);
     }
 
-    public static Object add(Object val1, double val2) {
-        if (val1 instanceof Scriptable) val1 = ((Scriptable) val1).getDefaultValue(null);
-        if (!(val1 instanceof CharSequence)) return wrapDouble(toNumber(val1) + val2);
-        return new ConsString((CharSequence) val1, toString(val2));
+    public static Object add(Object val1, double val2, Context cx) {
+        if (val1 instanceof Integer) return (Integer) val1 + val2;
+        if (val1 instanceof Double) return (Double) val1 + val2;
+        return ScriptRuntime.add(val1, val2, cx);
     }
 
-    public static Object add(double val1, Object val2) {
-        if (val2 instanceof Scriptable) val2 = ((Scriptable) val2).getDefaultValue(null);
-        if (!(val2 instanceof CharSequence)) return wrapDouble(toNumber(val2) + val1);
-        return new ConsString(toString(val1), (CharSequence) val2);
+    public static Object add(double val1, Object val2, Context cx) {
+        if (val2 instanceof Integer) return val1 + (Integer) val2;
+        if (val2 instanceof Double) return val1 + (Double) val2;
+        return ScriptRuntime.add(val1, val2, cx);
     }
 
     /** @deprecated Use {@link #elemIncrDecr(Object, double, Context, Scriptable, int)} instead */
diff --git a/testsrc/benchmarks/micro/math-benchmarks.js b/testsrc/benchmarks/micro/math-benchmarks.js
new file mode 100644
index 0000000..54b7cf2
--- /dev/null
+++ b/testsrc/benchmarks/micro/math-benchmarks.js
@@ -0,0 +1,110 @@
+'use strict';
+
+function assertEquals(x, y) {
+  if (x !== y) {
+    throw 'Expected ' + x + ' to equal ' + y;
+  }
+}
+
+function makeOne() {
+  return 1;
+}
+
+function makeFour() {
+  return 2 + 2;
+}
+
+function makeTwo() {
+  return 1 + 1;
+}
+
+function makePi() {
+  return 3.14;
+}
+
+function addInts() {
+  let result = makeTwo() + 2;
+  assertEquals(result,  4);
+  return result;
+}
+
+function addFloats() {
+  let result = makePi() + 1.1;
+  assertEquals(result,  4.24);
+  return result;
+}
+
+function addTwoFloats() {
+  let result = makePi() + makePi();
+  assertEquals(result,  6.28);
+  return result;
+}
+
+function subtractInts() {
+  let result = 4 - makeTwo();
+  assertEquals(result, 2);
+  return result;
+}
+
+function subtractFloats() {
+  let result = makePi() - 0.4;
+  assertEquals(result, 2.74);
+  return result;
+}
+
+function subtractTwoFloats() {
+  let result = makePi() - makePi();
+  assertEquals(result, 0);
+  return result;
+}
+
+function bitwiseAnd() {
+  let result = makeFour() & makeTwo();
+  assertEquals(result, 0);
+  return result;
+}
+
+function bitwiseOr() {
+  let result = makeFour() | makeTwo();
+  assertEquals(result, 6);
+  return result;
+}
+
+function bitwiseLsh() {
+  let result = makeTwo() << makeOne();
+  assertEquals(result, 4);
+  return result;
+}
+
+function bitwiseRsh() {
+  let result = makeFour() >> makeOne();
+  assertEquals(result, 2);
+  return result;
+}
+
+function bitwiseSignedRsh() {
+  let result = makeFour() >>> makeOne();
+  assertEquals(result, 2);
+  return result;
+}
+
+function addStringsInLoop() {
+  let s = "";
+  for (var i = 0; i < 10; i++) {
+    s += "aa";
+  }
+  assertEquals(s, "aaaaaaaaaaaaaaaaaaaa");
+  return s;
+}
+
+function addMixedStrings() {
+  let s = "Foo " + 100 + " bars, " + true + "!";
+  assertEquals(s, "Foo 100 bars, true!");
+  return s;
+}
+
+addInts();
+addFloats();
+addTwoFloats();
+addStringsInLoop();
+addMixedStrings();
\ No newline at end of file
diff --git a/testsrc/org/mozilla/javascript/tests/FallbackCallSiteTest.java b/testsrc/org/mozilla/javascript/tests/FallbackCallSiteTest.java
new file mode 100644
index 0000000..eb4a423
--- /dev/null
+++ b/testsrc/org/mozilla/javascript/tests/FallbackCallSiteTest.java
@@ -0,0 +1,120 @@
+package org.mozilla.javascript.tests;
+
+import static org.junit.Assert.*;
+
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodType;
+import org.junit.Test;
+import org.mozilla.javascript.optimizer.FallbackCallSite;
+import org.mozilla.javascript.optimizer.FallbackException;
+
+public class FallbackCallSiteTest {
+    private static final MethodType testMethodType = MethodType.methodType(String.class);
+
+    private static int alwaysFailInvokeCount = 0;
+
+    private static String getMessage() {
+        return "Hello, World!";
+    }
+
+    private static String alwaysFail() {
+        throw new FallbackException();
+    }
+
+    private static String sometimesFail() {
+        if (alwaysFailInvokeCount++ % 3 == 0) {
+            throw new FallbackException();
+        }
+        return "Hello, World!";
+    }
+
+    private static String fallback(FallbackException fe, FallbackCallSite site, int nonce)
+            throws Throwable {
+        MethodHandle nextCall = site.fallBack(nonce);
+        return (String) nextCall.invoke();
+    }
+
+    // Just test with one method that always works
+    @Test
+    public void testNoFallback() throws NoSuchMethodException, IllegalAccessException {
+        MethodHandles.Lookup lookup = MethodHandles.lookup();
+        FallbackCallSite site =
+                new FallbackCallSite(
+                        lookup.findStatic(
+                                FallbackCallSiteTest.class,
+                                "fallback",
+                                FallbackCallSite.makeFallbackCallType(testMethodType)),
+                        lookup.findStatic(
+                                FallbackCallSiteTest.class, "getMessage", testMethodType));
+        MethodHandle invoker = site.dynamicInvoker();
+
+        // We should be able to invoke over and over and eventually we will
+        // fail over, but every call should work
+        for (int i = 0; i < 20; i++) {
+            try {
+                Object result = invoker.invoke();
+                assertEquals("Hello, World!", result);
+            } catch (Throwable t) {
+                fail("Did not expect an exception: " + t);
+            }
+        }
+    }
+
+    // Test a method that always fails and ensure that it always falls back
+    // to the method that does not
+    @Test
+    public void testFallback() throws NoSuchMethodException, IllegalAccessException {
+        MethodHandles.Lookup lookup = MethodHandles.lookup();
+        FallbackCallSite site =
+                new FallbackCallSite(
+                        lookup.findStatic(
+                                FallbackCallSiteTest.class,
+                                "fallback",
+                                FallbackCallSite.makeFallbackCallType(testMethodType)),
+                        lookup.findStatic(FallbackCallSiteTest.class, "alwaysFail", testMethodType),
+                        lookup.findStatic(
+                                FallbackCallSiteTest.class, "getMessage", testMethodType));
+        MethodHandle invoker = site.dynamicInvoker();
+
+        // We should be able to invoke over and over and eventually we will
+        // fail over, but every call should work
+        for (int i = 0; i < 20; i++) {
+            try {
+                Object result = invoker.invoke();
+                assertEquals("Hello, World!", result);
+            } catch (Throwable t) {
+                fail("Did not expect an exception: " + t);
+            }
+        }
+    }
+
+    // Test a chain of three calls, with one in the middle that sometimes fails
+    @Test
+    public void testFallbackThree() throws NoSuchMethodException, IllegalAccessException {
+        MethodHandles.Lookup lookup = MethodHandles.lookup();
+        FallbackCallSite site =
+                new FallbackCallSite(
+                        lookup.findStatic(
+                                FallbackCallSiteTest.class,
+                                "fallback",
+                                FallbackCallSite.makeFallbackCallType(testMethodType)),
+                        lookup.findStatic(FallbackCallSiteTest.class, "alwaysFail", testMethodType),
+                        lookup.findStatic(
+                                FallbackCallSiteTest.class, "sometimesFail", testMethodType),
+                        lookup.findStatic(
+                                FallbackCallSiteTest.class, "getMessage", testMethodType));
+        MethodHandle invoker = site.dynamicInvoker();
+
+        // We should be able to invoke over and over and eventually we will
+        // fail over, but every call should work
+        for (int i = 0; i < 100; i++) {
+            try {
+                Object result = invoker.invoke();
+                assertEquals("Hello, World!", result);
+            } catch (Throwable t) {
+                fail("Did not expect an exception: " + t);
+            }
+        }
+    }
+}