changeset 50963:dd9ec7e7e35a

Merge
author prr
date Thu, 31 May 2018 13:04:30 -0700
parents 1ba28f0dbc33 d0d933d61610
children 8fbbd19bf3a1
files make/BuildNashorn.gmk make/UnpackSecurity.gmk src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.debug/src/org/graalvm/compiler/debug/DebugValueMap.java src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.hotspot.test/src/org/graalvm/compiler/hotspot/test/aaa src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements.verifier/src/META-INF/services/javax.annotation.processing.Processor src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements.verifier/src/org/graalvm/compiler/replacements/verifier/APHotSpotSignature.java src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements.verifier/src/org/graalvm/compiler/replacements/verifier/AbstractVerifier.java src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements.verifier/src/org/graalvm/compiler/replacements/verifier/ClassSubstitutionVerifier.java src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements.verifier/src/org/graalvm/compiler/replacements/verifier/FoldVerifier.java src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements.verifier/src/org/graalvm/compiler/replacements/verifier/GeneratedFoldPlugin.java src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements.verifier/src/org/graalvm/compiler/replacements/verifier/GeneratedNodeIntrinsicPlugin.java src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements.verifier/src/org/graalvm/compiler/replacements/verifier/GeneratedPlugin.java src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements.verifier/src/org/graalvm/compiler/replacements/verifier/InjectedDependencies.java src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements.verifier/src/org/graalvm/compiler/replacements/verifier/MethodSubstitutionVerifier.java src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements.verifier/src/org/graalvm/compiler/replacements/verifier/NodeIntrinsicVerifier.java src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements.verifier/src/org/graalvm/compiler/replacements/verifier/PluginGenerator.java src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements.verifier/src/org/graalvm/compiler/replacements/verifier/VerifierAnnotationProcessor.java src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements/src/org/graalvm/compiler/replacements/classfile/D
diffstat 806 files changed, 82165 insertions(+), 5987 deletions(-) [+]
line wrap: on
line diff
--- a/.hgtags	Thu May 31 09:52:32 2018 -0700
+++ b/.hgtags	Thu May 31 13:04:30 2018 -0700
@@ -487,3 +487,4 @@
 758deedaae8406ae60147486107a54e9864aa7b0 jdk-11+13
 3595bd343b65f8c37818ebe6a4c343ddeb1a5f88 jdk-11+14
 a11c1cb542bbd1671d25b85efe7d09b983c48525 jdk-11+15
+02934b0d661b82b7fe1052a04998d2091352e08d jdk-11+16
--- a/make/BuildNashorn.gmk	Thu May 31 09:52:32 2018 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,115 +0,0 @@
-#
-# Copyright (c) 2010, 2017, 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
-# 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.
-#
-
-# This must be the first rule
-default: all
-
-include $(SPEC)
-include MakeBase.gmk
-include JarArchive.gmk
-include JavaCompilation.gmk
-include SetupJavaCompilers.gmk
-include TextFileProcessing.gmk
-include Modules.gmk
-
-JDK_CLASSES := $(call PathList, $(strip $(addprefix $(JDK_OUTPUTDIR)/modules/, \
-      java.base java.logging java.scripting jdk.dynalink)))
-
-# Need to use source and target 8 for nasgen to work.
-$(eval $(call SetupJavaCompiler, GENERATE_NEWBYTECODE_DEBUG, \
-    JVM := $(JAVA_JAVAC), \
-    JAVAC := $(NEW_JAVAC), \
-    FLAGS := -g -source 10 -target 10 --upgrade-module-path "$(JDK_OUTPUTDIR)/modules/" \
-         --system none --module-source-path $(call GetModuleSrcPath), \
-    SERVER_DIR := $(SJAVAC_SERVER_DIR), \
-    SERVER_JVM := $(SJAVAC_SERVER_JAVA)))
-
-# Build nashorn into intermediate directory
-# Name the compilation setup the same as the module, as is done in the global
-# CompileJavaModules.gmk, to make dependency checking with other modules work
-# seamlessly.
-$(eval $(call SetupJavaCompilation, jdk.scripting.nashorn, \
-    SETUP := GENERATE_NEWBYTECODE_DEBUG, \
-    MODULE := jdk.scripting.nashorn, \
-    SRC := $(TOPDIR)/src/jdk.scripting.nashorn/share/classes, \
-    COPY := .properties .js, \
-    BIN := $(SUPPORT_OUTPUTDIR)/special_classes, \
-    CREATE_API_DIGEST := true, \
-))
-
-# Declare dependencies between java compilations of different modules.
-# Since the other modules are declared in different invocations of this file,
-# use the macro to find the correct target file to depend on.
-# Only the javac compilation actually depends on other modules so limit
-# dependency declaration to that by using the *_COMPILE_TARGET variable.
-$(jdk.scripting.nashorn_COMPILE_TARGET): $(foreach d, $(call FindDepsForModule, jdk.scripting.nashorn), \
-    $(call SetupJavaCompilationApiTarget, $d, \
-        $(if $($d_BIN), $($d_BIN), $(JDK_OUTPUTDIR)/modules/$d)))
-
-NASGEN_SRC := $(TOPDIR)/make/nashorn/buildtools/nasgen/src
-ASM_SRC := $(TOPDIR)/src/java.base/share/classes/jdk/internal/org/objectweb/asm
-
-# Build nasgen
-$(eval $(call SetupJavaCompilation, BUILD_NASGEN, \
-    SETUP := GENERATE_OLDBYTECODE, \
-    SRC := $(NASGEN_SRC) $(ASM_SRC), \
-    BIN := $(BUILDTOOLS_OUTPUTDIR)/nasgen_classes))
-
-NASHORN_CLASSES_DIR := $(JDK_OUTPUTDIR)/modules/jdk.scripting.nashorn
-NASGEN_RUN_FILE := $(NASHORN_CLASSES_DIR)/_the.nasgen.run
-
-NASGEN_OPTIONS := \
-    -cp $(BUILDTOOLS_OUTPUTDIR)/nasgen_classes \
-    --patch-module java.base=$(BUILDTOOLS_OUTPUTDIR)/nasgen_classes \
-    --add-exports java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED \
-    --add-exports java.base/jdk.internal.org.objectweb.asm.util=ALL-UNNAMED \
-    #
-
-# Copy classes to final classes dir and run nasgen to modify classes in jdk.nashorn.internal.objects package
-$(NASGEN_RUN_FILE): $(BUILD_NASGEN) $(jdk.scripting.nashorn)
-	$(ECHO) Running nasgen
-	$(MKDIR) -p $(@D)
-	$(RM) -rf $(@D)/jdk $(@D)/netscape
-	$(CP) -R -p $(SUPPORT_OUTPUTDIR)/special_classes/jdk.scripting.nashorn/* $(@D)/
-	$(JAVA_SMALL) $(NASGEN_OPTIONS) \
-	    jdk.nashorn.internal.tools.nasgen.Main $(@D) jdk.nashorn.internal.objects $(@D)
-	$(TOUCH) $@
-
-# Version file needs to be processed with version numbers
-$(eval $(call SetupTextFileProcessing, BUILD_VERSION_FILE, \
-  SOURCE_FILES := $(TOPDIR)/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/resources/version.properties.template, \
-  OUTPUT_FILE := $(JDK_OUTPUTDIR)/modules/jdk.scripting.nashorn/jdk/nashorn/internal/runtime/resources/version.properties, \
-  REPLACEMENTS := \
-      @@VERSION_STRING@@ => $(VERSION_STRING) ; \
-      @@VERSION_SHORT@@ => $(VERSION_SHORT) , \
-))
-
-# Version processing needs to happen after nasgen run since nasgen run deletes it
-$(BUILD_VERSION_FILE): $(NASGEN_RUN_FILE)
-
-compile: $(NASGEN_RUN_FILE) $(BUILD_VERSION_FILE)
-all: compile
-
-.PHONY: compile all
--- a/make/CompileJavaModules.gmk	Thu May 31 09:52:32 2018 -0700
+++ b/make/CompileJavaModules.gmk	Thu May 31 13:04:30 2018 -0700
@@ -341,6 +341,10 @@
 
 ################################################################################
 
+jdk.scripting.nashorn_COPY := .properties .js
+
+################################################################################
+
 jdk.scripting.nashorn.shell_COPY += .js .properties
 
 ################################################################################
@@ -440,11 +444,13 @@
 
 jdk.internal.vm.compiler_EXCLUDES += \
     jdk.internal.vm.compiler.collections.test \
+    org.graalvm.compiler.processor \
     org.graalvm.compiler.core.match.processor \
     org.graalvm.compiler.nodeinfo.processor \
     org.graalvm.compiler.options.processor \
     org.graalvm.compiler.serviceprovider.processor \
-    org.graalvm.compiler.replacements.verifier \
+    org.graalvm.compiler.replacements.processor \
+    org.graalvm.compiler.replacements.jdk9.test \
     org.graalvm.compiler.api.directives.test \
     org.graalvm.compiler.api.test \
     org.graalvm.compiler.asm.aarch64.test \
@@ -642,6 +648,12 @@
 
 ################################################################################
 
+ifeq ($(MODULE), jdk.scripting.nashorn)
+  include CompileJavaModulesNashorn.gmk
+endif
+
+################################################################################
+
 $(eval $(call IncludeCustomExtension, CompileJavaModules-post.gmk))
 
 ################################################################################
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/make/CompileJavaModulesNashorn.gmk	Thu May 31 13:04:30 2018 -0700
@@ -0,0 +1,54 @@
+#
+# Copyright (c) 2010, 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
+# 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.
+#
+
+NASGEN_SRC := $(TOPDIR)/make/nashorn/buildtools/nasgen/src
+ASM_SRC := $(TOPDIR)/src/java.base/share/classes/jdk/internal/org/objectweb/asm
+
+# Build nasgen
+$(eval $(call SetupJavaCompilation, BUILD_NASGEN, \
+    SETUP := GENERATE_OLDBYTECODE, \
+    SRC := $(NASGEN_SRC) $(ASM_SRC), \
+    BIN := $(BUILDTOOLS_OUTPUTDIR)/nasgen_classes, \
+))
+
+NASHORN_CLASSES_DIR := $(JDK_OUTPUTDIR)/modules/$(MODULE)
+NASGEN_RUN_FILE := $(NASHORN_CLASSES_DIR)/_the.nasgen.run
+
+NASGEN_OPTIONS := \
+    -cp $(BUILDTOOLS_OUTPUTDIR)/nasgen_classes \
+    --patch-module java.base=$(BUILDTOOLS_OUTPUTDIR)/nasgen_classes \
+    --add-exports java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED \
+    --add-exports java.base/jdk.internal.org.objectweb.asm.util=ALL-UNNAMED \
+    #
+
+# Run nasgen to modify classes in jdk.nashorn.internal.objects package
+$(NASGEN_RUN_FILE): $(BUILD_NASGEN) $($(MODULE))
+	$(ECHO) Running nasgen
+	$(JAVA_SMALL) $(NASGEN_OPTIONS) \
+	    jdk.nashorn.internal.tools.nasgen.Main $(@D) \
+	    jdk.nashorn.internal.objects $(@D)
+	$(TOUCH) $@
+
+TARGETS += $(NASGEN_RUN_FILE)
--- a/make/CompileToolsHotspot.gmk	Thu May 31 09:52:32 2018 -0700
+++ b/make/CompileToolsHotspot.gmk	Thu May 31 13:04:30 2018 -0700
@@ -47,34 +47,8 @@
   $(eval $(call SetupJavaCompilation, BUILD_VM_COMPILER_MATCH_PROCESSOR, \
       SETUP := GENERATE_OLDBYTECODE, \
       SRC := \
-          $(SRC_DIR)/jdk.internal.vm.compiler.word/src \
-          $(SRC_DIR)/jdk.internal.vm.compiler.collections/src \
-          $(SRC_DIR)/org.graalvm.compiler.core/src \
-          $(SRC_DIR)/org.graalvm.compiler.core.common/src \
+          $(SRC_DIR)/org.graalvm.compiler.processor/src \
           $(SRC_DIR)/org.graalvm.compiler.core.match.processor/src \
-          $(SRC_DIR)/org.graalvm.compiler.api.replacements/src \
-          $(SRC_DIR)/org.graalvm.compiler.asm/src \
-          $(SRC_DIR)/org.graalvm.compiler.bytecode/src \
-          $(SRC_DIR)/org.graalvm.compiler.code/src \
-          $(SRC_DIR)/org.graalvm.compiler.debug/src \
-          $(SRC_DIR)/org.graalvm.compiler.graph/src \
-          $(SRC_DIR)/org.graalvm.compiler.lir/src \
-          $(SRC_DIR)/org.graalvm.compiler.loop/src \
-          $(SRC_DIR)/org.graalvm.compiler.loop.phases/src \
-          $(SRC_DIR)/org.graalvm.compiler.nodeinfo/src \
-          $(SRC_DIR)/org.graalvm.compiler.nodes/src \
-          $(SRC_DIR)/org.graalvm.compiler.options/src \
-          $(SRC_DIR)/org.graalvm.compiler.phases/src \
-          $(SRC_DIR)/org.graalvm.compiler.phases.common/src \
-          $(SRC_DIR)/org.graalvm.compiler.serviceprovider/src \
-          $(SRC_DIR)/org.graalvm.compiler.virtual/src \
-          $(SRC_DIR)/org.graalvm.graphio/src \
-          $(SRC_DIR)/org.graalvm.util/src \
-          $(VM_CI_SRC_DIR)/jdk.vm.ci.code/src \
-          $(VM_CI_SRC_DIR)/jdk.vm.ci.common/src \
-          $(VM_CI_SRC_DIR)/jdk.vm.ci.meta/src \
-          $(VM_CI_SRC_DIR)/jdk.vm.ci.runtime/src \
-          $(VM_CI_SRC_DIR)/jdk.vm.ci.services/src \
           , \
       EXCLUDE_FILES := $(EXCLUDE_FILES), \
       BIN := $(BUILDTOOLS_OUTPUTDIR)/jdk.vm.compiler.match.processor, \
@@ -88,7 +62,7 @@
   $(eval $(call SetupJavaCompilation, BUILD_VM_COMPILER_NODEINFO_PROCESSOR, \
       SETUP := GENERATE_OLDBYTECODE, \
       SRC := \
-          $(SRC_DIR)/org.graalvm.compiler.nodeinfo/src \
+          $(SRC_DIR)/org.graalvm.compiler.processor/src \
           $(SRC_DIR)/org.graalvm.compiler.nodeinfo.processor/src \
           , \
       BIN := $(BUILDTOOLS_OUTPUTDIR)/jdk.vm.compiler.nodeinfo.processor, \
@@ -102,10 +76,8 @@
   $(eval $(call SetupJavaCompilation, BUILD_VM_COMPILER_OPTIONS_PROCESSOR, \
       SETUP := GENERATE_OLDBYTECODE, \
       SRC := \
-          $(SRC_DIR)/jdk.internal.vm.compiler.collections/src \
-          $(SRC_DIR)/org.graalvm.compiler.options/src \
+          $(SRC_DIR)/org.graalvm.compiler.processor/src \
           $(SRC_DIR)/org.graalvm.compiler.options.processor/src \
-          $(SRC_DIR)/org.graalvm.util/src \
           , \
       BIN := $(BUILDTOOLS_OUTPUTDIR)/jdk.vm.compiler.options.processor, \
       JAR := $(BUILDTOOLS_OUTPUTDIR)/jdk.vm.compiler.options.processor.jar, \
@@ -115,44 +87,26 @@
 
   ##############################################################################
 
-  $(eval $(call SetupJavaCompilation, BUILD_VM_COMPILER_REPLACEMENTS_VERIFIER, \
+  $(eval $(call SetupJavaCompilation, BUILD_VM_COMPILER_REPLACEMENTS_PROCESSOR, \
       SETUP := GENERATE_OLDBYTECODE, \
       SRC := \
-          $(SRC_DIR)/jdk.internal.vm.compiler.word/src \
-          $(SRC_DIR)/jdk.internal.vm.compiler.collections/src \
-          $(SRC_DIR)/org.graalvm.compiler.bytecode/src \
-          $(SRC_DIR)/org.graalvm.compiler.replacements.verifier/src \
-          $(SRC_DIR)/org.graalvm.compiler.api.replacements/src \
-          $(SRC_DIR)/org.graalvm.compiler.code/src \
-          $(SRC_DIR)/org.graalvm.compiler.core.common/src \
-          $(SRC_DIR)/org.graalvm.compiler.debug/src \
-          $(SRC_DIR)/org.graalvm.compiler.graph/src \
-          $(SRC_DIR)/org.graalvm.compiler.nodeinfo/src \
-          $(SRC_DIR)/org.graalvm.compiler.options/src \
-          $(SRC_DIR)/org.graalvm.compiler.serviceprovider/src \
-          $(SRC_DIR)/org.graalvm.graphio/src \
-          $(SRC_DIR)/org.graalvm.util/src \
-          $(VM_CI_SRC_DIR)/jdk.vm.ci.code/src \
-          $(VM_CI_SRC_DIR)/jdk.vm.ci.common/src \
-          $(VM_CI_SRC_DIR)/jdk.vm.ci.meta/src \
-          $(VM_CI_SRC_DIR)/jdk.vm.ci.runtime/src \
-          $(VM_CI_SRC_DIR)/jdk.vm.ci.services/src \
+          $(SRC_DIR)/org.graalvm.compiler.processor/src \
+          $(SRC_DIR)/org.graalvm.compiler.replacements.processor/src \
           , \
       EXCLUDE_FILES := $(EXCLUDE_FILES), \
       BIN := $(BUILDTOOLS_OUTPUTDIR)/jdk.vm.compiler.replacements.verifier, \
       JAR := $(BUILDTOOLS_OUTPUTDIR)/jdk.vm.compiler.replacements.verifier.jar, \
   ))
 
-  TARGETS += $(BUILD_VM_COMPILER_REPLACEMENTS_VERIFIER)
+  TARGETS += $(BUILD_VM_COMPILER_REPLACEMENTS_PROCESSOR)
 
   ##############################################################################
 
   $(eval $(call SetupJavaCompilation, BUILD_VM_COMPILER_SERVICEPROVIDER_PROCESSOR, \
       SETUP := GENERATE_OLDBYTECODE, \
       SRC := \
-          $(SRC_DIR)/org.graalvm.compiler.serviceprovider/src \
+          $(SRC_DIR)/org.graalvm.compiler.processor/src \
           $(SRC_DIR)/org.graalvm.compiler.serviceprovider.processor/src \
-          $(VM_CI_SRC_DIR)/jdk.vm.ci.services/src \
           , \
       EXCLUDE_FILES := $(EXCLUDE_FILES), \
       BIN := $(BUILDTOOLS_OUTPUTDIR)/jdk.vm.compiler.serviceprovider.processor, \
--- a/make/Main.gmk	Thu May 31 09:52:32 2018 -0700
+++ b/make/Main.gmk	Thu May 31 13:04:30 2018 -0700
@@ -98,13 +98,10 @@
 ################################################################################
 # Special targets for certain modules
 
-unpack-sec:
-	+($(CD) $(TOPDIR)/make && $(MAKE) $(MAKE_ARGS) -f UnpackSecurity.gmk)
-
 generate-exported-symbols:
 	+($(CD) $(TOPDIR)/make && $(MAKE) $(MAKE_ARGS) -f BuildStatic.gmk)
 
-ALL_TARGETS += unpack-sec generate-exported-symbols
+ALL_TARGETS += generate-exported-symbols
 
 ################################################################################
 # Gensrc targets, generating source before java compilation can be done
@@ -189,7 +186,7 @@
 ALL_TARGETS += $(ALL_COPY_TARGETS)
 
 ################################################################################
-# Targets for compiling all java modules. Nashorn is treated separately.
+# Targets for compiling all java modules.
 JAVA_MODULES := $(ALL_MODULES)
 JAVA_TARGETS := $(addsuffix -java, $(JAVA_MODULES))
 
@@ -199,14 +196,7 @@
 	    -f CompileJavaModules.gmk MODULE=$1)
 endef
 
-$(foreach m, $(filter-out jdk.scripting.nashorn, $(JAVA_MODULES)), \
-    $(eval $(call DeclareCompileJavaRecipe,$m)))
-
-# Build nashorn. Needs to be compiled separately from the rest of the modules
-# due to nasgen.
-jdk.scripting.nashorn-java:
-	+($(CD) $(TOPDIR)/make && $(MAKE) $(MAKE_ARGS) \
-	    -f BuildNashorn.gmk compile)
+$(foreach m, $(JAVA_MODULES), $(eval $(call DeclareCompileJavaRecipe,$m)))
 
 ALL_TARGETS += $(JAVA_TARGETS)
 
@@ -700,9 +690,6 @@
   # file to be processed by the gensrc-moduleinfo target.
   jdk.internal.vm.compiler-gensrc-moduleinfo: jdk.internal.vm.compiler-gensrc-src
 
-  # Explicitly add dependencies for special targets
-  java.base-java: unpack-sec
-
   jdk.jdeps-gendata: java rmic
 
   # The ct.sym generation uses all the moduleinfos as input
--- a/make/UnpackSecurity.gmk	Thu May 31 09:52:32 2018 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,88 +0,0 @@
-#
-# Copyright (c) 2012, 2014, 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
-# 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.
-#
-
-default: all
-
-include $(SPEC)
-include MakeBase.gmk
-
-################################################################################
-# Unpack the binary distributions of the crypto classes if they exist.
-SEC_FILES_ZIP := $(TOPDIR)/make/tools/crypto/sec-bin.zip
-SEC_FILES_WIN_ZIP := $(TOPDIR)/make/tools/crypto/sec-windows-bin.zip
-JGSS_WIN32_FILES_ZIP := $(TOPDIR)/make/tools/crypto/jgss-windows-i586-bin.zip
-JGSS_WIN64_FILES_ZIP := $(TOPDIR)/make/tools/crypto/jgss-windows-x64-bin.zip
-
-define unzip-sec-file
-	$(ECHO) Unzipping $(<F)
-	$(MKDIR) -p $(@D) $(JDK_OUTPUTDIR)
-	$(RM) $@
-	($(CD) $(JDK_OUTPUTDIR) && $(UNZIP) -q -o $< > $@.tmp)
-	$(MV) $@.tmp $@
-endef
-
-define unzip-native-sec-file
-	$(ECHO) Unzipping $(<F)
-	$(MKDIR) -p $(@D)
-	$(RM) $@
-	($(CD) $(SUPPORT_OUTPUTDIR) && $(UNZIP) -q -o $< > $@.tmp)
-	$(MV) $@.tmp $@
-endef
-
-$(SUPPORT_OUTPUTDIR)/_the.sec-bin.unzipped: $(SEC_FILES_ZIP)
-	$(call unzip-sec-file)
-
-# Trying to unzip both of the sec files at the same time may cause a race
-# when creating directories common to both files.
-$(SUPPORT_OUTPUTDIR)/_the.sec-windows-bin.unzipped: $(SEC_FILES_WIN_ZIP) \
-    | $(SUPPORT_OUTPUTDIR)/_the.sec-bin.unzipped
-	$(call unzip-sec-file)
-
-$(SUPPORT_OUTPUTDIR)/_the.jgss-windows-i586-bin.unzipped: $(JGSS_WIN32_FILES_ZIP)
-	$(call unzip-native-sec-file)
-
-$(SUPPORT_OUTPUTDIR)/_the.jgss-windows-x64-bin.unzipped: $(JGSS_WIN64_FILES_ZIP)
-	$(call unzip-native-sec-file)
-
-ifneq ($(wildcard $(SEC_FILES_ZIP)), )
-  IMPORT_TARGET_FILES += $(SUPPORT_OUTPUTDIR)/_the.sec-bin.unzipped
-  ifeq ($(OPENJDK_TARGET_OS), windows)
-    IMPORT_TARGET_FILES += $(SUPPORT_OUTPUTDIR)/_the.sec-windows-bin.unzipped
-    ifeq ($(OPENJDK_TARGET_CPU), x86)
-      IMPORT_TARGET_FILES += $(SUPPORT_OUTPUTDIR)/_the.jgss-windows-i586-bin.unzipped
-    endif
-    ifeq ($(OPENJDK_TARGET_CPU), x86_64)
-      IMPORT_TARGET_FILES += $(SUPPORT_OUTPUTDIR)/_the.jgss-windows-x64-bin.unzipped
-    endif
-  endif
-endif
-
-################################################################################
-
-sec: $(IMPORT_TARGET_FILES)
-
-all: sec
-
-.PHONY: sec all
--- a/make/autoconf/build-aux/config.guess	Thu May 31 09:52:32 2018 -0700
+++ b/make/autoconf/build-aux/config.guess	Thu May 31 13:04:30 2018 -0700
@@ -86,6 +86,17 @@
   fi
 fi
 
+# Test and fix little endian MIPS.
+if [ "x$OUT" = x ]; then
+  if [ `uname -s` = Linux ]; then
+    if [ `uname -m` = mipsel ]; then
+      OUT=mipsel-unknown-linux-gnu
+    elif [ `uname -m` = mips64el ]; then
+      OUT=mips64el-unknown-linux-gnu
+    fi
+  fi
+fi
+
 # Test and fix cpu on Macosx when C preprocessor is not on the path
 echo $OUT | grep i386-apple-darwin > /dev/null 2> /dev/null
 if test $? = 0; then
--- a/make/data/tzdata/VERSION	Thu May 31 09:52:32 2018 -0700
+++ b/make/data/tzdata/VERSION	Thu May 31 13:04:30 2018 -0700
@@ -21,4 +21,4 @@
 # or visit www.oracle.com if you need additional information or have any
 # questions.
 #
-tzdata2018d
+tzdata2018e
--- a/make/data/tzdata/africa	Thu May 31 09:52:32 2018 -0700
+++ b/make/data/tzdata/africa	Thu May 31 13:04:30 2018 -0700
@@ -29,7 +29,7 @@
 # tz@iana.org for general use in the future).  For more, please see
 # the file CONTRIBUTING in the tz distribution.
 
-# From Paul Eggert (2017-02-20):
+# From Paul Eggert (2017-04-09):
 #
 # Unless otherwise specified, the source for data through 1990 is:
 # Thomas G. Shanks and Rique Pottenger, The International Atlas (6th edition),
@@ -75,7 +75,7 @@
 # cannot now come up with solid citations.
 #
 # I invented the following abbreviations; corrections are welcome!
-#	 +02	WAST	West Africa Summer Time
+#	 +02	WAST	West Africa Summer Time (no longer used)
 #	 +03	CAST	Central Africa Summer Time (no longer used)
 #	 +03	SAST	South Africa Summer Time (no longer used)
 #	 +03	EAT	East Africa Time
@@ -990,6 +990,10 @@
 # commence at OOhOO on Monday 21 March 1994 and shall end at 02h00 on
 # Sunday 4 September 1994.
 
+# From Michael Deckers (2017-04-06):
+# ... both summer and winter time are called "standard"
+# (which differs from the use in Ireland) ...
+
 # From Petronella Sibeene (2007-03-30):
 # http://allafrica.com/stories/200703300178.html
 # While the entire country changes its time, Katima Mulilo and other
@@ -1015,19 +1019,42 @@
 # the same time they would normally start DST, the first Sunday in September:
 # https://www.timeanddate.com/news/time/namibia-new-time-zone.html
 
+# From Paul Eggert (2017-04-09):
+# Before the change, summer and winter time were both standard time legally.
+# However in common parlance, winter time was considered to be DST.  See, e.g.:
+# http://www.nbc.na/news/namibias-winter-time-could-be-scrapped.2706
+# https://zone.my.na/news/times-are-changing-in-namibia
+# https://www.newera.com.na/2017/02/23/namibias-winter-time-might-be-repealed/
+# Use plain "WAT" and "CAT" for the time zone abbreviations, to be compatible
+# with Namibia's neighbors.
+
 # RULE	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
-Rule	Namibia	1994	only	-	Mar	21	0:00	0	-
-Rule	Namibia	1994	2016	-	Sep	Sun>=1	2:00	1:00	S
-Rule	Namibia	1995	2017	-	Apr	Sun>=1	2:00	0	-
+# Vanguard section, for zic and other parsers that support negative DST.
+#Rule	Namibia	1994	only	-	Mar	21	0:00	-1:00	WAT
+#Rule	Namibia	1994	2017	-	Sep	Sun>=1	2:00	0	CAT
+#Rule	Namibia	1995	2017	-	Apr	Sun>=1	2:00	-1:00	WAT
+# Rearguard section, for parsers that do not support negative DST.
+Rule	Namibia	1994	only	-	Mar	21	0:00	0	WAT
+Rule	Namibia	1994	2017	-	Sep	Sun>=1	2:00	1:00	CAT
+Rule	Namibia	1995	2017	-	Apr	Sun>=1	2:00	0	WAT
+# End of rearguard section.
+
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone	Africa/Windhoek	1:08:24 -	LMT	1892 Feb 8
 			1:30	-	+0130	1903 Mar
 			2:00	-	SAST	1942 Sep 20  2:00
 			2:00	1:00	SAST	1943 Mar 21  2:00
 			2:00	-	SAST	1990 Mar 21 # independence
+# Vanguard section, for zic and other parsers that support negative DST.
+#			2:00	Namibia	%s
+# Rearguard section, for parsers that do not support negative DST.
 			2:00	-	CAT	1994 Mar 21  0:00
-			1:00	Namibia	WA%sT	2017 Sep  3  2:00
+# From Paul Eggert (2017-04-07):
+# The official date of the 2017 rule change was 2017-10-24.  See:
+# http://www.lac.org.na/laws/annoSTAT/Namibian%20Time%20Act%209%20of%202017.pdf
+			1:00	Namibia	%s	2017 Oct 24
 			2:00	-	CAT
+# End of rearguard section.
 
 # Niger
 # See Africa/Lagos.
--- a/make/data/tzdata/asia	Thu May 31 09:52:32 2018 -0700
+++ b/make/data/tzdata/asia	Thu May 31 13:04:30 2018 -0700
@@ -2006,6 +2006,19 @@
 # There is no common English-language abbreviation for this time zone.
 # Use KST, as that's what we already use for 1954-1961 in ROK.
 
+# From Kang Seonghoon (2018-04-29):
+# North Korea will revert its time zone from UTC+8:30 (PYT; Pyongyang
+# Time) back to UTC+9 (KST; Korea Standard Time).
+#
+# From Seo Sanghyeon (2018-04-30):
+# Rodong Sinmun 2018-04-30 announced Pyongyang Time transition plan.
+# https://www.nknews.org/kcna/wp-content/uploads/sites/5/2018/04/rodong-2018-04-30.pdf
+# ... the transition date is 2018-05-05 ...  Citation should be Decree
+# No. 2232 of April 30, 2018, of the Presidium of the Supreme People's
+# Assembly, as published in Rodong Sinmun.
+# From Tim Parenti (2018-04-29):
+# It appears to be the front page story at the top in the right-most column.
+
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone	Asia/Seoul	8:27:52	-	LMT	1908 Apr  1
 			8:30	-	KST	1912 Jan  1
@@ -2017,7 +2030,8 @@
 			8:30	-	KST	1912 Jan  1
 			9:00	-	JST	1945 Aug 24
 			9:00	-	KST	2015 Aug 15 00:00
-			8:30	-	KST
+			8:30	-	KST	2018 May  5
+			9:00	-	KST
 
 ###############################################################################
 
@@ -2681,7 +2695,7 @@
 # From Sharef Mustafa (2018-03-16):
 # Palestine summer time will start on Mar 24th 2018 by advancing the
 # clock by 60 minutes as per Palestinian cabinet decision published on
-# the offical website, though the decree did not specify the exact
+# the official website, though the decree did not specify the exact
 # time of the time shift.
 # http://www.palestinecabinet.gov.ps/Website/AR/NDecrees/ViewFile.ashx?ID=e7a42ab7-ee23-435a-b9c8-a4f7e81f3817
 #
--- a/make/data/tzdata/australasia	Thu May 31 09:52:32 2018 -0700
+++ b/make/data/tzdata/australasia	Thu May 31 13:04:30 2018 -0700
@@ -1108,6 +1108,15 @@
 # (1999-09-27) writes that Giles Meteorological Station uses
 # South Australian time even though it's located in Western Australia.
 
+# From Paul Eggert (2018-04-01):
+# The Guardian Express of Perth, Australia reported today that the
+# government decided to advance the clocks permanently on January 1,
+# 2019, from UT +08 to UT +09.  The article noted that an exemption
+# would be made for people aged 61 and over, who "can apply in writing
+# to have the extra hour of sunshine removed from their area."  See:
+# Daylight saving coming to WA in 2019. Guardian Express. 2018-04-01.
+# https://www.communitynews.com.au/guardian-express/news/exclusive-daylight-savings-coming-wa-summer-2018/
+
 # Queensland
 
 # From Paul Eggert (2018-02-26):
--- a/make/data/tzdata/europe	Thu May 31 09:52:32 2018 -0700
+++ b/make/data/tzdata/europe	Thu May 31 13:04:30 2018 -0700
@@ -551,13 +551,13 @@
 # summer and negative daylight saving time in winter.  It is for when
 # negative SAVE values are used.
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
-#Rule	Eire	1971	only	-	Oct	31	 2:00u	-1:00	GMT
-#Rule	Eire	1972	1980	-	Mar	Sun>=16	 2:00u	0	IST
-#Rule	Eire	1972	1980	-	Oct	Sun>=23	 2:00u	-1:00	GMT
-#Rule	Eire	1981	max	-	Mar	lastSun	 1:00u	0	IST
-#Rule	Eire	1981	1989	-	Oct	Sun>=23	 1:00u	-1:00	GMT
-#Rule	Eire	1990	1995	-	Oct	Sun>=22	 1:00u	-1:00	GMT
-#Rule	Eire	1996	max	-	Oct	lastSun	 1:00u	-1:00	GMT
+#Rule	Eire	1971	only	-	Oct	31	 2:00u	-1:00	-
+#Rule	Eire	1972	1980	-	Mar	Sun>=16	 2:00u	0	-
+#Rule	Eire	1972	1980	-	Oct	Sun>=23	 2:00u	-1:00	-
+#Rule	Eire	1981	max	-	Mar	lastSun	 1:00u	0	-
+#Rule	Eire	1981	1989	-	Oct	Sun>=23	 1:00u	-1:00	-
+#Rule	Eire	1990	1995	-	Oct	Sun>=22	 1:00u	-1:00	-
+#Rule	Eire	1996	max	-	Oct	lastSun	 1:00u	-1:00	-
 
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone	Europe/Dublin	-0:25:00 -	LMT	1880 Aug  2
@@ -993,18 +993,30 @@
 # Please see the 'asia' file for Asia/Nicosia.
 
 # Czech Republic / Czechia
+#
+# From Paul Eggert (2018-04-15):
+# The source for Czech data is: Kdy začíná a končí letní čas. 2018-04-15.
+# https://kalendar.beda.cz/kdy-zacina-a-konci-letni-cas
+# We know of no English-language name for historical Czech winter time;
+# abbreviate it as "GMT", as it happened to be GMT.
+#
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
-Rule	Czech	1945	only	-	Apr	 8	2:00s	1:00	S
-Rule	Czech	1945	only	-	Nov	18	2:00s	0	-
+Rule	Czech	1945	only	-	Apr	Mon>=1	2:00s	1:00	S
+Rule	Czech	1945	only	-	Oct	 1	2:00s	0	-
 Rule	Czech	1946	only	-	May	 6	2:00s	1:00	S
 Rule	Czech	1946	1949	-	Oct	Sun>=1	2:00s	0	-
-Rule	Czech	1947	only	-	Apr	20	2:00s	1:00	S
-Rule	Czech	1948	only	-	Apr	18	2:00s	1:00	S
+Rule	Czech	1947	1948	-	Apr	Sun>=15	2:00s	1:00	S
 Rule	Czech	1949	only	-	Apr	 9	2:00s	1:00	S
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone	Europe/Prague	0:57:44 -	LMT	1850
 			0:57:44	-	PMT	1891 Oct    # Prague Mean Time
-			1:00	C-Eur	CE%sT	1944 Sep 17  2:00s
+			1:00	C-Eur	CE%sT	1945 May  9
+			1:00	Czech	CE%sT	1946 Dec  1  3:00
+# Vanguard section, for zic and other parsers that support negative DST.
+#			1:00	-1:00	GMT	1947 Feb 23  2:00
+# Rearguard section, for parsers that do not support negative DST.
+			0:00	-	GMT	1947 Feb 23  2:00
+# End of rearguard section.
 			1:00	Czech	CE%sT	1979
 			1:00	EU	CE%sT
 # Use Europe/Prague also for Slovakia.
@@ -2039,7 +2051,7 @@
 Rule	Neth	1945	only	-	Apr	 2	2:00s	1:00	S
 Rule	Neth	1945	only	-	Sep	16	2:00s	0	-
 #
-# Amsterdam Mean Time was +00:19:32.13 exactly, but the .13 is omitted
+# Amsterdam Mean Time was +00:19:32.13, but the .13 is omitted
 # below because the current format requires GMTOFF to be an integer.
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone Europe/Amsterdam	0:19:32 -	LMT	1835
--- a/make/devkit/createWindowsDevkit2017.sh	Thu May 31 09:52:32 2018 -0700
+++ b/make/devkit/createWindowsDevkit2017.sh	Thu May 31 13:04:30 2018 -0700
@@ -108,8 +108,8 @@
 
     # The redist runtime libs are needed to run the compiler but may not be
     # installed on the machine where the devkit will be used.
-    cp $DEVKIT_ROOT/VC/redist/x64/$MSVCR_DLL $DEVKIT_ROOT/VC/bin/x86
-    cp $DEVKIT_ROOT/VC/redist/x64/$MSVCP_DLL $DEVKIT_ROOT/VC/bin/x86
+    cp $DEVKIT_ROOT/VC/redist/x86/$MSVCR_DLL $DEVKIT_ROOT/VC/bin/x86
+    cp $DEVKIT_ROOT/VC/redist/x86/$MSVCP_DLL $DEVKIT_ROOT/VC/bin/x86
     cp $DEVKIT_ROOT/VC/redist/x64/$MSVCR_DLL $DEVKIT_ROOT/VC/bin/x64
     cp $DEVKIT_ROOT/VC/redist/x64/$MSVCP_DLL $DEVKIT_ROOT/VC/bin/x64
 fi
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/make/gensrc/Gensrc-jdk.scripting.nashorn.gmk	Thu May 31 13:04:30 2018 -0700
@@ -0,0 +1,51 @@
+#
+# Copyright (c) 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
+# 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.
+#
+
+default: all
+
+include $(SPEC)
+include MakeBase.gmk
+include TextFileProcessing.gmk
+
+################################################################################
+
+# Version file needs to be processed with version numbers
+VERSION_FILE := jdk/nashorn/internal/runtime/resources/version.properties
+
+$(eval $(call SetupTextFileProcessing, BUILD_VERSION_FILE, \
+    SOURCE_FILES := $(TOPDIR)/src/$(MODULE)/share/classes/$(VERSION_FILE).template, \
+    OUTPUT_FILE := $(SUPPORT_OUTPUTDIR)/gensrc/$(MODULE)/$(VERSION_FILE), \
+    REPLACEMENTS := \
+        @@VERSION_STRING@@ => $(VERSION_STRING) ; \
+        @@VERSION_SHORT@@ => $(VERSION_SHORT) , \
+))
+
+TARGETS += $(NASGEN_RUN_FILE) $(BUILD_VERSION_FILE)
+
+################################################################################
+
+all: $(TARGETS)
+
+.PHONY: all default
--- a/make/lib/Lib-jdk.net.gmk	Thu May 31 09:52:32 2018 -0700
+++ b/make/lib/Lib-jdk.net.gmk	Thu May 31 13:04:30 2018 -0700
@@ -27,7 +27,7 @@
 
 ################################################################################
 
-ifneq ($(filter $(OPENJDK_TARGET_OS), solaris linux), )
+ifneq ($(filter $(OPENJDK_TARGET_OS), solaris linux macosx), )
 
   $(eval $(call SetupJdkLibrary, BUILD_LIBEXTNET, \
       NAME := extnet, \
--- a/make/test/JtregNativeHotspot.gmk	Thu May 31 09:52:32 2018 -0700
+++ b/make/test/JtregNativeHotspot.gmk	Thu May 31 13:04:30 2018 -0700
@@ -134,6 +134,11 @@
     -I$(VM_TESTBASE_DIR)/nsk/share/jvmti \
     -I$(VM_TESTBASE_DIR)/nsk/share/jvmti/aod
 
+NSK_AOD_INCLUDES := \
+    -I$(VM_TESTBASE_DIR)/nsk/share/aod \
+    -I$(VM_TESTBASE_DIR)/nsk/share/native \
+    -I$(VM_TESTBASE_DIR)/nsk/share/jni
+
 BUILD_HOTSPOT_JTREG_LIBRARIES_CFLAGS_libProcessUtils := $(VM_SHARE_INCLUDES)
 
 BUILD_HOTSPOT_JTREG_LIBRARIES_CFLAGS_libThreadController := $(NSK_MONITORING_INCLUDES)
@@ -823,6 +828,12 @@
 BUILD_HOTSPOT_JTREG_LIBRARIES_CFLAGS_libattach050Agent00 := $(NSK_JVMTI_AOD_INCLUDES)
 BUILD_HOTSPOT_JTREG_LIBRARIES_CFLAGS_libattach002Agent00 := $(NSK_JVMTI_AOD_INCLUDES)
 
+BUILD_HOTSPOT_JTREG_LIBRARIES_CFLAGS_libVirtualMachine07agent00 := $(NSK_AOD_INCLUDES)
+BUILD_HOTSPOT_JTREG_LIBRARIES_CFLAGS_libVirtualMachine07agent01 := $(NSK_AOD_INCLUDES)
+BUILD_HOTSPOT_JTREG_LIBRARIES_CFLAGS_libVirtualMachine07agent02 := $(NSK_AOD_INCLUDES)
+BUILD_HOTSPOT_JTREG_LIBRARIES_CFLAGS_libVirtualMachine07agent03 := $(NSK_AOD_INCLUDES)
+BUILD_HOTSPOT_JTREG_LIBRARIES_CFLAGS_libVirtualMachine09agent00 := $(NSK_AOD_INCLUDES)
+
 ################################################################################
 
 # Platform specific setup
@@ -851,8 +862,6 @@
     BUILD_HOTSPOT_JTREG_EXECUTABLES_CFLAGS_exeFPRegs := -MT
     BUILD_HOTSPOT_JTREG_EXCLUDE += exesigtest.c
 
-    # Disable warning until JDK-8203802 is fixed
-    BUILD_HOTSPOT_JTREG_LIBRARIES_CFLAGS_libtimers += -wd4477
 else
     BUILD_HOTSPOT_JTREG_LIBRARIES_LIBS_libbootclssearch_agent += -lpthread
     BUILD_HOTSPOT_JTREG_LIBRARIES_LIBS_libsystemclssearch_agent += -lpthread
--- a/src/hotspot/cpu/sparc/assembler_sparc.hpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/cpu/sparc/assembler_sparc.hpp	Thu May 31 13:04:30 2018 -0700
@@ -783,8 +783,10 @@
   void flush() {
 #ifdef VALIDATE_PIPELINE
     assert(_delay_state == NoDelay, "Ending code with a delay-slot.");
+#ifdef COMPILER2
     validate_no_pipeline_hazards();
 #endif
+#endif
     AbstractAssembler::flush();
   }
 
--- a/src/hotspot/cpu/x86/x86_64.ad	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/cpu/x86/x86_64.ad	Thu May 31 13:04:30 2018 -0700
@@ -2980,6 +2980,16 @@
   interface(CONST_INTER);
 %}
 
+operand immU8()
+%{
+  predicate((0 <= n->get_int()) && (n->get_int() <= 255));
+  match(ConI);
+
+  op_cost(5);
+  format %{ %}
+  interface(CONST_INTER);
+%}
+
 operand immI16()
 %{
   predicate((-32768 <= n->get_int()) && (n->get_int() <= 32767));
@@ -11597,6 +11607,46 @@
   ins_pipe(ialu_cr_reg_imm);
 %}
 
+instruct compUB_mem_imm(rFlagsReg cr, memory mem, immU8 imm)
+%{
+  match(Set cr (CmpI (LoadUB mem) imm));
+
+  ins_cost(125);
+  format %{ "cmpb    $mem, $imm" %}
+  ins_encode %{ __ cmpb($mem$$Address, $imm$$constant); %}
+  ins_pipe(ialu_cr_reg_mem);
+%}
+
+instruct compB_mem_imm(rFlagsReg cr, memory mem, immI8 imm)
+%{
+  match(Set cr (CmpI (LoadB mem) imm));
+
+  ins_cost(125);
+  format %{ "cmpb    $mem, $imm" %}
+  ins_encode %{ __ cmpb($mem$$Address, $imm$$constant); %}
+  ins_pipe(ialu_cr_reg_mem);
+%}
+
+instruct testUB_mem_imm(rFlagsReg cr, memory mem, immU8 imm, immI0 zero)
+%{
+  match(Set cr (CmpI (AndI (LoadUB mem) imm) zero));
+
+  ins_cost(125);
+  format %{ "testb   $mem, $imm" %}
+  ins_encode %{ __ testb($mem$$Address, $imm$$constant); %}
+  ins_pipe(ialu_cr_reg_mem);
+%}
+
+instruct testB_mem_imm(rFlagsReg cr, memory mem, immI8 imm, immI0 zero)
+%{
+  match(Set cr (CmpI (AndI (LoadB mem) imm) zero));
+
+  ins_cost(125);
+  format %{ "testb   $mem, $imm" %}
+  ins_encode %{ __ testb($mem$$Address, $imm$$constant); %}
+  ins_pipe(ialu_cr_reg_mem);
+%}
+
 //----------Max and Min--------------------------------------------------------
 // Min Instructions
 
--- a/src/hotspot/os/windows/os_perf_windows.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/os/windows/os_perf_windows.cpp	Thu May 31 13:04:30 2018 -0700
@@ -118,6 +118,11 @@
   bool               initialized;
 } MultiCounterQuerySetS, *MultiCounterQuerySetP;
 
+typedef struct {
+  MultiCounterQuerySetS set;
+  int                   process_index;
+} ProcessQueryS, *ProcessQueryP;
+
 static void pdh_cleanup(HQUERY* const query, HCOUNTER* const counter) {
   if (counter != NULL && *counter != NULL) {
     PdhDll::PdhRemoveCounter(*counter);
@@ -158,7 +163,7 @@
   }
 }
 
-static void destroy_counter_query(MultiCounterQuerySetP counter_query_set) {
+static void destroy_multi_counter_query(MultiCounterQuerySetP counter_query_set) {
   for (int i = 0; i < counter_query_set->size; i++) {
     for (int j = 0; j < counter_query_set->queries[i].noOfCounters; ++j) {
       pdh_cleanup(NULL, &counter_query_set->queries[i].counters[j]);
@@ -167,9 +172,18 @@
     pdh_cleanup(&counter_query_set->queries[i].query.query, NULL);
   }
   FREE_C_HEAP_ARRAY(MultiCounterQueryS, counter_query_set->queries);
+}
+
+static void destroy_counter_query(MultiCounterQuerySetP counter_query_set) {
+  destroy_multi_counter_query(counter_query_set);
   FREE_C_HEAP_ARRAY(MultiCounterQuerySetS, counter_query_set);
 }
 
+static void destroy_counter_query(ProcessQueryP process_query) {
+  destroy_multi_counter_query(&process_query->set);
+  FREE_C_HEAP_ARRAY(ProcessQueryS, process_query);
+}
+
 static int open_query(HQUERY* query) {
   return PdhDll::PdhOpenQuery(NULL, 0, query);
 }
@@ -204,6 +218,11 @@
   return OS_OK;
 }
 
+static int allocate_counters(ProcessQueryP process_query, size_t nofCounters) {
+  assert(process_query != NULL, "invariant");
+  return allocate_counters(&process_query->set, nofCounters);
+}
+
 static void deallocate_counters(MultiCounterQueryP query) {
   if (query->counters != NULL) {
     FREE_C_HEAP_ARRAY(char, query->counters);
@@ -262,7 +281,6 @@
 
 static OSReturn add_process_counter(MultiCounterQueryP query, int slot_index, const char* path, bool first_sample_on_init) {
   assert(query != NULL, "invariant");
-  assert(query != NULL, "invariant");
   assert(slot_index < query->noOfCounters, "invariant");
   assert(query->counters[slot_index] == NULL, "invariant");
   const OSReturn ret = add_counter(query, &query->counters[slot_index], path, first_sample_on_init);
@@ -326,13 +344,15 @@
 * (in order to keep this index valid when the list resets from underneath,
 * ensure to call current_query_index_for_process() before every query involving
 * Process object instance data).
+*
+* if unable to query, returns OS_ERR(-1)
 */
 static int current_query_index_for_process() {
   assert(process_image_name != NULL, "invariant");
   assert(pdh_IDProcess_counter_fmt != NULL, "invariant");
   HQUERY tmpQuery = NULL;
   if (open_query(&tmpQuery) != ERROR_SUCCESS) {
-    return 0;
+    return OS_ERR;
   }
   char counter[512];
   HCOUNTER handle_counter = NULL;
@@ -342,12 +362,12 @@
     assert(strlen(counter) < sizeof(counter), "invariant");
     if (PdhDll::PdhAddCounter(tmpQuery, counter, 0, &handle_counter) != ERROR_SUCCESS) {
       pdh_cleanup(&tmpQuery, &handle_counter);
-      return 0;
+      return OS_ERR;
     }
     const PDH_STATUS res = PdhDll::PdhCollectQueryData(tmpQuery);
     if (res == PDH_INVALID_HANDLE || res == PDH_NO_DATA) {
       pdh_cleanup(&tmpQuery, &handle_counter);
-      return 0;
+      return OS_ERR;
     } else {
       PDH_FMT_COUNTERVALUE counter_value;
       formatted_counter_value(handle_counter, PDH_FMT_LONG, &counter_value);
@@ -359,24 +379,28 @@
     }
   }
   pdh_cleanup(&tmpQuery, NULL);
-  return 0;
+  return OS_ERR;
 }
 
-static MultiCounterQuerySetP create_process_counter_query() {
-  MultiCounterQuerySetP const query = NEW_C_HEAP_ARRAY(MultiCounterQuerySetS, 1, mtInternal);
-  memset(query, 0, sizeof(MultiCounterQuerySetS));
+static ProcessQueryP create_process_query() {
   const int current_process_idx = current_query_index_for_process();
-  query->queries = NEW_C_HEAP_ARRAY(MultiCounterQueryS, current_process_idx + 1, mtInternal);
-  memset(query->queries, 0, sizeof(MultiCounterQueryS) * (current_process_idx + 1));
-  query->size = current_process_idx + 1;
-  return query;
+  if (OS_ERR == current_process_idx) {
+    return NULL;
+  }
+  ProcessQueryP const process_query = NEW_C_HEAP_ARRAY(ProcessQueryS, 1, mtInternal);
+  memset(process_query, 0, sizeof(ProcessQueryS));
+  process_query->set.queries = NEW_C_HEAP_ARRAY(MultiCounterQueryS, current_process_idx + 1, mtInternal);
+  memset(process_query->set.queries, 0, sizeof(MultiCounterQueryS) * (current_process_idx + 1));
+  process_query->process_index = current_process_idx;
+  process_query->set.size = current_process_idx + 1;
+  assert(process_query->set.size > process_query->process_index, "invariant");
+  return process_query;
 }
 
-static MultiCounterQueryP current_process_counter_query(MultiCounterQuerySetP process_query_set) {
-  assert(process_query_set != NULL, "invariant");
-  const int current_query_index = current_query_index_for_process();
-  assert(current_query_index < process_query_set->size, "invariant");
-  return &process_query_set->queries[current_query_index];
+static MultiCounterQueryP current_process_counter_query(ProcessQueryP process_query) {
+  assert(process_query != NULL, "invariant");
+  assert(process_query->process_index < process_query->set.size, "invariant");
+  return &process_query->set.queries[process_query->process_index];
 }
 
 static void clear_multi_counter(MultiCounterQueryP query) {
@@ -384,19 +408,46 @@
     pdh_cleanup(NULL, &query->counters[i]);
   }
   pdh_cleanup(&query->query.query, NULL);
+  query->initialized = false;
 }
 
-static int collect_process_query_data(MultiCounterQuerySetP counter_query_set) {
+static int ensure_valid_process_query_index(ProcessQueryP process_query) {
+  assert(process_query != NULL, "invariant");
+  const int previous_process_idx = process_query->process_index;
+  if (previous_process_idx == 0) {
+    return previous_process_idx;
+  }
   const int current_process_idx = current_query_index_for_process();
-  while (current_process_idx < counter_query_set->size - 1) {
-    const int new_size = --counter_query_set->size;
-    clear_multi_counter(&counter_query_set->queries[new_size]);
+  if (current_process_idx == previous_process_idx || OS_ERR == current_process_idx ||
+    current_process_idx >= process_query->set.size) {
+    return previous_process_idx;
   }
-  return collect_query_data(&counter_query_set->queries[current_process_idx]);
+
+  assert(current_process_idx >= 0 && current_process_idx < process_query->set.size, "out of bounds!");
+  while (current_process_idx < process_query->set.size - 1) {
+    const int new_size = --process_query->set.size;
+    clear_multi_counter(&process_query->set.queries[new_size]);
+  }
+  assert(current_process_idx < process_query->set.size, "invariant");
+  process_query->process_index = current_process_idx;
+  return current_process_idx;
 }
 
-static int query_process_counter(MultiCounterQuerySetP process_query_set, int slot_index, DWORD format, PDH_FMT_COUNTERVALUE* const value) {
-  MultiCounterQueryP const current_query = current_process_counter_query(process_query_set);
+static MultiCounterQueryP current_process_query(ProcessQueryP process_query) {
+  assert(process_query != NULL, "invariant");
+  const int current_process_idx = ensure_valid_process_query_index(process_query);
+  assert(current_process_idx == process_query->process_index, "invariant");
+  assert(current_process_idx < process_query->set.size, "invariant");
+  return &process_query->set.queries[current_process_idx];
+}
+
+static int collect_process_query_data(ProcessQueryP process_query) {
+  assert(process_query != NULL, "invariant");
+  return collect_query_data(current_process_query(process_query));
+}
+
+static int query_process_counter(ProcessQueryP process_query, int slot_index, DWORD format, PDH_FMT_COUNTERVALUE* const value) {
+  MultiCounterQueryP const current_query = current_process_counter_query(process_query);
   assert(current_query != NULL, "invariant");
   assert(slot_index < current_query->noOfCounters, "invariant");
   assert(current_query->counters[slot_index] != NULL, "invariant");
@@ -810,7 +861,7 @@
   return initialize_cpu_query_counters(cpu_query, pdh_counter_idx);
 }
 
-static int initialize_process_counter(MultiCounterQuerySetP query_set, int slot_index, DWORD pdh_counter_index) {
+static int initialize_process_counter(ProcessQueryP process_query, int slot_index, DWORD pdh_counter_index) {
   char* localized_process_object;
   if (lookup_name_by_index(PDH_PROCESS_IDX, &localized_process_object) != OS_OK) {
     return OS_ERR;
@@ -821,7 +872,7 @@
     return OS_ERR;
   }
   assert(localized_counter_name != NULL, "invariant");
-  for (int i = 0; i < query_set->size; ++i) {
+  for (int i = 0; i < process_query->set.size; ++i) {
     char instanceIndexBuffer[32];
     const char* counter_path = make_fully_qualified_counter_path(localized_process_object,
                                                                  localized_counter_name,
@@ -830,7 +881,7 @@
     if (counter_path == NULL) {
       return OS_ERR;
     }
-    MultiCounterQueryP const query = &query_set->queries[i];
+    MultiCounterQueryP const query = &process_query->set.queries[i];
     if (add_process_counter(query, slot_index, counter_path, true)) {
       return OS_ERR;
     }
@@ -839,8 +890,9 @@
 }
 
 static CounterQueryP create_counter_query(DWORD pdh_object_idx, DWORD pdh_counter_idx) {
-  assert(is_valid_pdh_index(pdh_object_idx), "invariant");
-  assert(is_valid_pdh_index(pdh_counter_idx), "invariant");
+  if (!((is_valid_pdh_index(pdh_object_idx) && is_valid_pdh_index(pdh_counter_idx)))) {
+    return NULL;
+  }
   CounterQueryP const query = create_counter_query();
   const char* object = pdh_localized_artifact(pdh_object_idx);
   assert(object != NULL, "invariant");
@@ -917,7 +969,7 @@
   friend class CPUPerformanceInterface;
  private:
   CounterQueryP _context_switches;
-  MultiCounterQuerySetP _process_cpu_load;
+  ProcessQueryP _process_cpu_load;
   MultiCounterQueryP _machine_cpu_load;
 
   int cpu_load(int which_logical_cpu, double* cpu_load);
@@ -963,34 +1015,28 @@
 
 bool CPUPerformanceInterface::CPUPerformance::initialize() {
   if (!pdh_acquire()) {
-    return false;
+    return true;
   }
   _context_switches = create_counter_query(PDH_SYSTEM_IDX, PDH_CONTEXT_SWITCH_RATE_IDX);
-  if (_context_switches == NULL) {
-    return false;
-  }
-  _process_cpu_load = create_process_counter_query();
+  _process_cpu_load = create_process_query();
   if (_process_cpu_load == NULL) {
-    return false;
+    return true;
   }
   if (allocate_counters(_process_cpu_load, 2) != OS_OK) {
-    return false;
+    return true;
   }
   if (initialize_process_counter(_process_cpu_load, 0, PDH_PROCESSOR_TIME_IDX) != OS_OK) {
-    return false;
+    return true;
   }
   if (initialize_process_counter(_process_cpu_load, 1, PDH_PRIV_PROCESSOR_TIME_IDX) != OS_OK) {
-    return false;
+    return true;
   }
-  _process_cpu_load->initialized = true;
-
+  _process_cpu_load->set.initialized = true;
   _machine_cpu_load = create_multi_counter_query();
   if (_machine_cpu_load == NULL) {
-    return false;
+    return true;
   }
-  if (initialize_cpu_query(_machine_cpu_load, PDH_PROCESSOR_TIME_IDX) != OS_OK) {
-    return false;
-  }
+  initialize_cpu_query(_machine_cpu_load, PDH_PROCESSOR_TIME_IDX);
   return true;
 }
 
@@ -1044,12 +1090,13 @@
 }
 
 int CPUPerformanceInterface::CPUPerformance::cpu_load(int which_logical_cpu, double* cpu_load) {
+  *cpu_load = .0;
+  if (_machine_cpu_load == NULL || !_machine_cpu_load->initialized) {
+    return OS_ERR;
+  }
   assert(_machine_cpu_load != NULL, "invariant");
   assert(which_logical_cpu < _machine_cpu_load->noOfCounters, "invariant");
-  *cpu_load = .0;
-  if (!_machine_cpu_load->initialized) {
-    return OS_ERR;
-  }
+
   if (collect_query_data(_machine_cpu_load)) {
     return OS_ERR;
   }
@@ -1062,11 +1109,11 @@
 }
 
 int CPUPerformanceInterface::CPUPerformance::cpu_load_total_process(double* cpu_load) {
-  assert(_process_cpu_load != NULL, "invariant");
   *cpu_load = .0;
-  if (!_process_cpu_load->initialized) {
+  if (_process_cpu_load == NULL || !_process_cpu_load->set.initialized) {
     return OS_ERR;
   }
+  assert(_process_cpu_load != NULL, "invariant");
   if (collect_process_query_data(_process_cpu_load)) {
     return OS_ERR;
   }
@@ -1090,9 +1137,11 @@
   *pjvmUserLoad = .0;
   *pjvmKernelLoad = .0;
   *psystemTotalLoad = .0;
-  if (!_process_cpu_load->initialized) {
+
+  if (_process_cpu_load == NULL || !_process_cpu_load->set.initialized) {
     return OS_ERR;
   }
+  assert(_process_cpu_load != NULL, "invariant");
   if (collect_process_query_data(_process_cpu_load)) {
     return OS_ERR;
   }
@@ -1138,9 +1187,10 @@
 int CPUPerformanceInterface::CPUPerformance::context_switch_rate(double* rate) {
   assert(rate != NULL, "invariant");
   *rate = .0;
-  if (!_context_switches->initialized) {
+  if (_context_switches == NULL || !_context_switches->initialized) {
     return OS_ERR;
   }
+  assert(_context_switches != NULL, "invariant");
   if (collect_query_data(_context_switches) != OS_OK) {
     return OS_ERR;
   }
--- a/src/hotspot/share/classfile/classLoaderData.hpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/classfile/classLoaderData.hpp	Thu May 31 13:04:30 2018 -0700
@@ -400,9 +400,16 @@
   static ClassLoaderData* class_loader_data_or_null(oop loader);
   static ClassLoaderData* anonymous_class_loader_data(Handle loader);
 
+  // Returns Klass* of associated class loader, or NULL if associated loader is <bootstrap>.
+  // Also works if unloading.
+  Klass* class_loader_klass() const { return _class_loader_klass; }
 
-  Klass* class_loader_klass() const { return _class_loader_klass; }
+  // Returns Name of associated class loader.
+  // Returns NULL if associated class loader is <bootstrap> or if no name has been set for
+  //   this loader.
+  // Also works if unloading.
   Symbol* class_loader_name() const { return _class_loader_name; }
+
   JFR_ONLY(DEFINE_TRACE_ID_METHODS;)
 };
 
--- a/src/hotspot/share/classfile/classLoaderExt.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/classfile/classLoaderExt.cpp	Thu May 31 13:04:30 2018 -0700
@@ -55,8 +55,10 @@
 
 void ClassLoaderExt::append_boot_classpath(ClassPathEntry* new_entry) {
 #if INCLUDE_CDS
-  warning("Sharing is only supported for boot loader classes because bootstrap classpath has been appended");
-  FileMapInfo::current_info()->header()->set_has_platform_or_app_classes(false);
+  if (UseSharedSpaces) {
+    warning("Sharing is only supported for boot loader classes because bootstrap classpath has been appended");
+    FileMapInfo::current_info()->header()->set_has_platform_or_app_classes(false);
+  }
 #endif
   ClassLoader::add_to_boot_append_entries(new_entry);
 }
--- a/src/hotspot/share/classfile/systemDictionary.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/classfile/systemDictionary.cpp	Thu May 31 13:04:30 2018 -0700
@@ -1817,22 +1817,11 @@
 // ----------------------------------------------------------------------------
 // GC support
 
-void SystemDictionary::always_strong_oops_do(OopClosure* blk) {
-  roots_oops_do(blk, NULL);
-}
-
-
 // Assumes classes in the SystemDictionary are only unloaded at a safepoint
 // Note: anonymous classes are not in the SD.
-bool SystemDictionary::do_unloading(BoolObjectClosure* is_alive,
-                                    GCTimer* gc_timer,
+bool SystemDictionary::do_unloading(GCTimer* gc_timer,
                                     bool do_cleaning) {
 
-  {
-    GCTraceTime(Debug, gc, phases) t("SystemDictionary WeakHandle cleaning", gc_timer);
-    vm_weak_oop_storage()->weak_oops_do(is_alive, &do_nothing_cl);
-  }
-
   bool unloading_occurred;
   {
     GCTraceTime(Debug, gc, phases) t("ClassLoaderData", gc_timer);
@@ -1863,27 +1852,6 @@
   return unloading_occurred;
 }
 
-void SystemDictionary::roots_oops_do(OopClosure* strong, OopClosure* weak) {
-  strong->do_oop(&_java_system_loader);
-  strong->do_oop(&_java_platform_loader);
-  strong->do_oop(&_system_loader_lock_obj);
-  CDS_ONLY(SystemDictionaryShared::roots_oops_do(strong);)
-
-  // Do strong roots marking if the closures are the same.
-  if (strong == weak || !ClassUnloading) {
-    // Only the protection domain oops contain references into the heap. Iterate
-    // over all of them.
-    vm_weak_oop_storage()->oops_do(strong);
-  } else {
-   if (weak != NULL) {
-     vm_weak_oop_storage()->oops_do(weak);
-   }
-  }
-
-  // Visit extra methods
-  invoke_method_table()->oops_do(strong);
-}
-
 void SystemDictionary::oops_do(OopClosure* f) {
   f->do_oop(&_java_system_loader);
   f->do_oop(&_java_platform_loader);
@@ -1892,8 +1860,6 @@
 
   // Visit extra methods
   invoke_method_table()->oops_do(f);
-
-  vm_weak_oop_storage()->oops_do(f);
 }
 
 // CDS: scan and relocate all classes in the system dictionary.
--- a/src/hotspot/share/classfile/systemDictionary.hpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/classfile/systemDictionary.hpp	Thu May 31 13:04:30 2018 -0700
@@ -357,14 +357,9 @@
 
   // Garbage collection support
 
-  // This method applies "blk->do_oop" to all the pointers to "system"
-  // classes and loaders.
-  static void always_strong_oops_do(OopClosure* blk);
-
   // Unload (that is, break root links to) all unmarked classes and
   // loaders.  Returns "true" iff something was unloaded.
-  static bool do_unloading(BoolObjectClosure* is_alive,
-                           GCTimer* gc_timer,
+  static bool do_unloading(GCTimer* gc_timer,
                            bool do_cleaning = true);
 
   // Used by DumpSharedSpaces only to remove classes that failed verification
@@ -374,7 +369,6 @@
 
   // Applies "f->do_oop" to all root oops in the system dictionary.
   static void oops_do(OopClosure* f);
-  static void roots_oops_do(OopClosure* strong, OopClosure* weak);
 
   // System loader lock
   static oop system_loader_lock()           { return _system_loader_lock_obj; }
--- a/src/hotspot/share/gc/cms/cmsHeap.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/gc/cms/cmsHeap.cpp	Thu May 31 13:04:30 2018 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2017, 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
@@ -222,10 +222,9 @@
                                 OopsInGenClosure* root_closure,
                                 CLDClosure* cld_closure) {
   MarkingCodeBlobClosure mark_code_closure(root_closure, !CodeBlobToOopClosure::FixRelocations);
-  OopsInGenClosure* weak_roots = only_strong_roots ? NULL : root_closure;
   CLDClosure* weak_cld_closure = only_strong_roots ? NULL : cld_closure;
 
-  process_roots(scope, so, root_closure, weak_roots, cld_closure, weak_cld_closure, &mark_code_closure);
+  process_roots(scope, so, root_closure, cld_closure, weak_cld_closure, &mark_code_closure);
   if (!only_strong_roots) {
     process_string_table_roots(scope, root_closure);
   }
--- a/src/hotspot/share/gc/cms/concurrentMarkSweepGeneration.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/gc/cms/concurrentMarkSweepGeneration.cpp	Thu May 31 13:04:30 2018 -0700
@@ -5201,7 +5201,7 @@
       GCTraceTime(Debug, gc, phases) t("Class Unloading", _gc_timer_cm);
 
       // Unload classes and purge the SystemDictionary.
-      bool purged_class = SystemDictionary::do_unloading(&_is_alive_closure, _gc_timer_cm);
+      bool purged_class = SystemDictionary::do_unloading(_gc_timer_cm);
 
       // Unload nmethods.
       CodeCache::do_unloading(&_is_alive_closure, purged_class);
--- a/src/hotspot/share/gc/cms/jvmFlagConstraintsCMS.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/gc/cms/jvmFlagConstraintsCMS.cpp	Thu May 31 13:04:30 2018 -0700
@@ -30,17 +30,16 @@
 #include "gc/shared/genCollectedHeap.hpp"
 #include "gc/shared/jvmFlagConstraintsGC.hpp"
 #include "memory/universe.hpp"
-#include "runtime/flags/jvmFlagRangeList.hpp"
 #include "runtime/globals_extension.hpp"
 #include "utilities/globalDefinitions.hpp"
 
 static JVMFlag::Error ParallelGCThreadsAndCMSWorkQueueDrainThreshold(uint threads, uintx threshold, bool verbose) {
   // CMSWorkQueueDrainThreshold is verified to be less than max_juint
   if (UseConcMarkSweepGC && (threads > (uint)(max_jint / (uint)threshold))) {
-    CommandLineError::print(verbose,
-                            "ParallelGCThreads (" UINT32_FORMAT ") or CMSWorkQueueDrainThreshold ("
-                            UINTX_FORMAT ") is too large\n",
-                            threads, threshold);
+    JVMFlag::printError(verbose,
+                        "ParallelGCThreads (" UINT32_FORMAT ") or CMSWorkQueueDrainThreshold ("
+                        UINTX_FORMAT ") is too large\n",
+                        threads, threshold);
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
   return JVMFlag::SUCCESS;
@@ -49,20 +48,20 @@
 JVMFlag::Error ParallelGCThreadsConstraintFuncCMS(uint value, bool verbose) {
   // To avoid overflow at ParScanClosure::do_oop_work.
   if (UseConcMarkSweepGC && (value > (max_jint / 10))) {
-    CommandLineError::print(verbose,
-                            "ParallelGCThreads (" UINT32_FORMAT ") must be "
-                            "less than or equal to " UINT32_FORMAT " for CMS GC\n",
-                            value, (max_jint / 10));
+    JVMFlag::printError(verbose,
+                        "ParallelGCThreads (" UINT32_FORMAT ") must be "
+                        "less than or equal to " UINT32_FORMAT " for CMS GC\n",
+                        value, (max_jint / 10));
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
   return ParallelGCThreadsAndCMSWorkQueueDrainThreshold(value, CMSWorkQueueDrainThreshold, verbose);
 }
 JVMFlag::Error ParGCStridesPerThreadConstraintFunc(uintx value, bool verbose) {
   if (UseConcMarkSweepGC && (value > ((uintx)max_jint / (uintx)ParallelGCThreads))) {
-    CommandLineError::print(verbose,
-                            "ParGCStridesPerThread (" UINTX_FORMAT ") must be "
-                            "less than or equal to ergonomic maximum (" UINTX_FORMAT ")\n",
-                            value, ((uintx)max_jint / (uintx)ParallelGCThreads));
+    JVMFlag::printError(verbose,
+                        "ParGCStridesPerThread (" UINTX_FORMAT ") must be "
+                        "less than or equal to ergonomic maximum (" UINTX_FORMAT ")\n",
+                        value, ((uintx)max_jint / (uintx)ParallelGCThreads));
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
   return JVMFlag::SUCCESS;
@@ -76,10 +75,10 @@
     size_t card_table_size = ct->cards_required(heap_size) - 1; // Valid card table size
 
     if ((size_t)value > card_table_size) {
-      CommandLineError::print(verbose,
-                              "ParGCCardsPerStrideChunk (" INTX_FORMAT ") is too large for the heap size and "
-                              "must be less than or equal to card table size (" SIZE_FORMAT ")\n",
-                              value, card_table_size);
+      JVMFlag::printError(verbose,
+                          "ParGCCardsPerStrideChunk (" INTX_FORMAT ") is too large for the heap size and "
+                          "must be less than or equal to card table size (" SIZE_FORMAT ")\n",
+                          value, card_table_size);
       return JVMFlag::VIOLATES_CONSTRAINT;
     }
 
@@ -89,10 +88,10 @@
     uintx n_strides = ParallelGCThreads * ParGCStridesPerThread;
     uintx ergo_max = max_uintx / n_strides;
     if ((uintx)value > ergo_max) {
-      CommandLineError::print(verbose,
-                              "ParGCCardsPerStrideChunk (" INTX_FORMAT ") must be "
-                              "less than or equal to ergonomic maximum (" UINTX_FORMAT ")\n",
-                              value, ergo_max);
+      JVMFlag::printError(verbose,
+                          "ParGCCardsPerStrideChunk (" INTX_FORMAT ") must be "
+                          "less than or equal to ergonomic maximum (" UINTX_FORMAT ")\n",
+                          value, ergo_max);
       return JVMFlag::VIOLATES_CONSTRAINT;
     }
   }
@@ -104,10 +103,10 @@
 
   if (UseConcMarkSweepGC) {
     if (value > CMSOldPLABMax) {
-      CommandLineError::print(verbose,
-                              "CMSOldPLABMin (" SIZE_FORMAT ") must be "
-                              "less than or equal to CMSOldPLABMax (" SIZE_FORMAT ")\n",
-                              value, CMSOldPLABMax);
+      JVMFlag::printError(verbose,
+                          "CMSOldPLABMin (" SIZE_FORMAT ") must be "
+                          "less than or equal to CMSOldPLABMax (" SIZE_FORMAT ")\n",
+                          value, CMSOldPLABMax);
       return JVMFlag::VIOLATES_CONSTRAINT;
     }
     status = MaxPLABSizeBounds("CMSOldPLABMin", value, verbose);
@@ -129,11 +128,11 @@
     ConcurrentMarkSweepGeneration* cms = CMSHeap::heap()->old_gen();
     const size_t ergo_max = cms->cmsSpace()->max_flag_size_for_task_size();
     if (value > ergo_max) {
-      CommandLineError::print(verbose,
-                              "%s (" SIZE_FORMAT ") must be "
-                              "less than or equal to ergonomic maximum (" SIZE_FORMAT ") "
-                              "which is based on the maximum size of the old generation of the Java heap\n",
-                              name, value, ergo_max);
+      JVMFlag::printError(verbose,
+                          "%s (" SIZE_FORMAT ") must be "
+                          "less than or equal to ergonomic maximum (" SIZE_FORMAT ") "
+                          "which is based on the maximum size of the old generation of the Java heap\n",
+                          name, value, ergo_max);
       return JVMFlag::VIOLATES_CONSTRAINT;
     }
   }
@@ -150,10 +149,10 @@
     // Note that rescan_task_size() will be aligned if CMSRescanMultiple is a multiple of 'HeapWordSize'
     // because rescan_task_size() is CardTable::card_size / HeapWordSize * BitsPerWord.
     if (value % HeapWordSize != 0) {
-      CommandLineError::print(verbose,
-                              "CMSRescanMultiple (" SIZE_FORMAT ") must be "
-                              "a multiple of " SIZE_FORMAT "\n",
-                              value, HeapWordSize);
+      JVMFlag::printError(verbose,
+                          "CMSRescanMultiple (" SIZE_FORMAT ") must be "
+                          "a multiple of " SIZE_FORMAT "\n",
+                          value, HeapWordSize);
       status = JVMFlag::VIOLATES_CONSTRAINT;
     }
   }
@@ -167,10 +166,10 @@
 
 JVMFlag::Error CMSPrecleanDenominatorConstraintFunc(uintx value, bool verbose) {
   if (UseConcMarkSweepGC && (value <= CMSPrecleanNumerator)) {
-    CommandLineError::print(verbose,
-                            "CMSPrecleanDenominator (" UINTX_FORMAT ") must be "
-                            "strickly greater than CMSPrecleanNumerator (" UINTX_FORMAT ")\n",
-                            value, CMSPrecleanNumerator);
+    JVMFlag::printError(verbose,
+                        "CMSPrecleanDenominator (" UINTX_FORMAT ") must be "
+                        "strickly greater than CMSPrecleanNumerator (" UINTX_FORMAT ")\n",
+                        value, CMSPrecleanNumerator);
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
   return JVMFlag::SUCCESS;
@@ -178,10 +177,10 @@
 
 JVMFlag::Error CMSPrecleanNumeratorConstraintFunc(uintx value, bool verbose) {
   if (UseConcMarkSweepGC && (value >= CMSPrecleanDenominator)) {
-    CommandLineError::print(verbose,
-                            "CMSPrecleanNumerator (" UINTX_FORMAT ") must be "
-                            "less than CMSPrecleanDenominator (" UINTX_FORMAT ")\n",
-                            value, CMSPrecleanDenominator);
+    JVMFlag::printError(verbose,
+                        "CMSPrecleanNumerator (" UINTX_FORMAT ") must be "
+                        "less than CMSPrecleanDenominator (" UINTX_FORMAT ")\n",
+                        value, CMSPrecleanDenominator);
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
   return JVMFlag::SUCCESS;
@@ -191,10 +190,10 @@
   if (UseConcMarkSweepGC) {
     size_t max_capacity = CMSHeap::heap()->young_gen()->max_capacity();
     if (value > max_uintx - max_capacity) {
-    CommandLineError::print(verbose,
-                            "CMSSamplingGrain (" UINTX_FORMAT ") must be "
-                            "less than or equal to ergonomic maximum (" SIZE_FORMAT ")\n",
-                            value, max_uintx - max_capacity);
+    JVMFlag::printError(verbose,
+                        "CMSSamplingGrain (" UINTX_FORMAT ") must be "
+                        "less than or equal to ergonomic maximum (" SIZE_FORMAT ")\n",
+                        value, max_uintx - max_capacity);
     return JVMFlag::VIOLATES_CONSTRAINT;
     }
   }
@@ -216,11 +215,11 @@
     size_t bitmap_size = cms->collector()->markBitMap()->sizeInWords();
 
     if (value > bitmap_size) {
-      CommandLineError::print(verbose,
-                              "CMSBitMapYieldQuantum (" SIZE_FORMAT ") must "
-                              "be less than or equal to bitmap size (" SIZE_FORMAT ") "
-                              "whose size corresponds to the size of old generation of the Java heap\n",
-                              value, bitmap_size);
+      JVMFlag::printError(verbose,
+                          "CMSBitMapYieldQuantum (" SIZE_FORMAT ") must "
+                          "be less than or equal to bitmap size (" SIZE_FORMAT ") "
+                          "whose size corresponds to the size of old generation of the Java heap\n",
+                          value, bitmap_size);
       return JVMFlag::VIOLATES_CONSTRAINT;
     }
   }
@@ -229,9 +228,9 @@
 
 JVMFlag::Error OldPLABSizeConstraintFuncCMS(size_t value, bool verbose) {
   if (value == 0) {
-    CommandLineError::print(verbose,
-                            "OldPLABSize (" SIZE_FORMAT ") must be greater than 0",
-                            value);
+    JVMFlag::printError(verbose,
+                        "OldPLABSize (" SIZE_FORMAT ") must be greater than 0",
+                        value);
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
   // For CMS, OldPLABSize is the number of free blocks of a given size that are used when
--- a/src/hotspot/share/gc/g1/g1CollectedHeap.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/gc/g1/g1CollectedHeap.cpp	Thu May 31 13:04:30 2018 -0700
@@ -1611,6 +1611,9 @@
   const uint max_region_idx = (1U << (sizeof(RegionIdx_t)*BitsPerByte-1)) - 1;
   guarantee((max_regions() - 1) <= max_region_idx, "too many regions");
 
+  // The G1FromCardCache reserves card with value 0 as "invalid", so the heap must not
+  // start within the first card.
+  guarantee(g1_rs.base() >= (char*)G1CardTable::card_size, "Java heap must not start within the first card.");
   // Also create a G1 rem set.
   _g1_rem_set = new G1RemSet(this, _card_table, _hot_card_cache);
   _g1_rem_set->initialize(max_capacity(), max_regions());
--- a/src/hotspot/share/gc/g1/g1ConcurrentMark.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/gc/g1/g1ConcurrentMark.cpp	Thu May 31 13:04:30 2018 -0700
@@ -1665,7 +1665,7 @@
   // Unload Klasses, String, Symbols, Code Cache, etc.
   if (ClassUnloadingWithConcurrentMark) {
     GCTraceTime(Debug, gc, phases) debug("Class Unloading", _gc_timer_cm);
-    bool purged_classes = SystemDictionary::do_unloading(&g1_is_alive, _gc_timer_cm, false /* Defer cleaning */);
+    bool purged_classes = SystemDictionary::do_unloading(_gc_timer_cm, false /* Defer cleaning */);
     _g1h->complete_cleaning(&g1_is_alive, purged_classes);
   } else {
     GCTraceTime(Debug, gc, phases) debug("Cleanup", _gc_timer_cm);
--- a/src/hotspot/share/gc/g1/g1FromCardCache.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/gc/g1/g1FromCardCache.cpp	Thu May 31 13:04:30 2018 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 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
@@ -47,7 +47,9 @@
                                                              num_par_rem_sets,
                                                              &_static_mem_size);
 
-  invalidate(0, _max_regions);
+  if (AlwaysPreTouch) {
+    invalidate(0, _max_regions);
+  }
 }
 
 void G1FromCardCache::invalidate(uint start_idx, size_t new_num_regions) {
--- a/src/hotspot/share/gc/g1/g1FromCardCache.hpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/gc/g1/g1FromCardCache.hpp	Thu May 31 13:04:30 2018 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 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
@@ -31,7 +31,7 @@
 // G1FromCardCache remembers the most recently processed card on the heap on
 // a per-region and per-thread basis.
 class G1FromCardCache : public AllStatic {
- private:
+private:
   // Array of card indices. Indexed by heap region (rows) and thread (columns) to minimize
   // thread contention.
   // This order minimizes the time to clear all entries for a given region during region
@@ -49,9 +49,12 @@
   }
 #endif
 
- public:
-  static const uintptr_t InvalidCard = UINTPTR_MAX;
+  // This card index indicates "no card for that entry" yet. This allows us to use the OS
+  // lazy backing of memory with zero-filled pages to avoid initial actual memory use.
+  // This means that the heap must not contain card zero.
+  static const uintptr_t InvalidCard = 0;
 
+public:
   static void clear(uint region_idx);
 
   // Returns true if the given card is in the cache at the given location, or
--- a/src/hotspot/share/gc/g1/g1FullCollector.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/gc/g1/g1FullCollector.cpp	Thu May 31 13:04:30 2018 -0700
@@ -222,7 +222,7 @@
   if (ClassUnloading) {
     GCTraceTime(Debug, gc, phases) debug("Phase 1: Class Unloading and Cleanup", scope()->timer());
     // Unload classes and purge the SystemDictionary.
-    bool purged_class = SystemDictionary::do_unloading(&_is_alive, scope()->timer());
+    bool purged_class = SystemDictionary::do_unloading(scope()->timer());
     _heap->complete_cleaning(&_is_alive, purged_class);
   } else {
     GCTraceTime(Debug, gc, phases) debug("Phase 1: String and Symbol Tables Cleanup", scope()->timer());
--- a/src/hotspot/share/gc/g1/g1RegionMarkStatsCache.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/gc/g1/g1RegionMarkStatsCache.cpp	Thu May 31 13:04:30 2018 -0700
@@ -36,9 +36,6 @@
   guarantee(is_power_of_2(num_cache_entries),
             "Number of cache entries must be power of two, but is %u", num_cache_entries);
   _cache = NEW_C_HEAP_ARRAY(G1RegionMarkStatsCacheEntry, _num_cache_entries, mtGC);
-  for (uint i = 0; i < _num_cache_entries; i++) {
-    _cache[i].clear();
-  }
   _num_cache_entries_mask = _num_cache_entries - 1;
 }
 
--- a/src/hotspot/share/gc/g1/g1RootProcessor.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/gc/g1/g1RootProcessor.cpp	Thu May 31 13:04:30 2018 -0700
@@ -241,7 +241,6 @@
                                        G1GCPhaseTimes* phase_times,
                                        uint worker_i) {
   OopClosure* strong_roots = closures->strong_oops();
-  OopClosure* weak_roots = closures->weak_oops();
 
   {
     G1GCParPhaseTimesTracker x(phase_times, G1GCPhaseTimes::UniverseRoots, worker_i);
@@ -290,7 +289,7 @@
   {
     G1GCParPhaseTimesTracker x(phase_times, G1GCPhaseTimes::SystemDictionaryRoots, worker_i);
     if (!_process_strong_tasks.is_task_claimed(G1RP_PS_SystemDictionary_oops_do)) {
-      SystemDictionary::roots_oops_do(strong_roots, weak_roots);
+      SystemDictionary::oops_do(strong_roots);
     }
   }
 }
--- a/src/hotspot/share/gc/g1/jvmFlagConstraintsG1.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/gc/g1/jvmFlagConstraintsG1.cpp	Thu May 31 13:04:30 2018 -0700
@@ -24,7 +24,7 @@
 
 #include "precompiled.hpp"
 #include "gc/g1/heapRegionBounds.inline.hpp"
-#include "runtime/flags/jvmFlagRangeList.hpp"
+#include "gc/g1/jvmFlagConstraintsG1.hpp"
 #include "runtime/globals_extension.hpp"
 #include "utilities/globalDefinitions.hpp"
 
@@ -34,10 +34,10 @@
   // Default value of G1RSetRegionEntries=0 means will be set ergonomically.
   // Minimum value is 1.
   if (FLAG_IS_CMDLINE(G1RSetRegionEntries) && (value < 1)) {
-    CommandLineError::print(verbose,
-                            "G1RSetRegionEntries (" INTX_FORMAT ") must be "
-                            "greater than or equal to 1\n",
-                            value);
+    JVMFlag::printError(verbose,
+                        "G1RSetRegionEntries (" INTX_FORMAT ") must be "
+                        "greater than or equal to 1\n",
+                        value);
     return JVMFlag::VIOLATES_CONSTRAINT;
   } else {
     return JVMFlag::SUCCESS;
@@ -50,10 +50,10 @@
   // Default value of G1RSetSparseRegionEntries=0 means will be set ergonomically.
   // Minimum value is 1.
   if (FLAG_IS_CMDLINE(G1RSetSparseRegionEntries) && (value < 1)) {
-    CommandLineError::print(verbose,
-                            "G1RSetSparseRegionEntries (" INTX_FORMAT ") must be "
-                            "greater than or equal to 1\n",
-                            value);
+    JVMFlag::printError(verbose,
+                        "G1RSetSparseRegionEntries (" INTX_FORMAT ") must be "
+                        "greater than or equal to 1\n",
+                        value);
     return JVMFlag::VIOLATES_CONSTRAINT;
   } else {
     return JVMFlag::SUCCESS;
@@ -65,10 +65,10 @@
 
   // Default value of G1HeapRegionSize=0 means will be set ergonomically.
   if (FLAG_IS_CMDLINE(G1HeapRegionSize) && (value < HeapRegionBounds::min_size())) {
-    CommandLineError::print(verbose,
-                            "G1HeapRegionSize (" SIZE_FORMAT ") must be "
-                            "greater than or equal to ergonomic heap region minimum size\n",
-                            value);
+    JVMFlag::printError(verbose,
+                        "G1HeapRegionSize (" SIZE_FORMAT ") must be "
+                        "greater than or equal to ergonomic heap region minimum size\n",
+                        value);
     return JVMFlag::VIOLATES_CONSTRAINT;
   } else {
     return JVMFlag::SUCCESS;
@@ -79,10 +79,10 @@
   if (!UseG1GC) return JVMFlag::SUCCESS;
 
   if (value > G1MaxNewSizePercent) {
-    CommandLineError::print(verbose,
-                            "G1NewSizePercent (" UINTX_FORMAT ") must be "
-                            "less than or equal to G1MaxNewSizePercent (" UINTX_FORMAT ")\n",
-                            value, G1MaxNewSizePercent);
+    JVMFlag::printError(verbose,
+                        "G1NewSizePercent (" UINTX_FORMAT ") must be "
+                        "less than or equal to G1MaxNewSizePercent (" UINTX_FORMAT ")\n",
+                        value, G1MaxNewSizePercent);
     return JVMFlag::VIOLATES_CONSTRAINT;
   } else {
     return JVMFlag::SUCCESS;
@@ -93,10 +93,10 @@
   if (!UseG1GC) return JVMFlag::SUCCESS;
 
   if (value < G1NewSizePercent) {
-    CommandLineError::print(verbose,
-                            "G1MaxNewSizePercent (" UINTX_FORMAT ") must be "
-                            "greater than or equal to G1NewSizePercent (" UINTX_FORMAT ")\n",
-                            value, G1NewSizePercent);
+    JVMFlag::printError(verbose,
+                        "G1MaxNewSizePercent (" UINTX_FORMAT ") must be "
+                        "greater than or equal to G1NewSizePercent (" UINTX_FORMAT ")\n",
+                        value, G1NewSizePercent);
     return JVMFlag::VIOLATES_CONSTRAINT;
   } else {
     return JVMFlag::SUCCESS;
@@ -105,10 +105,10 @@
 
 JVMFlag::Error MaxGCPauseMillisConstraintFuncG1(uintx value, bool verbose) {
   if (UseG1GC && FLAG_IS_CMDLINE(MaxGCPauseMillis) && (value >= GCPauseIntervalMillis)) {
-    CommandLineError::print(verbose,
-                            "MaxGCPauseMillis (" UINTX_FORMAT ") must be "
-                            "less than GCPauseIntervalMillis (" UINTX_FORMAT ")\n",
-                            value, GCPauseIntervalMillis);
+    JVMFlag::printError(verbose,
+                        "MaxGCPauseMillis (" UINTX_FORMAT ") must be "
+                        "less than GCPauseIntervalMillis (" UINTX_FORMAT ")\n",
+                        value, GCPauseIntervalMillis);
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
 
@@ -119,25 +119,25 @@
   if (UseG1GC) {
     if (FLAG_IS_CMDLINE(GCPauseIntervalMillis)) {
       if (value < 1) {
-        CommandLineError::print(verbose,
-                                "GCPauseIntervalMillis (" UINTX_FORMAT ") must be "
-                                "greater than or equal to 1\n",
-                                value);
+        JVMFlag::printError(verbose,
+                            "GCPauseIntervalMillis (" UINTX_FORMAT ") must be "
+                            "greater than or equal to 1\n",
+                            value);
         return JVMFlag::VIOLATES_CONSTRAINT;
       }
 
       if (FLAG_IS_DEFAULT(MaxGCPauseMillis)) {
-        CommandLineError::print(verbose,
-                                "GCPauseIntervalMillis cannot be set "
-                                "without setting MaxGCPauseMillis\n");
+        JVMFlag::printError(verbose,
+                            "GCPauseIntervalMillis cannot be set "
+                            "without setting MaxGCPauseMillis\n");
         return JVMFlag::VIOLATES_CONSTRAINT;
       }
 
       if (value <= MaxGCPauseMillis) {
-        CommandLineError::print(verbose,
-                                "GCPauseIntervalMillis (" UINTX_FORMAT ") must be "
-                                "greater than MaxGCPauseMillis (" UINTX_FORMAT ")\n",
-                                value, MaxGCPauseMillis);
+        JVMFlag::printError(verbose,
+                            "GCPauseIntervalMillis (" UINTX_FORMAT ") must be "
+                            "greater than MaxGCPauseMillis (" UINTX_FORMAT ")\n",
+                            value, MaxGCPauseMillis);
         return JVMFlag::VIOLATES_CONSTRAINT;
       }
     }
@@ -153,9 +153,9 @@
   // i.e. result of '(uint)(NewSize / region size(1~32MB))'
   // So maximum of NewSize should be 'max_juint * 1M'
   if (UseG1GC && (value > (max_juint * 1 * M))) {
-    CommandLineError::print(verbose,
-                            "NewSize (" SIZE_FORMAT ") must be less than ergonomic maximum value\n",
-                            value);
+    JVMFlag::printError(verbose,
+                        "NewSize (" SIZE_FORMAT ") must be less than ergonomic maximum value\n",
+                        value);
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
 #endif // _LP64
--- a/src/hotspot/share/gc/parallel/jvmFlagConstraintsParallel.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/gc/parallel/jvmFlagConstraintsParallel.cpp	Thu May 31 13:04:30 2018 -0700
@@ -23,7 +23,7 @@
  */
 
 #include "precompiled.hpp"
-#include "runtime/flags/jvmFlagRangeList.hpp"
+#include "gc/parallel/jvmFlagConstraintsParallel.hpp"
 #include "runtime/globals.hpp"
 #include "utilities/globalDefinitions.hpp"
 
@@ -32,10 +32,10 @@
   // So can't exceed with "max_jint"
 
   if (UseParallelGC && (value > (uint)max_jint)) {
-    CommandLineError::print(verbose,
-                            "ParallelGCThreads (" UINT32_FORMAT ") must be "
-                            "less than or equal to " UINT32_FORMAT " for Parallel GC\n",
-                            value, max_jint);
+    JVMFlag::printError(verbose,
+                        "ParallelGCThreads (" UINT32_FORMAT ") must be "
+                        "less than or equal to " UINT32_FORMAT " for Parallel GC\n",
+                        value, max_jint);
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
   return JVMFlag::SUCCESS;
@@ -44,10 +44,10 @@
 JVMFlag::Error InitialTenuringThresholdConstraintFuncParallel(uintx value, bool verbose) {
   // InitialTenuringThreshold is only used for ParallelGC.
   if (UseParallelGC && (value > MaxTenuringThreshold)) {
-      CommandLineError::print(verbose,
-                              "InitialTenuringThreshold (" UINTX_FORMAT ") must be "
-                              "less than or equal to MaxTenuringThreshold (" UINTX_FORMAT ")\n",
-                              value, MaxTenuringThreshold);
+      JVMFlag::printError(verbose,
+                          "InitialTenuringThreshold (" UINTX_FORMAT ") must be "
+                          "less than or equal to MaxTenuringThreshold (" UINTX_FORMAT ")\n",
+                          value, MaxTenuringThreshold);
       return JVMFlag::VIOLATES_CONSTRAINT;
   }
   return JVMFlag::SUCCESS;
@@ -57,10 +57,10 @@
   // As only ParallelGC uses InitialTenuringThreshold,
   // we don't need to compare InitialTenuringThreshold with MaxTenuringThreshold.
   if (UseParallelGC && (value < InitialTenuringThreshold)) {
-    CommandLineError::print(verbose,
-                            "MaxTenuringThreshold (" UINTX_FORMAT ") must be "
-                            "greater than or equal to InitialTenuringThreshold (" UINTX_FORMAT ")\n",
-                            value, InitialTenuringThreshold);
+    JVMFlag::printError(verbose,
+                        "MaxTenuringThreshold (" UINTX_FORMAT ") must be "
+                        "greater than or equal to InitialTenuringThreshold (" UINTX_FORMAT ")\n",
+                        value, InitialTenuringThreshold);
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
 
--- a/src/hotspot/share/gc/parallel/pcTasks.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/gc/parallel/pcTasks.cpp	Thu May 31 13:04:30 2018 -0700
@@ -104,7 +104,7 @@
       break;
 
     case system_dictionary:
-      SystemDictionary::always_strong_oops_do(&mark_and_push_closure);
+      SystemDictionary::oops_do(&mark_and_push_closure);
       break;
 
     case class_loader_data:
--- a/src/hotspot/share/gc/parallel/psCompactionManager.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/gc/parallel/psCompactionManager.cpp	Thu May 31 13:04:30 2018 -0700
@@ -200,16 +200,9 @@
       cm->mark_and_push(referent_addr);
     }
   }
-  T* next_addr = (T*)java_lang_ref_Reference::next_addr_raw(obj);
-  // Treat discovered as normal oop, if ref is not "active",
-  // i.e. if next is non-NULL.
-  T  next_oop = RawAccess<>::oop_load(next_addr);
-  if (!CompressedOops::is_null(next_oop)) { // i.e. ref is not "active"
-    T* discovered_addr = (T*)java_lang_ref_Reference::discovered_addr_raw(obj);
-    log_develop_trace(gc, ref)("   Process discovered as normal " PTR_FORMAT, p2i(discovered_addr));
-    cm->mark_and_push(discovered_addr);
-  }
-  cm->mark_and_push(next_addr);
+  // Treat discovered as normal oop.
+  T* discovered_addr = (T*)java_lang_ref_Reference::discovered_addr_raw(obj);
+  cm->mark_and_push(discovered_addr);
   klass->InstanceKlass::oop_pc_follow_contents(obj, cm);
 }
 
--- a/src/hotspot/share/gc/parallel/psMarkSweep.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/gc/parallel/psMarkSweep.cpp	Thu May 31 13:04:30 2018 -0700
@@ -521,7 +521,7 @@
     ObjectSynchronizer::oops_do(mark_and_push_closure());
     Management::oops_do(mark_and_push_closure());
     JvmtiExport::oops_do(mark_and_push_closure());
-    SystemDictionary::always_strong_oops_do(mark_and_push_closure());
+    SystemDictionary::oops_do(mark_and_push_closure());
     ClassLoaderDataGraph::always_strong_cld_do(follow_cld_closure());
     // Do not treat nmethods as strong roots for mark/sweep, since we can unload them.
     //CodeCache::scavenge_root_nmethods_do(CodeBlobToOopClosure(mark_and_push_closure()));
@@ -556,7 +556,7 @@
     GCTraceTime(Debug, gc, phases) t("Class Unloading", _gc_timer);
 
     // Unload classes and purge the SystemDictionary.
-    bool purged_class = SystemDictionary::do_unloading(is_alive_closure(), _gc_timer);
+    bool purged_class = SystemDictionary::do_unloading(_gc_timer);
 
     // Unload nmethods.
     CodeCache::do_unloading(is_alive_closure(), purged_class);
--- a/src/hotspot/share/gc/parallel/psParallelCompact.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/gc/parallel/psParallelCompact.cpp	Thu May 31 13:04:30 2018 -0700
@@ -2139,7 +2139,7 @@
     GCTraceTime(Debug, gc, phases) tm_m("Class Unloading", &_gc_timer);
 
     // Follow system dictionary roots and unload classes.
-    bool purged_class = SystemDictionary::do_unloading(is_alive_closure(), &_gc_timer);
+    bool purged_class = SystemDictionary::do_unloading(&_gc_timer);
 
     // Unload nmethods.
     CodeCache::do_unloading(is_alive_closure(), purged_class);
@@ -3081,13 +3081,10 @@
 #ifdef ASSERT
 template <class T> static void trace_reference_gc(const char *s, oop obj,
                                                   T* referent_addr,
-                                                  T* next_addr,
                                                   T* discovered_addr) {
   log_develop_trace(gc, ref)("%s obj " PTR_FORMAT, s, p2i(obj));
   log_develop_trace(gc, ref)("     referent_addr/* " PTR_FORMAT " / " PTR_FORMAT,
                              p2i(referent_addr), referent_addr ? p2i((oop)RawAccess<>::oop_load(referent_addr)) : NULL);
-  log_develop_trace(gc, ref)("     next_addr/* " PTR_FORMAT " / " PTR_FORMAT,
-                             p2i(next_addr), next_addr ? p2i((oop)RawAccess<>::oop_load(next_addr)) : NULL);
   log_develop_trace(gc, ref)("     discovered_addr/* " PTR_FORMAT " / " PTR_FORMAT,
                              p2i(discovered_addr), discovered_addr ? p2i((oop)RawAccess<>::oop_load(discovered_addr)) : NULL);
 }
@@ -3097,12 +3094,10 @@
 static void oop_pc_update_pointers_specialized(oop obj, ParCompactionManager* cm) {
   T* referent_addr = (T*)java_lang_ref_Reference::referent_addr_raw(obj);
   PSParallelCompact::adjust_pointer(referent_addr, cm);
-  T* next_addr = (T*)java_lang_ref_Reference::next_addr_raw(obj);
-  PSParallelCompact::adjust_pointer(next_addr, cm);
   T* discovered_addr = (T*)java_lang_ref_Reference::discovered_addr_raw(obj);
   PSParallelCompact::adjust_pointer(discovered_addr, cm);
   debug_only(trace_reference_gc("InstanceRefKlass::oop_update_ptrs", obj,
-                                referent_addr, next_addr, discovered_addr);)
+                                referent_addr, discovered_addr);)
 }
 
 void InstanceRefKlass::oop_pc_update_pointers(oop obj, ParCompactionManager* cm) {
--- a/src/hotspot/share/gc/parallel/psPromotionManager.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/gc/parallel/psPromotionManager.cpp	Thu May 31 13:04:30 2018 -0700
@@ -442,7 +442,7 @@
   if (PSScavenge::should_scavenge(referent_addr)) {
     ReferenceProcessor* rp = PSScavenge::reference_processor();
     if (rp->discover_reference(obj, klass->reference_type())) {
-      // reference already enqueued, referent and next will be traversed later
+      // reference discovered, referent will be traversed later.
       klass->InstanceKlass::oop_ps_push_contents(obj, pm);
       return;
     } else {
@@ -450,20 +450,10 @@
       pm->claim_or_forward_depth(referent_addr);
     }
   }
-  // Treat discovered as normal oop, if ref is not "active",
-  // i.e. if next is non-NULL.
-  T* next_addr = (T*)java_lang_ref_Reference::next_addr_raw(obj);
-  T  next_oop = RawAccess<>::oop_load(next_addr);
-  if (!CompressedOops::is_null(next_oop)) { // i.e. ref is not "active"
-    T* discovered_addr = (T*)java_lang_ref_Reference::discovered_addr_raw(obj);
-    log_develop_trace(gc, ref)("   Process discovered as normal " PTR_FORMAT, p2i(discovered_addr));
-    if (PSScavenge::should_scavenge(discovered_addr)) {
-      pm->claim_or_forward_depth(discovered_addr);
-    }
-  }
-  // Treat next as normal oop;  next is a link in the reference queue.
-  if (PSScavenge::should_scavenge(next_addr)) {
-    pm->claim_or_forward_depth(next_addr);
+  // Treat discovered as normal oop
+  T* discovered_addr = (T*)java_lang_ref_Reference::discovered_addr_raw(obj);
+  if (PSScavenge::should_scavenge(discovered_addr)) {
+    pm->claim_or_forward_depth(discovered_addr);
   }
   klass->InstanceKlass::oop_ps_push_contents(obj, pm);
 }
--- a/src/hotspot/share/gc/serial/genMarkSweep.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/gc/serial/genMarkSweep.cpp	Thu May 31 13:04:30 2018 -0700
@@ -228,7 +228,7 @@
     GCTraceTime(Debug, gc, phases) tm_m("Class Unloading", gc_timer());
 
     // Unload classes and purge the SystemDictionary.
-    bool purged_class = SystemDictionary::do_unloading(&is_alive, gc_timer());
+    bool purged_class = SystemDictionary::do_unloading(gc_timer());
 
     // Unload nmethods.
     CodeCache::do_unloading(&is_alive, purged_class);
--- a/src/hotspot/share/gc/shared/genCollectedHeap.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/gc/shared/genCollectedHeap.cpp	Thu May 31 13:04:30 2018 -0700
@@ -783,7 +783,6 @@
 void GenCollectedHeap::process_roots(StrongRootsScope* scope,
                                      ScanningOption so,
                                      OopClosure* strong_roots,
-                                     OopClosure* weak_roots,
                                      CLDClosure* strong_cld_closure,
                                      CLDClosure* weak_cld_closure,
                                      CodeBlobToOopClosure* code_roots) {
@@ -827,7 +826,7 @@
   }
 
   if (!_process_strong_tasks->is_task_claimed(GCH_PS_SystemDictionary_oops_do)) {
-    SystemDictionary::roots_oops_do(strong_roots, weak_roots);
+    SystemDictionary::oops_do(strong_roots);
   }
 
   if (!_process_strong_tasks->is_task_claimed(GCH_PS_CodeCache_oops_do)) {
@@ -869,7 +868,7 @@
                                            CLDClosure* cld_closure) {
   MarkingCodeBlobClosure mark_code_closure(root_closure, CodeBlobToOopClosure::FixRelocations);
 
-  process_roots(scope, SO_ScavengeCodeCache, root_closure, root_closure,
+  process_roots(scope, SO_ScavengeCodeCache, root_closure,
                 cld_closure, cld_closure, &mark_code_closure);
   process_string_table_roots(scope, root_closure);
 
@@ -893,10 +892,9 @@
                                           OopsInGenClosure* root_closure,
                                           CLDClosure* cld_closure) {
   MarkingCodeBlobClosure mark_code_closure(root_closure, is_adjust_phase);
-  OopsInGenClosure* weak_roots = only_strong_roots ? NULL : root_closure;
   CLDClosure* weak_cld_closure = only_strong_roots ? NULL : cld_closure;
 
-  process_roots(scope, so, root_closure, weak_roots, cld_closure, weak_cld_closure, &mark_code_closure);
+  process_roots(scope, so, root_closure, cld_closure, weak_cld_closure, &mark_code_closure);
   if (is_adjust_phase) {
     // We never treat the string table as roots during marking
     // for the full gc, so we only need to process it during
--- a/src/hotspot/share/gc/shared/genCollectedHeap.hpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/gc/shared/genCollectedHeap.hpp	Thu May 31 13:04:30 2018 -0700
@@ -396,7 +396,6 @@
   void process_roots(StrongRootsScope* scope,
                      ScanningOption so,
                      OopClosure* strong_roots,
-                     OopClosure* weak_roots,
                      CLDClosure* strong_cld_closure,
                      CLDClosure* weak_cld_closure,
                      CodeBlobToOopClosure* code_roots);
--- a/src/hotspot/share/gc/shared/jvmFlagConstraintsGC.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/gc/shared/jvmFlagConstraintsGC.cpp	Thu May 31 13:04:30 2018 -0700
@@ -30,12 +30,10 @@
 #include "gc/shared/plab.hpp"
 #include "gc/shared/threadLocalAllocBuffer.hpp"
 #include "runtime/arguments.hpp"
-#include "runtime/flags/jvmFlagRangeList.hpp"
 #include "runtime/globals.hpp"
 #include "runtime/globals_extension.hpp"
 #include "runtime/thread.inline.hpp"
 #include "utilities/align.hpp"
-#include "utilities/defaultStream.hpp"
 #include "utilities/macros.hpp"
 #if INCLUDE_CMSGC
 #include "gc/cms/jvmFlagConstraintsCMS.hpp"
@@ -88,10 +86,10 @@
   // CMS and G1 GCs use ConcGCThreads.
   if ((GCConfig::is_gc_selected(CollectedHeap::CMS) ||
        GCConfig::is_gc_selected(CollectedHeap::G1)) && (value > ParallelGCThreads)) {
-    CommandLineError::print(verbose,
-                            "ConcGCThreads (" UINT32_FORMAT ") must be "
-                            "less than or equal to ParallelGCThreads (" UINT32_FORMAT ")\n",
-                            value, ParallelGCThreads);
+    JVMFlag::printError(verbose,
+                        "ConcGCThreads (" UINT32_FORMAT ") must be "
+                        "less than or equal to ParallelGCThreads (" UINT32_FORMAT ")\n",
+                        value, ParallelGCThreads);
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
 
@@ -102,10 +100,10 @@
   if ((GCConfig::is_gc_selected(CollectedHeap::CMS) ||
        GCConfig::is_gc_selected(CollectedHeap::G1)  ||
        GCConfig::is_gc_selected(CollectedHeap::Parallel)) && (value < PLAB::min_size())) {
-    CommandLineError::print(verbose,
-                            "%s (" SIZE_FORMAT ") must be "
-                            "greater than or equal to ergonomic PLAB minimum size (" SIZE_FORMAT ")\n",
-                            name, value, PLAB::min_size());
+    JVMFlag::printError(verbose,
+                        "%s (" SIZE_FORMAT ") must be "
+                        "greater than or equal to ergonomic PLAB minimum size (" SIZE_FORMAT ")\n",
+                        name, value, PLAB::min_size());
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
 
@@ -116,10 +114,10 @@
   if ((GCConfig::is_gc_selected(CollectedHeap::CMS) ||
        GCConfig::is_gc_selected(CollectedHeap::G1)  ||
        GCConfig::is_gc_selected(CollectedHeap::Parallel)) && (value > PLAB::max_size())) {
-    CommandLineError::print(verbose,
-                            "%s (" SIZE_FORMAT ") must be "
-                            "less than or equal to ergonomic PLAB maximum size (" SIZE_FORMAT ")\n",
-                            name, value, PLAB::max_size());
+    JVMFlag::printError(verbose,
+                        "%s (" SIZE_FORMAT ") must be "
+                        "less than or equal to ergonomic PLAB maximum size (" SIZE_FORMAT ")\n",
+                        name, value, PLAB::max_size());
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
 
@@ -156,10 +154,10 @@
 
 JVMFlag::Error MinHeapFreeRatioConstraintFunc(uintx value, bool verbose) {
   if (value > MaxHeapFreeRatio) {
-    CommandLineError::print(verbose,
-                            "MinHeapFreeRatio (" UINTX_FORMAT ") must be "
-                            "less than or equal to MaxHeapFreeRatio (" UINTX_FORMAT ")\n",
-                            value, MaxHeapFreeRatio);
+    JVMFlag::printError(verbose,
+                        "MinHeapFreeRatio (" UINTX_FORMAT ") must be "
+                        "less than or equal to MaxHeapFreeRatio (" UINTX_FORMAT ")\n",
+                        value, MaxHeapFreeRatio);
     return JVMFlag::VIOLATES_CONSTRAINT;
   } else {
     return JVMFlag::SUCCESS;
@@ -168,10 +166,10 @@
 
 JVMFlag::Error MaxHeapFreeRatioConstraintFunc(uintx value, bool verbose) {
   if (value < MinHeapFreeRatio) {
-    CommandLineError::print(verbose,
-                            "MaxHeapFreeRatio (" UINTX_FORMAT ") must be "
-                            "greater than or equal to MinHeapFreeRatio (" UINTX_FORMAT ")\n",
-                            value, MinHeapFreeRatio);
+    JVMFlag::printError(verbose,
+                        "MaxHeapFreeRatio (" UINTX_FORMAT ") must be "
+                        "greater than or equal to MinHeapFreeRatio (" UINTX_FORMAT ")\n",
+                        value, MinHeapFreeRatio);
     return JVMFlag::VIOLATES_CONSTRAINT;
   } else {
     return JVMFlag::SUCCESS;
@@ -180,11 +178,11 @@
 
 static JVMFlag::Error CheckMaxHeapSizeAndSoftRefLRUPolicyMSPerMB(size_t maxHeap, intx softRef, bool verbose) {
   if ((softRef > 0) && ((maxHeap / M) > (max_uintx / softRef))) {
-    CommandLineError::print(verbose,
-                            "Desired lifetime of SoftReferences cannot be expressed correctly. "
-                            "MaxHeapSize (" SIZE_FORMAT ") or SoftRefLRUPolicyMSPerMB "
-                            "(" INTX_FORMAT ") is too large\n",
-                            maxHeap, softRef);
+    JVMFlag::printError(verbose,
+                        "Desired lifetime of SoftReferences cannot be expressed correctly. "
+                        "MaxHeapSize (" SIZE_FORMAT ") or SoftRefLRUPolicyMSPerMB "
+                        "(" INTX_FORMAT ") is too large\n",
+                        maxHeap, softRef);
     return JVMFlag::VIOLATES_CONSTRAINT;
   } else {
     return JVMFlag::SUCCESS;
@@ -197,10 +195,10 @@
 
 JVMFlag::Error MarkStackSizeConstraintFunc(size_t value, bool verbose) {
   if (value > MarkStackSizeMax) {
-    CommandLineError::print(verbose,
-                            "MarkStackSize (" SIZE_FORMAT ") must be "
-                            "less than or equal to MarkStackSizeMax (" SIZE_FORMAT ")\n",
-                            value, MarkStackSizeMax);
+    JVMFlag::printError(verbose,
+                        "MarkStackSize (" SIZE_FORMAT ") must be "
+                        "less than or equal to MarkStackSizeMax (" SIZE_FORMAT ")\n",
+                        value, MarkStackSizeMax);
     return JVMFlag::VIOLATES_CONSTRAINT;
   } else {
     return JVMFlag::SUCCESS;
@@ -209,10 +207,10 @@
 
 JVMFlag::Error MinMetaspaceFreeRatioConstraintFunc(uintx value, bool verbose) {
   if (value > MaxMetaspaceFreeRatio) {
-    CommandLineError::print(verbose,
-                            "MinMetaspaceFreeRatio (" UINTX_FORMAT ") must be "
-                            "less than or equal to MaxMetaspaceFreeRatio (" UINTX_FORMAT ")\n",
-                            value, MaxMetaspaceFreeRatio);
+    JVMFlag::printError(verbose,
+                        "MinMetaspaceFreeRatio (" UINTX_FORMAT ") must be "
+                        "less than or equal to MaxMetaspaceFreeRatio (" UINTX_FORMAT ")\n",
+                        value, MaxMetaspaceFreeRatio);
     return JVMFlag::VIOLATES_CONSTRAINT;
   } else {
     return JVMFlag::SUCCESS;
@@ -221,10 +219,10 @@
 
 JVMFlag::Error MaxMetaspaceFreeRatioConstraintFunc(uintx value, bool verbose) {
   if (value < MinMetaspaceFreeRatio) {
-    CommandLineError::print(verbose,
-                            "MaxMetaspaceFreeRatio (" UINTX_FORMAT ") must be "
-                            "greater than or equal to MinMetaspaceFreeRatio (" UINTX_FORMAT ")\n",
-                            value, MinMetaspaceFreeRatio);
+    JVMFlag::printError(verbose,
+                        "MaxMetaspaceFreeRatio (" UINTX_FORMAT ") must be "
+                        "greater than or equal to MinMetaspaceFreeRatio (" UINTX_FORMAT ")\n",
+                        value, MinMetaspaceFreeRatio);
     return JVMFlag::VIOLATES_CONSTRAINT;
   } else {
     return JVMFlag::SUCCESS;
@@ -252,12 +250,12 @@
 
   // MaxTenuringThreshold=0 means NeverTenure=false && AlwaysTenure=true
   if ((value == 0) && (NeverTenure || !AlwaysTenure)) {
-    CommandLineError::print(verbose,
-                            "MaxTenuringThreshold (0) should match to NeverTenure=false "
-                            "&& AlwaysTenure=true. But we have NeverTenure=%s "
-                            "AlwaysTenure=%s\n",
-                            NeverTenure ? "true" : "false",
-                            AlwaysTenure ? "true" : "false");
+    JVMFlag::printError(verbose,
+                        "MaxTenuringThreshold (0) should match to NeverTenure=false "
+                        "&& AlwaysTenure=true. But we have NeverTenure=%s "
+                        "AlwaysTenure=%s\n",
+                        NeverTenure ? "true" : "false",
+                        AlwaysTenure ? "true" : "false");
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
   return JVMFlag::SUCCESS;
@@ -288,10 +286,10 @@
 JVMFlag::Error InitialBootClassLoaderMetaspaceSizeConstraintFunc(size_t value, bool verbose) {
   size_t aligned_max = align_down(max_uintx/2, Metaspace::reserve_alignment_words());
   if (value > aligned_max) {
-    CommandLineError::print(verbose,
-                            "InitialBootClassLoaderMetaspaceSize (" SIZE_FORMAT ") must be "
-                            "less than or equal to aligned maximum value (" SIZE_FORMAT ")\n",
-                            value, aligned_max);
+    JVMFlag::printError(verbose,
+                        "InitialBootClassLoaderMetaspaceSize (" SIZE_FORMAT ") must be "
+                        "less than or equal to aligned maximum value (" SIZE_FORMAT ")\n",
+                        value, aligned_max);
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
   return JVMFlag::SUCCESS;
@@ -301,10 +299,10 @@
 static JVMFlag::Error MaxSizeForAlignment(const char* name, size_t value, size_t alignment, bool verbose) {
   size_t aligned_max = ((max_uintx - alignment) & ~(alignment-1));
   if (value > aligned_max) {
-    CommandLineError::print(verbose,
-                            "%s (" SIZE_FORMAT ") must be "
-                            "less than or equal to aligned maximum value (" SIZE_FORMAT ")\n",
-                            name, value, aligned_max);
+    JVMFlag::printError(verbose,
+                        "%s (" SIZE_FORMAT ") must be "
+                        "less than or equal to aligned maximum value (" SIZE_FORMAT ")\n",
+                        name, value, aligned_max);
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
   return JVMFlag::SUCCESS;
@@ -343,10 +341,10 @@
   // If an overflow happened in Arguments::set_heap_size(), MaxHeapSize will have too large a value.
   // Check for this by ensuring that MaxHeapSize plus the requested min base address still fit within max_uintx.
   if (UseCompressedOops && FLAG_IS_ERGO(MaxHeapSize) && (value > (max_uintx - MaxHeapSize))) {
-    CommandLineError::print(verbose,
-                            "HeapBaseMinAddress (" SIZE_FORMAT ") or MaxHeapSize (" SIZE_FORMAT ") is too large. "
-                            "Sum of them must be less than or equal to maximum of size_t (" SIZE_FORMAT ")\n",
-                            value, MaxHeapSize, max_uintx);
+    JVMFlag::printError(verbose,
+                        "HeapBaseMinAddress (" SIZE_FORMAT ") or MaxHeapSize (" SIZE_FORMAT ") is too large. "
+                        "Sum of them must be less than or equal to maximum of size_t (" SIZE_FORMAT ")\n",
+                        value, MaxHeapSize, max_uintx);
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
 
@@ -367,17 +365,17 @@
 JVMFlag::Error MinTLABSizeConstraintFunc(size_t value, bool verbose) {
   // At least, alignment reserve area is needed.
   if (value < ThreadLocalAllocBuffer::alignment_reserve_in_bytes()) {
-    CommandLineError::print(verbose,
-                            "MinTLABSize (" SIZE_FORMAT ") must be "
-                            "greater than or equal to reserved area in TLAB (" SIZE_FORMAT ")\n",
-                            value, ThreadLocalAllocBuffer::alignment_reserve_in_bytes());
+    JVMFlag::printError(verbose,
+                        "MinTLABSize (" SIZE_FORMAT ") must be "
+                        "greater than or equal to reserved area in TLAB (" SIZE_FORMAT ")\n",
+                        value, ThreadLocalAllocBuffer::alignment_reserve_in_bytes());
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
   if (value > (ThreadLocalAllocBuffer::max_size() * HeapWordSize)) {
-    CommandLineError::print(verbose,
-                            "MinTLABSize (" SIZE_FORMAT ") must be "
-                            "less than or equal to ergonomic TLAB maximum (" SIZE_FORMAT ")\n",
-                            value, ThreadLocalAllocBuffer::max_size() * HeapWordSize);
+    JVMFlag::printError(verbose,
+                        "MinTLABSize (" SIZE_FORMAT ") must be "
+                        "less than or equal to ergonomic TLAB maximum (" SIZE_FORMAT ")\n",
+                        value, ThreadLocalAllocBuffer::max_size() * HeapWordSize);
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
   return JVMFlag::SUCCESS;
@@ -387,17 +385,17 @@
   // Skip for default value of zero which means set ergonomically.
   if (FLAG_IS_CMDLINE(TLABSize)) {
     if (value < MinTLABSize) {
-      CommandLineError::print(verbose,
-                              "TLABSize (" SIZE_FORMAT ") must be "
-                              "greater than or equal to MinTLABSize (" SIZE_FORMAT ")\n",
-                              value, MinTLABSize);
+      JVMFlag::printError(verbose,
+                          "TLABSize (" SIZE_FORMAT ") must be "
+                          "greater than or equal to MinTLABSize (" SIZE_FORMAT ")\n",
+                          value, MinTLABSize);
       return JVMFlag::VIOLATES_CONSTRAINT;
     }
     if (value > (ThreadLocalAllocBuffer::max_size() * HeapWordSize)) {
-      CommandLineError::print(verbose,
-                              "TLABSize (" SIZE_FORMAT ") must be "
-                              "less than or equal to ergonomic TLAB maximum size (" SIZE_FORMAT ")\n",
-                              value, (ThreadLocalAllocBuffer::max_size() * HeapWordSize));
+      JVMFlag::printError(verbose,
+                          "TLABSize (" SIZE_FORMAT ") must be "
+                          "less than or equal to ergonomic TLAB maximum size (" SIZE_FORMAT ")\n",
+                          value, (ThreadLocalAllocBuffer::max_size() * HeapWordSize));
       return JVMFlag::VIOLATES_CONSTRAINT;
     }
   }
@@ -412,10 +410,10 @@
 
     // Compare with 'max_uintx' as ThreadLocalAllocBuffer::_refill_waste_limit is 'size_t'.
     if (refill_waste_limit > (max_uintx - value)) {
-      CommandLineError::print(verbose,
-                              "TLABWasteIncrement (" UINTX_FORMAT ") must be "
-                              "less than or equal to ergonomic TLAB waste increment maximum size(" SIZE_FORMAT ")\n",
-                              value, (max_uintx - refill_waste_limit));
+      JVMFlag::printError(verbose,
+                          "TLABWasteIncrement (" UINTX_FORMAT ") must be "
+                          "less than or equal to ergonomic TLAB waste increment maximum size(" SIZE_FORMAT ")\n",
+                          value, (max_uintx - refill_waste_limit));
       return JVMFlag::VIOLATES_CONSTRAINT;
     }
   }
@@ -425,11 +423,11 @@
 JVMFlag::Error SurvivorRatioConstraintFunc(uintx value, bool verbose) {
   if (FLAG_IS_CMDLINE(SurvivorRatio) &&
       (value > (MaxHeapSize / Universe::heap()->collector_policy()->space_alignment()))) {
-    CommandLineError::print(verbose,
-                            "SurvivorRatio (" UINTX_FORMAT ") must be "
-                            "less than or equal to ergonomic SurvivorRatio maximum (" SIZE_FORMAT ")\n",
-                            value,
-                            (MaxHeapSize / Universe::heap()->collector_policy()->space_alignment()));
+    JVMFlag::printError(verbose,
+                        "SurvivorRatio (" UINTX_FORMAT ") must be "
+                        "less than or equal to ergonomic SurvivorRatio maximum (" SIZE_FORMAT ")\n",
+                        value,
+                        (MaxHeapSize / Universe::heap()->collector_policy()->space_alignment()));
     return JVMFlag::VIOLATES_CONSTRAINT;
   } else {
     return JVMFlag::SUCCESS;
@@ -438,10 +436,10 @@
 
 JVMFlag::Error MetaspaceSizeConstraintFunc(size_t value, bool verbose) {
   if (value > MaxMetaspaceSize) {
-    CommandLineError::print(verbose,
-                            "MetaspaceSize (" SIZE_FORMAT ") must be "
-                            "less than or equal to MaxMetaspaceSize (" SIZE_FORMAT ")\n",
-                            value, MaxMetaspaceSize);
+    JVMFlag::printError(verbose,
+                        "MetaspaceSize (" SIZE_FORMAT ") must be "
+                        "less than or equal to MaxMetaspaceSize (" SIZE_FORMAT ")\n",
+                        value, MaxMetaspaceSize);
     return JVMFlag::VIOLATES_CONSTRAINT;
   } else {
     return JVMFlag::SUCCESS;
@@ -450,10 +448,10 @@
 
 JVMFlag::Error MaxMetaspaceSizeConstraintFunc(size_t value, bool verbose) {
   if (value < MetaspaceSize) {
-    CommandLineError::print(verbose,
-                            "MaxMetaspaceSize (" SIZE_FORMAT ") must be "
-                            "greater than or equal to MetaspaceSize (" SIZE_FORMAT ")\n",
-                            value, MaxMetaspaceSize);
+    JVMFlag::printError(verbose,
+                        "MaxMetaspaceSize (" SIZE_FORMAT ") must be "
+                        "greater than or equal to MetaspaceSize (" SIZE_FORMAT ")\n",
+                        value, MaxMetaspaceSize);
     return JVMFlag::VIOLATES_CONSTRAINT;
   } else {
     return JVMFlag::SUCCESS;
@@ -463,17 +461,17 @@
 JVMFlag::Error SurvivorAlignmentInBytesConstraintFunc(intx value, bool verbose) {
   if (value != 0) {
     if (!is_power_of_2(value)) {
-      CommandLineError::print(verbose,
-                              "SurvivorAlignmentInBytes (" INTX_FORMAT ") must be "
-                              "power of 2\n",
-                              value);
+      JVMFlag::printError(verbose,
+                          "SurvivorAlignmentInBytes (" INTX_FORMAT ") must be "
+                          "power of 2\n",
+                          value);
       return JVMFlag::VIOLATES_CONSTRAINT;
     }
     if (value < ObjectAlignmentInBytes) {
-      CommandLineError::print(verbose,
-                              "SurvivorAlignmentInBytes (" INTX_FORMAT ") must be "
-                              "greater than or equal to ObjectAlignmentInBytes (" INTX_FORMAT ")\n",
-                              value, ObjectAlignmentInBytes);
+      JVMFlag::printError(verbose,
+                          "SurvivorAlignmentInBytes (" INTX_FORMAT ") must be "
+                          "greater than or equal to ObjectAlignmentInBytes (" INTX_FORMAT ")\n",
+                          value, ObjectAlignmentInBytes);
       return JVMFlag::VIOLATES_CONSTRAINT;
     }
   }
--- a/src/hotspot/share/gc/shared/oopStorage.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/gc/shared/oopStorage.cpp	Thu May 31 13:04:30 2018 -0700
@@ -907,7 +907,8 @@
 // Parallel iteration support
 
 uint OopStorage::BasicParState::default_estimated_thread_count(bool concurrent) {
-  return concurrent ? ConcGCThreads : ParallelGCThreads;
+  uint configured = concurrent ? ConcGCThreads : ParallelGCThreads;
+  return MAX2(1u, configured);  // Never estimate zero threads.
 }
 
 OopStorage::BasicParState::BasicParState(const OopStorage* storage,
--- a/src/hotspot/share/gc/shared/referenceProcessor.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/gc/shared/referenceProcessor.cpp	Thu May 31 13:04:30 2018 -0700
@@ -303,9 +303,6 @@
 }
 
 void DiscoveredListIterator::enqueue() {
-  // Self-loop next, so as to make Ref not active.
-  java_lang_ref_Reference::set_next_raw(_current_discovered, _current_discovered);
-
   HeapAccess<AS_NO_KEEPALIVE>::oop_store_at(_current_discovered,
                                             java_lang_ref_Reference::discovered_offset,
                                             _next_discovered);
@@ -364,38 +361,35 @@
                              iter.removed(), iter.processed(), p2i(&refs_list));
 }
 
+inline void log_dropped_ref(const DiscoveredListIterator& iter, const char* reason) {
+  log_develop_trace(gc, ref)("Dropping %s reference " PTR_FORMAT ": %s",
+                             reason, p2i(iter.obj()),
+                             iter.obj()->klass()->internal_name());
+}
+
+// Traverse the list and remove any Refs whose referents are alive,
+// or NULL if discovery is not atomic.
 void ReferenceProcessor::process_phase2(DiscoveredList&    refs_list,
                                         BoolObjectClosure* is_alive,
                                         OopClosure*        keep_alive,
                                         VoidClosure*       complete_gc) {
-  if (discovery_is_atomic()) {
-    // complete_gc is ignored in this case for this phase
-    pp2_work(refs_list, is_alive, keep_alive);
-  } else {
-    assert(complete_gc != NULL, "Error");
-    pp2_work_concurrent_discovery(refs_list, is_alive,
-                                  keep_alive, complete_gc);
-  }
-}
-// Traverse the list and remove any Refs that are not active, or
-// whose referents are either alive or NULL.
-void
-ReferenceProcessor::pp2_work(DiscoveredList&    refs_list,
-                             BoolObjectClosure* is_alive,
-                             OopClosure*        keep_alive) {
-  assert(discovery_is_atomic(), "Error");
+  // complete_gc is unused.
   DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
   while (iter.has_next()) {
-    iter.load_ptrs(DEBUG_ONLY(false /* allow_null_referent */));
-    DEBUG_ONLY(oop next = java_lang_ref_Reference::next(iter.obj());)
-    assert(next == NULL, "Should not discover inactive Reference");
-    if (iter.is_referent_alive()) {
-      log_develop_trace(gc, ref)("Dropping strongly reachable reference (" INTPTR_FORMAT ": %s)",
-                                 p2i(iter.obj()), iter.obj()->klass()->internal_name());
+    iter.load_ptrs(DEBUG_ONLY(!discovery_is_atomic() /* allow_null_referent */));
+    if (iter.referent() == NULL) {
+      // Reference has been cleared since discovery; only possible if
+      // discovery is not atomic (checked by load_ptrs).  Remove
+      // reference from list.
+      log_dropped_ref(iter, "cleared");
+      iter.remove();
+      iter.move_to_next();
+    } else if (iter.is_referent_alive()) {
       // The referent is reachable after all.
-      // Remove Reference object from list.
+      // Remove reference from list.
+      log_dropped_ref(iter, "reachable");
       iter.remove();
-      // Update the referent pointer as necessary: Note that this
+      // Update the referent pointer as necessary.  Note that this
       // should not entail any recursive marking because the
       // referent must already have been traversed.
       iter.make_referent_alive();
@@ -413,45 +407,6 @@
   )
 }
 
-void
-ReferenceProcessor::pp2_work_concurrent_discovery(DiscoveredList&    refs_list,
-                                                  BoolObjectClosure* is_alive,
-                                                  OopClosure*        keep_alive,
-                                                  VoidClosure*       complete_gc) {
-  assert(!discovery_is_atomic(), "Error");
-  DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
-  while (iter.has_next()) {
-    iter.load_ptrs(DEBUG_ONLY(true /* allow_null_referent */));
-    HeapWord* next_addr = java_lang_ref_Reference::next_addr_raw(iter.obj());
-    oop next = java_lang_ref_Reference::next(iter.obj());
-    if ((iter.referent() == NULL || iter.is_referent_alive() ||
-         next != NULL)) {
-      assert(oopDesc::is_oop_or_null(next), "Expected an oop or NULL for next field at " PTR_FORMAT, p2i(next));
-      // Remove Reference object from list
-      iter.remove();
-      // Trace the cohorts
-      iter.make_referent_alive();
-      if (UseCompressedOops) {
-        keep_alive->do_oop((narrowOop*)next_addr);
-      } else {
-        keep_alive->do_oop((oop*)next_addr);
-      }
-      iter.move_to_next();
-    } else {
-      iter.next();
-    }
-  }
-  // Now close the newly reachable set
-  complete_gc->do_void();
-  NOT_PRODUCT(
-    if (iter.processed() > 0) {
-      log_develop_trace(gc, ref)(" Dropped " SIZE_FORMAT " active Refs out of " SIZE_FORMAT
-        " Refs in discovered list " INTPTR_FORMAT,
-        iter.removed(), iter.processed(), p2i(&refs_list));
-    }
-  )
-}
-
 void ReferenceProcessor::process_phase3(DiscoveredList&    refs_list,
                                         bool               clear_referent,
                                         BoolObjectClosure* is_alive,
@@ -465,8 +420,12 @@
       // NULL out referent pointer
       iter.clear_referent();
     } else {
-      // keep the referent around
+      // Current reference is a FinalReference; that's the only kind we
+      // don't clear the referent, instead keeping it for calling finalize.
       iter.make_referent_alive();
+      // Self-loop next, to mark it not active.
+      assert(java_lang_ref_Reference::next(iter.obj()) == NULL, "enqueued FinalReference");
+      java_lang_ref_Reference::set_next_raw(iter.obj(), iter.obj());
     }
     iter.enqueue();
     log_develop_trace(gc, ref)("Adding %sreference (" INTPTR_FORMAT ": %s) as pending",
@@ -913,9 +872,9 @@
   if (!_discovering_refs || !RegisterReferences) {
     return false;
   }
-  // We only discover active references.
-  oop next = java_lang_ref_Reference::next(obj);
-  if (next != NULL) {   // Ref is no longer active
+
+  if ((rt == REF_FINAL) && (java_lang_ref_Reference::next(obj) != NULL)) {
+    // Don't rediscover non-active FinalReferences.
     return false;
   }
 
@@ -1121,24 +1080,15 @@
       return true;
     }
     iter.load_ptrs(DEBUG_ONLY(true /* allow_null_referent */));
-    oop obj = iter.obj();
-    oop next = java_lang_ref_Reference::next(obj);
-    if (iter.referent() == NULL || iter.is_referent_alive() || next != NULL) {
-      // The referent has been cleared, or is alive, or the Reference is not
-      // active; we need to trace and mark its cohort.
+    if (iter.referent() == NULL || iter.is_referent_alive()) {
+      // The referent has been cleared, or is alive; we need to trace
+      // and mark its cohort.
       log_develop_trace(gc, ref)("Precleaning Reference (" INTPTR_FORMAT ": %s)",
                                  p2i(iter.obj()), iter.obj()->klass()->internal_name());
       // Remove Reference object from list
       iter.remove();
       // Keep alive its cohort.
       iter.make_referent_alive();
-      if (UseCompressedOops) {
-        narrowOop* next_addr = (narrowOop*)java_lang_ref_Reference::next_addr_raw(obj);
-        keep_alive->do_oop(next_addr);
-      } else {
-        oop* next_addr = (oop*)java_lang_ref_Reference::next_addr_raw(obj);
-        keep_alive->do_oop(next_addr);
-      }
       iter.move_to_next();
     } else {
       iter.next();
--- a/src/hotspot/share/gc/shared/referenceProcessor.hpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/gc/shared/referenceProcessor.hpp	Thu May 31 13:04:30 2018 -0700
@@ -262,15 +262,6 @@
                       BoolObjectClosure* is_alive,
                       OopClosure*        keep_alive,
                       VoidClosure*       complete_gc);
-  // Work methods in support of process_phase2
-  void pp2_work(DiscoveredList&    refs_list,
-                BoolObjectClosure* is_alive,
-                OopClosure*        keep_alive);
-  void pp2_work_concurrent_discovery(
-                DiscoveredList&    refs_list,
-                BoolObjectClosure* is_alive,
-                OopClosure*        keep_alive,
-                VoidClosure*       complete_gc);
   // Phase3: process the referents by either clearing them
   // or keeping them alive (and their closure), and enqueuing them.
   void process_phase3(DiscoveredList&    refs_list,
--- a/src/hotspot/share/gc/shared/weakProcessor.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/gc/shared/weakProcessor.cpp	Thu May 31 13:04:30 2018 -0700
@@ -23,6 +23,8 @@
  */
 
 #include "precompiled.hpp"
+#include "classfile/systemDictionary.hpp"
+#include "gc/shared/oopStorage.inline.hpp"
 #include "gc/shared/weakProcessor.hpp"
 #include "prims/jvmtiExport.hpp"
 #include "runtime/jniHandles.hpp"
@@ -34,6 +36,7 @@
 void WeakProcessor::weak_oops_do(BoolObjectClosure* is_alive, OopClosure* keep_alive) {
   JNIHandles::weak_oops_do(is_alive, keep_alive);
   JvmtiExport::weak_oops_do(is_alive, keep_alive);
+  SystemDictionary::vm_weak_oop_storage()->weak_oops_do(is_alive, keep_alive);
   JFR_ONLY(Jfr::weak_oops_do(is_alive, keep_alive);)
 }
 
--- a/src/hotspot/share/interpreter/bytecodeInterpreterProfiling.hpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/interpreter/bytecodeInterpreterProfiling.hpp	Thu May 31 13:04:30 2018 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved.
  * Copyright (c) 2012, 2014 SAP SE. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -30,25 +30,10 @@
 #ifndef SHARE_VM_INTERPRETER_BYTECODEINTERPRETERPROFILING_HPP
 #define SHARE_VM_INTERPRETER_BYTECODEINTERPRETERPROFILING_HPP
 
-
-// Global settings /////////////////////////////////////////////////////////////
-
-
-// Enables profiling support.
-#if defined(COMPILER2)
-#define CC_INTERP_PROFILE
-#endif
-
-// Enables assertions for profiling code (also works in product-builds).
-// #define CC_INTERP_PROFILE_WITH_ASSERTIONS
-
-
 #ifdef CC_INTERP
 
 // Empty dummy implementations if profiling code is switched off. //////////////
 
-#ifndef CC_INTERP_PROFILE
-
 #define SET_MDX(mdx)
 
 #define BI_PROFILE_GET_OR_CREATE_METHOD_DATA(exception_handler)                \
@@ -69,240 +54,6 @@
 #define BI_PROFILE_UPDATE_VIRTUALCALL(receiver)
 #define BI_PROFILE_UPDATE_SWITCH(switch_index)
 
-
-#else
-
-
-// Non-dummy implementations ///////////////////////////////////////////////////
-
-// Accessors for the current method data pointer 'mdx'.
-#define MDX()        (istate->mdx())
-#define SET_MDX(mdx)                                                           \
-  if (TraceProfileInterpreter) {                                               \
-    /* Let it look like TraceBytecodes' format. */                             \
-    tty->print_cr("[%d]           %4d  "                                       \
-                  "mdx " PTR_FORMAT "(%d)"                                     \
-                  "  "                                                         \
-                  " \t-> " PTR_FORMAT "(%d)",                                  \
-                (int) THREAD->osthread()->thread_id(),                         \
-                BCI(),                                                         \
-                p2i(MDX()),                                                    \
-                (MDX() == NULL                                                 \
-                 ? 0                                                           \
-                 : istate->method()->method_data()->dp_to_di((address)MDX())), \
-                p2i(mdx),                                                      \
-                istate->method()->method_data()->dp_to_di((address)mdx)        \
-                );                                                             \
-  };                                                                           \
-  istate->set_mdx(mdx);
-
-
-// Dumps the profiling method data for the current method.
-#ifdef PRODUCT
-#define BI_PROFILE_PRINT_METHOD_DATA()
-#else  // PRODUCT
-#define BI_PROFILE_PRINT_METHOD_DATA()                                         \
-  {                                                                            \
-    ttyLocker ttyl;                                                            \
-    MethodData *md = istate->method()->method_data();                          \
-    tty->cr();                                                                 \
-    tty->print("method data at mdx " PTR_FORMAT "(0) for",                     \
-               p2i(md->data_layout_at(md->bci_to_di(0))));                     \
-    istate->method()->print_short_name(tty);                                   \
-    tty->cr();                                                                 \
-    if (md != NULL) {                                                          \
-      md->print_data_on(tty);                                                  \
-      address mdx = (address) MDX();                                           \
-      if (mdx != NULL) {                                                       \
-        tty->print_cr("current mdx " PTR_FORMAT "(%d)",                        \
-                      p2i(mdx),                                                \
-                      istate->method()->method_data()->dp_to_di(mdx));         \
-      }                                                                        \
-    } else {                                                                   \
-      tty->print_cr("no method data");                                         \
-    }                                                                          \
-  }
-#endif // PRODUCT
-
-
-// Gets or creates the profiling method data and initializes mdx.
-#define BI_PROFILE_GET_OR_CREATE_METHOD_DATA(exception_handler)                \
-  if (ProfileInterpreter && MDX() == NULL) {                                   \
-    /* Mdx is not yet initialized for this activation. */                      \
-    MethodData *md = istate->method()->method_data();                          \
-    if (md == NULL) {                                                          \
-      MethodCounters* mcs;                                                     \
-      GET_METHOD_COUNTERS(mcs);                                                \
-      /* The profiling method data doesn't exist for this method, */           \
-      /* create it if the counters have overflowed. */                         \
-      if (mcs->invocation_counter()                                            \
-                         ->reached_ProfileLimit(mcs->backedge_counter())) {    \
-        /* Must use CALL_VM, because an async exception may be pending. */     \
-        CALL_VM((InterpreterRuntime::profile_method(THREAD)),                  \
-                exception_handler);                                            \
-        md = istate->method()->method_data();                                  \
-        if (md != NULL) {                                                      \
-          if (TraceProfileInterpreter) {                                       \
-            BI_PROFILE_PRINT_METHOD_DATA();                                    \
-          }                                                                    \
-          Method *m = istate->method();                                        \
-          int bci = m->bci_from(pc);                                           \
-          jint di = md->bci_to_di(bci);                                        \
-          SET_MDX(md->data_layout_at(di));                                     \
-        }                                                                      \
-      }                                                                        \
-    } else {                                                                   \
-      /* The profiling method data exists, align the method data pointer */    \
-      /* mdx to the current bytecode index. */                                 \
-      if (TraceProfileInterpreter) {                                           \
-        BI_PROFILE_PRINT_METHOD_DATA();                                        \
-      }                                                                        \
-      SET_MDX(md->data_layout_at(md->bci_to_di(BCI())));                       \
-    }                                                                          \
-  }
-
-
-// Asserts that the current method data pointer mdx corresponds
-// to the current bytecode.
-#if defined(CC_INTERP_PROFILE_WITH_ASSERTIONS)
-#define BI_PROFILE_CHECK_MDX()                                                 \
-  {                                                                            \
-    MethodData *md = istate->method()->method_data();                          \
-    address mdx  = (address) MDX();                                            \
-    address mdx2 = (address) md->data_layout_at(md->bci_to_di(BCI()));         \
-    guarantee(md   != NULL, "1");                                              \
-    guarantee(mdx  != NULL, "2");                                              \
-    guarantee(mdx2 != NULL, "3");                                              \
-    if (mdx != mdx2) {                                                         \
-      BI_PROFILE_PRINT_METHOD_DATA();                                          \
-      fatal3("invalid mdx at bci %d:"                                          \
-             " was " PTR_FORMAT                                                \
-             " but expected " PTR_FORMAT,                                      \
-             BCI(),                                                            \
-             mdx,                                                              \
-             mdx2);                                                            \
-    }                                                                          \
-  }
-#else
-#define BI_PROFILE_CHECK_MDX()
-#endif
-
-
-// Aligns the method data pointer mdx to the current bytecode index.
-#define BI_PROFILE_ALIGN_TO_CURRENT_BCI()                                      \
-  if (ProfileInterpreter && MDX() != NULL) {                                   \
-    MethodData *md = istate->method()->method_data();                          \
-    SET_MDX(md->data_layout_at(md->bci_to_di(BCI())));                         \
-  }
-
-
-// Updates profiling data for a jump.
-#define BI_PROFILE_UPDATE_JUMP()                                               \
-  if (ProfileInterpreter && MDX() != NULL) {                                   \
-    BI_PROFILE_CHECK_MDX();                                                    \
-    JumpData::increment_taken_count_no_overflow(MDX());                        \
-    /* Remember last branch taken count. */                                    \
-    mdo_last_branch_taken_count = JumpData::taken_count(MDX());                \
-    SET_MDX(JumpData::advance_taken(MDX()));                                   \
-  }
-
-
-// Updates profiling data for a taken/not taken branch.
-#define BI_PROFILE_UPDATE_BRANCH(is_taken)                                     \
-  if (ProfileInterpreter && MDX() != NULL) {                                   \
-    BI_PROFILE_CHECK_MDX();                                                    \
-    if (is_taken) {                                                            \
-      BranchData::increment_taken_count_no_overflow(MDX());                    \
-      /* Remember last branch taken count. */                                  \
-      mdo_last_branch_taken_count = BranchData::taken_count(MDX());            \
-      SET_MDX(BranchData::advance_taken(MDX()));                               \
-    } else {                                                                   \
-      BranchData::increment_not_taken_count_no_overflow(MDX());                \
-      SET_MDX(BranchData::advance_not_taken(MDX()));                           \
-    }                                                                          \
-  }
-
-
-// Updates profiling data for a ret with given bci.
-#define BI_PROFILE_UPDATE_RET(bci)                                             \
-  if (ProfileInterpreter && MDX() != NULL) {                                   \
-    BI_PROFILE_CHECK_MDX();                                                    \
-    MethodData *md = istate->method()->method_data();                          \
-/* FIXME: there is more to do here than increment and advance(mdx)! */         \
-    CounterData::increment_count_no_overflow(MDX());                           \
-    SET_MDX(RetData::advance(md, bci));                                        \
-  }
-
-// Decrement counter at checkcast if the subtype check fails (as template
-// interpreter does!).
-#define BI_PROFILE_SUBTYPECHECK_FAILED(receiver)                               \
-  if (ProfileInterpreter && MDX() != NULL) {                                   \
-    BI_PROFILE_CHECK_MDX();                                                    \
-    ReceiverTypeData::increment_receiver_count_no_overflow(MDX(), receiver);   \
-    ReceiverTypeData::decrement_count(MDX());                                  \
-  }
-
-// Updates profiling data for a checkcast (was a null seen? which receiver?).
-#define BI_PROFILE_UPDATE_CHECKCAST(null_seen, receiver)                       \
-  if (ProfileInterpreter && MDX() != NULL) {                                   \
-    BI_PROFILE_CHECK_MDX();                                                    \
-    if (null_seen) {                                                           \
-      ReceiverTypeData::set_null_seen(MDX());                                  \
-    } else {                                                                   \
-      /* Template interpreter doesn't increment count. */                      \
-      /* ReceiverTypeData::increment_count_no_overflow(MDX()); */              \
-      ReceiverTypeData::increment_receiver_count_no_overflow(MDX(), receiver); \
-    }                                                                          \
-    SET_MDX(ReceiverTypeData::advance(MDX()));                                 \
-  }
-
-
-// Updates profiling data for an instanceof (was a null seen? which receiver?).
-#define BI_PROFILE_UPDATE_INSTANCEOF(null_seen, receiver)                      \
-  BI_PROFILE_UPDATE_CHECKCAST(null_seen, receiver)
-
-
-// Updates profiling data for a call.
-#define BI_PROFILE_UPDATE_CALL()                                               \
-  if (ProfileInterpreter && MDX() != NULL) {                                   \
-    BI_PROFILE_CHECK_MDX();                                                    \
-    CounterData::increment_count_no_overflow(MDX());                           \
-    SET_MDX(CounterData::advance(MDX()));                                      \
-  }
-
-
-// Updates profiling data for a final call.
-#define BI_PROFILE_UPDATE_FINALCALL()                                          \
-  if (ProfileInterpreter && MDX() != NULL) {                                   \
-    BI_PROFILE_CHECK_MDX();                                                    \
-    VirtualCallData::increment_count_no_overflow(MDX());                       \
-    SET_MDX(VirtualCallData::advance(MDX()));                                  \
-  }
-
-
-// Updates profiling data for a virtual call with given receiver Klass.
-#define BI_PROFILE_UPDATE_VIRTUALCALL(receiver)                                \
-  if (ProfileInterpreter && MDX() != NULL) {                                   \
-    BI_PROFILE_CHECK_MDX();                                                    \
-    VirtualCallData::increment_receiver_count_no_overflow(MDX(), receiver);    \
-    SET_MDX(VirtualCallData::advance(MDX()));                                  \
-  }
-
-
-// Updates profiling data for a switch (tabelswitch or lookupswitch) with
-// given taken index (-1 means default case was taken).
-#define BI_PROFILE_UPDATE_SWITCH(switch_index)                                 \
-  if (ProfileInterpreter && MDX() != NULL) {                                   \
-    BI_PROFILE_CHECK_MDX();                                                    \
-    MultiBranchData::increment_count_no_overflow(MDX(), switch_index);         \
-    SET_MDX(MultiBranchData::advance(MDX(), switch_index));                    \
-  }
-
-
-// The end /////////////////////////////////////////////////////////////////////
-
-#endif // CC_INTERP_PROFILE
-
 #endif // CC_INTERP
 
 #endif // SHARE_VM_INTERPRETER_BYTECODECINTERPRETERPROFILING_HPP
--- a/src/hotspot/share/interpreter/linkResolver.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/interpreter/linkResolver.cpp	Thu May 31 13:04:30 2018 -0700
@@ -688,19 +688,21 @@
                                               CHECK);
   if (failed_type_symbol != NULL) {
     const char* msg = "loader constraint violation: when resolving field"
-      " \"%s\" the class loader %s of the referring class, "
-      "%s, and the class loader %s for the field's resolved "
-      "type, %s, have different Class objects for that type";
-    char* field_name = field->as_C_string();
+      " \"%s\" of type %s, the class loader %s of the current class, "
+      "%s, and the class loader %s for the field's defining "
+      "type, %s, have different Class objects for type %s";
+    const char* field_name = field->as_C_string();
     const char* loader1_name = java_lang_ClassLoader::describe_external(ref_loader());
-    char* sel = sel_klass->name()->as_C_string();
+    const char* sel = sel_klass->external_name();
     const char* loader2_name = java_lang_ClassLoader::describe_external(sel_loader());
-    char* failed_type_name = failed_type_symbol->as_C_string();
-    size_t buflen = strlen(msg) + strlen(field_name) + strlen(loader1_name) +
-                    strlen(sel) + strlen(loader2_name) + strlen(failed_type_name) + 1;
+    const char* failed_type_name = failed_type_symbol->as_klass_external_name();
+    const char* curr_klass_name = current_klass->external_name();
+    size_t buflen = strlen(msg) + strlen(field_name) + 2 * strlen(failed_type_name) +
+                    strlen(loader1_name) + strlen(curr_klass_name) +
+                    strlen(loader2_name) + strlen(sel) + 1;
     char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen);
-    jio_snprintf(buf, buflen, msg, field_name, loader1_name, sel, loader2_name,
-                     failed_type_name);
+    jio_snprintf(buf, buflen, msg, field_name, failed_type_name, loader1_name,
+                 curr_klass_name, loader2_name, sel, failed_type_name);
     THROW_MSG(vmSymbols::java_lang_LinkageError(), buf);
   }
 }
--- a/src/hotspot/share/jfr/leakprofiler/chains/rootSetClosure.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/jfr/leakprofiler/chains/rootSetClosure.cpp	Thu May 31 13:04:30 2018 -0700
@@ -100,7 +100,7 @@
   Universe::oops_do(closure);
   JNIHandles::oops_do(closure);
   JvmtiExport::oops_do(closure);
-  SystemDictionary::always_strong_oops_do(closure);
+  SystemDictionary::oops_do(closure);
   Management::oops_do(closure);
   StringTable::oops_do(closure);
   AOTLoader::oops_do(closure);
--- a/src/hotspot/share/memory/metaspace.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/memory/metaspace.cpp	Thu May 31 13:04:30 2018 -0700
@@ -132,18 +132,17 @@
 bool MetaspaceGC::inc_capacity_until_GC(size_t v, size_t* new_cap_until_GC, size_t* old_cap_until_GC) {
   assert_is_aligned(v, Metaspace::commit_alignment());
 
-  size_t capacity_until_GC = _capacity_until_GC;
-  size_t new_value = capacity_until_GC + v;
+  size_t old_capacity_until_GC = _capacity_until_GC;
+  size_t new_value = old_capacity_until_GC + v;
 
-  if (new_value < capacity_until_GC) {
+  if (new_value < old_capacity_until_GC) {
     // The addition wrapped around, set new_value to aligned max value.
     new_value = align_down(max_uintx, Metaspace::commit_alignment());
   }
 
-  size_t expected = _capacity_until_GC;
-  size_t actual = Atomic::cmpxchg(new_value, &_capacity_until_GC, expected);
+  size_t prev_value = Atomic::cmpxchg(new_value, &_capacity_until_GC, old_capacity_until_GC);
 
-  if (expected != actual) {
+  if (old_capacity_until_GC != prev_value) {
     return false;
   }
 
@@ -151,7 +150,7 @@
     *new_cap_until_GC = new_value;
   }
   if (old_cap_until_GC != NULL) {
-    *old_cap_until_GC = capacity_until_GC;
+    *old_cap_until_GC = old_capacity_until_GC;
   }
   return true;
 }
@@ -602,11 +601,12 @@
 void MetaspaceUtils::print_report(outputStream* out, size_t scale, int flags) {
 
   const bool print_loaders = (flags & rf_show_loaders) > 0;
+  const bool print_classes = (flags & rf_show_classes) > 0;
   const bool print_by_chunktype = (flags & rf_break_down_by_chunktype) > 0;
   const bool print_by_spacetype = (flags & rf_break_down_by_spacetype) > 0;
 
   // Some report options require walking the class loader data graph.
-  PrintCLDMetaspaceInfoClosure cl(out, scale, print_loaders, print_by_chunktype);
+  PrintCLDMetaspaceInfoClosure cl(out, scale, print_loaders, print_classes, print_by_chunktype);
   if (print_loaders) {
     out->cr();
     out->print_cr("Usage per loader:");
--- a/src/hotspot/share/memory/metaspace.hpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/memory/metaspace.hpp	Thu May 31 13:04:30 2018 -0700
@@ -389,7 +389,9 @@
     // Print details about the underlying virtual spaces.
     rf_show_vslist                  = (1 << 3),
     // Print metaspace map.
-    rf_show_vsmap                   = (1 << 4)
+    rf_show_vsmap                   = (1 << 4),
+    // If show_loaders: show loaded classes for each loader.
+    rf_show_classes                 = (1 << 5)
   };
 
   // This will print out a basic metaspace usage report but
--- a/src/hotspot/share/memory/metaspace/metaspaceDCmd.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/memory/metaspace/metaspaceDCmd.cpp	Thu May 31 13:04:30 2018 -0700
@@ -1,5 +1,6 @@
 /*
  * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2018, SAP and/or its affiliates.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -34,6 +35,7 @@
   : DCmdWithParser(output, heap)
   , _basic("basic", "Prints a basic summary (does not need a safepoint).", "BOOLEAN", false, "false")
   , _show_loaders("show-loaders", "Shows usage by class loader.", "BOOLEAN", false, "false")
+  , _show_classes("show-classes", "If show-loaders is set, shows loaded classes for each loader.", "BOOLEAN", false, "false")
   , _by_chunktype("by-chunktype", "Break down numbers by chunk type.", "BOOLEAN", false, "false")
   , _by_spacetype("by-spacetype", "Break down numbers by loader type.", "BOOLEAN", false, "false")
   , _show_vslist("vslist", "Shows details about the underlying virtual space.", "BOOLEAN", false, "false")
@@ -44,6 +46,7 @@
 {
   _dcmdparser.add_dcmd_option(&_basic);
   _dcmdparser.add_dcmd_option(&_show_loaders);
+  _dcmdparser.add_dcmd_option(&_show_classes);
   _dcmdparser.add_dcmd_option(&_by_chunktype);
   _dcmdparser.add_dcmd_option(&_by_spacetype);
   _dcmdparser.add_dcmd_option(&_show_vslist);
@@ -87,6 +90,7 @@
     // Full mode. Requires safepoint.
     int flags = 0;
     if (_show_loaders.value())         flags |= MetaspaceUtils::rf_show_loaders;
+    if (_show_classes.value())         flags |= MetaspaceUtils::rf_show_classes;
     if (_by_chunktype.value())         flags |= MetaspaceUtils::rf_break_down_by_chunktype;
     if (_by_spacetype.value())         flags |= MetaspaceUtils::rf_break_down_by_spacetype;
     if (_show_vslist.value())          flags |= MetaspaceUtils::rf_show_vslist;
--- a/src/hotspot/share/memory/metaspace/metaspaceDCmd.hpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/memory/metaspace/metaspaceDCmd.hpp	Thu May 31 13:04:30 2018 -0700
@@ -1,5 +1,6 @@
 /*
  * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2018, SAP and/or its affiliates.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -39,6 +40,7 @@
   DCmdArgument<bool> _show_vslist;
   DCmdArgument<bool> _show_vsmap;
   DCmdArgument<char*> _scale;
+  DCmdArgument<bool> _show_classes;
 public:
   MetaspaceDCmd(outputStream* output, bool heap);
   static const char* name() {
--- a/src/hotspot/share/memory/metaspace/printCLDMetaspaceInfoClosure.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/memory/metaspace/printCLDMetaspaceInfoClosure.cpp	Thu May 31 13:04:30 2018 -0700
@@ -22,8 +22,10 @@
  *
  */
 #include "precompiled.hpp"
-#include "classfile/classLoaderData.hpp"
+#include "classfile/classLoaderData.inline.hpp"
+#include "classfile/javaClasses.hpp"
 #include "memory/metaspace/printCLDMetaspaceInfoClosure.hpp"
+#include "memory/metaspace/printMetaspaceInfoKlassClosure.hpp"
 #include "memory/resourceArea.hpp"
 #include "runtime/safepoint.hpp"
 #include "utilities/globalDefinitions.hpp"
@@ -32,19 +34,31 @@
 
 namespace metaspace {
 
-PrintCLDMetaspaceInfoClosure::PrintCLDMetaspaceInfoClosure(outputStream* out, size_t scale, bool do_print, bool break_down_by_chunktype)
-: _out(out), _scale(scale), _do_print(do_print), _break_down_by_chunktype(break_down_by_chunktype)
-, _num_loaders(0)
+PrintCLDMetaspaceInfoClosure::PrintCLDMetaspaceInfoClosure(outputStream* out, size_t scale, bool do_print,
+    bool do_print_classes, bool break_down_by_chunktype)
+: _out(out), _scale(scale), _do_print(do_print), _do_print_classes(do_print_classes)
+, _break_down_by_chunktype(break_down_by_chunktype)
+, _num_loaders(0), _num_loaders_unloading(0), _num_loaders_without_metaspace(0)
 {
   memset(_num_loaders_by_spacetype, 0, sizeof(_num_loaders_by_spacetype));
 }
 
+static const char* classes_plural(uintx num) {
+  return num == 1 ? "" : "es";
+}
+
 void PrintCLDMetaspaceInfoClosure::do_cld(ClassLoaderData* cld) {
 
   assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
 
+  if (cld->is_unloading()) {
+    _num_loaders_unloading ++;
+    return;
+  }
+
   ClassLoaderMetaspace* msp = cld->metaspace_or_null();
   if (msp == NULL) {
+    _num_loaders_without_metaspace ++;
     return;
   }
 
@@ -63,17 +77,73 @@
 
     _out->print(UINTX_FORMAT_W(4) ": ", _num_loaders);
 
-    if (cld->is_anonymous()) {
-      _out->print("ClassLoaderData " PTR_FORMAT " for anonymous class", p2i(cld));
+    // Print "CLD for [<loader name>,] instance of <loader class name>"
+    // or    "CLD for <anonymous class>, loaded by [<loader name>,] instance of <loader class name>"
+
+    ResourceMark rm;
+    const char* name = NULL;
+    const char* class_name = NULL;
+
+    // Note: this should also work if unloading:
+    Klass* k = cld->class_loader_klass();
+    if (k != NULL) {
+      class_name = k->external_name();
+      Symbol* s = cld->class_loader_name();
+      if (s != NULL) {
+        name = s->as_C_string();
+      }
     } else {
-      ResourceMark rm;
-      _out->print("ClassLoaderData " PTR_FORMAT " for %s", p2i(cld), cld->loader_name());
+      name = "<bootstrap>";
     }
 
+    // Print
+    _out->print("CLD " PTR_FORMAT, p2i(cld));
     if (cld->is_unloading()) {
       _out->print(" (unloading)");
     }
+    _out->print(":");
+    if (cld->is_anonymous()) {
+      _out->print(" <anonymous class>, loaded by");
+    }
+    if (name != NULL) {
+      _out->print(" \"%s\"", name);
+    }
+    if (class_name != NULL) {
+      _out->print(" instance of %s", class_name);
+    }
 
+    if (_do_print_classes) {
+      streamIndentor sti(_out, 6);
+      _out->cr_indent();
+      _out->print("Loaded classes: ");
+      PrintMetaspaceInfoKlassClosure pkic(_out, true);
+      cld->classes_do(&pkic);
+      _out->cr_indent();
+      _out->print("-total-: ");
+      _out->print(UINTX_FORMAT " class%s", pkic._num_classes, classes_plural(pkic._num_classes));
+      if (pkic._num_instance_classes > 0 || pkic._num_array_classes > 0) {
+        _out->print(" (");
+        if (pkic._num_instance_classes > 0) {
+          _out->print(UINTX_FORMAT " instance class%s", pkic._num_instance_classes,
+              classes_plural(pkic._num_instance_classes));
+        }
+        if (pkic._num_array_classes > 0) {
+          if (pkic._num_instance_classes > 0) {
+            _out->print(", ");
+          }
+          _out->print(UINTX_FORMAT " array class%s", pkic._num_array_classes,
+              classes_plural(pkic._num_array_classes));
+        }
+        _out->print(").");
+      }
+    }
+
+    _out->cr();
+
+
+    _out->cr();
+
+    // Print statistics
     this_cld_stat.print_on(_out, _scale, _break_down_by_chunktype);
     _out->cr();
 
--- a/src/hotspot/share/memory/metaspace/printCLDMetaspaceInfoClosure.hpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/memory/metaspace/printCLDMetaspaceInfoClosure.hpp	Thu May 31 13:04:30 2018 -0700
@@ -39,17 +39,21 @@
   outputStream* const _out;
   const size_t        _scale;
   const bool          _do_print;
+  const bool          _do_print_classes;
   const bool          _break_down_by_chunktype;
 
 public:
 
   uintx                           _num_loaders;
+  uintx                           _num_loaders_without_metaspace;
+  uintx                           _num_loaders_unloading;
   ClassLoaderMetaspaceStatistics  _stats_total;
 
   uintx                           _num_loaders_by_spacetype [Metaspace::MetaspaceTypeCount];
   ClassLoaderMetaspaceStatistics  _stats_by_spacetype [Metaspace::MetaspaceTypeCount];
 
-  PrintCLDMetaspaceInfoClosure(outputStream* out, size_t scale, bool do_print, bool break_down_by_chunktype);
+  PrintCLDMetaspaceInfoClosure(outputStream* out, size_t scale, bool do_print,
+      bool do_print_classes, bool break_down_by_chunktype);
   void do_cld(ClassLoaderData* cld);
 
 };
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/hotspot/share/memory/metaspace/printMetaspaceInfoKlassClosure.cpp	Thu May 31 13:04:30 2018 -0700
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2018, SAP and/or its affiliates.
+ * 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.
+ *
+ */
+#include "precompiled.hpp"
+
+#include "classfile/systemDictionary.hpp"
+#include "memory/metaspace/printMetaspaceInfoKlassClosure.hpp"
+#include "memory/resourceArea.hpp"
+#include "oops/constantPool.inline.hpp"
+#include "oops/instanceKlass.hpp"
+#include "oops/klass.hpp"
+#include "utilities/constantTag.hpp"
+#include "utilities/globalDefinitions.hpp"
+#include "utilities/ostream.hpp"
+
+
+namespace metaspace {
+
+PrintMetaspaceInfoKlassClosure::PrintMetaspaceInfoKlassClosure(outputStream* out, bool do_print)
+: _out(out), _do_print(do_print)
+, _num_classes(0), _num_instance_classes(0), _num_array_classes(0) {
+}
+
+void PrintMetaspaceInfoKlassClosure::do_klass(Klass* k) {
+  _num_classes ++;
+  if (k->is_instance_klass()) {
+    _num_instance_classes ++;
+  } else if (k->is_array_klass()) {
+    _num_array_classes ++;
+  }
+  if (_do_print) {
+    _out->cr_indent();
+    _out->print(UINTX_FORMAT_W(4) ": ", _num_classes);
+    ResourceMark rm;
+    _out->print("%s", k->external_name());
+  }
+}
+
+} // namespace metaspace
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/hotspot/share/memory/metaspace/printMetaspaceInfoKlassClosure.hpp	Thu May 31 13:04:30 2018 -0700
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2018, SAP and/or its affiliates.
+ * 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.
+ *
+ */
+
+#ifndef SHARE_MEMORY_METASPACE_PRINTMETASPACEINFOKLASSCLOSURE_HPP_
+#define SHARE_MEMORY_METASPACE_PRINTMETASPACEINFOKLASSCLOSURE_HPP_
+
+#include "memory/iterator.hpp"
+#include "utilities/globalDefinitions.hpp"
+
+class outputStream;
+class InstanceKlass;
+
+namespace metaspace {
+
+// Helper class for MetaspaceUtils::print_report()
+class PrintMetaspaceInfoKlassClosure : public KlassClosure {
+private:
+  outputStream* const _out;
+  const bool          _do_print;
+
+public:
+  uintx _num_classes;
+  uintx _num_instance_classes;
+  uintx _num_array_classes;
+
+  PrintMetaspaceInfoKlassClosure(outputStream* out, bool do_print);
+  void do_klass(Klass* k);
+
+}; // end: PrintKlassInfoClosure
+
+} // namespace metaspace
+
+#endif /* SHARE_MEMORY_METASPACE_PRINTMETASPACEINFOKLASSCLOSURE_HPP_ */
--- a/src/hotspot/share/memory/metaspace/virtualSpaceNode.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/memory/metaspace/virtualSpaceNode.cpp	Thu May 31 13:04:30 2018 -0700
@@ -521,16 +521,6 @@
         "Checking that the pre-committed memory was registered by the VirtualSpace");
 
     set_top((MetaWord*)virtual_space()->low());
-    set_reserved(MemRegion((HeapWord*)_rs.base(),
-        (HeapWord*)(_rs.base() + _rs.size())));
-
-    assert(reserved()->start() == (HeapWord*) _rs.base(),
-        "Reserved start was not set properly " PTR_FORMAT
-        " != " PTR_FORMAT, p2i(reserved()->start()), p2i(_rs.base()));
-    assert(reserved()->word_size() == _rs.size() / BytesPerWord,
-        "Reserved size was not set properly " SIZE_FORMAT
-        " != " SIZE_FORMAT, reserved()->word_size(),
-        _rs.size() / BytesPerWord);
   }
 
   // Initialize Occupancy Map.
--- a/src/hotspot/share/memory/metaspace/virtualSpaceNode.hpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/memory/metaspace/virtualSpaceNode.hpp	Thu May 31 13:04:30 2018 -0700
@@ -49,7 +49,6 @@
   const bool _is_class;
 
   // total in the VirtualSpace
-  MemRegion _reserved;
   ReservedSpace _rs;
   VirtualSpace _virtual_space;
   MetaWord* _top;
@@ -102,11 +101,9 @@
   VirtualSpaceNode* next() { return _next; }
   void set_next(VirtualSpaceNode* v) { _next = v; }
 
-  void set_reserved(MemRegion const v) { _reserved = v; }
   void set_top(MetaWord* v) { _top = v; }
 
   // Accessors
-  MemRegion* reserved() { return &_reserved; }
   VirtualSpace* virtual_space() const { return (VirtualSpace*) &_virtual_space; }
 
   // Returns true if "word_size" is available in the VirtualSpace
@@ -135,8 +132,7 @@
   // Allocate a chunk from the virtual space and return it.
   Metachunk* get_chunk_vs(size_t chunk_word_size);
 
-  // Expands/shrinks the committed space in a virtual space.  Delegates
-  // to Virtualspace
+  // Expands the committed space by at least min_words words.
   bool expand_by(size_t min_words, size_t preferred_words);
 
   // In preparation for deleting this node, remove all the chunks
--- a/src/hotspot/share/memory/padded.hpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/memory/padded.hpp	Thu May 31 13:04:30 2018 -0700
@@ -104,6 +104,8 @@
  public:
   // Creates an aligned padded 2D array.
   // The memory cannot be deleted since the raw memory chunk is not returned.
+  // Always uses mmap to reserve memory. Only the first few pages with the index to
+  // the rows are touched. Allocation size should be "large" to cover page overhead.
   static T** create_unfreeable(uint rows, uint columns, size_t* allocation_size = NULL);
 };
 
--- a/src/hotspot/share/memory/padded.inline.hpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/memory/padded.inline.hpp	Thu May 31 13:04:30 2018 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 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
@@ -62,9 +62,8 @@
   size_t total_size = table_size + rows * row_size + alignment;
 
   // Allocate a chunk of memory large enough to allow alignment of the chunk.
-  void* chunk = AllocateHeap(total_size, flags);
+  void* chunk = MmapArrayAllocator<uint8_t>::allocate(total_size, flags);
   // Clear the allocated memory.
-  memset(chunk, 0, total_size);
   // Align the chunk of memory.
   T** result = (T**)align_up(chunk, alignment);
   void* data_start = (void*)((uintptr_t)result + table_size);
--- a/src/hotspot/share/oops/arrayKlass.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/oops/arrayKlass.cpp	Thu May 31 13:04:30 2018 -0700
@@ -130,7 +130,7 @@
 
 objArrayOop ArrayKlass::allocate_arrayArray(int n, int length, TRAPS) {
   if (length < 0) {
-    THROW_0(vmSymbols::java_lang_NegativeArraySizeException());
+    THROW_MSG_0(vmSymbols::java_lang_NegativeArraySizeException(), err_msg("%d", length));
   }
   if (length > arrayOopDesc::max_array_length(T_ARRAY)) {
     report_java_out_of_memory("Requested array size exceeds VM limit");
--- a/src/hotspot/share/oops/instanceKlass.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/oops/instanceKlass.cpp	Thu May 31 13:04:30 2018 -0700
@@ -975,7 +975,9 @@
 }
 
 objArrayOop InstanceKlass::allocate_objArray(int n, int length, TRAPS) {
-  if (length < 0) THROW_0(vmSymbols::java_lang_NegativeArraySizeException());
+  if (length < 0)  {
+    THROW_MSG_0(vmSymbols::java_lang_NegativeArraySizeException(), err_msg("%d", length));
+  }
   if (length > arrayOopDesc::max_array_length(T_OBJECT)) {
     report_java_out_of_memory("Requested array size exceeds VM limit");
     JvmtiExport::post_array_size_exhausted();
--- a/src/hotspot/share/oops/instanceRefKlass.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/oops/instanceRefKlass.cpp	Thu May 31 13:04:30 2018 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 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
@@ -30,10 +30,8 @@
 
 void InstanceRefKlass::update_nonstatic_oop_maps(Klass* k) {
   // Clear the nonstatic oop-map entries corresponding to referent
-  // and nextPending field.  They are treated specially by the
+  // and discovered fields.  They are treated specially by the
   // garbage collector.
-  // The discovered field is used only by the garbage collector
-  // and is also treated specially.
   InstanceKlass* ik = InstanceKlass::cast(k);
 
   // Check that we have the right class
@@ -45,22 +43,33 @@
 
   OopMapBlock* map = ik->start_of_nonstatic_oop_maps();
 
-  // Check that the current map is (2,4) - currently points at field with
-  // offset 2 (words) and has 4 map entries.
-  debug_only(int offset = java_lang_ref_Reference::referent_offset);
-  debug_only(unsigned int count = ((java_lang_ref_Reference::discovered_offset -
-    java_lang_ref_Reference::referent_offset)/heapOopSize) + 1);
+#ifdef ASSERT
+  // Verify fields are in the expected places.
+  int referent_offset = java_lang_ref_Reference::referent_offset;
+  int queue_offset = java_lang_ref_Reference::queue_offset;
+  int next_offset = java_lang_ref_Reference::next_offset;
+  int discovered_offset = java_lang_ref_Reference::discovered_offset;
+  assert(referent_offset < queue_offset, "just checking");
+  assert(queue_offset < next_offset, "just checking");
+  assert(next_offset < discovered_offset, "just checking");
+  const unsigned int count =
+    1 + ((discovered_offset - referent_offset) / heapOopSize);
+  assert(count == 4, "just checking");
+#endif // ASSERT
 
+  // Updated map starts at "queue", covers "queue" and "next".
+  const int new_offset = java_lang_ref_Reference::queue_offset;
+  const unsigned int new_count = 2; // queue and next
+
+  // Verify existing map is as expected, and update if needed.
   if (UseSharedSpaces) {
-    assert(map->offset() == java_lang_ref_Reference::queue_offset &&
-           map->count() == 1, "just checking");
+    assert(map->offset() == new_offset, "just checking");
+    assert(map->count() == new_count, "just checking");
   } else {
-    assert(map->offset() == offset && map->count() == count,
-           "just checking");
-
-    // Update map to (3,1) - point to offset of 3 (words) with 1 map entry.
-    map->set_offset(java_lang_ref_Reference::queue_offset);
-    map->set_count(1);
+    assert(map->offset() == referent_offset, "just checking");
+    assert(map->count() == count, "just checking");
+    map->set_offset(new_offset);
+    map->set_count(new_count);
   }
 }
 
@@ -74,7 +83,7 @@
   if (referent != NULL) {
     guarantee(oopDesc::is_oop(referent), "referent field heap failed");
   }
-  // Verify next field
+  // Additional verification for next field, which must be a Reference or null
   oop next = java_lang_ref_Reference::next(obj);
   if (next != NULL) {
     guarantee(oopDesc::is_oop(next), "next field should be an oop");
--- a/src/hotspot/share/oops/instanceRefKlass.inline.hpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/oops/instanceRefKlass.inline.hpp	Thu May 31 13:04:30 2018 -0700
@@ -46,14 +46,6 @@
 }
 
 template <bool nv, typename T, class OopClosureType, class Contains>
-void InstanceRefKlass::do_next(oop obj, OopClosureType* closure, Contains& contains) {
-  T* next_addr = (T*)java_lang_ref_Reference::next_addr_raw(obj);
-  if (contains(next_addr)) {
-    Devirtualizer<nv>::do_oop(closure, next_addr);
-  }
-}
-
-template <bool nv, typename T, class OopClosureType, class Contains>
 void InstanceRefKlass::do_discovered(oop obj, OopClosureType* closure, Contains& contains) {
   T* discovered_addr = (T*)java_lang_ref_Reference::discovered_addr_raw(obj);
   if (contains(discovered_addr)) {
@@ -84,24 +76,15 @@
     return;
   }
 
-  // Treat referent as normal oop.
+  // Treat referent and discovered as normal oops.
   do_referent<nv, T>(obj, closure, contains);
-
-  // Treat discovered as normal oop, if ref is not "active" (next non-NULL).
-  T next_oop  = RawAccess<>::oop_load((T*)java_lang_ref_Reference::next_addr_raw(obj));
-  if (!CompressedOops::is_null(next_oop)) {
-    do_discovered<nv, T>(obj, closure, contains);
-  }
-
-  // Treat next as normal oop.
-  do_next<nv, T>(obj, closure, contains);
+  do_discovered<nv, T>(obj, closure, contains);
 }
 
 template <bool nv, typename T, class OopClosureType, class Contains>
 void InstanceRefKlass::oop_oop_iterate_fields(oop obj, OopClosureType* closure, Contains& contains) {
   do_referent<nv, T>(obj, closure, contains);
   do_discovered<nv, T>(obj, closure, contains);
-  do_next<nv, T>(obj, closure, contains);
 }
 
 template <bool nv, typename T, class OopClosureType, class Contains>
@@ -192,14 +175,11 @@
 template <typename T>
 void InstanceRefKlass::trace_reference_gc(const char *s, oop obj) {
   T* referent_addr   = (T*) java_lang_ref_Reference::referent_addr_raw(obj);
-  T* next_addr       = (T*) java_lang_ref_Reference::next_addr_raw(obj);
   T* discovered_addr = (T*) java_lang_ref_Reference::discovered_addr_raw(obj);
 
   log_develop_trace(gc, ref)("InstanceRefKlass %s for obj " PTR_FORMAT, s, p2i(obj));
   log_develop_trace(gc, ref)("     referent_addr/* " PTR_FORMAT " / " PTR_FORMAT,
       p2i(referent_addr), p2i(referent_addr ? RawAccess<>::oop_load(referent_addr) : (oop)NULL));
-  log_develop_trace(gc, ref)("     next_addr/* " PTR_FORMAT " / " PTR_FORMAT,
-      p2i(next_addr), p2i(next_addr ? RawAccess<>::oop_load(next_addr) : (oop)NULL));
   log_develop_trace(gc, ref)("     discovered_addr/* " PTR_FORMAT " / " PTR_FORMAT,
       p2i(discovered_addr), p2i(discovered_addr ? RawAccess<>::oop_load(discovered_addr) : (oop)NULL));
 }
--- a/src/hotspot/share/oops/methodData.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/oops/methodData.cpp	Thu May 31 13:04:30 2018 -0700
@@ -541,12 +541,6 @@
   return mdp;
 }
 
-#ifdef CC_INTERP
-DataLayout* RetData::advance(MethodData *md, int bci) {
-  return (DataLayout*) md->bci_to_dp(bci);
-}
-#endif // CC_INTERP
-
 void RetData::print_data_on(outputStream* st, const char* extra) const {
   print_shared(st, "RetData", extra);
   uint row;
--- a/src/hotspot/share/oops/methodData.hpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/oops/methodData.hpp	Thu May 31 13:04:30 2018 -0700
@@ -232,11 +232,6 @@
   static ByteSize cell_offset(int index) {
     return byte_offset_of(DataLayout, _cells) + in_ByteSize(index * cell_size);
   }
-#ifdef CC_INTERP
-  static int cell_offset_in_bytes(int index) {
-    return (int)offset_of(DataLayout, _cells[index]);
-  }
-#endif // CC_INTERP
   // Return a value which, when or-ed as a byte into _flags, sets the flag.
   static int flag_number_to_byte_constant(int flag_number) {
     assert(0 <= flag_number && flag_number < flag_limit, "oob");
@@ -372,41 +367,6 @@
     _data = data;
   }
 
-#ifdef CC_INTERP
-  // Static low level accessors for DataLayout with ProfileData's semantics.
-
-  static int cell_offset_in_bytes(int index) {
-    return DataLayout::cell_offset_in_bytes(index);
-  }
-
-  static void increment_uint_at_no_overflow(DataLayout* layout, int index,
-                                            int inc = DataLayout::counter_increment) {
-    uint count = ((uint)layout->cell_at(index)) + inc;
-    if (count == 0) return;
-    layout->set_cell_at(index, (intptr_t) count);
-  }
-
-  static int int_at(DataLayout* layout, int index) {
-    return (int)layout->cell_at(index);
-  }
-
-  static int uint_at(DataLayout* layout, int index) {
-    return (uint)layout->cell_at(index);
-  }
-
-  static oop oop_at(DataLayout* layout, int index) {
-    return cast_to_oop(layout->cell_at(index));
-  }
-
-  static void set_intptr_at(DataLayout* layout, int index, intptr_t value) {
-    layout->set_cell_at(index, (intptr_t) value);
-  }
-
-  static void set_flag_at(DataLayout* layout, int flag_number) {
-    layout->set_flag_at(flag_number);
-  }
-#endif // CC_INTERP
-
 public:
   // Constructor for invalid ProfileData.
   ProfileData();
@@ -581,20 +541,6 @@
     return cell_offset(bit_cell_count);
   }
 
-#ifdef CC_INTERP
-  static int bit_data_size_in_bytes() {
-    return cell_offset_in_bytes(bit_cell_count);
-  }
-
-  static void set_null_seen(DataLayout* layout) {
-    set_flag_at(layout, null_seen_flag);
-  }
-
-  static DataLayout* advance(DataLayout* layout) {
-    return (DataLayout*) (((address)layout) + (ssize_t)BitData::bit_data_size_in_bytes());
-  }
-#endif // CC_INTERP
-
   void print_data_on(outputStream* st, const char* extra = NULL) const;
 };
 
@@ -639,25 +585,6 @@
     set_uint_at(count_off, count);
   }
 
-#ifdef CC_INTERP
-  static int counter_data_size_in_bytes() {
-    return cell_offset_in_bytes(counter_cell_count);
-  }
-
-  static void increment_count_no_overflow(DataLayout* layout) {
-    increment_uint_at_no_overflow(layout, count_off);
-  }
-
-  // Support counter decrementation at checkcast / subtype check failed.
-  static void decrement_count(DataLayout* layout) {
-    increment_uint_at_no_overflow(layout, count_off, -1);
-  }
-
-  static DataLayout* advance(DataLayout* layout) {
-    return (DataLayout*) (((address)layout) + (ssize_t)CounterData::counter_data_size_in_bytes());
-  }
-#endif // CC_INTERP
-
   void print_data_on(outputStream* st, const char* extra = NULL) const;
 };
 
@@ -728,20 +655,6 @@
     return cell_offset(displacement_off_set);
   }
 
-#ifdef CC_INTERP
-  static void increment_taken_count_no_overflow(DataLayout* layout) {
-    increment_uint_at_no_overflow(layout, taken_off_set);
-  }
-
-  static DataLayout* advance_taken(DataLayout* layout) {
-    return (DataLayout*) (((address)layout) + (ssize_t)int_at(layout, displacement_off_set));
-  }
-
-  static uint taken_count(DataLayout* layout) {
-    return (uint) uint_at(layout, taken_off_set);
-  }
-#endif // CC_INTERP
-
   // Specific initialization.
   void post_initialize(BytecodeStream* stream, MethodData* mdo);
 
@@ -1302,43 +1215,6 @@
   // GC support
   virtual void clean_weak_klass_links(bool always_clean);
 
-#ifdef CC_INTERP
-  static int receiver_type_data_size_in_bytes() {
-    return cell_offset_in_bytes(static_cell_count());
-  }
-
-  static Klass *receiver_unchecked(DataLayout* layout, uint row) {
-    Klass* recv = (Klass*)layout->cell_at(receiver_cell_index(row));
-    return recv;
-  }
-
-  static void increment_receiver_count_no_overflow(DataLayout* layout, Klass *rcvr) {
-    const int num_rows = row_limit();
-    // Receiver already exists?
-    for (int row = 0; row < num_rows; row++) {
-      if (receiver_unchecked(layout, row) == rcvr) {
-        increment_uint_at_no_overflow(layout, receiver_count_cell_index(row));
-        return;
-      }
-    }
-    // New receiver, find a free slot.
-    for (int row = 0; row < num_rows; row++) {
-      if (receiver_unchecked(layout, row) == NULL) {
-        set_intptr_at(layout, receiver_cell_index(row), (intptr_t)rcvr);
-        increment_uint_at_no_overflow(layout, receiver_count_cell_index(row));
-        return;
-      }
-    }
-    // Receiver did not match any saved receiver and there is no empty row for it.
-    // Increment total counter to indicate polymorphic case.
-    increment_count_no_overflow(layout);
-  }
-
-  static DataLayout* advance(DataLayout* layout) {
-    return (DataLayout*) (((address)layout) + (ssize_t)ReceiverTypeData::receiver_type_data_size_in_bytes());
-  }
-#endif // CC_INTERP
-
   void print_receiver_data_on(outputStream* st) const;
   void print_data_on(outputStream* st, const char* extra = NULL) const;
 };
@@ -1371,16 +1247,6 @@
     return cell_offset(static_cell_count());
   }
 
-#ifdef CC_INTERP
-  static int virtual_call_data_size_in_bytes() {
-    return cell_offset_in_bytes(static_cell_count());
-  }
-
-  static DataLayout* advance(DataLayout* layout) {
-    return (DataLayout*) (((address)layout) + (ssize_t)VirtualCallData::virtual_call_data_size_in_bytes());
-  }
-#endif // CC_INTERP
-
 #if INCLUDE_JVMCI
   static ByteSize method_offset(uint row) {
     return cell_offset(method_cell_index(row));
@@ -1658,10 +1524,6 @@
     return cell_offset(bci_displacement_cell_index(row));
   }
 
-#ifdef CC_INTERP
-  static DataLayout* advance(MethodData *md, int bci);
-#endif // CC_INTERP
-
   // Specific initialization.
   void post_initialize(BytecodeStream* stream, MethodData* mdo);
 
@@ -1726,20 +1588,6 @@
     return cell_offset(branch_cell_count);
   }
 
-#ifdef CC_INTERP
-  static int branch_data_size_in_bytes() {
-    return cell_offset_in_bytes(branch_cell_count);
-  }
-
-  static void increment_not_taken_count_no_overflow(DataLayout* layout) {
-    increment_uint_at_no_overflow(layout, not_taken_off_set);
-  }
-
-  static DataLayout* advance_not_taken(DataLayout* layout) {
-    return (DataLayout*) (((address)layout) + (ssize_t)BranchData::branch_data_size_in_bytes());
-  }
-#endif // CC_INTERP
-
   // Specific initialization.
   void post_initialize(BytecodeStream* stream, MethodData* mdo);
 
@@ -1779,20 +1627,6 @@
     set_int_at(aindex, value);
   }
 
-#ifdef CC_INTERP
-  // Static low level accessors for DataLayout with ArrayData's semantics.
-
-  static void increment_array_uint_at_no_overflow(DataLayout* layout, int index) {
-    int aindex = index + array_start_off_set;
-    increment_uint_at_no_overflow(layout, aindex);
-  }
-
-  static int array_int_at(DataLayout* layout, int index) {
-    int aindex = index + array_start_off_set;
-    return int_at(layout, aindex);
-  }
-#endif // CC_INTERP
-
   // Code generation support for subclasses.
   static ByteSize array_element_offset(int index) {
     return cell_offset(array_start_off_set + index);
@@ -1913,28 +1747,6 @@
     return in_ByteSize(relative_displacement_off_set) * cell_size;
   }
 
-#ifdef CC_INTERP
-  static void increment_count_no_overflow(DataLayout* layout, int index) {
-    if (index == -1) {
-      increment_array_uint_at_no_overflow(layout, default_count_off_set);
-    } else {
-      increment_array_uint_at_no_overflow(layout, case_array_start +
-                                                  index * per_case_cell_count +
-                                                  relative_count_off_set);
-    }
-  }
-
-  static DataLayout* advance(DataLayout* layout, int index) {
-    if (index == -1) {
-      return (DataLayout*) (((address)layout) + (ssize_t)array_int_at(layout, default_disaplacement_off_set));
-    } else {
-      return (DataLayout*) (((address)layout) + (ssize_t)array_int_at(layout, case_array_start +
-                                                                              index * per_case_cell_count +
-                                                                              relative_displacement_off_set));
-    }
-  }
-#endif // CC_INTERP
-
   // Specific initialization.
   void post_initialize(BytecodeStream* stream, MethodData* mdo);
 
@@ -2127,13 +1939,11 @@
 // adjusted in the event of a change in control flow.
 //
 
-CC_INTERP_ONLY(class BytecodeInterpreter;)
 class CleanExtraDataClosure;
 
 class MethodData : public Metadata {
   friend class VMStructs;
   friend class JVMCIVMStructs;
-  CC_INTERP_ONLY(friend class BytecodeInterpreter;)
 private:
   friend class ProfileData;
   friend class TypeEntriesAtCall;
--- a/src/hotspot/share/oops/objArrayKlass.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/oops/objArrayKlass.cpp	Thu May 31 13:04:30 2018 -0700
@@ -181,7 +181,7 @@
       THROW_OOP_0(Universe::out_of_memory_error_array_size());
     }
   } else {
-    THROW_0(vmSymbols::java_lang_NegativeArraySizeException());
+    THROW_MSG_0(vmSymbols::java_lang_NegativeArraySizeException(), err_msg("%d", length));
   }
 }
 
@@ -209,7 +209,7 @@
       for (int i = 0; i < rank - 1; ++i) {
         sizes += 1;
         if (*sizes < 0) {
-          THROW_0(vmSymbols::java_lang_NegativeArraySizeException());
+          THROW_MSG_0(vmSymbols::java_lang_NegativeArraySizeException(), err_msg("%d", *sizes));
         }
       }
     }
--- a/src/hotspot/share/oops/typeArrayKlass.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/oops/typeArrayKlass.cpp	Thu May 31 13:04:30 2018 -0700
@@ -116,7 +116,7 @@
       THROW_OOP_0(Universe::out_of_memory_error_array_size());
     }
   } else {
-    THROW_0(vmSymbols::java_lang_NegativeArraySizeException());
+    THROW_MSG_0(vmSymbols::java_lang_NegativeArraySizeException(), err_msg("%d", length));
   }
 }
 
--- a/src/hotspot/share/prims/jvmtiTagMap.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/prims/jvmtiTagMap.cpp	Thu May 31 13:04:30 2018 -0700
@@ -2577,7 +2577,7 @@
 
     jvmtiHeapReferenceKind kind = root_kind();
     if (kind == JVMTI_HEAP_REFERENCE_SYSTEM_CLASS) {
-      // SystemDictionary::always_strong_oops_do reports the application
+      // SystemDictionary::oops_do reports the application
       // class loader as a root. We want this root to be reported as
       // a root kind of "OTHER" rather than "SYSTEM_CLASS".
       if (!o->is_instance() || !InstanceKlass::cast(o->klass())->is_mirror_instance_klass()) {
@@ -3003,7 +3003,7 @@
 
   // Preloaded classes and loader from the system dictionary
   blk.set_kind(JVMTI_HEAP_REFERENCE_SYSTEM_CLASS);
-  SystemDictionary::always_strong_oops_do(&blk);
+  SystemDictionary::oops_do(&blk);
   ClassLoaderDataGraph::always_strong_oops_do(&blk, false);
   if (blk.stopped()) {
     return false;
--- a/src/hotspot/share/prims/whitebox.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/prims/whitebox.cpp	Thu May 31 13:04:30 2018 -0700
@@ -98,6 +98,7 @@
 #define CHECK_JNI_EXCEPTION_(env, value)                               \
   do {                                                                 \
     JavaThread* THREAD = JavaThread::thread_from_jni_environment(env); \
+    THREAD->clear_pending_jni_exception_check();                       \
     if (HAS_PENDING_EXCEPTION) {                                       \
       return(value);                                                   \
     }                                                                  \
@@ -106,6 +107,7 @@
 #define CHECK_JNI_EXCEPTION(env)                                       \
   do {                                                                 \
     JavaThread* THREAD = JavaThread::thread_from_jni_environment(env); \
+    THREAD->clear_pending_jni_exception_check();                       \
     if (HAS_PENDING_EXCEPTION) {                                       \
       return;                                                          \
     }                                                                  \
--- a/src/hotspot/share/runtime/arguments.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/runtime/arguments.cpp	Thu May 31 13:04:30 2018 -0700
@@ -3365,6 +3365,10 @@
   UNSUPPORTED_OPTION(TieredCompilation);
 #endif
 
+  if (!check_vm_args_consistency()) {
+    return JNI_ERR;
+  }
+
 #if INCLUDE_JVMCI
   if (EnableJVMCI &&
       !create_numbered_property("jdk.module.addmods", "jdk.internal.vm.ci", addmods_count++)) {
@@ -3372,10 +3376,6 @@
   }
 #endif
 
-  if (!check_vm_args_consistency()) {
-    return JNI_ERR;
-  }
-
 #if INCLUDE_JVMCI
   if (UseJVMCICompiler) {
     Compilation_mode = CompMode_server;
--- a/src/hotspot/share/runtime/flags/jvmFlag.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/runtime/flags/jvmFlag.cpp	Thu May 31 13:04:30 2018 -0700
@@ -1504,3 +1504,12 @@
   FREE_C_HEAP_ARRAY(JVMFlag*, array);
 }
 
+void JVMFlag::printError(bool verbose, const char* msg, ...) {
+  if (verbose) {
+    va_list listPointer;
+    va_start(listPointer, msg);
+    jio_vfprintf(defaultStream::error_stream(), msg, listPointer);
+    va_end(listPointer);
+  }
+}
+
--- a/src/hotspot/share/runtime/flags/jvmFlag.hpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/runtime/flags/jvmFlag.hpp	Thu May 31 13:04:30 2018 -0700
@@ -276,6 +276,7 @@
 
   // printRanges will print out flags type, name and range values as expected by -XX:+PrintFlagsRanges
   static void printFlags(outputStream* out, bool withComments, bool printRanges = false, bool skipDefaults = false);
+  static void printError(bool verbose, const char* msg, ...);
 
   static void verify() PRODUCT_RETURN;
 };
--- a/src/hotspot/share/runtime/flags/jvmFlagConstraintsCompiler.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/runtime/flags/jvmFlagConstraintsCompiler.cpp	Thu May 31 13:04:30 2018 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2017, 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
@@ -31,17 +31,15 @@
 #include "runtime/arguments.hpp"
 #include "runtime/flags/jvmFlag.hpp"
 #include "runtime/flags/jvmFlagConstraintsCompiler.hpp"
-#include "runtime/flags/jvmFlagRangeList.hpp"
 #include "runtime/globals.hpp"
 #include "runtime/globals_extension.hpp"
-#include "utilities/defaultStream.hpp"
 
 JVMFlag::Error AliasLevelConstraintFunc(intx value, bool verbose) {
   if ((value <= 1) && (Arguments::mode() == Arguments::_comp || Arguments::mode() == Arguments::_mixed)) {
-    CommandLineError::print(verbose,
-                            "AliasLevel (" INTX_FORMAT ") is not "
-                            "compatible with -Xcomp or -Xmixed\n",
-                            value);
+    JVMFlag::printError(verbose,
+                        "AliasLevel (" INTX_FORMAT ") is not "
+                        "compatible with -Xcomp or -Xmixed\n",
+                        value);
     return JVMFlag::VIOLATES_CONSTRAINT;
   } else {
     return JVMFlag::SUCCESS;
@@ -82,10 +80,10 @@
   min_number_of_compiler_threads = MIN2(min_number_of_compiler_threads, CI_COMPILER_COUNT);
 
   if (value < (intx)min_number_of_compiler_threads) {
-    CommandLineError::print(verbose,
-                            "CICompilerCount (" INTX_FORMAT ") must be "
-                            "at least %d \n",
-                            value, min_number_of_compiler_threads);
+    JVMFlag::printError(verbose,
+                        "CICompilerCount (" INTX_FORMAT ") must be "
+                        "at least %d \n",
+                        value, min_number_of_compiler_threads);
     return JVMFlag::VIOLATES_CONSTRAINT;
   } else {
     return JVMFlag::SUCCESS;
@@ -94,10 +92,10 @@
 
 JVMFlag::Error AllocatePrefetchDistanceConstraintFunc(intx value, bool verbose) {
   if (value < 0 || value > 512) {
-    CommandLineError::print(verbose,
-                            "AllocatePrefetchDistance (" INTX_FORMAT ") must be "
-                            "between 0 and " INTX_FORMAT "\n",
-                            AllocatePrefetchDistance, 512);
+    JVMFlag::printError(verbose,
+                        "AllocatePrefetchDistance (" INTX_FORMAT ") must be "
+                        "between 0 and " INTX_FORMAT "\n",
+                        AllocatePrefetchDistance, 512);
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
 
@@ -107,9 +105,9 @@
 JVMFlag::Error AllocatePrefetchStepSizeConstraintFunc(intx value, bool verbose) {
   if (AllocatePrefetchStyle == 3) {
     if (value % wordSize != 0) {
-      CommandLineError::print(verbose,
-                              "AllocatePrefetchStepSize (" INTX_FORMAT ") must be multiple of %d\n",
-                              value, wordSize);
+      JVMFlag::printError(verbose,
+                          "AllocatePrefetchStepSize (" INTX_FORMAT ") must be multiple of %d\n",
+                          value, wordSize);
       return JVMFlag::VIOLATES_CONSTRAINT;
     }
   }
@@ -124,9 +122,9 @@
   max_value = 3;
 #endif
   if (value < 0 || value > max_value) {
-    CommandLineError::print(verbose,
-                            "AllocatePrefetchInstr (" INTX_FORMAT ") must be "
-                            "between 0 and " INTX_FORMAT "\n", value, max_value);
+    JVMFlag::printError(verbose,
+                        "AllocatePrefetchInstr (" INTX_FORMAT ") must be "
+                        "between 0 and " INTX_FORMAT "\n", value, max_value);
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
 
@@ -135,11 +133,11 @@
 
 JVMFlag::Error CompileThresholdConstraintFunc(intx value, bool verbose) {
   if (value < 0 || value > INT_MAX >> InvocationCounter::count_shift) {
-    CommandLineError::print(verbose,
-                            "CompileThreshold (" INTX_FORMAT ") "
-                            "must be between 0 and %d\n",
-                            value,
-                            INT_MAX >> InvocationCounter::count_shift);
+    JVMFlag::printError(verbose,
+                        "CompileThreshold (" INTX_FORMAT ") "
+                        "must be between 0 and %d\n",
+                        value,
+                        INT_MAX >> InvocationCounter::count_shift);
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
 
@@ -150,10 +148,10 @@
   int backward_branch_limit;
   if (ProfileInterpreter) {
     if (OnStackReplacePercentage < InterpreterProfilePercentage) {
-      CommandLineError::print(verbose,
-                              "OnStackReplacePercentage (" INTX_FORMAT ") must be "
-                              "larger than InterpreterProfilePercentage (" INTX_FORMAT ")\n",
-                              OnStackReplacePercentage, InterpreterProfilePercentage);
+      JVMFlag::printError(verbose,
+                          "OnStackReplacePercentage (" INTX_FORMAT ") must be "
+                          "larger than InterpreterProfilePercentage (" INTX_FORMAT ")\n",
+                          OnStackReplacePercentage, InterpreterProfilePercentage);
       return JVMFlag::VIOLATES_CONSTRAINT;
     }
 
@@ -161,20 +159,20 @@
                             << InvocationCounter::count_shift;
 
     if (backward_branch_limit < 0) {
-      CommandLineError::print(verbose,
-                              "CompileThreshold * (InterpreterProfilePercentage - OnStackReplacePercentage) / 100 = "
-                              INTX_FORMAT " "
-                              "must be between 0 and " INTX_FORMAT ", try changing "
-                              "CompileThreshold, InterpreterProfilePercentage, and/or OnStackReplacePercentage\n",
-                              (CompileThreshold * (OnStackReplacePercentage - InterpreterProfilePercentage)) / 100,
-                              INT_MAX >> InvocationCounter::count_shift);
+      JVMFlag::printError(verbose,
+                          "CompileThreshold * (InterpreterProfilePercentage - OnStackReplacePercentage) / 100 = "
+                          INTX_FORMAT " "
+                          "must be between 0 and " INTX_FORMAT ", try changing "
+                          "CompileThreshold, InterpreterProfilePercentage, and/or OnStackReplacePercentage\n",
+                          (CompileThreshold * (OnStackReplacePercentage - InterpreterProfilePercentage)) / 100,
+                          INT_MAX >> InvocationCounter::count_shift);
       return JVMFlag::VIOLATES_CONSTRAINT;
     }
   } else {
     if (OnStackReplacePercentage < 0 ) {
-      CommandLineError::print(verbose,
-                              "OnStackReplacePercentage (" INTX_FORMAT ") must be "
-                              "non-negative\n", OnStackReplacePercentage);
+      JVMFlag::printError(verbose,
+                          "OnStackReplacePercentage (" INTX_FORMAT ") must be "
+                          "non-negative\n", OnStackReplacePercentage);
       return JVMFlag::VIOLATES_CONSTRAINT;
     }
 
@@ -182,12 +180,12 @@
                             << InvocationCounter::count_shift;
 
     if (backward_branch_limit < 0) {
-      CommandLineError::print(verbose,
-                              "CompileThreshold * OnStackReplacePercentage / 100 = " INTX_FORMAT " "
-                              "must be between 0 and " INTX_FORMAT ", try changing "
-                              "CompileThreshold and/or OnStackReplacePercentage\n",
-                              (CompileThreshold * OnStackReplacePercentage) / 100,
-                              INT_MAX >> InvocationCounter::count_shift);
+      JVMFlag::printError(verbose,
+                          "CompileThreshold * OnStackReplacePercentage / 100 = " INTX_FORMAT " "
+                          "must be between 0 and " INTX_FORMAT ", try changing "
+                          "CompileThreshold and/or OnStackReplacePercentage\n",
+                          (CompileThreshold * OnStackReplacePercentage) / 100,
+                          INT_MAX >> InvocationCounter::count_shift);
       return JVMFlag::VIOLATES_CONSTRAINT;
     }
   }
@@ -196,29 +194,29 @@
 
 JVMFlag::Error CodeCacheSegmentSizeConstraintFunc(uintx value, bool verbose) {
   if (CodeCacheSegmentSize < (uintx)CodeEntryAlignment) {
-    CommandLineError::print(verbose,
-                            "CodeCacheSegmentSize  (" UINTX_FORMAT ") must be "
-                            "larger than or equal to CodeEntryAlignment (" INTX_FORMAT ") "
-                            "to align entry points\n",
-                            CodeCacheSegmentSize, CodeEntryAlignment);
+    JVMFlag::printError(verbose,
+                        "CodeCacheSegmentSize  (" UINTX_FORMAT ") must be "
+                        "larger than or equal to CodeEntryAlignment (" INTX_FORMAT ") "
+                        "to align entry points\n",
+                        CodeCacheSegmentSize, CodeEntryAlignment);
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
 
   if (CodeCacheSegmentSize < sizeof(jdouble)) {
-    CommandLineError::print(verbose,
-                            "CodeCacheSegmentSize  (" UINTX_FORMAT ") must be "
-                            "at least " SIZE_FORMAT " to align constants\n",
-                            CodeCacheSegmentSize, sizeof(jdouble));
+    JVMFlag::printError(verbose,
+                        "CodeCacheSegmentSize  (" UINTX_FORMAT ") must be "
+                        "at least " SIZE_FORMAT " to align constants\n",
+                        CodeCacheSegmentSize, sizeof(jdouble));
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
 
 #ifdef COMPILER2
   if (CodeCacheSegmentSize < (uintx)OptoLoopAlignment) {
-    CommandLineError::print(verbose,
-                            "CodeCacheSegmentSize  (" UINTX_FORMAT ") must be "
-                            "larger than or equal to OptoLoopAlignment (" INTX_FORMAT ") "
-                            "to align inner loops\n",
-                            CodeCacheSegmentSize, OptoLoopAlignment);
+    JVMFlag::printError(verbose,
+                        "CodeCacheSegmentSize  (" UINTX_FORMAT ") must be "
+                        "larger than or equal to OptoLoopAlignment (" INTX_FORMAT ") "
+                        "to align inner loops\n",
+                        CodeCacheSegmentSize, OptoLoopAlignment);
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
 #endif
@@ -230,11 +228,11 @@
 #ifdef SOLARIS
   if ((value < MinimumPriority || value > MaximumPriority) &&
       (value != -1) && (value != -FXCriticalPriority)) {
-    CommandLineError::print(verbose,
-                            "CompileThreadPriority (" INTX_FORMAT ") must be "
-                            "between %d and %d inclusively or -1 (means no change) "
-                            "or %d (special value for critical thread class/priority)\n",
-                            value, MinimumPriority, MaximumPriority, -FXCriticalPriority);
+    JVMFlag::printError(verbose,
+                        "CompileThreadPriority (" INTX_FORMAT ") must be "
+                        "between %d and %d inclusively or -1 (means no change) "
+                        "or %d (special value for critical thread class/priority)\n",
+                        value, MinimumPriority, MaximumPriority, -FXCriticalPriority);
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
 #endif
@@ -245,25 +243,25 @@
 JVMFlag::Error CodeEntryAlignmentConstraintFunc(intx value, bool verbose) {
 #ifdef SPARC
   if (CodeEntryAlignment % relocInfo::addr_unit() != 0) {
-    CommandLineError::print(verbose,
-                            "CodeEntryAlignment (" INTX_FORMAT ") must be "
-                            "multiple of NOP size\n", CodeEntryAlignment);
+    JVMFlag::printError(verbose,
+                        "CodeEntryAlignment (" INTX_FORMAT ") must be "
+                        "multiple of NOP size\n", CodeEntryAlignment);
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
 #endif
 
   if (!is_power_of_2(value)) {
-    CommandLineError::print(verbose,
-                            "CodeEntryAlignment (" INTX_FORMAT ") must be "
-                            "a power of two\n", CodeEntryAlignment);
+    JVMFlag::printError(verbose,
+                        "CodeEntryAlignment (" INTX_FORMAT ") must be "
+                        "a power of two\n", CodeEntryAlignment);
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
 
   if (CodeEntryAlignment < 16) {
-      CommandLineError::print(verbose,
-                              "CodeEntryAlignment (" INTX_FORMAT ") must be "
-                              "greater than or equal to %d\n",
-                              CodeEntryAlignment, 16);
+      JVMFlag::printError(verbose,
+                          "CodeEntryAlignment (" INTX_FORMAT ") must be "
+                          "greater than or equal to %d\n",
+                          CodeEntryAlignment, 16);
       return JVMFlag::VIOLATES_CONSTRAINT;
   }
 
@@ -272,20 +270,20 @@
 
 JVMFlag::Error OptoLoopAlignmentConstraintFunc(intx value, bool verbose) {
   if (!is_power_of_2(value)) {
-    CommandLineError::print(verbose,
-                            "OptoLoopAlignment (" INTX_FORMAT ") "
-                            "must be a power of two\n",
-                            value);
+    JVMFlag::printError(verbose,
+                        "OptoLoopAlignment (" INTX_FORMAT ") "
+                        "must be a power of two\n",
+                        value);
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
 
   // Relevant on ppc, s390, sparc. Will be optimized where
   // addr_unit() == 1.
   if (OptoLoopAlignment % relocInfo::addr_unit() != 0) {
-    CommandLineError::print(verbose,
-                            "OptoLoopAlignment (" INTX_FORMAT ") must be "
-                            "multiple of NOP size (%d)\n",
-                            value, relocInfo::addr_unit());
+    JVMFlag::printError(verbose,
+                        "OptoLoopAlignment (" INTX_FORMAT ") must be "
+                        "multiple of NOP size (%d)\n",
+                        value, relocInfo::addr_unit());
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
 
@@ -294,9 +292,9 @@
 
 JVMFlag::Error ArraycopyDstPrefetchDistanceConstraintFunc(uintx value, bool verbose) {
   if (value >= 4032) {
-    CommandLineError::print(verbose,
-                            "ArraycopyDstPrefetchDistance (" UINTX_FORMAT ") must be"
-                            "between 0 and 4031\n", value);
+    JVMFlag::printError(verbose,
+                        "ArraycopyDstPrefetchDistance (" UINTX_FORMAT ") must be"
+                        "between 0 and 4031\n", value);
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
 
@@ -305,9 +303,9 @@
 
 JVMFlag::Error ArraycopySrcPrefetchDistanceConstraintFunc(uintx value, bool verbose) {
   if (value >= 4032) {
-    CommandLineError::print(verbose,
-                            "ArraycopySrcPrefetchDistance (" UINTX_FORMAT ") must be"
-                            "between 0 and 4031\n", value);
+    JVMFlag::printError(verbose,
+                        "ArraycopySrcPrefetchDistance (" UINTX_FORMAT ") must be"
+                        "between 0 and 4031\n", value);
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
 
@@ -317,9 +315,9 @@
 JVMFlag::Error TypeProfileLevelConstraintFunc(uintx value, bool verbose) {
   for (int i = 0; i < 3; i++) {
     if (value % 10 > 2) {
-      CommandLineError::print(verbose,
-                              "Invalid value (" UINTX_FORMAT ") "
-                              "in TypeProfileLevel at position %d\n", value, i);
+      JVMFlag::printError(verbose,
+                          "Invalid value (" UINTX_FORMAT ") "
+                          "in TypeProfileLevel at position %d\n", value, i);
       return JVMFlag::VIOLATES_CONSTRAINT;
     }
     value = value / 10;
@@ -339,26 +337,26 @@
 #ifdef COMPILER2
 JVMFlag::Error InteriorEntryAlignmentConstraintFunc(intx value, bool verbose) {
   if (InteriorEntryAlignment > CodeEntryAlignment) {
-    CommandLineError::print(verbose,
-                           "InteriorEntryAlignment (" INTX_FORMAT ") must be "
-                           "less than or equal to CodeEntryAlignment (" INTX_FORMAT ")\n",
-                           InteriorEntryAlignment, CodeEntryAlignment);
+    JVMFlag::printError(verbose,
+                       "InteriorEntryAlignment (" INTX_FORMAT ") must be "
+                       "less than or equal to CodeEntryAlignment (" INTX_FORMAT ")\n",
+                       InteriorEntryAlignment, CodeEntryAlignment);
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
 
 #ifdef SPARC
   if (InteriorEntryAlignment % relocInfo::addr_unit() != 0) {
-    CommandLineError::print(verbose,
-                            "InteriorEntryAlignment (" INTX_FORMAT ") must be "
-                            "multiple of NOP size\n");
+    JVMFlag::printError(verbose,
+                        "InteriorEntryAlignment (" INTX_FORMAT ") must be "
+                        "multiple of NOP size\n");
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
 #endif
 
   if (!is_power_of_2(value)) {
-     CommandLineError::print(verbose,
-                             "InteriorEntryAlignment (" INTX_FORMAT ") must be "
-                             "a power of two\n", InteriorEntryAlignment);
+     JVMFlag::printError(verbose,
+                         "InteriorEntryAlignment (" INTX_FORMAT ") must be "
+                         "a power of two\n", InteriorEntryAlignment);
      return JVMFlag::VIOLATES_CONSTRAINT;
    }
 
@@ -370,10 +368,10 @@
 #endif
 
   if (InteriorEntryAlignment < minimum_alignment) {
-    CommandLineError::print(verbose,
-                            "InteriorEntryAlignment (" INTX_FORMAT ") must be "
-                            "greater than or equal to %d\n",
-                            InteriorEntryAlignment, minimum_alignment);
+    JVMFlag::printError(verbose,
+                        "InteriorEntryAlignment (" INTX_FORMAT ") must be "
+                        "greater than or equal to %d\n",
+                        InteriorEntryAlignment, minimum_alignment);
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
 
@@ -382,10 +380,10 @@
 
 JVMFlag::Error NodeLimitFudgeFactorConstraintFunc(intx value, bool verbose) {
   if (value < MaxNodeLimit * 2 / 100 || value > MaxNodeLimit * 40 / 100) {
-    CommandLineError::print(verbose,
-                            "NodeLimitFudgeFactor must be between 2%% and 40%% "
-                            "of MaxNodeLimit (" INTX_FORMAT ")\n",
-                            MaxNodeLimit);
+    JVMFlag::printError(verbose,
+                        "NodeLimitFudgeFactor must be between 2%% and 40%% "
+                        "of MaxNodeLimit (" INTX_FORMAT ")\n",
+                        MaxNodeLimit);
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
 
@@ -396,10 +394,10 @@
 JVMFlag::Error RTMTotalCountIncrRateConstraintFunc(int value, bool verbose) {
 #if INCLUDE_RTM_OPT
   if (UseRTMLocking && !is_power_of_2(RTMTotalCountIncrRate)) {
-    CommandLineError::print(verbose,
-                            "RTMTotalCountIncrRate (" INTX_FORMAT
-                            ") must be a power of 2, resetting it to 64\n",
-                            RTMTotalCountIncrRate);
+    JVMFlag::printError(verbose,
+                        "RTMTotalCountIncrRate (" INTX_FORMAT
+                        ") must be a power of 2, resetting it to 64\n",
+                        RTMTotalCountIncrRate);
     FLAG_SET_DEFAULT(RTMTotalCountIncrRate, 64);
   }
 #endif
--- a/src/hotspot/share/runtime/flags/jvmFlagConstraintsRuntime.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/runtime/flags/jvmFlagConstraintsRuntime.cpp	Thu May 31 13:04:30 2018 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2017, 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
@@ -26,26 +26,24 @@
 #include "runtime/arguments.hpp"
 #include "runtime/flags/jvmFlag.hpp"
 #include "runtime/flags/jvmFlagConstraintsRuntime.hpp"
-#include "runtime/flags/jvmFlagRangeList.hpp"
 #include "runtime/globals.hpp"
 #include "runtime/safepointMechanism.hpp"
 #include "runtime/task.hpp"
-#include "utilities/defaultStream.hpp"
 
 JVMFlag::Error ObjectAlignmentInBytesConstraintFunc(intx value, bool verbose) {
   if (!is_power_of_2(value)) {
-    CommandLineError::print(verbose,
-                            "ObjectAlignmentInBytes (" INTX_FORMAT ") must be "
-                            "power of 2\n",
-                            value);
+    JVMFlag::printError(verbose,
+                        "ObjectAlignmentInBytes (" INTX_FORMAT ") must be "
+                        "power of 2\n",
+                        value);
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
   // In case page size is very small.
   if (value >= (intx)os::vm_page_size()) {
-    CommandLineError::print(verbose,
-                            "ObjectAlignmentInBytes (" INTX_FORMAT ") must be "
-                            "less than page size (" INTX_FORMAT ")\n",
-                            value, (intx)os::vm_page_size());
+    JVMFlag::printError(verbose,
+                        "ObjectAlignmentInBytes (" INTX_FORMAT ") must be "
+                        "less than page size (" INTX_FORMAT ")\n",
+                        value, (intx)os::vm_page_size());
     return JVMFlag::VIOLATES_CONSTRAINT;
   }
   return JVMFlag::SUCCESS;
@@ -55,10 +53,10 @@
 // It is sufficient to check against the largest type size.
 JVMFlag::Error ContendedPaddingWidthConstraintFunc(intx value, bool verbose) {
   if ((value % BytesPerLong) != 0) {
-    CommandLineError::print(verbose,
-                            "ContendedPaddingWidth (" INTX_FORMAT ") must be "
-                            "a multiple of %d\n",
-                            value, BytesPerLong);
+    JVMFlag::printError(verbose,
+                        "ContendedPaddingWidth (" INTX_FORMAT ") must be "
+                        "a multiple of %d\n",
+                        value, BytesPerLong);
     return JVMFlag::VIOLATES_CONSTRAINT;
   } else {
     return JVMFlag::SUCCESS;
@@ -67,10 +65,10 @@
 
 JVMFlag::Error BiasedLockingBulkRebiasThresholdFunc(intx value, bool verbose) {
   if (value > BiasedLockingBulkRevokeThreshold) {
-    CommandLineError::print(verbose,
-                            "BiasedLockingBulkRebiasThreshold (" INTX_FORMAT ") must be "
-                            "less than or equal to BiasedLockingBulkRevokeThreshold (" INTX_FORMAT ")\n",
-                            value, BiasedLockingBulkRevokeThreshold);
+    JVMFlag::printError(verbose,
+                        "BiasedLockingBulkRebiasThreshold (" INTX_FORMAT ") must be "
+                        "less than or equal to BiasedLockingBulkRevokeThreshold (" INTX_FORMAT ")\n",
+                        value, BiasedLockingBulkRevokeThreshold);
     return JVMFlag::VIOLATES_CONSTRAINT;
   } else {
     return JVMFlag::SUCCESS;
@@ -79,10 +77,10 @@
 
 JVMFlag::Error BiasedLockingStartupDelayFunc(intx value, bool verbose) {
   if ((value % PeriodicTask::interval_gran) != 0) {
-    CommandLineError::print(verbose,
-                            "BiasedLockingStartupDelay (" INTX_FORMAT ") must be "
-                            "evenly divisible by PeriodicTask::interval_gran (" INTX_FORMAT ")\n",
-                            value, PeriodicTask::interval_gran);
+    JVMFlag::printError(verbose,
+                        "BiasedLockingStartupDelay (" INTX_FORMAT ") must be "
+                        "evenly divisible by PeriodicTask::interval_gran (" INTX_FORMAT ")\n",
+                        value, PeriodicTask::interval_gran);
     return JVMFlag::VIOLATES_CONSTRAINT;
   } else {
     return JVMFlag::SUCCESS;
@@ -91,17 +89,17 @@
 
 JVMFlag::Error BiasedLockingBulkRevokeThresholdFunc(intx value, bool verbose) {
   if (value < BiasedLockingBulkRebiasThreshold) {
-    CommandLineError::print(verbose,
-                            "BiasedLockingBulkRevokeThreshold (" INTX_FORMAT ") must be "
-                            "greater than or equal to BiasedLockingBulkRebiasThreshold (" INTX_FORMAT ")\n",
-                            value, BiasedLockingBulkRebiasThreshold);
+    JVMFlag::printError(verbose,
+                        "BiasedLockingBulkRevokeThreshold (" INTX_FORMAT ") must be "
+                        "greater than or equal to BiasedLockingBulkRebiasThreshold (" INTX_FORMAT ")\n",
+                        value, BiasedLockingBulkRebiasThreshold);
     return JVMFlag::VIOLATES_CONSTRAINT;
   } else if ((double)value/(double)BiasedLockingDecayTime > 0.1) {
-    CommandLineError::print(verbose,
-                            "The ratio of BiasedLockingBulkRevokeThreshold (" INTX_FORMAT ")"
-                            " to BiasedLockingDecayTime (" INTX_FORMAT ") must be "
-                            "less than or equal to 0.1\n",
-                            value, BiasedLockingBulkRebiasThreshold);
+    JVMFlag::printError(verbose,
+                        "The ratio of BiasedLockingBulkRevokeThreshold (" INTX_FORMAT ")"
+                        " to BiasedLockingDecayTime (" INTX_FORMAT ") must be "
+                        "less than or equal to 0.1\n",
+                        value, BiasedLockingBulkRebiasThreshold);
     return JVMFlag::VIOLATES_CONSTRAINT;
   } else {
     return JVMFlag::SUCCESS;
@@ -110,11 +108,11 @@
 
 JVMFlag::Error BiasedLockingDecayTimeFunc(intx value, bool verbose) {
   if (BiasedLockingBulkRebiasThreshold/(double)value > 0.1) {
-    CommandLineError::print(verbose,
-                            "The ratio of BiasedLockingBulkRebiasThreshold (" INTX_FORMAT ")"
-                            " to BiasedLockingDecayTime (" INTX_FORMAT ") must be "
-                            "less than or equal to 0.1\n",
-                            BiasedLockingBulkRebiasThreshold, value);
+    JVMFlag::printError(verbose,
+                        "The ratio of BiasedLockingBulkRebiasThreshold (" INTX_FORMAT ")"
+                        " to BiasedLockingDecayTime (" INTX_FORMAT ") must be "
+                        "less than or equal to 0.1\n",
+                        BiasedLockingBulkRebiasThreshold, value);
     return JVMFlag::VIOLATES_CONSTRAINT;
   } else {
     return JVMFlag::SUCCESS;
@@ -123,10 +121,10 @@
 
 JVMFlag::Error PerfDataSamplingIntervalFunc(intx value, bool verbose) {
   if ((value % PeriodicTask::interval_gran != 0)) {
-    CommandLineError::print(verbose,
-                            "PerfDataSamplingInterval (" INTX_FORMAT ") must be "
-                            "evenly divisible by PeriodicTask::interval_gran (" INTX_FORMAT ")\n",
-                            value, PeriodicTask::interval_gran);
+    JVMFlag::printError(verbose,
+                        "PerfDataSamplingInterval (" INTX_FORMAT ") must be "
+                        "evenly divisible by PeriodicTask::interval_gran (" INTX_FORMAT ")\n",
+                        value, PeriodicTask::interval_gran);
     return JVMFlag::VIOLATES_CONSTRAINT;
   } else {
     return JVMFlag::SUCCESS;
@@ -136,7 +134,7 @@
 JVMFlag::Error ThreadLocalHandshakesConstraintFunc(bool value, bool verbose) {
   if (value) {
     if (!SafepointMechanism::supports_thread_local_poll()) {
-      CommandLineError::print(verbose, "ThreadLocalHandshakes not yet supported on this platform\n");
+      JVMFlag::printError(verbose, "ThreadLocalHandshakes not yet supported on this platform\n");
       return JVMFlag::VIOLATES_CONSTRAINT;
     }
   }
--- a/src/hotspot/share/runtime/flags/jvmFlagRangeList.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/runtime/flags/jvmFlagRangeList.cpp	Thu May 31 13:04:30 2018 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2017, 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
@@ -35,18 +35,8 @@
 #include "runtime/globals_extension.hpp"
 #include "runtime/os.hpp"
 #include "runtime/task.hpp"
-#include "utilities/defaultStream.hpp"
 #include "utilities/macros.hpp"
 
-void CommandLineError::print(bool verbose, const char* msg, ...) {
-  if (verbose) {
-    va_list listPointer;
-    va_start(listPointer, msg);
-    jio_vfprintf(defaultStream::error_stream(), msg, listPointer);
-    va_end(listPointer);
-  }
-}
-
 class JVMFlagRange_int : public JVMFlagRange {
   int _min;
   int _max;
@@ -63,10 +53,10 @@
 
   JVMFlag::Error check_int(int value, bool verbose = true) {
     if ((value < _min) || (value > _max)) {
-      CommandLineError::print(verbose,
-                              "int %s=%d is outside the allowed range "
-                              "[ %d ... %d ]\n",
-                              name(), value, _min, _max);
+      JVMFlag::printError(verbose,
+                          "int %s=%d is outside the allowed range "
+                          "[ %d ... %d ]\n",
+                          name(), value, _min, _max);
       return JVMFlag::OUT_OF_BOUNDS;
     } else {
       return JVMFlag::SUCCESS;
@@ -93,10 +83,10 @@
 
   JVMFlag::Error check_intx(intx value, bool verbose = true) {
     if ((value < _min) || (value > _max)) {
-      CommandLineError::print(verbose,
-                              "intx %s=" INTX_FORMAT " is outside the allowed range "
-                              "[ " INTX_FORMAT " ... " INTX_FORMAT " ]\n",
-                              name(), value, _min, _max);
+      JVMFlag::printError(verbose,
+                          "intx %s=" INTX_FORMAT " is outside the allowed range "
+                          "[ " INTX_FORMAT " ... " INTX_FORMAT " ]\n",
+                          name(), value, _min, _max);
       return JVMFlag::OUT_OF_BOUNDS;
     } else {
       return JVMFlag::SUCCESS;
@@ -124,10 +114,10 @@
 
   JVMFlag::Error check_uint(uint value, bool verbose = true) {
     if ((value < _min) || (value > _max)) {
-      CommandLineError::print(verbose,
-                              "uint %s=%u is outside the allowed range "
-                              "[ %u ... %u ]\n",
-                              name(), value, _min, _max);
+      JVMFlag::printError(verbose,
+                          "uint %s=%u is outside the allowed range "
+                          "[ %u ... %u ]\n",
+                          name(), value, _min, _max);
       return JVMFlag::OUT_OF_BOUNDS;
     } else {
       return JVMFlag::SUCCESS;
@@ -155,10 +145,10 @@
 
   JVMFlag::Error check_uintx(uintx value, bool verbose = true) {
     if ((value < _min) || (value > _max)) {
-      CommandLineError::print(verbose,
-                              "uintx %s=" UINTX_FORMAT " is outside the allowed range "
-                              "[ " UINTX_FORMAT " ... " UINTX_FORMAT " ]\n",
-                              name(), value, _min, _max);
+      JVMFlag::printError(verbose,
+                          "uintx %s=" UINTX_FORMAT " is outside the allowed range "
+                          "[ " UINTX_FORMAT " ... " UINTX_FORMAT " ]\n",
+                          name(), value, _min, _max);
       return JVMFlag::OUT_OF_BOUNDS;
     } else {
       return JVMFlag::SUCCESS;
@@ -186,10 +176,10 @@
 
   JVMFlag::Error check_uint64_t(uint64_t value, bool verbose = true) {
     if ((value < _min) || (value > _max)) {
-      CommandLineError::print(verbose,
-                              "uint64_t %s=" UINT64_FORMAT " is outside the allowed range "
-                              "[ " UINT64_FORMAT " ... " UINT64_FORMAT " ]\n",
-                              name(), value, _min, _max);
+      JVMFlag::printError(verbose,
+                          "uint64_t %s=" UINT64_FORMAT " is outside the allowed range "
+                          "[ " UINT64_FORMAT " ... " UINT64_FORMAT " ]\n",
+                          name(), value, _min, _max);
       return JVMFlag::OUT_OF_BOUNDS;
     } else {
       return JVMFlag::SUCCESS;
@@ -217,10 +207,10 @@
 
   JVMFlag::Error check_size_t(size_t value, bool verbose = true) {
     if ((value < _min) || (value > _max)) {
-      CommandLineError::print(verbose,
-                              "size_t %s=" SIZE_FORMAT " is outside the allowed range "
-                              "[ " SIZE_FORMAT " ... " SIZE_FORMAT " ]\n",
-                              name(), value, _min, _max);
+      JVMFlag::printError(verbose,
+                          "size_t %s=" SIZE_FORMAT " is outside the allowed range "
+                          "[ " SIZE_FORMAT " ... " SIZE_FORMAT " ]\n",
+                          name(), value, _min, _max);
       return JVMFlag::OUT_OF_BOUNDS;
     } else {
       return JVMFlag::SUCCESS;
@@ -248,10 +238,10 @@
 
   JVMFlag::Error check_double(double value, bool verbose = true) {
     if ((value < _min) || (value > _max)) {
-      CommandLineError::print(verbose,
-                              "double %s=%f is outside the allowed range "
-                              "[ %f ... %f ]\n",
-                              name(), value, _min, _max);
+      JVMFlag::printError(verbose,
+                          "double %s=%f is outside the allowed range "
+                          "[ %f ... %f ]\n",
+                          name(), value, _min, _max);
       return JVMFlag::OUT_OF_BOUNDS;
     } else {
       return JVMFlag::SUCCESS;
@@ -432,7 +422,6 @@
 }
 
 bool JVMFlagRangeList::check_ranges() {
-  // Check ranges.
   bool status = true;
   for (int i=0; i<length(); i++) {
     JVMFlagRange* range = at(i);
--- a/src/hotspot/share/runtime/flags/jvmFlagRangeList.hpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/runtime/flags/jvmFlagRangeList.hpp	Thu May 31 13:04:30 2018 -0700
@@ -39,11 +39,6 @@
  * then we need to use constraint instead.
  */
 
-class CommandLineError : public AllStatic {
-public:
-  static void print(bool verbose, const char* msg, ...);
-};
-
 class JVMFlagRange : public CHeapObj<mtArguments> {
 private:
   const char* _name;
--- a/src/hotspot/share/runtime/globals.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/runtime/globals.cpp	Thu May 31 13:04:30 2018 -0700
@@ -32,7 +32,6 @@
 #include "runtime/globals_extension.hpp"
 #include "runtime/flags/jvmFlagConstraintList.hpp"
 #include "runtime/flags/jvmFlagWriteableList.hpp"
-#include "runtime/flags/jvmFlagRangeList.hpp"
 #include "runtime/os.hpp"
 #include "runtime/sharedRuntime.hpp"
 #include "utilities/defaultStream.hpp"
--- a/src/hotspot/share/runtime/mutex.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/runtime/mutex.cpp	Thu May 31 13:04:30 2018 -0700
@@ -903,7 +903,7 @@
   }
 #endif // CHECK_UNHANDLED_OOPS
 
-  debug_only(check_prelock_state(Self));
+  debug_only(check_prelock_state(Self, StrictSafepointChecks));
   assert(_owner != Self, "invariant");
   assert(_OnDeck != Self->_MutexEvent, "invariant");
 
@@ -971,7 +971,7 @@
 
 bool Monitor::try_lock() {
   Thread * const Self = Thread::current();
-  debug_only(check_prelock_state(Self));
+  debug_only(check_prelock_state(Self, false));
   // assert(!thread->is_inside_signal_handler(), "don't lock inside signal handler");
 
   // Special case, where all Java threads are stopped.
@@ -1381,10 +1381,10 @@
 
 
 // Factored out common sanity checks for locking mutex'es. Used by lock() and try_lock()
-void Monitor::check_prelock_state(Thread *thread) {
-  assert((!thread->is_Java_thread() || ((JavaThread *)thread)->thread_state() == _thread_in_vm)
-         || rank() == Mutex::special, "wrong thread state for using locks");
-  if (StrictSafepointChecks) {
+void Monitor::check_prelock_state(Thread *thread, bool safepoint_check) {
+  if (safepoint_check) {
+    assert((!thread->is_Java_thread() || ((JavaThread *)thread)->thread_state() == _thread_in_vm)
+           || rank() == Mutex::special, "wrong thread state for using locks");
     if (thread->is_VM_thread() && !allow_vm_block()) {
       fatal("VM thread using lock %s (not allowed to block on)", name());
     }
--- a/src/hotspot/share/runtime/mutex.hpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/runtime/mutex.hpp	Thu May 31 13:04:30 2018 -0700
@@ -144,7 +144,7 @@
 #endif
 
   void set_owner_implementation(Thread* owner)                        PRODUCT_RETURN;
-  void check_prelock_state     (Thread* thread)                       PRODUCT_RETURN;
+  void check_prelock_state     (Thread* thread, bool safepoint_check) PRODUCT_RETURN;
   void check_block_state       (Thread* thread)                       PRODUCT_RETURN;
 
   // platform-dependent support code can go here (in os_<os_family>.cpp)
--- a/src/hotspot/share/runtime/reflection.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/runtime/reflection.cpp	Thu May 31 13:04:30 2018 -0700
@@ -337,7 +337,7 @@
     THROW_0(vmSymbols::java_lang_NullPointerException());
   }
   if (length < 0) {
-    THROW_0(vmSymbols::java_lang_NegativeArraySizeException());
+    THROW_MSG_0(vmSymbols::java_lang_NegativeArraySizeException(), err_msg("%d", length));
   }
   if (java_lang_Class::is_primitive(element_mirror)) {
     Klass* tak = basic_type_mirror_to_arrayklass(element_mirror, CHECK_NULL);
@@ -369,7 +369,7 @@
   for (int i = 0; i < len; i++) {
     int d = dim_array->int_at(i);
     if (d < 0) {
-      THROW_0(vmSymbols::java_lang_NegativeArraySizeException());
+      THROW_MSG_0(vmSymbols::java_lang_NegativeArraySizeException(), err_msg("%d", d));
     }
     dimensions[i] = d;
   }
--- a/src/hotspot/share/services/threadService.cpp	Thu May 31 09:52:32 2018 -0700
+++ b/src/hotspot/share/services/threadService.cpp	Thu May 31 13:04:30 2018 -0700
@@ -675,15 +675,15 @@
   // dump all locked concurrent locks
   assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped");
 
-  ResourceMark rm;
-
-  GrowableArray<oop>* aos_objects = new GrowableArray<oop>(INITIAL_ARRAY_SIZE);
+  GrowableArray<oop>* aos_objects = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<oop>(INITIAL_ARRAY_SIZE, true /* C_heap */);
 
   // Find all instances of AbstractOwnableSynchronizer
   HeapInspection::find_instances_at_safepoint(SystemDictionary::abstract_ownable_synchronizer_klass(),
                                                 aos_objects);
   // Build a map of thread to its owned AQS locks
   build_map(aos_objects);
+
+  delete aos_objects;
 }
 
 
--- a/src/java.base/linux/classes/sun/nio/fs/LinuxWatchService.java	Thu May 31 09:52:32 2018 -0700
+++ b/src/java.base/linux/classes/sun/nio/fs/LinuxWatchService.java	Thu May 31 13:04:30 2018 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 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
@@ -319,7 +319,7 @@
                     try {
                         bytesRead = read(ifd, address, BUFFER_SIZE);
                     } catch (UnixException x) {
-                        if (x.errno() != EAGAIN)
+                        if (x.errno() != EAGAIN && x.errno() != EWOULDBLOCK)
                             throw x;
                         bytesRead = 0;
                     }
@@ -367,7 +367,7 @@
                             if (shutdown)
                                 break;
                         } catch (UnixException x) {
-                            if (x.errno() != UnixConstants.EAGAIN)
+                            if (x.errno() != EAGAIN && x.errno() != EWOULDBLOCK)
                                 throw x;
                         }
                     }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.base/share/classes/com/sun/crypto/provider/ChaCha20Cipher.java	Thu May 31 13:04:30 2018 -0700
@@ -0,0 +1,1389 @@
+/*
+ * Copyright (c) 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
+ * 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.crypto.provider;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.VarHandle;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.security.*;
+import java.security.spec.AlgorithmParameterSpec;
+import java.util.Arrays;
+import java.util.Objects;
+import javax.crypto.spec.ChaCha20ParameterSpec;
+import javax.crypto.spec.IvParameterSpec;
+import javax.crypto.spec.SecretKeySpec;
+import javax.crypto.*;
+import sun.security.util.DerValue;
+
+/**
+ * Implementation of the ChaCha20 cipher, as described in RFC 7539.
+ *
+ * @since 11
+ */
+abstract class ChaCha20Cipher extends CipherSpi {
+    // Mode constants
+    private static final int MODE_NONE = 0;
+    private static final int MODE_AEAD = 1;
+
+    // Constants used in setting up the initial state
+    private static final int STATE_CONST_0 = 0x61707865;
+    private static final int STATE_CONST_1 = 0x3320646e;
+    private static final int STATE_CONST_2 = 0x79622d32;
+    private static final int STATE_CONST_3 = 0x6b206574;
+
+    // The keystream block size in bytes and as integers
+    private static final int KEYSTREAM_SIZE = 64;
+    private static final int KS_SIZE_INTS = KEYSTREAM_SIZE / Integer.BYTES;
+    private static final int CIPHERBUF_BASE = 1024;
+
+    // The initialization state of the cipher
+    private boolean initialized;
+
+    // The mode of operation for this object
+    protected int mode;
+
+    // The direction (encrypt vs. decrypt) for the data flow
+    private int direction;
+
+    // Has all AAD data been provided (i.e. have we called our first update)
+    private boolean aadDone = false;
+
+    // The key's encoding in bytes for this object
+    private byte[] keyBytes;
+
+    // The nonce used for this object
+    private byte[] nonce;
+
+    // The counter
+    private static final long MAX_UINT32 = 0x00000000FFFFFFFFL;
+    private long finalCounterValue;
+    private long counter;
+
+    // Two arrays, both implemented as 16-element integer arrays:
+    // The base state, created at initialization time, and a working
+    // state which is a clone of the start state, and is then modified
+    // with the counter and the ChaCha20 block function.
+    private final int[] startState = new int[KS_SIZE_INTS];
+    private final byte[] keyStream = new byte[KEYSTREAM_SIZE];
+
+    // The offset into the current keystream
+    private int keyStrOffset;
+
+    // AEAD-related fields and constants
+    private static final int TAG_LENGTH = 16;
+    private long aadLen;
+    private long dataLen;
+
+    // Have a buffer of zero padding that can be read all or in part
+    // by the authenticator.
+    private static final byte[] padBuf = new byte[TAG_LENGTH];
+
+    // Create a buffer for holding the AAD and Ciphertext lengths
+    private final byte[] lenBuf = new byte[TAG_LENGTH];
+
+    // The authenticator (Poly1305) when running in AEAD mode
+    protected String authAlgName;
+    private Poly1305 authenticator;
+
+    // The underlying engine for doing the ChaCha20/Poly1305 work
+    private ChaChaEngine engine;
+
+    // Use this VarHandle for converting the state elements into little-endian
+    // integer values for the ChaCha20 block function.
+    private static final VarHandle asIntLittleEndian =
+            MethodHandles.byteArrayViewVarHandle(int[].class,
+                    ByteOrder.LITTLE_ENDIAN);
+
+    // Use this VarHandle for converting the AAD and data lengths into
+    // little-endian long values for AEAD tag computations.
+    private static final VarHandle asLongLittleEndian =
+            MethodHandles.byteArrayViewVarHandle(long[].class,
+                    ByteOrder.LITTLE_ENDIAN);
+
+    // Use this for pulling in 8 bytes at a time as longs for XOR operations
+    private static final VarHandle asLongView =
+            MethodHandles.byteArrayViewVarHandle(long[].class,
+                    ByteOrder.nativeOrder());
+
+    /**
+     * Default constructor.
+     */
+    protected ChaCha20Cipher() {
+    }
+
+    /**
+     * Set the mode of operation.  Since this is a stream cipher, there
+     * is no mode of operation in the block-cipher sense of things.  The
+     * protected {@code mode} field will only accept a value of {@code None}
+     * (case-insensitive).
+     *
+     * @param mode The mode value
+     *
+     * @throws NoSuchAlgorithmException if a mode of operation besides
+     *      {@code None} is provided.
+     */
+    @Override
+    protected void engineSetMode(String mode) throws NoSuchAlgorithmException {
+        if (mode.equalsIgnoreCase("None") == false) {
+            throw new NoSuchAlgorithmException("Mode must be None");
+        }
+    }
+
+    /**
+     * Set the padding scheme.  Padding schemes do not make sense with stream
+     * ciphers, but allow {@code NoPadding}.  See JCE spec.
+     *
+     * @param padding The padding type.  The only allowed value is
+     *      {@code NoPadding} case insensitive).
+     *
+     * @throws NoSuchPaddingException if a padding scheme besides
+     *      {@code NoPadding} is provided.
+     */
+    @Override
+    protected void engineSetPadding(String padding)
+            throws NoSuchPaddingException {
+        if (padding.equalsIgnoreCase("NoPadding") == false) {
+            throw new NoSuchPaddingException("Padding must be NoPadding");
+        }
+    }
+
+    /**
+     * Returns the block size.  For a stream cipher like ChaCha20, this
+     * value will always be zero.
+     *
+     * @return This method always returns 0.  See the JCE Specification.
+     */
+    @Override
+    protected int engineGetBlockSize() {
+        return 0;
+    }
+
+    /**
+     * Get the output size based on an input length.  In simple stream-cipher
+     * mode, the output size will equal the input size.  For ChaCha20-Poly1305
+     * for encryption the output size will be the sum of the input length
+     * and tag length.  For decryption, the output size will be the input
+     * length less the tag length or zero, whichever is larger.
+     *
+     * @param inputLen the length in bytes of the input
+     *
+     * @return the output length in bytes.
+     */
+    @Override
+    protected int engineGetOutputSize(int inputLen) {
+        int outLen = 0;
+
+        if (mode == MODE_NONE) {
+            outLen = inputLen;
+        } else if (mode == MODE_AEAD) {
+            outLen = (direction == Cipher.ENCRYPT_MODE) ?
+                    Math.addExact(inputLen, TAG_LENGTH) :
+                    Integer.max(inputLen - TAG_LENGTH, 0);
+        }
+
+        return outLen;
+    }
+
+    /**
+     * Get the nonce value used.
+     *
+     * @return the nonce bytes.  For ChaCha20 this will be a 12-byte value.
+     */
+    @Override
+    protected byte[] engineGetIV() {
+        return nonce.clone();
+    }
+
+    /**
+     * Get the algorithm parameters for this cipher.  For the ChaCha20
+     * cipher, this will always return {@code null} as there currently is
+     * no {@code AlgorithmParameters} implementation for ChaCha20.  For
+     * ChaCha20-Poly1305, a {@code ChaCha20Poly1305Parameters} object will be
+     * created and initialized with the configured nonce value and returned
+     * to the caller.
+     *
+     * @return a {@code null} value if the ChaCha20 cipher is used (mode is
+     * MODE_NONE), or a {@code ChaCha20Poly1305Parameters} object containing
+     * the nonce if the mode is MODE_AEAD.
+     */
+    @Override
+    protected AlgorithmParameters engineGetParameters() {
+        AlgorithmParameters params = null;
+        if (mode == MODE_AEAD) {
+            try {
+                // Force the 12-byte nonce into a DER-encoded OCTET_STRING
+                byte[] derNonce = new byte[nonce.length + 2];
+                derNonce[0] = 0x04;                 // OCTET_STRING tag
+                derNonce[1] = (byte)nonce.length;   // 12-byte length;
+                System.arraycopy(nonce, 0, derNonce, 2, nonce.length);
+                params = AlgorithmParameters.getInstance("ChaCha20-Poly1305");
+                params.init(derNonce);
+            } catch (NoSuchAlgorithmException | IOException exc) {
+                throw new RuntimeException(exc);
+            }
+        }
+
+        return params;
+    }
+
+    /**
+     * Initialize the engine using a key and secure random implementation.  If
+     * a SecureRandom object is provided it will be used to create a random
+     * nonce value.  If the {@code random} parameter is null an internal
+     * secure random source will be used to create the random nonce.
+     * The counter value will be set to 1.
+     *
+     * @param opmode the type of operation to do.  This value may not be
+     *      {@code Cipher.DECRYPT_MODE} or {@code Cipher.UNWRAP_MODE} mode
+     *      because it must generate random parameters like the nonce.
+     * @param key a 256-bit key suitable for ChaCha20
+     * @param random a {@code SecureRandom} implementation used to create the
+     *      random nonce.  If {@code null} is used for the random object,
+     *      then an internal secure random source will be used to create the
+     *      nonce.
+     *
+     * @throws UnsupportedOperationException if the mode of operation
+     *      is {@code Cipher.WRAP_MODE} or {@code Cipher.UNWRAP_MODE}
+     *      (currently unsupported).
+     * @throws InvalidKeyException if the key is of the wrong type or is
+     *      not 256-bits in length.  This will also be thrown if the opmode
+     *      parameter is {@code Cipher.DECRYPT_MODE}.
+     *      {@code Cipher.UNWRAP_MODE} would normally be disallowed in this
+     *      context but it is preempted by the UOE case above.
+     */
+    @Override
+    protected void engineInit(int opmode, Key key, SecureRandom random)
+            throws InvalidKeyException {
+        if (opmode != Cipher.DECRYPT_MODE) {
+            byte[] newNonce = createRandomNonce(random);
+            counter = 1;
+            init(opmode, key, newNonce);
+        } else {
+            throw new InvalidKeyException("Default parameter generation " +
+                "disallowed in DECRYPT and UNWRAP modes");
+        }
+    }
+
+    /**
+     * Initialize the engine using a key and secure random implementation.
+     *
+     * @param opmode the type of operation to do.  This value must be either
+     *      {@code Cipher.ENCRYPT_MODE} or {@code Cipher.DECRYPT_MODE}
+     * @param key a 256-bit key suitable for ChaCha20
+     * @param params a {@code ChaCha20ParameterSpec} that will provide
+     *      the nonce and initial block counter value.
+     * @param random a {@code SecureRandom} implementation, this parameter
+     *      is not used in this form of the initializer.
+     *
+     * @throws UnsupportedOperationException if the mode of operation
+     *      is {@code Cipher.WRAP_MODE} or {@code Cipher.UNWRAP_MODE}
+     *      (currently unsupported).
+     * @throws InvalidKeyException if the key is of the wrong type or is
+     *      not 256-bits in length.  This will also be thrown if the opmode
+     *      parameter is not {@code Cipher.ENCRYPT_MODE} or
+     *      {@code Cipher.DECRYPT_MODE} (excepting the UOE case above).
+     * @throws InvalidAlgorithmParameterException if {@code params} is
+     *      not a {@code ChaCha20ParameterSpec}
+     * @throws NullPointerException if {@code params} is {@code null}
+     */
+    @Override
+    protected void engineInit(int opmode, Key key,
+            AlgorithmParameterSpec params, SecureRandom random)
+            throws InvalidKeyException, InvalidAlgorithmParameterException {
+
+        // If AlgorithmParameterSpec is null, then treat this like an init
+        // of the form (int, Key, SecureRandom)
+        if (params == null) {
+            engineInit(opmode, key, random);
+            return;
+        }
+
+        // We will ignore the secure random implementation and use the nonce
+        // from the AlgorithmParameterSpec instead.
+        byte[] newNonce = null;
+        switch (mode) {
+            case MODE_NONE:
+                if (!(params instanceof ChaCha20ParameterSpec)) {
+                    throw new InvalidAlgorithmParameterException(
+                        "ChaCha20 algorithm requires ChaCha20ParameterSpec");
+                }
+                ChaCha20ParameterSpec chaParams = (ChaCha20ParameterSpec)params;
+                newNonce = chaParams.getNonce();
+                counter = ((long)chaParams.getCounter()) & 0x00000000FFFFFFFFL;
+                break;
+            case MODE_AEAD:
+                if (!(params instanceof IvParameterSpec)) {
+                    throw new InvalidAlgorithmParameterException(
+                        "ChaCha20-Poly1305 requires IvParameterSpec");
+                }
+                IvParameterSpec ivParams = (IvParameterSpec)params;
+                newNonce = ivParams.getIV();
+                if (newNonce.length != 12) {
+                    throw new InvalidAlgorithmParameterException(
+                        "ChaCha20-Poly1305 nonce must be 12 bytes in length");
+                }
+                break;
+            default:
+                // Should never happen
+                throw new RuntimeException("ChaCha20 in unsupported mode");
+        }
+        init(opmode, key, newNonce);
+    }
+
+    /**
+     * Initialize the engine using the {@code AlgorithmParameter} initialization
+     * format.  This cipher does supports initialization with
+     * {@code AlgorithmParameter} objects for ChaCha20-Poly1305 but not for
+     * ChaCha20 as a simple stream cipher.  In the latter case, it will throw
+     * an {@code InvalidAlgorithmParameterException} if the value is non-null.
+     * If a null value is supplied for the {@code params} field
+     * the cipher will be initialized with the counter value set to 1 and
+     * a random nonce.  If {@code null} is used for the random object,
+     * then an internal secure random source will be used to create the
+     * nonce.
+     *
+     * @param opmode the type of operation to do.  This value must be either
+     *      {@code Cipher.ENCRYPT_MODE} or {@code Cipher.DECRYPT_MODE}
+     * @param key a 256-bit key suitable for ChaCha20
+     * @param params a {@code null} value if the algorithm is ChaCha20, or
+     *      the appropriate {@code AlgorithmParameters} object containing the
+     *      nonce information if the algorithm is ChaCha20-Poly1305.
+     * @param random a {@code SecureRandom} implementation, may be {@code null}.
+     *
+     * @throws UnsupportedOperationException if the mode of operation
+     *      is {@code Cipher.WRAP_MODE} or {@code Cipher.UNWRAP_MODE}
+     *      (currently unsupported).
+     * @throws InvalidKeyException if the key is of the wrong type or is
+     *      not 256-bits in length.  This will also be thrown if the opmode
+     *      parameter is not {@code Cipher.ENCRYPT_MODE} or
+     *      {@code Cipher.DECRYPT_MODE} (excepting the UOE case above).
+     * @throws InvalidAlgorithmParameterException if {@code params} is
+     *      non-null and the algorithm is ChaCha20.  This exception will be
+     *      also thrown if the algorithm is ChaCha20-Poly1305 and an incorrect
+     *      {@code AlgorithmParameters} object is supplied.
+     */
+    @Override
+    protected void engineInit(int opmode, Key key,
+            AlgorithmParameters params, SecureRandom random)
+            throws InvalidKeyException, InvalidAlgorithmParameterException {
+
+        // If AlgorithmParameters is null, then treat this like an init
+        // of the form (int, Key, SecureRandom)
+        if (params == null) {
+            engineInit(opmode, key, random);
+            return;
+        }
+
+        byte[] newNonce = null;
+        switch (mode) {
+            case MODE_NONE:
+                throw new InvalidAlgorithmParameterException(
+                        "AlgorithmParameters not supported");
+            case MODE_AEAD:
+                String paramAlg = params.getAlgorithm();
+                if (!paramAlg.equalsIgnoreCase("ChaCha20-Poly1305")) {
+                    throw new InvalidAlgorithmParameterException(
+                            "Invalid parameter type: " + paramAlg);
+                }
+                try {
+                    DerValue dv = new DerValue(params.getEncoded());
+                    newNonce = dv.getOctetString();
+                    if (newNonce.length != 12) {
+                        throw new InvalidAlgorithmParameterException(
+                                "ChaCha20-Poly1305 nonce must be " +
+                                "12 bytes in length");
+                    }
+                } catch (IOException ioe) {
+                    throw new InvalidAlgorithmParameterException(ioe);
+                }
+                break;
+            default:
+                throw new RuntimeException("Invalid mode: " + mode);
+        }
+
+        // If after all the above processing we still don't have a nonce value
+        // then supply a random one provided a random source has been given.
+        if (newNonce == null) {
+            newNonce = createRandomNonce(random);
+        }
+
+        // Continue with initialization
+        init(opmode, key, newNonce);
+    }
+
+    /**
+     * Update additional authenticated data (AAD).
+     *
+     * @param src the byte array containing the authentication data.
+     * @param offset the starting offset in the buffer to update.
+     * @param len the amount of authentication data to update.
+     *
+     * @throws IllegalStateException if the cipher has not been initialized,
+     *      {@code engineUpdate} has been called, or the cipher is running
+     *      in a non-AEAD mode of operation.  It will also throw this
+     *      exception if the submitted AAD would overflow a 64-bit length
+     *      counter.
+     */
+    @Override
+    protected void engineUpdateAAD(byte[] src, int offset, int len) {
+        if (!initialized) {
+            // We know that the cipher has not been initialized if the key
+            // is still null.
+            throw new IllegalStateException(
+                    "Attempted to update AAD on uninitialized Cipher");
+        } else if (aadDone) {
+            // No AAD updates allowed after the PT/CT update method is called
+            throw new IllegalStateException("Attempted to update AAD on " +
+                    "Cipher after plaintext/ciphertext update");
+        } else if (mode != MODE_AEAD) {
+            throw new IllegalStateException(
+                    "Cipher is running in non-AEAD mode");
+        } else {
+            try {
+                aadLen = Math.addExact(aadLen, len);
+                authUpdate(src, offset, len);
+            } catch (ArithmeticException ae) {
+                throw new IllegalStateException("AAD overflow", ae);
+            }
+        }
+    }
+
+    /**
+     * Update additional authenticated data (AAD).
+     *
+     * @param src the ByteBuffer containing the authentication data.
+     *
+     * @throws IllegalStateException if the cipher has not been initialized,
+     *      {@code engineUpdate} has been called, or the cipher is running
+     *      in a non-AEAD mode of operation.  It will also throw this
+     *      exception if the submitted AAD would overflow a 64-bit length
+     *      counter.
+     */
+    @Override
+    protected void engineUpdateAAD(ByteBuffer src) {
+        if (!initialized) {
+            // We know that the cipher has not been initialized if the key
+            // is still null.
+            throw new IllegalStateException(
+                    "Attempted to update AAD on uninitialized Cipher");
+        } else if (aadDone) {
+            // No AAD updates allowed after the PT/CT update method  is called
+            throw new IllegalStateException("Attempted to update AAD on " +
+                    "Cipher after plaintext/ciphertext update");
+        } else if (mode != MODE_AEAD) {
+            throw new IllegalStateException(
+                    "Cipher is running in non-AEAD mode");
+        } else {
+            try {
+                aadLen = Math.addExact(aadLen, (src.limit() - src.position()));
+                authenticator.engineUpdate(src);
+            } catch (ArithmeticException ae) {
+                throw new IllegalStateException("AAD overflow", ae);
+            }
+        }
+    }
+
+    /**
+     * Create a random 12-byte nonce.
+     *
+     * @param random a {@code SecureRandom} object.  If {@code null} is
+     * provided a new {@code SecureRandom} object will be instantiated.
+     *
+     * @return a 12-byte array containing the random nonce.
+     */
+    private byte[] createRandomNonce(SecureRandom random) {
+        byte[] newNonce = new byte[12];
+        SecureRandom rand = (random != null) ? random : new SecureRandom();
+        rand.nextBytes(newNonce);
+        return newNonce;
+    }
+
+    /**
+     * Perform additional initialization actions based on the key and operation
+     * type.
+     *
+     * @param opmode the type of operation to do.  This value must be either
+     *      {@code Cipher.ENCRYPT_MODE} or {@code Cipher.DECRYPT_MODE}
+     * @param key a 256-bit key suitable for ChaCha20
+     * @param newNonce the new nonce value for this initialization.
+     *
+     * @throws UnsupportedOperationException if the {@code opmode} parameter
+     *      is {@code Cipher.WRAP_MODE} or {@code Cipher.UNWRAP_MODE}
+     *      (currently unsupported).
+     * @throws InvalidKeyException if the {@code opmode} parameter is not
+     *      {@code Cipher.ENCRYPT_MODE} or {@code Cipher.DECRYPT_MODE}, or
+     *      if the key format is not {@code RAW}.
+     */
+    private void init(int opmode, Key key, byte[] newNonce)
+            throws InvalidKeyException {
+        if ((opmode == Cipher.WRAP_MODE) || (opmode == Cipher.UNWRAP_MODE)) {
+            throw new UnsupportedOperationException(
+                    "WRAP_MODE and UNWRAP_MODE are not currently supported");
+        } else if ((opmode != Cipher.ENCRYPT_MODE) &&
+                (opmode != Cipher.DECRYPT_MODE)) {
+            throw new InvalidKeyException("Unknown opmode: " + opmode);
+        }
+
+        // Make sure that the provided key and nonce are unique before
+        // assigning them to the object.
+        byte[] newKeyBytes = getEncodedKey(key);
+        checkKeyAndNonce(newKeyBytes, newNonce);
+        this.keyBytes = newKeyBytes;
+        nonce = newNonce;
+
+        // Now that we have the key and nonce, we can build the initial state
+        setInitialState();
+
+        if (mode == MODE_NONE) {
+            engine = new EngineStreamOnly();
+        } else if (mode == MODE_AEAD) {
+            if (opmode == Cipher.ENCRYPT_MODE) {
+                engine = new EngineAEADEnc();
+            } else if (opmode == Cipher.DECRYPT_MODE) {
+                engine = new EngineAEADDec();
+            } else {
+                throw new InvalidKeyException("Not encrypt or decrypt mode");
+            }
+        }
+
+        // We can also get one block's worth of keystream created
+        finalCounterValue = counter + MAX_UINT32;
+        generateKeystream();
+        direction = opmode;
+        aadDone = false;
+        this.keyStrOffset = 0;
+        initialized = true;
+    }
+
+    /**
+     * Check the key and nonce bytes to make sure that they do not repeat
+     * across reinitialization.
+     *
+     * @param newKeyBytes the byte encoding for the newly provided key
+     * @param newNonce the new nonce to be used with this initialization
+     *
+     * @throws InvalidKeyException if both the key and nonce match the
+     *      previous initialization.
+     *
+     */
+    private void checkKeyAndNonce(byte[] newKeyBytes, byte[] newNonce)
+            throws InvalidKeyException {
+        // A new initialization must have either a different key or nonce
+        // so the starting state for each block is not the same as the
+        // previous initialization.
+        if (MessageDigest.isEqual(newKeyBytes, keyBytes) &&
+                MessageDigest.isEqual(newNonce, nonce)) {
+            throw new InvalidKeyException(
+                    "Matching key and nonce from previous initialization");
+        }
+    }
+
+    /**
+     * Return the encoded key as a byte array
+     *
+     * @param key the {@code Key} object used for this {@code Cipher}
+     *
+     * @return the key bytes
+     *
+     * @throws InvalidKeyException if the key is of the wrong type or length,
+     *      or if the key encoding format is not {@code RAW}.
+     */
+    private static byte[] getEncodedKey(Key key) throws InvalidKeyException {
+        if ("RAW".equals(key.getFormat()) == false) {
+            throw new InvalidKeyException("Key encoding format must be RAW");
+        }
+        byte[] encodedKey = key.getEncoded();
+        if (encodedKey == null || encodedKey.length != 32) {
+            throw new InvalidKeyException("Key length must be 256 bits");
+        }
+        return encodedKey;
+    }
+
+    /**
+     * Update the currently running operation with additional data
+     *
+     * @param in the plaintext or ciphertext input bytes (depending on the
+     *      operation type).
+     * @param inOfs the offset into the input array
+     * @param inLen the length of the data to use for the update operation.
+     *
+     * @return the resulting plaintext or ciphertext bytes (depending on
+     *      the operation type)
+     */
+    @Override
+    protected byte[] engineUpdate(byte[] in, int inOfs, int inLen) {
+        byte[] out = new byte[inLen];
+        try {
+            engine.doUpdate(in, inOfs, inLen, out, 0);
+        } catch (ShortBufferException | KeyException exc) {
+            throw new RuntimeException(exc);
+        }
+
+        return out;
+    }
+
+    /**
+     * Update the currently running operation with additional data
+     *
+     * @param in the plaintext or ciphertext input bytes (depending on the
+     *      operation type).
+     * @param inOfs the offset into the input array
+     * @param inLen the length of the data to use for the update operation.
+     * @param out the byte array that will hold the resulting data.  The array
+     *      must be large enough to hold the resulting data.
+     * @param outOfs the offset for the {@code out} buffer to begin writing
+     *      the resulting data.
+     *
+     * @return the length in bytes of the data written into the {@code out}
+     *      buffer.
+     *
+     * @throws ShortBufferException if the buffer {@code out} does not have
+     *      enough space to hold the resulting data.
+     */
+    @Override
+    protected int engineUpdate(byte[] in, int inOfs, int inLen,
+            byte[] out, int outOfs) throws ShortBufferException {
+        int bytesUpdated = 0;
+        try {
+            bytesUpdated = engine.doUpdate(in, inOfs, inLen, out, outOfs);
+        } catch (KeyException ke) {
+            throw new RuntimeException(ke);
+        }
+        return bytesUpdated;
+    }
+
+    /**
+     * Complete the currently running operation using any final
+     * data provided by the caller.
+     *
+     * @param in the plaintext or ciphertext input bytes (depending on the
+     *      operation type).
+     * @param inOfs the offset into the input array
+     * @param inLen the length of the data to use for the update operation.
+     *
+     * @return the resulting plaintext or ciphertext bytes (depending on
+     *      the operation type)
+     *
+     * @throws AEADBadTagException if, during decryption, the provided tag
+     *      does not match the calculated tag.
+     */
+    @Override
+    protected byte[] engineDoFinal(byte[] in, int inOfs, int inLen)
+            throws AEADBadTagException {
+        byte[] output = new byte[engineGetOutputSize(inLen)];
+        try {
+            engine.doFinal(in, inOfs, inLen, output, 0);
+        } catch (ShortBufferException | KeyException exc) {
+            throw new RuntimeException(exc);
+        } finally {
+            // Regardless of what happens, the cipher cannot be used for
+            // further processing until it has been freshly initialized.
+            initialized = false;
+        }
+        return output;
+    }
+
+    /**
+     * Complete the currently running operation using any final
+     * data provided by the caller.
+     *
+     * @param in the plaintext or ciphertext input bytes (depending on the
+     *      operation type).
+     * @param inOfs the offset into the input array
+     * @param inLen the length of the data to use for the update operation.
+     * @param out the byte array that will hold the resulting data.  The array
+     *      must be large enough to hold the resulting data.
+     * @param outOfs the offset for the {@code out} buffer to begin writing
+     *      the resulting data.
+     *
+     * @return the length in bytes of the data written into the {@code out}
+     *      buffer.
+     *
+     * @throws ShortBufferException if the buffer {@code out} does not have
+     *      enough space to hold the resulting data.
+     * @throws AEADBadTagException if, during decryption, the provided tag
+     *      does not match the calculated tag.
+     */
+    @Override
+    protected int engineDoFinal(byte[] in, int inOfs, int inLen, byte[] out,
+            int outOfs) throws ShortBufferException, AEADBadTagException {
+
+        int bytesUpdated = 0;
+        try {
+            bytesUpdated = engine.doFinal(in, inOfs, inLen, out, outOfs);
+        } catch (KeyException ke) {
+            throw new RuntimeException(ke);
+        } finally {
+            // Regardless of what happens, the cipher cannot be used for
+            // further processing until it has been freshly initialized.
+            initialized = false;
+        }
+        return bytesUpdated;
+    }
+
+    /**
+     * Wrap a {@code Key} using this Cipher's current encryption parameters.
+     *
+     * @param key the key to wrap.  The data that will be encrypted will
+     *      be the provided {@code Key} in its encoded form.
+     *
+     * @return a byte array consisting of the wrapped key.
+     *
+     * @throws UnsupportedOperationException this will (currently) always
+     *      be thrown, as this method is not currently supported.
+     */
+    @Override
+    protected byte[] engineWrap(Key key) throws IllegalBlockSizeException,
+            InvalidKeyException {
+        throw new UnsupportedOperationException(
+                "Wrap operations are not supported");
+    }
+
+    /**
+     * Unwrap a {@code Key} using this Cipher's current encryption parameters.
+     *
+     * @param wrappedKey the key to unwrap.
+     * @param algorithm the algorithm associated with the wrapped key
+     * @param type the type of the wrapped key. This is one of
+     *      {@code SECRET_KEY}, {@code PRIVATE_KEY}, or {@code PUBLIC_KEY}.
+     *
+     * @return the unwrapped key as a {@code Key} object.
+     *
+     * @throws UnsupportedOperationException this will (currently) always
+     *      be thrown, as this method is not currently supported.
+     */
+    @Override
+    protected Key engineUnwrap(byte[] wrappedKey, String algorithm,
+            int type) throws InvalidKeyException, NoSuchAlgorithmException {
+        throw new UnsupportedOperationException(
+                "Unwrap operations are not supported");
+    }
+
+    /**
+     * Get the length of a provided key in bits.
+     *
+     * @param key the key to be evaluated
+     *
+     * @return the length of the key in bits
+     *
+     * @throws InvalidKeyException if the key is invalid or does not
+     *      have an encoded form.
+     */
+    @Override
+    protected int engineGetKeySize(Key key) throws InvalidKeyException {
+        byte[] encodedKey = getEncodedKey(key);
+        return encodedKey.length << 3;
+    }
+
+    /**
+     * Set the initial state.  This will populate the state array and put the
+     * key and nonce into their proper locations.  The counter field is not
+     * set here.
+     *
+     * @throws IllegalArgumentException if the key or nonce are not in
+     *      their proper lengths (32 bytes for the key, 12 bytes for the
+     *      nonce).
+     * @throws InvalidKeyException if the key does not support an encoded form.
+     */
+    private void setInitialState() throws InvalidKeyException {
+        // Apply constants to first 4 words
+        startState[0] = STATE_CONST_0;
+        startState[1] = STATE_CONST_1;
+        startState[2] = STATE_CONST_2;
+        startState[3] = STATE_CONST_3;
+
+        // Apply the key bytes as 8 32-bit little endian ints (4 through 11)
+        for (int i = 0; i < 32; i += 4) {
+            startState[(i / 4) + 4] = (keyBytes[i] & 0x000000FF) |
+                ((keyBytes[i + 1] << 8) & 0x0000FF00) |
+                ((keyBytes[i + 2] << 16) & 0x00FF0000) |
+                ((keyBytes[i + 3] << 24) & 0xFF000000);
+        }
+
+        startState[12] = 0;
+
+        // The final integers for the state are from the nonce
+        // interpreted as 3 little endian integers
+        for (int i = 0; i < 12; i += 4) {
+            startState[(i / 4) + 13] = (nonce[i] & 0x000000FF) |
+                ((nonce[i + 1] << 8) & 0x0000FF00) |
+                ((nonce[i + 2] << 16) & 0x00FF0000) |
+                ((nonce[i + 3] << 24) & 0xFF000000);
+        }
+    }
+
+    /**
+     * Using the current state and counter create the next set of keystream
+     * bytes.  This method will generate the next 512 bits of keystream and
+     * return it in the {@code keyStream} parameter.  Following the
+     * block function the counter will be incremented.
+     */
+    private void generateKeystream() {
+        chaCha20Block(startState, counter, keyStream);
+        counter++;
+    }
+
+    /**
+     * Perform a full 20-round ChaCha20 transform on the initial state.
+     *
+     * @param initState the starting state, not including the counter
+     *      value.
+     * @param counter the counter value to apply
+     * @param result  the array that will hold the result of the ChaCha20
+     *      block function.
+     *
+     * @note it is the caller's responsibility to ensure that the workState
+     * is sized the same as the initState, no checking is performed internally.
+     */
+    private static void chaCha20Block(int[] initState, long counter,
+                                      byte[] result) {
+        // Create an initial state and clone a working copy
+        int ws00 = STATE_CONST_0;
+        int ws01 = STATE_CONST_1;
+        int ws02 = STATE_CONST_2;
+        int ws03 = STATE_CONST_3;
+        int ws04 = initState[4];
+        int ws05 = initState[5];
+        int ws06 = initState[6];
+        int ws07 = initState[7];
+        int ws08 = initState[8];
+        int ws09 = initState[9];
+        int ws10 = initState[10];
+        int ws11 = initState[11];
+        int ws12 = (int)counter;
+        int ws13 = initState[13];
+        int ws14 = initState[14];
+        int ws15 = initState[15];
+
+        // Peform 10 iterations of the 8 quarter round set
+        for (int round = 0; round < 10; round++) {
+            ws00 += ws04;
+            ws12 = Integer.rotateLeft(ws12 ^ ws00, 16);
+
+            ws08 += ws12;
+            ws04 = Integer.rotateLeft(ws04 ^ ws08, 12);
+
+            ws00 += ws04;
+            ws12 = Integer.rotateLeft(ws12 ^ ws00, 8);
+
+            ws08 += ws12;
+            ws04 = Integer.rotateLeft(ws04 ^ ws08, 7);
+
+            ws01 += ws05;
+            ws13 = Integer.rotateLeft(ws13 ^ ws01, 16);
+
+            ws09 += ws13;
+            ws05 = Integer.rotateLeft(ws05 ^ ws09, 12);
+
+            ws01 += ws05;
+            ws13 = Integer.rotateLeft(ws13 ^ ws01, 8);
+
+            ws09 += ws13;
+            ws05 = Integer.rotateLeft(ws05 ^ ws09, 7);
+
+            ws02 += ws06;
+            ws14 = Integer.rotateLeft(ws14 ^ ws02, 16);
+
+            ws10 += ws14;
+            ws06 = Integer.rotateLeft(ws06 ^ ws10, 12);
+
+            ws02 += ws06;
+            ws14 = Integer.rotateLeft(ws14 ^ ws02, 8);
+
+            ws10 += ws14;
+            ws06 = Integer.rotateLeft(ws06 ^ ws10, 7);
+
+            ws03 += ws07;
+            ws15 = Integer.rotateLeft(ws15 ^ ws03, 16);
+
+            ws11 += ws15;
+            ws07 = Integer.rotateLeft(ws07 ^ ws11, 12);
+
+            ws03 += ws07;
+            ws15 = Integer.rotateLeft(ws15 ^ ws03, 8);
+
+            ws11 += ws15;
+            ws07 = Integer.rotateLeft(ws07 ^ ws11, 7);
+
+            ws00 += ws05;
+            ws15 = Integer.rotateLeft(ws15 ^ ws00, 16);
+
+            ws10 += ws15;
+            ws05 = Integer.rotateLeft(ws05 ^ ws10, 12);
+
+            ws00 += ws05;
+            ws15 = Integer.rotateLeft(ws15 ^ ws00, 8);
+
+            ws10 += ws15;
+            ws05 = Integer.rotateLeft(ws05 ^ ws10, 7);
+
+            ws01 += ws06;
+            ws12 = Integer.rotateLeft(ws12 ^ ws01, 16);
+
+            ws11 += ws12;
+            ws06 = Integer.rotateLeft(ws06 ^ ws11, 12);
+
+            ws01 += ws06;
+            ws12 = Integer.rotateLeft(ws12 ^ ws01, 8);
+
+            ws11 += ws12;
+            ws06 = Integer.rotateLeft(ws06 ^ ws11, 7);
+
+            ws02 += ws07;
+            ws13 = Integer.rotateLeft(ws13 ^ ws02, 16);
+
+            ws08 += ws13;
+            ws07 = Integer.rotateLeft(ws07 ^ ws08, 12);
+
+            ws02 += ws07;
+            ws13 = Integer.rotateLeft(ws13 ^ ws02, 8);
+
+            ws08 += ws13;
+            ws07 = Integer.rotateLeft(ws07 ^ ws08, 7);
+
+            ws03 += ws04;
+            ws14 = Integer.rotateLeft(ws14 ^ ws03, 16);
+
+            ws09 += ws14;
+            ws04 = Integer.rotateLeft(ws04 ^ ws09, 12);
+
+            ws03 += ws04;
+            ws14 = Integer.rotateLeft(ws14 ^ ws03, 8);
+
+            ws09 += ws14;
+            ws04 = Integer.rotateLeft(ws04 ^ ws09, 7);
+        }
+
+        // Add the end working state back into the original state
+        asIntLittleEndian.set(result, 0, ws00 + STATE_CONST_0);
+        asIntLittleEndian.set(result, 4, ws01 + STATE_CONST_1);
+        asIntLittleEndian.set(result, 8, ws02 + STATE_CONST_2);
+        asIntLittleEndian.set(result, 12, ws03 + STATE_CONST_3);
+        asIntLittleEndian.set(result, 16, ws04 + initState[4]);
+        asIntLittleEndian.set(result, 20, ws05 + initState[5]);
+        asIntLittleEndian.set(result, 24, ws06 + initState[6]);
+        asIntLittleEndian.set(result, 28, ws07 + initState[7]);
+        asIntLittleEndian.set(result, 32, ws08 + initState[8]);
+        asIntLittleEndian.set(result, 36, ws09 + initState[9]);
+        asIntLittleEndian.set(result, 40, ws10 + initState[10]);
+        asIntLittleEndian.set(result, 44, ws11 + initState[11]);
+        // Add the counter back into workState[12]
+        asIntLittleEndian.set(result, 48, ws12 + (int)counter);
+        asIntLittleEndian.set(result, 52, ws13 + initState[13]);
+        asIntLittleEndian.set(result, 56, ws14 + initState[14]);
+        asIntLittleEndian.set(result, 60, ws15 + initState[15]);
+    }
+
+    /**
+     * Perform the ChaCha20 transform.
+     *
+     * @param in the array of bytes for the input
+     * @param inOff the offset into the input array to start the transform
+     * @param inLen the length of the data to perform the transform on.
+     * @param out the output array.  It must be large enough to hold the
+     *      resulting data
+     * @param outOff the offset into the output array to place the resulting
+     *      data.
+     */
+    private void chaCha20Transform(byte[] in, int inOff, int inLen,
+            byte[] out, int outOff) throws KeyException {
+        int remainingData = inLen;
+
+        while (remainingData > 0) {
+            int ksRemain = keyStream.length - keyStrOffset;
+            if (ksRemain <= 0) {
+                if (counter <= finalCounterValue) {
+                    generateKeystream();
+                    keyStrOffset = 0;
+                    ksRemain = keyStream.length;
+                } else {
+                    throw new KeyException("Counter exhausted.  " +
+                            "Reinitialize with new key and/or nonce");
+                }
+            }
+
+            // XOR each byte in the keystream against the input
+            int xformLen = Math.min(remainingData, ksRemain);
+            xor(keyStream, keyStrOffset, in, inOff, out, outOff, xformLen);
+            outOff += xformLen;
+            inOff += xformLen;
+            keyStrOffset += xformLen;
+            remainingData -= xformLen;
+        }
+    }
+
+    private static void xor(byte[] in1, int off1, byte[] in2, int off2,
+            byte[] out, int outOff, int len) {
+        while (len >= 8) {
+            long v1 = (long) asLongView.get(in1, off1);
+            long v2 = (long) asLongView.get(in2, off2);
+            asLongView.set(out, outOff, v1 ^ v2);
+            off1 += 8;
+            off2 += 8;
+            outOff += 8;
+            len -= 8;
+        }
+        while (len > 0) {
+            out[outOff] = (byte) (in1[off1] ^ in2[off2]);
+            off1++;
+            off2++;
+            outOff++;
+            len--;
+        }
+    }
+
+    /**
+     * Perform initialization steps for the authenticator
+     *
+     * @throws InvalidKeyException if the key is unusable for some reason
+     *      (invalid length, etc.)
+     */
+    private void initAuthenticator() throws InvalidKeyException {
+        authenticator = new Poly1305();
+
+        // Derive the Poly1305 key from the starting state
+        byte[] serializedKey = new byte[KEYSTREAM_SIZE];
+        chaCha20Block(startState, 0, serializedKey);
+
+        authenticator.engineInit(new SecretKeySpec(serializedKey, 0, 32,
+                authAlgName), null);
+        aadLen = 0;
+        dataLen = 0;
+    }
+
+    /**
+     * Update the authenticator state with data.  This routine can be used
+     * to add data to the authenticator, whether AAD or application data.
+     *
+     * @param data the data to stir into the authenticator.
+     * @param offset the offset into the data.
+     * @param length the length of data to add to the authenticator.
+     *
+     * @return the number of bytes processed by this method.
+     */
+    private int authUpdate(byte[] data, int offset, int length) {
+        Objects.checkFromIndexSize(offset, length, data.length);
+        authenticator.engineUpdate(data, offset, length);
+        return length;
+    }
+
+    /**
+     * Finalize the data and return the tag.
+     *
+     * @param data an array containing any remaining data to process.
+     * @param dataOff the offset into the data.
+     * @param length the length of the data to process.
+     * @param out the array to write the resulting tag into
+     * @param outOff the offset to begin writing the data.
+     *
+     * @throws ShortBufferException if there is insufficient room to
+     *      write the tag.
+     */
+    private void authFinalizeData(byte[] data, int dataOff, int length,
+            byte[] out, int outOff) throws ShortBufferException {
+        // Update with the final chunk of ciphertext, then pad to a
+        // multiple of 16.
+        if (data != null) {
+            dataLen += authUpdate(data, dataOff, length);
+        }
+        authPad16(dataLen);
+
+        // Also write the AAD and ciphertext data lengths as little-endian
+        // 64-bit values.
+        authWriteLengths(aadLen, dataLen, lenBuf);
+        authenticator.engineUpdate(lenBuf, 0, lenBuf.length);
+        byte[] tag = authenticator.engineDoFinal();
+        Objects.checkFromIndexSize(outOff, tag.length, out.length);
+        System.arraycopy(tag, 0, out, outOff, tag.length);
+        aadLen = 0;
+        dataLen = 0;
+    }
+
+    /**
+     * Based on a given length of data, make the authenticator process
+     * zero bytes that will pad the length out to a multiple of 16.
+     *
+     * @param dataLen the starting length to be padded.
+     */
+    private void authPad16(long dataLen) {
+        // Pad out the AAD or data to a multiple of 16 bytes
+        authenticator.engineUpdate(padBuf, 0,
+                (TAG_LENGTH - ((int)dataLen & 15)) & 15);
+    }
+
+    /**
+     * Write the two 64-bit little-endian length fields into an array
+     * for processing by the poly1305 authenticator.
+     *
+     * @param aLen the length of the AAD.
+     * @param dLen the length of the application data.
+     * @param buf the buffer to write the two lengths into.
+     *
+     * @note it is the caller's responsibility to provide an array large
+     *      enough to hold the two longs.
+     */
+    private void authWriteLengths(long aLen, long dLen, byte[] buf) {
+        asLongLittleEndian.set(buf, 0, aLen);
+        asLongLittleEndian.set(buf, Long.BYTES, dLen);
+    }
+
+    /**
+     * Interface for the underlying processing engines for ChaCha20
+     */
+    interface ChaChaEngine {
+        /**
+         * Perform a multi-part update for ChaCha20.
+         *
+         * @param in the input data.
+         * @param inOff the offset into the input.
+         * @param inLen the length of the data to process.
+         * @param out the output buffer.
+         * @param outOff the offset at which to write the output data.
+         *
+         * @return the number of output bytes written.
+         *
+         * @throws ShortBufferException if the output buffer does not
+         *      provide enough space.
+         * @throws KeyException if the counter value has been exhausted.
+         */
+        int doUpdate(byte[] in, int inOff, int inLen, byte[] out, int outOff)
+                throws ShortBufferException, KeyException;
+
+        /**
+         * Finalize a multi-part or single-part ChaCha20 operation.
+         *
+         * @param in the input data.
+         * @param inOff the offset into the input.
+         * @param inLen the length of the data to process.
+         * @param out the output buffer.
+         * @param outOff the offset at which to write the output data.
+         *
+         * @return the number of output bytes written.
+         *
+         * @throws ShortBufferException if the output buffer does not
+         *      provide enough space.
+         * @throws AEADBadTagException if in decryption mode the provided
+         *      tag and calculated tag do not match.
+         * @throws KeyException if the counter value has been exhausted.
+         */
+        int doFinal(byte[] in, int inOff, int inLen, byte[] out, int outOff)
+                throws ShortBufferException, AEADBadTagException, KeyException;
+    }
+
+    private final class EngineStreamOnly implements ChaChaEngine {
+
+        private EngineStreamOnly () { }
+
+        @Override
+        public int doUpdate(byte[] in, int inOff, int inLen, byte[] out,
+                int outOff) throws ShortBufferException, KeyException {
+            if (initialized) {
+               try {
+                    if (out != null) {
+                        Objects.checkFromIndexSize(outOff, inLen, out.length);
+                    } else {
+                        throw new ShortBufferException(
+                                "Output buffer too small");
+                    }
+                } catch (IndexOutOfBoundsException iobe) {
+                    throw new ShortBufferException("Output buffer too small");
+                }
+                if (in != null) {
+                    Objects.checkFromIndexSize(inOff, inLen, in.length);
+                    chaCha20Transform(in, inOff, inLen, out, outOff);
+                }
+                return inLen;
+            } else {
+                throw new IllegalStateException(
+                        "Must use either a different key or iv.");
+            }
+        }
+
+        @Override
+        public int doFinal(byte[] in, int inOff, int inLen, byte[] out,
+                int outOff) throws ShortBufferException, KeyException {
+            return doUpdate(in, inOff, inLen, out, outOff);
+        }
+    }
+
+    private final class EngineAEADEnc implements ChaChaEngine {
+
+        private EngineAEADEnc() throws InvalidKeyException {
+            initAuthenticator();
+            counter = 1;
+        }
+
+        @Override
+        public int doUpdate(byte[] in, int inOff, int inLen, byte[] out,
+                int outOff) throws ShortBufferException, KeyException {
+            if (initialized) {
+                // If this is the first update since AAD updates, signal that
+                // we're done processing AAD info and pad the AAD to a multiple
+                // of 16 bytes.
+                if (!aadDone) {
+                    authPad16(aadLen);
+                    aadDone = true;
+                }
+                try {
+                    if (out != null) {
+                        Objects.checkFromIndexSize(outOff, inLen, out.length);
+                    } else {
+                        throw new ShortBufferException(
+                                "Output buffer too small");
+                    }
+                } catch (IndexOutOfBoundsException iobe) {
+                    throw new ShortBufferException("Output buffer too small");
+                }
+                if (in != null) {
+                    Objects.checkFromIndexSize(inOff, inLen, in.length);
+                    chaCha20Transform(in, inOff, inLen, out, outOff);
+                    dataLen += authUpdate(out, outOff, inLen);
+                }
+
+                return inLen;
+            } else {
+                throw new IllegalStateException(
+                        "Must use either a different key or iv.");
+            }
+        }
+
+        @Override
+        public int doFinal(byte[] in, int inOff, int inLen, byte[] out,
+                int outOff) throws ShortBufferException, KeyException {
+            // Make sure we have enough room for the remaining data (if any)
+            // and the tag.
+            if ((inLen + TAG_LENGTH) > (out.length - outOff)) {
+                throw new ShortBufferException("Output buffer too small");
+            }
+
+            doUpdate(in, inOff, inLen, out, outOff);
+            authFinalizeData(null, 0, 0, out, outOff + inLen);
+            aadDone = false;
+            return inLen + TAG_LENGTH;
+        }
+    }
+
+    private final class EngineAEADDec implements ChaChaEngine {
+
+        private final ByteArrayOutputStream cipherBuf;
+        private final byte[] tag;
+
+        private EngineAEADDec() throws InvalidKeyException {
+            initAuthenticator();
+            counter = 1;
+            cipherBuf = new ByteArrayOutputStream(CIPHERBUF_BASE);
+            tag = new byte[TAG_LENGTH];
+        }
+
+        @Override
+        public int doUpdate(byte[] in, int inOff, int inLen, byte[] out,
+                int outOff) {
+            if (initialized) {
+                // If this is the first update since AAD updates, signal that
+                // we're done processing AAD info and pad the AAD to a multiple
+                // of 16 bytes.
+                if (!aadDone) {
+                    authPad16(aadLen);
+                    aadDone = true;
+                }
+
+                if (in != null) {
+                    Objects.checkFromIndexSize(inOff, inLen, in.length);
+                    cipherBuf.write(in, inOff, inLen);
+                }
+            } else {
+                throw new IllegalStateException(
+                        "Must use either a different key or iv.");
+            }
+
+            return 0;
+        }
+
+        @Override
+        public int doFinal(byte[] in, int inOff, int inLen, byte[] out,
+                int outOff) throws ShortBufferException, AEADBadTagException,
+                KeyException {
+
+            byte[] ctPlusTag;
+            int ctPlusTagLen;
+            if (cipherBuf.size() == 0 && inOff == 0) {
+                // No previous data has been seen before doFinal, so we do
+                // not need to hold any ciphertext in a buffer.  We can
+                // process it directly from the "in" parameter.
+                doUpdate(null, inOff, inLen, out, outOff);
+                ctPlusTag = in;
+                ctPlusTagLen = inLen;
+            } else {
+                doUpdate(in, inOff, inLen, out, outOff);
+                ctPlusTag = cipherBuf.toByteArray();
+                ctPlusTagLen = ctPlusTag.length;
+            }
+            cipherBuf.reset();
+
+            // There must at least be a tag length's worth of ciphertext
+            // data in the buffered input.
+            if (ctPlusTagLen < TAG_LENGTH) {
+                throw new AEADBadTagException("Input too short - need tag");
+            }
+            int ctLen = ctPlusTagLen - TAG_LENGTH;
+
+            // Make sure we will have enough room for the output buffer
+            try {
+                Objects.checkFromIndexSize(outOff, ctLen, out.length);
+            } catch (IndexOutOfBoundsException ioobe) {
+                throw new ShortBufferException("Output buffer too small");
+            }
+
+            // Calculate and compare the tag.  Only do the decryption
+            // if and only if the tag matches.
+            authFinalizeData(ctPlusTag, 0, ctLen, tag, 0);
+            if (Arrays.compare(ctPlusTag, ctLen, ctPlusTagLen,
+                    tag, 0, tag.length) != 0) {
+                throw new AEADBadTagException("Tag mismatch");
+            }
+            chaCha20Transform(ctPlusTag, 0, ctLen, out, outOff);
+            aadDone = false;
+
+            return ctLen;
+        }
+    }
+
+    public static final class ChaCha20Only extends ChaCha20Cipher {
+        public ChaCha20Only() {
+            mode = MODE_NONE;
+        }
+    }
+
+    public static final class ChaCha20Poly1305 extends ChaCha20Cipher {
+        public ChaCha20Poly1305() {
+            mode = MODE_AEAD;
+            authAlgName = "Poly1305";
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.base/share/classes/com/sun/crypto/provider/ChaCha20Poly1305Parameters.java	Thu May 31 13:04:30 2018 -0700
@@ -0,0 +1,213 @@
+/*
+ * Copyright (c) 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
+ * 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.crypto.provider;
+
+import java.io.IOException;
+import java.security.AlgorithmParametersSpi;
+import java.security.spec.AlgorithmParameterSpec;
+import java.security.spec.InvalidParameterSpecException;
+import javax.crypto.spec.IvParameterSpec;
+import sun.security.util.*;
+
+/**
+ * This class implements the parameter set used with the ChaCha20-Poly1305
+ * algorithm.  The parameter definition comes from
+ * <a href="https://tools.ietf.org/html/rfc8103"><i>RFC 8103</i></a>
+ * and is defined according to the following ASN.1:
+ *
+ * <pre>
+ * id-alg-AEADChaCha20Poly1305 OBJECT IDENTIFIER ::=
+          { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1)
+            pkcs9(9) smime(16) alg(3) 18 }
+
+ * AEADChaCha20Poly1305Nonce ::= OCTET STRING (SIZE(12))
+ * </pre>
+ *
+ * The AlgorithmParameters may be instantiated either by its name
+ * ("ChaCha20-Poly1305") or via its OID (1.2.840.113549.1.9.16.3.18)
+ */
+public final class ChaCha20Poly1305Parameters extends AlgorithmParametersSpi {
+
+    private static final String DEFAULT_FMT = "ASN.1";
+    private byte[] nonce;
+
+    public ChaCha20Poly1305Parameters() {}
+
+    /**
+     * Initialize the ChaCha20Poly1305Parameters using an IvParameterSpec.
+     *
+     * @param paramSpec the {@code IvParameterSpec} used to configure
+     *      this object.
+     *
+     * @throws InvalidParameterSpecException if an object of a type other
+     *      than {@code IvParameterSpec} is used.
+     */
+    @Override
+    protected void engineInit(AlgorithmParameterSpec paramSpec)
+        throws InvalidParameterSpecException {
+
+        if (!(paramSpec instanceof IvParameterSpec)) {
+            throw new InvalidParameterSpecException
+                ("Inappropriate parameter specification");
+        }
+        IvParameterSpec ivps = (IvParameterSpec)paramSpec;
+
+        // Obtain the nonce
+        nonce = ivps.getIV();
+        if (nonce.length != 12) {
+            throw new InvalidParameterSpecException("ChaCha20-Poly1305 nonce" +
+                    " must be 12 bytes in length");
+        }
+    }
+
+    /**
+     * Initialize the ChaCha20Poly1305Parameters from a DER encoded
+     * parameter block.
+
+     * @param encoded the DER encoding of the nonce as an OCTET STRING.
+     *
+     * @throws IOException if the encoded nonce is not 12 bytes long or a DER
+     *      decoding error occurs.
+     */
+    @Override
+    protected void engineInit(byte[] encoded) throws IOException {
+        DerValue val = new DerValue(encoded);
+
+        // Get the nonce value
+        nonce = val.getOctetString();
+        if (nonce.length != 12) {
+           throw new IOException(
+                   "ChaCha20-Poly1305 nonce must be 12 bytes in length");
+        }
+    }
+
+    /**
+     * Initialize the ChaCha20Poly1305Parameters from a DER encoded
+     * parameter block.
+     *
+     * @param encoded the DER encoding of the nonce and initial block counter.
+     * @param decodingMethod the decoding method.  The only currently accepted
+     *      value is "ASN.1"
+     *
+     * @throws IOException if the encoded nonce is not 12 bytes long, a DER
+     *      decoding error occurs, or an unsupported decoding method is
+     *      provided.
+     */
+    @Override
+    protected void engineInit(byte[] encoded, String decodingMethod)
+            throws IOException {
+        if (decodingMethod == null ||
+                decodingMethod.equalsIgnoreCase(DEFAULT_FMT)) {
+            engineInit(encoded);
+        } else {
+            throw new IOException("Unsupported parameter format: " +
+                    decodingMethod);
+        }
+    }
+
+    /**
+     * Return an IvParameterSpec with the same parameters as those
+     * held in this object.
+     *
+     * @param paramSpec the class name of the spec.  In this case it should
+     *      be {@code IvParameterSpec.class}.
+     *
+     * @return a {@code IvParameterSpec} object containing the nonce
+     *      value held in this object.
+     *
+     * @throws InvalidParameterSpecException if a class other than
+     *      {@code IvParameterSpec.class} was specified in the paramSpec
+     *      parameter.
+     */
+    @Override
+    protected <T extends AlgorithmParameterSpec>
+            T engineGetParameterSpec(Class<T> paramSpec)
+        throws InvalidParameterSpecException {
+
+        if (IvParameterSpec.class.isAssignableFrom(paramSpec)) {
+            return paramSpec.cast(new IvParameterSpec(nonce));
+        } else {
+            throw new InvalidParameterSpecException
+                ("Inappropriate parameter specification");
+        }
+    }
+
+    /**
+     * Return the encoded parameters in ASN.1 form.
+     *
+     * @return a byte array containing the DER-encoding for the
+     *      ChaCha20-Poly1305 parameters.  This will be the nonce
+     *      encoded as a DER OCTET STRING.
+     *
+     * @throws IOException if any DER encoding error occurs.
+     */
+    @Override
+    protected byte[] engineGetEncoded() throws IOException {
+        DerOutputStream out = new DerOutputStream();
+        out.write(DerValue.tag_OctetString, nonce);
+        return out.toByteArray();
+    }
+
+    /**
+     * Return the encoded parameters in ASN.1 form.
+     *
+     * @param encodingMethod the encoding method to be used.  This parameter
+     *      must be "ASN.1" as it is the only currently supported encoding
+     *      format.  If the parameter is {@code null} then the default
+     *      encoding format will be used.
+     *
+     * @return a byte array containing the DER-encoding for the
+     *      ChaCha20-Poly1305 parameters.
+     *
+     * @throws IOException if any DER encoding error occurs or an unsupported
+     *      encoding method is provided.
+     */
+    @Override
+    protected byte[] engineGetEncoded(String encodingMethod)
+        throws IOException {
+        if (encodingMethod == null ||
+                encodingMethod.equalsIgnoreCase(DEFAULT_FMT)) {
+            return engineGetEncoded();
+        } else {
+            throw new IOException("Unsupported encoding format: " +
+                    encodingMethod);
+        }
+    }
+
+    /**
+     * Creates a formatted string describing the parameters.
+     *
+     * @return a string representation of the ChaCha20 parameters.
+     */
+    @Override
+    protected String engineToString() {
+        String LINE_SEP = System.lineSeparator();
+        HexDumpEncoder encoder = new HexDumpEncoder();
+        StringBuilder sb = new StringBuilder(LINE_SEP + "nonce:" +
+                LINE_SEP + "[" + encoder.encodeBuffer(nonce) + "]");
+        return sb.toString();
+    }
+}
--- a/src/java.base/share/classes/com/sun/crypto/provider/KeyGeneratorCore.java	Thu May 31 09:52:32 2018 -0700
+++ b/src/java.base/share/classes/com/sun/crypto/provider/KeyGeneratorCore.java	Thu May 31 13:04:30 2018 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 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
@@ -111,16 +111,20 @@
         protected HmacSHA2KG(String algoName, int len) {
             core = new KeyGeneratorCore(algoName, len);
         }
+        @Override
         protected void engineInit(SecureRandom random) {
             core.implInit(random);
         }
+        @Override
         protected void engineInit(AlgorithmParameterSpec params,
                 SecureRandom random) throws InvalidAlgorithmParameterException {
             core.implInit(params, random);
         }
+        @Override
         protected void engineInit(int keySize, SecureRandom random) {
             core.implInit(keySize, random);
         }
+        @Override
         protected SecretKey engineGenerateKey() {
             return core.implGenerateKey();
         }
@@ -153,13 +157,16 @@
         public RC2KeyGenerator() {
             core = new KeyGeneratorCore("RC2", 128);
         }
+        @Override
         protected void engineInit(SecureRandom random) {
             core.implInit(random);
         }
+        @Override
         protected void engineInit(AlgorithmParameterSpec params,
                 SecureRandom random) throws InvalidAlgorithmParameterException {
             core.implInit(params, random);
         }
+        @Override
         protected void engineInit(int keySize, SecureRandom random) {
             if ((keySize < 40) || (keySize > 1024)) {
                 throw new InvalidParameterException("Key length for RC2"
@@ -167,6 +174,7 @@
             }
             core.implInit(keySize, random);
         }
+        @Override
         protected SecretKey engineGenerateKey() {
             return core.implGenerateKey();
         }
@@ -178,13 +186,16 @@
         public ARCFOURKeyGenerator() {
             core = new KeyGeneratorCore("ARCFOUR", 128);
         }
+        @Override
         protected void engineInit(SecureRandom random) {
             core.implInit(random);
         }
+        @Override
         protected void engineInit(AlgorithmParameterSpec params,
                 SecureRandom random) throws InvalidAlgorithmParameterException {
             core.implInit(params, random);
         }
+        @Override
         protected void engineInit(int keySize, SecureRandom random) {
             if ((keySize < 40) || (keySize > 1024)) {
                 throw new InvalidParameterException("Key length for ARCFOUR"
@@ -192,9 +203,38 @@
             }
             core.implInit(keySize, random);
         }
+        @Override
         protected SecretKey engineGenerateKey() {
             return core.implGenerateKey();
         }
     }
 
+    // nested static class for the ChaCha20 key generator
+    public static final class ChaCha20KeyGenerator extends KeyGeneratorSpi {
+        private final KeyGeneratorCore core;
+        public ChaCha20KeyGenerator() {
+            core = new KeyGeneratorCore("ChaCha20", 256);
+        }
+        @Override
+        protected void engineInit(SecureRandom random) {
+            core.implInit(random);
+        }
+        @Override
+        protected void engineInit(AlgorithmParameterSpec params,
+                SecureRandom random) throws InvalidAlgorithmParameterException {
+            core.implInit(params, random);
+        }
+        @Override
+        protected void engineInit(int keySize, SecureRandom random) {
+            if (keySize != 256) {
+                throw new InvalidParameterException(
+                        "Key length for ChaCha20 must be 256 bits");
+            }
+            core.implInit(keySize, random);
+        }
+        @Override
+        protected SecretKey engineGenerateKey() {
+            return core.implGenerateKey();
+        }
+    }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.base/share/classes/com/sun/crypto/provider/Poly1305.java	Thu May 31 13:04:30 2018 -0700
@@ -0,0 +1,257 @@
+/*
+ * Copyright (c) 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
+ * 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.crypto.provider;
+
+import java.nio.ByteBuffer;
+import java.security.Key;
+import java