8200301: deduplicate lambda methods
authorcushon
Tue, 27 Mar 2018 13:48:16 -0400
changeset 49429 752ecccb0b7f
parent 49428 ce86061aff12
child 49430 e376090dc07e
8200301: deduplicate lambda methods Reviewed-by: vromero, mcimadamore
src/jdk.compiler/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java
src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TreeDiffer.java
src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TreeHasher.java
src/jdk.compiler/share/classes/com/sun/tools/javac/resources/compiler.properties
test/langtools/tools/javac/annotations/typeAnnotations/classfile/InstanceInitializer.java
test/langtools/tools/javac/annotations/typeAnnotations/classfile/StaticInitializer.java
test/langtools/tools/javac/classfiles/attributes/Synthetic/BridgeMethodsForLambdaTest.java
test/langtools/tools/javac/diags/examples/LambdaDeduplicate.java
test/langtools/tools/javac/lambda/deduplication/Deduplication.java
test/langtools/tools/javac/lambda/deduplication/DeduplicationTest.java
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java	Mon Mar 26 21:30:33 2018 -0700
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java	Tue Mar 27 13:48:16 2018 -0400
@@ -56,6 +56,7 @@
 import java.util.HashSet;
 import java.util.LinkedHashMap;
 import java.util.Map;
+import java.util.Objects;
 import java.util.Optional;
 import java.util.Set;
 import java.util.function.Consumer;
@@ -113,6 +114,15 @@
     /** force serializable representation, for stress testing **/
     private final boolean forceSerializable;
 
+    /** true if line or local variable debug info has been requested */
+    private final boolean debugLinesOrVars;
+
+    /** dump statistics about lambda method deduplication */
+    private final boolean verboseDeduplication;
+
+    /** deduplicate lambda implementation methods */
+    private final boolean deduplicateLambdas;
+
     /** Flag for alternate metafactories indicating the lambda object is intended to be serializable */
     public static final int FLAG_SERIALIZABLE = 1 << 0;
 
@@ -149,9 +159,64 @@
         dumpLambdaToMethodStats = options.isSet("debug.dumpLambdaToMethodStats");
         attr = Attr.instance(context);
         forceSerializable = options.isSet("forceSerializable");
+        debugLinesOrVars = options.isSet(Option.G)
+                || options.isSet(Option.G_CUSTOM, "lines")
+                || options.isSet(Option.G_CUSTOM, "vars");
+        verboseDeduplication = options.isSet("debug.dumpLambdaToMethodDeduplication");
+        deduplicateLambdas = options.getBoolean("deduplicateLambdas", true);
     }
     // </editor-fold>
 
+    class DedupedLambda {
+        private final MethodSymbol symbol;
+        private final JCTree tree;
+
+        private int hashCode;
+
+        DedupedLambda(MethodSymbol symbol, JCTree tree) {
+            this.symbol = symbol;
+            this.tree = tree;
+        }
+
+
+        @Override
+        public int hashCode() {
+            int hashCode = this.hashCode;
+            if (hashCode == 0) {
+                this.hashCode = hashCode = TreeHasher.hash(tree, sym -> {
+                    if (sym.owner == symbol) {
+                        int idx = symbol.params().indexOf(sym);
+                        if (idx != -1) {
+                            return idx;
+                        }
+                    }
+                    return null;
+                });
+            }
+            return hashCode;
+        }
+
+        @Override
+        public boolean equals(Object o) {
+            if (!(o instanceof DedupedLambda)) {
+                return false;
+            }
+            DedupedLambda that = (DedupedLambda) o;
+            return types.isSameType(symbol.asType(), that.symbol.asType())
+                    && new TreeDiffer((lhs, rhs) -> {
+                if (lhs.owner == symbol) {
+                    int idx = symbol.params().indexOf(lhs);
+                    if (idx != -1) {
+                        if (Objects.equals(idx, that.symbol.params().indexOf(rhs))) {
+                            return true;
+                        }
+                    }
+                }
+                return null;
+            }).scan(tree, that.tree);
+        }
+    }
+
     private class KlassInfo {
 
         /**
@@ -159,6 +224,8 @@
          */
         private ListBuffer<JCTree> appendedMethodList;
 
+        private Map<DedupedLambda, DedupedLambda> dedupedLambdas;
+
         /**
          * list of deserialization cases
          */
@@ -179,6 +246,7 @@
         private KlassInfo(JCClassDecl clazz) {
             this.clazz = clazz;
             appendedMethodList = new ListBuffer<>();
+            dedupedLambdas = new HashMap<>();
             deserializeCases = new HashMap<>();
             MethodType type = new MethodType(List.of(syms.serializedLambdaType), syms.objectType,
                     List.nil(), syms.methodClass);
@@ -329,8 +397,20 @@
         //captured members directly).
         lambdaDecl.body = translate(makeLambdaBody(tree, lambdaDecl));
 
-        //Add the method to the list of methods to be added to this class.
-        kInfo.addMethod(lambdaDecl);
+        boolean dedupe = false;
+        if (deduplicateLambdas && !debugLinesOrVars && !localContext.isSerializable()) {
+            DedupedLambda dedupedLambda = new DedupedLambda(lambdaDecl.sym, lambdaDecl.body);
+            DedupedLambda existing = kInfo.dedupedLambdas.putIfAbsent(dedupedLambda, dedupedLambda);
+            if (existing != null) {
+                sym = existing.symbol;
+                dedupe = true;
+                if (verboseDeduplication) log.note(tree, Notes.VerboseL2mDeduplicate(sym));
+            }
+        }
+        if (!dedupe) {
+            //Add the method to the list of methods to be added to this class.
+            kInfo.addMethod(lambdaDecl);
+        }
 
         //now that we have generated a method for the lambda expression,
         //we can translate the lambda into a method reference pointing to the newly
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TreeDiffer.java	Tue Mar 27 13:48:16 2018 -0400
@@ -0,0 +1,614 @@
+/*
+ * Copyright (c) 2018, Google LLC. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.tools.javac.comp;
+
+import com.sun.tools.javac.code.Symbol;
+import com.sun.tools.javac.tree.JCTree;
+import com.sun.tools.javac.tree.JCTree.JCAnnotatedType;
+import com.sun.tools.javac.tree.JCTree.JCAnnotation;
+import com.sun.tools.javac.tree.JCTree.JCArrayAccess;
+import com.sun.tools.javac.tree.JCTree.JCArrayTypeTree;
+import com.sun.tools.javac.tree.JCTree.JCAssert;
+import com.sun.tools.javac.tree.JCTree.JCAssign;
+import com.sun.tools.javac.tree.JCTree.JCAssignOp;
+import com.sun.tools.javac.tree.JCTree.JCBinary;
+import com.sun.tools.javac.tree.JCTree.JCBlock;
+import com.sun.tools.javac.tree.JCTree.JCBreak;
+import com.sun.tools.javac.tree.JCTree.JCCase;
+import com.sun.tools.javac.tree.JCTree.JCCatch;
+import com.sun.tools.javac.tree.JCTree.JCClassDecl;
+import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
+import com.sun.tools.javac.tree.JCTree.JCConditional;
+import com.sun.tools.javac.tree.JCTree.JCContinue;
+import com.sun.tools.javac.tree.JCTree.JCDoWhileLoop;
+import com.sun.tools.javac.tree.JCTree.JCEnhancedForLoop;
+import com.sun.tools.javac.tree.JCTree.JCErroneous;
+import com.sun.tools.javac.tree.JCTree.JCExports;
+import com.sun.tools.javac.tree.JCTree.JCExpressionStatement;
+import com.sun.tools.javac.tree.JCTree.JCFieldAccess;
+import com.sun.tools.javac.tree.JCTree.JCForLoop;
+import com.sun.tools.javac.tree.JCTree.JCIdent;
+import com.sun.tools.javac.tree.JCTree.JCIf;
+import com.sun.tools.javac.tree.JCTree.JCImport;
+import com.sun.tools.javac.tree.JCTree.JCInstanceOf;
+import com.sun.tools.javac.tree.JCTree.JCLabeledStatement;
+import com.sun.tools.javac.tree.JCTree.JCLambda;
+import com.sun.tools.javac.tree.JCTree.JCLiteral;
+import com.sun.tools.javac.tree.JCTree.JCMemberReference;
+import com.sun.tools.javac.tree.JCTree.JCMethodDecl;
+import com.sun.tools.javac.tree.JCTree.JCMethodInvocation;
+import com.sun.tools.javac.tree.JCTree.JCModifiers;
+import com.sun.tools.javac.tree.JCTree.JCModuleDecl;
+import com.sun.tools.javac.tree.JCTree.JCNewArray;
+import com.sun.tools.javac.tree.JCTree.JCNewClass;
+import com.sun.tools.javac.tree.JCTree.JCOpens;
+import com.sun.tools.javac.tree.JCTree.JCPackageDecl;
+import com.sun.tools.javac.tree.JCTree.JCPrimitiveTypeTree;
+import com.sun.tools.javac.tree.JCTree.JCProvides;
+import com.sun.tools.javac.tree.JCTree.JCRequires;
+import com.sun.tools.javac.tree.JCTree.JCReturn;
+import com.sun.tools.javac.tree.JCTree.JCSwitch;
+import com.sun.tools.javac.tree.JCTree.JCSynchronized;
+import com.sun.tools.javac.tree.JCTree.JCThrow;
+import com.sun.tools.javac.tree.JCTree.JCTry;
+import com.sun.tools.javac.tree.JCTree.JCTypeApply;
+import com.sun.tools.javac.tree.JCTree.JCTypeCast;
+import com.sun.tools.javac.tree.JCTree.JCTypeIntersection;
+import com.sun.tools.javac.tree.JCTree.JCTypeParameter;
+import com.sun.tools.javac.tree.JCTree.JCTypeUnion;
+import com.sun.tools.javac.tree.JCTree.JCUnary;
+import com.sun.tools.javac.tree.JCTree.JCUses;
+import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
+import com.sun.tools.javac.tree.JCTree.JCWhileLoop;
+import com.sun.tools.javac.tree.JCTree.JCWildcard;
+import com.sun.tools.javac.tree.JCTree.LetExpr;
+import com.sun.tools.javac.tree.JCTree.TypeBoundKind;
+import com.sun.tools.javac.tree.TreeInfo;
+import com.sun.tools.javac.tree.TreeScanner;
+import com.sun.tools.javac.util.List;
+
+import javax.lang.model.element.ElementKind;
+import java.util.Iterator;
+import java.util.Objects;
+import java.util.function.BiFunction;
+import java.util.function.Consumer;
+
+/** A visitor that compares two lambda bodies for structural equality. */
+public class TreeDiffer extends TreeScanner {
+
+    private BiFunction<Symbol, Symbol, Boolean> symbolDiffer;
+
+    public TreeDiffer(BiFunction<Symbol, Symbol, Boolean> symbolDiffer) {
+        this.symbolDiffer = Objects.requireNonNull(symbolDiffer);
+    }
+
+    private JCTree parameter;
+    private boolean result;
+
+    public boolean scan(JCTree tree, JCTree parameter) {
+        if (tree == null || parameter == null) {
+            return tree == null && parameter == null;
+        }
+        tree = TreeInfo.skipParens(tree);
+        parameter = TreeInfo.skipParens(parameter);
+        if (tree.type != null
+                && tree.type.constValue() != null
+                && parameter.type != null
+                && parameter.type.constValue() != null) {
+            return Objects.equals(tree.type.constValue(), parameter.type.constValue());
+        }
+        if (tree.getTag() != parameter.getTag()) {
+            return false;
+        }
+        JCTree prevParameter = this.parameter;
+        boolean prevResult = this.result;
+        try {
+            this.parameter = parameter;
+            tree.accept(this);
+            return result;
+        } finally {
+            this.parameter = prevParameter;
+            this.result = prevResult;
+        }
+    }
+
+    private boolean scan(Iterable<? extends JCTree> xs, Iterable<? extends JCTree> ys) {
+        if (xs == null || ys == null) {
+            return xs == null && ys == null;
+        }
+        Iterator<? extends JCTree> x = xs.iterator();
+        Iterator<? extends JCTree> y = ys.iterator();
+        while (x.hasNext() && y.hasNext()) {
+            if (!scan(x.next(), y.next())) {
+                return false;
+            }
+        }
+        return !x.hasNext() && !y.hasNext();
+    }
+
+    private boolean scanDimAnnotations(List<List<JCAnnotation>> xs, List<List<JCAnnotation>> ys) {
+        if (xs == null || ys == null) {
+            return xs == null && ys == null;
+        }
+        Iterator<List<JCAnnotation>> x = xs.iterator();
+        Iterator<List<JCAnnotation>> y = ys.iterator();
+        while (x.hasNext() && y.hasNext()) {
+            if (!scan(x.next(), y.next())) {
+                return false;
+            }
+        }
+        return !x.hasNext() && !y.hasNext();
+    }
+
+    @Override
+    public void visitIdent(JCIdent tree) {
+        JCIdent that = (JCIdent) parameter;
+        // Identifiers are a special case: we want to ensure the identifiers correspond to the
+        // same symbols (rather than just having the same name), but also consider lambdas
+        // equal if they differ only in the names of the parameters.
+        Symbol symbol = tree.sym;
+        Symbol otherSymbol = that.sym;
+        if (symbol != null && otherSymbol != null) {
+            Boolean tmp = symbolDiffer.apply(symbol, otherSymbol);
+            if (tmp != null) {
+                result = tmp;
+                return;
+            }
+        }
+        result = tree.sym == that.sym;
+    }
+
+    @Override
+    public void visitSelect(JCFieldAccess tree) {
+        JCFieldAccess that = (JCFieldAccess) parameter;
+        result = scan(tree.selected, that.selected) && tree.sym == that.sym;
+    }
+
+    @Override
+    public void visitAnnotatedType(JCAnnotatedType tree) {
+        JCAnnotatedType that = (JCAnnotatedType) parameter;
+        result =
+                scan(tree.annotations, that.annotations)
+                        && scan(tree.underlyingType, that.underlyingType);
+    }
+
+    @Override
+    public void visitAnnotation(JCAnnotation tree) {
+        JCAnnotation that = (JCAnnotation) parameter;
+        result = scan(tree.annotationType, that.annotationType) && scan(tree.args, that.args);
+    }
+
+    @Override
+    public void visitApply(JCMethodInvocation tree) {
+        JCMethodInvocation that = (JCMethodInvocation) parameter;
+        result =
+                scan(tree.typeargs, that.typeargs)
+                        && scan(tree.meth, that.meth)
+                        && scan(tree.args, that.args)
+                        && tree.polyKind == that.polyKind;
+    }
+
+    @Override
+    public void visitAssert(JCAssert tree) {
+        JCAssert that = (JCAssert) parameter;
+        result = scan(tree.cond, that.cond) && scan(tree.detail, that.detail);
+    }
+
+    @Override
+    public void visitAssign(JCAssign tree) {
+        JCAssign that = (JCAssign) parameter;
+        result = scan(tree.lhs, that.lhs) && scan(tree.rhs, that.rhs);
+    }
+
+    @Override
+    public void visitAssignop(JCAssignOp tree) {
+        JCAssignOp that = (JCAssignOp) parameter;
+        result =
+                scan(tree.lhs, that.lhs)
+                        && scan(tree.rhs, that.rhs)
+                        && tree.operator == that.operator;
+    }
+
+    @Override
+    public void visitBinary(JCBinary tree) {
+        JCBinary that = (JCBinary) parameter;
+        result =
+                scan(tree.lhs, that.lhs)
+                        && scan(tree.rhs, that.rhs)
+                        && tree.operator == that.operator;
+    }
+
+    @Override
+    public void visitBlock(JCBlock tree) {
+        JCBlock that = (JCBlock) parameter;
+        result = tree.flags == that.flags && scan(tree.stats, that.stats);
+    }
+
+    @Override
+    public void visitBreak(JCBreak tree) {
+        JCBreak that = (JCBreak) parameter;
+        result = tree.label == that.label;
+    }
+
+    @Override
+    public void visitCase(JCCase tree) {
+        JCCase that = (JCCase) parameter;
+        result = scan(tree.pat, that.pat) && scan(tree.stats, that.stats);
+    }
+
+    @Override
+    public void visitCatch(JCCatch tree) {
+        JCCatch that = (JCCatch) parameter;
+        result = scan(tree.param, that.param) && scan(tree.body, that.body);
+    }
+
+    @Override
+    public void visitClassDef(JCClassDecl tree) {
+        JCClassDecl that = (JCClassDecl) parameter;
+        result =
+                scan(tree.mods, that.mods)
+                        && tree.name == that.name
+                        && scan(tree.typarams, that.typarams)
+                        && scan(tree.extending, that.extending)
+                        && scan(tree.implementing, that.implementing)
+                        && scan(tree.defs, that.defs);
+    }
+
+    @Override
+    public void visitConditional(JCConditional tree) {
+        JCConditional that = (JCConditional) parameter;
+        result =
+                scan(tree.cond, that.cond)
+                        && scan(tree.truepart, that.truepart)
+                        && scan(tree.falsepart, that.falsepart);
+    }
+
+    @Override
+    public void visitContinue(JCContinue tree) {
+        JCContinue that = (JCContinue) parameter;
+        result = tree.label == that.label;
+    }
+
+    @Override
+    public void visitDoLoop(JCDoWhileLoop tree) {
+        JCDoWhileLoop that = (JCDoWhileLoop) parameter;
+        result = scan(tree.body, that.body) && scan(tree.cond, that.cond);
+    }
+
+    @Override
+    public void visitErroneous(JCErroneous tree) {
+        JCErroneous that = (JCErroneous) parameter;
+        result = scan(tree.errs, that.errs);
+    }
+
+    @Override
+    public void visitExec(JCExpressionStatement tree) {
+        JCExpressionStatement that = (JCExpressionStatement) parameter;
+        result = scan(tree.expr, that.expr);
+    }
+
+    @Override
+    public void visitExports(JCExports tree) {
+        JCExports that = (JCExports) parameter;
+        result = scan(tree.qualid, that.qualid) && scan(tree.moduleNames, that.moduleNames);
+    }
+
+    @Override
+    public void visitForLoop(JCForLoop tree) {
+        JCForLoop that = (JCForLoop) parameter;
+        result =
+                scan(tree.init, that.init)
+                        && scan(tree.cond, that.cond)
+                        && scan(tree.step, that.step)
+                        && scan(tree.body, that.body);
+    }
+
+    @Override
+    public void visitForeachLoop(JCEnhancedForLoop tree) {
+        JCEnhancedForLoop that = (JCEnhancedForLoop) parameter;
+        result =
+                scan(tree.var, that.var)
+                        && scan(tree.expr, that.expr)
+                        && scan(tree.body, that.body);
+    }
+
+    @Override
+    public void visitIf(JCIf tree) {
+        JCIf that = (JCIf) parameter;
+        result =
+                scan(tree.cond, that.cond)
+                        && scan(tree.thenpart, that.thenpart)
+                        && scan(tree.elsepart, that.elsepart);
+    }
+
+    @Override
+    public void visitImport(JCImport tree) {
+        JCImport that = (JCImport) parameter;
+        result = tree.staticImport == that.staticImport && scan(tree.qualid, that.qualid);
+    }
+
+    @Override
+    public void visitIndexed(JCArrayAccess tree) {
+        JCArrayAccess that = (JCArrayAccess) parameter;
+        result = scan(tree.indexed, that.indexed) && scan(tree.index, that.index);
+    }
+
+    @Override
+    public void visitLabelled(JCLabeledStatement tree) {
+        JCLabeledStatement that = (JCLabeledStatement) parameter;
+        result = tree.label == that.label && scan(tree.body, that.body);
+    }
+
+    @Override
+    public void visitLambda(JCLambda tree) {
+        JCLambda that = (JCLambda) parameter;
+        result =
+                scan(tree.params, that.params)
+                        && scan(tree.body, that.body)
+                        && tree.paramKind == that.paramKind;
+    }
+
+    @Override
+    public void visitLetExpr(LetExpr tree) {
+        LetExpr that = (LetExpr) parameter;
+        result = scan(tree.defs, that.defs) && scan(tree.expr, that.expr);
+    }
+
+    @Override
+    public void visitLiteral(JCLiteral tree) {
+        JCLiteral that = (JCLiteral) parameter;
+        result = tree.typetag == that.typetag && Objects.equals(tree.value, that.value);
+    }
+
+    @Override
+    public void visitMethodDef(JCMethodDecl tree) {
+        JCMethodDecl that = (JCMethodDecl) parameter;
+        result =
+                scan(tree.mods, that.mods)
+                        && tree.name == that.name
+                        && scan(tree.restype, that.restype)
+                        && scan(tree.typarams, that.typarams)
+                        && scan(tree.recvparam, that.recvparam)
+                        && scan(tree.params, that.params)
+                        && scan(tree.thrown, that.thrown)
+                        && scan(tree.body, that.body)
+                        && scan(tree.defaultValue, that.defaultValue);
+    }
+
+    @Override
+    public void visitModifiers(JCModifiers tree) {
+        JCModifiers that = (JCModifiers) parameter;
+        result = tree.flags == that.flags && scan(tree.annotations, that.annotations);
+    }
+
+    @Override
+    public void visitModuleDef(JCModuleDecl tree) {
+        JCModuleDecl that = (JCModuleDecl) parameter;
+        result =
+                scan(tree.mods, that.mods)
+                        && scan(tree.qualId, that.qualId)
+                        && scan(tree.directives, that.directives);
+    }
+
+    @Override
+    public void visitNewArray(JCNewArray tree) {
+        JCNewArray that = (JCNewArray) parameter;
+        result =
+                scan(tree.elemtype, that.elemtype)
+                        && scan(tree.dims, that.dims)
+                        && scan(tree.annotations, that.annotations)
+                        && scanDimAnnotations(tree.dimAnnotations, that.dimAnnotations)
+                        && scan(tree.elems, that.elems);
+    }
+
+    @Override
+    public void visitNewClass(JCNewClass tree) {
+        JCNewClass that = (JCNewClass) parameter;
+        result =
+                scan(tree.encl, that.encl)
+                        && scan(tree.typeargs, that.typeargs)
+                        && scan(tree.clazz, that.clazz)
+                        && scan(tree.args, that.args)
+                        && scan(tree.def, that.def)
+                        && tree.constructor == that.constructor;
+    }
+
+    @Override
+    public void visitOpens(JCOpens tree) {
+        JCOpens that = (JCOpens) parameter;
+        result = scan(tree.qualid, that.qualid) && scan(tree.moduleNames, that.moduleNames);
+    }
+
+    @Override
+    public void visitPackageDef(JCPackageDecl tree) {
+        JCPackageDecl that = (JCPackageDecl) parameter;
+        result =
+                scan(tree.annotations, that.annotations)
+                        && scan(tree.pid, that.pid)
+                        && tree.packge == that.packge;
+    }
+
+    @Override
+    public void visitProvides(JCProvides tree) {
+        JCProvides that = (JCProvides) parameter;
+        result = scan(tree.serviceName, that.serviceName) && scan(tree.implNames, that.implNames);
+    }
+
+    @Override
+    public void visitReference(JCMemberReference tree) {
+        JCMemberReference that = (JCMemberReference) parameter;
+        result =
+                tree.mode == that.mode
+                        && tree.kind == that.kind
+                        && tree.name == that.name
+                        && scan(tree.expr, that.expr)
+                        && scan(tree.typeargs, that.typeargs);
+    }
+
+    @Override
+    public void visitRequires(JCRequires tree) {
+        JCRequires that = (JCRequires) parameter;
+        result =
+                tree.isTransitive == that.isTransitive
+                        && tree.isStaticPhase == that.isStaticPhase
+                        && scan(tree.moduleName, that.moduleName);
+    }
+
+    @Override
+    public void visitReturn(JCReturn tree) {
+        JCReturn that = (JCReturn) parameter;
+        result = scan(tree.expr, that.expr);
+    }
+
+    @Override
+    public void visitSwitch(JCSwitch tree) {
+        JCSwitch that = (JCSwitch) parameter;
+        result = scan(tree.selector, that.selector) && scan(tree.cases, that.cases);
+    }
+
+    @Override
+    public void visitSynchronized(JCSynchronized tree) {
+        JCSynchronized that = (JCSynchronized) parameter;
+        result = scan(tree.lock, that.lock) && scan(tree.body, that.body);
+    }
+
+    @Override
+    public void visitThrow(JCThrow tree) {
+        JCThrow that = (JCThrow) parameter;
+        result = scan(tree.expr, that.expr);
+    }
+
+    @Override
+    public void visitTopLevel(JCCompilationUnit tree) {
+        JCCompilationUnit that = (JCCompilationUnit) parameter;
+        result =
+                scan(tree.defs, that.defs)
+                        && tree.modle == that.modle
+                        && tree.packge == that.packge;
+    }
+
+    @Override
+    public void visitTry(JCTry tree) {
+        JCTry that = (JCTry) parameter;
+        result =
+                scan(tree.body, that.body)
+                        && scan(tree.catchers, that.catchers)
+                        && scan(tree.finalizer, that.finalizer)
+                        && scan(tree.resources, that.resources);
+    }
+
+    @Override
+    public void visitTypeApply(JCTypeApply tree) {
+        JCTypeApply that = (JCTypeApply) parameter;
+        result = scan(tree.clazz, that.clazz) && scan(tree.arguments, that.arguments);
+    }
+
+    @Override
+    public void visitTypeArray(JCArrayTypeTree tree) {
+        JCArrayTypeTree that = (JCArrayTypeTree) parameter;
+        result = scan(tree.elemtype, that.elemtype);
+    }
+
+    @Override
+    public void visitTypeBoundKind(TypeBoundKind tree) {
+        TypeBoundKind that = (TypeBoundKind) parameter;
+        result = tree.kind == that.kind;
+    }
+
+    @Override
+    public void visitTypeCast(JCTypeCast tree) {
+        JCTypeCast that = (JCTypeCast) parameter;
+        result = scan(tree.clazz, that.clazz) && scan(tree.expr, that.expr);
+    }
+
+    @Override
+    public void visitTypeIdent(JCPrimitiveTypeTree tree) {
+        JCPrimitiveTypeTree that = (JCPrimitiveTypeTree) parameter;
+        result = tree.typetag == that.typetag;
+    }
+
+    @Override
+    public void visitTypeIntersection(JCTypeIntersection tree) {
+        JCTypeIntersection that = (JCTypeIntersection) parameter;
+        result = scan(tree.bounds, that.bounds);
+    }
+
+    @Override
+    public void visitTypeParameter(JCTypeParameter tree) {
+        JCTypeParameter that = (JCTypeParameter) parameter;
+        result =
+                tree.name == that.name
+                        && scan(tree.bounds, that.bounds)
+                        && scan(tree.annotations, that.annotations);
+    }
+
+    @Override
+    public void visitTypeTest(JCInstanceOf tree) {
+        JCInstanceOf that = (JCInstanceOf) parameter;
+        result = scan(tree.expr, that.expr) && scan(tree.clazz, that.clazz);
+    }
+
+    @Override
+    public void visitTypeUnion(JCTypeUnion tree) {
+        JCTypeUnion that = (JCTypeUnion) parameter;
+        result = scan(tree.alternatives, that.alternatives);
+    }
+
+    @Override
+    public void visitUnary(JCUnary tree) {
+        JCUnary that = (JCUnary) parameter;
+        result = scan(tree.arg, that.arg) && tree.operator == that.operator;
+    }
+
+    @Override
+    public void visitUses(JCUses tree) {
+        JCUses that = (JCUses) parameter;
+        result = scan(tree.qualid, that.qualid);
+    }
+
+    @Override
+    public void visitVarDef(JCVariableDecl tree) {
+        JCVariableDecl that = (JCVariableDecl) parameter;
+        result =
+                scan(tree.mods, that.mods)
+                        && tree.name == that.name
+                        && scan(tree.nameexpr, that.nameexpr)
+                        && scan(tree.vartype, that.vartype)
+                        && scan(tree.init, that.init);
+    }
+
+    @Override
+    public void visitWhileLoop(JCWhileLoop tree) {
+        JCWhileLoop that = (JCWhileLoop) parameter;
+        result = scan(tree.cond, that.cond) && scan(tree.body, that.body);
+    }
+
+    @Override
+    public void visitWildcard(JCWildcard tree) {
+        JCWildcard that = (JCWildcard) parameter;
+        result = scan(tree.kind, that.kind) && scan(tree.inner, that.inner);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TreeHasher.java	Tue Mar 27 13:48:16 2018 -0400
@@ -0,0 +1,102 @@
+/*
+ * Copyright (c) 2018, Google LLC. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.tools.javac.comp;
+
+import com.sun.tools.javac.code.Symbol;
+import com.sun.tools.javac.tree.JCTree;
+import com.sun.tools.javac.tree.JCTree.JCFieldAccess;
+import com.sun.tools.javac.tree.JCTree.JCIdent;
+import com.sun.tools.javac.tree.JCTree.JCLiteral;
+import com.sun.tools.javac.tree.TreeInfo;
+import com.sun.tools.javac.tree.TreeScanner;
+import java.util.Objects;
+import java.util.function.Function;
+
+/** A tree visitor that computes a hash code. */
+public class TreeHasher extends TreeScanner {
+
+    private final Function<Symbol, Integer> symbolHasher;
+    private int result = 17;
+
+    public TreeHasher(Function<Symbol, Integer> symbolHasher) {
+        this.symbolHasher = Objects.requireNonNull(symbolHasher);
+    }
+
+    public static int hash(JCTree tree, Function<Symbol, Integer> symbolHasher) {
+        if (tree == null) {
+            return 0;
+        }
+        TreeHasher hasher = new TreeHasher(symbolHasher);
+        tree.accept(hasher);
+        return hasher.result;
+    }
+
+    private void hash(Object object) {
+        result = 31 * result + Objects.hashCode(object);
+    }
+
+    @Override
+    public void scan(JCTree tree) {
+        if (tree == null) {
+            return;
+        }
+        tree = TreeInfo.skipParens(tree);
+        if (tree.type != null) {
+            Object value = tree.type.constValue();
+            if (value != null) {
+                hash(value);
+                return;
+            }
+        }
+        hash(tree.getTag());
+        tree.accept(this);
+    }
+
+    @Override
+    public void visitLiteral(JCLiteral tree) {
+        hash(tree.value);
+        super.visitLiteral(tree);
+    }
+
+    @Override
+    public void visitIdent(JCIdent tree) {
+        Symbol sym = tree.sym;
+        if (sym != null) {
+            Integer hash = symbolHasher.apply(sym);
+            if (hash != null) {
+                hash(hash);
+                return;
+            }
+        }
+        hash(sym);
+    }
+
+    @Override
+    public void visitSelect(JCFieldAccess tree) {
+        hash(tree.sym);
+        super.visitSelect(tree);
+    }
+}
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/compiler.properties	Mon Mar 26 21:30:33 2018 -0700
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/compiler.properties	Tue Mar 27 13:48:16 2018 -0400
@@ -2828,6 +2828,15 @@
     target-type: {2}
 
 ########################################
+# Diagnostics for lambda deduplication
+# used by LambdaToMethod (debug only)
+########################################
+
+# 0: symbol
+compiler.note.verbose.l2m.deduplicate=\
+    deduplicating lambda implementation method {0}
+
+########################################
 # Diagnostics for where clause implementation
 # used by the RichDiagnosticFormatter.
 ########################################
--- a/test/langtools/tools/javac/annotations/typeAnnotations/classfile/InstanceInitializer.java	Mon Mar 26 21:30:33 2018 -0700
+++ b/test/langtools/tools/javac/annotations/typeAnnotations/classfile/InstanceInitializer.java	Tue Mar 27 13:48:16 2018 -0400
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -28,9 +28,11 @@
 
 /*
  * @test
- * @bug 8136419
+ * @bug 8136419 8200301
  * @summary test that type annotations on entities in initializers are emitted to classfile
  * @modules jdk.jdeps/com.sun.tools.classfile
+ * @compile -XDdeduplicateLambdas=false InstanceInitializer.java
+ * @run main InstanceInitializer
  */
 
 public class InstanceInitializer extends ClassfileTestHelper {
--- a/test/langtools/tools/javac/annotations/typeAnnotations/classfile/StaticInitializer.java	Mon Mar 26 21:30:33 2018 -0700
+++ b/test/langtools/tools/javac/annotations/typeAnnotations/classfile/StaticInitializer.java	Tue Mar 27 13:48:16 2018 -0400
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -28,9 +28,11 @@
 
 /*
  * @test
- * @bug 8136419
+ * @bug 8136419 8200301
  * @summary test that type annotations on entities in static initializers are emitted to classfile
  * @modules jdk.jdeps/com.sun.tools.classfile
+ * @compile -XDdeduplicateLambdas=false StaticInitializer.java
+ * @run main StaticInitializer
  */
 
 public class StaticInitializer extends ClassfileTestHelper {
--- a/test/langtools/tools/javac/classfiles/attributes/Synthetic/BridgeMethodsForLambdaTest.java	Mon Mar 26 21:30:33 2018 -0700
+++ b/test/langtools/tools/javac/classfiles/attributes/Synthetic/BridgeMethodsForLambdaTest.java	Tue Mar 27 13:48:16 2018 -0400
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug 8044537
+ * @bug 8044537 8200301
  * @summary Checking ACC_SYNTHETIC flag is generated for bridge method
  *          generated for lambda expressions and method references.
  * @modules jdk.compiler/com.sun.tools.javac.api
@@ -31,7 +31,8 @@
  *          jdk.jdeps/com.sun.tools.classfile
  * @library /tools/lib /tools/javac/lib ../lib
  * @build toolbox.ToolBox InMemoryFileManager TestResult TestBase
- * @build BridgeMethodsForLambdaTest SyntheticTestDriver ExpectedClass ExpectedClasses
+ * @build SyntheticTestDriver ExpectedClass ExpectedClasses
+ * @compile -XDdeduplicateLambdas=false BridgeMethodsForLambdaTest.java
  * @run main SyntheticTestDriver BridgeMethodsForLambdaTest 1
  */
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/langtools/tools/javac/diags/examples/LambdaDeduplicate.java	Tue Mar 27 13:48:16 2018 -0400
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2018, Google LLC. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+
+// key: compiler.note.verbose.l2m.deduplicate
+// options: --debug:dumpLambdaToMethodDeduplication
+
+import java.util.function.Function;
+
+public class LambdaDeduplicate {
+  Function<Integer, Integer> f1 = x -> x;
+  Function<Integer, Integer> f2 = x -> x;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/langtools/tools/javac/lambda/deduplication/Deduplication.java	Tue Mar 27 13:48:16 2018 -0400
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) 2018, Google LLC. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.tools.javac.comp;
+
+import java.util.function.BiFunction;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.function.Supplier;
+
+public class Deduplication {
+    void group(Object... xs) {}
+
+    void test() {
+        group((Function<String, Integer>) x -> x.hashCode());
+        group((Function<Object, Integer>) x -> x.hashCode());
+
+        {
+            int x = 1;
+            group((Supplier<Integer>) () -> x + 1);
+        }
+        {
+            int x = 1;
+            group((Supplier<Integer>) () -> x + 1);
+        }
+        group(
+                (BiFunction<Integer, Integer, ?>) (x, y) -> x + ((y)),
+                (BiFunction<Integer, Integer, ?>) (x, y) -> x + (y),
+                (BiFunction<Integer, Integer, ?>) (x, y) -> x + y,
+                (BiFunction<Integer, Integer, ?>) (x, y) -> (x) + ((y)),
+                (BiFunction<Integer, Integer, ?>) (x, y) -> (x) + (y),
+                (BiFunction<Integer, Integer, ?>) (x, y) -> (x) + y,
+                (BiFunction<Integer, Integer, ?>) (x, y) -> ((x)) + ((y)),
+                (BiFunction<Integer, Integer, ?>) (x, y) -> ((x)) + (y),
+                (BiFunction<Integer, Integer, ?>) (x, y) -> ((x)) + y);
+
+        group(
+                (Function<Integer, Integer>) x -> x + (1 + 2 + 3),
+                (Function<Integer, Integer>) x -> x + 6);
+
+        group((Function<Integer, Integer>) x -> x + 1, (Function<Integer, Integer>) y -> y + 1);
+
+        group((Consumer<Integer>) x -> this.f(), (Consumer<Integer>) x -> this.f());
+
+        group((Consumer<Integer>) y -> this.g());
+
+        group((Consumer<Integer>) x -> f(), (Consumer<Integer>) x -> f());
+
+        group((Consumer<Integer>) y -> g());
+
+        group((Function<Integer, Integer>) x -> this.i, (Function<Integer, Integer>) x -> this.i);
+
+        group((Function<Integer, Integer>) y -> this.j);
+
+        group((Function<Integer, Integer>) x -> i, (Function<Integer, Integer>) x -> i);
+
+        group((Function<Integer, Integer>) y -> j);
+
+        group(
+                (Function<Integer, Integer>) y -> {
+                        while (true) {
+                              break;
+                        }
+                        return 42;
+                },
+                (Function<Integer, Integer>) y -> {
+                        while (true) {
+                              break;
+                        }
+                        return 42;
+                });
+
+        class Local {
+            int i;
+
+            void f() {}
+
+            {
+                group((Function<Integer, Integer>) x -> this.i);
+                group((Consumer<Integer>) x -> this.f());
+                group((Function<Integer, Integer>) x -> Deduplication.this.i);
+                group((Consumer<Integer>) x -> Deduplication.this.f());
+            }
+        }
+    }
+
+    void f() {}
+
+    void g() {}
+
+    int i;
+    int j;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/langtools/tools/javac/lambda/deduplication/DeduplicationTest.java	Tue Mar 27 13:48:16 2018 -0400
@@ -0,0 +1,357 @@
+/*
+ * Copyright (c) 2018, Google LLC. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * @test 8200301
+ * @summary deduplicate lambda methods with the same body, target type, and captured state
+ * @modules jdk.jdeps/com.sun.tools.classfile jdk.compiler/com.sun.tools.javac.api
+ *     jdk.compiler/com.sun.tools.javac.code jdk.compiler/com.sun.tools.javac.comp
+ *     jdk.compiler/com.sun.tools.javac.file jdk.compiler/com.sun.tools.javac.main
+ *     jdk.compiler/com.sun.tools.javac.tree jdk.compiler/com.sun.tools.javac.util
+ * @run main DeduplicationTest
+ */
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static java.util.stream.Collectors.joining;
+import static java.util.stream.Collectors.toMap;
+import static java.util.stream.Collectors.toSet;
+
+import com.sun.source.util.JavacTask;
+import com.sun.source.util.TaskEvent;
+import com.sun.source.util.TaskEvent.Kind;
+import com.sun.source.util.TaskListener;
+import com.sun.tools.classfile.Attribute;
+import com.sun.tools.classfile.BootstrapMethods_attribute;
+import com.sun.tools.classfile.BootstrapMethods_attribute.BootstrapMethodSpecifier;
+import com.sun.tools.classfile.ClassFile;
+import com.sun.tools.classfile.ConstantPool.CONSTANT_MethodHandle_info;
+import com.sun.tools.javac.api.ClientCodeWrapper.Trusted;
+import com.sun.tools.javac.api.JavacTool;
+import com.sun.tools.javac.code.Symbol;
+import com.sun.tools.javac.code.Symbol.MethodSymbol;
+import com.sun.tools.javac.comp.TreeDiffer;
+import com.sun.tools.javac.comp.TreeHasher;
+import com.sun.tools.javac.file.JavacFileManager;
+import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
+import com.sun.tools.javac.tree.JCTree.JCExpression;
+import com.sun.tools.javac.tree.JCTree.JCIdent;
+import com.sun.tools.javac.tree.JCTree.JCLambda;
+import com.sun.tools.javac.tree.JCTree.JCMethodInvocation;
+import com.sun.tools.javac.tree.JCTree.JCTypeCast;
+import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
+import com.sun.tools.javac.tree.JCTree.Tag;
+import com.sun.tools.javac.tree.TreeScanner;
+import com.sun.tools.javac.util.Context;
+import com.sun.tools.javac.util.JCDiagnostic;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.function.BiFunction;
+import javax.tools.Diagnostic;
+import javax.tools.DiagnosticListener;
+import javax.tools.JavaFileObject;
+
+public class DeduplicationTest {
+
+    public static void main(String[] args) throws Exception {
+        JavacFileManager fileManager = new JavacFileManager(new Context(), false, UTF_8);
+        JavacTool javacTool = JavacTool.create();
+        Listener diagnosticListener = new Listener();
+        Path testSrc = Paths.get(System.getProperty("test.src"));
+        Path file = testSrc.resolve("Deduplication.java");
+        JavacTask task =
+                javacTool.getTask(
+                        null,
+                        null,
+                        diagnosticListener,
+                        Arrays.asList(
+                                "-d",
+                                ".",
+                                "-XDdebug.dumpLambdaToMethodDeduplication",
+                                "-XDdebug.dumpLambdaToMethodStats"),
+                        null,
+                        fileManager.getJavaFileObjects(file));
+        Map<JCLambda, JCLambda> dedupedLambdas = new LinkedHashMap<>();
+        task.addTaskListener(new TreeDiffHashTaskListener(dedupedLambdas));
+        Iterable<? extends JavaFileObject> generated = task.generate();
+        if (!diagnosticListener.unexpected.isEmpty()) {
+            throw new AssertionError(
+                    diagnosticListener
+                            .unexpected
+                            .stream()
+                            .map(
+                                    d ->
+                                            String.format(
+                                                    "%s: %s",
+                                                    d.getCode(), d.getMessage(Locale.getDefault())))
+                            .collect(joining(", ", "unexpected diagnostics: ", "")));
+        }
+
+        // Assert that each group of lambdas was deduplicated.
+        Map<JCLambda, JCLambda> actual = diagnosticListener.deduplicationTargets();
+        dedupedLambdas.forEach(
+                (k, v) -> {
+                    if (!actual.containsKey(k)) {
+                        throw new AssertionError("expected " + k + " to be deduplicated");
+                    }
+                    if (!v.equals(actual.get(k))) {
+                        throw new AssertionError(
+                                String.format(
+                                        "expected %s to be deduplicated to:\n  %s\nwas:  %s",
+                                        k, v, actual.get(v)));
+                    }
+                });
+
+        // Assert that the output contains only the canonical lambdas, and not the deduplicated
+        // lambdas.
+        Set<String> bootstrapMethodNames = new TreeSet<>();
+        for (JavaFileObject output : generated) {
+            ClassFile cf = ClassFile.read(output.openInputStream());
+            BootstrapMethods_attribute bsm =
+                    (BootstrapMethods_attribute) cf.getAttribute(Attribute.BootstrapMethods);
+            for (BootstrapMethodSpecifier b : bsm.bootstrap_method_specifiers) {
+                bootstrapMethodNames.add(
+                        ((CONSTANT_MethodHandle_info)
+                                        cf.constant_pool.get(b.bootstrap_arguments[1]))
+                                .getCPRefInfo()
+                                .getNameAndTypeInfo()
+                                .getName());
+            }
+        }
+        Set<String> deduplicatedNames =
+                diagnosticListener
+                        .expectedLambdaMethods()
+                        .stream()
+                        .map(s -> s.getSimpleName().toString())
+                        .sorted()
+                        .collect(toSet());
+        if (!deduplicatedNames.equals(bootstrapMethodNames)) {
+            throw new AssertionError(
+                    String.format(
+                            "expected deduplicated methods: %s, but saw: %s",
+                            deduplicatedNames, bootstrapMethodNames));
+        }
+    }
+
+    /**
+     * Returns a symbol comparator that treats symbols that correspond to the same parameter of each
+     * of the given lambdas as equal.
+     */
+    private static BiFunction<Symbol, Symbol, Boolean> paramsEqual(JCLambda lhs, JCLambda rhs) {
+        return (x, y) -> {
+            Integer idx = paramIndex(lhs, x);
+            if (idx != null && idx != -1) {
+                if (Objects.equals(idx, paramIndex(rhs, y))) {
+                    return true;
+                }
+            }
+            return null;
+        };
+    }
+
+    /**
+     * Returns the index of the given symbol as a parameter of the given lambda, or else {@code -1}
+     * if is not a parameter.
+     */
+    private static Integer paramIndex(JCLambda lambda, Symbol sym) {
+        if (sym != null) {
+            int idx = 0;
+            for (JCVariableDecl param : lambda.params) {
+                if (sym == param.sym) {
+                    return idx;
+                }
+            }
+        }
+        return null;
+    }
+
+    /** A diagnostic listener that records debug messages related to lambda desugaring. */
+    @Trusted
+    static class Listener implements DiagnosticListener<JavaFileObject> {
+
+        /** A map from method symbols to lambda trees for desugared lambdas. */
+        final Map<MethodSymbol, JCLambda> lambdaMethodSymbolsToTrees = new LinkedHashMap<>();
+
+        /**
+         * A map from lambda trees that were deduplicated to the method symbol of the canonical
+         * lambda implementation method they were deduplicated to.
+         */
+        final Map<JCLambda, MethodSymbol> deduped = new LinkedHashMap<>();
+
+        final List<Diagnostic<? extends JavaFileObject>> unexpected = new ArrayList<>();
+
+        @Override
+        public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
+            JCDiagnostic d = (JCDiagnostic) diagnostic;
+            switch (d.getCode()) {
+                case "compiler.note.lambda.stat":
+                    lambdaMethodSymbolsToTrees.put(
+                            (MethodSymbol) d.getArgs()[1],
+                            (JCLambda) d.getDiagnosticPosition().getTree());
+                    break;
+                case "compiler.note.verbose.l2m.deduplicate":
+                    deduped.put(
+                            (JCLambda) d.getDiagnosticPosition().getTree(),
+                            (MethodSymbol) d.getArgs()[0]);
+                    break;
+                default:
+                    unexpected.add(diagnostic);
+            }
+        }
+
+        /** Returns expected lambda implementation method symbols. */
+        Set<MethodSymbol> expectedLambdaMethods() {
+            return lambdaMethodSymbolsToTrees
+                    .entrySet()
+                    .stream()
+                    .filter(e -> !deduped.containsKey(e.getValue()))
+                    .map(Map.Entry::getKey)
+                    .collect(toSet());
+        }
+
+        /**
+         * Returns a mapping from deduplicated lambda trees to the tree of the canonical lambda they
+         * were deduplicated to.
+         */
+        Map<JCLambda, JCLambda> deduplicationTargets() {
+            return deduped.entrySet()
+                    .stream()
+                    .collect(
+                            toMap(
+                                    Map.Entry::getKey,
+                                    e -> lambdaMethodSymbolsToTrees.get(e.getValue()),
+                                    (a, b) -> {
+                                        throw new AssertionError();
+                                    },
+                                    LinkedHashMap::new));
+        }
+    }
+
+    /**
+     * A task listener that tests {@link TreeDiffer} and {@link TreeHasher} on all lambda trees in a
+     * compilation, post-analysis.
+     */
+    private static class TreeDiffHashTaskListener implements TaskListener {
+
+        /**
+         * A map from deduplicated lambdas to the canonical lambda they are expected to be
+         * deduplicated to.
+         */
+        private final Map<JCLambda, JCLambda> dedupedLambdas;
+
+        public TreeDiffHashTaskListener(Map<JCLambda, JCLambda> dedupedLambdas) {
+            this.dedupedLambdas = dedupedLambdas;
+        }
+
+        @Override
+        public void finished(TaskEvent e) {
+            if (e.getKind() != Kind.ANALYZE) {
+                return;
+            }
+            // Scan the compilation for calls to a varargs method named 'group', whose arguments
+            // are a group of lambdas that are equivalent to each other, but distinct from all
+            // lambdas in the compilation unit outside of that group.
+            List<List<JCLambda>> lambdaGroups = new ArrayList<>();
+            new TreeScanner() {
+                @Override
+                public void visitApply(JCMethodInvocation tree) {
+                    if (tree.getMethodSelect().getTag() == Tag.IDENT
+                            && ((JCIdent) tree.getMethodSelect())
+                                    .getName()
+                                    .contentEquals("group")) {
+                        List<JCLambda> xs = new ArrayList<>();
+                        for (JCExpression arg : tree.getArguments()) {
+                            if (arg instanceof JCTypeCast) {
+                                arg = ((JCTypeCast) arg).getExpression();
+                            }
+                            xs.add((JCLambda) arg);
+                        }
+                        lambdaGroups.add(xs);
+                    }
+                    super.visitApply(tree);
+                }
+            }.scan((JCCompilationUnit) e.getCompilationUnit());
+            for (int i = 0; i < lambdaGroups.size(); i++) {
+                List<JCLambda> curr = lambdaGroups.get(i);
+                JCLambda first = null;
+                // Assert that all pairwise combinations of lambdas in the group are equal, and
+                // hash to the same value.
+                for (JCLambda lhs : curr) {
+                    if (first == null) {
+                        first = lhs;
+                    } else {
+                        dedupedLambdas.put(lhs, first);
+                    }
+                    for (JCLambda rhs : curr) {
+                        if (!new TreeDiffer(paramsEqual(lhs, rhs)).scan(lhs.body, rhs.body)) {
+                            throw new AssertionError(
+                                    String.format(
+                                            "expected lambdas to be equal\n%s\n%s", lhs, rhs));
+                        }
+                        if (TreeHasher.hash(lhs, sym -> paramIndex(lhs, sym))
+                                != TreeHasher.hash(rhs, sym -> paramIndex(rhs, sym))) {
+                            throw new AssertionError(
+                                    String.format(
+                                            "expected lambdas to hash to the same value\n%s\n%s",
+                                            lhs, rhs));
+                        }
+                    }
+                }
+                // Assert that no lambdas in a group are equal to any lambdas outside that group,
+                // or hash to the same value as lambda outside the group.
+                // (Note that the hash collisions won't result in correctness problems but could
+                // regress performs, and do not currently occurr for any of the test inputs.)
+                for (int j = 0; j < lambdaGroups.size(); j++) {
+                    if (i == j) {
+                        continue;
+                    }
+                    for (JCLambda lhs : curr) {
+                        for (JCLambda rhs : lambdaGroups.get(j)) {
+                            if (new TreeDiffer(paramsEqual(lhs, rhs)).scan(lhs.body, rhs.body)) {
+                                throw new AssertionError(
+                                        String.format(
+                                                "expected lambdas to not be equal\n%s\n%s",
+                                                lhs, rhs));
+                            }
+                            if (TreeHasher.hash(lhs, sym -> paramIndex(lhs, sym))
+                                    == TreeHasher.hash(rhs, sym -> paramIndex(rhs, sym))) {
+                                throw new AssertionError(
+                                        String.format(
+                                                "expected lambdas to hash to different values\n%s\n%s",
+                                                lhs, rhs));
+                            }
+                        }
+                    }
+                }
+            }
+            lambdaGroups.clear();
+        }
+    }
+}