changeset 48976:4f20b62eabfa enhanced-enums

Automatic merge with default
author mcimadamore
date Mon, 22 Jan 2018 16:55:01 +0100
parents 02465b43166a 89111a0e6355
children c27f9ab75c0a
files
diffstat 144 files changed, 5456 insertions(+), 1955 deletions(-) [+]
line wrap: on
line diff
--- a/make/data/jdwp/jdwp.spec	Thu Jan 18 22:05:05 2018 +0100
+++ b/make/data/jdwp/jdwp.spec	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 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
@@ -869,7 +869,6 @@
         "section in "
         "<cite>The Java&trade; Virtual Machine Specification</cite>. "
         "Since JDWP version 1.5."
-        "<p>
         (Out
             (referenceType refType "The reference type ID.")
         )
@@ -2723,7 +2722,6 @@
         "<P>"
         "The events that are grouped in a composite event are restricted in the "
         "following ways: "
-        "<P>"
         "<UL>"
         "<LI>Only with other thread start events for the same thread:"
         "    <UL>"
--- a/make/jdk/src/classes/build/tools/jdwpgen/AbstractCommandNode.java	Thu Jan 18 22:05:05 2018 +0100
+++ b/make/jdk/src/classes/build/tools/jdwpgen/AbstractCommandNode.java	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 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,8 +30,8 @@
 class AbstractCommandNode extends AbstractNamedNode {
 
     void document(PrintWriter writer) {
-        writer.println("<h5><a name=\"" + context.whereC + "\">" + name +
-                       " Command</a> (" + nameNode.value() + ")</h5>");
+        writer.println("<h5 id=\"" + context.whereC + "\">" + name +
+                       " Command (" + nameNode.value() + ")</h5>");
         writer.println(comment());
         writer.println("<dl>");
         for (Node node : components) {
--- a/make/jdk/src/classes/build/tools/jdwpgen/AbstractNamedNode.java	Thu Jan 18 22:05:05 2018 +0100
+++ b/make/jdk/src/classes/build/tools/jdwpgen/AbstractNamedNode.java	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 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,8 +62,8 @@
     }
 
     void document(PrintWriter writer) {
-        writer.println("<h4><a name=" + name + ">" + name +
-                       " Command Set</a></h4>");
+        writer.println("<h4 id=\"" + name + "\">" + name +
+                       " Command Set</h4>");
         for (Node node : components) {
             node.document(writer);
         }
--- a/make/jdk/src/classes/build/tools/jdwpgen/AbstractTypeListNode.java	Thu Jan 18 22:05:05 2018 +0100
+++ b/make/jdk/src/classes/build/tools/jdwpgen/AbstractTypeListNode.java	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 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
@@ -43,11 +43,11 @@
         if (components.isEmpty()) {
             writer.println("<dd>(None)");
         } else {
-            writer.println("<dd><table border=1 cellpadding=3 cellspacing=0 width=\"90%\" summary=\"\"><tr>");
+            writer.println("<dd><table><tr>");
             for (int i = maxStructIndent; i > 0; --i) {
-                writer.print("<th width=\"4%\">");
+                writer.print("<th style=\"width: 4%\">");
             }
-            writer.println("<th width=\"15%\"><th width=\"65%\">");
+            writer.println("<th style=\"width: 15%\"><th style=\"width: 65%\">");
             writer.println("");
             for (Node node : components) {
                 node.document(writer);
--- a/make/jdk/src/classes/build/tools/jdwpgen/CommandSetNode.java	Thu Jan 18 22:05:05 2018 +0100
+++ b/make/jdk/src/classes/build/tools/jdwpgen/CommandSetNode.java	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 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
@@ -38,8 +38,8 @@
     }
 
     void document(PrintWriter writer) {
-        writer.println("<h4><a name=\"" + context.whereC + "\">" + name +
-                       " Command Set</a> (" +
+        writer.println("<h4 id=\"" + context.whereC + "\">" + name +
+                       " Command Set (" +
                        nameNode.value() + ")</h4>");
         writer.println(comment());
         for (Node node : components) {
@@ -51,11 +51,13 @@
         writer.print("<li><a href=\"#" + context.whereC + "\">");
         writer.println(name() + "</a> Command Set (" +
                        nameNode.value() + ")");
-        writer.println("<ul>");
-        for (Node node : components) {
-            node.documentIndex(writer);
+        if (components.size() > 0) {
+            writer.println("<ul>");
+            for (Node node : components) {
+                node.documentIndex(writer);
+            }
+            writer.println("</ul>");
         }
-        writer.println("</ul>");
     }
 
     void genJavaClassSpecifics(PrintWriter writer, int depth) {
--- a/make/jdk/src/classes/build/tools/jdwpgen/ConstantSetNode.java	Thu Jan 18 22:05:05 2018 +0100
+++ b/make/jdk/src/classes/build/tools/jdwpgen/ConstantSetNode.java	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 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
@@ -54,15 +54,15 @@
     }
 
     void document(PrintWriter writer) {
-        writer.println("<h4><a name=\"" + context.whereC + "\">" + name +
-                       " Constants</a></h4>");
+        writer.println("<h4 id=\"" + context.whereC + "\">" + name +
+                       " Constants</h4>");
         writer.println(comment());
-        writer.println("<dd><table border=1 cellpadding=3 cellspacing=0 width=\"90%\" summary=\"\"><tr>");
-        writer.println("<th width=\"20%\"><th width=\"5%\"><th width=\"65%\">");
+        writer.println("<table><tr>");
+        writer.println("<th style=\"width: 20%\"><th style=\"width: 5%\"><th style=\"width:  65%\">");
         ConstantNode n;
         for (Node node : components) {
             n = (ConstantNode)node;
-            writer.println("<a NAME=\"" + name + "_" + n.name + "\"></a>");
+            writer.println("<span id=\"" + name + "_" + n.name + "\"></span>");
             n.document(writer);
         }
         writer.println("</table>");
--- a/make/jdk/src/classes/build/tools/jdwpgen/ErrorSetNode.java	Thu Jan 18 22:05:05 2018 +0100
+++ b/make/jdk/src/classes/build/tools/jdwpgen/ErrorSetNode.java	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2013, 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
@@ -43,7 +43,7 @@
         if (components.isEmpty()) {
             writer.println("<dd>(None)");
         } else {
-            writer.println("<dd><table border=1 cellpadding=3 cellspacing=0 width=\"90%\" summary=\"\">");
+            writer.println("<dd><table>");
         for (Node node : components) {
             node.document(writer);
         }
--- a/make/jdk/src/classes/build/tools/jdwpgen/RootNode.java	Thu Jan 18 22:05:05 2018 +0100
+++ b/make/jdk/src/classes/build/tools/jdwpgen/RootNode.java	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 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
@@ -41,11 +41,22 @@
 
     void document(PrintWriter writer) {
         writer.println("<!DOCTYPE html>");
-        writer.println("<html><head><title>" + comment() + "</title></head>");
-        writer.println("<body bgcolor=\"white\">");
+        writer.println("<html lang=\"en\">");
+        writer.println("<head>");
+        writer.println("<meta charset=\"utf-8\"/>");
+        writer.println("<title>" + comment() + "</title>");
+        writer.println("<style>");
+        writer.println("body {background-color:white;}");
+        writer.println("table {border: 1px solid grey; border-spacing:0px; border-collapse: separate; width: 90%;}");
+        writer.println("td, th {padding: 3px; border: 1px solid black;}");
+        writer.println("</style>");
+        writer.println("</head>");
+        writer.println("<body>");
+        writer.println("<ul>");
         for (Node node : components) {
             node.documentIndex(writer);
         }
+        writer.println("</ul>");
         for (Node node : components) {
             node.document(writer);
         }
--- a/make/test/JtregNativeHotspot.gmk	Thu Jan 18 22:05:05 2018 +0100
+++ b/make/test/JtregNativeHotspot.gmk	Mon Jan 22 16:55:01 2018 +0100
@@ -44,6 +44,7 @@
 # Add more directories here when needed.
 BUILD_HOTSPOT_JTREG_NATIVE_SRC += \
     $(TOPDIR)/test/hotspot/jtreg/gc/g1/TestJNIWeakG1 \
+    $(TOPDIR)/test/hotspot/jtreg/gc/stress/TestJNIBlockFullGC \
     $(TOPDIR)/test/hotspot/jtreg/gc/stress/gclocker \
     $(TOPDIR)/test/hotspot/jtreg/gc/cslocker \
     $(TOPDIR)/test/hotspot/jtreg/native_sanity \
--- a/src/hotspot/cpu/aarch64/assembler_aarch64.hpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/cpu/aarch64/assembler_aarch64.hpp	Mon Jan 22 16:55:01 2018 +0100
@@ -2295,23 +2295,32 @@
     rf(Vn, 5), rf(Rd, 0);
   }
 
-#define INSN(NAME, opc, opc2)                                           \
+#define INSN(NAME, opc, opc2, isSHR)                                    \
   void NAME(FloatRegister Vd, SIMD_Arrangement T, FloatRegister Vn, int shift){ \
     starti;                                                             \
-    /* The encodings for the immh:immb fields (bits 22:16) are          \
-     *   0001 xxx       8B/16B, shift = xxx                             \
-     *   001x xxx       4H/8H,  shift = xxxx                            \
-     *   01xx xxx       2S/4S,  shift = xxxxx                           \
-     *   1xxx xxx       1D/2D,  shift = xxxxxx (1D is RESERVED)         \
+    /* The encodings for the immh:immb fields (bits 22:16) in *SHR are  \
+     *   0001 xxx       8B/16B, shift = 16  - UInt(immh:immb)           \
+     *   001x xxx       4H/8H,  shift = 32  - UInt(immh:immb)           \
+     *   01xx xxx       2S/4S,  shift = 64  - UInt(immh:immb)           \
+     *   1xxx xxx       1D/2D,  shift = 128 - UInt(immh:immb)           \
+     *   (1D is RESERVED)                                               \
+     * for SHL shift is calculated as:                                  \
+     *   0001 xxx       8B/16B, shift = UInt(immh:immb) - 8             \
+     *   001x xxx       4H/8H,  shift = UInt(immh:immb) - 16            \
+     *   01xx xxx       2S/4S,  shift = UInt(immh:immb) - 32            \
+     *   1xxx xxx       1D/2D,  shift = UInt(immh:immb) - 64            \
+     *   (1D is RESERVED)                                               \
      */                                                                 \
     assert((1 << ((T>>1)+3)) > shift, "Invalid Shift value");           \
+    int cVal = (1 << (((T >> 1) + 3) + (isSHR ? 1 : 0)));               \
+    int encodedShift = isSHR ? cVal - shift : cVal + shift;             \
     f(0, 31), f(T & 1, 30), f(opc, 29), f(0b011110, 28, 23),            \
-    f((1 << ((T>>1)+3))|shift, 22, 16); f(opc2, 15, 10), rf(Vn, 5), rf(Vd, 0); \
+    f(encodedShift, 22, 16); f(opc2, 15, 10), rf(Vn, 5), rf(Vd, 0);     \
   }
 
-  INSN(shl,  0, 0b010101);
-  INSN(sshr, 0, 0b000001);
-  INSN(ushr, 1, 0b000001);
+  INSN(shl,  0, 0b010101, /* isSHR = */ false);
+  INSN(sshr, 0, 0b000001, /* isSHR = */ true);
+  INSN(ushr, 1, 0b000001, /* isSHR = */ true);
 
 #undef INSN
 
--- a/src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -963,8 +963,12 @@
                                              RegisterOrConstant itable_index,
                                              Register method_result,
                                              Register scan_temp,
-                                             Label& L_no_such_interface) {
-  assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
+                                             Label& L_no_such_interface,
+                         bool return_method) {
+  assert_different_registers(recv_klass, intf_klass, scan_temp);
+  assert_different_registers(method_result, intf_klass, scan_temp);
+  assert(recv_klass != method_result || !return_method,
+     "recv_klass can be destroyed when method isn't needed");
   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
          "caller must use same register for non-constant itable index as for method");
 
@@ -982,12 +986,14 @@
   lea(scan_temp, Address(recv_klass, scan_temp, Address::lsl(3)));
   add(scan_temp, scan_temp, vtable_base);
 
-  // Adjust recv_klass by scaled itable_index, so we can free itable_index.
-  assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
-  // lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
-  lea(recv_klass, Address(recv_klass, itable_index, Address::lsl(3)));
-  if (itentry_off)
-    add(recv_klass, recv_klass, itentry_off);
+  if (return_method) {
+    // Adjust recv_klass by scaled itable_index, so we can free itable_index.
+    assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
+    // lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
+    lea(recv_klass, Address(recv_klass, itable_index, Address::lsl(3)));
+    if (itentry_off)
+      add(recv_klass, recv_klass, itentry_off);
+  }
 
   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
   //   if (scan->interface() == intf) {
@@ -1021,8 +1027,10 @@
   bind(found_method);
 
   // Got a hit.
-  ldr(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
-  ldr(method_result, Address(recv_klass, scan_temp));
+  if (return_method) {
+    ldrw(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
+    ldr(method_result, Address(recv_klass, scan_temp, Address::uxtw(0)));
+  }
 }
 
 // virtual method calling
--- a/src/hotspot/cpu/aarch64/macroAssembler_aarch64.hpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/cpu/aarch64/macroAssembler_aarch64.hpp	Mon Jan 22 16:55:01 2018 +0100
@@ -875,7 +875,8 @@
                                RegisterOrConstant itable_index,
                                Register method_result,
                                Register scan_temp,
-                               Label& no_such_interface);
+                               Label& no_such_interface,
+                   bool return_method = true);
 
   // virtual method calling
   // n.b. x86 allows RegisterOrConstant for vtable_index
--- a/src/hotspot/cpu/aarch64/templateTable_aarch64.cpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/cpu/aarch64/templateTable_aarch64.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -3279,11 +3279,11 @@
   transition(vtos, vtos);
   assert(byte_no == f1_byte, "use this argument");
 
-  prepare_invoke(byte_no, r0, rmethod,  // get f1 Klass*, f2 itable index
+  prepare_invoke(byte_no, r0, rmethod,  // get f1 Klass*, f2 Method*
                  r2, r3); // recv, flags
 
   // r0: interface klass (from f1)
-  // rmethod: itable index (from f2)
+  // rmethod: method (from f2)
   // r2: receiver
   // r3: flags
 
@@ -3302,10 +3302,27 @@
   __ null_check(r2, oopDesc::klass_offset_in_bytes());
   __ load_klass(r3, r2);
 
+  Label no_such_interface, no_such_method;
+
+  // Receiver subtype check against REFC.
+  // Superklass in r0. Subklass in r3. Blows rscratch2, r13
+  __ lookup_interface_method(// inputs: rec. class, interface, itable index
+                             r3, r0, noreg,
+                             // outputs: scan temp. reg, scan temp. reg
+                             rscratch2, r13,
+                             no_such_interface,
+                             /*return_method=*/false);
+
   // profile this call
   __ profile_virtual_call(r3, r13, r19);
 
-  Label no_such_interface, no_such_method;
+  // Get declaring interface class from method, and itable index
+  __ ldr(r0, Address(rmethod, Method::const_offset()));
+  __ ldr(r0, Address(r0, ConstMethod::constants_offset()));
+  __ ldr(r0, Address(r0, ConstantPool::pool_holder_offset_in_bytes()));
+  __ ldrw(rmethod, Address(rmethod, Method::itable_index_offset()));
+  __ subw(rmethod, rmethod, Method::itable_index_max);
+  __ negw(rmethod, rmethod);
 
   __ lookup_interface_method(// inputs: rec. class, interface, itable index
                              r3, r0, rmethod,
--- a/src/hotspot/cpu/aarch64/vtableStubs_aarch64.cpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/cpu/aarch64/vtableStubs_aarch64.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -29,6 +29,7 @@
 #include "code/vtableStubs.hpp"
 #include "interp_masm_aarch64.hpp"
 #include "memory/resourceArea.hpp"
+#include "oops/compiledICHolder.hpp"
 #include "oops/instanceKlass.hpp"
 #include "oops/klassVtable.hpp"
 #include "runtime/sharedRuntime.hpp"
@@ -140,28 +141,44 @@
 #endif
 
   // Entry arguments:
-  //  rscratch2: Interface
+  //  rscratch2: CompiledICHolder
   //  j_rarg0: Receiver
 
-  // Free registers (non-args) are r0 (interface), rmethod
+
+  // Most registers are in use; we'll use r0, rmethod, r10, r11
+  const Register recv_klass_reg     = r10;
+  const Register holder_klass_reg   = r0; // declaring interface klass (DECC)
+  const Register resolved_klass_reg = rmethod; // resolved interface klass (REFC)
+  const Register temp_reg           = r11;
+  const Register icholder_reg       = rscratch2;
+
+  Label L_no_such_interface;
+
+  __ ldr(resolved_klass_reg, Address(icholder_reg, CompiledICHolder::holder_klass_offset()));
+  __ ldr(holder_klass_reg,   Address(icholder_reg, CompiledICHolder::holder_metadata_offset()));
 
   // get receiver (need to skip return address on top of stack)
-
   assert(VtableStub::receiver_location() == j_rarg0->as_VMReg(), "receiver expected in j_rarg0");
   // get receiver klass (also an implicit null-check)
   address npe_addr = __ pc();
+  __ load_klass(recv_klass_reg, j_rarg0);
 
-  // Most registers are in use; we'll use r0, rmethod, r10, r11
-  __ load_klass(r10, j_rarg0);
+  // Receiver subtype check against REFC.
+  // Destroys recv_klass_reg value.
+  __ lookup_interface_method(// inputs: rec. class, interface
+                             recv_klass_reg, resolved_klass_reg, noreg,
+                             // outputs:  scan temp. reg1, scan temp. reg2
+                             recv_klass_reg, temp_reg,
+                             L_no_such_interface,
+                             /*return_method=*/false);
 
-  Label throw_icce;
-
-  // Get Method* and entrypoint for compiler
+  // Get selected method from declaring class and itable index
+  __ load_klass(recv_klass_reg, j_rarg0);   // restore recv_klass_reg
   __ lookup_interface_method(// inputs: rec. class, interface, itable index
-                             r10, rscratch2, itable_index,
-                             // outputs: method, scan temp. reg
-                             rmethod, r11,
-                             throw_icce);
+                       recv_klass_reg, holder_klass_reg, itable_index,
+                       // outputs: method, scan temp. reg
+                       rmethod, temp_reg,
+                       L_no_such_interface);
 
   // method (rmethod): Method*
   // j_rarg0: receiver
@@ -183,7 +200,7 @@
   __ ldr(rscratch1, Address(rmethod, Method::from_compiled_offset()));
   __ br(rscratch1);
 
-  __ bind(throw_icce);
+  __ bind(L_no_such_interface);
   __ far_jump(RuntimeAddress(StubRoutines::throw_IncompatibleClassChangeError_entry()));
 
   __ flush();
@@ -205,11 +222,11 @@
   int size = DebugVtables ? 216 : 0;
   if (CountCompiledCalls)
     size += 6 * 4;
-  // FIXME
+  // FIXME: vtable stubs only need 36 bytes
   if (is_vtable_stub)
     size += 52;
   else
-    size += 104;
+    size += 176;
   return size;
 
   // In order to tune these parameters, run the JVM with VM options
@@ -217,33 +234,58 @@
   // actual itable stubs.  Run it with -Xmx31G -XX:+UseCompressedOops.
   //
   // If Universe::narrow_klass_base is nonzero, decoding a compressed
-  // class can take zeveral instructions.  Run it with -Xmx31G
-  // -XX:+UseCompressedOops.
+  // class can take zeveral instructions.
   //
   // The JVM98 app. _202_jess has a megamorphic interface call.
   // The itable code looks like this:
-  // Decoding VtableStub itbl[1]@12
-  //     ldr     w10, [x1,#8]
-  //     lsl     x10, x10, #3
-  //     ldr     w11, [x10,#280]
-  //     add     x11, x10, x11, uxtx #3
-  //     add     x11, x11, #0x1b8
-  //     ldr     x12, [x11]
-  //     cmp     x9, x12
-  //     b.eq    success
-  // loop:
-  //     cbz     x12, throw_icce
-  //     add     x11, x11, #0x10
-  //     ldr     x12, [x11]
-  //     cmp     x9, x12
-  //     b.ne    loop
-  // success:
-  //     ldr     x11, [x11,#8]
-  //     ldr     x12, [x10,x11]
-  //     ldr     x8, [x12,#72]
-  //     br      x8
-  // throw_icce:
-  //     b      throw_ICCE_entry
+
+  //    ldr    xmethod, [xscratch2,#CompiledICHolder::holder_klass_offset]
+  //    ldr    x0, [xscratch2]
+  //    ldr    w10, [x1,#oopDesc::klass_offset_in_bytes]
+  //    mov    xheapbase, #0x3c000000                //   #narrow_klass_base
+  //    movk    xheapbase, #0x3f7, lsl #32
+  //    add    x10, xheapbase, x10
+  //    mov    xheapbase, #0xe7ff0000                //   #heapbase
+  //    movk    xheapbase, #0x3f7, lsl #32
+  //    ldr    w11, [x10,#vtable_length_offset]
+  //    add    x11, x10, x11, uxtx #3
+  //    add    x11, x11, #itableMethodEntry::method_offset_in_bytes
+  //    ldr    x10, [x11]
+  //    cmp    xmethod, x10
+  //    b.eq    found_method
+  // search:
+  //    cbz    x10, no_such_interface
+  //    add    x11, x11, #0x10
+  //    ldr    x10, [x11]
+  //    cmp    xmethod, x10
+  //    b.ne    search
+  // found_method:
+  //    ldr    w10, [x1,#oopDesc::klass_offset_in_bytes]
+  //    mov    xheapbase, #0x3c000000                //   #narrow_klass_base
+  //    movk    xheapbase, #0x3f7, lsl #32
+  //    add    x10, xheapbase, x10
+  //    mov    xheapbase, #0xe7ff0000                //   #heapbase
+  //    movk    xheapbase, #0x3f7, lsl #32
+  //    ldr    w11, [x10,#vtable_length_offset]
+  //    add    x11, x10, x11, uxtx #3
+  //    add    x11, x11, #itableMethodEntry::method_offset_in_bytes
+  //    add    x10, x10, #itentry_off
+  //    ldr    xmethod, [x11]
+  //    cmp    x0, xmethod
+  //    b.eq    found_method2
+  // search2:
+  //    cbz    xmethod, 0x000003ffa872e6cc
+  //    add    x11, x11, #0x10
+  //    ldr    xmethod, [x11]
+  //    cmp    x0, xmethod
+  //    b.ne    search2
+  // found_method2:
+  //    ldr    w11, [x11,#itableOffsetEntry::offset_offset_in_bytes]
+  //    ldr    xmethod, [x10,w11,uxtw]
+  //    ldr    xscratch1, [xmethod,#Method::from_compiled_offset]
+  //    br    xscratch1
+  // no_such_interface:
+  //    b      throw_ICCE_entry
 
 }
 
--- a/src/hotspot/cpu/arm/templateTable_arm.cpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/cpu/arm/templateTable_arm.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -4335,7 +4335,6 @@
   Label done;
   Label initialize_header;
   Label initialize_object;  // including clearing the fields
-  Label allocate_shared;
 
   const bool allow_shared_alloc =
     Universe::heap()->supports_inline_contig_alloc();
@@ -4380,13 +4379,19 @@
   // Klass::_lh_instance_slow_path_bit is really a bit mask, not bit number
   __ tbnz(Rsize, exact_log2(Klass::_lh_instance_slow_path_bit), slow_case);
 
+  // Allocate the instance:
+  //  If TLAB is enabled:
+  //    Try to allocate in the TLAB.
+  //    If fails, go to the slow path.
+  //  Else If inline contiguous allocations are enabled:
+  //    Try to allocate in eden.
+  //    If fails due to heap end, go to slow path.
   //
-  // Allocate the instance
-  // 1) Try to allocate in the TLAB
-  // 2) if fail and the object is large allocate in the shared Eden
-  // 3) if the above fails (or is not applicable), go to a slow case
-  // (creates a new TLAB, etc.)
-
+  //  If TLAB is enabled OR inline contiguous is enabled:
+  //    Initialize the allocation.
+  //    Exit.
+  //
+  //  Go to slow path.
   if (UseTLAB) {
     const Register Rtlab_top = R1_tmp;
     const Register Rtlab_end = R2_tmp;
@@ -4396,7 +4401,7 @@
     __ ldr(Rtlab_end, Address(Rthread, in_bytes(JavaThread::tlab_end_offset())));
     __ add(Rtlab_top, Robj, Rsize);
     __ cmp(Rtlab_top, Rtlab_end);
-    __ b(allow_shared_alloc ? allocate_shared : slow_case, hi);
+    __ b(slow_case, hi);
     __ str(Rtlab_top, Address(Rthread, JavaThread::tlab_top_offset()));
     if (ZeroTLAB) {
       // the fields have been already cleared
@@ -4405,45 +4410,43 @@
       // initialize both the header and fields
       __ b(initialize_object);
     }
-  }
-
-  // Allocation in the shared Eden, if allowed.
-  if (allow_shared_alloc) {
-    __ bind(allocate_shared);
-
-    const Register Rheap_top_addr = R2_tmp;
-    const Register Rheap_top = R5_tmp;
-    const Register Rheap_end = Rtemp;
-    assert_different_registers(Robj, Rklass, Rsize, Rheap_top_addr, Rheap_top, Rheap_end, LR);
-
-    // heap_end now (re)loaded in the loop since also used as a scratch register in the CAS
-    __ ldr_literal(Rheap_top_addr, Lheap_top_addr);
-
-    Label retry;
-    __ bind(retry);
+  } else {
+    // Allocation in the shared Eden, if allowed.
+    if (allow_shared_alloc) {
+      const Register Rheap_top_addr = R2_tmp;
+      const Register Rheap_top = R5_tmp;
+      const Register Rheap_end = Rtemp;
+      assert_different_registers(Robj, Rklass, Rsize, Rheap_top_addr, Rheap_top, Rheap_end, LR);
+
+      // heap_end now (re)loaded in the loop since also used as a scratch register in the CAS
+      __ ldr_literal(Rheap_top_addr, Lheap_top_addr);
+
+      Label retry;
+      __ bind(retry);
 
 #ifdef AARCH64
-    __ ldxr(Robj, Rheap_top_addr);
+      __ ldxr(Robj, Rheap_top_addr);
 #else
-    __ ldr(Robj, Address(Rheap_top_addr));
+      __ ldr(Robj, Address(Rheap_top_addr));
 #endif // AARCH64
 
-    __ ldr(Rheap_end, Address(Rheap_top_addr, (intptr_t)Universe::heap()->end_addr()-(intptr_t)Universe::heap()->top_addr()));
-    __ add(Rheap_top, Robj, Rsize);
-    __ cmp(Rheap_top, Rheap_end);
-    __ b(slow_case, hi);
-
-    // Update heap top atomically.
-    // If someone beats us on the allocation, try again, otherwise continue.
+      __ ldr(Rheap_end, Address(Rheap_top_addr, (intptr_t)Universe::heap()->end_addr()-(intptr_t)Universe::heap()->top_addr()));
+      __ add(Rheap_top, Robj, Rsize);
+      __ cmp(Rheap_top, Rheap_end);
+      __ b(slow_case, hi);
+
+      // Update heap top atomically.
+      // If someone beats us on the allocation, try again, otherwise continue.
 #ifdef AARCH64
-    __ stxr(Rtemp2, Rheap_top, Rheap_top_addr);
-    __ cbnz_w(Rtemp2, retry);
+      __ stxr(Rtemp2, Rheap_top, Rheap_top_addr);
+      __ cbnz_w(Rtemp2, retry);
 #else
-    __ atomic_cas_bool(Robj, Rheap_top, Rheap_top_addr, 0, Rheap_end/*scratched*/);
-    __ b(retry, ne);
+      __ atomic_cas_bool(Robj, Rheap_top, Rheap_top_addr, 0, Rheap_end/*scratched*/);
+      __ b(retry, ne);
 #endif // AARCH64
 
-    __ incr_allocated_bytes(Rsize, Rtemp);
+      __ incr_allocated_bytes(Rsize, Rtemp);
+    }
   }
 
   if (UseTLAB || allow_shared_alloc) {
--- a/src/hotspot/cpu/ppc/c1_MacroAssembler_ppc.cpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/cpu/ppc/c1_MacroAssembler_ppc.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2012, 2015 SAP SE. All rights reserved.
+ * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018 SAP SE. 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
@@ -34,8 +34,8 @@
 #include "runtime/basicLock.hpp"
 #include "runtime/biasedLocking.hpp"
 #include "runtime/os.hpp"
+#include "runtime/sharedRuntime.hpp"
 #include "runtime/stubRoutines.hpp"
-#include "runtime/sharedRuntime.hpp"
 #include "utilities/align.hpp"
 
 
--- a/src/hotspot/cpu/ppc/c1_globals_ppc.hpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/cpu/ppc/c1_globals_ppc.hpp	Mon Jan 22 16:55:01 2018 +0100
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2012, 2015 SAP SE. All rights reserved.
+ * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018 SAP SE. 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
@@ -33,36 +33,36 @@
 // (see c1_globals.hpp)
 
 #ifndef TIERED
-define_pd_global(bool, BackgroundCompilation,        true );
-define_pd_global(bool, CICompileOSR,                 true );
-define_pd_global(bool, InlineIntrinsics,             true );
-define_pd_global(bool, PreferInterpreterNativeStubs, false);
-define_pd_global(bool, ProfileTraps,                 false);
-define_pd_global(bool, UseOnStackReplacement,        true );
-define_pd_global(bool, TieredCompilation,            false);
-define_pd_global(intx, CompileThreshold,             1000 );
+define_pd_global(bool,     BackgroundCompilation,        true);
+define_pd_global(bool,     CICompileOSR,                 true);
+define_pd_global(bool,     InlineIntrinsics,             true);
+define_pd_global(bool,     PreferInterpreterNativeStubs, false);
+define_pd_global(bool,     ProfileTraps,                 false);
+define_pd_global(bool,     UseOnStackReplacement,        true);
+define_pd_global(bool,     TieredCompilation,            false);
+define_pd_global(intx,     CompileThreshold,             1000);
 
-define_pd_global(intx, OnStackReplacePercentage,     1400 );
-define_pd_global(bool, UseTLAB,                      true );
-define_pd_global(bool, ProfileInterpreter,           false);
-define_pd_global(intx, FreqInlineSize,               325  );
-define_pd_global(bool, ResizeTLAB,                   true );
-define_pd_global(intx, ReservedCodeCacheSize,        32*M );
-define_pd_global(intx, CodeCacheExpansionSize,       32*K );
-define_pd_global(uintx,CodeCacheMinBlockLength,      1);
-define_pd_global(uintx,MetaspaceSize,                12*M );
-define_pd_global(bool, NeverActAsServerClassMachine, true );
-define_pd_global(intx, NewSizeThreadIncrease,        16*K );
-define_pd_global(uint64_t,MaxRAM,                    1ULL*G);
-define_pd_global(intx, InitialCodeCacheSize,         160*K);
+define_pd_global(intx,     OnStackReplacePercentage,     1400);
+define_pd_global(bool,     UseTLAB,                      true);
+define_pd_global(bool,     ProfileInterpreter,           false);
+define_pd_global(intx,     FreqInlineSize,               325 );
+define_pd_global(bool,     ResizeTLAB,                   true);
+define_pd_global(uintx,    ReservedCodeCacheSize,        32*M);
+define_pd_global(uintx,    CodeCacheExpansionSize,       32*K);
+define_pd_global(uintx,    CodeCacheMinBlockLength,      1);
+define_pd_global(size_t,   MetaspaceSize,                12*M);
+define_pd_global(bool,     NeverActAsServerClassMachine, true);
+define_pd_global(size_t,   NewSizeThreadIncrease,        16*K);
+define_pd_global(uint64_t, MaxRAM,                       1ULL*G);
+define_pd_global(uintx,    InitialCodeCacheSize,         160*K);
 #endif // !TIERED
 
-define_pd_global(bool, UseTypeProfile,               false);
-define_pd_global(bool, RoundFPResults,               false);
+define_pd_global(bool,     UseTypeProfile,               false);
+define_pd_global(bool,     RoundFPResults,               false);
 
-define_pd_global(bool, LIRFillDelaySlots,            false);
-define_pd_global(bool, OptimizeSinglePrecision,      false);
-define_pd_global(bool, CSEArrayLength,               true );
-define_pd_global(bool, TwoOperandLIRForm,            false);
+define_pd_global(bool,     LIRFillDelaySlots,            false);
+define_pd_global(bool,     OptimizeSinglePrecision,      false);
+define_pd_global(bool,     CSEArrayLength,               true);
+define_pd_global(bool,     TwoOperandLIRForm,            false);
 
 #endif // CPU_PPC_VM_C1_GLOBALS_PPC_HPP
--- a/src/hotspot/cpu/ppc/c2_globals_ppc.hpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/cpu/ppc/c2_globals_ppc.hpp	Mon Jan 22 16:55:01 2018 +0100
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2012, 2016 SAP SE. All rights reserved.
+ * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018 SAP SE. 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
@@ -39,7 +39,7 @@
 define_pd_global(bool, ProfileTraps,                 true);
 define_pd_global(bool, UseOnStackReplacement,        true);
 define_pd_global(bool, ProfileInterpreter,           true);
-define_pd_global(bool, TieredCompilation,            true);
+define_pd_global(bool, TieredCompilation,            trueInTiered);
 define_pd_global(intx, CompileThreshold,             10000);
 
 define_pd_global(intx, OnStackReplacePercentage,     140);
@@ -78,27 +78,27 @@
 //   x.f = 0
 //   loc = x.f
 //   NullCheck loc
-define_pd_global(bool, OptoScheduling,               false);
-define_pd_global(bool, IdealizeClearArrayNode,       true);
+define_pd_global(bool,     OptoScheduling,               false);
+define_pd_global(bool,     IdealizeClearArrayNode,       true);
 
-define_pd_global(intx, InitialCodeCacheSize,         2048*K); // Integral multiple of CodeCacheExpansionSize
-define_pd_global(intx, ReservedCodeCacheSize,        256*M);
-define_pd_global(intx, NonProfiledCodeHeapSize,      125*M);
-define_pd_global(intx, ProfiledCodeHeapSize,         126*M);
-define_pd_global(intx, NonNMethodCodeHeapSize,       5*M  );
-define_pd_global(intx, CodeCacheExpansionSize,       64*K);
+define_pd_global(uintx,    InitialCodeCacheSize,         2048*K); // Integral multiple of CodeCacheExpansionSize
+define_pd_global(uintx,    ReservedCodeCacheSize,        256*M);
+define_pd_global(uintx,    NonProfiledCodeHeapSize,      125*M);
+define_pd_global(uintx,    ProfiledCodeHeapSize,         126*M);
+define_pd_global(uintx,    NonNMethodCodeHeapSize,       5*M  );
+define_pd_global(uintx,    CodeCacheExpansionSize,       64*K);
 
 // Ergonomics related flags
-define_pd_global(uint64_t, MaxRAM,                   4ULL*G);
-define_pd_global(uintx, CodeCacheMinBlockLength,     4);
-define_pd_global(uintx, CodeCacheMinimumUseSpace,    400*K);
+define_pd_global(uint64_t, MaxRAM,                       128ULL*G);
+define_pd_global(uintx,    CodeCacheMinBlockLength,      4);
+define_pd_global(uintx,    CodeCacheMinimumUseSpace,     400*K);
 
-define_pd_global(bool,  TrapBasedRangeChecks,        true);
+define_pd_global(bool,     TrapBasedRangeChecks,          true);
 
 // Heap related flags
-define_pd_global(size_t, MetaspaceSize,              ScaleForWordSize(16*M));
+define_pd_global(size_t,   MetaspaceSize,                ScaleForWordSize(16*M));
 
 // Ergonomics related flags
-define_pd_global(bool, NeverActAsServerClassMachine, false);
+define_pd_global(bool,     NeverActAsServerClassMachine, false);
 
 #endif // CPU_PPC_VM_C2_GLOBALS_PPC_HPP
--- a/src/hotspot/cpu/ppc/c2_init_ppc.cpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/cpu/ppc/c2_init_ppc.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2012, 2015 SAP SE. All rights reserved.
+ * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018 SAP SE. 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
@@ -29,11 +29,11 @@
 #include "runtime/globals.hpp"
 #include "utilities/debug.hpp"
 
-// processor dependent initialization for ppc
+// Processor dependent initialization of C2 compiler for ppc.
 
 void Compile::pd_compiler2_init() {
 
-  // Power7 and later
+  // Power7 and later.
   if (PowerArchitecturePPC64 > 6) {
     if (FLAG_IS_DEFAULT(UsePopCountInstruction)) {
       FLAG_SET_ERGO(bool, UsePopCountInstruction, true);
--- a/src/hotspot/cpu/ppc/globals_ppc.hpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/cpu/ppc/globals_ppc.hpp	Mon Jan 22 16:55:01 2018 +0100
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 2002, 2017, Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2012, 2017 SAP SE. All rights reserved.
+ * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018 SAP SE. 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
@@ -86,14 +86,14 @@
 define_pd_global(bool, ThreadLocalHandshakes, true);
 
 // Platform dependent flag handling: flags only defined on this platform.
-#define ARCH_FLAGS(develop, \
-                   product, \
-                   diagnostic, \
+#define ARCH_FLAGS(develop,      \
+                   product,      \
+                   diagnostic,   \
                    experimental, \
-                   notproduct, \
-                   range, \
-                   constraint, \
-                   writeable)  \
+                   notproduct,   \
+                   range,        \
+                   constraint,   \
+                   writeable)    \
                                                                             \
   product(uintx, PowerArchitecturePPC64, 0,                                 \
           "CPU Version: x for PowerX. Currently recognizes Power5 to "      \
--- a/src/hotspot/cpu/ppc/icache_ppc.cpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/cpu/ppc/icache_ppc.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2012, 2013 SAP SE. All rights reserved.
+ * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018 SAP SE. 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
@@ -24,7 +24,6 @@
  */
 
 #include "precompiled.hpp"
-#include "assembler_ppc.inline.hpp"
 #include "runtime/icache.hpp"
 
 // Use inline assembler to implement icache flush.
@@ -32,7 +31,7 @@
   address end = start + (unsigned int)lines*ICache::line_size;
   assert(start <= end, "flush_icache parms");
 
-  // store modified cache lines from data cache
+  // Store modified cache lines from data cache.
   for (address a = start; a < end; a += ICache::line_size) {
     __asm__ __volatile__(
      "dcbst 0, %0  \n"
@@ -48,7 +47,7 @@
      :
      : "memory");
 
-  // invalidate respective cache lines in instruction cache
+  // Invalidate respective cache lines in instruction cache.
   for (address a = start; a < end; a += ICache::line_size) {
     __asm__ __volatile__(
      "icbi 0, %0   \n"
@@ -57,7 +56,7 @@
      : "memory");
   }
 
-  // discard fetched instructions
+  // Discard fetched instructions.
   __asm__ __volatile__(
      "isync \n"
      :
@@ -71,6 +70,8 @@
 
   *flush_icache_stub = (ICache::flush_icache_stub_t)ICache::ppc64_flush_icache;
 
-  // First call to flush itself
+  // First call to flush itself.
+  // Pointless since we call C, but it is expected to get
+  // executed during VM_Version::determine_features().
   ICache::invalidate_range((address)(*flush_icache_stub), 0);
 }
--- a/src/hotspot/cpu/ppc/interp_masm_ppc_64.cpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/cpu/ppc/interp_masm_ppc_64.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2012, 2017 SAP SE. All rights reserved.
+ * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018 SAP SE. 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
@@ -32,6 +32,10 @@
 #include "runtime/safepointMechanism.hpp"
 #include "runtime/sharedRuntime.hpp"
 
+// Implementation of InterpreterMacroAssembler.
+
+// This file specializes the assembler with interpreter-specific macros.
+
 #ifdef PRODUCT
 #define BLOCK_COMMENT(str) // nothing
 #else
--- a/src/hotspot/cpu/ppc/jniFastGetField_ppc.cpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/cpu/ppc/jniFastGetField_ppc.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2012, 2013 SAP SE. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018 SAP SE. 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
@@ -24,7 +24,7 @@
  */
 
 #include "precompiled.hpp"
-#include "assembler_ppc.inline.hpp"
+#include "asm/assembler.inline.hpp"
 #include "memory/resourceArea.hpp"
 #include "prims/jniFastGetField.hpp"
 #include "prims/jvm_misc.hpp"
--- a/src/hotspot/cpu/ppc/macroAssembler_ppc.cpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/cpu/ppc/macroAssembler_ppc.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -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.
  * Copyright (c) 2012, 2017, SAP SE. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -2883,10 +2883,6 @@
     //assert(ObjectMonitor::recursions_size_in_bytes() == 8, "unexpected size");
     asm_assert_mem8_is_zero(ObjectMonitor::recursions_offset_in_bytes(), temp,
                             "monitor->_recursions should be 0", -1);
-    // Invariant 2: OwnerIsThread shouldn't be 0.
-    //assert(ObjectMonitor::OwnerIsThread_size_in_bytes() == 4, "unexpected size");
-    //asm_assert_mem4_isnot_zero(ObjectMonitor::OwnerIsThread_offset_in_bytes(), temp,
-    //                           "monitor->OwnerIsThread shouldn't be 0", -1);
 #   endif
 
 #if INCLUDE_RTM_OPT
--- a/src/hotspot/cpu/ppc/nativeInst_ppc.hpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/cpu/ppc/nativeInst_ppc.hpp	Mon Jan 22 16:55:01 2018 +0100
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2012, 2015 SAP SE. All rights reserved.
+ * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018 SAP SE. 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,7 +26,6 @@
 #ifndef CPU_PPC_VM_NATIVEINST_PPC_HPP
 #define CPU_PPC_VM_NATIVEINST_PPC_HPP
 
-#include "asm/assembler.hpp"
 #include "asm/macroAssembler.hpp"
 #include "memory/allocation.hpp"
 #include "runtime/icache.hpp"
--- a/src/hotspot/cpu/ppc/runtime_ppc.cpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/cpu/ppc/runtime_ppc.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2012, 2015 SAP SE. All rights reserved.
+ * Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018 SAP SE. 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
@@ -25,7 +25,6 @@
 
 #include "precompiled.hpp"
 #ifdef COMPILER2
-#include "asm/assembler.inline.hpp"
 #include "asm/macroAssembler.inline.hpp"
 #include "classfile/systemDictionary.hpp"
 #include "code/vmreg.hpp"
--- a/src/hotspot/cpu/ppc/sharedRuntime_ppc.cpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/cpu/ppc/sharedRuntime_ppc.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2012, 2017 SAP SE. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018 SAP SE. 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
@@ -1912,8 +1912,8 @@
   // - *_slot_offset Indicates offset from SP in number of stack slots.
   // - *_offset      Indicates offset from SP in bytes.
 
-  int stack_slots = c_calling_convention(out_sig_bt, out_regs, out_regs2, total_c_args) // 1+2)
-                  + SharedRuntime::out_preserve_stack_slots(); // See c_calling_convention.
+  int stack_slots = c_calling_convention(out_sig_bt, out_regs, out_regs2, total_c_args) + // 1+2)
+                    SharedRuntime::out_preserve_stack_slots(); // See c_calling_convention.
 
   // Now the space for the inbound oop handle area.
   int total_save_slots = num_java_iarg_registers * VMRegImpl::slots_per_word;
@@ -2044,7 +2044,8 @@
   OopMap    *oop_map  = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
 
   if (is_critical_native) {
-    check_needs_gc_for_critical_native(masm, stack_slots, total_in_args, oop_handle_slot_offset, oop_maps, in_regs, in_sig_bt, r_temp_1);
+    check_needs_gc_for_critical_native(masm, stack_slots, total_in_args, oop_handle_slot_offset,
+                                       oop_maps, in_regs, in_sig_bt, r_temp_1);
   }
 
   // Move arguments from register/stack to register/stack.
--- a/src/hotspot/cpu/ppc/stubGenerator_ppc.cpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/cpu/ppc/stubGenerator_ppc.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -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.
  * Copyright (c) 2012, 2017, SAP SE. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -40,6 +40,10 @@
 #include "runtime/thread.inline.hpp"
 #include "utilities/align.hpp"
 
+// Declaration and definition of StubGenerator (no .hpp file).
+// For a more detailed description of the stub routine structure
+// see the comment in stubRoutines.hpp.
+
 #define __ _masm->
 
 #ifdef PRODUCT
--- a/src/hotspot/cpu/ppc/stubRoutines_ppc_64.cpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/cpu/ppc/stubRoutines_ppc_64.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved.
  * Copyright (c) 2012, 2017, SAP SE. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -23,6 +23,7 @@
  *
  */
 
+#include "precompiled.hpp"
 #include "asm/macroAssembler.inline.hpp"
 #include "runtime/stubRoutines.hpp"
 
--- a/src/hotspot/cpu/ppc/templateInterpreterGenerator_ppc.cpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/cpu/ppc/templateInterpreterGenerator_ppc.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved.
  * Copyright (c) 2015, 2017, SAP SE. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -582,25 +582,6 @@
   return entry;
 }
 
-#if 0
-// Call special ClassCastException constructor taking object to cast
-// and target class as arguments.
-address TemplateInterpreterGenerator::generate_ClassCastException_verbose_handler() {
-  address entry = __ pc();
-
-  // Expression stack must be empty before entering the VM if an
-  // exception happened.
-  __ empty_expression_stack();
-
-  // Thread will be loaded to R3_ARG1.
-  // Target class oop is in register R5_ARG3 by convention!
-  __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_ClassCastException_verbose), R17_tos, R5_ARG3);
-  // Above call must not return here since exception pending.
-  DEBUG_ONLY(__ should_not_reach_here();)
-  return entry;
-}
-#endif
-
 address TemplateInterpreterGenerator::generate_ClassCastException_handler() {
   address entry = __ pc();
   // Expression stack must be empty before entering the VM if an
@@ -1896,7 +1877,6 @@
   return NULL;
 }
 
-
 /**
  * Method entry for static native methods:
  *   int java.util.zip.CRC32.updateBytes(     int crc, byte[] b,  int off, int len)
--- a/src/hotspot/cpu/s390/bytes_s390.hpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/cpu/s390/bytes_s390.hpp	Mon Jan 22 16:55:01 2018 +0100
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2016 SAP SE. All rights reserved.
+ * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2018 SAP SE. 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
@@ -42,11 +42,6 @@
   //
   // In short, it makes no sense on z/Architecture to piecemeal get or put unaligned data.
 
-  // Only swap on little endian machines => suffix `_le'.
-  static inline u2   swap_u2_le(u2 x) { return x; }
-  static inline u4   swap_u4_le(u4 x) { return x; }
-  static inline u8   swap_u8_le(u8 x) { return x; }
-
   static inline u2   get_native_u2(address p) { return *(u2*)p; }
   static inline u4   get_native_u4(address p) { return *(u4*)p; }
   static inline u8   get_native_u8(address p) { return *(u8*)p; }
@@ -55,7 +50,8 @@
   static inline void put_native_u4(address p, u4 x) { *(u4*)p = x; }
   static inline void put_native_u8(address p, u8 x) { *(u8*)p = x; }
 
-#include "bytes_linux_s390.inline.hpp"
+  // The following header contains the implementations of swap_u2, swap_u4, and swap_u8.
+#include OS_CPU_HEADER_INLINE(bytes)
 
   // Efficient reading and writing of unaligned unsigned data in Java byte ordering (i.e. big-endian ordering)
   static inline u2   get_Java_u2(address p) { return get_native_u2(p); }
--- a/src/hotspot/cpu/s390/c1_globals_s390.hpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/cpu/s390/c1_globals_s390.hpp	Mon Jan 22 16:55:01 2018 +0100
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2016 SAP SE. All rights reserved.
+ * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2018 SAP SE. 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
@@ -48,7 +48,7 @@
 define_pd_global(bool,     ProfileInterpreter,           false);
 define_pd_global(intx,     FreqInlineSize,               325);
 define_pd_global(bool,     ResizeTLAB,                   true);
-define_pd_global(intx,     ReservedCodeCacheSize,        32*M);
+define_pd_global(uintx,    ReservedCodeCacheSize,        32*M);
 define_pd_global(uintx,    NonProfiledCodeHeapSize,      13*M);
 define_pd_global(uintx,    ProfiledCodeHeapSize,         14*M);
 define_pd_global(uintx,    NonNMethodCodeHeapSize,       5*M);
--- a/src/hotspot/cpu/s390/c2_globals_s390.hpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/cpu/s390/c2_globals_s390.hpp	Mon Jan 22 16:55:01 2018 +0100
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2016 SAP SE. All rights reserved.
+ * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2018 SAP SE. 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
@@ -58,7 +58,7 @@
 define_pd_global(intx, LoopPercentProfileLimit,      10);
 define_pd_global(intx, MinJumpTableSize,             18);
 
-// Peephole and CISC spilling both break the graph, and so makes the
+// Peephole and CISC spilling both break the graph, and so make the
 // scheduler sick.
 define_pd_global(bool, OptoPeephole,                 false);
 define_pd_global(bool, UseCISCSpill,                 true);
--- a/src/hotspot/cpu/s390/globals_s390.hpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/cpu/s390/globals_s390.hpp	Mon Jan 22 16:55:01 2018 +0100
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2016, 2017 Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2016, 2017 SAP SE. All rights reserved.
+ * Copyright (c) 2016, 2018 SAP SE. 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
@@ -87,7 +87,14 @@
 
 define_pd_global(bool, ThreadLocalHandshakes, true);
 
-#define ARCH_FLAGS(develop, product, diagnostic, experimental, notproduct, range, constraint, writeable) \
+#define ARCH_FLAGS(develop,      \
+                   product,      \
+                   diagnostic,   \
+                   experimental, \
+                   notproduct,   \
+                   range,        \
+                   constraint,   \
+                   writeable)    \
                                                                               \
   /* Reoptimize code-sequences of calls at runtime, e.g. replace an */        \
   /* indirect call by a direct call.                                */        \
--- a/src/hotspot/os/aix/os_aix.cpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/os/aix/os_aix.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
  * Copyright (c) 2012, 2017 SAP SE. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -1723,7 +1723,7 @@
   local_sem_post();
 }
 
-static int check_pending_signals(bool wait) {
+static int check_pending_signals() {
   Atomic::store(0, &sigint_count);
   for (;;) {
     for (int i = 0; i < NSIG + 1; i++) {
@@ -1732,9 +1732,6 @@
         return i;
       }
     }
-    if (!wait) {
-      return -1;
-    }
     JavaThread *thread = JavaThread::current();
     ThreadBlockInVM tbivm(thread);
 
@@ -1763,12 +1760,8 @@
   }
 }
 
-int os::signal_lookup() {
-  return check_pending_signals(false);
-}
-
 int os::signal_wait() {
-  return check_pending_signals(true);
+  return check_pending_signals();
 }
 
 ////////////////////////////////////////////////////////////////////////////////
--- a/src/hotspot/os/bsd/os_bsd.cpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/os/bsd/os_bsd.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 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
@@ -52,13 +52,13 @@
 #include "runtime/orderAccess.inline.hpp"
 #include "runtime/osThread.hpp"
 #include "runtime/perfMemory.hpp"
+#include "runtime/semaphore.hpp"
 #include "runtime/sharedRuntime.hpp"
 #include "runtime/statSampler.hpp"
 #include "runtime/stubRoutines.hpp"
 #include "runtime/thread.inline.hpp"
 #include "runtime/threadCritical.hpp"
 #include "runtime/timer.hpp"
-#include "semaphore_bsd.hpp"
 #include "services/attachListener.hpp"
 #include "services/memTracker.hpp"
 #include "services/runtimeService.hpp"
@@ -91,7 +91,6 @@
 # include <time.h>
 # include <pwd.h>
 # include <poll.h>
-# include <semaphore.h>
 # include <fcntl.h>
 # include <string.h>
 # include <sys/param.h>
@@ -1829,135 +1828,28 @@
 
 // a counter for each possible signal value
 static volatile jint pending_signals[NSIG+1] = { 0 };
-
-// Bsd(POSIX) specific hand shaking semaphore.
-#ifdef __APPLE__
-typedef semaphore_t os_semaphore_t;
-
-  #define SEM_INIT(sem, value)    semaphore_create(mach_task_self(), &sem, SYNC_POLICY_FIFO, value)
-  #define SEM_WAIT(sem)           semaphore_wait(sem)
-  #define SEM_POST(sem)           semaphore_signal(sem)
-  #define SEM_DESTROY(sem)        semaphore_destroy(mach_task_self(), sem)
-#else
-typedef sem_t os_semaphore_t;
-
-  #define SEM_INIT(sem, value)    sem_init(&sem, 0, value)
-  #define SEM_WAIT(sem)           sem_wait(&sem)
-  #define SEM_POST(sem)           sem_post(&sem)
-  #define SEM_DESTROY(sem)        sem_destroy(&sem)
-#endif
-
-#ifdef __APPLE__
-// OS X doesn't support unamed POSIX semaphores, so the implementation in os_posix.cpp can't be used.
-
-static const char* sem_init_strerror(kern_return_t value) {
-  switch (value) {
-    case KERN_INVALID_ARGUMENT:  return "Invalid argument";
-    case KERN_RESOURCE_SHORTAGE: return "Resource shortage";
-    default:                     return "Unknown";
-  }
-}
-
-OSXSemaphore::OSXSemaphore(uint value) {
-  kern_return_t ret = SEM_INIT(_semaphore, value);
-
-  guarantee(ret == KERN_SUCCESS, "Failed to create semaphore: %s", sem_init_strerror(ret));
-}
-
-OSXSemaphore::~OSXSemaphore() {
-  SEM_DESTROY(_semaphore);
-}
-
-void OSXSemaphore::signal(uint count) {
-  for (uint i = 0; i < count; i++) {
-    kern_return_t ret = SEM_POST(_semaphore);
-
-    assert(ret == KERN_SUCCESS, "Failed to signal semaphore");
-  }
-}
-
-void OSXSemaphore::wait() {
-  kern_return_t ret;
-  while ((ret = SEM_WAIT(_semaphore)) == KERN_ABORTED) {
-    // Semaphore was interrupted. Retry.
-  }
-  assert(ret == KERN_SUCCESS, "Failed to wait on semaphore");
-}
-
-jlong OSXSemaphore::currenttime() {
-  struct timeval tv;
-  gettimeofday(&tv, NULL);
-  return (tv.tv_sec * NANOSECS_PER_SEC) + (tv.tv_usec * 1000);
-}
-
-bool OSXSemaphore::trywait() {
-  return timedwait(0, 0);
-}
-
-bool OSXSemaphore::timedwait(unsigned int sec, int nsec) {
-  kern_return_t kr = KERN_ABORTED;
-  mach_timespec_t waitspec;
-  waitspec.tv_sec = sec;
-  waitspec.tv_nsec = nsec;
-
-  jlong starttime = currenttime();
-
-  kr = semaphore_timedwait(_semaphore, waitspec);
-  while (kr == KERN_ABORTED) {
-    jlong totalwait = (sec * NANOSECS_PER_SEC) + nsec;
-
-    jlong current = currenttime();
-    jlong passedtime = current - starttime;
-
-    if (passedtime >= totalwait) {
-      waitspec.tv_sec = 0;
-      waitspec.tv_nsec = 0;
-    } else {
-      jlong waittime = totalwait - (current - starttime);
-      waitspec.tv_sec = waittime / NANOSECS_PER_SEC;
-      waitspec.tv_nsec = waittime % NANOSECS_PER_SEC;
-    }
-
-    kr = semaphore_timedwait(_semaphore, waitspec);
-  }
-
-  return kr == KERN_SUCCESS;
-}
-
-#else
-// Use POSIX implementation of semaphores.
-
-struct timespec PosixSemaphore::create_timespec(unsigned int sec, int nsec) {
-  struct timespec ts;
-  unpackTime(&ts, false, (sec * NANOSECS_PER_SEC) + nsec);
-
-  return ts;
-}
-
-#endif // __APPLE__
-
-static os_semaphore_t sig_sem;
-
-#ifdef __APPLE__
-static OSXSemaphore sr_semaphore;
-#else
-static PosixSemaphore sr_semaphore;
-#endif
+static Semaphore* sig_sem = NULL;
 
 void os::signal_init_pd() {
   // Initialize signal structures
   ::memset((void*)pending_signals, 0, sizeof(pending_signals));
 
   // Initialize signal semaphore
-  ::SEM_INIT(sig_sem, 0);
+  sig_sem = new Semaphore();
 }
 
 void os::signal_notify(int sig) {
-  Atomic::inc(&pending_signals[sig]);
-  ::SEM_POST(sig_sem);
+  if (sig_sem != NULL) {
+    Atomic::inc(&pending_signals[sig]);
+    sig_sem->signal();
+  } else {
+    // Signal thread is not created with ReduceSignalUsage and signal_init_pd
+    // initialization isn't called.
+    assert(ReduceSignalUsage, "signal semaphore should be created");
+  }
 }
 
-static int check_pending_signals(bool wait) {
+static int check_pending_signals() {
   Atomic::store(0, &sigint_count);
   for (;;) {
     for (int i = 0; i < NSIG + 1; i++) {
@@ -1966,9 +1858,6 @@
         return i;
       }
     }
-    if (!wait) {
-      return -1;
-    }
     JavaThread *thread = JavaThread::current();
     ThreadBlockInVM tbivm(thread);
 
@@ -1976,7 +1865,7 @@
     do {
       thread->set_suspend_equivalent();
       // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
-      ::SEM_WAIT(sig_sem);
+      sig_sem->wait();
 
       // were we externally suspended while we were waiting?
       threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
@@ -1985,7 +1874,7 @@
         // another thread suspended us. We don't want to continue running
         // while suspended because that would surprise the thread that
         // suspended us.
-        ::SEM_POST(sig_sem);
+        sig_sem->signal();
 
         thread->java_suspend_self();
       }
@@ -1993,12 +1882,8 @@
   }
 }
 
-int os::signal_lookup() {
-  return check_pending_signals(false);
-}
-
 int os::signal_wait() {
-  return check_pending_signals(true);
+  return check_pending_signals();
 }
 
 ////////////////////////////////////////////////////////////////////////////////
@@ -2663,6 +2548,12 @@
 //
 // Currently only ever called on the VMThread or JavaThread
 //
+#ifdef __APPLE__
+static OSXSemaphore sr_semaphore;
+#else
+static PosixSemaphore sr_semaphore;
+#endif
+
 static void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context) {
   // Save and restore errno to avoid confusing native code with EINTR
   // after sigsuspend.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/hotspot/os/bsd/semaphore_bsd.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -0,0 +1,107 @@
+/*
+ * 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.
+ *
+ * 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/precompiled.hpp"
+#include "semaphore_bsd.hpp"
+#include "utilities/debug.hpp"
+
+#include <semaphore.h>
+
+#ifdef __APPLE__
+// OS X doesn't support unamed POSIX semaphores, so the implementation in os_posix.cpp can't be used.
+
+static const char* sem_init_strerror(kern_return_t value) {
+  switch (value) {
+    case KERN_INVALID_ARGUMENT:  return "Invalid argument";
+    case KERN_RESOURCE_SHORTAGE: return "Resource shortage";
+    default:                     return "Unknown";
+  }
+}
+
+OSXSemaphore::OSXSemaphore(uint value) {
+  kern_return_t ret = semaphore_create(mach_task_self(), &_semaphore, SYNC_POLICY_FIFO, value);
+
+  guarantee(ret == KERN_SUCCESS, "Failed to create semaphore: %s", sem_init_strerror(ret));
+}
+
+OSXSemaphore::~OSXSemaphore() {
+  semaphore_destroy(mach_task_self(), _semaphore);
+}
+
+void OSXSemaphore::signal(uint count) {
+  for (uint i = 0; i < count; i++) {
+    kern_return_t ret = semaphore_signal(_semaphore);
+
+    assert(ret == KERN_SUCCESS, "Failed to signal semaphore");
+  }
+}
+
+void OSXSemaphore::wait() {
+  kern_return_t ret;
+  while ((ret = semaphore_wait(_semaphore)) == KERN_ABORTED) {
+    // Semaphore was interrupted. Retry.
+  }
+  assert(ret == KERN_SUCCESS, "Failed to wait on semaphore");
+}
+
+int64_t OSXSemaphore::currenttime() {
+  struct timeval tv;
+  gettimeofday(&tv, NULL);
+  return (tv.tv_sec * NANOSECS_PER_SEC) + (tv.tv_usec * 1000);
+}
+
+bool OSXSemaphore::trywait() {
+  return timedwait(0, 0);
+}
+
+bool OSXSemaphore::timedwait(unsigned int sec, int nsec) {
+  kern_return_t kr = KERN_ABORTED;
+  mach_timespec_t waitspec;
+  waitspec.tv_sec = sec;
+  waitspec.tv_nsec = nsec;
+
+  int64_t starttime = currenttime();
+
+  kr = semaphore_timedwait(_semaphore, waitspec);
+  while (kr == KERN_ABORTED) {
+    int64_t totalwait = (sec * NANOSECS_PER_SEC) + nsec;
+
+    int64_t current = currenttime();
+    int64_t passedtime = current - starttime;
+
+    if (passedtime >= totalwait) {
+      waitspec.tv_sec = 0;
+      waitspec.tv_nsec = 0;
+    } else {
+      int64_t waittime = totalwait - (current - starttime);
+      waitspec.tv_sec = waittime / NANOSECS_PER_SEC;
+      waitspec.tv_nsec = waittime % NANOSECS_PER_SEC;
+    }
+
+    kr = semaphore_timedwait(_semaphore, waitspec);
+  }
+
+  return kr == KERN_SUCCESS;
+}
+#endif // __APPLE__
--- a/src/hotspot/os/bsd/semaphore_bsd.hpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/os/bsd/semaphore_bsd.hpp	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -53,7 +53,7 @@
   bool timedwait(unsigned int sec, int nsec);
 
  private:
-  static jlong currenttime();
+  static int64_t currenttime();
 };
 
 typedef OSXSemaphore SemaphoreImpl;
--- a/src/hotspot/os/linux/os_linux.cpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/os/linux/os_linux.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 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
@@ -95,7 +95,6 @@
 # include <sys/wait.h>
 # include <pwd.h>
 # include <poll.h>
-# include <semaphore.h>
 # include <fcntl.h>
 # include <string.h>
 # include <syscall.h>
@@ -2479,11 +2478,11 @@
   return CAST_FROM_FN_PTR(void*, UserHandler);
 }
 
-struct timespec PosixSemaphore::create_timespec(unsigned int sec, int nsec) {
+static struct timespec create_semaphore_timespec(unsigned int sec, int nsec) {
   struct timespec ts;
   // Semaphore's are always associated with CLOCK_REALTIME
   os::Linux::clock_gettime(CLOCK_REALTIME, &ts);
-  // see unpackTime for discussion on overflow checking
+  // see os_posix.cpp for discussion on overflow checking
   if (sec >= MAX_SECS) {
     ts.tv_sec += MAX_SECS;
     ts.tv_nsec = 0;
@@ -2535,7 +2534,7 @@
 static volatile jint pending_signals[NSIG+1] = { 0 };
 
 // Linux(POSIX) specific hand shaking semaphore.
-static sem_t sig_sem;
+static Semaphore* sig_sem = NULL;
 static PosixSemaphore sr_semaphore;
 
 void os::signal_init_pd() {
@@ -2543,15 +2542,21 @@
   ::memset((void*)pending_signals, 0, sizeof(pending_signals));
 
   // Initialize signal semaphore
-  ::sem_init(&sig_sem, 0, 0);
+  sig_sem = new Semaphore();
 }
 
 void os::signal_notify(int sig) {
-  Atomic::inc(&pending_signals[sig]);
-  ::sem_post(&sig_sem);
-}
-
-static int check_pending_signals(bool wait) {
+  if (sig_sem != NULL) {
+    Atomic::inc(&pending_signals[sig]);
+    sig_sem->signal();
+  } else {
+    // Signal thread is not created with ReduceSignalUsage and signal_init_pd
+    // initialization isn't called.
+    assert(ReduceSignalUsage, "signal semaphore should be created");
+  }
+}
+
+static int check_pending_signals() {
   Atomic::store(0, &sigint_count);
   for (;;) {
     for (int i = 0; i < NSIG + 1; i++) {
@@ -2560,9 +2565,6 @@
         return i;
       }
     }
-    if (!wait) {
-      return -1;
-    }
     JavaThread *thread = JavaThread::current();
     ThreadBlockInVM tbivm(thread);
 
@@ -2570,7 +2572,7 @@
     do {
       thread->set_suspend_equivalent();
       // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
-      ::sem_wait(&sig_sem);
+      sig_sem->wait();
 
       // were we externally suspended while we were waiting?
       threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
@@ -2579,7 +2581,7 @@
         // another thread suspended us. We don't want to continue running
         // while suspended because that would surprise the thread that
         // suspended us.
-        ::sem_post(&sig_sem);
+        sig_sem->signal();
 
         thread->java_suspend_self();
       }
@@ -2587,12 +2589,8 @@
   }
 }
 
-int os::signal_lookup() {
-  return check_pending_signals(false);
-}
-
 int os::signal_wait() {
-  return check_pending_signals(true);
+  return check_pending_signals();
 }
 
 ////////////////////////////////////////////////////////////////////////////////
@@ -4317,7 +4315,7 @@
 
   // managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED
   while (true) {
-    if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
+    if (sr_semaphore.timedwait(create_semaphore_timespec(0, 2 * NANOSECS_PER_MILLISEC))) {
       break;
     } else {
       // timeout
@@ -4351,7 +4349,7 @@
 
   while (true) {
     if (sr_notify(osthread) == 0) {
-      if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
+      if (sr_semaphore.timedwait(create_semaphore_timespec(0, 2 * NANOSECS_PER_MILLISEC))) {
         if (osthread->sr.is_running()) {
           return;
         }
--- a/src/hotspot/os/posix/os_posix.cpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/os/posix/os_posix.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 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,14 +31,8 @@
 #include "utilities/macros.hpp"
 #include "utilities/vmError.hpp"
 
-#ifndef __APPLE__
-// POSIX unamed semaphores are not supported on OS X.
-#include "semaphore_posix.hpp"
-#endif
-
 #include <dlfcn.h>
 #include <pthread.h>
-#include <semaphore.h>
 #include <signal.h>
 #include <sys/mman.h>
 #include <sys/resource.h>
@@ -1499,67 +1493,6 @@
   }
 }
 
-// POSIX unamed semaphores are not supported on OS X.
-#ifndef __APPLE__
-
-PosixSemaphore::PosixSemaphore(uint value) {
-  int ret = sem_init(&_semaphore, 0, value);
-
-  guarantee_with_errno(ret == 0, "Failed to initialize semaphore");
-}
-
-PosixSemaphore::~PosixSemaphore() {
-  sem_destroy(&_semaphore);
-}
-
-void PosixSemaphore::signal(uint count) {
-  for (uint i = 0; i < count; i++) {
-    int ret = sem_post(&_semaphore);
-
-    assert_with_errno(ret == 0, "sem_post failed");
-  }
-}
-
-void PosixSemaphore::wait() {
-  int ret;
-
-  do {
-    ret = sem_wait(&_semaphore);
-  } while (ret != 0 && errno == EINTR);
-
-  assert_with_errno(ret == 0, "sem_wait failed");
-}
-
-bool PosixSemaphore::trywait() {
-  int ret;
-
-  do {
-    ret = sem_trywait(&_semaphore);
-  } while (ret != 0 && errno == EINTR);
-
-  assert_with_errno(ret == 0 || errno == EAGAIN, "trywait failed");
-
-  return ret == 0;
-}
-
-bool PosixSemaphore::timedwait(struct timespec ts) {
-  while (true) {
-    int result = sem_timedwait(&_semaphore, &ts);
-    if (result == 0) {
-      return true;
-    } else if (errno == EINTR) {
-      continue;
-    } else if (errno == ETIMEDOUT) {
-      return false;
-    } else {
-      assert_with_errno(false, "timedwait failed");
-      return false;
-    }
-  }
-}
-
-#endif // __APPLE__
-
 
 // Shared pthread_mutex/cond based PlatformEvent implementation.
 // Not currently usable by Solaris.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/hotspot/os/posix/semaphore_posix.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -0,0 +1,98 @@
+/*
+ * 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.
+ *
+ * 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/precompiled.hpp"
+#ifndef __APPLE__
+#include "runtime/os.hpp"
+// POSIX unamed semaphores are not supported on OS X.
+#include "semaphore_posix.hpp"
+#include <semaphore.h>
+
+#define check_with_errno(check_type, cond, msg)                             \
+  do {                                                                      \
+    int err = errno;                                                        \
+    check_type(cond, "%s; error='%s' (errno=%s)", msg, os::strerror(err),   \
+               os::errno_name(err));                                        \
+} while (false)
+
+#define assert_with_errno(cond, msg)    check_with_errno(assert, cond, msg)
+#define guarantee_with_errno(cond, msg) check_with_errno(guarantee, cond, msg)
+
+PosixSemaphore::PosixSemaphore(uint value) {
+  int ret = sem_init(&_semaphore, 0, value);
+
+  guarantee_with_errno(ret == 0, "Failed to initialize semaphore");
+}
+
+PosixSemaphore::~PosixSemaphore() {
+  sem_destroy(&_semaphore);
+}
+
+void PosixSemaphore::signal(uint count) {
+  for (uint i = 0; i < count; i++) {
+    int ret = sem_post(&_semaphore);
+
+    assert_with_errno(ret == 0, "sem_post failed");
+  }
+}
+
+void PosixSemaphore::wait() {
+  int ret;
+
+  do {
+    ret = sem_wait(&_semaphore);
+  } while (ret != 0 && errno == EINTR);
+
+  assert_with_errno(ret == 0, "sem_wait failed");
+}
+
+bool PosixSemaphore::trywait() {
+  int ret;
+
+  do {
+    ret = sem_trywait(&_semaphore);
+  } while (ret != 0 && errno == EINTR);
+
+  assert_with_errno(ret == 0 || errno == EAGAIN, "trywait failed");
+
+  return ret == 0;
+}
+
+bool PosixSemaphore::timedwait(struct timespec ts) {
+  while (true) {
+    int result = sem_timedwait(&_semaphore, &ts);
+    if (result == 0) {
+      return true;
+    } else if (errno == EINTR) {
+      continue;
+    } else if (errno == ETIMEDOUT) {
+      return false;
+    } else {
+      assert_with_errno(false, "timedwait failed");
+      return false;
+    }
+  }
+}
+#endif // __APPLE__
+
--- a/src/hotspot/os/posix/semaphore_posix.hpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/os/posix/semaphore_posix.hpp	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -45,15 +45,7 @@
   void wait();
 
   bool trywait();
-  bool timedwait(unsigned int sec, int nsec) {
-    return timedwait(create_timespec(sec, nsec));
-  }
-
- private:
   bool timedwait(struct timespec ts);
-
-  // OS specific implementation to create a timespec suitable for semaphores.
-  struct timespec create_timespec(unsigned int set, int nsec);
 };
 
 typedef PosixSemaphore SemaphoreImpl;
--- a/src/hotspot/os/solaris/os_solaris.cpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/os/solaris/os_solaris.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -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
@@ -2062,7 +2062,7 @@
   return CAST_FROM_FN_PTR(void*, UserHandler);
 }
 
-struct timespec PosixSemaphore::create_timespec(unsigned int sec, int nsec) {
+static struct timespec create_semaphore_timespec(unsigned int sec, int nsec) {
   struct timespec ts;
   unpackTime(&ts, false, (sec * NANOSECS_PER_SEC) + nsec);
 
@@ -2100,7 +2100,7 @@
 static jint *pending_signals = NULL;
 static int *preinstalled_sigs = NULL;
 static struct sigaction *chainedsigactions = NULL;
-static sema_t sig_sem;
+static Semaphore* sig_sem = NULL;
 typedef int (*version_getting_t)();
 version_getting_t os::Solaris::get_libjsig_version = NULL;
 
@@ -2115,6 +2115,7 @@
   Sigexit = Maxsignum+1;
   assert(Maxsignum >0, "Unable to obtain max signal number");
 
+  // Initialize signal structures
   // pending_signals has one int per signal
   // The additional signal is for SIGEXIT - exit signal to signal_thread
   pending_signals = (jint *)os::malloc(sizeof(jint) * (Sigexit+1), mtInternal);
@@ -2132,21 +2133,22 @@
 }
 
 void os::signal_init_pd() {
-  int ret;
-
-  ret = ::sema_init(&sig_sem, 0, NULL, NULL);
-  assert(ret == 0, "sema_init() failed");
-}
-
-void os::signal_notify(int signal_number) {
-  int ret;
-
-  Atomic::inc(&pending_signals[signal_number]);
-  ret = ::sema_post(&sig_sem);
-  assert(ret == 0, "sema_post() failed");
-}
-
-static int check_pending_signals(bool wait_for_signal) {
+  // Initialize signal semaphore
+  sig_sem = new Semaphore();
+}
+
+void os::signal_notify(int sig) {
+  if (sig_sem != NULL) {
+    Atomic::inc(&pending_signals[sig]);
+    sig_sem->signal();
+  } else {
+    // Signal thread is not created with ReduceSignalUsage and signal_init_pd
+    // initialization isn't called.
+    assert(ReduceSignalUsage, "signal semaphore should be created");
+  }
+}
+
+static int check_pending_signals() {
   int ret;
   while (true) {
     for (int i = 0; i < Sigexit + 1; i++) {
@@ -2155,19 +2157,13 @@
         return i;
       }
     }
-    if (!wait_for_signal) {
-      return -1;
-    }
     JavaThread *thread = JavaThread::current();
     ThreadBlockInVM tbivm(thread);
 
     bool threadIsSuspended;
     do {
       thread->set_suspend_equivalent();
-      // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
-      while ((ret = ::sema_wait(&sig_sem)) == EINTR)
-        ;
-      assert(ret == 0, "sema_wait() failed");
+      sig_sem->wait();
 
       // were we externally suspended while we were waiting?
       threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
@@ -2176,8 +2172,7 @@
         // another thread suspended us. We don't want to continue running
         // while suspended because that would surprise the thread that
         // suspended us.
-        ret = ::sema_post(&sig_sem);
-        assert(ret == 0, "sema_post() failed");
+        sig_sem->signal();
 
         thread->java_suspend_self();
       }
@@ -2185,12 +2180,8 @@
   }
 }
 
-int os::signal_lookup() {
-  return check_pending_signals(false);
-}
-
 int os::signal_wait() {
-  return check_pending_signals(true);
+  return check_pending_signals();
 }
 
 ////////////////////////////////////////////////////////////////////////////////
@@ -3599,7 +3590,7 @@
 
   // managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED
   while (true) {
-    if (sr_semaphore.timedwait(0, 2000 * NANOSECS_PER_MILLISEC)) {
+    if (sr_semaphore.timedwait(create_semaphore_timespec(0, 2000 * NANOSECS_PER_MILLISEC))) {
       break;
     } else {
       // timeout
@@ -3633,7 +3624,7 @@
 
   while (true) {
     if (sr_notify(osthread) == 0) {
-      if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
+      if (sr_semaphore.timedwait(create_semaphore_timespec(0, 2 * NANOSECS_PER_MILLISEC))) {
         if (osthread->sr.is_running()) {
           return;
         }
--- a/src/hotspot/os/windows/os_windows.cpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/os/windows/os_windows.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -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
@@ -62,7 +62,6 @@
 #include "runtime/threadCritical.hpp"
 #include "runtime/timer.hpp"
 #include "runtime/vm_version.hpp"
-#include "semaphore_windows.hpp"
 #include "services/attachListener.hpp"
 #include "services/memTracker.hpp"
 #include "services/runtimeService.hpp"
@@ -1845,36 +1844,6 @@
   return (int)error;
 }
 
-WindowsSemaphore::WindowsSemaphore(uint value) {
-  _semaphore = ::CreateSemaphore(NULL, value, LONG_MAX, NULL);
-
-  guarantee(_semaphore != NULL, "CreateSemaphore failed with error code: %lu", GetLastError());
-}
-
-WindowsSemaphore::~WindowsSemaphore() {
-  ::CloseHandle(_semaphore);
-}
-
-void WindowsSemaphore::signal(uint count) {
-  if (count > 0) {
-    BOOL ret = ::ReleaseSemaphore(_semaphore, count, NULL);
-
-    assert(ret != 0, "ReleaseSemaphore failed with error code: %lu", GetLastError());
-  }
-}
-
-void WindowsSemaphore::wait() {
-  DWORD ret = ::WaitForSingleObject(_semaphore, INFINITE);
-  assert(ret != WAIT_FAILED,   "WaitForSingleObject failed with error code: %lu", GetLastError());
-  assert(ret == WAIT_OBJECT_0, "WaitForSingleObject failed with return value: %lu", ret);
-}
-
-bool WindowsSemaphore::trywait() {
-  DWORD ret = ::WaitForSingleObject(_semaphore, 0);
-  assert(ret != WAIT_FAILED,   "WaitForSingleObject failed with error code: %lu", GetLastError());
-  return ret == WAIT_OBJECT_0;
-}
-
 // sun.misc.Signal
 // NOTE that this is a workaround for an apparent kernel bug where if
 // a signal handler for SIGBREAK is installed then that signal handler
@@ -1966,13 +1935,14 @@
 
 // a counter for each possible signal value, including signal_thread exit signal
 static volatile jint pending_signals[NSIG+1] = { 0 };
-static HANDLE sig_sem = NULL;
+static Semaphore* sig_sem = NULL;
 
 void os::signal_init_pd() {
   // Initialize signal structures
   memset((void*)pending_signals, 0, sizeof(pending_signals));
 
-  sig_sem = ::CreateSemaphore(NULL, 0, NSIG+1, NULL);
+  // Initialize signal semaphore
+  sig_sem = new Semaphore();
 
   // Programs embedding the VM do not want it to attempt to receive
   // events like CTRL_LOGOFF_EVENT, which are used to implement the
@@ -1994,17 +1964,18 @@
   }
 }
 
-void os::signal_notify(int signal_number) {
-  BOOL ret;
+void os::signal_notify(int sig) {
   if (sig_sem != NULL) {
-    Atomic::inc(&pending_signals[signal_number]);
-    ret = ::ReleaseSemaphore(sig_sem, 1, NULL);
-    assert(ret != 0, "ReleaseSemaphore() failed");
-  }
-}
-
-static int check_pending_signals(bool wait_for_signal) {
-  DWORD ret;
+    Atomic::inc(&pending_signals[sig]);
+    sig_sem->signal();
+  } else {
+    // Signal thread is not created with ReduceSignalUsage and signal_init_pd
+    // initialization isn't called.
+    assert(ReduceSignalUsage, "signal semaphore should be created");
+  }
+}
+
+static int check_pending_signals() {
   while (true) {
     for (int i = 0; i < NSIG + 1; i++) {
       jint n = pending_signals[i];
@@ -2012,10 +1983,6 @@
         return i;
       }
     }
-    if (!wait_for_signal) {
-      return -1;
-    }
-
     JavaThread *thread = JavaThread::current();
 
     ThreadBlockInVM tbivm(thread);
@@ -2024,8 +1991,7 @@
     do {
       thread->set_suspend_equivalent();
       // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
-      ret = ::WaitForSingleObject(sig_sem, INFINITE);
-      assert(ret == WAIT_OBJECT_0, "WaitForSingleObject() failed");
+      sig_sem->wait();
 
       // were we externally suspended while we were waiting?
       threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
@@ -2034,8 +2000,7 @@
         // another thread suspended us. We don't want to continue running
         // while suspended because that would surprise the thread that
         // suspended us.
-        ret = ::ReleaseSemaphore(sig_sem, 1, NULL);
-        assert(ret != 0, "ReleaseSemaphore() failed");
+        sig_sem->signal();
 
         thread->java_suspend_self();
       }
@@ -2043,12 +2008,8 @@
   }
 }
 
-int os::signal_lookup() {
-  return check_pending_signals(false);
-}
-
 int os::signal_wait() {
-  return check_pending_signals(true);
+  return check_pending_signals();
 }
 
 // Implicit OS exception handling
@@ -4394,13 +4355,49 @@
 
 // Is a (classpath) directory empty?
 bool os::dir_is_empty(const char* path) {
-  WIN32_FIND_DATA fd;
-  HANDLE f = FindFirstFile(path, &fd);
-  if (f == INVALID_HANDLE_VALUE) {
-    return true;
-  }
-  FindClose(f);
-  return false;
+  char* search_path = (char*)os::malloc(strlen(path) + 3, mtInternal);
+  if (search_path == NULL) {
+    errno = ENOMEM;
+    return false;
+  }
+  strcpy(search_path, path);
+  // Append "*", or possibly "\\*", to path
+  if (path[1] == ':' &&
+    (path[2] == '\0' ||
+    (path[2] == '\\' && path[3] == '\0'))) {
+    // No '\\' needed for cases like "Z:" or "Z:\"
+    strcat(search_path, "*");
+  }
+  else {
+    strcat(search_path, "\\*");
+  }
+  errno_t err = ERROR_SUCCESS;
+  wchar_t* wpath = create_unc_path(search_path, err);
+  if (err != ERROR_SUCCESS) {
+    if (wpath != NULL) {
+      destroy_unc_path(wpath);
+    }
+    os::free(search_path);
+    errno = err;
+    return false;
+  }
+  WIN32_FIND_DATAW fd;
+  HANDLE f = ::FindFirstFileW(wpath, &fd);
+  destroy_unc_path(wpath);
+  bool is_empty = true;
+  if (f != INVALID_HANDLE_VALUE) {
+    while (is_empty && ::FindNextFileW(f, &fd)) {
+      // An empty directory contains only the current directory file
+      // and the previous directory file.
+      if ((wcscmp(fd.cFileName, L".") != 0) &&
+          (wcscmp(fd.cFileName, L"..") != 0)) {
+        is_empty = false;
+      }
+    }
+    FindClose(f);
+  }
+  os::free(search_path);
+  return is_empty;
 }
 
 // create binary file, rewriting existing file if required
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/hotspot/os/windows/semaphore_windows.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -0,0 +1,60 @@
+/*
+ * 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.
+ *
+ * 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 "semaphore_windows.hpp"
+#include "utilities/debug.hpp"
+
+#include <windows.h>
+#include <errno.h>
+
+WindowsSemaphore::WindowsSemaphore(uint value) {
+  _semaphore = ::CreateSemaphore(NULL, value, LONG_MAX, NULL);
+
+  guarantee(_semaphore != NULL, "CreateSemaphore failed with error code: %lu", GetLastError());
+}
+
+WindowsSemaphore::~WindowsSemaphore() {
+  ::CloseHandle(_semaphore);
+}
+
+void WindowsSemaphore::signal(uint count) {
+  if (count > 0) {
+    BOOL ret = ::ReleaseSemaphore(_semaphore, count, NULL);
+
+    assert(ret != 0, "ReleaseSemaphore failed with error code: %lu", GetLastError());
+  }
+}
+
+void WindowsSemaphore::wait() {
+  DWORD ret = ::WaitForSingleObject(_semaphore, INFINITE);
+  assert(ret != WAIT_FAILED,   "WaitForSingleObject failed with error code: %lu", GetLastError());
+  assert(ret == WAIT_OBJECT_0, "WaitForSingleObject failed with return value: %lu", ret);
+}
+
+bool WindowsSemaphore::trywait() {
+  DWORD ret = ::WaitForSingleObject(_semaphore, 0);
+  assert(ret != WAIT_FAILED,   "WaitForSingleObject failed with error code: %lu", GetLastError());
+  return ret == WAIT_OBJECT_0;
+}
--- a/src/hotspot/share/ci/ciInstanceKlass.cpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/share/ci/ciInstanceKlass.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -34,35 +34,12 @@
 #include "oops/oop.inline.hpp"
 #include "oops/fieldStreams.hpp"
 #include "runtime/fieldDescriptor.hpp"
-#if INCLUDE_ALL_GCS
-# include "gc/g1/g1SATBCardTableModRefBS.hpp"
-#endif
 
 // ciInstanceKlass
 //
 // This class represents a Klass* in the HotSpot virtual machine
 // whose Klass part in an InstanceKlass.
 
-// ------------------------------------------------------------------
-// ensure_metadata_alive
-//
-// Ensure that the metadata wrapped by the ciMetadata is kept alive by GC.
-// This is primarily useful for metadata which is considered as weak roots
-// by the GC but need to be strong roots if reachable from a current compilation.
-// InstanceKlass are created for both weak and strong metadata.  Ensuring this metadata
-// alive covers the cases where there are weak roots without performance cost.
-//
-static void ensure_metadata_alive(oop metadata_holder) {
-#if INCLUDE_ALL_GCS
-  if (!UseG1GC) {
-    return;
-  }
-  if (metadata_holder != NULL) {
-    G1SATBCardTableModRefBS::enqueue(metadata_holder);
-  }
-#endif
-}
-
 
 // ------------------------------------------------------------------
 // ciInstanceKlass::ciInstanceKlass
@@ -88,8 +65,12 @@
   _has_injected_fields = -1;
   _implementor = NULL; // we will fill these lazily
 
-  oop holder = ik->klass_holder();
-  ensure_metadata_alive(holder);
+  // Ensure that the metadata wrapped by the ciMetadata is kept alive by GC.
+  // This is primarily useful for metadata which is considered as weak roots
+  // by the GC but need to be strong roots if reachable from a current compilation.
+  // InstanceKlass are created for both weak and strong metadata.  Ensuring this metadata
+  // alive covers the cases where there are weak roots without performance cost.
+  oop holder = ik->klass_holder_phantom();
   if (ik->is_anonymous()) {
     // Though ciInstanceKlass records class loader oop, it's not enough to keep
     // VM anonymous classes alive (loader == NULL). Klass holder should be used instead.
--- a/src/hotspot/share/classfile/classLoaderData.cpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/share/classfile/classLoaderData.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -63,6 +63,7 @@
 #include "memory/metaspaceShared.hpp"
 #include "memory/oopFactory.hpp"
 #include "memory/resourceArea.hpp"
+#include "oops/access.inline.hpp"
 #include "oops/objArrayOop.inline.hpp"
 #include "oops/oop.inline.hpp"
 #include "runtime/atomic.hpp"
@@ -75,9 +76,6 @@
 #include "utilities/growableArray.hpp"
 #include "utilities/macros.hpp"
 #include "utilities/ostream.hpp"
-#if INCLUDE_ALL_GCS
-#include "gc/g1/g1SATBCardTableModRefBS.hpp"
-#endif // INCLUDE_ALL_GCS
 #if INCLUDE_TRACE
 #include "trace/tracing.hpp"
 #endif
@@ -759,18 +757,9 @@
   oop* ptr = h.ptr_raw();
   if (ptr != NULL) {
     assert(_handles.contains(ptr), "Got unexpected handle " PTR_FORMAT, p2i(ptr));
-#if INCLUDE_ALL_GCS
-    // This barrier is used by G1 to remember the old oop values, so
-    // that we don't forget any objects that were live at the snapshot at
-    // the beginning.
-    if (UseG1GC) {
-      oop obj = *ptr;
-      if (obj != NULL) {
-        G1SATBCardTableModRefBS::enqueue(obj);
-      }
-    }
-#endif
-    *ptr = NULL;
+    // This root is not walked in safepoints, and hence requires an appropriate
+    // decorator that e.g. maintains the SATB invariant in SATB collectors.
+    RootAccess<IN_CONCURRENT_ROOT>::oop_store(ptr, oop(NULL));
   }
 }
 
--- a/src/hotspot/share/classfile/classLoaderData.hpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/share/classfile/classLoaderData.hpp	Mon Jan 22 16:55:01 2018 +0100
@@ -217,6 +217,7 @@
   friend class ClassLoaderDataGraphKlassIteratorAtomic;
   friend class ClassLoaderDataGraphKlassIteratorStatic;
   friend class ClassLoaderDataGraphMetaspaceIterator;
+  friend class InstanceKlass;
   friend class MetaDataFactory;
   friend class Method;
 
--- a/src/hotspot/share/classfile/javaClasses.cpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/share/classfile/javaClasses.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -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
@@ -33,6 +33,8 @@
 #include "code/dependencyContext.hpp"
 #include "code/pcDesc.hpp"
 #include "interpreter/interpreter.hpp"
+#include "logging/log.hpp"
+#include "logging/logStream.hpp"
 #include "memory/oopFactory.hpp"
 #include "memory/resourceArea.hpp"
 #include "memory/universe.inline.hpp"
@@ -104,52 +106,59 @@
 }
 
 
-static bool find_field(InstanceKlass* ik,
-                       Symbol* name_symbol, Symbol* signature_symbol,
-                       fieldDescriptor* fd,
-                       bool is_static = false, bool allow_super = false) {
-  if (allow_super || is_static) {
-    return ik->find_field(name_symbol, signature_symbol, is_static, fd) != NULL;
-  } else {
-    return ik->find_local_field(name_symbol, signature_symbol, fd);
+// Helpful routine for computing field offsets at run time rather than hardcoding them
+// Finds local fields only, including static fields.  Static field offsets are from the
+// beginning of the mirror.
+static void compute_offset(int &dest_offset,
+                           InstanceKlass* ik, Symbol* name_symbol, Symbol* signature_symbol,
+                           bool is_static = false) {
+  fieldDescriptor fd;
+  if (ik == NULL) {
+    ResourceMark rm;
+    log_error(class)("Mismatch JDK version for field: %s type: %s", name_symbol->as_C_string(), signature_symbol->as_C_string());
+    vm_exit_during_initialization("Invalid layout of preloaded class");
   }
-}
-
-// Helpful routine for computing field offsets at run time rather than hardcoding them
-static void
-compute_offset(int &dest_offset,
-               Klass* klass, Symbol* name_symbol, Symbol* signature_symbol,
-               bool is_static = false, bool allow_super = false) {
-  fieldDescriptor fd;
-  InstanceKlass* ik = InstanceKlass::cast(klass);
-  if (!find_field(ik, name_symbol, signature_symbol, &fd, is_static, allow_super)) {
+
+  if (!ik->find_local_field(name_symbol, signature_symbol, &fd) || fd.is_static() != is_static) {
     ResourceMark rm;
-    tty->print_cr("Invalid layout of %s at %s", ik->external_name(), name_symbol->as_C_string());
+    log_error(class)("Invalid layout of %s field: %s type: %s", ik->external_name(),
+                     name_symbol->as_C_string(), signature_symbol->as_C_string());
 #ifndef PRODUCT
-    ik->print();
-    tty->print_cr("all fields:");
-    for (AllFieldStream fs(ik); !fs.done(); fs.next()) {
-      tty->print_cr("  name: %s, sig: %s, flags: %08x", fs.name()->as_C_string(), fs.signature()->as_C_string(), fs.access_flags().as_int());
-    }
+    // Prints all fields and offsets
+    Log(class) lt;
+    LogStream ls(lt.error());
+    ik->print_on(&ls);
 #endif //PRODUCT
     vm_exit_during_initialization("Invalid layout of preloaded class: use -Xlog:class+load=info to see the origin of the problem class");
   }
   dest_offset = fd.offset();
 }
 
+// Overloading to pass name as a string.
+static void compute_offset(int& dest_offset, InstanceKlass* ik,
+                           const char* name_string, Symbol* signature_symbol,
+                           bool is_static = false) {
+  TempNewSymbol name = SymbolTable::probe(name_string, (int)strlen(name_string));
+  if (name == NULL) {
+    ResourceMark rm;
+    log_error(class)("Name %s should be in the SymbolTable since its class is loaded", name_string);
+    vm_exit_during_initialization("Invalid layout of preloaded class", ik->external_name());
+  }
+  compute_offset(dest_offset, ik, name, signature_symbol, is_static);
+}
+
 // Same as above but for "optional" offsets that might not be present in certain JDK versions
+// Old versions should be cleaned out since Hotspot only supports the current JDK, and this
+// function should be removed.
 static void
 compute_optional_offset(int& dest_offset,
-                        Klass* klass, Symbol* name_symbol, Symbol* signature_symbol,
-                        bool allow_super = false) {
+                        InstanceKlass* ik, Symbol* name_symbol, Symbol* signature_symbol) {
   fieldDescriptor fd;
-  InstanceKlass* ik = InstanceKlass::cast(klass);
-  if (find_field(ik, name_symbol, signature_symbol, &fd, allow_super)) {
+  if (ik->find_local_field(name_symbol, signature_symbol, &fd)) {
     dest_offset = fd.offset();
   }
 }
 
-
 int java_lang_String::value_offset  = 0;
 int java_lang_String::hash_offset   = 0;
 int java_lang_String::coder_offset  = 0;
@@ -163,10 +172,10 @@
 void java_lang_String::compute_offsets() {
   assert(!initialized, "offsets should be initialized only once");
 
-  Klass* k = SystemDictionary::String_klass();
+  InstanceKlass* k = SystemDictionary::String_klass();
   compute_offset(value_offset,           k, vmSymbols::value_name(),  vmSymbols::byte_array_signature());
-  compute_offset(hash_offset,            k, vmSymbols::hash_name(),   vmSymbols::int_signature());
-  compute_offset(coder_offset,           k, vmSymbols::coder_name(),  vmSymbols::byte_signature());
+  compute_offset(hash_offset,            k, "hash",   vmSymbols::int_signature());
+  compute_offset(coder_offset,           k, "coder",  vmSymbols::byte_signature());
 
   initialized = true;
 }
@@ -619,12 +628,12 @@
 bool java_lang_String::equals(oop java_string, jchar* chars, int len) {
   assert(java_string->klass() == SystemDictionary::String_klass(),
          "must be java_string");
-  typeArrayOop value  = java_lang_String::value(java_string);
-  int          length = java_lang_String::length(java_string);
+  typeArrayOop value = java_lang_String::value_no_keepalive(java_string);
+  int length = java_lang_String::length(java_string);
   if (length != len) {
     return false;
   }
-  bool      is_latin1 = java_lang_String::is_latin1(java_string);
+  bool is_latin1 = java_lang_String::is_latin1(java_string);
   if (!is_latin1) {
     for (int i = 0; i < len; i++) {
       if (value->char_at(i) != chars[i]) {
@@ -646,12 +655,12 @@
          "must be java String");
   assert(str2->klass() == SystemDictionary::String_klass(),
          "must be java String");
-  typeArrayOop value1  = java_lang_String::value(str1);
-  int          length1 = java_lang_String::length(str1);
-  bool       is_latin1 = java_lang_String::is_latin1(str1);
-  typeArrayOop value2  = java_lang_String::value(str2);
-  int          length2 = java_lang_String::length(str2);
-  bool       is_latin2 = java_lang_String::is_latin1(str2);
+  typeArrayOop value1    = java_lang_String::value_no_keepalive(str1);
+  int          length1   = java_lang_String::length(value1);
+  bool         is_latin1 = java_lang_String::is_latin1(str1);
+  typeArrayOop value2    = java_lang_String::value_no_keepalive(str2);
+  int          length2   = java_lang_String::length(value2);
+  bool         is_latin2 = java_lang_String::is_latin1(str2);
 
   if ((length1 != length2) || (is_latin1 != is_latin2)) {
     // Strings of different size or with different
@@ -659,7 +668,7 @@
     return false;
   }
   int blength1 = value1->length();
-  for (int i = 0; i < value1->length(); i++) {
+  for (int i = 0; i < blength1; i++) {
     if (value1->byte_at(i) != value2->byte_at(i)) {
       return false;
     }
@@ -669,7 +678,7 @@
 
 void java_lang_String::print(oop java_string, outputStream* st) {
   assert(java_string->klass() == SystemDictionary::String_klass(), "must be java_string");
-  typeArrayOop value  = java_lang_String::value(java_string);
+  typeArrayOop value  = java_lang_String::value_no_keepalive(java_string);
 
   if (value == NULL) {
     // This can happen if, e.g., printing a String
@@ -1161,25 +1170,11 @@
   assert(!offsets_computed, "offsets should be initialized only once");
   offsets_computed = true;
 
-  Klass* k = SystemDictionary::Class_klass();
-  // The classRedefinedCount field is only present starting in 1.5,
-  // so don't go fatal.
-  compute_optional_offset(classRedefinedCount_offset,
-                          k, vmSymbols::classRedefinedCount_name(), vmSymbols::int_signature());
-
-  // Needs to be optional because the old build runs Queens during bootstrapping
-  // and jdk8-9 doesn't have coordinated pushes yet.
-  compute_optional_offset(_class_loader_offset,
-                 k, vmSymbols::classLoader_name(),
-                 vmSymbols::classloader_signature());
-
-  compute_offset(_component_mirror_offset,
-                 k, vmSymbols::componentType_name(),
-                 vmSymbols::class_signature());
-
-  compute_offset(_module_offset,
-                 k, vmSymbols::module_name(),
-                 vmSymbols::module_signature());
+  InstanceKlass* k = SystemDictionary::Class_klass();
+  compute_offset(classRedefinedCount_offset, k, "classRedefinedCount", vmSymbols::int_signature());
+  compute_offset(_class_loader_offset,       k, "classLoader", vmSymbols::classloader_signature());
+  compute_offset(_component_mirror_offset,   k, "componentType", vmSymbols::class_signature());
+  compute_offset(_module_offset,             k, "module", vmSymbols::module_signature());
 
   // Init lock is a C union with component_mirror.  Only instanceKlass mirrors have
   // init_lock and only ArrayKlass mirrors have component_mirror.  Since both are oops
@@ -1234,24 +1229,22 @@
 void java_lang_Thread::compute_offsets() {
   assert(_group_offset == 0, "offsets should be initialized only once");
 
-  Klass* k = SystemDictionary::Thread_klass();
+  InstanceKlass* k = SystemDictionary::Thread_klass();
   compute_offset(_name_offset,      k, vmSymbols::name_name(),      vmSymbols::string_signature());
   compute_offset(_group_offset,     k, vmSymbols::group_name(),     vmSymbols::threadgroup_signature());
-  compute_offset(_contextClassLoader_offset, k, vmSymbols::contextClassLoader_name(), vmSymbols::classloader_signature());
-  compute_offset(_inheritedAccessControlContext_offset, k, vmSymbols::inheritedAccessControlContext_name(), vmSymbols::accesscontrolcontext_signature());
+  compute_offset(_contextClassLoader_offset, k, vmSymbols::contextClassLoader_name(),
+                 vmSymbols::classloader_signature());
+  compute_offset(_inheritedAccessControlContext_offset, k, vmSymbols::inheritedAccessControlContext_name(),
+                 vmSymbols::accesscontrolcontext_signature());
   compute_offset(_priority_offset,  k, vmSymbols::priority_name(),  vmSymbols::int_signature());
   compute_offset(_daemon_offset,    k, vmSymbols::daemon_name(),    vmSymbols::bool_signature());
-  compute_offset(_eetop_offset,     k, vmSymbols::eetop_name(),     vmSymbols::long_signature());
-  compute_offset(_stillborn_offset, k, vmSymbols::stillborn_name(), vmSymbols::bool_signature());
-  // The stackSize field is only present starting in 1.4, so don't go fatal.
-  compute_optional_offset(_stackSize_offset, k, vmSymbols::stackSize_name(), vmSymbols::long_signature());
-  // The tid and thread_status fields are only present starting in 1.5, so don't go fatal.
-  compute_optional_offset(_tid_offset, k, vmSymbols::thread_id_name(), vmSymbols::long_signature());
-  compute_optional_offset(_thread_status_offset, k, vmSymbols::thread_status_name(), vmSymbols::int_signature());
-  // The parkBlocker field is only present starting in 1.6, so don't go fatal.
-  compute_optional_offset(_park_blocker_offset, k, vmSymbols::park_blocker_name(), vmSymbols::object_signature());
-  compute_optional_offset(_park_event_offset, k, vmSymbols::park_event_name(),
- vmSymbols::long_signature());
+  compute_offset(_eetop_offset,     k, "eetop", vmSymbols::long_signature());
+  compute_offset(_stillborn_offset, k, "stillborn", vmSymbols::bool_signature());
+  compute_offset(_stackSize_offset, k, "stackSize", vmSymbols::long_signature());
+  compute_offset(_tid_offset,       k, "tid", vmSymbols::long_signature());
+  compute_offset(_thread_status_offset, k, "threadStatus", vmSymbols::int_signature());
+  compute_offset(_park_blocker_offset,  k, "parkBlocker", vmSymbols::object_signature());
+  compute_offset(_park_event_offset,    k, "nativeParkEventPointer", vmSymbols::long_signature());
 }
 
 
@@ -1486,7 +1479,7 @@
 void java_lang_ThreadGroup::compute_offsets() {
   assert(_parent_offset == 0, "offsets should be initialized only once");
 
-  Klass* k = SystemDictionary::ThreadGroup_klass();
+  InstanceKlass* k = SystemDictionary::ThreadGroup_klass();
 
   compute_offset(_parent_offset,      k, vmSymbols::parent_name(),      vmSymbols::threadgroup_signature());
   compute_offset(_name_offset,        k, vmSymbols::name_name(),        vmSymbols::string_signature());
@@ -1501,8 +1494,13 @@
 
 
 void java_lang_Throwable::compute_offsets() {
-  Klass* k = SystemDictionary::Throwable_klass();
-  compute_offset(depth_offset, k, vmSymbols::depth_name(), vmSymbols::int_signature());
+  InstanceKlass* k = SystemDictionary::Throwable_klass();
+  compute_offset(backtrace_offset,     k, "backtrace", vmSymbols::object_signature());
+  compute_offset(detailMessage_offset, k, "detailMessage", vmSymbols::string_signature());
+  compute_offset(stackTrace_offset,    k, "stackTrace",    vmSymbols::java_lang_StackTraceElement_array());
+  compute_offset(depth_offset,         k, "depth", vmSymbols::int_signature());
+  compute_offset(static_unassigned_stacktrace_offset, k, "UNASSIGNED_STACK", vmSymbols::java_lang_StackTraceElement_array(),
+                 /*is_static*/true);
 }
 
 oop java_lang_Throwable::unassigned_stacktrace() {
@@ -2270,23 +2268,23 @@
 }
 
 void java_lang_StackFrameInfo::compute_offsets() {
-  Klass* k = SystemDictionary::StackFrameInfo_klass();
-  compute_offset(_memberName_offset,     k, vmSymbols::memberName_name(),  vmSymbols::object_signature());
-  compute_offset(_bci_offset,            k, vmSymbols::bci_name(),         vmSymbols::short_signature());
+  InstanceKlass* k = SystemDictionary::StackFrameInfo_klass();
+  compute_offset(_memberName_offset,     k, "memberName",  vmSymbols::object_signature());
+  compute_offset(_bci_offset,            k, "bci",         vmSymbols::short_signature());
   STACKFRAMEINFO_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
 }
 
 void java_lang_LiveStackFrameInfo::compute_offsets() {
-  Klass* k = SystemDictionary::LiveStackFrameInfo_klass();
-  compute_offset(_monitors_offset,   k, vmSymbols::monitors_name(),    vmSymbols::object_array_signature());
-  compute_offset(_locals_offset,     k, vmSymbols::locals_name(),      vmSymbols::object_array_signature());
-  compute_offset(_operands_offset,   k, vmSymbols::operands_name(),    vmSymbols::object_array_signature());
-  compute_offset(_mode_offset,       k, vmSymbols::mode_name(),        vmSymbols::int_signature());
+  InstanceKlass* k = SystemDictionary::LiveStackFrameInfo_klass();
+  compute_offset(_monitors_offset,   k, "monitors",    vmSymbols::object_array_signature());
+  compute_offset(_locals_offset,     k, "locals",      vmSymbols::object_array_signature());
+  compute_offset(_operands_offset,   k, "operands",    vmSymbols::object_array_signature());
+  compute_offset(_mode_offset,       k, "mode",        vmSymbols::int_signature());
 }
 
 void java_lang_reflect_AccessibleObject::compute_offsets() {
-  Klass* k = SystemDictionary::reflect_AccessibleObject_klass();
-  compute_offset(override_offset, k, vmSymbols::override_name(), vmSymbols::bool_signature());
+  InstanceKlass* k = SystemDictionary::reflect_AccessibleObject_klass();
+  compute_offset(override_offset, k, "override", vmSymbols::bool_signature());
 }
 
 jboolean java_lang_reflect_AccessibleObject::override(oop reflect) {
@@ -2300,7 +2298,7 @@
 }
 
 void java_lang_reflect_Method::compute_offsets() {
-  Klass* k = SystemDictionary::reflect_Method_klass();
+  InstanceKlass* k = SystemDictionary::reflect_Method_klass();
   compute_offset(clazz_offset,          k, vmSymbols::clazz_name(),          vmSymbols::class_signature());
   compute_offset(name_offset,           k, vmSymbols::name_name(),           vmSymbols::string_signature());
   compute_offset(returnType_offset,     k, vmSymbols::returnType_name(),     vmSymbols::class_signature());
@@ -2481,7 +2479,7 @@
 }
 
 void java_lang_reflect_Constructor::compute_offsets() {
-  Klass* k = SystemDictionary::reflect_Constructor_klass();
+  InstanceKlass* k = SystemDictionary::reflect_Constructor_klass();
   compute_offset(clazz_offset,          k, vmSymbols::clazz_name(),          vmSymbols::class_signature());
   compute_offset(parameterTypes_offset, k, vmSymbols::parameterTypes_name(), vmSymbols::class_array_signature());
   compute_offset(exceptionTypes_offset, k, vmSymbols::exceptionTypes_name(), vmSymbols::class_array_signature());
@@ -2623,7 +2621,7 @@
 }
 
 void java_lang_reflect_Field::compute_offsets() {
-  Klass* k = SystemDictionary::reflect_Field_klass();
+  InstanceKlass* k = SystemDictionary::reflect_Field_klass();
   compute_offset(clazz_offset,     k, vmSymbols::clazz_name(),     vmSymbols::class_signature());
   compute_offset(name_offset,      k, vmSymbols::name_name(),      vmSymbols::string_signature());
   compute_offset(type_offset,      k, vmSymbols::type_name(),      vmSymbols::class_signature());
@@ -2747,22 +2745,17 @@
 }
 
 void reflect_ConstantPool::compute_offsets() {
-  Klass* k = SystemDictionary::reflect_ConstantPool_klass();
-  // This null test can be removed post beta
-  if (k != NULL) {
-    // The field is called ConstantPool* in the sun.reflect.ConstantPool class.
-    compute_offset(_oop_offset, k, vmSymbols::ConstantPool_name(), vmSymbols::object_signature());
-  }
+  InstanceKlass* k = SystemDictionary::reflect_ConstantPool_klass();
+  // The field is called ConstantPool* in the sun.reflect.ConstantPool class.
+  compute_offset(_oop_offset, k, "constantPoolOop", vmSymbols::object_signature());
 }
 
 void java_lang_reflect_Parameter::compute_offsets() {
-  Klass* k = SystemDictionary::reflect_Parameter_klass();
-  if(NULL != k) {
-    compute_offset(name_offset,        k, vmSymbols::name_name(),        vmSymbols::string_signature());
-    compute_offset(modifiers_offset,   k, vmSymbols::modifiers_name(),   vmSymbols::int_signature());
-    compute_offset(index_offset,       k, vmSymbols::index_name(),       vmSymbols::int_signature());
-    compute_offset(executable_offset,  k, vmSymbols::executable_name(),  vmSymbols::executable_signature());
-  }
+  InstanceKlass* k = SystemDictionary::reflect_Parameter_klass();
+  compute_offset(name_offset,        k, vmSymbols::name_name(),        vmSymbols::string_signature());
+  compute_offset(modifiers_offset,   k, vmSymbols::modifiers_name(),   vmSymbols::int_signature());
+  compute_offset(index_offset,       k, vmSymbols::index_name(),       vmSymbols::int_signature());
+  compute_offset(executable_offset,  k, vmSymbols::executable_name(),  vmSymbols::executable_signature());
 }
 
 Handle java_lang_reflect_Parameter::create(TRAPS) {
@@ -2836,12 +2829,10 @@
 }
 
 void java_lang_Module::compute_offsets() {
-  Klass* k = SystemDictionary::Module_klass();
-  if(NULL != k) {
-    compute_offset(loader_offset,  k, vmSymbols::loader_name(),  vmSymbols::classloader_signature());
-    compute_offset(name_offset,    k, vmSymbols::name_name(),    vmSymbols::string_signature());
-    MODULE_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
-  }
+  InstanceKlass* k = SystemDictionary::Module_klass();
+  compute_offset(loader_offset,  k, vmSymbols::loader_name(),  vmSymbols::classloader_signature());
+  compute_offset(name_offset,    k, vmSymbols::name_name(),    vmSymbols::string_signature());
+  MODULE_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
 }
 
 
@@ -2921,12 +2912,8 @@
 }
 
 void reflect_UnsafeStaticFieldAccessorImpl::compute_offsets() {
-  Klass* k = SystemDictionary::reflect_UnsafeStaticFieldAccessorImpl_klass();
-  // This null test can be removed post beta
-  if (k != NULL) {
-    compute_offset(_base_offset, k,
-                   vmSymbols::base_name(), vmSymbols::object_signature());
-  }
+  InstanceKlass* k = SystemDictionary::reflect_UnsafeStaticFieldAccessorImpl_klass();
+  compute_offset(_base_offset, k, "base", vmSymbols::object_signature());
 }
 
 oop java_lang_boxing_object::initialize_and_allocate(BasicType type, TRAPS) {
@@ -3084,6 +3071,13 @@
 }
 
 // Support for java_lang_ref_SoftReference
+//
+
+void java_lang_ref_SoftReference::compute_offsets() {
+  InstanceKlass* k = SystemDictionary::SoftReference_klass();
+  compute_offset(timestamp_offset,    k, "timestamp", vmSymbols::long_signature());
+  compute_offset(static_clock_offset, k, "clock",     vmSymbols::long_signature(), true);
+}
 
 jlong java_lang_ref_SoftReference::timestamp(oop ref) {
   return ref->long_field(timestamp_offset);
@@ -3113,10 +3107,8 @@
 }
 
 void java_lang_invoke_DirectMethodHandle::compute_offsets() {
-  Klass* k = SystemDictionary::DirectMethodHandle_klass();
-  if (k != NULL) {
-    compute_offset(_member_offset, k, vmSymbols::member_name(), vmSymbols::java_lang_invoke_MemberName_signature());
-  }
+  InstanceKlass* k = SystemDictionary::DirectMethodHandle_klass();
+  compute_offset(_member_offset, k, "member", vmSymbols::java_lang_invoke_MemberName_signature());
 }
 
 // Support for java_lang_invoke_MethodHandle
@@ -3137,16 +3129,13 @@
 int java_lang_invoke_LambdaForm::_vmentry_offset;
 
 void java_lang_invoke_MethodHandle::compute_offsets() {
-  Klass* k = SystemDictionary::MethodHandle_klass();
-  if (k != NULL) {
-    compute_offset(_type_offset, k, vmSymbols::type_name(), vmSymbols::java_lang_invoke_MethodType_signature());
-    compute_offset(_form_offset, k, vmSymbols::form_name(), vmSymbols::java_lang_invoke_LambdaForm_signature());
-  }
+  InstanceKlass* k = SystemDictionary::MethodHandle_klass();
+  compute_offset(_type_offset, k, vmSymbols::type_name(), vmSymbols::java_lang_invoke_MethodType_signature());
+  compute_offset(_form_offset, k, "form", vmSymbols::java_lang_invoke_LambdaForm_signature());
 }
 
 void java_lang_invoke_MemberName::compute_offsets() {
-  Klass* k = SystemDictionary::MemberName_klass();
-  assert (k != NULL, "jdk mismatch");
+  InstanceKlass* k = SystemDictionary::MemberName_klass();
   compute_offset(_clazz_offset,   k, vmSymbols::clazz_name(),   vmSymbols::class_signature());
   compute_offset(_name_offset,    k, vmSymbols::name_name(),    vmSymbols::string_signature());
   compute_offset(_type_offset,    k, vmSymbols::type_name(),    vmSymbols::object_signature());
@@ -3156,15 +3145,15 @@
 }
 
 void java_lang_invoke_ResolvedMethodName::compute_offsets() {
-  Klass* k = SystemDictionary::ResolvedMethodName_klass();
+  InstanceKlass* k = SystemDictionary::ResolvedMethodName_klass();
   assert(k != NULL, "jdk mismatch");
   RESOLVEDMETHOD_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
 }
 
 void java_lang_invoke_LambdaForm::compute_offsets() {
-  Klass* k = SystemDictionary::LambdaForm_klass();
+  InstanceKlass* k = SystemDictionary::LambdaForm_klass();
   assert (k != NULL, "jdk mismatch");
-  compute_offset(_vmentry_offset, k, vmSymbols::vmentry_name(), vmSymbols::java_lang_invoke_MemberName_signature());
+  compute_offset(_vmentry_offset, k, "vmentry", vmSymbols::java_lang_invoke_MemberName_signature());
 }
 
 bool java_lang_invoke_LambdaForm::is_instance(oop obj) {
@@ -3305,11 +3294,9 @@
 int java_lang_invoke_MethodType::_ptypes_offset;
 
 void java_lang_invoke_MethodType::compute_offsets() {
-  Klass* k = SystemDictionary::MethodType_klass();
-  if (k != NULL) {
-    compute_offset(_rtype_offset,  k, vmSymbols::rtype_name(),  vmSymbols::class_signature());
-    compute_offset(_ptypes_offset, k, vmSymbols::ptypes_name(), vmSymbols::class_array_signature());
-  }
+  InstanceKlass* k = SystemDictionary::MethodType_klass();
+  compute_offset(_rtype_offset,  k, "rtype",  vmSymbols::class_signature());
+  compute_offset(_ptypes_offset, k, "ptypes", vmSymbols::class_array_signature());
 }
 
 void java_lang_invoke_MethodType::print_signature(oop mt, outputStream* st) {
@@ -3392,12 +3379,10 @@
 int java_lang_invoke_CallSite::_context_offset;
 
 void java_lang_invoke_CallSite::compute_offsets() {
-  Klass* k = SystemDictionary::CallSite_klass();
-  if (k != NULL) {
-    compute_offset(_target_offset, k, vmSymbols::target_name(), vmSymbols::java_lang_invoke_MethodHandle_signature());
-    compute_offset(_context_offset, k, vmSymbols::context_name(),
-                   vmSymbols::java_lang_invoke_MethodHandleNatives_CallSiteContext_signature());
-  }
+  InstanceKlass* k = SystemDictionary::CallSite_klass();
+  compute_offset(_target_offset,  k, "target", vmSymbols::java_lang_invoke_MethodHandle_signature());
+  compute_offset(_context_offset, k, "context",
+                 vmSymbols::java_lang_invoke_MethodHandleNatives_CallSiteContext_signature());
 }
 
 oop java_lang_invoke_CallSite::context(oop call_site) {
@@ -3412,10 +3397,8 @@
 int java_lang_invoke_MethodHandleNatives_CallSiteContext::_vmdependencies_offset;
 
 void java_lang_invoke_MethodHandleNatives_CallSiteContext::compute_offsets() {
-  Klass* k = SystemDictionary::Context_klass();
-  if (k != NULL) {
-    CALLSITECONTEXT_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
-  }
+  InstanceKlass* k = SystemDictionary::Context_klass();
+  CALLSITECONTEXT_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
 }
 
 DependencyContext java_lang_invoke_MethodHandleNatives_CallSiteContext::vmdependencies(oop call_site) {
@@ -3434,28 +3417,12 @@
 
 void java_security_AccessControlContext::compute_offsets() {
   assert(_isPrivileged_offset == 0, "offsets should be initialized only once");
-  fieldDescriptor fd;
-  InstanceKlass* ik = SystemDictionary::AccessControlContext_klass();
-
-  if (!ik->find_local_field(vmSymbols::context_name(), vmSymbols::protectiondomain_signature(), &fd)) {
-    fatal("Invalid layout of java.security.AccessControlContext");
-  }
-  _context_offset = fd.offset();
-
-  if (!ik->find_local_field(vmSymbols::privilegedContext_name(), vmSymbols::accesscontrolcontext_signature(), &fd)) {
-    fatal("Invalid layout of java.security.AccessControlContext");
-  }
-  _privilegedContext_offset = fd.offset();
-
-  if (!ik->find_local_field(vmSymbols::isPrivileged_name(), vmSymbols::bool_signature(), &fd)) {
-    fatal("Invalid layout of java.security.AccessControlContext");
-  }
-  _isPrivileged_offset = fd.offset();
-
-  // The offset may not be present for bootstrapping with older JDK.
-  if (ik->find_local_field(vmSymbols::isAuthorized_name(), vmSymbols::bool_signature(), &fd)) {
-    _isAuthorized_offset = fd.offset();
-  }
+  InstanceKlass* k = SystemDictionary::AccessControlContext_klass();
+
+  compute_offset(_context_offset,           k, "context",      vmSymbols::protectiondomain_signature());
+  compute_offset(_privilegedContext_offset, k, "privilegedContext", vmSymbols::accesscontrolcontext_signature());
+  compute_offset(_isPrivileged_offset,      k, "isPrivileged", vmSymbols::bool_signature());
+  compute_offset(_isAuthorized_offset,      k, "isAuthorized", vmSymbols::bool_signature());
 }
 
 
@@ -3504,16 +3471,17 @@
   assert(!offsets_computed, "offsets should be initialized only once");
   offsets_computed = true;
 
-  // The field indicating parallelCapable (parallelLockMap) is only present starting in 7,
-  Klass* k1 = SystemDictionary::ClassLoader_klass();
-  compute_optional_offset(parallelCapable_offset,
-    k1, vmSymbols::parallelCapable_name(), vmSymbols::concurrenthashmap_signature());
+  InstanceKlass* k1 = SystemDictionary::ClassLoader_klass();
+  compute_offset(parallelCapable_offset,
+    k1, "parallelLockMap", vmSymbols::concurrenthashmap_signature());
 
   compute_offset(name_offset,
     k1, vmSymbols::name_name(), vmSymbols::string_signature());
 
   compute_offset(unnamedModule_offset,
-    k1, vmSymbols::unnamedModule_name(), vmSymbols::module_signature());
+    k1, "unnamedModule", vmSymbols::module_signature());
+
+  compute_offset(parent_offset, k1, "parent", vmSymbols::classloader_signature());
 
   CLASSLOADER_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
 }
@@ -3600,19 +3568,18 @@
 }
 
 // Support for java_lang_System
-int java_lang_System::in_offset_in_bytes() {
-  return (InstanceMirrorKlass::offset_of_static_fields() + static_in_offset);
-}
-
-
-int java_lang_System::out_offset_in_bytes() {
-  return (InstanceMirrorKlass::offset_of_static_fields() + static_out_offset);
-}
-
-
-int java_lang_System::err_offset_in_bytes() {
-  return (InstanceMirrorKlass::offset_of_static_fields() + static_err_offset);
-}
+//
+void java_lang_System::compute_offsets() {
+  InstanceKlass* k = SystemDictionary::System_klass();
+  compute_offset(static_in_offset,  k, "in",  vmSymbols::input_stream_signature(), true);
+  compute_offset(static_out_offset, k, "out", vmSymbols::print_stream_signature(), true);
+  compute_offset(static_err_offset, k, "err", vmSymbols::print_stream_signature(), true);
+  compute_offset(static_security_offset, k, "security", vmSymbols::security_manager_signature(), true);
+}
+
+int java_lang_System::in_offset_in_bytes() { return static_in_offset; }
+int java_lang_System::out_offset_in_bytes() { return static_out_offset; }
+int java_lang_System::err_offset_in_bytes() { return static_err_offset; }
 
 
 bool java_lang_System::has_security_manager() {
@@ -3682,7 +3649,6 @@
 int java_lang_ref_Reference::queue_offset;
 int java_lang_ref_Reference::next_offset;
 int java_lang_ref_Reference::discovered_offset;
-int java_lang_ref_Reference::number_of_fake_oop_fields;
 int java_lang_ref_SoftReference::timestamp_offset;
 int java_lang_ref_SoftReference::static_clock_offset;
 int java_lang_ClassLoader::parent_offset;
@@ -3717,6 +3683,17 @@
 
 
 // Support for java_lang_StackTraceElement
+void java_lang_StackTraceElement::compute_offsets() {
+  InstanceKlass* k = SystemDictionary::StackTraceElement_klass();
+  compute_offset(declaringClassObject_offset,  k, "declaringClassObject", vmSymbols::class_signature());
+  compute_offset(classLoaderName_offset, k, "classLoaderName", vmSymbols::string_signature());
+  compute_offset(moduleName_offset,      k, "moduleName",      vmSymbols::string_signature());
+  compute_offset(moduleVersion_offset,   k, "moduleVersion",   vmSymbols::string_signature());
+  compute_offset(declaringClass_offset,  k, "declaringClass",  vmSymbols::string_signature());
+  compute_offset(methodName_offset,      k, "methodName",      vmSymbols::string_signature());
+  compute_offset(fileName_offset,        k, "fileName",        vmSymbols::string_signature());
+  compute_offset(lineNumber_offset,      k, "lineNumber",      vmSymbols::int_signature());
+}
 
 void java_lang_StackTraceElement::set_fileName(oop element, oop value) {
   element->obj_field_put(fileName_offset, value);
@@ -3776,6 +3753,16 @@
 
 // Support for java Assertions - java_lang_AssertionStatusDirectives.
 
+void java_lang_AssertionStatusDirectives::compute_offsets() {
+  InstanceKlass* k = SystemDictionary::AssertionStatusDirectives_klass();
+  compute_offset(classes_offset,        k, "classes",        vmSymbols::string_array_signature());
+  compute_offset(classEnabled_offset,   k, "classEnabled",   vmSymbols::bool_array_signature());
+  compute_offset(packages_offset,       k, "packages",       vmSymbols::string_array_signature());
+  compute_offset(packageEnabled_offset, k, "packageEnabled", vmSymbols::bool_array_signature());
+  compute_offset(deflt_offset,          k, "deflt",          vmSymbols::bool_signature());
+}
+
+
 void java_lang_AssertionStatusDirectives::set_classes(oop o, oop val) {
   o->obj_field_put(classes_offset, val);
 }
@@ -3804,18 +3791,18 @@
 
 
 void java_nio_Buffer::compute_offsets() {
-  Klass* k = SystemDictionary::nio_Buffer_klass();
+  InstanceKlass* k = SystemDictionary::nio_Buffer_klass();
   assert(k != NULL, "must be loaded in 1.4+");
-  compute_offset(_limit_offset, k, vmSymbols::limit_name(), vmSymbols::int_signature());
+  compute_offset(_limit_offset, k, "limit", vmSymbols::int_signature());
 }
 
 void java_util_concurrent_locks_AbstractOwnableSynchronizer::initialize(TRAPS) {
   if (_owner_offset != 0) return;
 
   SystemDictionary::load_abstract_ownable_synchronizer_klass(CHECK);
-  Klass* k = SystemDictionary::abstract_ownable_synchronizer_klass();
+  InstanceKlass* k = SystemDictionary::abstract_ownable_synchronizer_klass();
   compute_offset(_owner_offset, k,
-                 vmSymbols::exclusive_owner_thread_name(), vmSymbols::thread_signature());
+                 "exclusiveOwnerThread", vmSymbols::thread_signature());
 }
 
 oop java_util_concurrent_locks_AbstractOwnableSynchronizer::get_owner_threadObj(oop obj) {
@@ -3823,71 +3810,37 @@
   return obj->obj_field(_owner_offset);
 }
 
+static int member_offset(int hardcoded_offset) {
+  return (hardcoded_offset * heapOopSize) + instanceOopDesc::base_offset_in_bytes();
+}
+
 // Compute hard-coded offsets
 // Invoked before SystemDictionary::initialize, so pre-loaded classes
 // are not available to determine the offset_of_static_fields.
 void JavaClasses::compute_hard_coded_offsets() {
-  const int x = heapOopSize;
-  const int header = instanceOopDesc::base_offset_in_bytes();
-
-  // Throwable Class
-  java_lang_Throwable::backtrace_offset  = java_lang_Throwable::hc_backtrace_offset  * x + header;
-  java_lang_Throwable::detailMessage_offset = java_lang_Throwable::hc_detailMessage_offset * x + header;
-  java_lang_Throwable::stackTrace_offset = java_lang_Throwable::hc_stackTrace_offset * x + header;
-  java_lang_Throwable::static_unassigned_stacktrace_offset = java_lang_Throwable::hc_static_unassigned_stacktrace_offset *  x;
 
   // java_lang_boxing_object
-  java_lang_boxing_object::value_offset = java_lang_boxing_object::hc_value_offset + header;
-  java_lang_boxing_object::long_value_offset = align_up((java_lang_boxing_object::hc_value_offset + header), BytesPerLong);
-
-  // java_lang_ref_Reference:
-  java_lang_ref_Reference::referent_offset = java_lang_ref_Reference::hc_referent_offset * x + header;
-  java_lang_ref_Reference::queue_offset = java_lang_ref_Reference::hc_queue_offset * x + header;
-  java_lang_ref_Reference::next_offset  = java_lang_ref_Reference::hc_next_offset * x + header;
-  java_lang_ref_Reference::discovered_offset  = java_lang_ref_Reference::hc_discovered_offset * x + header;
-  // Artificial fields for java_lang_ref_Reference
-  // The first field is for the discovered field added in 1.4
-  java_lang_ref_Reference::number_of_fake_oop_fields = 1;
-
-  // java_lang_ref_SoftReference Class
-  java_lang_ref_SoftReference::timestamp_offset = align_up((java_lang_ref_SoftReference::hc_timestamp_offset * x + header), BytesPerLong);
-  // Don't multiply static fields because they are always in wordSize units
-  java_lang_ref_SoftReference::static_clock_offset = java_lang_ref_SoftReference::hc_static_clock_offset * x;
-
-  // java_lang_ClassLoader
-  java_lang_ClassLoader::parent_offset = java_lang_ClassLoader::hc_parent_offset * x + header;
-
-  // java_lang_System
-  java_lang_System::static_in_offset  = java_lang_System::hc_static_in_offset  * x;
-  java_lang_System::static_out_offset = java_lang_System::hc_static_out_offset * x;
-  java_lang_System::static_err_offset = java_lang_System::hc_static_err_offset * x;
-  java_lang_System::static_security_offset = java_lang_System::hc_static_security_offset * x;
-
-  // java_lang_StackTraceElement
-  java_lang_StackTraceElement::declaringClassObject_offset = java_lang_StackTraceElement::hc_declaringClassObject_offset * x + header;
-  java_lang_StackTraceElement::classLoaderName_offset = java_lang_StackTraceElement::hc_classLoaderName_offset * x + header;
-  java_lang_StackTraceElement::moduleName_offset = java_lang_StackTraceElement::hc_moduleName_offset * x + header;
-  java_lang_StackTraceElement::moduleVersion_offset = java_lang_StackTraceElement::hc_moduleVersion_offset * x + header;
-  java_lang_StackTraceElement::declaringClass_offset = java_lang_StackTraceElement::hc_declaringClass_offset  * x + header;
-  java_lang_StackTraceElement::methodName_offset = java_lang_StackTraceElement::hc_methodName_offset * x + header;
-  java_lang_StackTraceElement::fileName_offset   = java_lang_StackTraceElement::hc_fileName_offset   * x + header;
-  java_lang_StackTraceElement::lineNumber_offset = java_lang_StackTraceElement::hc_lineNumber_offset * x + header;
-  java_lang_AssertionStatusDirectives::classes_offset = java_lang_AssertionStatusDirectives::hc_classes_offset * x + header;
-  java_lang_AssertionStatusDirectives::classEnabled_offset = java_lang_AssertionStatusDirectives::hc_classEnabled_offset * x + header;
-  java_lang_AssertionStatusDirectives::packages_offset = java_lang_AssertionStatusDirectives::hc_packages_offset * x + header;
-  java_lang_AssertionStatusDirectives::packageEnabled_offset = java_lang_AssertionStatusDirectives::hc_packageEnabled_offset * x + header;
-  java_lang_AssertionStatusDirectives::deflt_offset = java_lang_AssertionStatusDirectives::hc_deflt_offset * x + header;
-
+  java_lang_boxing_object::value_offset      = member_offset(java_lang_boxing_object::hc_value_offset);
+  java_lang_boxing_object::long_value_offset = align_up(member_offset(java_lang_boxing_object::hc_value_offset), BytesPerLong);
+
+  // java_lang_ref_Reference
+  java_lang_ref_Reference::referent_offset    = member_offset(java_lang_ref_Reference::hc_referent_offset);
+  java_lang_ref_Reference::queue_offset       = member_offset(java_lang_ref_Reference::hc_queue_offset);
+  java_lang_ref_Reference::next_offset        = member_offset(java_lang_ref_Reference::hc_next_offset);
+  java_lang_ref_Reference::discovered_offset  = member_offset(java_lang_ref_Reference::hc_discovered_offset);
 }
 
 
 // Compute non-hard-coded field offsets of all the classes in this file
 void JavaClasses::compute_offsets() {
   // java_lang_Class::compute_offsets was called earlier in bootstrap
+  java_lang_System::compute_offsets();
   java_lang_ClassLoader::compute_offsets();
   java_lang_Throwable::compute_offsets();
   java_lang_Thread::compute_offsets();
   java_lang_ThreadGroup::compute_offsets();
+  java_lang_AssertionStatusDirectives::compute_offsets();
+  java_lang_ref_SoftReference::compute_offsets();
   java_lang_invoke_MethodHandle::compute_offsets();
   java_lang_invoke_DirectMethodHandle::compute_offsets();
   java_lang_invoke_MemberName::compute_offsets();
@@ -3910,6 +3863,7 @@
   reflect_UnsafeStaticFieldAccessorImpl::compute_offsets();
   java_lang_reflect_Parameter::compute_offsets();
   java_lang_Module::compute_offsets();
+  java_lang_StackTraceElement::compute_offsets();
   java_lang_StackFrameInfo::compute_offsets();
   java_lang_LiveStackFrameInfo::compute_offsets();
 
@@ -3947,62 +3901,6 @@
   }
 }
 
-
-bool JavaClasses::check_static_offset(const char *klass_name, int hardcoded_offset, const char *field_name, const char* field_sig) {
-  EXCEPTION_MARK;
-  fieldDescriptor fd;
-  TempNewSymbol klass_sym = SymbolTable::new_symbol(klass_name, CATCH);
-  Klass* k = SystemDictionary::resolve_or_fail(klass_sym, true, CATCH);
-  InstanceKlass* ik = InstanceKlass::cast(k);
-  TempNewSymbol f_name = SymbolTable::new_symbol(field_name, CATCH);
-  TempNewSymbol f_sig  = SymbolTable::new_symbol(field_sig, CATCH);
-  if (!ik->find_local_field(f_name, f_sig, &fd)) {
-    tty->print_cr("Static field %s.%s not found", klass_name, field_name);
-    return false;
-  }
-  if (!fd.is_static()) {
-    tty->print_cr("Static field %s.%s appears to be nonstatic", klass_name, field_name);
-    return false;
-  }
-  if (fd.offset() == hardcoded_offset + InstanceMirrorKlass::offset_of_static_fields()) {
-    return true;
-  } else {
-    tty->print_cr("Offset of static field %s.%s is hardcoded as %d but should really be %d.", klass_name, field_name, hardcoded_offset, fd.offset() - InstanceMirrorKlass::offset_of_static_fields());
-    return false;
-  }
-}
-
-
-bool JavaClasses::check_constant(const char *klass_name, int hardcoded_constant, const char *field_name, const char* field_sig) {
-  EXCEPTION_MARK;
-  fieldDescriptor fd;
-  TempNewSymbol klass_sym = SymbolTable::new_symbol(klass_name, CATCH);
-  Klass* k = SystemDictionary::resolve_or_fail(klass_sym, true, CATCH);
-  InstanceKlass* ik = InstanceKlass::cast(k);
-  TempNewSymbol f_name = SymbolTable::new_symbol(field_name, CATCH);
-  TempNewSymbol f_sig  = SymbolTable::new_symbol(field_sig, CATCH);
-  if (!ik->find_local_field(f_name, f_sig, &fd)) {
-    tty->print_cr("Static field %s.%s not found", klass_name, field_name);
-    return false;
-  }
-  if (!fd.is_static() || !fd.has_initial_value()) {
-    tty->print_cr("Static field %s.%s appears to be non-constant", klass_name, field_name);
-    return false;
-  }
-  if (!fd.initial_value_tag().is_int()) {
-    tty->print_cr("Static field %s.%s is not an int", klass_name, field_name);
-    return false;
-  }
-  jint field_value = fd.int_initial_value();
-  if (field_value == hardcoded_constant) {
-    return true;
-  } else {
-    tty->print_cr("Constant value of static field %s.%s is hardcoded as %d but should really be %d.", klass_name, field_name, hardcoded_constant, field_value);
-    return false;
-  }
-}
-
-
 // Check the hard-coded field offsets of all the classes in this file
 
 void JavaClasses::check_offsets() {
@@ -4014,31 +3912,6 @@
 #define CHECK_LONG_OFFSET(klass_name, cpp_klass_name, field_name, field_sig) \
   valid &= check_offset(klass_name, cpp_klass_name :: long_ ## field_name ## _offset, #field_name, field_sig)
 
-#define CHECK_STATIC_OFFSET(klass_name, cpp_klass_name, field_name, field_sig) \
-  valid &= check_static_offset(klass_name, cpp_klass_name :: static_ ## field_name ## _offset, #field_name, field_sig)
-
-#define CHECK_CONSTANT(klass_name, cpp_klass_name, field_name, field_sig) \
-  valid &= check_constant(klass_name, cpp_klass_name :: field_name, #field_name, field_sig)
-
-  // java.lang.String
-
-  CHECK_OFFSET("java/lang/String", java_lang_String, value, "[B");
-  CHECK_OFFSET("java/lang/String", java_lang_String, hash, "I");
-  CHECK_OFFSET("java/lang/String", java_lang_String, coder, "B");
-
-  // java.lang.Class
-
-  // Fake fields
-  // CHECK_OFFSET("java/lang/Class", java_lang_Class, klass); // %%% this needs to be checked
-  // CHECK_OFFSET("java/lang/Class", java_lang_Class, array_klass); // %%% this needs to be checked
-
-  // java.lang.Throwable
-
-  CHECK_OFFSET("java/lang/Throwable", java_lang_Throwable, backtrace, "Ljava/lang/Object;");
-  CHECK_OFFSET("java/lang/Throwable", java_lang_Throwable, detailMessage, "Ljava/lang/String;");
-  CHECK_OFFSET("java/lang/Throwable", java_lang_Throwable, stackTrace, "[Ljava/lang/StackTraceElement;");
-  CHECK_OFFSET("java/lang/Throwable", java_lang_Throwable, depth, "I");
-
   // Boxed primitive objects (java_lang_boxing_object)
 
   CHECK_OFFSET("java/lang/Boolean",   java_lang_boxing_object, value, "Z");
@@ -4050,28 +3923,6 @@
   CHECK_OFFSET("java/lang/Integer",   java_lang_boxing_object, value, "I");
   CHECK_LONG_OFFSET("java/lang/Long", java_lang_boxing_object, value, "J");
 
-  // java.lang.ClassLoader
-
-  CHECK_OFFSET("java/lang/ClassLoader", java_lang_ClassLoader, parent,        "Ljava/lang/ClassLoader;");
-
-  // java.lang.System
-
-  CHECK_STATIC_OFFSET("java/lang/System", java_lang_System,  in, "Ljava/io/InputStream;");
-  CHECK_STATIC_OFFSET("java/lang/System", java_lang_System, out, "Ljava/io/PrintStream;");
-  CHECK_STATIC_OFFSET("java/lang/System", java_lang_System, err, "Ljava/io/PrintStream;");
-  CHECK_STATIC_OFFSET("java/lang/System", java_lang_System, security, "Ljava/lang/SecurityManager;");
-
-  // java.lang.StackTraceElement
-
-  CHECK_OFFSET("java/lang/StackTraceElement", java_lang_StackTraceElement, declaringClassObject, "Ljava/lang/Class;");
-  CHECK_OFFSET("java/lang/StackTraceElement", java_lang_StackTraceElement, classLoaderName, "Ljava/lang/String;");
-  CHECK_OFFSET("java/lang/StackTraceElement", java_lang_StackTraceElement, moduleName,      "Ljava/lang/String;");
-  CHECK_OFFSET("java/lang/StackTraceElement", java_lang_StackTraceElement, moduleVersion,   "Ljava/lang/String;");
-  CHECK_OFFSET("java/lang/StackTraceElement", java_lang_StackTraceElement, declaringClass,  "Ljava/lang/String;");
-  CHECK_OFFSET("java/lang/StackTraceElement", java_lang_StackTraceElement, methodName,      "Ljava/lang/String;");
-  CHECK_OFFSET("java/lang/StackTraceElement", java_lang_StackTraceElement, fileName,        "Ljava/lang/String;");
-  CHECK_OFFSET("java/lang/StackTraceElement", java_lang_StackTraceElement, lineNumber,      "I");
-
   // java.lang.ref.Reference
 
   CHECK_OFFSET("java/lang/ref/Reference", java_lang_ref_Reference, referent, "Ljava/lang/Object;");
@@ -4080,28 +3931,6 @@
   // Fake field
   //CHECK_OFFSET("java/lang/ref/Reference", java_lang_ref_Reference, discovered, "Ljava/lang/ref/Reference;");
 
-  // java.lang.ref.SoftReference
-
-  CHECK_OFFSET("java/lang/ref/SoftReference", java_lang_ref_SoftReference, timestamp, "J");
-  CHECK_STATIC_OFFSET("java/lang/ref/SoftReference", java_lang_ref_SoftReference, clock, "J");
-
-  // java.lang.AssertionStatusDirectives
-  //
-  // The CheckAssertionStatusDirectives boolean can be removed from here and
-  // globals.hpp after the AssertionStatusDirectives class has been integrated
-  // into merlin "for some time."  Without it, the vm will fail with early
-  // merlin builds.
-
-  if (CheckAssertionStatusDirectives) {
-    const char* nm = "java/lang/AssertionStatusDirectives";
-    const char* sig = "[Ljava/lang/String;";
-    CHECK_OFFSET(nm, java_lang_AssertionStatusDirectives, classes, sig);
-    CHECK_OFFSET(nm, java_lang_AssertionStatusDirectives, classEnabled, "[Z");
-    CHECK_OFFSET(nm, java_lang_AssertionStatusDirectives, packages, sig);
-    CHECK_OFFSET(nm, java_lang_AssertionStatusDirectives, packageEnabled, "[Z");
-    CHECK_OFFSET(nm, java_lang_AssertionStatusDirectives, deflt, "Z");
-  }
-
   if (!valid) vm_exit_during_initialization("Hard-coded field offset verification failed");
 }
 
--- a/src/hotspot/share/classfile/javaClasses.hpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/share/classfile/javaClasses.hpp	Mon Jan 22 16:55:01 2018 +0100
@@ -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
@@ -102,6 +102,7 @@
 
   // Accessors
   static inline typeArrayOop value(oop java_string);
+  static inline typeArrayOop value_no_keepalive(oop java_string);
   static inline unsigned int hash(oop java_string);
   static inline bool is_latin1(oop java_string);
   static inline int length(oop java_string);
@@ -444,9 +445,6 @@
     hc_cause_offset         =  2,  // New since 1.4
     hc_stackTrace_offset    =  3   // New since 1.4
   };
-  enum {
-      hc_static_unassigned_stacktrace_offset = 0  // New since 1.7
-  };
   // Trace constants
   enum {
     trace_methods_offset = 0,
@@ -878,7 +876,6 @@
   static int queue_offset;
   static int next_offset;
   static int discovered_offset;
-  static int number_of_fake_oop_fields;
 
   // Accessors
   static inline oop referent(oop ref);
@@ -902,14 +899,6 @@
 
 class java_lang_ref_SoftReference: public java_lang_ref_Reference {
  public:
-  enum {
-   // The timestamp is a long field and may need to be adjusted for alignment.
-   hc_timestamp_offset  = hc_discovered_offset + 1
-  };
-  enum {
-   hc_static_clock_offset = 0
-  };
-
   static int timestamp_offset;
   static int static_clock_offset;
 
@@ -919,6 +908,8 @@
   // Accessors for statics
   static jlong clock();
   static void set_clock(jlong value);
+
+  static void compute_offsets();
 };
 
 // Interface to java.lang.invoke.MethodHandle objects
@@ -1228,10 +1219,6 @@
 
 class java_lang_ClassLoader : AllStatic {
  private:
-  // The fake offsets are added by the class loader when java.lang.Class is loaded
-  enum {
-   hc_parent_offset = 0
-  };
   static int _loader_data_offset;
   static bool offsets_computed;
   static int parent_offset;
@@ -1279,13 +1266,6 @@
 
 class java_lang_System : AllStatic {
  private:
-  enum {
-   hc_static_in_offset  = 0,
-   hc_static_out_offset = 1,
-   hc_static_err_offset = 2,
-   hc_static_security_offset = 3
-  };
-
   static int  static_in_offset;
   static int static_out_offset;
   static int static_err_offset;
@@ -1298,6 +1278,8 @@
 
   static bool has_security_manager();
 
+  static void compute_offsets();
+
   // Debugging
   friend class JavaClasses;
 };
@@ -1307,17 +1289,6 @@
 
 class java_lang_StackTraceElement: AllStatic {
  private:
-  enum {
-    hc_declaringClassObject_offset    = 0,
-    hc_classLoaderName_offset      = 1,
-    hc_moduleName_offset           = 2,
-    hc_moduleVersion_offset        = 3,
-    hc_declaringClass_offset       = 4,
-    hc_methodName_offset           = 5,
-    hc_fileName_offset             = 6,
-    hc_lineNumber_offset           = 7
-  };
-
   static int declaringClassObject_offset;
   static int classLoaderName_offset;
   static int moduleName_offset;
@@ -1344,6 +1315,8 @@
   static void fill_in(Handle element, InstanceKlass* holder, const methodHandle& method,
                       int version, int bci, Symbol* name, TRAPS);
 
+  static void compute_offsets();
+
   // Debugging
   friend class JavaClasses;
 };
@@ -1416,14 +1389,6 @@
 
 class java_lang_AssertionStatusDirectives: AllStatic {
  private:
-  enum {
-    hc_classes_offset,
-    hc_classEnabled_offset,
-    hc_packages_offset,
-    hc_packageEnabled_offset,
-    hc_deflt_offset
-  };
-
   static int classes_offset;
   static int classEnabled_offset;
   static int packages_offset;
@@ -1437,6 +1402,9 @@
   static void set_packages(oop obj, oop val);
   static void set_packageEnabled(oop obj, oop val);
   static void set_deflt(oop obj, bool val);
+
+  static void compute_offsets();
+
   // Debugging
   friend class JavaClasses;
 };
@@ -1508,9 +1476,6 @@
   static InjectedField _injected_fields[];
 
   static bool check_offset(const char *klass_name, int offset, const char *field_name, const char* field_sig) PRODUCT_RETURN0;
-  static bool check_static_offset(const char *klass_name, int hardcoded_offset, const char *field_name, const char* field_sig) PRODUCT_RETURN0;
-  static bool check_constant(const char *klass_name, int constant, const char *field_name, const char* field_sig) PRODUCT_RETURN0;
-
  public:
   enum InjectedFieldID {
     ALL_INJECTED_FIELDS(DECLARE_INJECTED_FIELD_ENUM)
--- a/src/hotspot/share/classfile/javaClasses.inline.hpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/share/classfile/javaClasses.inline.hpp	Mon Jan 22 16:55:01 2018 +0100
@@ -26,6 +26,7 @@
 #define SHARE_VM_CLASSFILE_JAVACLASSES_INLINE_HPP
 
 #include "classfile/javaClasses.hpp"
+#include "oops/access.inline.hpp"
 #include "oops/oop.inline.hpp"
 #include "oops/oopsHierarchy.hpp"
 
@@ -53,6 +54,11 @@
   assert(is_instance(java_string), "must be java_string");
   return (typeArrayOop) java_string->obj_field(value_offset);
 }
+typeArrayOop java_lang_String::value_no_keepalive(oop java_string) {
+  assert(initialized && (value_offset > 0), "Must be initialized");
+  assert(is_instance(java_string), "must be java_string");
+  return (typeArrayOop) java_string->obj_field_access<AS_NO_KEEPALIVE>(value_offset);
+}
 unsigned int java_lang_String::hash(oop java_string) {
   assert(initialized && (hash_offset > 0), "Must be initialized");
   assert(is_instance(java_string), "must be java_string");
@@ -68,11 +74,11 @@
 int java_lang_String::length(oop java_string) {
   assert(initialized, "Must be initialized");
   assert(is_instance(java_string), "must be java_string");
-  typeArrayOop value_array = ((typeArrayOop)java_string->obj_field(value_offset));
-  if (value_array == NULL) {
+  typeArrayOop value = java_lang_String::value_no_keepalive(java_string);
+  if (value == NULL) {
     return 0;
   }
-  int arr_length = value_array->length();
+  int arr_length = value->length();
   if (!is_latin1(java_string)) {
     assert((arr_length & 1) == 0, "should be even for UTF16 string");
     arr_length >>= 1; // convert number of bytes to number of elements
--- a/src/hotspot/share/classfile/stringTable.cpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/share/classfile/stringTable.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -35,6 +35,7 @@
 #include "memory/filemap.hpp"
 #include "memory/metaspaceShared.hpp"
 #include "memory/resourceArea.hpp"
+#include "oops/access.inline.hpp"
 #include "oops/oop.inline.hpp"
 #include "runtime/atomic.hpp"
 #include "runtime/mutexLocker.hpp"
@@ -43,7 +44,6 @@
 #include "utilities/macros.hpp"
 #if INCLUDE_ALL_GCS
 #include "gc/g1/g1CollectedHeap.hpp"
-#include "gc/g1/g1SATBCardTableModRefBS.hpp"
 #include "gc/g1/g1StringDedup.hpp"
 #endif
 
@@ -124,6 +124,22 @@
   }
 }
 
+oop StringTable::string_object(HashtableEntry<oop, mtSymbol>* entry) {
+  return RootAccess<ON_PHANTOM_OOP_REF>::oop_load(entry->literal_addr());
+}
+
+oop StringTable::string_object_no_keepalive(HashtableEntry<oop, mtSymbol>* entry) {
+  // The AS_NO_KEEPALIVE peeks at the oop without keeping it alive.
+  // This is *very dangerous* in general but is okay in this specific
+  // case. The subsequent oop_load keeps the oop alive if it it matched
+  // the jchar* string.
+  return RootAccess<ON_PHANTOM_OOP_REF | AS_NO_KEEPALIVE>::oop_load(entry->literal_addr());
+}
+
+void StringTable::set_string_object(HashtableEntry<oop, mtSymbol>* entry, oop string) {
+  RootAccess<ON_PHANTOM_OOP_REF>::oop_store(entry->literal_addr(), string);
+}
+
 oop StringTable::lookup_shared(jchar* name, int len, unsigned int hash) {
   assert(hash == java_lang_String::hash_code(name, len),
          "hash must be computed using java_lang_String::hash_code");
@@ -131,13 +147,16 @@
 }
 
 oop StringTable::lookup_in_main_table(int index, jchar* name,
-                                int len, unsigned int hash) {
+                                      int len, unsigned int hash) {
   int count = 0;
   for (HashtableEntry<oop, mtSymbol>* l = bucket(index); l != NULL; l = l->next()) {
     count++;
     if (l->hash() == hash) {
-      if (java_lang_String::equals(l->literal(), name, len)) {
-        return l->literal();
+      if (java_lang_String::equals(string_object_no_keepalive(l), name, len)) {
+        // We must perform a new load with string_object() that keeps the string
+        // alive as we must expose the oop as strongly reachable when exiting
+        // this context, in case the oop gets published.
+        return string_object(l);
       }
     }
   }
@@ -192,18 +211,6 @@
   return lookup(chars, length);
 }
 
-// Tell the GC that this string was looked up in the StringTable.
-static void ensure_string_alive(oop string) {
-  // A lookup in the StringTable could return an object that was previously
-  // considered dead. The SATB part of G1 needs to get notified about this
-  // potential resurrection, otherwise the marking might not find the object.
-#if INCLUDE_ALL_GCS
-  if (UseG1GC && string != NULL) {
-    G1SATBCardTableModRefBS::enqueue(string);
-  }
-#endif
-}
-
 oop StringTable::lookup(jchar* name, int len) {
   // shared table always uses java_lang_String::hash_code
   unsigned int hash = java_lang_String::hash_code(name, len);
@@ -217,8 +224,6 @@
   int index = the_table()->hash_to_index(hash);
   string = the_table()->lookup_in_main_table(index, name, len, hash);
 
-  ensure_string_alive(string);
-
   return string;
 }
 
@@ -238,9 +243,6 @@
 
   // Found
   if (found_string != NULL) {
-    if (found_string != string_or_null()) {
-      ensure_string_alive(found_string);
-    }
     return found_string;
   }
 
@@ -276,10 +278,6 @@
                                   hashValue, CHECK_NULL);
   }
 
-  if (added_or_found != string()) {
-    ensure_string_alive(added_or_found);
-  }
-
   return added_or_found;
 }
 
@@ -388,9 +386,9 @@
     while (entry != NULL) {
       assert(!entry->is_shared(), "CDS not used for the StringTable");
 
-      if (is_alive->do_object_b(entry->literal())) {
+      if (is_alive->do_object_b(string_object_no_keepalive(entry))) {
         if (f != NULL) {
-          f->do_oop((oop*)entry->literal_addr());
+          f->do_oop(entry->literal_addr());
         }
         p = entry->next_addr();
       } else {
@@ -429,7 +427,7 @@
   for (int i = 0; i < the_table()->table_size(); ++i) {
     HashtableEntry<oop, mtSymbol>* p = the_table()->bucket(i);
     for ( ; p != NULL; p = p->next()) {
-      oop s = p->literal();
+      oop s = string_object_no_keepalive(p);
       guarantee(s != NULL, "interned string is NULL");
       unsigned int h = hash_string(s);
       guarantee(p->hash() == h, "broken hash in string table entry");
@@ -448,10 +446,10 @@
     for (int i = 0; i < the_table()->table_size(); ++i) {
       HashtableEntry<oop, mtSymbol>* p = the_table()->bucket(i);
       for ( ; p != NULL; p = p->next()) {
-        oop s = p->literal();
-        typeArrayOop value  = java_lang_String::value(s);
-        int          length = java_lang_String::length(s);
-        bool      is_latin1 = java_lang_String::is_latin1(s);
+        oop s = string_object_no_keepalive(p);
+        typeArrayOop value     = java_lang_String::value_no_keepalive(s);
+        int          length    = java_lang_String::length(s);
+        bool         is_latin1 = java_lang_String::is_latin1(s);
 
         if (length <= 0) {
           st->print("%d: ", length);
@@ -484,8 +482,8 @@
                                       HashtableEntry<oop, mtSymbol>* e_ptr2) {
   // These entries are sanity checked by verify_and_compare_entries()
   // before this function is called.
-  oop str1 = e_ptr1->literal();
-  oop str2 = e_ptr2->literal();
+  oop str1 = string_object_no_keepalive(e_ptr1);
+  oop str2 = string_object_no_keepalive(e_ptr2);
 
   if (str1 == str2) {
     tty->print_cr("ERROR: identical oop values (0x" PTR_FORMAT ") "
@@ -505,12 +503,12 @@
 }
 
 StringTable::VerifyRetTypes StringTable::verify_entry(int bkt, int e_cnt,
-                                      HashtableEntry<oop, mtSymbol>* e_ptr,
-                                      StringTable::VerifyMesgModes mesg_mode) {
+                                                      HashtableEntry<oop, mtSymbol>* e_ptr,
+                                                      StringTable::VerifyMesgModes mesg_mode) {
 
   VerifyRetTypes ret = _verify_pass;  // be optimistic
 
-  oop str = e_ptr->literal();
+  oop str = string_object_no_keepalive(e_ptr);
   if (str == NULL) {
     if (mesg_mode == _verify_with_mesgs) {
       tty->print_cr("ERROR: NULL oop value in entry @ bucket[%d][%d]", bkt,
@@ -684,7 +682,7 @@
   assert(DumpSharedSpaces, "this function is only used with -Xshare:dump");
 
   oop new_s = NULL;
-  typeArrayOop v = java_lang_String::value(s);
+  typeArrayOop v = java_lang_String::value_no_keepalive(s);
   typeArrayOop new_v = (typeArrayOop)MetaspaceShared::archive_heap_object(v, THREAD);
   if (new_v == NULL) {
     return NULL;
@@ -708,7 +706,7 @@
   for (int i = 0; i < the_table()->table_size(); ++i) {
     HashtableEntry<oop, mtSymbol>* bucket = the_table()->bucket(i);
     for ( ; bucket != NULL; bucket = bucket->next()) {
-      oop s = bucket->literal();
+      oop s = string_object_no_keepalive(bucket);
       unsigned int hash = java_lang_String::hash_code(s);
       if (hash == 0) {
         continue;
@@ -721,7 +719,7 @@
       }
 
       // set the archived string in bucket
-      bucket->set_literal(new_s);
+      set_string_object(bucket, new_s);
 
       // add to the compact table
       writer->add(hash, new_s);
@@ -763,4 +761,3 @@
   _shared_table.oops_do(f);
 }
 #endif //INCLUDE_CDS_JAVA_HEAP
-
--- a/src/hotspot/share/classfile/stringTable.hpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/share/classfile/stringTable.hpp	Mon Jan 22 16:55:01 2018 +0100
@@ -76,6 +76,13 @@
   static unsigned int hash_string(oop string);
   static unsigned int alt_hash_string(const jchar* s, int len);
 
+  // Accessors for the string roots in the hashtable entries.
+  // Use string_object_no_keepalive() only when the value is not returned
+  // outside of a scope where a thread transition is possible.
+  static oop string_object(HashtableEntry<oop, mtSymbol>* entry);
+  static oop string_object_no_keepalive(HashtableEntry<oop, mtSymbol>* entry);
+  static void set_string_object(HashtableEntry<oop, mtSymbol>* entry, oop string);
+
   StringTable() : RehashableHashtable<oop, mtSymbol>((int)StringTableSize,
                               sizeof (HashtableEntry<oop, mtSymbol>)) {}
 
--- a/src/hotspot/share/classfile/systemDictionary.hpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/share/classfile/systemDictionary.hpp	Mon Jan 22 16:55:01 2018 +0100
@@ -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
@@ -173,6 +173,7 @@
   do_klass(VolatileCallSite_klass,                      java_lang_invoke_VolatileCallSite,         Pre                 ) \
   /* Note: MethodHandle must be first, and VolatileCallSite last in group */                                             \
                                                                                                                          \
+  do_klass(AssertionStatusDirectives_klass,             java_lang_AssertionStatusDirectives,       Pre                 ) \
   do_klass(StringBuffer_klass,                          java_lang_StringBuffer,                    Pre                 ) \
   do_klass(StringBuilder_klass,                         java_lang_StringBuilder,                   Pre                 ) \
   do_klass(internal_Unsafe_klass,                       jdk_internal_misc_Unsafe,                  Pre                 ) \
--- a/src/hotspot/share/classfile/vmSymbols.hpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/share/classfile/vmSymbols.hpp	Mon Jan 22 16:55:01 2018 +0100
@@ -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
@@ -251,7 +251,6 @@
   template(compiledLambdaForm_name,                   "<compiledLambdaForm>")  /*fake name*/      \
   template(star_name,                                 "*") /*not really a name*/                  \
   template(invoke_name,                               "invoke")                                   \
-  template(override_name,                             "override")                                 \
   template(parameterTypes_name,                       "parameterTypes")                           \
   template(returnType_name,                           "returnType")                               \
   template(signature_name,                            "signature")                                \
@@ -265,7 +264,6 @@
   template(parameter_annotations_name,                "parameterAnnotations")                     \
   template(annotation_default_name,                   "annotationDefault")                        \
   template(reflect_ConstantPool,                      "jdk/internal/reflect/ConstantPool")        \
-  template(ConstantPool_name,                         "constantPoolOop")                          \
   template(reflect_UnsafeStaticFieldAccessorImpl,     "jdk/internal/reflect/UnsafeStaticFieldAccessorImpl")\
   template(base_name,                                 "base")                                     \
   /* Type Annotations (JDK 8 and above) */                                                        \
@@ -341,8 +339,6 @@
   template(stillborn_name,                            "stillborn")                                \
   template(group_name,                                "group")                                    \
   template(daemon_name,                               "daemon")                                   \
-  template(eetop_name,                                "eetop")                                    \
-  template(thread_status_name,                        "threadStatus")                             \
   template(run_method_name,                           "run")                                      \
   template(exit_method_name,                          "exit")                                     \
   template(add_method_name,                           "add")                                      \
@@ -376,34 +372,21 @@
   template(fillInStackTrace_name,                     "fillInStackTrace")                         \
   template(getCause_name,                             "getCause")                                 \
   template(initCause_name,                            "initCause")                                \
-  template(depth_name,                                "depth")                                    \
   template(setProperty_name,                          "setProperty")                              \
   template(getProperty_name,                          "getProperty")                              \
   template(context_name,                              "context")                                  \
-  template(privilegedContext_name,                    "privilegedContext")                        \
   template(contextClassLoader_name,                   "contextClassLoader")                       \
   template(inheritedAccessControlContext_name,        "inheritedAccessControlContext")            \
-  template(isPrivileged_name,                         "isPrivileged")                             \
-  template(isAuthorized_name,                         "isAuthorized")                             \
   template(getClassContext_name,                      "getClassContext")                          \
   template(wait_name,                                 "wait")                                     \
   template(checkPackageAccess_name,                   "checkPackageAccess")                       \
-  template(stackSize_name,                            "stackSize")                                \
-  template(thread_id_name,                            "tid")                                      \
   template(newInstance0_name,                         "newInstance0")                             \
-  template(limit_name,                                "limit")                                    \
-  template(member_name,                               "member")                                   \
   template(forName_name,                              "forName")                                  \
   template(forName0_name,                             "forName0")                                 \
   template(isJavaIdentifierStart_name,                "isJavaIdentifierStart")                    \
   template(isJavaIdentifierPart_name,                 "isJavaIdentifierPart")                     \
-  template(exclusive_owner_thread_name,               "exclusiveOwnerThread")                     \
-  template(park_blocker_name,                         "parkBlocker")                              \
-  template(park_event_name,                           "nativeParkEventPointer")                   \
   template(cache_field_name,                          "cache")                                    \
   template(value_name,                                "value")                                    \
-  template(hash_name,                                 "hash")                                     \
-  template(coder_name,                                "coder")                                    \
   template(compact_strings_name,                      "COMPACT_STRINGS")                          \
   template(numberOfLeadingZeros_name,                 "numberOfLeadingZeros")                     \
   template(numberOfTrailingZeros_name,                "numberOfTrailingZeros")                    \
@@ -420,27 +403,17 @@
   template(method_name,                               "method")                                   \
   template(vmindex_name,                              "vmindex")                                  \
   template(vmcount_name,                              "vmcount")                                  \
-  template(vmentry_name,                              "vmentry")                                  \
   template(flags_name,                                "flags")                                    \
-  template(rtype_name,                                "rtype")                                    \
-  template(ptypes_name,                               "ptypes")                                   \
-  template(form_name,                                 "form")                                     \
   template(basicType_name,                            "basicType")                                \
   template(append_name,                               "append")                                   \
   template(klass_name,                                "klass")                                    \
   template(array_klass_name,                          "array_klass")                              \
-  template(memberName_name,                           "memberName")                               \
   template(mid_name,                                  "mid")                                      \
   template(cpref_name,                                "cpref")                                    \
   template(version_name,                              "version")                                  \
-  template(bci_name,                                  "bci")                                      \
   template(methodName_name,                           "methodName")                               \
   template(fileName_name,                             "fileName")                                 \
   template(lineNumber_name,                           "lineNumber")                               \
-  template(monitors_name,                             "monitors")                                 \
-  template(locals_name,                               "locals")                                   \
-  template(operands_name,                             "operands")                                 \
-  template(mode_name,                                 "mode")                                     \
   template(oop_size_name,                             "oop_size")                                 \
   template(static_oop_field_count_name,               "static_oop_field_count")                   \
   template(protection_domain_name,                    "protection_domain")                        \
@@ -448,9 +421,11 @@
   template(loader_data_name,                          "loader_data")                              \
   template(vmdependencies_name,                       "vmdependencies")                           \
   template(loader_name,                               "loader")                                   \
-  template(module_name,                               "module")                                   \
   template(getModule_name,                            "getModule")                                \
   template(input_stream_void_signature,               "(Ljava/io/InputStream;)V")                 \
+  template(input_stream_signature,                    "Ljava/io/InputStream;")                    \
+  template(print_stream_signature,                    "Ljava/io/PrintStream;")                    \
+  template(security_manager_signature,                "Ljava/lang/SecurityManager;")              \
   template(definePackage_name,                        "definePackage")                            \
   template(definePackage_signature,                   "(Ljava/lang/String;Ljava/lang/Module;)Ljava/lang/Package;") \
   template(defineOrCheckPackage_name,                 "defineOrCheckPackage")                     \
@@ -499,6 +474,7 @@
   template(short_signature,                           "S")                                        \
   template(bool_signature,                            "Z")                                        \
   template(void_signature,                            "V")                                        \
+  template(bool_array_signature,                      "[Z")                                       \
   template(byte_array_signature,                      "[B")                                       \
   template(char_array_signature,                      "[C")                                       \
   template(int_array_signature,                       "[I")                                       \
@@ -553,6 +529,7 @@
   template(object_array_signature,                    "[Ljava/lang/Object;")                                      \
   template(class_signature,                           "Ljava/lang/Class;")                                        \
   template(string_signature,                          "Ljava/lang/String;")                                       \
+  template(string_array_signature,                    "[Ljava/lang/String;")                                      \
   template(reference_signature,                       "Ljava/lang/ref/Reference;")                                \
   template(sun_misc_Cleaner_signature,                "Lsun/misc/Cleaner;")                                       \
   template(executable_signature,                      "Ljava/lang/reflect/Executable;")                           \
@@ -579,12 +556,6 @@
   /* used by ClassFormatError when class name is not known yet */                                                 \
   template(unknown_class_name,                        "<Unknown>")                                                \
                                                                                                                   \
-  /* used to identify class loaders handling parallel class loading */                                            \
-  template(parallelCapable_name,                      "parallelLockMap")                                          \
-                                                                                                                  \
-  /* used to return a class loader's unnamed module */                                                            \
-  template(unnamedModule_name,                        "unnamedModule")                                            \
-                                                                                                                  \
   /* JVM monitoring and management support */                                                                     \
   template(java_lang_StackTraceElement_array,          "[Ljava/lang/StackTraceElement;")                          \
   template(java_lang_management_ThreadState,           "java/lang/management/ThreadState")                        \
--- a/src/hotspot/share/gc/g1/g1CollectedHeap.cpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/share/gc/g1/g1CollectedHeap.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -445,9 +445,7 @@
   assert_heap_not_locked_and_not_at_safepoint();
   assert(!is_humongous(word_size), "we do not allow humongous TLABs");
 
-  uint dummy_gc_count_before;
-  uint dummy_gclocker_retry_count = 0;
-  return attempt_allocation(word_size, &dummy_gc_count_before, &dummy_gclocker_retry_count);
+  return attempt_allocation(word_size);
 }
 
 HeapWord*
@@ -455,62 +453,16 @@
                               bool*  gc_overhead_limit_was_exceeded) {
   assert_heap_not_locked_and_not_at_safepoint();
 
-  // Loop until the allocation is satisfied, or unsatisfied after GC.
-  for (uint try_count = 1, gclocker_retry_count = 0; /* we'll return */; try_count += 1) {
-    uint gc_count_before;
-
-    HeapWord* result = NULL;
-    if (!is_humongous(word_size)) {
-      result = attempt_allocation(word_size, &gc_count_before, &gclocker_retry_count);
-    } else {
-      result = attempt_allocation_humongous(word_size, &gc_count_before, &gclocker_retry_count);
-    }
-    if (result != NULL) {
-      return result;
-    }
-
-    // Create the garbage collection operation...
-    VM_G1CollectForAllocation op(gc_count_before, word_size);
-    op.set_allocation_context(AllocationContext::current());
-
-    // ...and get the VM thread to execute it.
-    VMThread::execute(&op);
-
-    if (op.prologue_succeeded() && op.pause_succeeded()) {
-      // If the operation was successful we'll return the result even
-      // if it is NULL. If the allocation attempt failed immediately
-      // after a Full GC, it's unlikely we'll be able to allocate now.
-      HeapWord* result = op.result();
-      if (result != NULL && !is_humongous(word_size)) {
-        // Allocations that take place on VM operations do not do any
-        // card dirtying and we have to do it here. We only have to do
-        // this for non-humongous allocations, though.
-        dirty_young_block(result, word_size);
-      }
-      return result;
-    } else {
-      if (gclocker_retry_count > GCLockerRetryAllocationCount) {
-        return NULL;
-      }
-      assert(op.result() == NULL,
-             "the result should be NULL if the VM op did not succeed");
-    }
-
-    // Give a warning if we seem to be looping forever.
-    if ((QueuedAllocationWarningCount > 0) &&
-        (try_count % QueuedAllocationWarningCount == 0)) {
-      log_warning(gc)("G1CollectedHeap::mem_allocate retries %d times", try_count);
-    }
+  if (is_humongous(word_size)) {
+    return attempt_allocation_humongous(word_size);
   }
-
-  ShouldNotReachHere();
-  return NULL;
+  return attempt_allocation(word_size);
 }
 
 HeapWord* G1CollectedHeap::attempt_allocation_slow(size_t word_size,
-                                                   AllocationContext_t context,
-                                                   uint* gc_count_before_ret,
-                                                   uint* gclocker_retry_count_ret) {
+                                                   AllocationContext_t context) {
+  ResourceMark rm; // For retrieving the thread names in log messages.
+
   // Make sure you read the note in attempt_allocation_humongous().
 
   assert_heap_not_locked_and_not_at_safepoint();
@@ -525,7 +477,7 @@
   // fails to perform the allocation. b) is the only case when we'll
   // return NULL.
   HeapWord* result = NULL;
-  for (int try_count = 1; /* we'll return */; try_count += 1) {
+  for (uint try_count = 1, gclocker_retry_count = 0; /* we'll return */; try_count += 1) {
     bool should_try_gc;
     uint gc_count_before;
 
@@ -536,30 +488,23 @@
         return result;
       }
 
-      if (GCLocker::is_active_and_needs_gc()) {
-        if (g1_policy()->can_expand_young_list()) {
-          // No need for an ergo verbose message here,
-          // can_expand_young_list() does this when it returns true.
-          result = _allocator->attempt_allocation_force(word_size, context);
-          if (result != NULL) {
-            return result;
-          }
-        }
-        should_try_gc = false;
-      } else {
-        // The GCLocker may not be active but the GCLocker initiated
-        // GC may not yet have been performed (GCLocker::needs_gc()
-        // returns true). In this case we do not try this GC and
-        // wait until the GCLocker initiated GC is performed, and
-        // then retry the allocation.
-        if (GCLocker::needs_gc()) {
-          should_try_gc = false;
-        } else {
-          // Read the GC count while still holding the Heap_lock.
-          gc_count_before = total_collections();
-          should_try_gc = true;
+      // If the GCLocker is active and we are bound for a GC, try expanding young gen.
+      // This is different to when only GCLocker::needs_gc() is set: try to avoid
+      // waiting because the GCLocker is active to not wait too long.
+      if (GCLocker::is_active_and_needs_gc() && g1_policy()->can_expand_young_list()) {
+        // No need for an ergo message here, can_expand_young_list() does this when
+        // it returns true.
+        result = _allocator->attempt_allocation_force(word_size, context);
+        if (result != NULL) {
+          return result;
         }
       }
+      // Only try a GC if the GCLocker does not signal the need for a GC. Wait until
+      // the GCLocker initiated GC has been performed and then retry. This includes
+      // the case when the GC Locker is not active but has not been performed.
+      should_try_gc = !GCLocker::needs_gc();
+      // Read the GC count while still holding the Heap_lock.
+      gc_count_before = total_collections();
     }
 
     if (should_try_gc) {
@@ -568,28 +513,33 @@
                                    GCCause::_g1_inc_collection_pause);
       if (result != NULL) {
         assert(succeeded, "only way to get back a non-NULL result");
+        log_trace(gc, alloc)("%s: Successfully scheduled collection returning " PTR_FORMAT,
+                             Thread::current()->name(), p2i(result));
         return result;
       }
 
       if (succeeded) {
-        // If we get here we successfully scheduled a collection which
-        // failed to allocate. No point in trying to allocate
-        // further. We'll just return NULL.
-        MutexLockerEx x(Heap_lock);
-        *gc_count_before_ret = total_collections();
+        // We successfully scheduled a collection which failed to allocate. No
+        // point in trying to allocate further. We'll just return NULL.
+        log_trace(gc, alloc)("%s: Successfully scheduled collection failing to allocate "
+                             SIZE_FORMAT " words", Thread::current()->name(), word_size);
         return NULL;
       }
+      log_trace(gc, alloc)("%s: Unsuccessfully scheduled collection allocating " SIZE_FORMAT " words",
+                           Thread::current()->name(), word_size);
     } else {
-      if (*gclocker_retry_count_ret > GCLockerRetryAllocationCount) {
-        MutexLockerEx x(Heap_lock);
-        *gc_count_before_ret = total_collections();
+      // Failed to schedule a collection.
+      if (gclocker_retry_count > GCLockerRetryAllocationCount) {
+        log_warning(gc, alloc)("%s: Retried waiting for GCLocker too often allocating "
+                               SIZE_FORMAT " words", Thread::current()->name(), word_size);
         return NULL;
       }
+      log_trace(gc, alloc)("%s: Stall until clear", Thread::current()->name());
       // The GCLocker is either active or the GCLocker initiated
       // GC has not yet been performed. Stall until it is and
       // then retry the allocation.
       GCLocker::stall_until_clear();
-      (*gclocker_retry_count_ret) += 1;
+      gclocker_retry_count += 1;
     }
 
     // We can reach here if we were unsuccessful in scheduling a
@@ -600,6 +550,7 @@
     // first attempt (without holding the Heap_lock) here and the
     // follow-on attempt will be at the start of the next loop
     // iteration (after taking the Heap_lock).
+
     result = _allocator->attempt_allocation(word_size, context);
     if (result != NULL) {
       return result;
@@ -608,8 +559,8 @@
     // Give a warning if we seem to be looping forever.
     if ((QueuedAllocationWarningCount > 0) &&
         (try_count % QueuedAllocationWarningCount == 0)) {
-      log_warning(gc)("G1CollectedHeap::attempt_allocation_slow() "
-                      "retries %d times", try_count);
+      log_warning(gc, alloc)("%s:  Retried allocation %u times for " SIZE_FORMAT " words",
+                             Thread::current()->name(), try_count, word_size);
     }
   }
 
@@ -830,9 +781,7 @@
   }
 }
 
-inline HeapWord* G1CollectedHeap::attempt_allocation(size_t word_size,
-                                                     uint* gc_count_before_ret,
-                                                     uint* gclocker_retry_count_ret) {
+inline HeapWord* G1CollectedHeap::attempt_allocation(size_t word_size) {
   assert_heap_not_locked_and_not_at_safepoint();
   assert(!is_humongous(word_size), "attempt_allocation() should not "
          "be called for humongous allocation requests");
@@ -841,10 +790,7 @@
   HeapWord* result = _allocator->attempt_allocation(word_size, context);
 
   if (result == NULL) {
-    result = attempt_allocation_slow(word_size,
-                                     context,
-                                     gc_count_before_ret,
-                                     gclocker_retry_count_ret);
+    result = attempt_allocation_slow(word_size, context);
   }
   assert_heap_not_locked();
   if (result != NULL) {
@@ -925,9 +871,9 @@
   decrease_used(size_used);
 }
 
-HeapWord* G1CollectedHeap::attempt_allocation_humongous(size_t word_size,
-                                                        uint* gc_count_before_ret,
-                                                        uint* gclocker_retry_count_ret) {
+HeapWord* G1CollectedHeap::attempt_allocation_humongous(size_t word_size) {
+  ResourceMark rm; // For retrieving the thread names in log messages.
+
   // The structure of this method has a lot of similarities to
   // attempt_allocation_slow(). The reason these two were not merged
   // into a single one is that such a method would require several "if
@@ -958,10 +904,11 @@
   // fails to perform the allocation. b) is the only case when we'll
   // return NULL.
   HeapWord* result = NULL;
-  for (int try_count = 1; /* we'll return */; try_count += 1) {
+  for (uint try_count = 1, gclocker_retry_count = 0; /* we'll return */; try_count += 1) {
     bool should_try_gc;
     uint gc_count_before;
 
+
     {
       MutexLockerEx x(Heap_lock);
 
@@ -975,69 +922,63 @@
         return result;
       }
 
-      if (GCLocker::is_active_and_needs_gc()) {
-        should_try_gc = false;
-      } else {
-         // The GCLocker may not be active but the GCLocker initiated
-        // GC may not yet have been performed (GCLocker::needs_gc()
-        // returns true). In this case we do not try this GC and
-        // wait until the GCLocker initiated GC is performed, and
-        // then retry the allocation.
-        if (GCLocker::needs_gc()) {
-          should_try_gc = false;
-        } else {
-          // Read the GC count while still holding the Heap_lock.
-          gc_count_before = total_collections();
-          should_try_gc = true;
-        }
-      }
+      // Only try a GC if the GCLocker does not signal the need for a GC. Wait until
+      // the GCLocker initiated GC has been performed and then retry. This includes
+      // the case when the GC Locker is not active but has not been performed.
+      should_try_gc = !GCLocker::needs_gc();
+      // Read the GC count while still holding the Heap_lock.
+      gc_count_before = total_collections();
     }
 
     if (should_try_gc) {
-      // If we failed to allocate the humongous object, we should try to
-      // do a collection pause (if we're allowed) in case it reclaims
-      // enough space for the allocation to succeed after the pause.
-
       bool succeeded;
       result = do_collection_pause(word_size, gc_count_before, &succeeded,
                                    GCCause::_g1_humongous_allocation);
       if (result != NULL) {
         assert(succeeded, "only way to get back a non-NULL result");
+        log_trace(gc, alloc)("%s: Successfully scheduled collection returning " PTR_FORMAT,
+                             Thread::current()->name(), p2i(result));
         return result;
       }
 
       if (succeeded) {
-        // If we get here we successfully scheduled a collection which
-        // failed to allocate. No point in trying to allocate
-        // further. We'll just return NULL.
-        MutexLockerEx x(Heap_lock);
-        *gc_count_before_ret = total_collections();
+        // We successfully scheduled a collection which failed to allocate. No
+        // point in trying to allocate further. We'll just return NULL.
+        log_trace(gc, alloc)("%s: Successfully scheduled collection failing to allocate "
+                             SIZE_FORMAT " words", Thread::current()->name(), word_size);
         return NULL;
       }
+      log_trace(gc, alloc)("%s: Unsuccessfully scheduled collection allocating " SIZE_FORMAT "",
+                           Thread::current()->name(), word_size);
     } else {
-      if (*gclocker_retry_count_ret > GCLockerRetryAllocationCount) {
-        MutexLockerEx x(Heap_lock);
-        *gc_count_before_ret = total_collections();
+      // Failed to schedule a collection.
+      if (gclocker_retry_count > GCLockerRetryAllocationCount) {
+        log_warning(gc, alloc)("%s: Retried waiting for GCLocker too often allocating "
+                               SIZE_FORMAT " words", Thread::current()->name(), word_size);
         return NULL;
       }
+      log_trace(gc, alloc)("%s: Stall until clear", Thread::current()->name());
       // The GCLocker is either active or the GCLocker initiated
       // GC has not yet been performed. Stall until it is and
       // then retry the allocation.
       GCLocker::stall_until_clear();
-      (*gclocker_retry_count_ret) += 1;
+      gclocker_retry_count += 1;
     }
 
+
     // We can reach here if we were unsuccessful in scheduling a
     // collection (because another thread beat us to it) or if we were
     // stalled due to the GC locker. In either can we should retry the
     // allocation attempt in case another thread successfully
-    // performed a collection and reclaimed enough space.  Give a
-    // warning if we seem to be looping forever.
+    // performed a collection and reclaimed enough space.
+    // Humongous object allocation always needs a lock, so we wait for the retry
+    // in the next iteration of the loop, unlike for the regular iteration case.
+    // Give a warning if we seem to be looping forever.
 
     if ((QueuedAllocationWarningCount > 0) &&
         (try_count % QueuedAllocationWarningCount == 0)) {
-      log_warning(gc)("G1CollectedHeap::attempt_allocation_humongous() "
-                      "retries %d times", try_count);
+      log_warning(gc, alloc)("%s: Retried allocation %u times for " SIZE_FORMAT " words",
+                             Thread::current()->name(), try_count, word_size);
     }
   }
 
@@ -1339,7 +1280,6 @@
                                     context,
                                     expect_null_mutator_alloc_region);
   if (result != NULL) {
-    assert(*gc_succeeded, "sanity");
     return result;
   }
 
@@ -1349,7 +1289,6 @@
   // do something smarter than full collection to satisfy a failed alloc.)
   result = expand_and_allocate(word_size, context);
   if (result != NULL) {
-    assert(*gc_succeeded, "sanity");
     return result;
   }
 
@@ -1401,7 +1340,6 @@
                                             succeeded);
 
   if (result != NULL) {
-    assert(*succeeded, "sanity");
     return result;
   }
 
@@ -1412,7 +1350,6 @@
   // space available is large enough for the allocation, then a more
   // complete compaction phase than we've tried so far might be
   // appropriate.
-  assert(*succeeded, "sanity");
   return NULL;
 }
 
@@ -2147,7 +2084,7 @@
   // This notify_all() will ensure that a thread that called
   // System.gc() with (with ExplicitGCInvokesConcurrent set or not)
   // and it's waiting for a full GC to finish will be woken up. It is
-  // waiting in VM_G1IncCollectionPause::doit_epilogue().
+  // waiting in VM_G1CollectForAllocation::doit_epilogue().
   FullGCCount_lock->notify_all();
 }
 
@@ -2175,13 +2112,12 @@
       // Schedule an initial-mark evacuation pause that will start a
       // concurrent cycle. We're setting word_size to 0 which means that
       // we are not requesting a post-GC allocation.
-      VM_G1IncCollectionPause op(gc_count_before,
-                                 0,     /* word_size */
-                                 true,  /* should_initiate_conc_mark */
-                                 g1_policy()->max_pause_time_ms(),
-                                 cause);
-      op.set_allocation_context(AllocationContext::current());
-
+      VM_G1CollectForAllocation op(0,     /* word_size */
+                                   gc_count_before,
+                                   cause,
+                                   true,  /* should_initiate_conc_mark */
+                                   g1_policy()->max_pause_time_ms(),
+                                   AllocationContext::current());
       VMThread::execute(&op);
       if (!op.pause_succeeded()) {
         if (old_marking_count_before == _old_marking_cycles_started) {
@@ -2204,11 +2140,12 @@
 
         // Schedule a standard evacuation pause. We're setting word_size
         // to 0 which means that we are not requesting a post-GC allocation.
-        VM_G1IncCollectionPause op(gc_count_before,
-                                   0,     /* word_size */
-                                   false, /* should_initiate_conc_mark */
-                                   g1_policy()->max_pause_time_ms(),
-                                   cause);
+        VM_G1CollectForAllocation op(0,     /* word_size */
+                                     gc_count_before,
+                                     cause,
+                                     false, /* should_initiate_conc_mark */
+                                     g1_policy()->max_pause_time_ms(),
+                                     AllocationContext::current());
         VMThread::execute(&op);
       } else {
         // Schedule a Full GC.
@@ -2619,13 +2556,12 @@
                                                bool* succeeded,
                                                GCCause::Cause gc_cause) {
   assert_heap_not_locked_and_not_at_safepoint();
-  VM_G1IncCollectionPause op(gc_count_before,
-                             word_size,
-                             false, /* should_initiate_conc_mark */
-                             g1_policy()->max_pause_time_ms(),
-                             gc_cause);
-
-  op.set_allocation_context(AllocationContext::current());
+  VM_G1CollectForAllocation op(word_size,
+                               gc_count_before,
+                               gc_cause,
+                               false, /* should_initiate_conc_mark */
+                               g1_policy()->max_pause_time_ms(),
+                               AllocationContext::current());
   VMThread::execute(&op);
 
   HeapWord* result = op.result();
--- a/src/hotspot/share/gc/g1/g1CollectedHeap.hpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/share/gc/g1/g1CollectedHeap.hpp	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2017, 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
@@ -125,7 +125,6 @@
   friend class VM_CollectForMetadataAllocation;
   friend class VM_G1CollectForAllocation;
   friend class VM_G1CollectFull;
-  friend class VM_G1IncCollectionPause;
   friend class VMStructs;
   friend class MutatorAllocRegion;
   friend class G1FullCollector;
@@ -454,35 +453,20 @@
   virtual HeapWord* mem_allocate(size_t word_size,
                                  bool*  gc_overhead_limit_was_exceeded);
 
-  // The following three methods take a gc_count_before_ret
-  // parameter which is used to return the GC count if the method
-  // returns NULL. Given that we are required to read the GC count
-  // while holding the Heap_lock, and these paths will take the
-  // Heap_lock at some point, it's easier to get them to read the GC
-  // count while holding the Heap_lock before they return NULL instead
-  // of the caller (namely: mem_allocate()) having to also take the
-  // Heap_lock just to read the GC count.
-
   // First-level mutator allocation attempt: try to allocate out of
   // the mutator alloc region without taking the Heap_lock. This
   // should only be used for non-humongous allocations.
-  inline HeapWord* attempt_allocation(size_t word_size,
-                                      uint* gc_count_before_ret,
-                                      uint* gclocker_retry_count_ret);
+  inline HeapWord* attempt_allocation(size_t word_size);
 
   // Second-level mutator allocation attempt: take the Heap_lock and
   // retry the allocation attempt, potentially scheduling a GC
   // pause. This should only be used for non-humongous allocations.
   HeapWord* attempt_allocation_slow(size_t word_size,
-                                    AllocationContext_t context,
-                                    uint* gc_count_before_ret,
-                                    uint* gclocker_retry_count_ret);
+                                    AllocationContext_t context);
 
   // Takes the Heap_lock and attempts a humongous allocation. It can
   // potentially schedule a GC pause.
-  HeapWord* attempt_allocation_humongous(size_t word_size,
-                                         uint* gc_count_before_ret,
-                                         uint* gclocker_retry_count_ret);
+  HeapWord* attempt_allocation_humongous(size_t word_size);
 
   // Allocation attempt that should be called during safepoints (e.g.,
   // at the end of a successful GC). expect_null_mutator_alloc_region
@@ -1078,6 +1062,11 @@
     return _hrm.available() == 0;
   }
 
+  // Returns whether there are any regions left in the heap for allocation.
+  bool has_regions_left_for_allocation() const {
+    return !is_maximal_no_gc() || num_free_regions() != 0;
+  }
+
   // The current number of regions in the heap.
   uint num_regions() const { return _hrm.length(); }
 
--- a/src/hotspot/share/gc/g1/g1OopClosures.inline.hpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/share/gc/g1/g1OopClosures.inline.hpp	Mon Jan 22 16:55:01 2018 +0100
@@ -33,6 +33,7 @@
 #include "gc/g1/heapRegion.inline.hpp"
 #include "gc/g1/heapRegionRemSet.hpp"
 #include "memory/iterator.inline.hpp"
+#include "oops/access.inline.hpp"
 #include "runtime/prefetch.inline.hpp"
 
 template <class T>
@@ -87,13 +88,13 @@
 
 template <class T>
 inline void G1CMOopClosure::do_oop_nv(T* p) {
-  oop obj = oopDesc::load_decode_heap_oop(p);
+  oop obj = RawAccess<MO_VOLATILE>::oop_load(p);
   _task->deal_with_reference(obj);
 }
 
 template <class T>
 inline void G1RootRegionScanClosure::do_oop_nv(T* p) {
-  T heap_oop = oopDesc::load_heap_oop(p);
+  T heap_oop = RawAccess<MO_VOLATILE>::oop_load(p);
   if (oopDesc::is_null(heap_oop)) {
     return;
   }
@@ -124,7 +125,7 @@
 
 template <class T>
 inline void G1ConcurrentRefineOopClosure::do_oop_nv(T* p) {
-  T o = oopDesc::load_heap_oop(p);
+  T o = RawAccess<MO_VOLATILE>::oop_load(p);
   if (oopDesc::is_null(o)) {
     return;
   }
--- a/src/hotspot/share/gc/g1/g1SATBCardTableModRefBS.inline.hpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/share/gc/g1/g1SATBCardTableModRefBS.inline.hpp	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 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
@@ -27,7 +27,6 @@
 
 #include "gc/shared/accessBarrierSupport.inline.hpp"
 #include "gc/g1/g1SATBCardTableModRefBS.hpp"
-#include "oops/oop.inline.hpp"
 
 template <DecoratorSet decorators, typename T>
 inline void G1SATBCardTableModRefBS::write_ref_field_pre(T* field) {
--- a/src/hotspot/share/gc/g1/vm_operations_g1.cpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/share/gc/g1/vm_operations_g1.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -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
@@ -33,34 +33,21 @@
 #include "gc/shared/isGCActiveMark.hpp"
 #include "runtime/interfaceSupport.hpp"
 
-VM_G1CollectForAllocation::VM_G1CollectForAllocation(uint gc_count_before,
-                                                     size_t word_size)
-  : VM_G1OperationWithAllocRequest(gc_count_before, word_size,
-                                   GCCause::_allocation_failure) {
-  guarantee(word_size != 0, "An allocation should always be requested with this operation.");
-}
-
-void VM_G1CollectForAllocation::doit() {
-  G1CollectedHeap* g1h = G1CollectedHeap::heap();
-  GCCauseSetter x(g1h, _gc_cause);
-
-  _result = g1h->satisfy_failed_allocation(_word_size, allocation_context(), &_pause_succeeded);
-  assert(_result == NULL || _pause_succeeded,
-         "if we get back a result, the pause should have succeeded");
-}
-
 void VM_G1CollectFull::doit() {
   G1CollectedHeap* g1h = G1CollectedHeap::heap();
   GCCauseSetter x(g1h, _gc_cause);
   g1h->do_full_collection(false /* clear_all_soft_refs */);
 }
 
-VM_G1IncCollectionPause::VM_G1IncCollectionPause(uint           gc_count_before,
-                                                 size_t         word_size,
-                                                 bool           should_initiate_conc_mark,
-                                                 double         target_pause_time_ms,
-                                                 GCCause::Cause gc_cause)
-  : VM_G1OperationWithAllocRequest(gc_count_before, word_size, gc_cause),
+VM_G1CollectForAllocation::VM_G1CollectForAllocation(size_t         word_size,
+                                                     uint           gc_count_before,
+                                                     GCCause::Cause gc_cause,
+                                                     bool           should_initiate_conc_mark,
+                                                     double         target_pause_time_ms,
+                                                     AllocationContext_t allocation_context)
+  : VM_CollectForAllocation(word_size, gc_count_before, gc_cause),
+    _pause_succeeded(false),
+    _allocation_context(allocation_context),
     _should_initiate_conc_mark(should_initiate_conc_mark),
     _target_pause_time_ms(target_pause_time_ms),
     _should_retry_gc(false),
@@ -71,8 +58,8 @@
   _gc_cause = gc_cause;
 }
 
-bool VM_G1IncCollectionPause::doit_prologue() {
-  bool res = VM_G1OperationWithAllocRequest::doit_prologue();
+bool VM_G1CollectForAllocation::doit_prologue() {
+  bool res = VM_CollectForAllocation::doit_prologue();
   if (!res) {
     if (_should_initiate_conc_mark) {
       // The prologue can fail for a couple of reasons. The first is that another GC
@@ -87,7 +74,7 @@
   return res;
 }
 
-void VM_G1IncCollectionPause::doit() {
+void VM_G1CollectForAllocation::doit() {
   G1CollectedHeap* g1h = G1CollectedHeap::heap();
   assert(!_should_initiate_conc_mark || g1h->should_do_concurrent_full_gc(_gc_cause),
       "only a GC locker, a System.gc(), stats update, whitebox, or a hum allocation induced GC should start a cycle");
@@ -95,7 +82,7 @@
   if (_word_size > 0) {
     // An allocation has been requested. So, try to do that first.
     _result = g1h->attempt_allocation_at_safepoint(_word_size,
-                                                   allocation_context(),
+                                                   _allocation_context,
                                                    false /* expect_null_cur_alloc_region */);
     if (_result != NULL) {
       // If we can successfully allocate before we actually do the
@@ -144,27 +131,38 @@
     }
   }
 
-  _pause_succeeded =
-    g1h->do_collection_pause_at_safepoint(_target_pause_time_ms);
-  if (_pause_succeeded && _word_size > 0) {
-    // An allocation had been requested.
-    _result = g1h->attempt_allocation_at_safepoint(_word_size,
-                                                   allocation_context(),
-                                                   true /* expect_null_cur_alloc_region */);
+  // Try a partial collection of some kind.
+  _pause_succeeded = g1h->do_collection_pause_at_safepoint(_target_pause_time_ms);
+
+  if (_pause_succeeded) {
+    if (_word_size > 0) {
+      // An allocation had been requested. Do it, eventually trying a stronger
+      // kind of GC.
+      _result = g1h->satisfy_failed_allocation(_word_size, _allocation_context, &_pause_succeeded);
+    } else {
+      bool should_upgrade_to_full = !g1h->should_do_concurrent_full_gc(_gc_cause) &&
+                                    !g1h->has_regions_left_for_allocation();
+      if (should_upgrade_to_full) {
+        // There has been a request to perform a GC to free some space. We have no
+        // information on how much memory has been asked for. In case there are
+        // absolutely no regions left to allocate into, do a maximally compacting full GC.
+        log_info(gc, ergo)("Attempting maximally compacting collection");
+        _pause_succeeded = g1h->do_full_collection(false, /* explicit gc */
+                                                   true   /* clear_all_soft_refs */);
+      }
+    }
+    guarantee(_pause_succeeded, "Elevated collections during the safepoint must always succeed.");
   } else {
     assert(_result == NULL, "invariant");
-    if (!_pause_succeeded) {
-      // Another possible reason reason for the pause to not be successful
-      // is that, again, the GC locker is active (and has become active
-      // since the prologue was executed). In this case we should retry
-      // the pause after waiting for the GC locker to become inactive.
-      _should_retry_gc = true;
-    }
+    // The only reason for the pause to not be successful is that, the GC locker is
+    // active (or has become active since the prologue was executed). In this case
+    // we should retry the pause after waiting for the GC locker to become inactive.
+    _should_retry_gc = true;
   }
 }
 
-void VM_G1IncCollectionPause::doit_epilogue() {
-  VM_G1OperationWithAllocRequest::doit_epilogue();
+void VM_G1CollectForAllocation::doit_epilogue() {
+  VM_CollectForAllocation::doit_epilogue();
 
   // If the pause was initiated by a System.gc() and
   // +ExplicitGCInvokesConcurrent, we have to wait here for the cycle
--- a/src/hotspot/share/gc/g1/vm_operations_g1.hpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/share/gc/g1/vm_operations_g1.hpp	Mon Jan 22 16:55:01 2018 +0100
@@ -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
@@ -32,26 +32,8 @@
 // VM_operations for the G1 collector.
 // VM_GC_Operation:
 //   - VM_CGC_Operation
+//   - VM_G1CollectForAllocation
 //   - VM_G1CollectFull
-//   - VM_G1OperationWithAllocRequest
-//     - VM_G1CollectForAllocation
-//     - VM_G1IncCollectionPause
-
-class VM_G1OperationWithAllocRequest : public VM_CollectForAllocation {
-protected:
-  bool      _pause_succeeded;
-  AllocationContext_t _allocation_context;
-
-public:
-  VM_G1OperationWithAllocRequest(uint           gc_count_before,
-                                 size_t         word_size,
-                                 GCCause::Cause gc_cause)
-    : VM_CollectForAllocation(word_size, gc_count_before, gc_cause),
-      _pause_succeeded(false) {}
-  bool pause_succeeded() { return _pause_succeeded; }
-  void set_allocation_context(AllocationContext_t context) { _allocation_context = context; }
-  AllocationContext_t  allocation_context() { return _allocation_context; }
-};
 
 class VM_G1CollectFull: public VM_GC_Operation {
 public:
@@ -62,41 +44,35 @@
   virtual VMOp_Type type() const { return VMOp_G1CollectFull; }
   virtual void doit();
   virtual const char* name() const {
-    return "full garbage-first collection";
+    return "G1 Full collection";
   }
 };
 
-class VM_G1CollectForAllocation: public VM_G1OperationWithAllocRequest {
-public:
-  VM_G1CollectForAllocation(uint         gc_count_before,
-                            size_t       word_size);
-  virtual VMOp_Type type() const { return VMOp_G1CollectForAllocation; }
-  virtual void doit();
-  virtual const char* name() const {
-    return "garbage-first collection to satisfy allocation";
-  }
-};
+class VM_G1CollectForAllocation: public VM_CollectForAllocation {
+private:
+  bool      _pause_succeeded;
+  AllocationContext_t _allocation_context;
 
-class VM_G1IncCollectionPause: public VM_G1OperationWithAllocRequest {
-private:
   bool         _should_initiate_conc_mark;
   bool         _should_retry_gc;
   double       _target_pause_time_ms;
   uint         _old_marking_cycles_completed_before;
 public:
-  VM_G1IncCollectionPause(uint           gc_count_before,
-                          size_t         word_size,
-                          bool           should_initiate_conc_mark,
-                          double         target_pause_time_ms,
-                          GCCause::Cause gc_cause);
-  virtual VMOp_Type type() const { return VMOp_G1IncCollectionPause; }
+  VM_G1CollectForAllocation(size_t         word_size,
+                            uint           gc_count_before,
+                            GCCause::Cause gc_cause,
+                            bool           should_initiate_conc_mark,
+                            double         target_pause_time_ms,
+                            AllocationContext_t allocation_context);
+  virtual VMOp_Type type() const { return VMOp_G1CollectForAllocation; }
   virtual bool doit_prologue();
   virtual void doit();
   virtual void doit_epilogue();
   virtual const char* name() const {
-    return "garbage-first incremental collection pause";
+    return "G1 collect for allocation";
   }
   bool should_retry_gc() const { return _should_retry_gc; }
+  bool pause_succeeded() { return _pause_succeeded; }
 };
 
 // Concurrent GC stop-the-world operations such as remark and cleanup;
--- a/src/hotspot/share/gc/shared/barrierSet.hpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/share/gc/shared/barrierSet.hpp	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 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
@@ -147,9 +147,8 @@
   // 3) Provide specializations for BarrierSet::GetName and BarrierSet::GetType.
   template <DecoratorSet decorators, typename BarrierSetT>
   class AccessBarrier: protected RawAccessBarrier<decorators> {
-  protected:
+  private:
     typedef RawAccessBarrier<decorators> Raw;
-    typedef typename BarrierSetT::template AccessBarrier<decorators> CRTPAccessBarrier;
 
   public:
     // Primitive heap accesses. These accessors get resolved when
--- a/src/hotspot/share/jvmci/jvmciJavaClasses.hpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/share/jvmci/jvmciJavaClasses.hpp	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 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
@@ -351,7 +351,7 @@
     static type name() {                                                                                       \
       assert(klassName::klass() != NULL && klassName::klass()->is_linked(), "Class not yet linked: " #klassName); \
       InstanceKlass* ik = klassName::klass();                                                                  \
-      address addr = ik->static_field_addr(_##name##_offset - InstanceMirrorKlass::offset_of_static_fields()); \
+      address addr = ik->static_field_addr(_##name##_offset);                                                  \
       oop result = HeapAccess<>::oop_load((HeapWord*)addr);                                                    \
       return type(result);                                                                                     \
     }                                                                                                          \
@@ -359,7 +359,7 @@
       assert(klassName::klass() != NULL && klassName::klass()->is_linked(), "Class not yet linked: " #klassName); \
       assert(klassName::klass() != NULL, "Class not yet loaded: " #klassName);                                 \
       InstanceKlass* ik = klassName::klass();                                                                  \
-      address addr = ik->static_field_addr(_##name##_offset - InstanceMirrorKlass::offset_of_static_fields()); \
+      address addr = ik->static_field_addr(_##name##_offset);                                                  \
       HeapAccess<>::oop_store((HeapWord*)addr, x);                                                             \
     }
 #define STATIC_PRIMITIVE_FIELD(klassName, name, jtypename)                                                     \
@@ -367,13 +367,13 @@
     static jtypename name() {                                                                                  \
       assert(klassName::klass() != NULL && klassName::klass()->is_linked(), "Class not yet linked: " #klassName); \
       InstanceKlass* ik = klassName::klass();                                                                  \
-      address addr = ik->static_field_addr(_##name##_offset - InstanceMirrorKlass::offset_of_static_fields()); \
+      address addr = ik->static_field_addr(_##name##_offset);                                                  \
       return HeapAccess<>::load((jtypename*)addr);                                                             \
     }                                                                                                          \
     static void set_##name(jtypename x) {                                                                      \
       assert(klassName::klass() != NULL && klassName::klass()->is_linked(), "Class not yet linked: " #klassName); \
       InstanceKlass* ik = klassName::klass();                                                                  \
-      address addr = ik->static_field_addr(_##name##_offset - InstanceMirrorKlass::offset_of_static_fields()); \
+      address addr = ik->static_field_addr(_##name##_offset);                                                  \
       HeapAccess<>::store((jtypename*)addr, x);                                                                \
     }
 
--- a/src/hotspot/share/oops/access.hpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/share/oops/access.hpp	Mon Jan 22 16:55:01 2018 +0100
@@ -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
@@ -342,7 +342,7 @@
   template <DecoratorSet expected_mo_decorators>
   static void verify_primitive_decorators() {
     const DecoratorSet primitive_decorators = (AS_DECORATOR_MASK ^ AS_NO_KEEPALIVE) | IN_HEAP |
-                                               IN_HEAP_ARRAY | MO_DECORATOR_MASK;
+                                               IN_HEAP_ARRAY;
     verify_decorators<expected_mo_decorators | primitive_decorators>();
   }
 
@@ -350,7 +350,7 @@
   static void verify_oop_decorators() {
     const DecoratorSet oop_decorators = AS_DECORATOR_MASK | IN_DECORATOR_MASK |
                                         (ON_DECORATOR_MASK ^ ON_UNKNOWN_OOP_REF) | // no unknown oop refs outside of the heap
-                                        OOP_DECORATOR_MASK | MO_DECORATOR_MASK;
+                                        OOP_DECORATOR_MASK;
     verify_decorators<expected_mo_decorators | oop_decorators>();
   }
 
@@ -358,8 +358,7 @@
   static void verify_heap_oop_decorators() {
     const DecoratorSet heap_oop_decorators = AS_DECORATOR_MASK | ON_DECORATOR_MASK |
                                              OOP_DECORATOR_MASK | (IN_DECORATOR_MASK ^
-                                                                  (IN_ROOT ^ IN_CONCURRENT_ROOT)) | // no root accesses in the heap
-                                             MO_DECORATOR_MASK;
+                                                                   (IN_ROOT | IN_CONCURRENT_ROOT)); // no root accesses in the heap
     verify_decorators<expected_mo_decorators | heap_oop_decorators>();
   }
 
--- a/src/hotspot/share/oops/access.inline.hpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/share/oops/access.inline.hpp	Mon Jan 22 16:55:01 2018 +0100
@@ -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
@@ -491,11 +491,12 @@
   // not possible.
   struct PreRuntimeDispatch: AllStatic {
     template<DecoratorSet decorators>
-    static bool can_hardwire_raw() {
-      return !HasDecorator<decorators, INTERNAL_VALUE_IS_OOP>::value || // primitive access
-             !HasDecorator<decorators, INTERNAL_CONVERT_COMPRESSED_OOP>::value || // don't care about compressed oops (oop* address)
-             HasDecorator<decorators, INTERNAL_RT_USE_COMPRESSED_OOPS>::value; // we can infer we use compressed oops (narrowOop* address)
-    }
+    struct CanHardwireRaw: public IntegralConstant<
+      bool,
+      !HasDecorator<decorators, INTERNAL_VALUE_IS_OOP>::value || // primitive access
+      !HasDecorator<decorators, INTERNAL_CONVERT_COMPRESSED_OOP>::value || // don't care about compressed oops (oop* address)
+      HasDecorator<decorators, INTERNAL_RT_USE_COMPRESSED_OOPS>::value> // we can infer we use compressed oops (narrowOop* address)
+    {};
 
     static const DecoratorSet convert_compressed_oops = INTERNAL_RT_USE_COMPRESSED_OOPS | INTERNAL_CONVERT_COMPRESSED_OOP;
 
@@ -507,16 +508,21 @@
 
     template <DecoratorSet decorators, typename T>
     inline static typename EnableIf<
-      HasDecorator<decorators, AS_RAW>::value>::type
+      HasDecorator<decorators, AS_RAW>::value && CanHardwireRaw<decorators>::value>::type
     store(void* addr, T value) {
       typedef RawAccessBarrier<decorators & RAW_DECORATOR_MASK> Raw;
-      if (can_hardwire_raw<decorators>()) {
-        if (HasDecorator<decorators, INTERNAL_VALUE_IS_OOP>::value) {
-          Raw::oop_store(addr, value);
-        } else {
-          Raw::store(addr, value);
-        }
-      } else if (UseCompressedOops) {
+      if (HasDecorator<decorators, INTERNAL_VALUE_IS_OOP>::value) {
+        Raw::oop_store(addr, value);
+      } else {
+        Raw::store(addr, value);
+      }
+    }
+
+    template <DecoratorSet decorators, typename T>
+    inline static typename EnableIf<
+      HasDecorator<decorators, AS_RAW>::value && !CanHardwireRaw<decorators>::value>::type
+    store(void* addr, T value) {
+      if (UseCompressedOops) {
         const DecoratorSet expanded_decorators = decorators | convert_compressed_oops;
         PreRuntimeDispatch::store<expanded_decorators>(addr, value);
       } else {
@@ -558,16 +564,21 @@
 
     template <DecoratorSet decorators, typename T>
     inline static typename EnableIf<
-      HasDecorator<decorators, AS_RAW>::value, T>::type
+      HasDecorator<decorators, AS_RAW>::value && CanHardwireRaw<decorators>::value, T>::type
     load(void* addr) {
       typedef RawAccessBarrier<decorators & RAW_DECORATOR_MASK> Raw;
-      if (can_hardwire_raw<decorators>()) {
-        if (HasDecorator<decorators, INTERNAL_VALUE_IS_OOP>::value) {
-          return Raw::template oop_load<T>(addr);
-        } else {
-          return Raw::template load<T>(addr);
-        }
-      } else if (UseCompressedOops) {
+      if (HasDecorator<decorators, INTERNAL_VALUE_IS_OOP>::value) {
+        return Raw::template oop_load<T>(addr);
+      } else {
+        return Raw::template load<T>(addr);
+      }
+    }
+
+    template <DecoratorSet decorators, typename T>
+    inline static typename EnableIf<
+      HasDecorator<decorators, AS_RAW>::value && !CanHardwireRaw<decorators>::value, T>::type
+    load(void* addr) {
+      if (UseCompressedOops) {
         const DecoratorSet expanded_decorators = decorators | convert_compressed_oops;
         return PreRuntimeDispatch::load<expanded_decorators, T>(addr);
       } else {
@@ -609,16 +620,21 @@
 
     template <DecoratorSet decorators, typename T>
     inline static typename EnableIf<
-      HasDecorator<decorators, AS_RAW>::value, T>::type
+      HasDecorator<decorators, AS_RAW>::value && CanHardwireRaw<decorators>::value, T>::type
     atomic_cmpxchg(T new_value, void* addr, T compare_value) {
       typedef RawAccessBarrier<decorators & RAW_DECORATOR_MASK> Raw;
-      if (can_hardwire_raw<decorators>()) {
-        if (HasDecorator<decorators, INTERNAL_VALUE_IS_OOP>::value) {
-          return Raw::oop_atomic_cmpxchg(new_value, addr, compare_value);
-        } else {
-          return Raw::atomic_cmpxchg(new_value, addr, compare_value);
-        }
-      } else if (UseCompressedOops) {
+      if (HasDecorator<decorators, INTERNAL_VALUE_IS_OOP>::value) {
+        return Raw::oop_atomic_cmpxchg(new_value, addr, compare_value);
+      } else {
+        return Raw::atomic_cmpxchg(new_value, addr, compare_value);
+      }
+    }
+
+    template <DecoratorSet decorators, typename T>
+    inline static typename EnableIf<
+      HasDecorator<decorators, AS_RAW>::value && !CanHardwireRaw<decorators>::value, T>::type
+    atomic_cmpxchg(T new_value, void* addr, T compare_value) {
+      if (UseCompressedOops) {
         const DecoratorSet expanded_decorators = decorators | convert_compressed_oops;
         return PreRuntimeDispatch::atomic_cmpxchg<expanded_decorators>(new_value, addr, compare_value);
       } else {
@@ -661,16 +677,21 @@
 
     template <DecoratorSet decorators, typename T>
     inline static typename EnableIf<
-      HasDecorator<decorators, AS_RAW>::value, T>::type
+      HasDecorator<decorators, AS_RAW>::value && CanHardwireRaw<decorators>::value, T>::type
     atomic_xchg(T new_value, void* addr) {
       typedef RawAccessBarrier<decorators & RAW_DECORATOR_MASK> Raw;
-      if (can_hardwire_raw<decorators>()) {
-        if (HasDecorator<decorators, INTERNAL_VALUE_IS_OOP>::value) {
-          return Raw::oop_atomic_xchg(new_value, addr);
-        } else {
-          return Raw::atomic_xchg(new_value, addr);
-        }
-      } else if (UseCompressedOops) {
+      if (HasDecorator<decorators, INTERNAL_VALUE_IS_OOP>::value) {
+        return Raw::oop_atomic_xchg(new_value, addr);
+      } else {
+        return Raw::atomic_xchg(new_value, addr);
+      }
+    }
+
+    template <DecoratorSet decorators, typename T>
+    inline static typename EnableIf<
+      HasDecorator<decorators, AS_RAW>::value && !CanHardwireRaw<decorators>::value, T>::type
+    atomic_xchg(T new_value, void* addr) {
+      if (UseCompressedOops) {
         const DecoratorSet expanded_decorators = decorators | convert_compressed_oops;
         return PreRuntimeDispatch::atomic_xchg<expanded_decorators>(new_value, addr);
       } else {
@@ -798,6 +819,13 @@
   }
 
   template <DecoratorSet decorators>
+  inline void store_reduce_types(narrowOop* addr, narrowOop value) {
+    const DecoratorSet expanded_decorators = decorators | INTERNAL_CONVERT_COMPRESSED_OOP |
+                                             INTERNAL_RT_USE_COMPRESSED_OOPS;
+    PreRuntimeDispatch::store<expanded_decorators>(addr, value);
+  }
+
+  template <DecoratorSet decorators>
   inline void store_reduce_types(HeapWord* addr, oop value) {
     const DecoratorSet expanded_decorators = decorators | INTERNAL_CONVERT_COMPRESSED_OOP;
     PreRuntimeDispatch::store<expanded_decorators>(addr, value);
@@ -816,7 +844,16 @@
   }
 
   template <DecoratorSet decorators>
-  inline oop atomic_cmpxchg_reduce_types(oop new_value, HeapWord* addr, oop compare_value) {
+  inline narrowOop atomic_cmpxchg_reduce_types(narrowOop new_value, narrowOop* addr, narrowOop compare_value) {
+    const DecoratorSet expanded_decorators = decorators | INTERNAL_CONVERT_COMPRESSED_OOP |
+                                             INTERNAL_RT_USE_COMPRESSED_OOPS;
+    return PreRuntimeDispatch::atomic_cmpxchg<expanded_decorators>(new_value, addr, compare_value);
+  }
+
+  template <DecoratorSet decorators>
+  inline oop atomic_cmpxchg_reduce_types(oop new_value,
+                                         HeapWord* addr,
+                                         oop compare_value) {
     const DecoratorSet expanded_decorators = decorators | INTERNAL_CONVERT_COMPRESSED_OOP;
     return PreRuntimeDispatch::atomic_cmpxchg<expanded_decorators>(new_value, addr, compare_value);
   }
@@ -835,6 +872,13 @@
   }
 
   template <DecoratorSet decorators>
+  inline narrowOop atomic_xchg_reduce_types(narrowOop new_value, narrowOop* addr) {
+    const DecoratorSet expanded_decorators = decorators | INTERNAL_CONVERT_COMPRESSED_OOP |
+                                             INTERNAL_RT_USE_COMPRESSED_OOPS;
+    return PreRuntimeDispatch::atomic_xchg<expanded_decorators>(new_value, addr);
+  }
+
+  template <DecoratorSet decorators>
   inline oop atomic_xchg_reduce_types(oop new_value, HeapWord* addr) {
     const DecoratorSet expanded_decorators = decorators | INTERNAL_CONVERT_COMPRESSED_OOP;
     return PreRuntimeDispatch::atomic_xchg<expanded_decorators>(new_value, addr);
@@ -846,9 +890,10 @@
   }
 
   template <DecoratorSet decorators, typename T>
-  inline oop load_reduce_types(narrowOop* addr) {
-    const DecoratorSet expanded_decorators = decorators | INTERNAL_CONVERT_COMPRESSED_OOP | INTERNAL_RT_USE_COMPRESSED_OOPS;
-    return PreRuntimeDispatch::load<expanded_decorators, oop>(addr);
+  inline typename OopOrNarrowOop<T>::type load_reduce_types(narrowOop* addr) {
+    const DecoratorSet expanded_decorators = decorators | INTERNAL_CONVERT_COMPRESSED_OOP |
+                                             INTERNAL_RT_USE_COMPRESSED_OOPS;
+    return PreRuntimeDispatch::load<expanded_decorators, typename OopOrNarrowOop<T>::type>(addr);
   }
 
   template <DecoratorSet decorators, typename T>
--- a/src/hotspot/share/oops/accessBackend.hpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/share/oops/accessBackend.hpp	Mon Jan 22 16:55:01 2018 +0100
@@ -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
@@ -28,6 +28,7 @@
 #include "metaprogramming/conditional.hpp"
 #include "metaprogramming/enableIf.hpp"
 #include "metaprogramming/integralConstant.hpp"
+#include "metaprogramming/isSame.hpp"
 #include "utilities/debug.hpp"
 #include "utilities/globalDefinitions.hpp"
 
@@ -54,11 +55,11 @@
     BARRIER_CLONE
   };
 
-  template <DecoratorSet decorators>
+  template <DecoratorSet decorators, typename T>
   struct MustConvertCompressedOop: public IntegralConstant<bool,
     HasDecorator<decorators, INTERNAL_VALUE_IS_OOP>::value &&
-    HasDecorator<decorators, INTERNAL_CONVERT_COMPRESSED_OOP>::value &&
-    HasDecorator<decorators, INTERNAL_RT_USE_COMPRESSED_OOPS>::value> {};
+    IsSame<typename HeapOopType<decorators>::type, narrowOop>::value &&
+    IsSame<T, oop>::value> {};
 
   // This metafunction returns an appropriate oop type if the value is oop-like
   // and otherwise returns the same type T.
@@ -172,13 +173,13 @@
   // Only encode if INTERNAL_VALUE_IS_OOP
   template <DecoratorSet idecorators, typename T>
   static inline typename EnableIf<
-    AccessInternal::MustConvertCompressedOop<idecorators>::value,
+    AccessInternal::MustConvertCompressedOop<idecorators, T>::value,
     typename HeapOopType<idecorators>::type>::type
   encode_internal(T value);
 
   template <DecoratorSet idecorators, typename T>
   static inline typename EnableIf<
-    !AccessInternal::MustConvertCompressedOop<idecorators>::value, T>::type
+    !AccessInternal::MustConvertCompressedOop<idecorators, T>::value, T>::type
   encode_internal(T value) {
     return value;
   }
@@ -192,12 +193,12 @@
   // Only decode if INTERNAL_VALUE_IS_OOP
   template <DecoratorSet idecorators, typename T>
   static inline typename EnableIf<
-    AccessInternal::MustConvertCompressedOop<idecorators>::value, T>::type
+    AccessInternal::MustConvertCompressedOop<idecorators, T>::value, T>::type
   decode_internal(typename HeapOopType<idecorators>::type value);
 
   template <DecoratorSet idecorators, typename T>
   static inline typename EnableIf<
-    !AccessInternal::MustConvertCompressedOop<idecorators>::value, T>::type
+    !AccessInternal::MustConvertCompressedOop<idecorators, T>::value, T>::type
   decode_internal(T value) {
     return value;
   }
--- a/src/hotspot/share/oops/accessBackend.inline.hpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/share/oops/accessBackend.inline.hpp	Mon Jan 22 16:55:01 2018 +0100
@@ -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
@@ -32,7 +32,7 @@
 template <DecoratorSet decorators>
 template <DecoratorSet idecorators, typename T>
 inline typename EnableIf<
-  AccessInternal::MustConvertCompressedOop<idecorators>::value, T>::type
+  AccessInternal::MustConvertCompressedOop<idecorators, T>::value, T>::type
 RawAccessBarrier<decorators>::decode_internal(typename HeapOopType<idecorators>::type value) {
   if (HasDecorator<decorators, OOP_NOT_NULL>::value) {
     return oopDesc::decode_heap_oop_not_null(value);
@@ -44,7 +44,7 @@
 template <DecoratorSet decorators>
 template <DecoratorSet idecorators, typename T>
 inline typename EnableIf<
-  AccessInternal::MustConvertCompressedOop<idecorators>::value,
+  AccessInternal::MustConvertCompressedOop<idecorators, T>::value,
   typename HeapOopType<idecorators>::type>::type
 RawAccessBarrier<decorators>::encode_internal(T value) {
   if (HasDecorator<decorators, OOP_NOT_NULL>::value) {
--- a/src/hotspot/share/oops/instanceKlass.cpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/share/oops/instanceKlass.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -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
@@ -2265,7 +2265,8 @@
 }
 
 address InstanceKlass::static_field_addr(int offset) {
-  return (address)(offset + InstanceMirrorKlass::offset_of_static_fields() + cast_from_oop<intptr_t>(java_mirror()));
+  assert(offset >= InstanceMirrorKlass::offset_of_static_fields(), "has already been adjusted");
+  return (address)(offset + cast_from_oop<intptr_t>(java_mirror()));
 }
 
 
@@ -3421,6 +3422,15 @@
   }
 }
 
+oop InstanceKlass::klass_holder_phantom() {
+  oop* addr;
+  if (is_anonymous()) {
+    addr = _java_mirror.ptr_raw();
+  } else {
+    addr = &class_loader_data()->_class_loader;
+  }
+  return RootAccess<IN_CONCURRENT_ROOT | ON_PHANTOM_OOP_REF>::oop_load(addr);
+}
 
 #ifdef ASSERT
 void InstanceKlass::set_init_state(ClassState state) {
--- a/src/hotspot/share/oops/instanceKlass.hpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/share/oops/instanceKlass.hpp	Mon Jan 22 16:55:01 2018 +0100
@@ -645,6 +645,11 @@
     return is_anonymous() ? java_mirror() : class_loader();
   }
 
+  // Load the klass_holder as a phantom. This is useful when a weak Klass
+  // pointer has been "peeked" and then must be kept alive before it may
+  // be used safely.
+  oop klass_holder_phantom();
+
   bool is_contended() const                {
     return (_misc_flags & _misc_is_contended) != 0;
   }
--- a/src/hotspot/share/oops/oop.hpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/share/oops/oop.hpp	Mon Jan 22 16:55:01 2018 +0100
@@ -28,6 +28,7 @@
 #include "gc/shared/specialized_oop_closures.hpp"
 #include "memory/iterator.hpp"
 #include "memory/memRegion.hpp"
+#include "oops/access.hpp"
 #include "oops/metadata.hpp"
 #include "utilities/macros.hpp"
 
@@ -178,6 +179,8 @@
   static inline void encode_store_heap_oop(oop* p, oop v);
 
   // Access to fields in a instanceOop through these methods.
+  template <DecoratorSet decorator>
+  oop obj_field_access(int offset) const;
   oop obj_field(int offset) const;
   void obj_field_put(int offset, oop value);
   void obj_field_put_raw(int offset, oop value);
--- a/src/hotspot/share/oops/oop.inline.hpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/share/oops/oop.inline.hpp	Mon Jan 22 16:55:01 2018 +0100
@@ -326,7 +326,10 @@
   *p = encode_heap_oop(v);
 }
 
+template <DecoratorSet decorators>
+inline oop  oopDesc::obj_field_access(int offset) const             { return HeapAccess<decorators>::oop_load_at(as_oop(), offset); }
 inline oop  oopDesc::obj_field(int offset) const                    { return HeapAccess<>::oop_load_at(as_oop(), offset);  }
+
 inline void oopDesc::obj_field_put(int offset, oop value)           { HeapAccess<>::oop_store_at(as_oop(), offset, value); }
 
 inline jbyte oopDesc::byte_field(int offset) const                  { return HeapAccess<>::load_at(as_oop(), offset);  }
--- a/src/hotspot/share/prims/jvmtiTagMap.cpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/share/prims/jvmtiTagMap.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -30,6 +30,7 @@
 #include "code/codeCache.hpp"
 #include "jvmtifiles/jvmtiEnv.hpp"
 #include "memory/resourceArea.hpp"
+#include "oops/access.inline.hpp"
 #include "oops/instanceMirrorKlass.hpp"
 #include "oops/objArrayKlass.hpp"
 #include "oops/objArrayOop.inline.hpp"
@@ -52,10 +53,6 @@
 #include "runtime/vm_operations.hpp"
 #include "services/serviceUtil.hpp"
 #include "utilities/macros.hpp"
-#if INCLUDE_ALL_GCS
-#include "gc/g1/g1SATBCardTableModRefBS.hpp"
-#include "gc/parallel/parallelScavengeHeap.hpp"
-#endif // INCLUDE_ALL_GCS
 
 // JvmtiTagHashmapEntry
 //
@@ -78,22 +75,31 @@
   }
 
   // constructor
-  JvmtiTagHashmapEntry(oop object, jlong tag)         { init(object, tag); }
+  JvmtiTagHashmapEntry(oop object, jlong tag) { init(object, tag); }
 
  public:
 
   // accessor methods
-  inline oop object() const                           { return _object; }
-  inline oop* object_addr()                           { return &_object; }
-  inline jlong tag() const                            { return _tag; }
+  inline oop* object_addr() { return &_object; }
+  inline oop object()       { return RootAccess<ON_PHANTOM_OOP_REF>::oop_load(object_addr()); }
+  // Peek at the object without keeping it alive. The returned object must be
+  // kept alive using a normal access if it leaks out of a thread transition from VM.
+  inline oop object_peek()  {
+    return RootAccess<ON_PHANTOM_OOP_REF | AS_NO_KEEPALIVE>::oop_load(object_addr());
+  }
+  inline jlong tag() const  { return _tag; }
 
   inline void set_tag(jlong tag) {
     assert(tag != 0, "can't be zero");
     _tag = tag;
   }
 
-  inline JvmtiTagHashmapEntry* next() const             { return _next; }
-  inline void set_next(JvmtiTagHashmapEntry* next)      { _next = next; }
+  inline bool equals(oop object) {
+    return object == object_peek();
+  }
+
+  inline JvmtiTagHashmapEntry* next() const        { return _next; }
+  inline void set_next(JvmtiTagHashmapEntry* next) { _next = next; }
 };
 
 
@@ -211,7 +217,7 @@
       JvmtiTagHashmapEntry* entry = _table[i];
       while (entry != NULL) {
         JvmtiTagHashmapEntry* next = entry->next();
-        oop key = entry->object();
+        oop key = entry->object_peek();
         assert(key != NULL, "jni weak reference cleared!!");
         unsigned int h = hash(key, new_size);
         JvmtiTagHashmapEntry* anchor = new_table[h];
@@ -304,7 +310,7 @@
     unsigned int h = hash(key);
     JvmtiTagHashmapEntry* entry = _table[h];
     while (entry != NULL) {
-      if (entry->object() == key) {
+      if (entry->equals(key)) {
          return entry;
       }
       entry = entry->next();
@@ -345,7 +351,7 @@
     JvmtiTagHashmapEntry* entry = _table[h];
     JvmtiTagHashmapEntry* prev = NULL;
     while (entry != NULL) {
-      if (key == entry->object()) {
+      if (entry->equals(key)) {
         break;
       }
       prev = entry;
@@ -1535,16 +1541,12 @@
   void do_entry(JvmtiTagHashmapEntry* entry) {
     for (int i=0; i<_tag_count; i++) {
       if (_tags[i] == entry->tag()) {
+        // The reference in this tag map could be the only (implicitly weak)
+        // reference to that object. If we hand it out, we need to keep it live wrt
+        // SATB marking similar to other j.l.ref.Reference referents. This is
+        // achieved by using a phantom load in the object() accessor.
         oop o = entry->object();
         assert(o != NULL && Universe::heap()->is_in_reserved(o), "sanity check");
-#if INCLUDE_ALL_GCS
-        if (UseG1GC) {
-          // The reference in this tag map could be the only (implicitly weak)
-          // reference to that object. If we hand it out, we need to keep it live wrt
-          // SATB marking similar to other j.l.ref.Reference referents.
-          G1SATBCardTableModRefBS::enqueue(o);
-        }
-#endif
         jobject ref = JNIHandles::make_local(JavaThread::current(), o);
         _object_results->append(ref);
         _tag_results->append((uint64_t)entry->tag());
@@ -3363,10 +3365,8 @@
     while (entry != NULL) {
       JvmtiTagHashmapEntry* next = entry->next();
 
-      oop* obj = entry->object_addr();
-
       // has object been GC'ed
-      if (!is_alive->do_object_b(entry->object())) {
+      if (!is_alive->do_object_b(entry->object_peek())) {
         // grab the tag
         jlong tag = entry->tag();
         guarantee(tag != 0, "checking");
@@ -3384,7 +3384,7 @@
         ++freed;
       } else {
         f->do_oop(entry->object_addr());
-        oop new_oop = entry->object();
+        oop new_oop = entry->object_peek();
 
         // if the object has moved then re-hash it and move its
         // entry to its new location.
@@ -3418,7 +3418,7 @@
   // Re-add all the entries which were kept aside
   while (delayed_add != NULL) {
     JvmtiTagHashmapEntry* next = delayed_add->next();
-    unsigned int pos = JvmtiTagHashmap::hash(delayed_add->object(), size);
+    unsigned int pos = JvmtiTagHashmap::hash(delayed_add->object_peek(), size);
     delayed_add->set_next(table[pos]);
     table[pos] = delayed_add;
     delayed_add = next;
--- a/src/hotspot/share/prims/resolvedMethodTable.cpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/share/prims/resolvedMethodTable.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -25,6 +25,7 @@
 #include "precompiled.hpp"
 #include "gc/shared/gcLocker.hpp"
 #include "memory/allocation.hpp"
+#include "oops/access.inline.hpp"
 #include "oops/oop.inline.hpp"
 #include "oops/method.hpp"
 #include "oops/symbol.hpp"
@@ -33,24 +34,39 @@
 #include "runtime/mutexLocker.hpp"
 #include "utilities/hashtable.inline.hpp"
 #include "utilities/macros.hpp"
-#if INCLUDE_ALL_GCS
-#include "gc/g1/g1SATBCardTableModRefBS.hpp"
-#endif
 
 
+oop ResolvedMethodEntry::object() {
+  return RootAccess<ON_PHANTOM_OOP_REF>::oop_load(literal_addr());
+}
+
+oop ResolvedMethodEntry::object_no_keepalive() {
+  // The AS_NO_KEEPALIVE peeks at the oop without keeping it alive.
+  // This is dangerous in general but is okay if the loaded oop does
+  // not leak out past a thread transition where a safepoint can happen.
+  // A subsequent oop_load without AS_NO_KEEPALIVE (the object() accessor)
+  // keeps the oop alive before doing so.
+  return RootAccess<ON_PHANTOM_OOP_REF | AS_NO_KEEPALIVE>::oop_load(literal_addr());
+}
+
 ResolvedMethodTable::ResolvedMethodTable()
   : Hashtable<oop, mtClass>(_table_size, sizeof(ResolvedMethodEntry)) { }
 
 oop ResolvedMethodTable::lookup(int index, unsigned int hash, Method* method) {
   for (ResolvedMethodEntry* p = bucket(index); p != NULL; p = p->next()) {
     if (p->hash() == hash) {
-      oop target = p->literal();
+
+      // Peek the object to check if it is the right target.
+      oop target = p->object_no_keepalive();
+
       // The method is in the table as a target already
       if (java_lang_invoke_ResolvedMethodName::vmtarget(target) == method) {
         ResourceMark rm;
         log_debug(membername, table) ("ResolvedMethod entry found for %s index %d",
                                        method->name_and_sig_as_C_string(), index);
-        return target;
+        // The object() accessor makes sure the target object is kept alive before
+        // leaking out.
+        return p->object();
       }
     }
   }
@@ -70,18 +86,6 @@
   return lookup(index, hash, method);
 }
 
-// Tell the GC that this oop was looked up in the table
-static void ensure_oop_alive(oop mname) {
-  // A lookup in the ResolvedMethodTable could return an object that was previously
-  // considered dead. The SATB part of G1 needs to get notified about this
-  // potential resurrection, otherwise the marking might not find the object.
-#if INCLUDE_ALL_GCS
-  if (UseG1GC && mname != NULL) {
-    G1SATBCardTableModRefBS::enqueue(mname);
-  }
-#endif
-}
-
 oop ResolvedMethodTable::basic_add(Method* method, oop rmethod_name) {
   assert_locked_or_safepoint(ResolvedMethodTable_lock);
 
@@ -91,7 +95,6 @@
   // One was added while aquiring the lock
   oop entry = lookup(index, hash, method);
   if (entry != NULL) {
-    ensure_oop_alive(entry);
     return entry;
   }
 
@@ -100,14 +103,13 @@
   ResourceMark rm;
   log_debug(membername, table) ("ResolvedMethod entry added for %s index %d",
                                  method->name_and_sig_as_C_string(), index);
-  return p->literal();
+  return rmethod_name;
 }
 
 ResolvedMethodTable* ResolvedMethodTable::_the_table = NULL;
 
 oop ResolvedMethodTable::find_method(Method* method) {
   oop entry = _the_table->lookup(method);
-  ensure_oop_alive(entry);
   return entry;
 }
 
@@ -147,12 +149,12 @@
     ResolvedMethodEntry* entry = _the_table->bucket(i);
     while (entry != NULL) {
       _oops_counted++;
-      if (is_alive->do_object_b(entry->literal())) {
+      if (is_alive->do_object_b(entry->object_no_keepalive())) {
         p = entry->next_addr();
       } else {
         _oops_removed++;
         if (log_is_enabled(Debug, membername, table)) {
-          Method* m = (Method*)java_lang_invoke_ResolvedMethodName::vmtarget(entry->literal());
+          Method* m = (Method*)java_lang_invoke_ResolvedMethodName::vmtarget(entry->object_no_keepalive());
           ResourceMark rm;
           log_debug(membername, table) ("ResolvedMethod entry removed for %s index %d",
                                            m->name_and_sig_as_C_string(), i);
@@ -185,7 +187,7 @@
     ResolvedMethodEntry* entry = bucket(i);
     while (entry != NULL) {
       tty->print("%d : ", i);
-      oop rmethod_name = entry->literal();
+      oop rmethod_name = entry->object_no_keepalive();
       rmethod_name->print();
       Method* m = (Method*)java_lang_invoke_ResolvedMethodName::vmtarget(rmethod_name);
       m->print();
@@ -203,8 +205,7 @@
   for (int i = 0; i < _the_table->table_size(); ++i) {
     ResolvedMethodEntry* entry = _the_table->bucket(i);
     while (entry != NULL) {
-
-      oop mem_name = entry->literal();
+      oop mem_name = entry->object_no_keepalive();
       Method* old_method = (Method*)java_lang_invoke_ResolvedMethodName::vmtarget(mem_name);
 
       if (old_method->is_old()) {
--- a/src/hotspot/share/prims/resolvedMethodTable.hpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/share/prims/resolvedMethodTable.hpp	Mon Jan 22 16:55:01 2018 +0100
@@ -44,6 +44,9 @@
     return (ResolvedMethodEntry**)HashtableEntry<oop, mtClass>::next_addr();
   }
 
+  oop object();
+  oop object_no_keepalive();
+
   void print_on(outputStream* st) const;
 };
 
--- a/src/hotspot/share/runtime/arguments.cpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/share/runtime/arguments.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -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
@@ -527,6 +527,7 @@
   { "ConvertSleepToYield",           JDK_Version::jdk(9),      JDK_Version::jdk(10), JDK_Version::jdk(11) },
   { "ConvertYieldToSleep",           JDK_Version::jdk(9),      JDK_Version::jdk(10), JDK_Version::jdk(11) },
   { "MinSleepInterval",              JDK_Version::jdk(9),      JDK_Version::jdk(10), JDK_Version::jdk(11) },
+  { "CheckAssertionStatusDirectives",JDK_Version::undefined(), JDK_Version::jdk(11), JDK_Version::jdk(12) },
   { "PermSize",                      JDK_Version::undefined(), JDK_Version::jdk(8),  JDK_Version::undefined() },
   { "MaxPermSize",                   JDK_Version::undefined(), JDK_Version::jdk(8),  JDK_Version::undefined() },
   { "SharedReadWriteSize",           JDK_Version::undefined(), JDK_Version::jdk(10), JDK_Version::undefined() },
--- a/src/hotspot/share/runtime/globals.hpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/share/runtime/globals.hpp	Mon Jan 22 16:55:01 2018 +0100
@@ -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
@@ -893,9 +893,6 @@
   develop(bool, TraceJavaAssertions, false,                                 \
           "Trace java language assertions")                                 \
                                                                             \
-  notproduct(bool, CheckAssertionStatusDirectives, false,                   \
-          "Temporary - see javaClasses.cpp")                                \
-                                                                            \
   notproduct(bool, PrintMallocFree, false,                                  \
           "Trace calls to C heap malloc/free allocation")                   \
                                                                             \
--- a/src/hotspot/share/runtime/init.cpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/share/runtime/init.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -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
@@ -131,6 +131,7 @@
   InterfaceSupport_init();
   SharedRuntime::generate_stubs();
   universe2_init();  // dependent on codeCache_init and stubRoutines_init1
+  javaClasses_init();// must happen after vtable initialization, before referenceProcessor_init
   referenceProcessor_init();
   jni_handles_init();
 #if INCLUDE_VM_STRUCTS
@@ -150,7 +151,6 @@
   if (!universe_post_init()) {
     return JNI_ERR;
   }
-  javaClasses_init();   // must happen after vtable initialization
   stubRoutines_init2(); // note: StubRoutines need 2-phase init
   MethodHandles::generate_adapters();
 
--- a/src/hotspot/share/runtime/os.hpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/share/runtime/os.hpp	Mon Jan 22 16:55:01 2018 +0100
@@ -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
@@ -778,7 +778,6 @@
   static void* signal(int signal_number, void* handler);
   static void  signal_raise(int signal_number);
   static int   signal_wait();
-  static int   signal_lookup();
   static void* user_handler();
   static void  terminate_signal_thread();
   static int   sigexitnum_pd();
--- a/src/hotspot/share/runtime/vm_operations.hpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/share/runtime/vm_operations.hpp	Mon Jan 22 16:55:01 2018 +0100
@@ -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
@@ -67,9 +67,8 @@
   template(CGC_Operation)                         \
   template(CMS_Initial_Mark)                      \
   template(CMS_Final_Remark)                      \
+  template(G1CollectForAllocation)                \
   template(G1CollectFull)                         \
-  template(G1CollectForAllocation)                \
-  template(G1IncCollectionPause)                  \
   template(HandshakeOneThread)                    \
   template(HandshakeAllThreads)                   \
   template(HandshakeFallback)                     \
--- a/src/hotspot/share/utilities/vmError.cpp	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/hotspot/share/utilities/vmError.cpp	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2017, 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
@@ -243,11 +243,12 @@
           RegisterMap map((JavaThread*)t, false); // No update
           fr = fr.sender(&map);
         } else {
+          // is_first_C_frame() does only simple checks for frame pointer,
+          // it will pass if java compiled code has a pointer in EBP.
+          if (os::is_first_C_frame(&fr)) break;
           fr = os::get_sender_for_C_frame(&fr);
         }
       } else {
-        // is_first_C_frame() does only simple checks for frame pointer,
-        // it will pass if java compiled code has a pointer in EBP.
         if (os::is_first_C_frame(&fr)) break;
         fr = os::get_sender_for_C_frame(&fr);
       }
--- a/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTWindow.m	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTWindow.m	Mon Jan 22 16:55:01 2018 +0100
@@ -954,11 +954,6 @@
     return lastKeyWindow;
 }
 
-- (BOOL)windowShouldZoom:(NSWindow *)window toFrame:(NSRect)newFrame {
-    return !NSEqualSizes(self.nsWindow.frame.size, newFrame.size);
-}
-
-
 @end // AWTWindow
 
 
--- a/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReader.java	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReader.java	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 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
@@ -374,7 +374,10 @@
             // And set current image since we've read it now
             currentImage = 0;
         }
-        if (seekForwardOnly) {
+        // If the image positions list is empty as in the case of a tables-only
+        // stream, then attempting to access the element at index
+        // imagePositions.size() - 1 will cause an IndexOutOfBoundsException.
+        if (seekForwardOnly && !imagePositions.isEmpty()) {
             Long pos = imagePositions.get(imagePositions.size()-1);
             iis.flushBefore(pos.longValue());
         }
@@ -492,6 +495,11 @@
         if (!tablesOnlyChecked) {
             checkTablesOnly();
         }
+        // If the image positions list is empty as in the case of a tables-only
+        // stream, then no image data can be read.
+        if (imagePositions.isEmpty()) {
+            throw new IIOException("No image data present to read");
+        }
         if (imageIndex < imagePositions.size()) {
             iis.seek(imagePositions.get(imageIndex).longValue());
         } else {
--- a/src/java.desktop/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 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
@@ -739,6 +739,17 @@
                     // If chunk type is 'IDAT', we've reached the image data.
                     if (imageStartPosition == -1L) {
                         /*
+                         * The PNG specification mandates that if colorType is
+                         * PNG_COLOR_PALETTE then the PLTE chunk should appear
+                         * before the first IDAT chunk.
+                         */
+                        if (colorType == PNG_COLOR_PALETTE &&
+                            !(metadata.PLTE_present))
+                        {
+                            throw new IIOException("Required PLTE chunk"
+                                    + " missing");
+                        }
+                        /*
                          * PNGs may contain multiple IDAT chunks containing
                          * a portion of image data. We store the position of
                          * the first IDAT chunk and continue with iteration
@@ -986,7 +997,9 @@
         }
 
         int inputBands = inputBandsForColorType[metadata.IHDR_colorType];
-        int bytesPerRow = (inputBands*passWidth*metadata.IHDR_bitDepth + 7)/8;
+        int bitsPerRow = Math.
+                multiplyExact((inputBands * metadata.IHDR_bitDepth), passWidth);
+        int bytesPerRow = (bitsPerRow + 7) / 8;
 
         // Read the image row-by-row
         for (int srcY = 0; srcY < passHeight; srcY++) {
@@ -1037,7 +1050,8 @@
         int bytesPerPixel = (bitDepth == 16) ? 2 : 1;
         bytesPerPixel *= inputBands;
 
-        int bytesPerRow = (inputBands*passWidth*bitDepth + 7)/8;
+        int bitsPerRow = Math.multiplyExact((inputBands * bitDepth), passWidth);
+        int bytesPerRow = (bitsPerRow + 7) / 8;
         int eltsPerRow = (bitDepth == 16) ? bytesPerRow/2 : bytesPerRow;
 
         // If no pixels need updating, just skip the input data
--- a/src/java.desktop/share/classes/java/awt/image/BandedSampleModel.java	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/java.desktop/share/classes/java/awt/image/BandedSampleModel.java	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, 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
@@ -185,7 +185,33 @@
     public DataBuffer createDataBuffer() {
         DataBuffer dataBuffer = null;
 
+        // The minimum size required to store samples of one band
         int size = scanlineStride * height;
+
+        if (numBanks == 1) {
+            /*
+             * The sample model contains a single bank of data buffer. Hence
+             * we need to compute the size required to store samples of all
+             * bands including the respective offsets.
+             */
+            int sizePerBand = size;
+            size += bandOffsets[0];
+            for (int index = 1; index < bandOffsets.length; index++) {
+                size += (bandOffsets[index] - size) + sizePerBand;
+            }
+        } else {
+            /*
+             * The sample model contains multiple banks of data buffer where
+             * each bank would correspond to a particular band. Hence we need
+             * to compute only the additional space required for band offsets.
+             */
+            int maxBandOffset = bandOffsets[0];
+            for (int index = 1; index < bandOffsets.length; index++) {
+                maxBandOffset = Math.max(maxBandOffset, bandOffsets[index]);
+            }
+            size += maxBandOffset;
+        }
+
         switch (dataType) {
         case DataBuffer.TYPE_BYTE:
             dataBuffer = new DataBufferByte(size, numBanks);
--- a/src/java.desktop/share/classes/javax/swing/tree/VariableHeightLayoutCache.java	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/java.desktop/share/classes/javax/swing/tree/VariableHeightLayoutCache.java	Mon Jan 22 16:55:01 2018 +0100
@@ -409,11 +409,10 @@
      */
     public void treeNodesChanged(TreeModelEvent e) {
         if(e != null) {
-            int               changedIndexs[];
-            TreeStateNode     changedNode;
+            int               changedIndexs[]  = e.getChildIndices();
+            TreeStateNode     changedNode = getNodeForPath(
+                    SwingUtilities2.getTreePath(e, getModel()), false, false);
 
-            changedIndexs = e.getChildIndices();
-            changedNode = getNodeForPath(SwingUtilities2.getTreePath(e, getModel()), false, false);
             if(changedNode != null) {
                 Object            changedValue = changedNode.getValue();
 
@@ -421,17 +420,12 @@
                    child indexs that are passed in. */
                 changedNode.updatePreferredSize();
                 if(changedNode.hasBeenExpanded() && changedIndexs != null) {
-                    int                counter;
-                    TreeStateNode      changedChildNode;
-
-                    for(counter = 0; counter < changedIndexs.length;
-                        counter++) {
-                        changedChildNode = (TreeStateNode)changedNode
-                                    .getChildAt(changedIndexs[counter]);
+                    for(int index : changedIndexs) {
+                        TreeStateNode changedChildNode = (TreeStateNode)changedNode
+                                    .getChildAt(index);
                         /* Reset the user object. */
                         changedChildNode.setUserObject
-                                    (treeModel.getChild(changedValue,
-                                                     changedIndexs[counter]));
+                                    (treeModel.getChild(changedValue, index));
                         changedChildNode.updatePreferredSize();
                     }
                 }
@@ -462,34 +456,26 @@
      */
     public void treeNodesInserted(TreeModelEvent e) {
         if(e != null) {
-            int               changedIndexs[];
-            TreeStateNode     changedParentNode;
-
-            changedIndexs = e.getChildIndices();
-            changedParentNode = getNodeForPath(SwingUtilities2.getTreePath(e, getModel()), false, false);
+            int               changedIndexs[] = e.getChildIndices();
+            TreeStateNode     changedParentNode = getNodeForPath(
+                    SwingUtilities2.getTreePath(e, getModel()), false, false);
             /* Only need to update the children if the node has been
                expanded once. */
             // PENDING(scott): make sure childIndexs is sorted!
             if(changedParentNode != null && changedIndexs != null &&
                changedIndexs.length > 0) {
                 if(changedParentNode.hasBeenExpanded()) {
-                    boolean            makeVisible;
-                    int                counter;
-                    Object             changedParent;
-                    TreeStateNode      newNode;
-                    int                oldChildCount = changedParentNode.
-                                          getChildCount();
+                    boolean   makeVisible =((changedParentNode == root &&
+                                            !rootVisible) ||
+                                            (changedParentNode.getRow() != -1 &&
+                                               changedParentNode.isExpanded()));
+                    int  oldChildCount = changedParentNode.getChildCount();
 
-                    changedParent = changedParentNode.getValue();
-                    makeVisible = ((changedParentNode == root &&
-                                    !rootVisible) ||
-                                   (changedParentNode.getRow() != -1 &&
-                                    changedParentNode.isExpanded()));
-                    for(counter = 0;counter < changedIndexs.length;counter++)
+                    for(int index : changedIndexs)
                     {
-                        newNode = this.createNodeAt(changedParentNode,
-                                                    changedIndexs[counter]);
+                        this.createNodeAt(changedParentNode, index);
                     }
+
                     if(oldChildCount == 0) {
                         // Update the size of the parent.
                         changedParentNode.updatePreferredSize();
@@ -643,7 +629,7 @@
                 rebuild(true);
             }
             else if(changedNode != null) {
-                int                              nodeIndex, oldRow;
+                int                              nodeIndex;
                 TreeStateNode                    newNode, parent;
                 boolean                          wasExpanded, wasVisible;
                 int                              newIndex;
@@ -925,24 +911,22 @@
       * row index, the last row index is returned.
       */
     private int getRowContainingYLocation(int location) {
+        final int rows = getRowCount();
+
+        if(rows <= 0)
+            return -1;
         if(isFixedRowHeight()) {
-            if(getRowCount() == 0)
-                return -1;
-            return Math.max(0, Math.min(getRowCount() - 1,
+            return Math.max(0, Math.min(rows - 1,
                                         location / getRowHeight()));
         }
 
-        int                    max, maxY, mid, min, minY;
-        TreeStateNode          node;
+        int max = rows, min = 0, mid = 0;
 
-        if((max = getRowCount()) <= 0)
-            return -1;
-        mid = min = 0;
         while(min < max) {
             mid = (max - min) / 2 + min;
-            node = (TreeStateNode)visibleNodes.elementAt(mid);
-            minY = node.getYOrigin();
-            maxY = minY + node.getPreferredHeight();
+            TreeStateNode node = (TreeStateNode)visibleNodes.elementAt(mid);
+            int minY = node.getYOrigin();
+            int maxY = minY + node.getPreferredHeight();
             if(location < minY) {
                 max = mid - 1;
             }
@@ -954,8 +938,8 @@
         }
         if(min == max) {
             mid = min;
-            if(mid >= getRowCount())
-                mid = getRowCount() - 1;
+            if(mid >= rows)
+                mid = rows - 1;
         }
         return mid;
     }
@@ -1008,9 +992,9 @@
             if(nodeWidth > maxWidth)
                 maxWidth = nodeWidth;
         }
+
         return maxWidth;
     }
-
     /**
       * Responsible for creating a TreeStateNode that will be used
       * to track display information about value.
@@ -1362,17 +1346,11 @@
                                                        isExpanded(),
                                                        boundsBuffer);
 
-            if(bounds == null) {
+            if(bounds == null || bounds.height == 0) {
                 xOrigin = 0;
                 preferredWidth = preferredHeight = 0;
                 updateNodeSizes = true;
-            }
-            else if(bounds.height == 0) {
-                xOrigin = 0;
-                preferredWidth = preferredHeight = 0;
-                updateNodeSizes = true;
-            }
-            else {
+            } else {
                 xOrigin = bounds.x;
                 preferredWidth = bounds.width;
                 if(isFixedRowHeight())
@@ -1477,24 +1455,14 @@
                     Object         realNode = getValue();
                     TreeModel      treeModel = getModel();
                     int            count = treeModel.getChildCount(realNode);
+                    int offset = originalRow == -1 ? -1 : originalRow + 1;
+                    hasBeenExpanded = true;
 
-                    hasBeenExpanded = true;
-                    if(originalRow == -1) {
-                        for (int i = 0; i < count; i++) {
-                            newNode = createNodeForValue(treeModel.getChild
-                                                            (realNode, i));
-                            this.add(newNode);
-                            newNode.updatePreferredSize(-1);
-                        }
-                    }
-                    else {
-                        int offset = originalRow + 1;
-                        for (int i = 0; i < count; i++) {
-                            newNode = createNodeForValue(treeModel.getChild
-                                                       (realNode, i));
-                            this.add(newNode);
-                            newNode.updatePreferredSize(offset);
-                        }
+                    for (int i = 0; i < count; i++) {
+                        newNode = createNodeForValue(treeModel.getChild
+                                                        (realNode, i));
+                        this.add(newNode);
+                        newNode.updatePreferredSize(offset);
                     }
                 }
 
@@ -1502,14 +1470,9 @@
                 Enumeration<TreeNode> cursor = preorderEnumeration();
                 cursor.nextElement(); // don't add me, I'm already in
 
-                int newYOrigin;
+                int newYOrigin = isFixed || (this == root && !isRootVisible()) ?
+                                    0 : getYOrigin() + this.getPreferredHeight();
 
-                if(isFixed)
-                    newYOrigin = 0;
-                else if(this == root && !isRootVisible())
-                    newYOrigin = 0;
-                else
-                    newYOrigin = getYOrigin() + this.getPreferredHeight();
                 TreeStateNode   aNode;
                 if(!isFixed) {
                     while (cursor.hasMoreElements()) {
@@ -1744,14 +1707,10 @@
         protected boolean updateNextIndex() {
             // nextIndex == -1 identifies receiver, make sure is expanded
             // before descend.
-            if(nextIndex == -1 && !parent.isExpanded())
-                return false;
-
-            // Check that it can have kids
-            if(childCount == 0)
-                return false;
-            // Make sure next index not beyond child count.
-            else if(++nextIndex >= childCount)
+            if((nextIndex == -1 && !parent.isExpanded()) ||
+                childCount == 0 || // Check that it can have kids
+                ++nextIndex >= childCount) // Make sure next index not beyond
+                                             // child count.
                 return false;
 
             TreeStateNode       child = (TreeStateNode)parent.
--- a/src/java.desktop/unix/classes/sun/java2d/xr/XRSolidSrcPict.java	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/java.desktop/unix/classes/sun/java2d/xr/XRSolidSrcPict.java	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2014, 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
@@ -47,7 +47,7 @@
 
     public XRSurfaceData prepareSrcPict(int pixelVal) {
         if(pixelVal != curPixVal) {
-            xrCol.setColorValues(pixelVal, false);
+            xrCol.setColorValues(pixelVal, true);
             con.renderRectangle(srcPict.picture, XRUtils.PictOpSrc, xrCol, 0, 0, 1, 1);
             this.curPixVal = pixelVal;
         }
--- a/src/java.security.jgss/share/classes/javax/security/auth/kerberos/KeyImpl.java	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/java.security.jgss/share/classes/javax/security/auth/kerberos/KeyImpl.java	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 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
@@ -138,6 +138,12 @@
         case EncryptedData.ETYPE_AES256_CTS_HMAC_SHA1_96:
             return "aes256-cts-hmac-sha1-96";
 
+        case EncryptedData.ETYPE_AES128_CTS_HMAC_SHA256_128:
+            return "aes128-cts-hmac-sha256-128";
+
+        case EncryptedData.ETYPE_AES256_CTS_HMAC_SHA384_192:
+            return "aes256-cts-hmac-sha384-192";
+
         case EncryptedData.ETYPE_NULL:
             return "none";
 
--- a/src/java.security.jgss/share/classes/sun/security/jgss/krb5/CipherHelper.java	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/java.security.jgss/share/classes/sun/security/jgss/krb5/CipherHelper.java	Mon Jan 22 16:55:01 2018 +0100
@@ -40,6 +40,8 @@
 import java.security.GeneralSecurityException;
 import java.security.NoSuchAlgorithmException;
 import sun.security.krb5.*;
+import sun.security.krb5.internal.crypto.Aes128Sha2;
+import sun.security.krb5.internal.crypto.Aes256Sha2;
 import sun.security.krb5.internal.crypto.Des3;
 import sun.security.krb5.internal.crypto.Aes128;
 import sun.security.krb5.internal.crypto.Aes256;
@@ -101,6 +103,8 @@
 
         case EncryptedData.ETYPE_AES128_CTS_HMAC_SHA1_96:
         case EncryptedData.ETYPE_AES256_CTS_HMAC_SHA1_96:
+        case EncryptedData.ETYPE_AES128_CTS_HMAC_SHA256_128:
+        case EncryptedData.ETYPE_AES256_CTS_HMAC_SHA384_192:
             sgnAlg = -1;
             sealAlg = -1;
             break;
@@ -365,6 +369,33 @@
                 throw ge;
             }
 
+        case EncryptedData.ETYPE_AES128_CTS_HMAC_SHA256_128:
+            try {
+                byte[] answer = Aes128Sha2.calculateChecksum(keybytes, key_usage,
+                        buf, 0, total);
+                return answer;
+            } catch (GeneralSecurityException e) {
+                GSSException ge = new GSSException(GSSException.FAILURE, -1,
+                        "Could not use AES128 signing algorithm - " +
+                                e.getMessage());
+                ge.initCause(e);
+                throw ge;
+            }
+
+        case EncryptedData.ETYPE_AES256_CTS_HMAC_SHA384_192:
+            try {
+                byte[] answer = Aes256Sha2.calculateChecksum(keybytes, key_usage,
+                        buf, 0, total);
+                return answer;
+            } catch (GeneralSecurityException e) {
+                GSSException ge = new GSSException(GSSException.FAILURE, -1,
+                        "Could not use AES256 signing algorithm - " +
+                                e.getMessage());
+                ge.initCause(e);
+                throw ge;
+            }
+
+
         default:
             throw new GSSException(GSSException.FAILURE, -1,
                 "Unsupported encryption type: " + etype);
@@ -517,6 +548,11 @@
         case EncryptedData.ETYPE_AES256_CTS_HMAC_SHA1_96:
             return Aes256.getChecksumLength();
 
+        case EncryptedData.ETYPE_AES128_CTS_HMAC_SHA256_128:
+            return Aes128Sha2.getChecksumLength();
+        case EncryptedData.ETYPE_AES256_CTS_HMAC_SHA384_192:
+            return Aes256Sha2.getChecksumLength();
+
         case EncryptedData.ETYPE_ARCFOUR_HMAC:
             // only first 8 octets of HMAC Sgn_Cksum are used
             return HMAC_CHECKSUM_SIZE;
@@ -574,6 +610,14 @@
                     aes256Decrypt(token, ciphertext, cStart, cLen,
                                 plaintext, pStart, key_usage);
                     break;
+            case EncryptedData.ETYPE_AES128_CTS_HMAC_SHA256_128:
+                    aes128Sha2Decrypt(token, ciphertext, cStart, cLen,
+                            plaintext, pStart, key_usage);
+                    break;
+            case EncryptedData.ETYPE_AES256_CTS_HMAC_SHA384_192:
+                    aes256Sha2Decrypt(token, ciphertext, cStart, cLen,
+                            plaintext, pStart, key_usage);
+                    break;
             default:
                     throw new GSSException(GSSException.FAILURE, -1,
                         "Unsupported etype: " + etype);
@@ -654,6 +698,14 @@
                     aes256Decrypt(token, ciphertext, 0, cLen,
                                 plaintext, pStart, key_usage);
                     break;
+            case EncryptedData.ETYPE_AES128_CTS_HMAC_SHA256_128:
+                    aes128Sha2Decrypt(token, ciphertext, 0, cLen,
+                            plaintext, pStart, key_usage);
+                    break;
+            case EncryptedData.ETYPE_AES256_CTS_HMAC_SHA384_192:
+                    aes256Sha2Decrypt(token, ciphertext, 0, cLen,
+                            plaintext, pStart, key_usage);
+                    break;
             default:
                     throw new GSSException(GSSException.FAILURE, -1,
                         "Unsupported etype: " + etype);
@@ -720,6 +772,12 @@
             case EncryptedData.ETYPE_AES256_CTS_HMAC_SHA1_96:
                 return aes256Encrypt(confounder, tokenHeader,
                             plaintext, start, len, key_usage);
+            case EncryptedData.ETYPE_AES128_CTS_HMAC_SHA256_128:
+                return aes128Sha2Encrypt(confounder, tokenHeader,
+                        plaintext, start, len, key_usage);
+            case EncryptedData.ETYPE_AES256_CTS_HMAC_SHA384_192:
+                return aes256Sha2Encrypt(confounder, tokenHeader,
+                        plaintext, start, len, key_usage);
             default:
                 throw new GSSException(GSSException.FAILURE, -1,
                     "Unsupported etype: " + etype);
@@ -796,6 +854,14 @@
                     ctext = aes256Encrypt(confounder, tokenHeader,
                                 plaintext, pStart, pLen, key_usage);
                     break;
+            case EncryptedData.ETYPE_AES128_CTS_HMAC_SHA256_128:
+                    ctext = aes128Sha2Encrypt(confounder, tokenHeader,
+                            plaintext, pStart, pLen, key_usage);
+                    break;
+            case EncryptedData.ETYPE_AES256_CTS_HMAC_SHA384_192:
+                    ctext = aes256Sha2Encrypt(confounder, tokenHeader,
+                            plaintext, pStart, pLen, key_usage);
+                    break;
             default:
                     throw new GSSException(GSSException.FAILURE, -1,
                         "Unsupported etype: " + etype);
@@ -1317,6 +1383,38 @@
         }
     }
 
+    private byte[] aes128Sha2Encrypt(byte[] confounder, byte[] tokenHeader,
+            byte[] plaintext, int start, int len, int key_usage)
+            throws GSSException {
+
+        // encrypt { AES-plaintext-data | filler | header }
+        // AES-plaintext-data { confounder | plaintext }
+        // WrapToken = { tokenHeader |
+        //      Encrypt (confounder | plaintext | tokenHeader ) | HMAC }
+
+        byte[] all = new byte[confounder.length + len + tokenHeader.length];
+        System.arraycopy(confounder, 0, all, 0, confounder.length);
+        System.arraycopy(plaintext, start, all, confounder.length, len);
+        System.arraycopy(tokenHeader, 0, all, confounder.length+len,
+                tokenHeader.length);
+
+        // Krb5Token.debug("\naes128Sha2Encrypt:" + Krb5Token.getHexBytes(all));
+        try {
+            byte[] answer = Aes128Sha2.encryptRaw(keybytes, key_usage,
+                    ZERO_IV_AES,
+                    all, 0, all.length);
+            // Krb5Token.debug("\naes128Sha2Encrypt encrypted:" +
+            //                  Krb5Token.getHexBytes(answer));
+            return answer;
+        } catch (Exception e) {
+            // GeneralSecurityException, KrbCryptoException
+            GSSException ge = new GSSException(GSSException.FAILURE, -1,
+                    "Could not use Aes128Sha2 Cipher - " + e.getMessage());
+            ge.initCause(e);
+            throw ge;
+        }
+    }
+
     private void aes128Decrypt(WrapToken_v2 token, byte[] ciphertext,
         int cStart, int cLen, byte[] plaintext, int pStart, int key_usage)
         throws GSSException {
@@ -1354,6 +1452,43 @@
         */
     }
 
+    private void aes128Sha2Decrypt(WrapToken_v2 token, byte[] ciphertext,
+            int cStart, int cLen, byte[] plaintext, int pStart, int key_usage)
+            throws GSSException {
+
+        byte[] ptext = null;
+
+        try {
+            ptext = Aes128Sha2.decryptRaw(keybytes, key_usage,
+                    ZERO_IV_AES, ciphertext, cStart, cLen);
+        } catch (GeneralSecurityException e) {
+            GSSException ge = new GSSException(GSSException.FAILURE, -1,
+                    "Could not use AES128Sha2 Cipher - " + e.getMessage());
+            ge.initCause(e);
+            throw ge;
+        }
+
+        /*
+        Krb5Token.debug("\naes128Sha2Decrypt in: " +
+            Krb5Token.getHexBytes(ciphertext, cStart, cLen));
+        Krb5Token.debug("\naes128Sha2Decrypt plain: " +
+            Krb5Token.getHexBytes(ptext));
+        Krb5Token.debug("\naes128Sha2Decrypt ptext: " +
+            Krb5Token.getHexBytes(ptext));
+        */
+
+        // Strip out confounder and token header
+        int len = ptext.length - WrapToken_v2.CONFOUNDER_SIZE -
+                WrapToken_v2.TOKEN_HEADER_SIZE;
+        System.arraycopy(ptext, WrapToken_v2.CONFOUNDER_SIZE,
+                plaintext, pStart, len);
+
+        /*
+        Krb5Token.debug("\naes128Sha2Decrypt plaintext: " +
+            Krb5Token.getHexBytes(plaintext, pStart, len));
+        */
+    }
+
     private byte[] aes256Encrypt(byte[] confounder, byte[] tokenHeader,
         byte[] plaintext, int start, int len, int key_usage)
         throws GSSException {
@@ -1386,6 +1521,38 @@
         }
     }
 
+    private byte[] aes256Sha2Encrypt(byte[] confounder, byte[] tokenHeader,
+            byte[] plaintext, int start, int len, int key_usage)
+            throws GSSException {
+
+        // encrypt { AES-plaintext-data | filler | header }
+        // AES-plaintext-data { confounder | plaintext }
+        // WrapToken = { tokenHeader |
+        //       Encrypt (confounder | plaintext | tokenHeader ) | HMAC }
+
+        byte[] all = new byte[confounder.length + len + tokenHeader.length];
+        System.arraycopy(confounder, 0, all, 0, confounder.length);
+        System.arraycopy(plaintext, start, all, confounder.length, len);
+        System.arraycopy(tokenHeader, 0, all, confounder.length+len,
+                tokenHeader.length);
+
+        // Krb5Token.debug("\naes256Sha2Encrypt:" + Krb5Token.getHexBytes(all));
+
+        try {
+            byte[] answer = Aes256Sha2.encryptRaw(keybytes, key_usage,
+                    ZERO_IV_AES, all, 0, all.length);
+            // Krb5Token.debug("\naes256Sha2Encrypt encrypted:" +
+            //  Krb5Token.getHexBytes(answer));
+            return answer;
+        } catch (Exception e) {
+            // GeneralSecurityException, KrbCryptoException
+            GSSException ge = new GSSException(GSSException.FAILURE, -1,
+                    "Could not use Aes256Sha2 Cipher - " + e.getMessage());
+            ge.initCause(e);
+            throw ge;
+        }
+    }
+
     private void aes256Decrypt(WrapToken_v2 token, byte[] ciphertext,
         int cStart, int cLen, byte[] plaintext, int pStart, int key_usage)
         throws GSSException {
@@ -1423,6 +1590,43 @@
 
     }
 
+    private void aes256Sha2Decrypt(WrapToken_v2 token, byte[] ciphertext,
+            int cStart, int cLen, byte[] plaintext, int pStart, int key_usage)
+            throws GSSException {
+
+        byte[] ptext;
+        try {
+            ptext = Aes256Sha2.decryptRaw(keybytes, key_usage,
+                    ZERO_IV_AES, ciphertext, cStart, cLen);
+        } catch (GeneralSecurityException e) {
+            GSSException ge = new GSSException(GSSException.FAILURE, -1,
+                    "Could not use AES256Sha2 Cipher - " + e.getMessage());
+            ge.initCause(e);
+            throw ge;
+        }
+
+        /*
+        Krb5Token.debug("\naes256Sha2Decrypt in: " +
+            Krb5Token.getHexBytes(ciphertext, cStart, cLen));
+        Krb5Token.debug("\naes256Sha2Decrypt plain: " +
+            Krb5Token.getHexBytes(ptext));
+        Krb5Token.debug("\naes256Sha2Decrypt ptext: " +
+            Krb5Token.getHexBytes(ptext));
+        */
+
+        // Strip out confounder and token header
+        int len = ptext.length - WrapToken_v2.CONFOUNDER_SIZE -
+                WrapToken_v2.TOKEN_HEADER_SIZE;
+        System.arraycopy(ptext, WrapToken_v2.CONFOUNDER_SIZE,
+                plaintext, pStart, len);
+
+        /*
+        Krb5Token.debug("\naes256Sha2Decrypt plaintext: " +
+            Krb5Token.getHexBytes(plaintext, pStart, len));
+        */
+
+    }
+
     /**
      * This class provides a truncated inputstream needed by WrapToken. The
      * truncated inputstream is passed to CipherInputStream. It prevents
--- a/src/java.security.jgss/share/classes/sun/security/krb5/Checksum.java	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/java.security.jgss/share/classes/sun/security/krb5/Checksum.java	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 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
@@ -66,6 +66,10 @@
     public static final int CKSUMTYPE_HMAC_SHA1_96_AES128 = 15;        // 96
     public static final int CKSUMTYPE_HMAC_SHA1_96_AES256 = 16;        // 96
 
+    // rfc8009
+    public static final int CKSUMTYPE_HMAC_SHA256_128_AES128 = 19;        // 96
+    public static final int CKSUMTYPE_HMAC_SHA384_192_AES256 = 20;        // 96
+
     // draft-brezak-win2k-krb-rc4-hmac-04.txt
     public static final int CKSUMTYPE_HMAC_MD5_ARCFOUR = -138;
 
--- a/src/java.security.jgss/share/classes/sun/security/krb5/Config.java	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/java.security.jgss/share/classes/sun/security/krb5/Config.java	Mon Jan 22 16:55:01 2018 +0100
@@ -1030,11 +1030,19 @@
         } else if (input.startsWith("a") || (input.startsWith("A"))) {
             // AES
             if (input.equalsIgnoreCase("aes128-cts") ||
-                input.equalsIgnoreCase("aes128-cts-hmac-sha1-96")) {
+                    input.equalsIgnoreCase("aes128-sha1") ||
+                    input.equalsIgnoreCase("aes128-cts-hmac-sha1-96")) {
                 result = EncryptedData.ETYPE_AES128_CTS_HMAC_SHA1_96;
             } else if (input.equalsIgnoreCase("aes256-cts") ||
-                input.equalsIgnoreCase("aes256-cts-hmac-sha1-96")) {
+                    input.equalsIgnoreCase("aes256-sha1") ||
+                    input.equalsIgnoreCase("aes256-cts-hmac-sha1-96")) {
                 result = EncryptedData.ETYPE_AES256_CTS_HMAC_SHA1_96;
+            } else if (input.equalsIgnoreCase("aes128-sha2") ||
+                    input.equalsIgnoreCase("aes128-cts-hmac-sha256-128")) {
+                result = EncryptedData.ETYPE_AES128_CTS_HMAC_SHA256_128;
+            } else if (input.equalsIgnoreCase("aes256-sha2") ||
+                    input.equalsIgnoreCase("aes256-cts-hmac-sha384-192")) {
+                result = EncryptedData.ETYPE_AES256_CTS_HMAC_SHA384_192;
             // ARCFOUR-HMAC
             } else if (input.equalsIgnoreCase("arcfour-hmac") ||
                    input.equalsIgnoreCase("arcfour-hmac-md5")) {
@@ -1057,6 +1065,10 @@
             result = Checksum.CKSUMTYPE_HMAC_SHA1_96_AES128;
         } else if (input.equalsIgnoreCase("hmac-sha1-96-aes256")) {
             result = Checksum.CKSUMTYPE_HMAC_SHA1_96_AES256;
+        } else if (input.equalsIgnoreCase("hmac-sha256-128-aes128")) {
+            result = Checksum.CKSUMTYPE_HMAC_SHA256_128_AES128;
+        } else if (input.equalsIgnoreCase("hmac-sha384-192-aes256")) {
+            result = Checksum.CKSUMTYPE_HMAC_SHA384_192_AES256;
         } else if (input.equalsIgnoreCase("hmac-md5-rc4") ||
                 input.equalsIgnoreCase("hmac-md5-arcfour") ||
                 input.equalsIgnoreCase("hmac-md5-enc")) {
--- a/src/java.security.jgss/share/classes/sun/security/krb5/EncryptedData.java	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/java.security.jgss/share/classes/sun/security/krb5/EncryptedData.java	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 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
@@ -79,6 +79,12 @@
     public static final int
          ETYPE_AES256_CTS_HMAC_SHA1_96 = 18; // 16      0           16
 
+    // rfc8009
+    public static final int
+        ETYPE_AES128_CTS_HMAC_SHA256_128 = 19; // 16      0           16
+    public static final int
+        ETYPE_AES256_CTS_HMAC_SHA384_192 = 20; // 16      0           16
+
     /* used by self */
     private EncryptedData() {
     }
--- a/src/java.security.jgss/share/classes/sun/security/krb5/EncryptionKey.java	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/java.security.jgss/share/classes/sun/security/krb5/EncryptionKey.java	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 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
@@ -252,6 +252,12 @@
                 case EncryptedData.ETYPE_AES256_CTS_HMAC_SHA1_96:
                         return Aes256.stringToKey(password, salt, s2kparams);
 
+                case EncryptedData.ETYPE_AES128_CTS_HMAC_SHA256_128:
+                        return Aes128Sha2.stringToKey(password, salt, s2kparams);
+
+                case EncryptedData.ETYPE_AES256_CTS_HMAC_SHA384_192:
+                    return Aes256Sha2.stringToKey(password, salt, s2kparams);
+
                 default:
                         throw new IllegalArgumentException("encryption type " +
                         EType.toString(keyType) + " not supported");
@@ -293,6 +299,15 @@
                 throw new IllegalArgumentException("Algorithm " + algorithm +
                         " not enabled");
             }
+        } else if (algorithm.equalsIgnoreCase("aes128-cts-hmac-sha256-128")) {
+            keyType = EncryptedData.ETYPE_AES128_CTS_HMAC_SHA256_128;
+        } else if (algorithm.equalsIgnoreCase("aes256-cts-hmac-sha384-192")) {
+            keyType = EncryptedData.ETYPE_AES256_CTS_HMAC_SHA384_192;
+            // validate if AES256 is enabled
+            if (!EType.isSupported(keyType)) {
+                throw new IllegalArgumentException("Algorithm " + algorithm +
+                        " not enabled");
+            }
         } else {
             throw new IllegalArgumentException("Algorithm " + algorithm +
                 " not supported");
--- a/src/java.security.jgss/share/classes/sun/security/krb5/KrbTgsReq.java	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/java.security.jgss/share/classes/sun/security/krb5/KrbTgsReq.java	Mon Jan 22 16:55:01 2018 +0100
@@ -356,6 +356,8 @@
         case Checksum.CKSUMTYPE_HMAC_MD5_ARCFOUR:
         case Checksum.CKSUMTYPE_HMAC_SHA1_96_AES128:
         case Checksum.CKSUMTYPE_HMAC_SHA1_96_AES256:
+        case Checksum.CKSUMTYPE_HMAC_SHA256_128_AES128:
+        case Checksum.CKSUMTYPE_HMAC_SHA384_192_AES256:
             cksum = new Checksum(Checksum.CKSUMTYPE_DEFAULT, temp, key,
                 KeyUsage.KU_PA_TGS_REQ_CKSUM);
             break;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.security.jgss/share/classes/sun/security/krb5/internal/crypto/Aes128CtsHmacSha2EType.java	Mon Jan 22 16:55:01 2018 +0100
@@ -0,0 +1,112 @@
+/*
+ * Copyright (c) 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.
+ */
+
+package sun.security.krb5.internal.crypto;
+
+import sun.security.krb5.KrbCryptoException;
+import sun.security.krb5.internal.*;
+import java.security.GeneralSecurityException;
+import sun.security.krb5.EncryptedData;
+import sun.security.krb5.Checksum;
+
+/*
+ * This class encapsulates the encryption type for aes128-cts-hmac-sha256-128
+ */
+
+public final class Aes128CtsHmacSha2EType extends EType {
+
+    public int eType() {
+        return EncryptedData.ETYPE_AES128_CTS_HMAC_SHA256_128;
+    }
+
+    public int minimumPadSize() {
+        return 0;
+    }
+
+    public int confounderSize() {
+        return blockSize();
+    }
+
+    public int checksumType() {
+        return Checksum.CKSUMTYPE_HMAC_SHA256_128_AES128;
+    }
+
+    public int checksumSize() {
+        return Aes128Sha2.getChecksumLength();
+    }
+
+    public int blockSize() {
+        return 16;
+    }
+
+    public int keyType() {
+        return Krb5.KEYTYPE_AES;
+    }
+
+    public int keySize() {
+        return 16; // bytes
+    }
+
+    public byte[] encrypt(byte[] data, byte[] key, int usage)
+        throws KrbCryptoException {
+        byte[] ivec = new byte[blockSize()];
+        return encrypt(data, key, ivec, usage);
+    }
+
+    public byte[] encrypt(byte[] data, byte[] key, byte[] ivec, int usage)
+        throws KrbCryptoException {
+        try {
+            return Aes128Sha2.encrypt(key, usage, ivec, data, 0, data.length);
+        } catch (GeneralSecurityException e) {
+            KrbCryptoException ke = new KrbCryptoException(e.getMessage());
+            ke.initCause(e);
+            throw ke;
+        }
+    }
+
+    public byte[] decrypt(byte[] cipher, byte[] key, int usage)
+        throws KrbApErrException, KrbCryptoException {
+        byte[] ivec = new byte[blockSize()];
+        return decrypt(cipher, key, ivec, usage);
+    }
+
+    public byte[] decrypt(byte[] cipher, byte[] key, byte[] ivec, int usage)
+        throws KrbApErrException, KrbCryptoException {
+        try {
+            return Aes128Sha2.decrypt(key, usage, ivec, cipher, 0, cipher.length);
+        } catch (GeneralSecurityException e) {
+            KrbCryptoException ke = new KrbCryptoException(e.getMessage());
+            ke.initCause(e);
+            throw ke;
+        }
+    }
+
+    // Override default, because our decrypted data does not return confounder
+    // Should eventually get rid of EType.decryptedData and
+    // EncryptedData.decryptedData altogether
+    public byte[] decryptedData(byte[] data) {
+        return data;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.security.jgss/share/classes/sun/security/krb5/internal/crypto/Aes128Sha2.java	Mon Jan 22 16:55:01 2018 +0100
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 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.
+ */
+
+package sun.security.krb5.internal.crypto;
+
+import sun.security.krb5.internal.crypto.dk.AesSha2DkCrypto;
+import sun.security.krb5.KrbCryptoException;
+import java.security.GeneralSecurityException;
+
+/**
+ * Class with static methods for doing aes128-cts-hmac-sha256-128 operations.
+ */
+
+public class Aes128Sha2 {
+    private static final AesSha2DkCrypto CRYPTO = new AesSha2DkCrypto(128);
+
+    private Aes128Sha2() {
+    }
+
+    public static byte[] stringToKey(char[] password, String salt, byte[] params)
+        throws GeneralSecurityException {
+        return CRYPTO.stringToKey(password, salt, params);
+    }
+
+    // in bytes
+    public static int getChecksumLength() {
+        return CRYPTO.getChecksumLength();
+    }
+
+    public static byte[] calculateChecksum(byte[] baseKey, int usage,
+        byte[] input, int start, int len) throws GeneralSecurityException {
+            return CRYPTO.calculateChecksum(baseKey, usage, input, start, len);
+    }
+
+    public static byte[] encrypt(byte[] baseKey, int usage,
+        byte[] ivec, byte[] plaintext, int start, int len)
+        throws GeneralSecurityException, KrbCryptoException {
+            return CRYPTO.encrypt(baseKey, usage, ivec, null /* new_ivec */,
+                plaintext, start, len);
+    }
+
+    /* Encrypt plaintext; do not add confounder, or checksum */
+    public static byte[] encryptRaw(byte[] baseKey, int usage,
+        byte[] ivec, byte[] plaintext, int start, int len)
+        throws GeneralSecurityException, KrbCryptoException {
+        return CRYPTO.encryptRaw(baseKey, usage, ivec, plaintext, start, len);
+    }
+
+    public static byte[] decrypt(byte[] baseKey, int usage, byte[] ivec,
+        byte[] ciphertext, int start, int len)
+        throws GeneralSecurityException {
+        return CRYPTO.decrypt(baseKey, usage, ivec, ciphertext, start, len);
+    }
+
+    /* Decrypt ciphertext; do not remove confounder, or check checksum */
+    public static byte[] decryptRaw(byte[] baseKey, int usage, byte[] ivec,
+        byte[] ciphertext, int start, int len)
+        throws GeneralSecurityException {
+        return CRYPTO.decryptRaw(baseKey, usage, ivec, ciphertext, start, len);
+    }
+};
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.security.jgss/share/classes/sun/security/krb5/internal/crypto/Aes256CtsHmacSha2EType.java	Mon Jan 22 16:55:01 2018 +0100
@@ -0,0 +1,112 @@
+/*
+ * Copyright (c) 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.
+ */
+
+package sun.security.krb5.internal.crypto;
+
+import sun.security.krb5.KrbCryptoException;
+import sun.security.krb5.internal.*;
+import java.security.GeneralSecurityException;
+import sun.security.krb5.EncryptedData;
+import sun.security.krb5.Checksum;
+
+/*
+ * This class encapsulates the encryption type for aes256-cts-hmac-sha384-192
+ */
+
+public final class Aes256CtsHmacSha2EType extends EType {
+
+    public int eType() {
+        return EncryptedData.ETYPE_AES256_CTS_HMAC_SHA384_192;
+    }
+
+    public int minimumPadSize() {
+        return 0;
+    }
+
+    public int confounderSize() {
+        return blockSize();
+    }
+
+    public int checksumType() {
+        return Checksum.CKSUMTYPE_HMAC_SHA384_192_AES256;
+    }
+
+    public int checksumSize() {
+        return Aes256Sha2.getChecksumLength();
+    }
+
+    public int blockSize() {
+        return 16;
+    }
+
+    public int keyType() {
+        return Krb5.KEYTYPE_AES;
+    }
+
+    public int keySize() {
+        return 32; // bytes
+    }
+
+    public byte[] encrypt(byte[] data, byte[] key, int usage)
+        throws KrbCryptoException {
+        byte[] ivec = new byte[blockSize()];
+        return encrypt(data, key, ivec, usage);
+    }
+
+    public byte[] encrypt(byte[] data, byte[] key, byte[] ivec, int usage)
+        throws KrbCryptoException {
+        try {
+            return Aes256Sha2.encrypt(key, usage, ivec, data, 0, data.length);
+        } catch (GeneralSecurityException e) {
+            KrbCryptoException ke = new KrbCryptoException(e.getMessage());
+            ke.initCause(e);
+            throw ke;
+        }
+    }
+
+    public byte[] decrypt(byte[] cipher, byte[] key, int usage)
+        throws KrbApErrException, KrbCryptoException {
+        byte[] ivec = new byte[blockSize()];
+        return decrypt(cipher, key, ivec, usage);
+    }
+
+    public byte[] decrypt(byte[] cipher, byte[] key, byte[] ivec, int usage)
+        throws KrbApErrException, KrbCryptoException {
+        try {
+            return Aes256Sha2.decrypt(key, usage, ivec, cipher, 0, cipher.length);
+        } catch (GeneralSecurityException e) {
+            KrbCryptoException ke = new KrbCryptoException(e.getMessage());
+            ke.initCause(e);
+            throw ke;
+        }
+    }
+
+    // Override default, because our decrypted data does not return confounder
+    // Should eventually get rid of EType.decryptedData and
+    // EncryptedData.decryptedData altogether
+    public byte[] decryptedData(byte[] data) {
+        return data;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.security.jgss/share/classes/sun/security/krb5/internal/crypto/Aes256Sha2.java	Mon Jan 22 16:55:01 2018 +0100
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 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.
+ */
+
+package sun.security.krb5.internal.crypto;
+
+import sun.security.krb5.internal.crypto.dk.AesSha2DkCrypto;
+import sun.security.krb5.KrbCryptoException;
+import java.security.GeneralSecurityException;
+
+/**
+ * Class with static methods for doing aes256-cts-hmac-sha384-192 operations.
+ */
+
+public class Aes256Sha2 {
+    private static final AesSha2DkCrypto CRYPTO = new AesSha2DkCrypto(256);
+
+    private Aes256Sha2() {
+    }
+
+    public static byte[] stringToKey(char[] password, String salt, byte[] params)
+        throws GeneralSecurityException {
+        return CRYPTO.stringToKey(password, salt, params);
+    }
+
+    // in bytes
+    public static int getChecksumLength() {
+        return CRYPTO.getChecksumLength();
+    }
+
+    public static byte[] calculateChecksum(byte[] baseKey, int usage,
+        byte[] input, int start, int len) throws GeneralSecurityException {
+            return CRYPTO.calculateChecksum(baseKey, usage, input, start, len);
+    }
+
+    public static byte[] encrypt(byte[] baseKey, int usage,
+        byte[] ivec, byte[] plaintext, int start, int len)
+        throws GeneralSecurityException, KrbCryptoException {
+            return CRYPTO.encrypt(baseKey, usage, ivec, null /* new_ivec */,
+                plaintext, start, len);
+    }
+
+    /* Encrypt plaintext; do not add confounder, padding, or checksum */
+    public static byte[] encryptRaw(byte[] baseKey, int usage,
+        byte[] ivec, byte[] plaintext, int start, int len)
+        throws GeneralSecurityException, KrbCryptoException {
+        return CRYPTO.encryptRaw(baseKey, usage, ivec, plaintext, start, len);
+    }
+
+    public static byte[] decrypt(byte[] baseKey, int usage, byte[] ivec,
+        byte[] ciphertext, int start, int len)
+        throws GeneralSecurityException {
+        return CRYPTO.decrypt(baseKey, usage, ivec, ciphertext, start, len);
+    }
+
+    /*
+     * Decrypt ciphertext; do not remove confounder, padding, or check
+     * checksum
+     */
+    public static byte[] decryptRaw(byte[] baseKey, int usage, byte[] ivec,
+        byte[] ciphertext, int start, int len)
+        throws GeneralSecurityException {
+        return CRYPTO.decryptRaw(baseKey, usage, ivec, ciphertext, start, len);
+    }
+};
--- a/src/java.security.jgss/share/classes/sun/security/krb5/internal/crypto/EType.java	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/java.security.jgss/share/classes/sun/security/krb5/internal/crypto/EType.java	Mon Jan 22 16:55:01 2018 +0100
@@ -106,7 +106,19 @@
                 "sun.security.krb5.internal.crypto.Aes256CtsHmacSha1EType";
             break;
 
-        case EncryptedData.ETYPE_ARCFOUR_HMAC:
+        case EncryptedData.ETYPE_AES128_CTS_HMAC_SHA256_128:
+            eType = new Aes128CtsHmacSha2EType();
+            eTypeName =
+                    "sun.security.krb5.internal.crypto.Aes128CtsHmacSha2EType";
+            break;
+
+        case EncryptedData.ETYPE_AES256_CTS_HMAC_SHA384_192:
+            eType = new Aes256CtsHmacSha2EType();
+            eTypeName =
+                    "sun.security.krb5.internal.crypto.Aes256CtsHmacSha2EType";
+            break;
+
+            case EncryptedData.ETYPE_ARCFOUR_HMAC:
             eType = new ArcFourHmacEType();
             eTypeName = "sun.security.krb5.internal.crypto.ArcFourHmacEType";
             break;
@@ -189,20 +201,23 @@
     // is set to false.
 
     private static final int[] BUILTIN_ETYPES = new int[] {
-        EncryptedData.ETYPE_AES256_CTS_HMAC_SHA1_96,
-        EncryptedData.ETYPE_AES128_CTS_HMAC_SHA1_96,
-        EncryptedData.ETYPE_DES3_CBC_HMAC_SHA1_KD,
-        EncryptedData.ETYPE_ARCFOUR_HMAC,
-        EncryptedData.ETYPE_DES_CBC_CRC,
-        EncryptedData.ETYPE_DES_CBC_MD5,
+            EncryptedData.ETYPE_AES256_CTS_HMAC_SHA1_96,
+            EncryptedData.ETYPE_AES128_CTS_HMAC_SHA1_96,
+            EncryptedData.ETYPE_AES256_CTS_HMAC_SHA384_192,
+            EncryptedData.ETYPE_AES128_CTS_HMAC_SHA256_128,
+            EncryptedData.ETYPE_DES3_CBC_HMAC_SHA1_KD,
+            EncryptedData.ETYPE_ARCFOUR_HMAC,
+            EncryptedData.ETYPE_DES_CBC_CRC,
+            EncryptedData.ETYPE_DES_CBC_MD5,
     };
 
     private static final int[] BUILTIN_ETYPES_NOAES256 = new int[] {
-        EncryptedData.ETYPE_AES128_CTS_HMAC_SHA1_96,
-        EncryptedData.ETYPE_DES3_CBC_HMAC_SHA1_KD,
-        EncryptedData.ETYPE_ARCFOUR_HMAC,
-        EncryptedData.ETYPE_DES_CBC_CRC,
-        EncryptedData.ETYPE_DES_CBC_MD5,
+            EncryptedData.ETYPE_AES128_CTS_HMAC_SHA1_96,
+            EncryptedData.ETYPE_AES128_CTS_HMAC_SHA256_128,
+            EncryptedData.ETYPE_DES3_CBC_HMAC_SHA1_KD,
+            EncryptedData.ETYPE_ARCFOUR_HMAC,
+            EncryptedData.ETYPE_DES_CBC_CRC,
+            EncryptedData.ETYPE_DES_CBC_MD5,
     };
 
 
@@ -363,7 +378,10 @@
             return "RC4 with HMAC";
         case 24:
             return "RC4 with HMAC EXP";
-
+        case EncryptedData.ETYPE_AES128_CTS_HMAC_SHA256_128:
+            return "AES128 CTS mode with HMAC SHA256-128";
+        case EncryptedData.ETYPE_AES256_CTS_HMAC_SHA384_192:
+            return "AES256 CTS mode with HMAC SHA384-192";
         }
         return "Unknown (" + type + ")";
     }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.security.jgss/share/classes/sun/security/krb5/internal/crypto/HmacSha2Aes128CksumType.java	Mon Jan 22 16:55:01 2018 +0100
@@ -0,0 +1,110 @@
+/*
+ * Copyright (c) 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.
+ */
+
+package sun.security.krb5.internal.crypto;
+
+import sun.security.krb5.Checksum;
+import sun.security.krb5.KrbCryptoException;
+import sun.security.krb5.internal.*;
+import java.security.GeneralSecurityException;
+
+/*
+ * This class encapsulates the checksum type for aes128-cts-sha256
+ */
+
+public class HmacSha2Aes128CksumType extends CksumType {
+
+    public HmacSha2Aes128CksumType() {
+    }
+
+    public int confounderSize() {
+        return 16;
+    }
+
+    public int cksumType() {
+        return Checksum.CKSUMTYPE_HMAC_SHA256_128_AES128;
+    }
+
+    public boolean isSafe() {
+        return true;
+    }
+
+    public int cksumSize() {
+        return 16;  // bytes
+    }
+
+    public int keyType() {
+        return Krb5.KEYTYPE_AES;
+    }
+
+    public int keySize() {
+        return 16;   // bytes
+    }
+
+    public byte[] calculateChecksum(byte[] data, int size) {
+        return null;
+    }
+
+    /**
+     * Calculates keyed checksum.
+     * @param data the data used to generate the checksum.
+     * @param size length of the data.
+     * @param key the key used to encrypt the checksum.
+     * @return keyed checksum.
+     */
+    public byte[] calculateKeyedChecksum(byte[] data, int size, byte[] key,
+        int usage) throws KrbCryptoException {
+
+         try {
+            return Aes128Sha2.calculateChecksum(key, usage, data, 0, size);
+         } catch (GeneralSecurityException e) {
+            KrbCryptoException ke = new KrbCryptoException(e.getMessage());
+            ke.initCause(e);
+            throw ke;
+         }
+    }
+
+    /**
+     * Verifies keyed checksum.
+     * @param data the data.
+     * @param size the length of data.
+     * @param key the key used to encrypt the checksum.
+     * @param checksum the checksum.
+     * @return true if verification is successful.
+     */
+    public boolean verifyKeyedChecksum(byte[] data, int size,
+        byte[] key, byte[] checksum, int usage) throws KrbCryptoException {
+
+         try {
+            byte[] newCksum = Aes128Sha2.calculateChecksum(key, usage,
+                                                        data, 0, size);
+            return isChecksumEqual(checksum, newCksum);
+         } catch (GeneralSecurityException e) {
+            KrbCryptoException ke = new KrbCryptoException(e.getMessage());
+            ke.initCause(e);
+            throw ke;
+         }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.security.jgss/share/classes/sun/security/krb5/internal/crypto/HmacSha2Aes256CksumType.java	Mon Jan 22 16:55:01 2018 +0100
@@ -0,0 +1,110 @@
+/*
+ * Copyright (c) 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.
+ */
+
+package sun.security.krb5.internal.crypto;
+
+import sun.security.krb5.Checksum;
+import sun.security.krb5.KrbCryptoException;
+import sun.security.krb5.internal.*;
+import java.security.GeneralSecurityException;
+
+/*
+ * This class encapsulates the checksum type for aes256-cts-sha384
+ */
+
+public class HmacSha2Aes256CksumType extends CksumType {
+
+    public HmacSha2Aes256CksumType() {
+    }
+
+    public int confounderSize() {
+        return 16;
+    }
+
+    public int cksumType() {
+        return Checksum.CKSUMTYPE_HMAC_SHA384_192_AES256;
+    }
+
+    public boolean isSafe() {
+        return true;
+    }
+
+    public int cksumSize() {
+        return 24;  // bytes
+    }
+
+    public int keyType() {
+        return Krb5.KEYTYPE_AES;
+    }
+
+    public int keySize() {
+        return 32;   // bytes
+    }
+
+    public byte[] calculateChecksum(byte[] data, int size) {
+        return null;
+    }
+
+    /**
+     * Calculates keyed checksum.
+     * @param data the data used to generate the checksum.
+     * @param size length of the data.
+     * @param key the key used to encrypt the checksum.
+     * @return keyed checksum.
+     */
+    public byte[] calculateKeyedChecksum(byte[] data, int size, byte[] key,
+        int usage) throws KrbCryptoException {
+
+         try {
+            return Aes256Sha2.calculateChecksum(key, usage, data, 0, size);
+         } catch (GeneralSecurityException e) {
+            KrbCryptoException ke = new KrbCryptoException(e.getMessage());
+            ke.initCause(e);
+            throw ke;
+         }
+    }
+
+    /**
+     * Verifies keyed checksum.
+     * @param data the data.
+     * @param size the length of data.
+     * @param key the key used to encrypt the checksum.
+     * @param checksum the checksum.
+     * @return true if verification is successful.
+     */
+    public boolean verifyKeyedChecksum(byte[] data, int size,
+        byte[] key, byte[] checksum, int usage) throws KrbCryptoException {
+
+         try {
+            byte[] newCksum = Aes256Sha2.calculateChecksum(key, usage, data,
+                                                        0, size);
+            return isChecksumEqual(checksum, newCksum);
+         } catch (GeneralSecurityException e) {
+            KrbCryptoException ke = new KrbCryptoException(e.getMessage());
+            ke.initCause(e);
+            throw ke;
+         }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.security.jgss/share/classes/sun/security/krb5/internal/crypto/dk/AesSha2DkCrypto.java	Mon Jan 22 16:55:01 2018 +0100
@@ -0,0 +1,541 @@
+/*
+ * Copyright (c) 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.
+ */
+
+/*
+ */
+
+package sun.security.krb5.internal.crypto.dk;
+
+import javax.crypto.Cipher;
+import javax.crypto.Mac;
+import javax.crypto.SecretKeyFactory;
+import javax.crypto.SecretKey;
+import javax.crypto.spec.SecretKeySpec;
+import javax.crypto.spec.IvParameterSpec;
+import javax.crypto.spec.PBEKeySpec;
+import java.security.GeneralSecurityException;
+import sun.security.krb5.KrbCryptoException;
+import sun.security.krb5.Confounder;
+import sun.security.krb5.internal.crypto.KeyUsage;
+import java.util.Arrays;
+
+/**
+ * This class provides the implementation of AES Encryption with
+ * HMAC-SHA2 for Kerberos 5
+ * https://tools.ietf.org/html/rfc8009
+ *
+ * Algorithm profile described in [KCRYPTO]:
+ * +--------------------------------------------------------------------+
+ * |               protocol key format          128- or 256-bit string  |
+ * |                                                                    |
+ * |            string-to-key function          PBKDF2+DK with variable |
+ * |                                          iteration count (see      |
+ * |                                          above)                    |
+ * |                                                                    |
+ * |  default string-to-key parameters          00 00 80 00             |
+ * |                                                                    |
+ * |        key-generation seed length          key size                |
+ * |                                                                    |
+ * |            random-to-key function          identity function       |
+ * |                                                                    |
+ * |                  hash function, H          SHA-256 / SHA-384       |
+ * |                                                                    |
+ * |               HMAC output size, h          16/24 octets            |
+ * |                                                                    |
+ * |             message block size, m          1 octet                 |
+ * |                                                                    |
+ * |  encryption/decryption functions,          AES in CBC-CTS mode     |
+ * |  E and D                                 (cipher block size 16     |
+ * |                                          octets), with next to     |
+ * |                                          last block as CBC-style   |
+ * |                                          ivec                      |
+ * +--------------------------------------------------------------------+
+ *
+ * Supports aes128-cts-hmac-sha256-128 and aes256-cts-hmac-sha384-192
+ */
+
+public class AesSha2DkCrypto extends DkCrypto {
+
+    private static final boolean debug = false;
+
+    private static final int BLOCK_SIZE = 16;
+    private static final int DEFAULT_ITERATION_COUNT = 32768;
+    private static final byte[] ZERO_IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0,
+                                                       0, 0, 0, 0, 0, 0, 0, 0 };
+
+    private static final byte[] ETYPE_NAME_128 =
+            "aes128-cts-hmac-sha256-128".getBytes();
+    private static final byte[] ETYPE_NAME_256 =
+            "aes256-cts-hmac-sha384-192".getBytes();
+
+    private final int hashSize;
+    private final int keyLength;
+
+    public AesSha2DkCrypto(int length) {
+        keyLength = length;
+        hashSize = (length == 128?128:192)/8;
+    }
+
+    protected int getKeySeedLength() {
+        return keyLength;   // bits; AES key material
+    }
+
+    public byte[] stringToKey(char[] password, String salt, byte[] s2kparams)
+        throws GeneralSecurityException {
+
+        byte[] saltUtf8 = null;
+        try {
+            saltUtf8 = salt.getBytes("UTF-8");
+            return stringToKey(password, saltUtf8, s2kparams);
+        } catch (Exception e) {
+            return null;
+        } finally {
+            if (saltUtf8 != null) {
+                Arrays.fill(saltUtf8, (byte)0);
+            }
+        }
+    }
+
+    // https://tools.ietf.org/html/rfc8009#section-4
+    private byte[] stringToKey(char[] secret, byte[] salt, byte[] params)
+        throws GeneralSecurityException {
+
+        int iter_count = DEFAULT_ITERATION_COUNT;
+        if (params != null) {
+            if (params.length != 4) {
+                throw new RuntimeException("Invalid parameter to stringToKey");
+            }
+            iter_count = readBigEndian(params, 0, 4);
+        }
+
+        byte[] saltp = new byte[26 + 1 + salt.length];
+        if (keyLength == 128) {
+            System.arraycopy(ETYPE_NAME_128, 0, saltp, 0, 26);
+        } else {
+            System.arraycopy(ETYPE_NAME_256, 0, saltp, 0, 26);
+        }
+        System.arraycopy(salt, 0, saltp, 27, salt.length);
+        byte[] tmpKey = randomToKey(PBKDF2(secret, saltp, iter_count,
+                                        getKeySeedLength()));
+        byte[] result = dk(tmpKey, KERBEROS_CONSTANT);
+        return result;
+    }
+
+    protected byte[] randomToKey(byte[] in) {
+        // simple identity operation
+        return in;
+    }
+
+    /*
+     * https://tools.ietf.org/html/rfc8009#section-3 defines
+     * a new key derivation function:
+     *
+     * KDF-HMAC-SHA2(key, label, k) = k-truncate(K1)
+     * K1 = HMAC-SHA-256(key, 0x00000001 | label | 0x00 | k) or
+     * K1 = HMAC-SHA-384(key, 0x00000001 | label | 0x00 | k)
+     *
+     * where label is constant below.
+     */
+    protected byte[] dr(byte[] key, byte[] constant)
+            throws GeneralSecurityException {
+        byte[] result;
+        byte[] input = new byte[constant.length + 9];
+        // 0x00000001 at the beginning
+        input[3] = 1;
+        // label follows
+        System.arraycopy(constant, 0, input, 4, constant.length);
+        SecretKeySpec tkey = new SecretKeySpec(key, "HMAC");
+        Mac mac = Mac.getInstance(
+                keyLength == 128? "HmacSHA256": "HmacSHA384");
+        mac.init(tkey);
+
+        int k;
+        if (keyLength == 128) {
+            // key length for enc and hmac both 128
+            k = 128;
+        } else {
+            byte last = constant[constant.length-1];
+            if (last == (byte)0x99 || last == (byte)0x55) {
+                // 192 for hmac
+                k = 192;
+            } else {
+                // 256 for enc
+                k = 256;
+            }
+        }
+        // 0x00 and k at the end
+        input[input.length - 1] = (byte)(k);
+        input[input.length - 2] = (byte)(k / 256);
+
+        result = mac.doFinal(input);
+        return Arrays.copyOf(result, k / 8);
+    }
+
+    protected Cipher getCipher(byte[] key, byte[] ivec, int mode)
+        throws GeneralSecurityException {
+
+        // IV
+        if (ivec == null) {
+           ivec = ZERO_IV;
+        }
+        SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
+        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
+        IvParameterSpec encIv = new IvParameterSpec(ivec, 0, ivec.length);
+        cipher.init(mode, secretKey, encIv);
+        return cipher;
+    }
+
+    // get an instance of the AES Cipher in CTS mode
+    public int getChecksumLength() {
+        return hashSize;  // bytes
+    }
+
+    /**
+     * Get the truncated HMAC
+     */
+    protected byte[] getHmac(byte[] key, byte[] msg)
+        throws GeneralSecurityException {
+
+        SecretKey keyKi = new SecretKeySpec(key, "HMAC");
+        Mac m = Mac.getInstance(keyLength == 128 ? "HmacSHA256" : "HmacSHA384");
+        m.init(keyKi);
+
+        // generate hash
+        byte[] hash = m.doFinal(msg);
+
+        // truncate hash
+        byte[] output = new byte[hashSize];
+        System.arraycopy(hash, 0, output, 0, hashSize);
+        return output;
+    }
+
+    private byte[] deriveKey(byte[] baseKey, int usage, byte type)
+            throws GeneralSecurityException {
+        byte[] constant = new byte[5];
+        constant[0] = (byte) ((usage>>24)&0xff);
+        constant[1] = (byte) ((usage>>16)&0xff);
+        constant[2] = (byte) ((usage>>8)&0xff);
+        constant[3] = (byte) (usage&0xff);
+        constant[4] = type;
+        return dk(baseKey, constant);
+    }
+
+    /**
+     * Calculate the checksum
+     */
+    public byte[] calculateChecksum(byte[] baseKey, int usage, byte[] input,
+        int start, int len) throws GeneralSecurityException {
+
+        if (!KeyUsage.isValid(usage)) {
+            throw new GeneralSecurityException("Invalid key usage number: "
+                                                + usage);
+        }
+
+        byte[] Kc = deriveKey(baseKey, usage, (byte) 0x99);  // Checksum key
+        if (debug) {
+            System.err.println("usage: " + usage);
+            traceOutput("input", input, start, Math.min(len, 32));
+            traceOutput("baseKey", baseKey, 0, baseKey.length);
+            traceOutput("Kc", Kc, 0, Kc.length);
+        }
+
+        try {
+            // Generate checksum
+            // H1 = HMAC(Kc, input)
+            byte[] hmac = getHmac(Kc, input);
+            if (debug) {
+                traceOutput("hmac", hmac, 0, hmac.length);
+            }
+            if (hmac.length == getChecksumLength()) {
+                return hmac;
+            } else if (hmac.length > getChecksumLength()) {
+                byte[] buf = new byte[getChecksumLength()];
+                System.arraycopy(hmac, 0, buf, 0, buf.length);
+                return buf;
+            } else {
+                throw new GeneralSecurityException("checksum size too short: " +
+                        hmac.length + "; expecting : " + getChecksumLength());
+            }
+        } finally {
+            Arrays.fill(Kc, 0, Kc.length, (byte)0);
+        }
+    }
+
+    /**
+     * Performs encryption using derived key; adds confounder.
+     */
+    public byte[] encrypt(byte[] baseKey, int usage,
+        byte[] ivec, byte[] new_ivec, byte[] plaintext, int start, int len)
+        throws GeneralSecurityException, KrbCryptoException {
+
+        if (!KeyUsage.isValid(usage)) {
+            throw new GeneralSecurityException("Invalid key usage number: "
+                                                 + usage);
+        }
+        byte[] output = encryptCTS(baseKey, usage, ivec, new_ivec, plaintext,
+                                        start, len, true);
+        return output;
+    }
+
+    /**
+     * Performs encryption using derived key; does not add confounder.
+     */
+    public byte[] encryptRaw(byte[] baseKey, int usage,
+        byte[] ivec, byte[] plaintext, int start, int len)
+        throws GeneralSecurityException, KrbCryptoException {
+
+        if (!KeyUsage.isValid(usage)) {
+            throw new GeneralSecurityException("Invalid key usage number: "
+                                                + usage);
+        }
+        byte[] output = encryptCTS(baseKey, usage, ivec, null, plaintext,
+                                        start, len, false);
+        return output;
+    }
+
+    /**
+     * @param baseKey key from which keys are to be derived using usage
+     * @param ciphertext  E(Ke, conf | plaintext | padding, ivec) | H1[1..h]
+     */
+    public byte[] decrypt(byte[] baseKey, int usage, byte[] ivec,
+        byte[] ciphertext, int start, int len) throws GeneralSecurityException {
+
+        if (!KeyUsage.isValid(usage)) {
+            throw new GeneralSecurityException("Invalid key usage number: "
+                                                + usage);
+        }
+        byte[] output = decryptCTS(baseKey, usage, ivec, ciphertext,
+                                        start, len, true);
+        return output;
+    }
+
+    /**
+     * Decrypts data using specified key and initial vector.
+     * @param baseKey encryption key to use
+     * @param ciphertext  encrypted data to be decrypted
+     * @param usage ignored
+     */
+    public byte[] decryptRaw(byte[] baseKey, int usage, byte[] ivec,
+        byte[] ciphertext, int start, int len)
+        throws GeneralSecurityException {
+
+        if (!KeyUsage.isValid(usage)) {
+            throw new GeneralSecurityException("Invalid key usage number: "
+                                                + usage);
+        }
+        byte[] output = decryptCTS(baseKey, usage, ivec, ciphertext,
+                                        start, len, false);
+        return output;
+    }
+
+    /**
+     * Encrypt AES in CBC-CTS mode using derived keys.
+     */
+    private byte[] encryptCTS(byte[] baseKey, int usage, byte[] ivec,
+        byte[] new_ivec, byte[] plaintext, int start, int len,
+        boolean confounder_exists)
+        throws GeneralSecurityException, KrbCryptoException {
+
+        byte[] Ke = null;
+        byte[] Ki = null;
+
+        if (debug) {
+            System.err.println("usage: " + usage);
+            if (ivec != null) {
+                traceOutput("old_state.ivec", ivec, 0, ivec.length);
+            }
+            traceOutput("plaintext", plaintext, start, Math.min(len, 32));
+            traceOutput("baseKey", baseKey, 0, baseKey.length);
+        }
+
+        try {
+            Ke = deriveKey(baseKey, usage, (byte) 0xaa);  // Encryption key
+
+            byte[] toBeEncrypted = null;
+            if (confounder_exists) {
+                byte[] confounder = Confounder.bytes(BLOCK_SIZE);
+                toBeEncrypted = new byte[confounder.length + len];
+                System.arraycopy(confounder, 0, toBeEncrypted,
+                                        0, confounder.length);
+                System.arraycopy(plaintext, start, toBeEncrypted,
+                                        confounder.length, len);
+            } else {
+                toBeEncrypted = new byte[len];
+                System.arraycopy(plaintext, start, toBeEncrypted, 0, len);
+            }
+
+            // encryptedData + HMAC
+            byte[] output = new byte[toBeEncrypted.length + hashSize];
+
+            // AES in JCE
+            Cipher cipher = Cipher.getInstance("AES/CTS/NoPadding");
+            SecretKeySpec secretKey = new SecretKeySpec(Ke, "AES");
+            IvParameterSpec encIv = new IvParameterSpec(ivec, 0, ivec.length);
+            cipher.init(Cipher.ENCRYPT_MODE, secretKey, encIv);
+            cipher.doFinal(toBeEncrypted, 0, toBeEncrypted.length, output);
+
+            Ki = deriveKey(baseKey, usage, (byte) 0x55);
+            if (debug) {
+                traceOutput("Ki", Ki, 0, Ke.length);
+            }
+
+            // Generate checksum
+            // H = HMAC(Ki, IV | C)
+            byte[] msg = Arrays.copyOf(ivec, ivec.length + toBeEncrypted.length);
+            System.arraycopy(output, 0, msg, ivec.length, toBeEncrypted.length);
+            byte[] hmac = getHmac(Ki, msg);
+
+            // encryptedData + HMAC
+            System.arraycopy(hmac, 0, output, toBeEncrypted.length,
+                                hmac.length);
+            return output;
+        } finally {
+            if (Ke != null) {
+                Arrays.fill(Ke, 0, Ke.length, (byte) 0);
+            }
+            if (Ki != null) {
+                Arrays.fill(Ki, 0, Ki.length, (byte) 0);
+            }
+        }
+    }
+
+    /**
+     * Decrypt AES in CBC-CTS mode using derived keys.
+     */
+    private byte[] decryptCTS(byte[] baseKey, int usage, byte[] ivec,
+        byte[] ciphertext, int start, int len, boolean confounder_exists)
+        throws GeneralSecurityException {
+
+        byte[] Ke = null;
+        byte[] Ki = null;
+
+        try {
+            Ke = deriveKey(baseKey, usage, (byte) 0xaa);  // Encryption key
+
+            if (debug) {
+                System.err.println("usage: " + usage);
+                if (ivec != null) {
+                    traceOutput("old_state.ivec", ivec, 0, ivec.length);
+                }
+                traceOutput("ciphertext", ciphertext, start, Math.min(len, 32));
+                traceOutput("baseKey", baseKey, 0, baseKey.length);
+                traceOutput("Ke", Ke, 0, Ke.length);
+            }
+
+            // Decrypt [confounder | plaintext ] (without checksum)
+
+            // AES in JCE
+            Cipher cipher = Cipher.getInstance("AES/CTS/NoPadding");
+            SecretKeySpec secretKey = new SecretKeySpec(Ke, "AES");
+            IvParameterSpec encIv = new IvParameterSpec(ivec, 0, ivec.length);
+            cipher.init(Cipher.DECRYPT_MODE, secretKey, encIv);
+            byte[] plaintext = cipher.doFinal(ciphertext, start, len-hashSize);
+
+            if (debug) {
+                traceOutput("AES PlainText", plaintext, 0,
+                                Math.min(plaintext.length, 32));
+            }
+
+            Ki = deriveKey(baseKey, usage, (byte) 0x55);  // Integrity key
+            if (debug) {
+                traceOutput("Ki", Ki, 0, Ke.length);
+            }
+
+            // Verify checksum
+            // H = HMAC(Ki, IV | C)
+            byte[] msg = Arrays.copyOf(ivec, ivec.length + len-hashSize);
+            System.arraycopy(ciphertext, start, msg, ivec.length, len-hashSize);
+            byte[] calculatedHmac = getHmac(Ki, msg);
+            int hmacOffset = start + len - hashSize;
+            if (debug) {
+                traceOutput("calculated Hmac", calculatedHmac,
+                                0, calculatedHmac.length);
+                traceOutput("message Hmac", ciphertext, hmacOffset, hashSize);
+            }
+            boolean cksumFailed = false;
+            if (calculatedHmac.length >= hashSize) {
+                for (int i = 0; i < hashSize; i++) {
+                    if (calculatedHmac[i] != ciphertext[hmacOffset+i]) {
+                        cksumFailed = true;
+                        if (debug) {
+                            System.err.println("Checksum failed !");
+                        }
+                        break;
+                    }
+                }
+            }
+            if (cksumFailed) {
+                throw new GeneralSecurityException("Checksum failed");
+            }
+
+            if (confounder_exists) {
+                // Get rid of confounder
+                // [ confounder | plaintext ]
+                byte[] output = new byte[plaintext.length - BLOCK_SIZE];
+                System.arraycopy(plaintext, BLOCK_SIZE, output,
+                                        0, output.length);
+                return output;
+            } else {
+                return plaintext;
+            }
+        } finally {
+            if (Ke != null) {
+                Arrays.fill(Ke, 0, Ke.length, (byte) 0);
+            }
+            if (Ki != null) {
+                Arrays.fill(Ki, 0, Ki.length, (byte) 0);
+            }
+        }
+    }
+
+    /*
+     * Invoke the PKCS#5 PBKDF2 algorithm
+     */
+    private static byte[] PBKDF2(char[] secret, byte[] salt,
+        int count, int keyLength) throws GeneralSecurityException {
+
+        PBEKeySpec keySpec = new PBEKeySpec(secret, salt, count, keyLength);
+        SecretKeyFactory skf =
+                SecretKeyFactory.getInstance(keyLength == 128 ?
+                        "PBKDF2WithHmacSHA256" : "PBKDF2WithHmacSHA384");
+        SecretKey key = skf.generateSecret(keySpec);
+        byte[] result = key.getEncoded();
+
+        return result;
+    }
+
+    public static final int readBigEndian(byte[] data, int pos, int size) {
+        int retVal = 0;
+        int shifter = (size-1)*8;
+        while (size > 0) {
+            retVal += (data[pos] & 0xff) << shifter;
+            shifter -= 8;
+            pos++;
+            size--;
+        }
+        return retVal;
+    }
+
+}
--- a/src/java.security.jgss/share/classes/sun/security/krb5/internal/crypto/dk/DkCrypto.java	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/java.security.jgss/share/classes/sun/security/krb5/internal/crypto/dk/DkCrypto.java	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2017, Oracle and/or its affiliates. All rights reserved.
  */
 
 /*
@@ -478,7 +478,7 @@
      *
      * DR(Key, Constant) = k-truncate(K1 | K2 | K3 | K4 ...)
      */
-    private byte[] dr(byte[] key, byte[] constant)
+    protected byte[] dr(byte[] key, byte[] constant)
         throws GeneralSecurityException {
 
         Cipher encCipher = getCipher(key, null, Cipher.ENCRYPT_MODE);
@@ -667,7 +667,7 @@
             new HexDumpEncoder().encodeBuffer(
                 new ByteArrayInputStream(output, offset, len), out);
 
-            System.err.println(traceTag + ":" + out.toString());
+            System.err.println(traceTag + ":\n" + out.toString());
         } catch (Exception e) {
         }
     }
--- a/src/jdk.attach/share/classes/sun/tools/attach/HotSpotVirtualMachine.java	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/jdk.attach/share/classes/sun/tools/attach/HotSpotVirtualMachine.java	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 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
@@ -86,6 +86,10 @@
     private void loadAgentLibrary(String agentLibrary, boolean isAbsolute, String options)
         throws AgentLoadException, AgentInitializationException, IOException
     {
+        if (agentLibrary == null) {
+            throw new NullPointerException("agentLibrary cannot be null");
+        }
+
         String msgPrefix = "return code: ";
         InputStream in = execute("load",
                                  agentLibrary,
@@ -131,6 +135,10 @@
     public void loadAgent(String agent, String options)
         throws AgentLoadException, AgentInitializationException, IOException
     {
+        if (agent == null) {
+            throw new NullPointerException("agent cannot be null");
+        }
+
         String args = agent;
         if (options != null) {
             args = args + "=" + options;
--- a/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/CommandProcessor.java	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/CommandProcessor.java	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 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
@@ -1607,7 +1607,9 @@
                             if (!all) return;
                         }
                     }
-                    out.println("Couldn't find thread " + name);
+                    if (!all) {
+                        out.println("Couldn't find thread " + name);
+                    }
                 }
             }
         },
--- a/src/jdk.jshell/share/classes/jdk/jshell/Eval.java	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/jdk.jshell/share/classes/jdk/jshell/Eval.java	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 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
@@ -36,6 +36,7 @@
 import com.sun.source.tree.ArrayTypeTree;
 import com.sun.source.tree.AssignmentTree;
 import com.sun.source.tree.ClassTree;
+import com.sun.source.tree.ExpressionStatementTree;
 import com.sun.source.tree.ExpressionTree;
 import com.sun.source.tree.IdentifierTree;
 import com.sun.source.tree.MethodTree;
@@ -43,6 +44,7 @@
 import com.sun.source.tree.NewClassTree;
 import com.sun.source.tree.Tree;
 import com.sun.source.tree.VariableTree;
+import com.sun.source.util.TreeScanner;
 import com.sun.tools.javac.tree.JCTree;
 import com.sun.tools.javac.tree.Pretty;
 import java.io.IOException;
@@ -52,6 +54,8 @@
 import java.util.LinkedHashSet;
 import java.util.Set;
 import jdk.jshell.ExpressionToTypeInfo.ExpressionInfo;
+import jdk.jshell.ExpressionToTypeInfo.ExpressionInfo.AnonymousDescription;
+import jdk.jshell.ExpressionToTypeInfo.ExpressionInfo.AnonymousDescription.VariableDesc;
 import jdk.jshell.Key.ErroneousKey;
 import jdk.jshell.Key.MethodKey;
 import jdk.jshell.Key.TypeDeclKey;
@@ -60,6 +64,7 @@
 import jdk.jshell.TaskFactory.AnalyzeTask;
 import jdk.jshell.TaskFactory.BaseTask;
 import jdk.jshell.TaskFactory.ParseTask;
+import jdk.jshell.Util.Pair;
 import jdk.jshell.Wrap.CompoundWrap;
 import jdk.jshell.Wrap.Range;
 import jdk.jshell.Snippet.Status;
@@ -74,6 +79,7 @@
 import static java.util.stream.Collectors.toList;
 import static java.util.stream.Collectors.toSet;
 import static java.util.Collections.singletonList;
+import com.sun.tools.javac.code.Symbol.TypeSymbol;
 import static jdk.internal.jshell.debug.InternalDebugControl.DBG_GEN;
 import static jdk.jshell.Util.DOIT_METHOD_NAME;
 import static jdk.jshell.Util.PREFIX_PATTERN;
@@ -98,6 +104,11 @@
 
     private int varNumber = 0;
 
+    /* The number of anonymous innerclasses seen so far. Used to generate unique
+     * names of these classes.
+     */
+    private int anonCount = 0;
+
     private final JShell state;
 
     // The set of names of methods on Object
@@ -203,7 +214,7 @@
                 case VARIABLE:
                     return processVariables(userSource, units, compileSourceInt, pt);
                 case EXPRESSION_STATEMENT:
-                    return processExpression(userSource, compileSourceInt);
+                    return processExpression(userSource, unitTree, compileSourceInt, pt);
                 case CLASS:
                     return processClass(userSource, unitTree, compileSourceInt, SubKind.CLASS_SUBKIND, pt);
                 case ENUM:
@@ -285,15 +296,19 @@
             String name = vt.getName().toString();
             String typeName;
             String fullTypeName;
+            String displayType;
+            boolean hasEnhancedType = false;
             TreeDependencyScanner tds = new TreeDependencyScanner();
             Wrap typeWrap;
             Wrap anonDeclareWrap = null;
             Wrap winit = null;
+            boolean enhancedDesugaring = false;
+            Set<String> anonymousClasses = Collections.emptySet();
             StringBuilder sbBrackets = new StringBuilder();
             Tree baseType = vt.getType();
             if (baseType != null) {
                 tds.scan(baseType); // Not dependent on initializer
-                fullTypeName = typeName = EvalPretty.prettyExpr((JCTree) vt.getType(), false);
+                fullTypeName = displayType = typeName = EvalPretty.prettyExpr((JCTree) vt.getType(), false);
                 while (baseType instanceof ArrayTypeTree) {
                     //TODO handle annotations too
                     baseType = ((ArrayTypeTree) baseType).getType();
@@ -311,83 +326,27 @@
                     Range rinit = dis.treeToRange(init);
                     String initCode = rinit.part(compileSource);
                     ExpressionInfo ei =
-                            ExpressionToTypeInfo.localVariableTypeForInitializer(initCode, state);
-                    typeName = ei == null ? "java.lang.Object" : ei.typeName;
-                    fullTypeName = ei == null ? "java.lang.Object" : ei.fullTypeName;
-                    if (ei != null && init.getKind() == Tree.Kind.NEW_CLASS &&
-                        ((NewClassTree) init).getClassBody() != null) {
-                        NewClassTree nct = (NewClassTree) init;
-                        StringBuilder constructor = new StringBuilder();
-                        constructor.append(fullTypeName).append("(");
-                        String sep = "";
-                        if (ei.enclosingInstanceType != null) {
-                            constructor.append(ei.enclosingInstanceType);
-                            constructor.append(" encl");
-                            sep = ", ";
-                        }
-                        int idx = 0;
-                        for (String type : ei.parameterTypes) {
-                            constructor.append(sep);
-                            constructor.append(type);
-                            constructor.append(" ");
-                            constructor.append("arg" + idx++);
-                            sep = ", ";
-                        }
-                        if (ei.enclosingInstanceType != null) {
-                            constructor.append(") { encl.super (");
-                        } else {
-                            constructor.append(") { super (");
-                        }
-                        sep = "";
-                        for (int i = 0; i < idx; i++) {
-                            constructor.append(sep);
-                            constructor.append("arg" + i++);
-                            sep = ", ";
-                        }
-                        constructor.append("); }");
-                        List<? extends Tree> members = nct.getClassBody().getMembers();
-                        Range bodyRange = dis.treeListToRange(members);
-                        Wrap bodyWrap;
+                            ExpressionToTypeInfo.localVariableTypeForInitializer(initCode, state, false);
+                    if (ei != null) {
+                        typeName = ei.declareTypeName;
+                        fullTypeName = ei.fullTypeName;
+                        displayType = ei.displayTypeName;
 
-                        if (bodyRange != null) {
-                            bodyWrap = Wrap.rangeWrap(compileSource, bodyRange);
-                        } else {
-                            bodyWrap = Wrap.simpleWrap(" ");
-                        }
+                        hasEnhancedType = !typeName.equals(fullTypeName);
 
-                        Range argRange = dis.treeListToRange(nct.getArguments());
-                        Wrap argWrap;
+                        enhancedDesugaring = !ei.isPrimitiveType;
 
-                        if (argRange != null) {
-                            argWrap = Wrap.rangeWrap(compileSource, argRange);
-                        } else {
-                            argWrap = Wrap.simpleWrap(" ");
-                        }
-
-                        if (ei.enclosingInstanceType != null) {
-                            Range enclosingRanges =
-                                    dis.treeToRange(nct.getEnclosingExpression());
-                            Wrap enclosingWrap = Wrap.rangeWrap(compileSource, enclosingRanges);
-                            argWrap = argRange != null ? new CompoundWrap(enclosingWrap,
-                                                                          Wrap.simpleWrap(","),
-                                                                          argWrap)
-                                                       : enclosingWrap;
-                        }
-                        Wrap hwrap = Wrap.simpleWrap("public static class " + fullTypeName +
-                                                     (ei.isClass ? " extends " : " implements ") +
-                                                     typeName + " { " + constructor);
-                        anonDeclareWrap = new CompoundWrap(hwrap, bodyWrap, Wrap.simpleWrap("}"));
-                        winit = new CompoundWrap("new " + fullTypeName + "(", argWrap, ")");
-
-                        String superType = typeName;
-
-                        typeName = fullTypeName;
-                        fullTypeName = ei.isClass ? "<anonymous class extending " + superType + ">"
-                                                  : "<anonymous class implementing " + superType + ">";
+                        Pair<Wrap, Wrap> anonymous2Member =
+                                anonymous2Member(ei, compileSource, rinit, dis, init);
+                        anonDeclareWrap = anonymous2Member.first;
+                        winit = anonymous2Member.second;
+                        anonymousClasses = ei.anonymousClasses.stream().map(ad -> ad.declareTypeName).collect(Collectors.toSet());
+                    } else {
+                        displayType = fullTypeName = typeName = "java.lang.Object";
                     }
                     tds.scan(init);
                 } else {
-                    fullTypeName = typeName = "java.lang.Object";
+                    displayType = fullTypeName = typeName = "java.lang.Object";
                 }
                 typeWrap = Wrap.identityWrap(typeName);
             }
@@ -411,17 +370,193 @@
             int nameEnd = nameStart + name.length();
             Range rname = new Range(nameStart, nameEnd);
             Wrap guts = Wrap.varWrap(compileSource, typeWrap, sbBrackets.toString(), rname,
-                                     winit, anonDeclareWrap);
-                        DiagList modDiag = modifierDiagnostics(vt.getModifiers(), dis, true);
+                                     winit, enhancedDesugaring, anonDeclareWrap);
+            DiagList modDiag = modifierDiagnostics(vt.getModifiers(), dis, true);
             Snippet snip = new VarSnippet(state.keyMap.keyForVariable(name), userSource, guts,
-                    name, subkind, fullTypeName,
+                    name, subkind, displayType, hasEnhancedType ? fullTypeName : null, anonymousClasses,
                     tds.declareReferences(), modDiag);
             snippets.add(snip);
         }
         return snippets;
     }
 
-    private List<Snippet> processExpression(String userSource, String compileSource) {
+    /**Convert anonymous classes in "init" to member classes, based
+     * on the additional information from ExpressionInfo.anonymousClasses.
+     *
+     * This means:
+     * -if the code in the anonymous class captures any variables from the
+     *  enclosing context, create fields for them
+     * -creating an explicit constructor that:
+     * --if the new class expression has a base/enclosing expression, make it an
+     *   explicit constructor parameter "encl" and use "encl.super" when invoking
+     *   the supertype constructor
+     * --if the (used) supertype constructor has any parameters, declare them
+     *   as explicit parameters of the constructor, and pass them to the super
+     *   constructor
+     * --if the code in the anonymous class captures any variables from the
+     *   enclosing context, make them an explicit paramters of the constructor
+     *   and assign to respective fields.
+     * --if there are any explicit fields with initializers in the anonymous class,
+     *   move the initializers at the end of the constructor (after the captured fields
+     *   are assigned, so that the initializers of these fields can use them).
+     * -from the captured variables fields, constructor, and existing members
+     *  (with cleared field initializers), create an explicit class that extends or
+     *  implements the supertype of the anonymous class.
+     *
+     * This method returns two wraps: the first contains the class declarations for the
+     * converted classes, the first one should be used instead of "init" in the variable
+     * declaration.
+     */
+    private Pair<Wrap, Wrap> anonymous2Member(ExpressionInfo ei,
+                                              String compileSource,
+                                              Range rinit,
+                                              TreeDissector dis,
+                                              Tree init) {
+        List<Wrap> anonymousDeclarations = new ArrayList<>();
+        List<Wrap> partitionedInit = new ArrayList<>();
+        int lastPos = rinit.begin;
+        com.sun.tools.javac.util.List<NewClassTree> toConvert =
+                ExpressionToTypeInfo.listAnonymousClassesToConvert(init);
+        com.sun.tools.javac.util.List<AnonymousDescription> descriptions =
+                ei.anonymousClasses;
+        while (toConvert.nonEmpty() && descriptions.nonEmpty()) {
+            NewClassTree node = toConvert.head;
+            AnonymousDescription ad = descriptions.head;
+
+            toConvert = toConvert.tail;
+            descriptions = descriptions.tail;
+
+            List<Object> classBodyParts = new ArrayList<>();
+            //declarations of the captured variables:
+            for (VariableDesc vd : ad.capturedVariables) {
+                classBodyParts.add(vd.type + " " + vd.name + ";\n");
+            }
+
+            List<Object> constructorParts = new ArrayList<>();
+            constructorParts.add(ad.declareTypeName + "(");
+            String sep = "";
+            //add the parameter for the base/enclosing expression, if any:
+            if (ad.enclosingInstanceType != null) {
+                constructorParts.add(ad.enclosingInstanceType + " encl");
+                sep = ", ";
+            }
+            int idx = 0;
+            //add parameters of the super constructor, if any:
+            for (String type : ad.parameterTypes) {
+                constructorParts.add(sep);
+                constructorParts.add(type + " " + "arg" + idx++);
+                sep = ", ";
+            }
+            //add parameters for the captured variables:
+            for (VariableDesc vd : ad.capturedVariables) {
+                constructorParts.add(sep);
+                constructorParts.add(vd.type + " " + "cap$" + vd.name);
+                sep = ", ";
+            }
+            //construct super constructor call:
+            if (ad.enclosingInstanceType != null) {
+                //if there's an enclosing instance, call super on it:
+                constructorParts.add(") { encl.super (");
+            } else {
+                constructorParts.add(") { super (");
+            }
+            sep = "";
+            for (int i = 0; i < idx; i++) {
+                constructorParts.add(sep);
+                constructorParts.add("arg" + i);
+                sep = ", ";
+            }
+            constructorParts.add(");");
+            //initialize the captured variables:
+            for (VariableDesc vd : ad.capturedVariables) {
+                constructorParts.add("this." + vd.name + " = " + "cap$" + vd.name + ";\n");
+            }
+            List<? extends Tree> members =
+                    node.getClassBody().getMembers();
+            for (Tree member : members) {
+                if (member.getKind() == Tree.Kind.VARIABLE) {
+                    VariableTree vt = (VariableTree) member;
+
+                    if (vt.getInitializer() != null) {
+                        //for variables with initializer, explicitly move the initializer
+                        //to the constructor after the captured variables as assigned
+                        //(the initializers would otherwise run too early):
+                        Range wholeVar = dis.treeToRange(vt);
+                        int name = ((JCTree) vt).pos;
+                        classBodyParts.add(new CompoundWrap(Wrap.rangeWrap(compileSource,
+                                                                      new Range(wholeVar.begin, name)),
+                                                       vt.getName().toString(),
+                                                       ";\n"));
+                        constructorParts.add(Wrap.rangeWrap(compileSource,
+                                                            new Range(name, wholeVar.end)));
+                        continue;
+                    }
+                }
+                classBodyParts.add(Wrap.rangeWrap(compileSource,
+                                             dis.treeToRange(member)));
+            }
+
+            constructorParts.add("}");
+
+            //construct the member class:
+            classBodyParts.add(new CompoundWrap(constructorParts.toArray()));
+
+            Wrap classBodyWrap = new CompoundWrap(classBodyParts.toArray());
+
+            anonymousDeclarations.add(new CompoundWrap("public static class ", ad.declareTypeName,
+                                         (ad.isClass ? " extends " : " implements "),
+                                         ad.superTypeName, " { ", classBodyWrap, "}"));
+
+            //change the new class expression to use the newly created member type:
+            Range argRange = dis.treeListToRange(node.getArguments());
+            Wrap argWrap;
+
+            if (argRange != null) {
+                argWrap = Wrap.rangeWrap(compileSource, argRange);
+            } else {
+                argWrap = Wrap.simpleWrap(" ");
+            }
+
+            if (ad.enclosingInstanceType != null) {
+                //if there's an enclosing expression, set it as the first parameter:
+                Range enclosingRanges =
+                        dis.treeToRange(node.getEnclosingExpression());
+                Wrap enclosingWrap = Wrap.rangeWrap(compileSource, enclosingRanges);
+                argWrap = argRange != null ? new CompoundWrap(enclosingWrap,
+                                                              Wrap.simpleWrap(","),
+                                                              argWrap)
+                                           : enclosingWrap;
+            }
+
+            Range current = dis.treeToRange(node);
+            String capturedArgs;
+            if (!ad.capturedVariables.isEmpty()) {
+                capturedArgs = (ad.parameterTypes.isEmpty() ? "" : ", ") +
+                               ad.capturedVariables.stream()
+                                                   .map(vd -> vd.name)
+                                                   .collect(Collectors.joining(","));
+            } else {
+                capturedArgs = "";
+            }
+            if (lastPos < current.begin)
+                partitionedInit.add(Wrap.rangeWrap(compileSource,
+                                                   new Range(lastPos, current.begin)));
+            partitionedInit.add(new CompoundWrap("new " + ad.declareTypeName + "(",
+                                                 argWrap,
+                                                 capturedArgs,
+                                                 ")"));
+            lastPos = current.end;
+        }
+
+        if (lastPos < rinit.end)
+            partitionedInit.add(Wrap.rangeWrap(compileSource, new Range(lastPos, rinit.end)));
+
+        return new Pair<>(new CompoundWrap(anonymousDeclarations.toArray()),
+                          new CompoundWrap(partitionedInit.toArray()));
+    }
+
+    private List<Snippet> processExpression(String userSource, Tree tree, String compileSource, ParseTask pt) {
+        ExpressionStatementTree expr = (ExpressionStatementTree) tree;
         String name = null;
         ExpressionInfo ei = ExpressionToTypeInfo.expressionInfo(compileSource, state);
         ExpressionTree assignVar;
@@ -453,10 +588,31 @@
                         name = "$" + ++varNumber;
                     }
                 }
-                guts = Wrap.tempVarWrap(compileSource, ei.accessibleTypeName, name);
+                TreeDissector dis = TreeDissector.createByFirstClass(pt);
+                ExpressionInfo varEI =
+                        ExpressionToTypeInfo.localVariableTypeForInitializer(compileSource, state, true);
+                String declareTypeName;
+                String fullTypeName;
+                String displayTypeName;
+                Set<String> anonymousClasses;
+                if (varEI != null) {
+                    declareTypeName = varEI.declareTypeName;
+                    fullTypeName = varEI.fullTypeName;
+                    displayTypeName = varEI.displayTypeName;
+
+                    Pair<Wrap, Wrap> anonymous2Member =
+                            anonymous2Member(varEI, compileSource, new Range(0, compileSource.length()), dis, expr.getExpression());
+                    guts = Wrap.tempVarWrap(anonymous2Member.second.wrapped(), declareTypeName, name, anonymous2Member.first);
+                    anonymousClasses = varEI.anonymousClasses.stream().map(ad -> ad.declareTypeName).collect(Collectors.toSet());
+                } else {
+                    declareTypeName = ei.accessibleTypeName;
+                    displayTypeName = fullTypeName = typeName;
+                    guts = Wrap.tempVarWrap(compileSource, declareTypeName, name, null);
+                    anonymousClasses = Collections.emptySet();
+                }
                 Collection<String> declareReferences = null; //TODO
                 snip = new VarSnippet(state.keyMap.keyForVariable(name), userSource, guts,
-                        name, SubKind.TEMP_VAR_EXPRESSION_SUBKIND, typeName, declareReferences, null);
+                        name, SubKind.TEMP_VAR_EXPRESSION_SUBKIND, displayTypeName, fullTypeName, anonymousClasses, declareReferences, null);
             } else {
                 guts = Wrap.methodReturnWrap(compileSource);
                 snip = new ExpressionSnippet(state.keyMap.keyForExpression(name, typeName), userSource, guts,
@@ -1059,4 +1215,7 @@
                 : new DiagList(new ModifierDiagnostic(list, fatal));
     }
 
+    String computeDeclareName(TypeSymbol ts) {
+        return Util.JSHELL_ANONYMOUS + "$" + Long.toUnsignedString(anonCount++);
+    }
 }
--- a/src/jdk.jshell/share/classes/jdk/jshell/ExpressionToTypeInfo.java	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/jdk.jshell/share/classes/jdk/jshell/ExpressionToTypeInfo.java	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 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
@@ -25,12 +25,21 @@
 
 package jdk.jshell;
 
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Function;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ElementKind;
+import javax.lang.model.element.VariableElement;
 import com.sun.source.tree.ReturnTree;
 import com.sun.source.tree.ClassTree;
 import com.sun.source.tree.CompilationUnitTree;
 import com.sun.source.tree.ConditionalExpressionTree;
-import com.sun.source.tree.ExpressionStatementTree;
 import com.sun.source.tree.ExpressionTree;
+import com.sun.source.tree.IdentifierTree;
 import com.sun.source.tree.MethodInvocationTree;
 import com.sun.source.tree.MethodTree;
 import com.sun.source.tree.NewClassTree;
@@ -39,13 +48,21 @@
 import com.sun.source.tree.VariableTree;
 import com.sun.source.util.TreePath;
 import com.sun.source.util.TreePathScanner;
+import com.sun.source.util.TreeScanner;
 import com.sun.tools.javac.code.Flags;
 import com.sun.tools.javac.code.Symbol;
+import com.sun.tools.javac.code.Symbol.TypeSymbol;
 import com.sun.tools.javac.code.Symtab;
 import com.sun.tools.javac.code.Type;
 import com.sun.tools.javac.code.Types;
+import com.sun.tools.javac.tree.JCTree.JCClassDecl;
+import com.sun.tools.javac.tree.TreeInfo;
 import com.sun.tools.javac.util.List;
+import com.sun.tools.javac.util.ListBuffer;
+import jdk.jshell.ExpressionToTypeInfo.ExpressionInfo.AnonymousDescription;
+import jdk.jshell.ExpressionToTypeInfo.ExpressionInfo.AnonymousDescription.VariableDesc;
 import jdk.jshell.TaskFactory.AnalyzeTask;
+import jdk.jshell.TypePrinter.AnonymousTypeKind;
 
 /**
  * Compute information about an expression string, particularly its type name.
@@ -57,26 +74,75 @@
     final AnalyzeTask at;
     final CompilationUnitTree cu;
     final JShell state;
+    final boolean computeEnhancedInfo;
+    final boolean enhancedTypesAccessible;
     final Symtab syms;
     final Types types;
+    final Map<TypeSymbol, String> anon2Name = new HashMap<>();
 
-    private ExpressionToTypeInfo(AnalyzeTask at, CompilationUnitTree cu, JShell state) {
+    private ExpressionToTypeInfo(AnalyzeTask at, CompilationUnitTree cu, JShell state,
+                                 boolean computeEnhancedInfo, boolean enhancedTypesAccessible) {
         this.at = at;
         this.cu = cu;
         this.state = state;
+        this.computeEnhancedInfo = computeEnhancedInfo;
+        this.enhancedTypesAccessible = enhancedTypesAccessible;
         this.syms = Symtab.instance(at.context);
         this.types = Types.instance(at.context);
     }
 
     public static class ExpressionInfo {
         ExpressionTree tree;
+        boolean isPrimitiveType;
         String typeName;
         String accessibleTypeName;
+        /* In result of localVariableTypeForInitializer, the type that should be used
+         * as a declaration type of the field. This does not include intersection types,
+         * but does contain references to anonymous types converted to member types.
+         */
+        String declareTypeName;
+        /* In result of localVariableTypeForInitializer, the apparent/infered type of
+         * the variable. This includes intersection types, and references to anonymous
+         * types converted to member types.
+         */
         String fullTypeName;
-        List<String> parameterTypes;
-        String enclosingInstanceType;
-        boolean isClass;
+        /* In result of localVariableTypeForInitializer, the human readable type of
+         * the variable. This includes intersection types, and human readable descriptions
+         * of anonymous types.
+         */
+        String displayTypeName;
         boolean isNonVoid;
+        /* In result of localVariableTypeForInitializer, description of important anonymous
+         * classes.
+         */
+        List<AnonymousDescription> anonymousClasses = List.nil();
+
+        /* A description of an anonymous class. */
+        static class AnonymousDescription {
+            /* Parameter types of the invoked super constructor.*/
+            List<String> parameterTypes;
+            /* Type of the base/enclosing expression, if any.*/
+            String enclosingInstanceType;
+            /* The denotable name of the supertype.*/
+            String superTypeName;
+            /* The human-readable name of this class.*/
+            String declareTypeName;
+            /* If the supertype of this anonymous is a class. */
+            boolean isClass;
+            /* Variables captured by this anonymous class*/
+            List<VariableDesc> capturedVariables;
+
+            static class VariableDesc {
+                String type;
+                String name;
+
+                public VariableDesc(String type, String name) {
+                    this.type = type;
+                    this.name = name;
+                }
+
+            }
+        }
     }
 
     // return mechanism and other general structure from TreePath.getPath()
@@ -173,7 +239,7 @@
                 if (at.hasErrors() || cu == null) {
                     return null;
                 }
-                return new ExpressionToTypeInfo(at, cu, state).typeOfExpression();
+                return new ExpressionToTypeInfo(at, cu, state, false, false).typeOfExpression();
             });
         } catch (Exception ex) {
             return null;
@@ -187,7 +253,7 @@
      * @param state a JShell instance
      * @return type information
      */
-    public static ExpressionInfo localVariableTypeForInitializer(String code, JShell state) {
+    public static ExpressionInfo localVariableTypeForInitializer(String code, JShell state, boolean onlyAccessible) {
         if (code == null || code.isEmpty()) {
             return null;
         }
@@ -198,13 +264,37 @@
                 if (at.hasErrors() || cu == null) {
                     return null;
                 }
-                return new ExpressionToTypeInfo(at, cu, state).typeOfExpression();
+                return new ExpressionToTypeInfo(at, cu, state, true, onlyAccessible)
+                        .typeOfExpression();
             });
         } catch (Exception ex) {
             return null;
         }
     }
 
+    /**List (in a stable order) all NewClassTree instances under {@code from} that should be
+     * converted to member classes
+     *
+     * @param from tree to inspect
+     * @return NewClassTree instances that should be converted to member classes
+     */
+    public static List<NewClassTree> listAnonymousClassesToConvert(Tree from) {
+        ListBuffer<NewClassTree> classes = new ListBuffer<>();
+
+        new TreeScanner<Void, Void>() {
+            @Override
+            public Void visitNewClass(NewClassTree node, Void p) {
+                if (node.getClassBody() != null) {
+                    classes.append(node);
+                    return null;
+                }
+                return super.visitNewClass(node, p);
+            }
+        }.scan(from, null);
+
+        return classes.toList();
+    }
+
     private ExpressionInfo typeOfExpression() {
         return treeToInfo(findExpressionPath());
     }
@@ -256,23 +346,31 @@
      * @return the type, if it is accessible, otherwise a superclass or
      * interface which is
      */
-    private Type findAccessibleSupertype(Type type) {
+    private List<Type> findAccessibleSupertypes(Type type) {
+        List<Type> accessible = List.nil();
+        Type accessibleSuper = syms.objectType;
         // Iterate up the superclasses, see if any are accessible
         for (Type sup = type; !types.isSameType(sup, syms.objectType); sup = supertype(sup)) {
             if (isAccessible(sup)) {
-                return sup;
+                accessible = accessible.prepend(sup);
+                accessibleSuper = sup;
+                break;
             }
         }
-        // Failing superclasses, look through superclasses for accessible interfaces
-        for (Type sup = type; !types.isSameType(sup, syms.objectType); sup = supertype(sup)) {
+        // then look through superclasses for accessible interfaces
+        for (Type sup = type; !types.isSameType(sup, accessibleSuper); sup = supertype(sup)) {
             for (Type itf : types.interfaces(sup)) {
                 if (isAccessible(itf)) {
-                    return itf;
+                    accessible = accessible.prepend(itf);
                 }
             }
         }
-        // Punt, return Object which is the supertype of everything
-        return syms.objectType;
+        if (accessible.isEmpty()) {
+            // Punt, use Object which is the supertype of everything
+            accessible = accessible.prepend(syms.objectType);
+        }
+
+        return accessible.reverse();
     }
 
     private ExpressionInfo treeToInfo(TreePath tp) {
@@ -298,48 +396,125 @@
                             break;
                         default: {
                             ei.isNonVoid = true;
-                            ei.typeName = varTypeName(type, false);
-                            ei.accessibleTypeName = varTypeName(findAccessibleSupertype(type), false);
-                            ei.fullTypeName = varTypeName(type, true);
+                            ei.isPrimitiveType = type.isPrimitive();
+                            ei.typeName = varTypeName(type, false, AnonymousTypeKind.SUPER);
+                            List<Type> accessibleTypes = findAccessibleSupertypes(type);
+                            ei.accessibleTypeName =
+                                    varTypeName(accessibleTypes.head, false, AnonymousTypeKind.SUPER);
+                            if (computeEnhancedInfo) {
+                                Type accessibleType = accessibleTypes.size() == 1 ? accessibleTypes.head
+                                            : types.makeIntersectionType(accessibleTypes);
+                                ei.declareTypeName =
+                                        varTypeName(accessibleType, false, AnonymousTypeKind.DECLARE);
+                                ei.fullTypeName =
+                                        varTypeName(enhancedTypesAccessible ? accessibleType : type,
+                                                    true, AnonymousTypeKind.DECLARE);
+                                ei.displayTypeName =
+                                        varTypeName(type, true, AnonymousTypeKind.DISPLAY);
+                            }
                             break;
                         }
                     }
                 }
-                if (tree.getKind() == Tree.Kind.VARIABLE) {
+                if (tree.getKind() == Tree.Kind.VARIABLE && computeEnhancedInfo) {
                     Tree init = ((VariableTree) tree).getInitializer();
-                    if (init.getKind() == Tree.Kind.NEW_CLASS &&
-                        ((NewClassTree) init).getClassBody() != null) {
-                        NewClassTree nct = (NewClassTree) init;
-                        ClassTree clazz = nct.getClassBody();
-                        MethodTree constructor = (MethodTree) clazz.getMembers().get(0);
-                        ExpressionStatementTree superCallStatement =
-                                (ExpressionStatementTree) constructor.getBody().getStatements().get(0);
+                    for (NewClassTree node : listAnonymousClassesToConvert(init)) {
+                        Set<VariableElement> captured = capturedVariables(at,
+                                                                          tp.getCompilationUnit(),
+                                                                          node);
+                        JCClassDecl clazz = (JCClassDecl) node.getClassBody();
                         MethodInvocationTree superCall =
-                                (MethodInvocationTree) superCallStatement.getExpression();
-                        TreePath superCallPath =
-                                at.trees().getPath(tp.getCompilationUnit(), superCall.getMethodSelect());
+                                clazz.getMembers()
+                                     .stream()
+                                     .map(TreeInfo::firstConstructorCall)
+                                     .findAny()
+                                     .get();
+                        TreePath superCallPath
+                                = at.trees().
+                                        getPath(tp.getCompilationUnit(), superCall.
+                                                getMethodSelect());
                         Type constrType = pathToType(superCallPath);
-                        ei.parameterTypes = constrType.getParameterTypes()
-                                                      .stream()
-                                                      .map(t -> varTypeName(t, false))
-                                                      .collect(List.collector());
-                        if (nct.getEnclosingExpression() != null) {
-                            TreePath enclPath = new TreePath(tp, nct.getEnclosingExpression());
-                            ei.enclosingInstanceType = varTypeName(pathToType(enclPath), false);
+                        AnonymousDescription desc = new AnonymousDescription();
+                        desc.parameterTypes = constrType.getParameterTypes().
+                                stream().
+                                map(t -> varTypeName(t, false, AnonymousTypeKind.DECLARE)).
+                                collect(List.collector());
+                        if (node.getEnclosingExpression() != null) {
+                            TreePath enclPath = new TreePath(tp,
+                                                             node.getEnclosingExpression());
+                            desc.enclosingInstanceType = varTypeName(pathToType(enclPath),
+                                                                     false,
+                                                                     AnonymousTypeKind.DECLARE);
                         }
-                        ei.isClass = at.task.getTypes().directSupertypes(type).size() == 1;
+                        TreePath currentPath = at.trees()
+                                                 .getPath(tp.getCompilationUnit(),
+                                                          node);
+                        Type nodeType = pathToType(currentPath, node);
+                        desc.superTypeName = varTypeName(nodeType,
+                                                         false,
+                                                         AnonymousTypeKind.SUPER);
+                        desc.declareTypeName = varTypeName(nodeType,
+                                                           true, AnonymousTypeKind.DECLARE);
+                        desc.capturedVariables =
+                                captured.stream()
+                                        .map(ve -> new VariableDesc(varTypeName((Type) ve.asType(),
+                                                                                false,
+                                                                                AnonymousTypeKind.DECLARE),
+                                                                    ve.getSimpleName().toString()))
+                                        .collect(List.collector());
+
+                        desc.isClass = at.task.getTypes().directSupertypes(nodeType).size() == 1;
+                        ei.anonymousClasses = ei.anonymousClasses.prepend(desc);
                     }
+                    ei.anonymousClasses = ei.anonymousClasses.reverse();
                 }
                 return ei;
             }
         }
         return null;
     }
+    //where:
+        private static Set<VariableElement> capturedVariables(AnalyzeTask at,
+                                                              CompilationUnitTree topLevel,
+                                                              Tree tree) {
+            Set<VariableElement> capturedVars = new HashSet<>();
+            new TreeScanner<Void, Void>() {
+                Set<VariableElement> declaredLocalVars = new HashSet<>();
+                @Override
+                public Void visitVariable(VariableTree node, Void p) {
+                    TreePath currentPath = at.trees()
+                                             .getPath(topLevel, node);
+                    declaredLocalVars.add((VariableElement) at.trees().getElement(currentPath));
+                    return super.visitVariable(node, p);
+                }
 
-    private String varTypeName(Type type, boolean printIntersectionTypes) {
+                @Override
+                public Void visitIdentifier(IdentifierTree node, Void p) {
+                    TreePath currentPath = at.trees()
+                                             .getPath(topLevel, node);
+                    Element el = at.trees().getElement(currentPath);
+                    if (el != null &&
+                        LOCAL_VARIABLES.contains(el.getKind()) &&
+                        !declaredLocalVars.contains(el)) {
+                        capturedVars.add((VariableElement) el);
+                    }
+                    return super.visitIdentifier(node, p);
+                }
+            }.scan(tree, null);
+
+            return capturedVars;
+        }
+        private static final Set<ElementKind> LOCAL_VARIABLES =
+                EnumSet.of(ElementKind.EXCEPTION_PARAMETER, ElementKind.LOCAL_VARIABLE,
+                           ElementKind.PARAMETER, ElementKind.RESOURCE_VARIABLE);
+
+    private String varTypeName(Type type, boolean printIntersectionTypes, AnonymousTypeKind anonymousTypesKind) {
         try {
+            Function<TypeSymbol, String> anonymousClass2DeclareName =
+                    cs -> anon2Name.computeIfAbsent(cs, state.eval::computeDeclareName);
             TypePrinter tp = new TypePrinter(at.messages(),
-                    state.maps::fullClassNameAndPackageToClass, printIntersectionTypes);
+                    state.maps::fullClassNameAndPackageToClass, anonymousClass2DeclareName,
+                    printIntersectionTypes, anonymousTypesKind);
             List<Type> captures = types.captures(type);
             String res = tp.toString(types.upward(type, captures));
 
--- a/src/jdk.jshell/share/classes/jdk/jshell/TaskFactory.java	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/jdk.jshell/share/classes/jdk/jshell/TaskFactory.java	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 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
@@ -61,24 +61,33 @@
 import java.lang.Runtime.Version;
 import java.nio.CharBuffer;
 import java.util.function.BiFunction;
+import com.sun.source.tree.ClassTree;
 import com.sun.source.tree.Tree.Kind;
 import com.sun.source.util.TaskEvent;
 import com.sun.source.util.TaskListener;
 import com.sun.tools.javac.api.JavacTaskPool;
 import com.sun.tools.javac.code.ClassFinder;
 import com.sun.tools.javac.code.Kinds;
+import com.sun.tools.javac.code.Symbol;
 import com.sun.tools.javac.code.Symbol.ClassSymbol;
 import com.sun.tools.javac.code.Symbol.PackageSymbol;
+import com.sun.tools.javac.code.Symbol.TypeSymbol;
 import com.sun.tools.javac.code.Symbol.VarSymbol;
 import com.sun.tools.javac.code.Symtab;
+import com.sun.tools.javac.code.Type;
 import com.sun.tools.javac.comp.Attr;
+import com.sun.tools.javac.comp.AttrContext;
+import com.sun.tools.javac.comp.Enter;
+import com.sun.tools.javac.comp.Env;
+import com.sun.tools.javac.comp.Resolve;
 import com.sun.tools.javac.parser.Parser;
 import com.sun.tools.javac.parser.ParserFactory;
-import com.sun.tools.javac.tree.JCTree.JCClassDecl;
 import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
 import com.sun.tools.javac.tree.JCTree.JCExpression;
 import com.sun.tools.javac.tree.JCTree.JCTypeCast;
+import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
 import com.sun.tools.javac.tree.JCTree.Tag;
+import com.sun.tools.javac.util.Context.Factory;
 import com.sun.tools.javac.util.Log;
 import com.sun.tools.javac.util.Log.DiscardDiagnosticHandler;
 import com.sun.tools.javac.util.Names;
@@ -197,6 +206,7 @@
                                          compilationUnits, task -> {
                  JavacTaskImpl jti = (JavacTaskImpl) task;
                  Context context = jti.getContext();
+                 DisableAccessibilityResolve.preRegister(context);
                  jti.addTaskListener(new TaskListenerImpl(context, state));
                  try {
                      return worker.withTask(creator.apply(jti, diagnostics));
@@ -578,10 +588,25 @@
         }
     }
 
+    /**The variable types inferred for "var"s may be non-denotable.
+     * jshell desugars these variables into fields, and fields must have
+     * a denotable type. So these fields are declared with some simpler denotable
+     * type, and the listener here enhances the types of the fields to be the full
+     * inferred types. This is mainly when the inferred type contains:
+     * -intersection types (e.g. <Z extends Runnable&CharSequence> Z get() {...} var z = get();)
+     * -types that are inaccessible at the given place
+     *
+     * This type enhancement does not need to do anything about anonymous classes, as these
+     * are desugared into member classes.
+     */
     private static final class TaskListenerImpl implements TaskListener {
 
         private final Context context;
         private final JShell state;
+        /* Keep the original (declaration) types of the fields that were enhanced.
+         * The declaration types need to be put back before writing the fields
+         * into classfiles.*/
+        private final Map<VarSymbol, Type> var2OriginalType = new HashMap<>();
 
         public TaskListenerImpl(Context context, JShell state) {
             this.context = context;
@@ -589,43 +614,85 @@
         }
 
         @Override
+        public void started(TaskEvent e) {
+            if (e.getKind() != TaskEvent.Kind.GENERATE)
+                return ;
+            //clear enhanced types in fields we are about to write to the classfiles:
+            for (Tree clazz : e.getCompilationUnit().getTypeDecls()) {
+                ClassTree ct = (ClassTree) clazz;
+
+                for (Tree member : ct.getMembers()) {
+                    if (member.getKind() != Tree.Kind.VARIABLE)
+                        continue;
+                    VarSymbol vsym = ((JCVariableDecl) member).sym;
+                    Type original = var2OriginalType.remove(vsym);
+                    if (original != null) {
+                        vsym.type = original;
+                    }
+                }
+            }
+        }
+
+        private boolean variablesSet = false;
+
+        @Override
         public void finished(TaskEvent e) {
-            if (e.getKind() != TaskEvent.Kind.ENTER)
+            if (e.getKind() != TaskEvent.Kind.ENTER || variablesSet)
                 return ;
             state.maps
                  .snippetList()
                  .stream()
                  .filter(s -> s.status() == Status.VALID)
                  .filter(s -> s.kind() == Snippet.Kind.VAR)
-                 .filter(s -> s.subKind() == Snippet.SubKind.VAR_DECLARATION_WITH_INITIALIZER_SUBKIND)
-                 .forEach(s -> setVariableType((JCCompilationUnit) e.getCompilationUnit(), (VarSnippet) s));
+                 .filter(s -> s.subKind() == Snippet.SubKind.VAR_DECLARATION_WITH_INITIALIZER_SUBKIND ||
+                              s.subKind() == Snippet.SubKind.TEMP_VAR_EXPRESSION_SUBKIND)
+                 .forEach(s -> setVariableType((VarSnippet) s));
+            variablesSet = true;
         }
 
-        private void setVariableType(JCCompilationUnit root, VarSnippet s) {
+        /* If the snippet contain enhanced types, enhance the type of
+         * the variable from snippet s to be the enhanced type.
+         */
+        private void setVariableType(VarSnippet s) {
+            String typeName = s.fullTypeName;
+
+            if (typeName == null)
+                return ;
+
             Symtab syms = Symtab.instance(context);
             Names names = Names.instance(context);
             Log log  = Log.instance(context);
             ParserFactory parserFactory = ParserFactory.instance(context);
             Attr attr = Attr.instance(context);
+            Enter enter = Enter.instance(context);
+            DisableAccessibilityResolve rs = (DisableAccessibilityResolve) Resolve.instance(context);
 
+            //find the variable:
             ClassSymbol clazz = syms.getClass(syms.unnamedModule, names.fromString(s.classFullName()));
             if (clazz == null || !clazz.isCompleted())
                 return;
             VarSymbol field = (VarSymbol) clazz.members().findFirst(names.fromString(s.name()), sym -> sym.kind == Kinds.Kind.VAR);
-            if (field != null) {
+
+            if (field != null && !var2OriginalType.containsKey(field)) {
+                //if it was not enhanced yet:
+                //ignore any errors:
                 JavaFileObject prev = log.useSource(null);
                 DiscardDiagnosticHandler h = new DiscardDiagnosticHandler(log);
                 try {
-                    String typeName = s.typeName();
+                    //parse the type as a cast, i.e. "(<typeName>) x". This is to support
+                    //intersection types:
                     CharBuffer buf = CharBuffer.wrap(("(" + typeName +")x\u0000").toCharArray(), 0, typeName.length() + 3);
                     Parser parser = parserFactory.newParser(buf, false, false, false);
                     JCExpression expr = parser.parseExpression();
                     if (expr.hasTag(Tag.TYPECAST)) {
+                        //if parsed OK, attribute and set the type:
+                        var2OriginalType.put(field, field.type);
+
                         JCTypeCast tree = (JCTypeCast) expr;
-                        if (tree.clazz.hasTag(Tag.TYPEINTERSECTION)) {
+                        rs.runWithoutAccessChecks(() -> {
                             field.type = attr.attribType(tree.clazz,
-                                                         ((JCClassDecl) root.getTypeDecls().head).sym);
-                        }
+                                                         enter.getEnvs().iterator().next().enclClass.sym);
+                        });
                     }
                 } finally {
                     log.popDiagnosticHandler(h);
@@ -635,4 +702,48 @@
         }
     }
 
+    private static final class DisableAccessibilityResolve extends Resolve {
+
+        public static void preRegister(Context context) {
+            if (context.get(Marker.class) == null) {
+                context.put(resolveKey, ((Factory<Resolve>) c -> new DisableAccessibilityResolve(c)));
+                context.put(Marker.class, new Marker());
+            }
+        }
+
+        private boolean noAccessChecks;
+
+        public DisableAccessibilityResolve(Context context) {
+            super(context);
+        }
+
+        /**Run the given Runnable with all access checks disabled.
+         *
+         * @param r Runnnable to run
+         */
+        public void runWithoutAccessChecks(Runnable r) {
+            boolean prevNoAccessCheckes = noAccessChecks;
+            try {
+                noAccessChecks = true;
+                r.run();
+            } finally {
+                noAccessChecks = prevNoAccessCheckes;
+            }
+        }
+
+        @Override
+        public boolean isAccessible(Env<AttrContext> env, TypeSymbol c, boolean checkInner) {
+            if (noAccessChecks) return true;
+            return super.isAccessible(env, c, checkInner);
+        }
+
+        @Override
+        public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym, boolean checkInner) {
+            if (noAccessChecks) return true;
+            return super.isAccessible(env, site, sym, checkInner);
+        }
+
+        private static final class Marker {}
+    }
+
 }
--- a/src/jdk.jshell/share/classes/jdk/jshell/TreeDissector.java	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/jdk.jshell/share/classes/jdk/jshell/TreeDissector.java	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 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
@@ -48,6 +48,7 @@
 import java.util.function.Predicate;
 import java.util.stream.Stream;
 import javax.lang.model.type.TypeMirror;
+import jdk.jshell.TypePrinter.AnonymousTypeKind;
 import jdk.jshell.Util.Pair;
 
 /**
@@ -227,7 +228,7 @@
         Type typeImpl = (Type) type;
         try {
             TypePrinter tp = new TypePrinter(at.messages(),
-                    state.maps::fullClassNameAndPackageToClass, true);
+                    state.maps::fullClassNameAndPackageToClass, true, AnonymousTypeKind.DISPLAY);
             return tp.toString(typeImpl);
         } catch (Exception ex) {
             return null;
--- a/src/jdk.jshell/share/classes/jdk/jshell/TypePrinter.java	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/jdk.jshell/share/classes/jdk/jshell/TypePrinter.java	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -30,14 +30,17 @@
 import com.sun.tools.javac.code.Symbol;
 import com.sun.tools.javac.code.Symbol.ClassSymbol;
 import com.sun.tools.javac.code.Symbol.PackageSymbol;
+import com.sun.tools.javac.code.Symbol.TypeSymbol;
 import com.sun.tools.javac.code.Type;
 import com.sun.tools.javac.code.Type.ClassType;
 import com.sun.tools.javac.code.Type.IntersectionClassType;
 import com.sun.tools.javac.util.JavacMessages;
 import java.util.Locale;
 import java.util.function.BinaryOperator;
+import java.util.function.Function;
 import java.util.stream.Collectors;
 
+
 /**
  * Print types in source form.
  */
@@ -47,14 +50,44 @@
 
     private final JavacMessages messages;
     private final BinaryOperator<String> fullClassNameAndPackageToClass;
-    private final boolean printEnhancedTypes;
+    private final Function<TypeSymbol, String> anonymousToName;
+    private final boolean printIntersectionTypes;
+    private final AnonymousTypeKind anonymousTypesKind;
 
+    /**Create a TypePrinter.
+     *
+     * @param messages javac's messages
+     * @param fullClassNameAndPackageToClass convertor to convert full class names to
+     *                                       simple class names.
+     * @param printIntersectionTypes whether intersection types should be printed
+     * @param anonymousTypesKind how the anonymous types should be printed
+     */
     TypePrinter(JavacMessages messages,
                 BinaryOperator<String> fullClassNameAndPackageToClass,
-                boolean printEnhancedTypes) {
+                boolean printIntersectionTypes, AnonymousTypeKind anonymousTypesKind) {
+        this(messages, fullClassNameAndPackageToClass, cs -> cs.flatName().toString(),
+             printIntersectionTypes, anonymousTypesKind);
+    }
+
+    /**Create a TypePrinter.
+     *
+     * @param messages javac's messages
+     * @param fullClassNameAndPackageToClass convertor to convert full class names to
+     *                                       simple class names.
+     * @param anonymousToName convertor from anonymous classes to name that should be printed
+     *                        if anonymousTypesKind == AnonymousTypeKind.DECLARE
+     * @param printIntersectionTypes whether intersection types should be printed
+     * @param anonymousTypesKind how the anonymous types should be printed
+     */
+    TypePrinter(JavacMessages messages,
+                BinaryOperator<String> fullClassNameAndPackageToClass,
+                Function<TypeSymbol, String> anonymousToName,
+                boolean printIntersectionTypes, AnonymousTypeKind anonymousTypesKind) {
         this.messages = messages;
         this.fullClassNameAndPackageToClass = fullClassNameAndPackageToClass;
-        this.printEnhancedTypes = printEnhancedTypes;
+        this.anonymousToName = anonymousToName;
+        this.printIntersectionTypes = printIntersectionTypes;
+        this.anonymousTypesKind = anonymousTypesKind;
     }
 
     String toString(Type t) {
@@ -96,9 +129,9 @@
      */
     @Override
     protected String className(ClassType t, boolean longform, Locale locale) {
-        Symbol sym = t.tsym;
+        TypeSymbol sym = t.tsym;
         if (sym.name.length() == 0 && (sym.flags() & COMPOUND) != 0) {
-            if (printEnhancedTypes) {
+            if (printIntersectionTypes) {
                 return ((IntersectionClassType) t).getExplicitComponents()
                                                   .stream()
                                                   .map(i -> visit(i, locale))
@@ -107,18 +140,26 @@
                 return OBJECT;
             }
         } else if (sym.name.length() == 0) {
-            if (printEnhancedTypes) {
-                return t.tsym.flatName().toString().substring(t.tsym.outermostClass().flatName().length());
+            if (anonymousTypesKind == AnonymousTypeKind.DECLARE) {
+                return anonymousToName.apply(sym);
             }
             // Anonymous
             String s;
+            boolean isClass;
             ClassType norm = (ClassType) t.tsym.type;
             if (norm == null) {
                 s = OBJECT;
+                isClass = true;
             } else if (norm.interfaces_field != null && norm.interfaces_field.nonEmpty()) {
                 s = visit(norm.interfaces_field.head, locale);
+                isClass = false;
             } else {
                 s = visit(norm.supertype_field, locale);
+                isClass = true;
+            }
+            if (anonymousTypesKind == AnonymousTypeKind.DISPLAY) {
+                s = isClass ? "<anonymous class extending " + s + ">"
+                            : "<anonymous class implementing " + s + ">";
             }
             return s;
         } else if (longform) {
@@ -152,4 +193,14 @@
                 : s.fullname.toString();
     }
 
+    /** Specifies how the anonymous classes should be handled. */
+    public enum AnonymousTypeKind {
+        /* The anonymous class is printed as the name of its supertype. */
+        SUPER,
+        /* The anonymous class is printed as converted by the anonymousToName
+         * convertor. */
+        DECLARE,
+        /* The anonymous class is printed in a human readable form. */
+        DISPLAY;
+    }
 }
--- a/src/jdk.jshell/share/classes/jdk/jshell/Util.java	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/jdk.jshell/share/classes/jdk/jshell/Util.java	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 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
@@ -56,6 +56,11 @@
     static final String DOIT_METHOD_NAME = "do_it$";
 
     /**
+     * The prefix for all anonymous classes upgraded to member classes.
+     */
+    static final String JSHELL_ANONYMOUS = "$JShell$anonymous$";
+
+    /**
      * A pattern matching the full or simple class name of a wrapper class.
      */
     static final Pattern PREFIX_PATTERN = Pattern.compile(
--- a/src/jdk.jshell/share/classes/jdk/jshell/VarSnippet.java	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/jdk.jshell/share/classes/jdk/jshell/VarSnippet.java	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,6 +26,8 @@
 package jdk.jshell;
 
 import java.util.Collection;
+import java.util.Set;
+import java.util.stream.Collectors;
 import jdk.jshell.Key.VarKey;
 
 /**
@@ -41,15 +43,30 @@
  */
 public class VarSnippet extends DeclarationSnippet {
 
+    /**A human readable type of the variable. May include intersection types
+     * and human readable description of anonymous classes.
+     */
     final String typeName;
 
+    /**The full type inferred for "var" variables. May include intersection types
+     * and inaccessible types. {@literal null} if enhancing the type is not necessary.
+     */
+    final String fullTypeName;
+
+    /**The anonymous class declared in the initializer of the "var" variable.
+     * These are automatically statically imported when the field is imported.
+     */
+    final Set<String> anonymousClasses;
+
      VarSnippet(VarKey key, String userSource, Wrap guts,
-            String name, SubKind subkind, String typeName,
-            Collection<String> declareReferences,
+            String name, SubKind subkind, String typeName, String fullTypeName,
+            Set<String> anonymousClasses, Collection<String> declareReferences,
             DiagList syntheticDiags) {
         super(key, userSource, guts, name, subkind, null, declareReferences,
                 null, syntheticDiags);
         this.typeName = typeName;
+        this.fullTypeName = fullTypeName;
+        this.anonymousClasses = anonymousClasses;
     }
 
     /**
@@ -59,4 +76,13 @@
     public String typeName() {
         return typeName;
     }
+
+    @Override
+    String importLine(JShell state) {
+        return "import static " + classFullName() + "." + name() + ";\n" +
+               anonymousClasses.stream()
+                               .map(c -> "import static " + classFullName() + "." + c + ";\n")
+                               .collect(Collectors.joining());
+    }
+
 }
--- a/src/jdk.jshell/share/classes/jdk/jshell/Wrap.java	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/jdk.jshell/share/classes/jdk/jshell/Wrap.java	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,7 +25,9 @@
 
 package jdk.jshell;
 
+import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.List;
 import static java.util.stream.Collectors.joining;
 import static jdk.jshell.Util.DOIT_METHOD_NAME;
 
@@ -66,37 +68,76 @@
         return "\n" + indent(n);
     }
 
-    /**
+    /**Create a stub of a compilable representation of a variable snippet.
+     * The variable is always represented by a field. If the variable
+     * in the snippet has an initializer, the field is initialized by
+     * calling the DOIT_METHOD_NAME method.
      *
-     * @param in
-     * @param rname
-     * @param rinit Initializer or null
-     * @param rdecl Type name and name
-     * @return
+     * In some cases, the real inferred type of the variable may be non-denotable
+     * (e.g. intersection types). The declared type of the field must always
+     * be denotable (i.e. such that it can be written into the classfile), but
+     * if the real type is potentially non-denotable, the {@code enhanced} parameter
+     * must be true.
+     *
+     * @param source the snippet's masked source code
+     * @param wtype variable's denotable type suitable for field declaration
+     * @param brackets any [] that should be appended to the type
+     * @param rname range in source that denotes the name of the
+     * @param winit Initializer or null
+     * @param enhanced if the real inferred type of the variable is potentially
+     *                 non-denotable, this must be true
+     * @return a Wrap that declares the given variable, potentially with
+     *         an initialization method
      */
     public static Wrap varWrap(String source, Wrap wtype, String brackets,
-                               Range rname, Wrap winit, Wrap anonDeclareWrap) {
+                               Range rname, Wrap winit, boolean enhanced,
+                               Wrap anonDeclareWrap) {
         RangeWrap wname = new RangeWrap(source, rname);
-        Wrap wVarDecl = new VarDeclareWrap(wtype, brackets, wname);
+        List<Object> components = new ArrayList<>();
+        components.add(new VarDeclareWrap(wtype, brackets, wname));
         Wrap wmeth;
 
         if (winit == null) {
             wmeth = new CompoundWrap(new NoWrap(" "), "   return null;\n");
         } else {
-        // int x = y
-            // int x_ = y; return x = x_;
-            // decl + "_ = " + init ; + "return " + name + "=" + name + "_ ;"
-            wmeth = new CompoundWrap(
-                    wtype, brackets + " ", wname, "_ =\n        ", winit, semi(winit),
-                    "        return ", wname, " = ", wname, "_;\n"
-            );
+            // int x = y
+            if (enhanced) {
+                // private static <Z> Z do_itAux() {
+                //     wtype x_ = y;
+                //     @SuppressWarnings("unchecked")
+                //     Z x__ = (Z) x_;
+                //     return x__;
+                // }
+                // in do_it method:
+                //return do_itAux();
+                Wrap waux = new CompoundWrap(
+                        "    private static <Z> Z ", DOIT_METHOD_NAME + "Aux", "() throws Throwable {\n",
+                        wtype, brackets + " ", wname, "_ =\n        ", winit, semi(winit),
+                        "        @SuppressWarnings(\"unchecked\") Z ", wname, "__ = (Z)", wname, "_;\n",
+                        "        return ", wname, "__;\n",
+                        "}"
+                );
+                components.add(waux);
+                wmeth = new CompoundWrap(
+                        "        return ", wname, " = ", DOIT_METHOD_NAME + "Aux", "();\n"
+                );
+            } else {
+                // int x_ = y; return x = x_;
+                // decl + "_ = " + init ; + "return " + name + "= " + name + "_ ;"
+                wmeth = new CompoundWrap(
+                        wtype, brackets + " ", wname, "_ =\n        ", winit, semi(winit),
+                        "        return ", wname, " = ", wname, "_;\n"
+                );
+            }
         }
-        Wrap wInitMeth = new DoitMethodWrap(wmeth);
-        return anonDeclareWrap != null ? new CompoundWrap(wVarDecl, wInitMeth, anonDeclareWrap)
-                                       : new CompoundWrap(wVarDecl, wInitMeth);
+        components.add(new DoitMethodWrap(wmeth));
+        if (anonDeclareWrap != null) {
+            components.add(anonDeclareWrap);
+        }
+        return new CompoundWrap(components.toArray());
     }
 
-    public static Wrap tempVarWrap(String source, String typename, String name) {
+    public static Wrap tempVarWrap(String source, String typename, String name, Wrap anonDeclareWrap) {
         RangeWrap winit = new NoWrap(source);
         // y
         // return $1 = y;
@@ -105,7 +146,8 @@
         Wrap wInitMeth = new DoitMethodWrap(wmeth);
 
         String varDecl = "    public static\n    " + typename + " " + name + ";\n";
-        return new CompoundWrap(varDecl, wInitMeth);
+        return anonDeclareWrap != null ? new CompoundWrap(varDecl, wInitMeth, anonDeclareWrap)
+                                       : new CompoundWrap(varDecl, wInitMeth);
     }
 
     public static Wrap simpleWrap(String source) {
--- a/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/api/tree/IRTranslator.java	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/api/tree/IRTranslator.java	Mon Jan 22 16:55:01 2018 +0100
@@ -473,9 +473,9 @@
     @Override
     public boolean enterClassNode(final ClassNode classNode) {
         assert !classNode.isStatement(): "should not reach here for class declaration";
-
+        final IdentNode className = classNode.getIdent();
         curExpr = new ClassExpressionTreeImpl(classNode,
-            translateIdent(classNode.getIdent()),
+            className != null? translateIdent(className) : null,
             translateExpr(classNode.getClassHeritage()),
             translateProperty(classNode.getConstructor()),
             translateProperties(classNode.getClassElements()));
--- a/src/utils/LogCompilation/src/main/java/com/sun/hotspot/tools/compiler/CallSite.java	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/utils/LogCompilation/src/main/java/com/sun/hotspot/tools/compiler/CallSite.java	Mon Jan 22 16:55:01 2018 +0100
@@ -105,6 +105,11 @@
     private List<UncommonTrap> traps;
 
     /**
+     * The name of the intrinsic at this call site.
+     */
+    private String intrinsicName;
+
+    /**
      * Default constructor: used to create an instance that represents the top
      * scope of a compilation.
      */
@@ -179,6 +184,7 @@
         } else {
             stream.print("  @ " + getBci() + " " + m + " " + getReason());
         }
+        stream.print(getIntrinsicOrEmptyString());
         stream.printf(" (end time: %6.4f", getTimeStamp());
         if (getEndNodes() > 0) {
             stream.printf(" nodes: %d live: %d", getEndNodes(), getEndLiveNodes());
@@ -368,4 +374,19 @@
     public void setInlineId(long inlineId) {
         this.inlineId = inlineId;
     }
+
+    public String getIntrinsicName() {
+        return intrinsicName;
+    }
+
+    public void setIntrinsicName(String name) {
+        this.intrinsicName = name;
+    }
+
+    public String getIntrinsicOrEmptyString() {
+        if (intrinsicName != null) {
+            return " (intrinsic: " + getIntrinsicName() + ")";
+        }
+        return "";
+    }
 }
--- a/src/utils/LogCompilation/src/main/java/com/sun/hotspot/tools/compiler/LogParser.java	Thu Jan 18 22:05:05 2018 +0100
+++ b/src/utils/LogCompilation/src/main/java/com/sun/hotspot/tools/compiler/LogParser.java	Mon Jan 22 16:55:01 2018 +0100
@@ -975,6 +975,12 @@
                 // track of it but don't add it to the list yet.
                 methodHandleSite = site;
             }
+        } else if (qname.equals("intrinsic")) {
+            String id = atts.getValue("id");
+            assert id != null : "intrinsic id is null";
+            CallSite cs = (site != null) ? site : scopes.peek();
+            assert cs != null : "no CallSite?";
+            cs.setIntrinsicName(id);
         } else if (qname.equals("regalloc")) {
             compile.setAttempts(Integer.parseInt(search(atts, "attempts")));
         } else if (qname.equals("inline_fail")) {
--- a/test/hotspot/jtreg/Makefile	Thu Jan 18 22:05:05 2018 +0100
+++ b/test/hotspot/jtreg/Makefile	Mon Jan 22 16:55:01 2018 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 1995, 2016, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 1995, 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
@@ -66,13 +66,15 @@
   CONCURRENCY_FACTOR = 1
 endif
 
-# Concurrency based on min(cores / 2, 12)
-CONCURRENCY := $(shell awk 'BEGIN { printf "%.0f", $(NUM_CORES) / 2 * $(CONCURRENCY_FACTOR) }')
-ifeq ($(CONCURRENCY), 0)
-  CONCURRENCY := 1
-else ifeq ($(shell expr $(CONCURRENCY) \> 12), 1)
-  CONCURRENCY := 12
-endif
+# Concurrency based on min(cores / 2, 12) * CONCURRENCY_FACTOR
+CONCURRENCY := $(shell awk \
+  'BEGIN { \
+    c = $(NUM_CORES) / 2; \
+    if (c > 12) c = 12; \
+    c = c * $(CONCURRENCY_FACTOR); \
+    if (c < 1) c = 1; \
+    printf "%.0f", c; \
+  }')
 
 # Make sure MaxRAMPercentage is high enough to not cause OOM or swapping since we may end up with a lot of JVM's
 JTREG_BASIC_OPTIONS += -vmoption:-XX:MaxRAMPercentage=$(shell expr 25 / $(CONCURRENCY))
--- a/test/hotspot/jtreg/ProblemList.txt	Thu Jan 18 22:05:05 2018 +0100
+++ b/test/hotspot/jtreg/ProblemList.txt	Mon Jan 22 16:55:01 2018 +0100
@@ -71,6 +71,7 @@
 gc/stress/gclocker/TestGCLockerWithParallel.java 8180622 generic-all
 gc/stress/gclocker/TestGCLockerWithG1.java 8179226 generic-all
 gc/survivorAlignment/TestPromotionFromSurvivorToTenuredAfterMinorGC.java 8177765 generic-all
+gc/stress/TestJNIBlockFullGC/TestJNIBlockFullGC.java 8192647 generic-all
 
 #############################################################################
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/gc/g1/TestConcurrentSystemGC.java	Mon Jan 22 16:55:01 2018 +0100
@@ -0,0 +1,54 @@
+/*
+ * 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.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test TestConcurrentSystemGC
+ * @bug 8195158
+ * @summary Test that a System.gc() with -XX:+ExplicitGCInvokesConcurrent
+ *          is *not* upgraded to STW full GC
+ * @key gc
+ * @requires vm.gc.G1
+ * @library /test/lib
+ * @modules java.base/jdk.internal.misc
+ *          java.management
+ * @run main/othervm -XX:+UseG1GC -XX:+ExplicitGCInvokesConcurrent -Xmx8m -Xms8m -XX:G1HeapRegionSize=1m TestConcurrentSystemGC
+ */
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class TestConcurrentSystemGC {
+    public static List<char[]> memory;
+