Merge
authoramurillo
Thu, 30 Oct 2014 22:52:13 -0700
changeset 27436 edb2a1d98e1a
parent 27325 948cceef81ba (current diff)
parent 27435 58d1380ceacb (diff)
child 27446 c461dfe64745
Merge
--- a/hotspot/make/solaris/makefiles/vm.make	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/make/solaris/makefiles/vm.make	Thu Oct 30 22:52:13 2014 -0700
@@ -143,7 +143,7 @@
 LIBS += -lsocket -lsched -ldl $(LIBM) -lthread -lc -ldemangle
 endif # sparcWorks
 
-LIBS += -lkstat -lpicl
+LIBS += -lkstat
 
 # By default, link the *.o into the library, not the executable.
 LINK_INTO$(LINK_INTO) = LIBJVM
--- a/hotspot/src/cpu/x86/vm/vm_version_x86.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/cpu/x86/vm/vm_version_x86.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -865,14 +865,19 @@
   if (supports_bmi1()) {
     // tzcnt does not require VEX prefix
     if (FLAG_IS_DEFAULT(UseCountTrailingZerosInstruction)) {
-      UseCountTrailingZerosInstruction = true;
+      if (!UseBMI1Instructions && !FLAG_IS_DEFAULT(UseBMI1Instructions)) {
+        // Don't use tzcnt if BMI1 is switched off on command line.
+        UseCountTrailingZerosInstruction = false;
+      } else {
+        UseCountTrailingZerosInstruction = true;
+      }
     }
   } else if (UseCountTrailingZerosInstruction) {
     warning("tzcnt instruction is not available on this CPU");
     FLAG_SET_DEFAULT(UseCountTrailingZerosInstruction, false);
   }
 
-  // BMI instructions use an encoding with VEX prefix.
+  // BMI instructions (except tzcnt) use an encoding with VEX prefix.
   // VEX prefix is generated only when AVX > 0.
   if (supports_bmi1() && supports_avx()) {
     if (FLAG_IS_DEFAULT(UseBMI1Instructions)) {
--- a/hotspot/src/os/aix/vm/os_aix.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/os/aix/vm/os_aix.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -4137,15 +4137,6 @@
   return 1;
 }
 
-int os::socket_available(int fd, jint *pbytes) {
-  // Linux doc says EINTR not returned, unlike Solaris
-  int ret = ::ioctl(fd, FIONREAD, pbytes);
-
-  //%% note ioctl can return 0 when successful, JVM_SocketAvailable
-  // is expected to return 0 on failure and 1 on success to the jdk.
-  return (ret < 0) ? 0 : 1;
-}
-
 // Map a block of memory.
 char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,
                         char *addr, size_t bytes, bool read_only,
--- a/hotspot/src/os/aix/vm/os_aix.inline.hpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/os/aix/vm/os_aix.inline.hpp	Thu Oct 30 22:52:13 2014 -0700
@@ -178,92 +178,14 @@
   return os::send(fd, buf, nBytes, flags);
 }
 
-inline int os::timeout(int fd, long timeout) {
-  julong prevtime,newtime;
-  struct timeval t;
-
-  gettimeofday(&t, NULL);
-  prevtime = ((julong)t.tv_sec * 1000) + t.tv_usec / 1000;
-
-  for(;;) {
-    struct pollfd pfd;
-
-    pfd.fd = fd;
-    pfd.events = POLLIN | POLLERR;
-
-    int res = ::poll(&pfd, 1, timeout);
-
-    if (res == OS_ERR && errno == EINTR) {
-
-      // On Linux any value < 0 means "forever"
-
-      if(timeout >= 0) {
-        gettimeofday(&t, NULL);
-        newtime = ((julong)t.tv_sec * 1000) + t.tv_usec / 1000;
-        timeout -= newtime - prevtime;
-        if(timeout <= 0)
-          return OS_OK;
-        prevtime = newtime;
-      }
-    } else
-      return res;
-  }
-}
-
-inline int os::listen(int fd, int count) {
-  return ::listen(fd, count);
-}
-
 inline int os::connect(int fd, struct sockaddr* him, socklen_t len) {
   RESTARTABLE_RETURN_INT(::connect(fd, him, len));
 }
 
-inline int os::accept(int fd, struct sockaddr* him, socklen_t* len) {
-  // Linux doc says this can't return EINTR, unlike accept() on Solaris.
-  // But see attachListener_linux.cpp, LinuxAttachListener::dequeue().
-  return (int)::accept(fd, him, len);
-}
-
-inline int os::recvfrom(int fd, char* buf, size_t nBytes, uint flags,
-                        sockaddr* from, socklen_t* fromlen) {
-  RESTARTABLE_RETURN_INT((int)::recvfrom(fd, buf, nBytes, flags, from, fromlen));
-}
-
-inline int os::sendto(int fd, char* buf, size_t len, uint flags,
-                      struct sockaddr* to, socklen_t tolen) {
-  RESTARTABLE_RETURN_INT((int)::sendto(fd, buf, len, flags, to, tolen));
-}
-
-inline int os::socket_shutdown(int fd, int howto) {
-  return ::shutdown(fd, howto);
-}
-
-inline int os::bind(int fd, struct sockaddr* him, socklen_t len) {
-  return ::bind(fd, him, len);
-}
-
-inline int os::get_sock_name(int fd, struct sockaddr* him, socklen_t* len) {
-  return ::getsockname(fd, him, len);
-}
-
-inline int os::get_host_name(char* name, int namelen) {
-  return ::gethostname(name, namelen);
-}
-
 inline struct hostent* os::get_host_by_name(char* name) {
   return ::gethostbyname(name);
 }
 
-inline int os::get_sock_opt(int fd, int level, int optname,
-                            char* optval, socklen_t* optlen) {
-  return ::getsockopt(fd, level, optname, optval, optlen);
-}
-
-inline int os::set_sock_opt(int fd, int level, int optname,
-                            const char* optval, socklen_t optlen) {
-  return ::setsockopt(fd, level, optname, optval, optlen);
-}
-
 inline bool os::supports_monotonic_clock() {
   // mread_real_time() is monotonic on AIX (see os::javaTimeNanos() comments)
   return true;
--- a/hotspot/src/os/bsd/vm/os_bsd.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/os/bsd/vm/os_bsd.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -3958,21 +3958,6 @@
   return 1;
 }
 
-int os::socket_available(int fd, jint *pbytes) {
-  if (fd < 0) {
-    return OS_OK;
-  }
-
-  int ret;
-
-  RESTARTABLE(::ioctl(fd, FIONREAD, pbytes), ret);
-
-  //%% note ioctl can return 0 when successful, JVM_SocketAvailable
-  // is expected to return 0 on failure and 1 on success to the jdk.
-
-  return (ret == OS_ERR) ? 0 : 1;
-}
-
 // Map a block of memory.
 char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,
                         char *addr, size_t bytes, bool read_only,
--- a/hotspot/src/os/bsd/vm/os_bsd.inline.hpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/os/bsd/vm/os_bsd.inline.hpp	Thu Oct 30 22:52:13 2014 -0700
@@ -181,91 +181,14 @@
   return os::send(fd, buf, nBytes, flags);
 }
 
-inline int os::timeout(int fd, long timeout) {
-  julong prevtime,newtime;
-  struct timeval t;
-
-  gettimeofday(&t, NULL);
-  prevtime = ((julong)t.tv_sec * 1000)  +  t.tv_usec / 1000;
-
-  for(;;) {
-    struct pollfd pfd;
-
-    pfd.fd = fd;
-    pfd.events = POLLIN | POLLERR;
-
-    int res = ::poll(&pfd, 1, timeout);
-
-    if (res == OS_ERR && errno == EINTR) {
-
-      // On Bsd any value < 0 means "forever"
-
-      if(timeout >= 0) {
-        gettimeofday(&t, NULL);
-        newtime = ((julong)t.tv_sec * 1000)  +  t.tv_usec / 1000;
-        timeout -= newtime - prevtime;
-        if(timeout <= 0)
-          return OS_OK;
-        prevtime = newtime;
-      }
-    } else
-      return res;
-  }
-}
-
-inline int os::listen(int fd, int count) {
-  return ::listen(fd, count);
-}
-
 inline int os::connect(int fd, struct sockaddr* him, socklen_t len) {
   RESTARTABLE_RETURN_INT(::connect(fd, him, len));
 }
 
-inline int os::accept(int fd, struct sockaddr* him, socklen_t* len) {
-  // At least OpenBSD and FreeBSD can return EINTR from accept.
-  RESTARTABLE_RETURN_INT(::accept(fd, him, len));
-}
-
-inline int os::recvfrom(int fd, char* buf, size_t nBytes, uint flags,
-                         sockaddr* from, socklen_t* fromlen) {
-  RESTARTABLE_RETURN_INT((int)::recvfrom(fd, buf, nBytes, flags, from, fromlen));
-}
-
-inline int os::sendto(int fd, char* buf, size_t len, uint flags,
-                      struct sockaddr *to, socklen_t tolen) {
-  RESTARTABLE_RETURN_INT((int)::sendto(fd, buf, len, flags, to, tolen));
-}
-
-inline int os::socket_shutdown(int fd, int howto) {
-  return ::shutdown(fd, howto);
-}
-
-inline int os::bind(int fd, struct sockaddr* him, socklen_t len) {
-  return ::bind(fd, him, len);
-}
-
-inline int os::get_sock_name(int fd, struct sockaddr* him, socklen_t* len) {
-  return ::getsockname(fd, him, len);
-}
-
-inline int os::get_host_name(char* name, int namelen) {
-  return ::gethostname(name, namelen);
-}
-
 inline struct hostent* os::get_host_by_name(char* name) {
   return ::gethostbyname(name);
 }
 
-inline int os::get_sock_opt(int fd, int level, int optname,
-                            char *optval, socklen_t* optlen) {
-  return ::getsockopt(fd, level, optname, optval, optlen);
-}
-
-inline int os::set_sock_opt(int fd, int level, int optname,
-                            const char* optval, socklen_t optlen) {
-  return ::setsockopt(fd, level, optname, optval, optlen);
-}
-
 inline bool os::supports_monotonic_clock() {
 #ifdef __APPLE__
   return true;
--- a/hotspot/src/os/linux/vm/os_linux.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/os/linux/vm/os_linux.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -5211,15 +5211,6 @@
   return 1;
 }
 
-int os::socket_available(int fd, jint *pbytes) {
-  // Linux doc says EINTR not returned, unlike Solaris
-  int ret = ::ioctl(fd, FIONREAD, pbytes);
-
-  //%% note ioctl can return 0 when successful, JVM_SocketAvailable
-  // is expected to return 0 on failure and 1 on success to the jdk.
-  return (ret < 0) ? 0 : 1;
-}
-
 // Map a block of memory.
 char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,
                         char *addr, size_t bytes, bool read_only,
--- a/hotspot/src/os/linux/vm/os_linux.inline.hpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/os/linux/vm/os_linux.inline.hpp	Thu Oct 30 22:52:13 2014 -0700
@@ -173,92 +173,14 @@
   return os::send(fd, buf, nBytes, flags);
 }
 
-inline int os::timeout(int fd, long timeout) {
-  julong prevtime,newtime;
-  struct timeval t;
-
-  gettimeofday(&t, NULL);
-  prevtime = ((julong)t.tv_sec * 1000)  +  t.tv_usec / 1000;
-
-  for(;;) {
-    struct pollfd pfd;
-
-    pfd.fd = fd;
-    pfd.events = POLLIN | POLLERR;
-
-    int res = ::poll(&pfd, 1, timeout);
-
-    if (res == OS_ERR && errno == EINTR) {
-
-      // On Linux any value < 0 means "forever"
-
-      if(timeout >= 0) {
-        gettimeofday(&t, NULL);
-        newtime = ((julong)t.tv_sec * 1000)  +  t.tv_usec / 1000;
-        timeout -= newtime - prevtime;
-        if(timeout <= 0)
-          return OS_OK;
-        prevtime = newtime;
-      }
-    } else
-      return res;
-  }
-}
-
-inline int os::listen(int fd, int count) {
-  return ::listen(fd, count);
-}
-
 inline int os::connect(int fd, struct sockaddr* him, socklen_t len) {
   RESTARTABLE_RETURN_INT(::connect(fd, him, len));
 }
 
-inline int os::accept(int fd, struct sockaddr* him, socklen_t* len) {
-  // Linux doc says this can't return EINTR, unlike accept() on Solaris.
-  // But see attachListener_linux.cpp, LinuxAttachListener::dequeue().
-  return (int)::accept(fd, him, len);
-}
-
-inline int os::recvfrom(int fd, char* buf, size_t nBytes, uint flags,
-                        sockaddr* from, socklen_t* fromlen) {
-  RESTARTABLE_RETURN_INT((int)::recvfrom(fd, buf, nBytes, flags, from, fromlen));
-}
-
-inline int os::sendto(int fd, char* buf, size_t len, uint flags,
-                      struct sockaddr* to, socklen_t tolen) {
-  RESTARTABLE_RETURN_INT((int)::sendto(fd, buf, len, flags, to, tolen));
-}
-
-inline int os::socket_shutdown(int fd, int howto) {
-  return ::shutdown(fd, howto);
-}
-
-inline int os::bind(int fd, struct sockaddr* him, socklen_t len) {
-  return ::bind(fd, him, len);
-}
-
-inline int os::get_sock_name(int fd, struct sockaddr* him, socklen_t* len) {
-  return ::getsockname(fd, him, len);
-}
-
-inline int os::get_host_name(char* name, int namelen) {
-  return ::gethostname(name, namelen);
-}
-
 inline struct hostent* os::get_host_by_name(char* name) {
   return ::gethostbyname(name);
 }
 
-inline int os::get_sock_opt(int fd, int level, int optname,
-                            char* optval, socklen_t* optlen) {
-  return ::getsockopt(fd, level, optname, optval, optlen);
-}
-
-inline int os::set_sock_opt(int fd, int level, int optname,
-                            const char* optval, socklen_t optlen) {
-  return ::setsockopt(fd, level, optname, optval, optlen);
-}
-
 inline bool os::supports_monotonic_clock() {
   return Linux::_clock_gettime != NULL;
 }
--- a/hotspot/src/os/solaris/vm/os_solaris.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/os/solaris/vm/os_solaris.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -5912,37 +5912,6 @@
 // a poll() is done with timeout == -1, in which case we repeat with this
 // "wait forever" value.
 
-int os::timeout(int fd, long timeout) {
-  int res;
-  struct timeval t;
-  julong prevtime, newtime;
-  static const char* aNull = 0;
-  struct pollfd pfd;
-  pfd.fd = fd;
-  pfd.events = POLLIN;
-
-  assert(((JavaThread*)Thread::current())->thread_state() == _thread_in_native,
-         "Assumed _thread_in_native");
-
-  gettimeofday(&t, &aNull);
-  prevtime = ((julong)t.tv_sec * 1000)  +  t.tv_usec / 1000;
-
-  for (;;) {
-    res = ::poll(&pfd, 1, timeout);
-    if (res == OS_ERR && errno == EINTR) {
-      if (timeout != -1) {
-        gettimeofday(&t, &aNull);
-        newtime = ((julong)t.tv_sec * 1000)  +  t.tv_usec /1000;
-        timeout -= newtime - prevtime;
-        if (timeout <= 0) {
-          return OS_OK;
-        }
-        prevtime = newtime;
-      }
-    } else return res;
-  }
-}
-
 int os::connect(int fd, struct sockaddr *him, socklen_t len) {
   int _result;
   _result = ::connect(fd, him, len);
@@ -5982,46 +5951,6 @@
   return _result;
 }
 
-int os::accept(int fd, struct sockaddr* him, socklen_t* len) {
-  if (fd < 0) {
-    return OS_ERR;
-  }
-  assert(((JavaThread*)Thread::current())->thread_state() == _thread_in_native,
-         "Assumed _thread_in_native");
-  RESTARTABLE_RETURN_INT((int)::accept(fd, him, len));
-}
-
-int os::recvfrom(int fd, char* buf, size_t nBytes, uint flags,
-                 sockaddr* from, socklen_t* fromlen) {
-  assert(((JavaThread*)Thread::current())->thread_state() == _thread_in_native,
-         "Assumed _thread_in_native");
-  RESTARTABLE_RETURN_INT((int)::recvfrom(fd, buf, nBytes, flags, from, fromlen));
-}
-
-int os::sendto(int fd, char* buf, size_t len, uint flags,
-               struct sockaddr* to, socklen_t tolen) {
-  assert(((JavaThread*)Thread::current())->thread_state() == _thread_in_native,
-         "Assumed _thread_in_native");
-  RESTARTABLE_RETURN_INT((int)::sendto(fd, buf, len, flags, to, tolen));
-}
-
-int os::socket_available(int fd, jint *pbytes) {
-  if (fd < 0) {
-    return OS_OK;
-  }
-  int ret;
-  RESTARTABLE(::ioctl(fd, FIONREAD, pbytes), ret);
-  // note: ioctl can return 0 when successful, JVM_SocketAvailable
-  // is expected to return 0 on failure and 1 on success to the jdk.
-  return (ret == OS_ERR) ? 0 : 1;
-}
-
-int os::bind(int fd, struct sockaddr* him, socklen_t len) {
-  assert(((JavaThread*)Thread::current())->thread_state() == _thread_in_native,
-         "Assumed _thread_in_native");
-  return ::bind(fd, him, len);
-}
-
 // Get the default path to the core file
 // Returns the length of the string
 int os::get_core_path(char* buffer, size_t bufferSize) {
--- a/hotspot/src/os/solaris/vm/os_solaris.inline.hpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/os/solaris/vm/os_solaris.inline.hpp	Thu Oct 30 22:52:13 2014 -0700
@@ -120,38 +120,10 @@
   return ::socket(domain, type, protocol);
 }
 
-inline int    os::listen(int fd, int count) {
-  if (fd < 0) return OS_ERR;
-
-  return ::listen(fd, count);
-}
-
-inline int os::socket_shutdown(int fd, int howto){
-  return ::shutdown(fd, howto);
-}
-
-inline int os::get_sock_name(int fd, struct sockaddr* him, socklen_t* len){
-  return ::getsockname(fd, him, len);
-}
-
-inline int os::get_host_name(char* name, int namelen){
-  return ::gethostname(name, namelen);
-}
-
 inline struct hostent* os::get_host_by_name(char* name) {
   return ::gethostbyname(name);
 }
 
-inline int os::get_sock_opt(int fd, int level, int optname,
-                            char* optval, socklen_t* optlen) {
-  return ::getsockopt(fd, level, optname, optval, optlen);
-}
-
-inline int os::set_sock_opt(int fd, int level, int optname,
-                            const char *optval, socklen_t optlen) {
-  return ::setsockopt(fd, level, optname, optval, optlen);
-}
-
 inline bool os::supports_monotonic_clock() {
   // javaTimeNanos() is monotonic on Solaris, see getTimeNanos() comments
   return true;
--- a/hotspot/src/os/windows/vm/os_windows.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/os/windows/vm/os_windows.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -5091,39 +5091,14 @@
   return ::closesocket(fd);
 }
 
-int os::socket_available(int fd, jint *pbytes) {
-  int ret = ::ioctlsocket(fd, FIONREAD, (u_long*)pbytes);
-  return (ret < 0) ? 0 : 1;
-}
-
 int os::socket(int domain, int type, int protocol) {
   return ::socket(domain, type, protocol);
 }
 
-int os::listen(int fd, int count) {
-  return ::listen(fd, count);
-}
-
 int os::connect(int fd, struct sockaddr* him, socklen_t len) {
   return ::connect(fd, him, len);
 }
 
-int os::accept(int fd, struct sockaddr* him, socklen_t* len) {
-  return ::accept(fd, him, len);
-}
-
-int os::sendto(int fd, char* buf, size_t len, uint flags,
-               struct sockaddr* to, socklen_t tolen) {
-
-  return ::sendto(fd, buf, (int)len, flags, to, tolen);
-}
-
-int os::recvfrom(int fd, char *buf, size_t nBytes, uint flags,
-                 sockaddr* from, socklen_t* fromlen) {
-
-  return ::recvfrom(fd, buf, (int)nBytes, flags, from, fromlen);
-}
-
 int os::recv(int fd, char* buf, size_t nBytes, uint flags) {
   return ::recv(fd, buf, (int)nBytes, flags);
 }
@@ -5136,45 +5111,6 @@
   return ::send(fd, buf, (int)nBytes, flags);
 }
 
-int os::timeout(int fd, long timeout) {
-  fd_set tbl;
-  struct timeval t;
-
-  t.tv_sec  = timeout / 1000;
-  t.tv_usec = (timeout % 1000) * 1000;
-
-  tbl.fd_count    = 1;
-  tbl.fd_array[0] = fd;
-
-  return ::select(1, &tbl, 0, 0, &t);
-}
-
-int os::get_host_name(char* name, int namelen) {
-  return ::gethostname(name, namelen);
-}
-
-int os::socket_shutdown(int fd, int howto) {
-  return ::shutdown(fd, howto);
-}
-
-int os::bind(int fd, struct sockaddr* him, socklen_t len) {
-  return ::bind(fd, him, len);
-}
-
-int os::get_sock_name(int fd, struct sockaddr* him, socklen_t* len) {
-  return ::getsockname(fd, him, len);
-}
-
-int os::get_sock_opt(int fd, int level, int optname,
-                     char* optval, socklen_t* optlen) {
-  return ::getsockopt(fd, level, optname, optval, optlen);
-}
-
-int os::set_sock_opt(int fd, int level, int optname,
-                     const char* optval, socklen_t optlen) {
-  return ::setsockopt(fd, level, optname, optval, optlen);
-}
-
 // WINDOWS CONTEXT Flags for THREAD_SAMPLING
 #if defined(IA32)
   #define sampling_context_flags (CONTEXT_FULL | CONTEXT_FLOATING_POINT | CONTEXT_EXTENDED_REGISTERS)
--- a/hotspot/src/os_cpu/solaris_sparc/vm/vm_version_solaris_sparc.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/os_cpu/solaris_sparc/vm/vm_version_solaris_sparc.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -33,18 +33,51 @@
 #include <sys/systeminfo.h>
 #include <kstat.h>
 #include <picl.h>
+#include <dlfcn.h>
+#include <link.h>
 
 extern "C" static int PICL_get_l1_data_cache_line_size_helper(picl_nodehdl_t nodeh, void *result);
 extern "C" static int PICL_get_l2_cache_line_size_helper(picl_nodehdl_t nodeh, void *result);
 
+// Functions from the library we need (signatures should match those in picl.h)
+extern "C" {
+  typedef int (*picl_initialize_func_t)(void);
+  typedef int (*picl_shutdown_func_t)(void);
+  typedef int (*picl_get_root_func_t)(picl_nodehdl_t *nodehandle);
+  typedef int (*picl_walk_tree_by_class_func_t)(picl_nodehdl_t rooth,
+      const char *classname, void *c_args,
+      int (*callback_fn)(picl_nodehdl_t hdl, void *args));
+  typedef int (*picl_get_prop_by_name_func_t)(picl_nodehdl_t nodeh, const char *nm,
+      picl_prophdl_t *ph);
+  typedef int (*picl_get_propval_func_t)(picl_prophdl_t proph, void *valbuf, size_t sz);
+  typedef int (*picl_get_propinfo_func_t)(picl_prophdl_t proph, picl_propinfo_t *pi);
+}
+
 class PICL {
+  // Pointers to functions in the library
+  picl_initialize_func_t _picl_initialize;
+  picl_shutdown_func_t _picl_shutdown;
+  picl_get_root_func_t _picl_get_root;
+  picl_walk_tree_by_class_func_t _picl_walk_tree_by_class;
+  picl_get_prop_by_name_func_t _picl_get_prop_by_name;
+  picl_get_propval_func_t _picl_get_propval;
+  picl_get_propinfo_func_t _picl_get_propinfo;
+  // Handle to the library that is returned by dlopen
+  void *_dl_handle;
+
+  bool open_library();
+  void close_library();
+
+  template<typename FuncType> bool bind(FuncType& func, const char* name);
+  bool bind_library_functions();
+
   // Get a value of the integer property. The value in the tree can be either 32 or 64 bit
   // depending on the platform. The result is converted to int.
-  static int get_int_property(picl_nodehdl_t nodeh, const char* name, int* result) {
+  int get_int_property(picl_nodehdl_t nodeh, const char* name, int* result) {
     picl_propinfo_t pinfo;
     picl_prophdl_t proph;
-    if (picl_get_prop_by_name(nodeh, name, &proph) != PICL_SUCCESS ||
-        picl_get_propinfo(proph, &pinfo) != PICL_SUCCESS) {
+    if (_picl_get_prop_by_name(nodeh, name, &proph) != PICL_SUCCESS ||
+        _picl_get_propinfo(proph, &pinfo) != PICL_SUCCESS) {
       return PICL_FAILURE;
     }
 
@@ -54,13 +87,13 @@
     }
     if (pinfo.size == sizeof(int64_t)) {
       int64_t val;
-      if (picl_get_propval(proph, &val, sizeof(int64_t)) != PICL_SUCCESS) {
+      if (_picl_get_propval(proph, &val, sizeof(int64_t)) != PICL_SUCCESS) {
         return PICL_FAILURE;
       }
       *result = static_cast<int>(val);
     } else if (pinfo.size == sizeof(int32_t)) {
       int32_t val;
-      if (picl_get_propval(proph, &val, sizeof(int32_t)) != PICL_SUCCESS) {
+      if (_picl_get_propval(proph, &val, sizeof(int32_t)) != PICL_SUCCESS) {
         return PICL_FAILURE;
       }
       *result = static_cast<int>(val);
@@ -74,6 +107,7 @@
   // Visitor and a state machine that visits integer properties and verifies that the
   // values are the same. Stores the unique value observed.
   class UniqueValueVisitor {
+    PICL *_picl;
     enum {
       INITIAL,        // Start state, no assignments happened
       ASSIGNED,       // Assigned a value
@@ -81,7 +115,7 @@
     } _state;
     int _value;
   public:
-    UniqueValueVisitor() : _state(INITIAL) { }
+    UniqueValueVisitor(PICL* picl) : _picl(picl), _state(INITIAL) { }
     int value() {
       assert(_state == ASSIGNED, "Precondition");
       return _value;
@@ -98,9 +132,10 @@
 
     static int visit(picl_nodehdl_t nodeh, const char* name, void *arg) {
       UniqueValueVisitor *state = static_cast<UniqueValueVisitor*>(arg);
+      PICL* picl = state->_picl;
       assert(!state->is_inconsistent(), "Precondition");
       int curr;
-      if (PICL::get_int_property(nodeh, name, &curr) == PICL_SUCCESS) {
+      if (picl->get_int_property(nodeh, name, &curr) == PICL_SUCCESS) {
         if (!state->is_assigned()) { // first iteration
           state->set_value(curr);
         } else if (curr != state->value()) { // following iterations
@@ -124,32 +159,36 @@
     return UniqueValueVisitor::visit(nodeh, "l2-cache-line-size", state);
   }
 
-  PICL() : _L1_data_cache_line_size(0), _L2_cache_line_size(0) {
-    if (picl_initialize() == PICL_SUCCESS) {
+  PICL() : _L1_data_cache_line_size(0), _L2_cache_line_size(0), _dl_handle(NULL) {
+    if (!open_library()) {
+      return;
+    }
+    if (_picl_initialize() == PICL_SUCCESS) {
       picl_nodehdl_t rooth;
-      if (picl_get_root(&rooth) == PICL_SUCCESS) {
-        UniqueValueVisitor L1_state;
+      if (_picl_get_root(&rooth) == PICL_SUCCESS) {
+        UniqueValueVisitor L1_state(this);
         // Visit all "cpu" class instances
-        picl_walk_tree_by_class(rooth, "cpu", &L1_state, PICL_get_l1_data_cache_line_size_helper);
+        _picl_walk_tree_by_class(rooth, "cpu", &L1_state, PICL_get_l1_data_cache_line_size_helper);
         if (L1_state.is_initial()) { // Still initial, iteration found no values
           // Try walk all "core" class instances, it might be a Fujitsu machine
-          picl_walk_tree_by_class(rooth, "core", &L1_state, PICL_get_l1_data_cache_line_size_helper);
+          _picl_walk_tree_by_class(rooth, "core", &L1_state, PICL_get_l1_data_cache_line_size_helper);
         }
         if (L1_state.is_assigned()) { // Is there a value?
           _L1_data_cache_line_size = L1_state.value();
         }
 
-        UniqueValueVisitor L2_state;
-        picl_walk_tree_by_class(rooth, "cpu", &L2_state, PICL_get_l2_cache_line_size_helper);
+        UniqueValueVisitor L2_state(this);
+        _picl_walk_tree_by_class(rooth, "cpu", &L2_state, PICL_get_l2_cache_line_size_helper);
         if (L2_state.is_initial()) {
-          picl_walk_tree_by_class(rooth, "core", &L2_state, PICL_get_l2_cache_line_size_helper);
+          _picl_walk_tree_by_class(rooth, "core", &L2_state, PICL_get_l2_cache_line_size_helper);
         }
         if (L2_state.is_assigned()) {
           _L2_cache_line_size = L2_state.value();
         }
       }
-      picl_shutdown();
+      _picl_shutdown();
     }
+    close_library();
   }
 
   unsigned int L1_data_cache_line_size() const { return _L1_data_cache_line_size; }
@@ -163,6 +202,43 @@
   return PICL::get_l2_cache_line_size(nodeh, result);
 }
 
+template<typename FuncType>
+bool PICL::bind(FuncType& func, const char* name) {
+  func = reinterpret_cast<FuncType>(dlsym(_dl_handle, name));
+  return func != NULL;
+}
+
+bool PICL::bind_library_functions() {
+  assert(_dl_handle != NULL, "library should be open");
+  return bind(_picl_initialize,         "picl_initialize"        ) &&
+         bind(_picl_shutdown,           "picl_shutdown"          ) &&
+         bind(_picl_get_root,           "picl_get_root"          ) &&
+         bind(_picl_walk_tree_by_class, "picl_walk_tree_by_class") &&
+         bind(_picl_get_prop_by_name,   "picl_get_prop_by_name"  ) &&
+         bind(_picl_get_propval,        "picl_get_propval"       ) &&
+         bind(_picl_get_propinfo,       "picl_get_propinfo"      );
+}
+
+bool PICL::open_library() {
+  _dl_handle = dlopen("libpicl.so.1", RTLD_LAZY);
+  if (_dl_handle == NULL) {
+    warning("PICL (libpicl.so.1) is missing. Performance will not be optimal.");
+    return false;
+  }
+  if (!bind_library_functions()) {
+    assert(false, "unexpected PICL API change");
+    close_library();
+    return false;
+  }
+  return true;
+}
+
+void PICL::close_library() {
+  assert(_dl_handle != NULL, "library should be open");
+  dlclose(_dl_handle);
+  _dl_handle = NULL;
+}
+
 // We need to keep these here as long as we have to build on Solaris
 // versions before 10.
 #ifndef SI_ARCHITECTURE_32
--- a/hotspot/src/share/vm/ci/ciEnv.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/ci/ciEnv.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -1093,9 +1093,8 @@
     // JVMTI -- compiled method notification (must be done outside lock)
     nm->post_compiled_method_load_event();
   } else {
-    // The CodeCache is full. Print out warning and disable compilation.
+    // The CodeCache is full.
     record_failure("code cache is full");
-    CompileBroker::handle_full_code_cache(CodeCache::get_code_blob_type(comp_level));
   }
 }
 
--- a/hotspot/src/share/vm/classfile/classFileParser.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/classfile/classFileParser.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -2557,7 +2557,7 @@
 Array<Method*>* ClassFileParser::parse_methods(bool is_interface,
                                                AccessFlags* promoted_flags,
                                                bool* has_final_method,
-                                               bool* has_default_methods,
+                                               bool* declares_default_methods,
                                                TRAPS) {
   ClassFileStream* cfs = stream();
   cfs->guarantee_more(2, CHECK_NULL);  // length
@@ -2576,11 +2576,11 @@
       if (method->is_final()) {
         *has_final_method = true;
       }
-      if (is_interface && !(*has_default_methods)
-        && !method->is_abstract() && !method->is_static()
-        && !method->is_private()) {
-        // default method
-        *has_default_methods = true;
+      // declares_default_methods: declares concrete instance methods, any access flags
+      // used for interface initialization, and default method inheritance analysis
+      if (is_interface && !(*declares_default_methods)
+        && !method->is_abstract() && !method->is_static()) {
+        *declares_default_methods = true;
       }
       _methods->at_put(index, method());
     }
@@ -3739,6 +3739,7 @@
   JvmtiCachedClassFileData *cached_class_file = NULL;
   Handle class_loader(THREAD, loader_data->class_loader());
   bool has_default_methods = false;
+  bool declares_default_methods = false;
   ResourceMark rm(THREAD);
 
   ClassFileStream* cfs = stream();
@@ -3976,9 +3977,13 @@
     Array<Method*>* methods = parse_methods(access_flags.is_interface(),
                                             &promoted_flags,
                                             &has_final_method,
-                                            &has_default_methods,
+                                            &declares_default_methods,
                                             CHECK_(nullHandle));
 
+    if (declares_default_methods) {
+      has_default_methods = true;
+    }
+
     // Additional attributes
     ClassAnnotationCollector parsed_annotations;
     parse_classfile_attributes(&parsed_annotations, CHECK_(nullHandle));
@@ -4120,6 +4125,7 @@
     this_klass->set_minor_version(minor_version);
     this_klass->set_major_version(major_version);
     this_klass->set_has_default_methods(has_default_methods);
+    this_klass->set_declares_default_methods(declares_default_methods);
 
     if (!host_klass.is_null()) {
       assert (this_klass->is_anonymous(), "should be the same");
--- a/hotspot/src/share/vm/classfile/classFileParser.hpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/classfile/classFileParser.hpp	Thu Oct 30 22:52:13 2014 -0700
@@ -247,7 +247,7 @@
   Array<Method*>* parse_methods(bool is_interface,
                                 AccessFlags* promoted_flags,
                                 bool* has_final_method,
-                                bool* has_default_method,
+                                bool* declares_default_methods,
                                 TRAPS);
   intArray* sort_methods(Array<Method*>* methods);
 
--- a/hotspot/src/share/vm/code/codeBlob.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/code/codeBlob.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -229,8 +229,8 @@
   return blob;
 }
 
-void* BufferBlob::operator new(size_t s, unsigned size, bool is_critical) throw() {
-  return CodeCache::allocate(size, CodeBlobType::NonNMethod, is_critical);
+void* BufferBlob::operator new(size_t s, unsigned size) throw() {
+  return CodeCache::allocate(size, CodeBlobType::NonNMethod);
 }
 
 void BufferBlob::free(BufferBlob *blob) {
@@ -260,10 +260,7 @@
   unsigned int size = allocation_size(cb, sizeof(AdapterBlob));
   {
     MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
-    // The parameter 'true' indicates a critical memory allocation.
-    // This means that CodeCacheMinimumFreeSpace is used, if necessary
-    const bool is_critical = true;
-    blob = new (size, is_critical) AdapterBlob(size, cb);
+    blob = new (size) AdapterBlob(size, cb);
   }
   // Track memory usage statistic after releasing CodeCache_lock
   MemoryService::track_code_cache_memory_usage();
@@ -285,10 +282,7 @@
   size += round_to(buffer_size, oopSize);
   {
     MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
-    // The parameter 'true' indicates a critical memory allocation.
-    // This means that CodeCacheMinimumFreeSpace is used, if necessary
-    const bool is_critical = true;
-    blob = new (size, is_critical) MethodHandlesAdapterBlob(size);
+    blob = new (size) MethodHandlesAdapterBlob(size);
   }
   // Track memory usage statistic after releasing CodeCache_lock
   MemoryService::track_code_cache_memory_usage();
@@ -336,14 +330,14 @@
 
 
 void* RuntimeStub::operator new(size_t s, unsigned size) throw() {
-  void* p = CodeCache::allocate(size, CodeBlobType::NonNMethod, true);
+  void* p = CodeCache::allocate(size, CodeBlobType::NonNMethod);
   if (!p) fatal("Initial size of CodeCache is too small");
   return p;
 }
 
 // operator new shared by all singletons:
 void* SingletonBlob::operator new(size_t s, unsigned size) throw() {
-  void* p = CodeCache::allocate(size, CodeBlobType::NonNMethod, true);
+  void* p = CodeCache::allocate(size, CodeBlobType::NonNMethod);
   if (!p) fatal("Initial size of CodeCache is too small");
   return p;
 }
--- a/hotspot/src/share/vm/code/codeBlob.hpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/code/codeBlob.hpp	Thu Oct 30 22:52:13 2014 -0700
@@ -221,7 +221,7 @@
   BufferBlob(const char* name, int size);
   BufferBlob(const char* name, int size, CodeBuffer* cb);
 
-  void* operator new(size_t s, unsigned size, bool is_critical = false) throw();
+  void* operator new(size_t s, unsigned size) throw();
 
  public:
   // Creation
--- a/hotspot/src/share/vm/code/codeCache.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/code/codeCache.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -44,6 +44,7 @@
 #include "runtime/icache.hpp"
 #include "runtime/java.hpp"
 #include "runtime/mutexLocker.hpp"
+#include "runtime/sweeper.hpp"
 #include "runtime/compilationPolicy.hpp"
 #include "services/memoryService.hpp"
 #include "trace/tracing.hpp"
@@ -192,16 +193,16 @@
   }
 
   // Make sure we have enough space for VM internal code
-  uint min_code_cache_size = (CodeCacheMinimumUseSpace DEBUG_ONLY(* 3)) + CodeCacheMinimumFreeSpace;
+  uint min_code_cache_size = CodeCacheMinimumUseSpace DEBUG_ONLY(* 3);
   if (NonNMethodCodeHeapSize < (min_code_cache_size + code_buffers_size)) {
     vm_exit_during_initialization("Not enough space in non-nmethod code heap to run VM.");
   }
   guarantee(NonProfiledCodeHeapSize + ProfiledCodeHeapSize + NonNMethodCodeHeapSize <= ReservedCodeCacheSize, "Size check");
 
   // Align reserved sizes of CodeHeaps
-  size_t non_method_size    = ReservedCodeSpace::allocation_align_size_up(NonNMethodCodeHeapSize);
-  size_t profiled_size      = ReservedCodeSpace::allocation_align_size_up(ProfiledCodeHeapSize);
-  size_t non_profiled_size  = ReservedCodeSpace::allocation_align_size_up(NonProfiledCodeHeapSize);
+  size_t non_method_size   = ReservedCodeSpace::allocation_align_size_up(NonNMethodCodeHeapSize);
+  size_t profiled_size     = ReservedCodeSpace::allocation_align_size_up(ProfiledCodeHeapSize);
+  size_t non_profiled_size = ReservedCodeSpace::allocation_align_size_up(NonProfiledCodeHeapSize);
 
   // Compute initial sizes of CodeHeaps
   size_t init_non_method_size   = MIN2(InitialCodeCacheSize, non_method_size);
@@ -267,6 +268,22 @@
   }
 }
 
+const char* CodeCache::get_code_heap_flag_name(int code_blob_type) {
+  switch(code_blob_type) {
+  case CodeBlobType::NonNMethod:
+    return "NonNMethodCodeHeapSize";
+    break;
+  case CodeBlobType::MethodNonProfiled:
+    return "NonProfiledCodeHeapSize";
+    break;
+  case CodeBlobType::MethodProfiled:
+    return "ProfiledCodeHeapSize";
+    break;
+  }
+  ShouldNotReachHere();
+  return NULL;
+}
+
 void CodeCache::add_heap(ReservedSpace rs, const char* name, size_t size_initial, int code_blob_type) {
   // Check if heap is needed
   if (!heap_available(code_blob_type)) {
@@ -332,14 +349,18 @@
   return next_blob(get_code_heap(cb), cb);
 }
 
-CodeBlob* CodeCache::allocate(int size, int code_blob_type, bool is_critical) {
-  // Do not seize the CodeCache lock here--if the caller has not
-  // already done so, we are going to lose bigtime, since the code
-  // cache will contain a garbage CodeBlob until the caller can
-  // run the constructor for the CodeBlob subclass he is busy
-  // instantiating.
+/**
+ * Do not seize the CodeCache lock here--if the caller has not
+ * already done so, we are going to lose bigtime, since the code
+ * cache will contain a garbage CodeBlob until the caller can
+ * run the constructor for the CodeBlob subclass he is busy
+ * instantiating.
+ */
+CodeBlob* CodeCache::allocate(int size, int code_blob_type) {
+  // Possibly wakes up the sweeper thread.
+  NMethodSweeper::notify(code_blob_type);
   assert_locked_or_safepoint(CodeCache_lock);
-  assert(size > 0, "allocation request must be reasonable");
+  assert(size > 0, err_msg_res("Code cache allocation request must be > 0 but is %d", size));
   if (size <= 0) {
     return NULL;
   }
@@ -350,14 +371,18 @@
   assert(heap != NULL, "heap is null");
 
   while (true) {
-    cb = (CodeBlob*)heap->allocate(size, is_critical);
+    cb = (CodeBlob*)heap->allocate(size);
     if (cb != NULL) break;
     if (!heap->expand_by(CodeCacheExpansionSize)) {
       // Expansion failed
       if (SegmentedCodeCache && (code_blob_type == CodeBlobType::NonNMethod)) {
-        // Fallback solution: Store non-nmethod code in the non-profiled code heap
-        return allocate(size, CodeBlobType::MethodNonProfiled, is_critical);
+        // Fallback solution: Store non-nmethod code in the non-profiled code heap.
+        // Note that at in the sweeper, we check the reverse_free_ratio of the non-profiled
+        // code heap and force stack scanning if less than 10% if the code heap are free.
+        return allocate(size, CodeBlobType::MethodNonProfiled);
       }
+      MutexUnlockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
+      CompileBroker::handle_full_code_cache(code_blob_type);
       return NULL;
     }
     if (PrintCodeCacheExtension) {
@@ -755,19 +780,6 @@
 }
 
 /**
- * Returns true if a CodeHeap is full and sets code_blob_type accordingly.
- */
-bool CodeCache::is_full(int* code_blob_type) {
-  FOR_ALL_HEAPS(heap) {
-    if ((*heap)->unallocated_capacity() < CodeCacheMinimumFreeSpace) {
-      *code_blob_type = (*heap)->code_blob_type();
-      return true;
-    }
-  }
-  return false;
-}
-
-/**
  * Returns the reverse free ratio. E.g., if 25% (1/4) of the code heap
  * is free, reverse_free_ratio() returns 4.
  */
@@ -776,9 +788,13 @@
   if (heap == NULL) {
     return 0;
   }
-  double unallocated_capacity = (double)(heap->unallocated_capacity() - CodeCacheMinimumFreeSpace);
+
+  double unallocated_capacity = MAX2((double)heap->unallocated_capacity(), 1.0); // Avoid division by 0;
   double max_capacity = (double)heap->max_capacity();
-  return max_capacity / unallocated_capacity;
+  double result = max_capacity / unallocated_capacity;
+  assert (max_capacity >= unallocated_capacity, "Must be");
+  assert (result >= 1.0, err_msg_res("reverse_free_ratio must be at least 1. It is %f", result));
+  return result;
 }
 
 size_t CodeCache::bytes_allocated_in_freelists() {
@@ -1011,9 +1027,8 @@
     // Not yet reported for this heap, report
     heap->report_full();
     if (SegmentedCodeCache) {
-      warning("%s is full. Compiler has been disabled.", CodeCache::get_code_heap_name(code_blob_type));
-      warning("Try increasing the code heap size using -XX:%s=",
-          (code_blob_type == CodeBlobType::MethodNonProfiled) ? "NonProfiledCodeHeapSize" : "ProfiledCodeHeapSize");
+      warning("%s is full. Compiler has been disabled.", get_code_heap_name(code_blob_type));
+      warning("Try increasing the code heap size using -XX:%s=", get_code_heap_flag_name(code_blob_type));
     } else {
       warning("CodeCache is full. Compiler has been disabled.");
       warning("Try increasing the code cache size using -XX:ReservedCodeCacheSize=");
--- a/hotspot/src/share/vm/code/codeCache.hpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/code/codeCache.hpp	Thu Oct 30 22:52:13 2014 -0700
@@ -100,6 +100,8 @@
   static void add_heap(ReservedSpace rs, const char* name, size_t size_initial, int code_blob_type);
   static CodeHeap* get_code_heap(CodeBlob* cb);               // Returns the CodeHeap for the given CodeBlob
   static CodeHeap* get_code_heap(int code_blob_type);         // Returns the CodeHeap for the given CodeBlobType
+  // Returns the name of the VM option to set the size of the corresponding CodeHeap
+  static const char* get_code_heap_flag_name(int code_blob_type);
   static bool heap_available(int code_blob_type);             // Returns true if an own CodeHeap for the given CodeBlobType is available
   static ReservedCodeSpace reserve_heap_memory(size_t size);  // Reserves one continuous chunk of memory for the CodeHeaps
 
@@ -118,16 +120,16 @@
   static void initialize();
 
   // Allocation/administration
-  static CodeBlob* allocate(int size, int code_blob_type, bool is_critical = false); // allocates a new CodeBlob
-  static void commit(CodeBlob* cb);                     // called when the allocated CodeBlob has been filled
-  static int  alignment_unit();                         // guaranteed alignment of all CodeBlobs
-  static int  alignment_offset();                       // guaranteed offset of first CodeBlob byte within alignment unit (i.e., allocation header)
-  static void free(CodeBlob* cb);                       // frees a CodeBlob
-  static bool contains(void *p);                        // returns whether p is included
-  static void blobs_do(void f(CodeBlob* cb));           // iterates over all CodeBlobs
-  static void blobs_do(CodeBlobClosure* f);             // iterates over all CodeBlobs
-  static void nmethods_do(void f(nmethod* nm));         // iterates over all nmethods
-  static void alive_nmethods_do(void f(nmethod* nm));   // iterates over all alive nmethods
+  static CodeBlob* allocate(int size, int code_blob_type); // allocates a new CodeBlob
+  static void commit(CodeBlob* cb);                        // called when the allocated CodeBlob has been filled
+  static int  alignment_unit();                            // guaranteed alignment of all CodeBlobs
+  static int  alignment_offset();                          // guaranteed offset of first CodeBlob byte within alignment unit (i.e., allocation header)
+  static void free(CodeBlob* cb);                          // frees a CodeBlob
+  static bool contains(void *p);                           // returns whether p is included
+  static void blobs_do(void f(CodeBlob* cb));              // iterates over all CodeBlobs
+  static void blobs_do(CodeBlobClosure* f);                // iterates over all CodeBlobs
+  static void nmethods_do(void f(nmethod* nm));            // iterates over all nmethods
+  static void alive_nmethods_do(void f(nmethod* nm));      // iterates over all alive nmethods
 
   // Lookup
   static CodeBlob* find_blob(void* start);              // Returns the CodeBlob containing the given address
@@ -180,7 +182,6 @@
   static size_t unallocated_capacity();
   static size_t max_capacity();
 
-  static bool   is_full(int* code_blob_type);
   static double reverse_free_ratio(int code_blob_type);
 
   static bool needs_cache_clean()                     { return _needs_cache_clean; }
--- a/hotspot/src/share/vm/code/nmethod.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/code/nmethod.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -804,10 +804,7 @@
 #endif // def HAVE_DTRACE_H
 
 void* nmethod::operator new(size_t size, int nmethod_size, int comp_level) throw () {
-  // With a SegmentedCodeCache, nmethods are allocated on separate heaps and therefore do not share memory
-  // with critical CodeBlobs. We define the allocation as critical to make sure all code heap memory is used.
-  bool is_critical = SegmentedCodeCache;
-  return CodeCache::allocate(nmethod_size, CodeCache::get_code_blob_type(comp_level), is_critical);
+  return CodeCache::allocate(nmethod_size, CodeCache::get_code_blob_type(comp_level));
 }
 
 nmethod::nmethod(
--- a/hotspot/src/share/vm/code/vtableStubs.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/code/vtableStubs.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -63,7 +63,6 @@
    // If changing the name, update the other file accordingly.
     BufferBlob* blob = BufferBlob::create("vtable chunks", bytes);
     if (blob == NULL) {
-      CompileBroker::handle_full_code_cache(CodeBlobType::NonNMethod);
       return NULL;
     }
     _chunk = blob->content_begin();
--- a/hotspot/src/share/vm/compiler/compileBroker.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/compiler/compileBroker.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -156,8 +156,6 @@
 CompileQueue* CompileBroker::_c2_compile_queue   = NULL;
 CompileQueue* CompileBroker::_c1_compile_queue   = NULL;
 
-GrowableArray<CompilerThread*>* CompileBroker::_compiler_threads = NULL;
-
 
 class CompilationLog : public StringEventLog {
  public:
@@ -649,13 +647,10 @@
   lock()->notify_all();
 }
 
-// ------------------------------------------------------------------
-// CompileQueue::get
-//
-// Get the next CompileTask from a CompileQueue
+/**
+ * Get the next CompileTask from a CompileQueue
+ */
 CompileTask* CompileQueue::get() {
-  NMethodSweeper::possibly_sweep();
-
   MutexLocker locker(lock());
   // If _first is NULL we have no more compile jobs. There are two reasons for
   // having no compile jobs: First, we compiled everything we wanted. Second,
@@ -668,35 +663,16 @@
       return NULL;
     }
 
-    if (UseCodeCacheFlushing && !CompileBroker::should_compile_new_jobs()) {
-      // Wait a certain amount of time to possibly do another sweep.
-      // We must wait until stack scanning has happened so that we can
-      // transition a method's state from 'not_entrant' to 'zombie'.
-      long wait_time = NmethodSweepCheckInterval * 1000;
-      if (FLAG_IS_DEFAULT(NmethodSweepCheckInterval)) {
-        // Only one thread at a time can do sweeping. Scale the
-        // wait time according to the number of compiler threads.
-        // As a result, the next sweep is likely to happen every 100ms
-        // with an arbitrary number of threads that do sweeping.
-        wait_time = 100 * CICompilerCount;
-      }
-      bool timeout = lock()->wait(!Mutex::_no_safepoint_check_flag, wait_time);
-      if (timeout) {
-        MutexUnlocker ul(lock());
-        NMethodSweeper::possibly_sweep();
-      }
-    } else {
-      // If there are no compilation tasks and we can compile new jobs
-      // (i.e., there is enough free space in the code cache) there is
-      // no need to invoke the sweeper. As a result, the hotness of methods
-      // remains unchanged. This behavior is desired, since we want to keep
-      // the stable state, i.e., we do not want to evict methods from the
-      // code cache if it is unnecessary.
-      // We need a timed wait here, since compiler threads can exit if compilation
-      // is disabled forever. We use 5 seconds wait time; the exiting of compiler threads
-      // is not critical and we do not want idle compiler threads to wake up too often.
-      lock()->wait(!Mutex::_no_safepoint_check_flag, 5*1000);
-    }
+    // If there are no compilation tasks and we can compile new jobs
+    // (i.e., there is enough free space in the code cache) there is
+    // no need to invoke the sweeper. As a result, the hotness of methods
+    // remains unchanged. This behavior is desired, since we want to keep
+    // the stable state, i.e., we do not want to evict methods from the
+    // code cache if it is unnecessary.
+    // We need a timed wait here, since compiler threads can exit if compilation
+    // is disabled forever. We use 5 seconds wait time; the exiting of compiler threads
+    // is not critical and we do not want idle compiler threads to wake up too often.
+    lock()->wait(!Mutex::_no_safepoint_check_flag, 5*1000);
   }
 
   if (CompileBroker::is_compilation_disabled_forever()) {
@@ -886,8 +862,8 @@
   _compilers[1] = new SharkCompiler();
 #endif // SHARK
 
-  // Start the CompilerThreads
-  init_compiler_threads(c1_count, c2_count);
+  // Start the compiler thread(s) and the sweeper thread
+  init_compiler_sweeper_threads(c1_count, c2_count);
   // totalTime performance counter is always created as it is required
   // by the implementation of java.lang.management.CompilationMBean.
   {
@@ -991,13 +967,10 @@
 }
 
 
-CompilerThread* CompileBroker::make_compiler_thread(const char* name, CompileQueue* queue, CompilerCounters* counters,
-                                                    AbstractCompiler* comp, TRAPS) {
-  CompilerThread* compiler_thread = NULL;
-
-  Klass* k =
-    SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(),
-                                      true, CHECK_0);
+JavaThread* CompileBroker::make_thread(const char* name, CompileQueue* queue, CompilerCounters* counters,
+                                       AbstractCompiler* comp, bool compiler_thread, TRAPS) {
+  JavaThread* thread = NULL;
+  Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, CHECK_0);
   instanceKlassHandle klass (THREAD, k);
   instanceHandle thread_oop = klass->allocate_instance_handle(CHECK_0);
   Handle string = java_lang_String::create_from_str(name, CHECK_0);
@@ -1015,7 +988,11 @@
 
   {
     MutexLocker mu(Threads_lock, THREAD);
-    compiler_thread = new CompilerThread(queue, counters);
+    if (compiler_thread) {
+      thread = new CompilerThread(queue, counters);
+    } else {
+      thread = new CodeCacheSweeperThread();
+    }
     // At this point the new CompilerThread data-races with this startup
     // thread (which I believe is the primoridal thread and NOT the VM
     // thread).  This means Java bytecodes being executed at startup can
@@ -1028,12 +1005,12 @@
     // in that case. However, since this must work and we do not allow
     // exceptions anyway, check and abort if this fails.
 
-    if (compiler_thread == NULL || compiler_thread->osthread() == NULL){
+    if (thread == NULL || thread->osthread() == NULL) {
       vm_exit_during_initialization("java.lang.OutOfMemoryError",
                                     os::native_thread_creation_failed_msg());
     }
 
-    java_lang_Thread::set_thread(thread_oop(), compiler_thread);
+    java_lang_Thread::set_thread(thread_oop(), thread);
 
     // Note that this only sets the JavaThread _priority field, which by
     // definition is limited to Java priorities and not OS priorities.
@@ -1054,24 +1031,26 @@
         native_prio = os::java_to_os_priority[NearMaxPriority];
       }
     }
-    os::set_native_priority(compiler_thread, native_prio);
+    os::set_native_priority(thread, native_prio);
 
     java_lang_Thread::set_daemon(thread_oop());
 
-    compiler_thread->set_threadObj(thread_oop());
-    compiler_thread->set_compiler(comp);
-    Threads::add(compiler_thread);
-    Thread::start(compiler_thread);
+    thread->set_threadObj(thread_oop());
+    if (compiler_thread) {
+      thread->as_CompilerThread()->set_compiler(comp);
+    }
+    Threads::add(thread);
+    Thread::start(thread);
   }
 
   // Let go of Threads_lock before yielding
   os::naked_yield(); // make sure that the compiler thread is started early (especially helpful on SOLARIS)
 
-  return compiler_thread;
+  return thread;
 }
 
 
-void CompileBroker::init_compiler_threads(int c1_compiler_count, int c2_compiler_count) {
+void CompileBroker::init_compiler_sweeper_threads(int c1_compiler_count, int c2_compiler_count) {
   EXCEPTION_MARK;
 #if !defined(ZERO) && !defined(SHARK)
   assert(c2_compiler_count > 0 || c1_compiler_count > 0, "No compilers?");
@@ -1088,17 +1067,14 @@
 
   int compiler_count = c1_compiler_count + c2_compiler_count;
 
-  _compiler_threads =
-    new (ResourceObj::C_HEAP, mtCompiler) GrowableArray<CompilerThread*>(compiler_count, true);
-
   char name_buffer[256];
+  const bool compiler_thread = true;
   for (int i = 0; i < c2_compiler_count; i++) {
     // Create a name for our thread.
     sprintf(name_buffer, "C2 CompilerThread%d", i);
     CompilerCounters* counters = new CompilerCounters("compilerThread", i, CHECK);
     // Shark and C2
-    CompilerThread* new_thread = make_compiler_thread(name_buffer, _c2_compile_queue, counters, _compilers[1], CHECK);
-    _compiler_threads->append(new_thread);
+    make_thread(name_buffer, _c2_compile_queue, counters, _compilers[1], compiler_thread, CHECK);
   }
 
   for (int i = c2_compiler_count; i < compiler_count; i++) {
@@ -1106,13 +1082,17 @@
     sprintf(name_buffer, "C1 CompilerThread%d", i);
     CompilerCounters* counters = new CompilerCounters("compilerThread", i, CHECK);
     // C1
-    CompilerThread* new_thread = make_compiler_thread(name_buffer, _c1_compile_queue, counters, _compilers[0], CHECK);
-    _compiler_threads->append(new_thread);
+    make_thread(name_buffer, _c1_compile_queue, counters, _compilers[0], compiler_thread, CHECK);
   }
 
   if (UsePerfData) {
     PerfDataManager::create_constant(SUN_CI, "threads", PerfData::U_Bytes, compiler_count, CHECK);
   }
+
+  if (MethodFlushing) {
+    // Initialize the sweeper thread
+    make_thread("Sweeper thread", NULL, NULL, NULL, false, CHECK);
+  }
 }
 
 
@@ -1759,13 +1739,6 @@
     // We need this HandleMark to avoid leaking VM handles.
     HandleMark hm(thread);
 
-    // Check if the CodeCache is full
-    int code_blob_type = 0;
-    if (CodeCache::is_full(&code_blob_type)) {
-      // The CodeHeap for code_blob_type is really full
-      handle_full_code_cache(code_blob_type);
-    }
-
     CompileTask* task = queue->get();
     if (task == NULL) {
       continue;
@@ -1773,8 +1746,9 @@
 
     // Give compiler threads an extra quanta.  They tend to be bursty and
     // this helps the compiler to finish up the job.
-    if( CompilerThreadHintNoPreempt )
+    if (CompilerThreadHintNoPreempt) {
       os::hint_no_preempt();
+    }
 
     // trace per thread time and compile statistics
     CompilerCounters* counters = ((CompilerThread*)thread)->counters();
@@ -2074,8 +2048,10 @@
 }
 
 /**
- * The CodeCache is full.  Print out warning and disable compilation
- * or try code cache cleaning so compilation can continue later.
+ * The CodeCache is full. Print warning and disable compilation.
+ * Schedule code cache cleaning so compilation can continue later.
+ * This function needs to be called only from CodeCache::allocate(),
+ * since we currently handle a full code cache uniformly.
  */
 void CompileBroker::handle_full_code_cache(int code_blob_type) {
   UseInterpreter = true;
@@ -2107,10 +2083,6 @@
       if (CompileBroker::set_should_compile_new_jobs(CompileBroker::stop_compilation)) {
         NMethodSweeper::log_sweep("disable_compiler");
       }
-      // Switch to 'vm_state'. This ensures that possibly_sweep() can be called
-      // without having to consider the state in which the current thread is.
-      ThreadInVMfromUnknown in_vm;
-      NMethodSweeper::possibly_sweep();
     } else {
       disable_compilation_forever();
     }
--- a/hotspot/src/share/vm/compiler/compileBroker.hpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/compiler/compileBroker.hpp	Thu Oct 30 22:52:13 2014 -0700
@@ -290,8 +290,6 @@
   static CompileQueue* _c2_compile_queue;
   static CompileQueue* _c1_compile_queue;
 
-  static GrowableArray<CompilerThread*>* _compiler_threads;
-
   // performance counters
   static PerfCounter* _perf_total_compilation;
   static PerfCounter* _perf_native_compilation;
@@ -339,8 +337,8 @@
 
   static volatile jint _print_compilation_warning;
 
-  static CompilerThread* make_compiler_thread(const char* name, CompileQueue* queue, CompilerCounters* counters, AbstractCompiler* comp, TRAPS);
-  static void init_compiler_threads(int c1_compiler_count, int c2_compiler_count);
+  static JavaThread* make_thread(const char* name, CompileQueue* queue, CompilerCounters* counters, AbstractCompiler* comp, bool compiler_thread, TRAPS);
+  static void init_compiler_sweeper_threads(int c1_compiler_count, int c2_compiler_count);
   static bool compilation_is_complete  (methodHandle method, int osr_bci, int comp_level);
   static bool compilation_is_prohibited(methodHandle method, int osr_bci, int comp_level);
   static bool is_compile_blocking();
--- a/hotspot/src/share/vm/interpreter/interpreterRuntime.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/interpreter/interpreterRuntime.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -1077,7 +1077,6 @@
 address SignatureHandlerLibrary::set_handler_blob() {
   BufferBlob* handler_blob = BufferBlob::create("native signature handlers", blob_size);
   if (handler_blob == NULL) {
-    CompileBroker::handle_full_code_cache(CodeBlobType::NonNMethod);
     return NULL;
   }
   address handler = handler_blob->code_begin();
--- a/hotspot/src/share/vm/memory/heap.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/memory/heap.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -171,13 +171,13 @@
 }
 
 
-void* CodeHeap::allocate(size_t instance_size, bool is_critical) {
+void* CodeHeap::allocate(size_t instance_size) {
   size_t number_of_segments = size_to_segments(instance_size + header_size());
   assert(segments_to_size(number_of_segments) >= sizeof(FreeBlock), "not enough room for FreeList");
 
   // First check if we can satisfy request from freelist
   NOT_PRODUCT(verify());
-  HeapBlock* block = search_freelist(number_of_segments, is_critical);
+  HeapBlock* block = search_freelist(number_of_segments);
   NOT_PRODUCT(verify());
 
   if (block != NULL) {
@@ -191,15 +191,6 @@
   // Ensure minimum size for allocation to the heap.
   number_of_segments = MAX2((int)CodeCacheMinBlockLength, (int)number_of_segments);
 
-  if (!is_critical) {
-    // Make sure the allocation fits in the unallocated heap without using
-    // the CodeCacheMimimumFreeSpace that is reserved for critical allocations.
-    if (segments_to_size(number_of_segments) > (heap_unallocated_capacity() - CodeCacheMinimumFreeSpace)) {
-      // Fail allocation
-      return NULL;
-    }
-  }
-
   if (_next_segment + number_of_segments <= _number_of_committed_segments) {
     mark_segmap_as_used(_next_segment, _next_segment + number_of_segments);
     HeapBlock* b =  block_at(_next_segment);
@@ -427,24 +418,17 @@
  * Search freelist for an entry on the list with the best fit.
  * @return NULL, if no one was found
  */
-FreeBlock* CodeHeap::search_freelist(size_t length, bool is_critical) {
+FreeBlock* CodeHeap::search_freelist(size_t length) {
   FreeBlock* found_block = NULL;
   FreeBlock* found_prev  = NULL;
   size_t     found_length = 0;
 
   FreeBlock* prev = NULL;
   FreeBlock* cur = _freelist;
-  const size_t critical_boundary = (size_t)high_boundary() - CodeCacheMinimumFreeSpace;
 
   // Search for first block that fits
   while(cur != NULL) {
     if (cur->length() >= length) {
-      // Non critical allocations are not allowed to use the last part of the code heap.
-      // Make sure the end of the allocation doesn't cross into the last part of the code heap.
-      if (!is_critical && (((size_t)cur + length) > critical_boundary)) {
-        // The freelist is sorted by address - if one fails, all consecutive will also fail.
-        break;
-      }
       // Remember block, its previous element, and its length
       found_block = cur;
       found_prev  = prev;
--- a/hotspot/src/share/vm/memory/heap.hpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/memory/heap.hpp	Thu Oct 30 22:52:13 2014 -0700
@@ -120,7 +120,7 @@
 
   // Toplevel freelist management
   void add_to_freelist(HeapBlock* b);
-  FreeBlock* search_freelist(size_t length, bool is_critical);
+  FreeBlock* search_freelist(size_t length);
 
   // Iteration helpers
   void*      next_free(HeapBlock* b) const;
@@ -140,8 +140,8 @@
   bool  expand_by(size_t size);                  // expands committed memory by size
 
   // Memory allocation
-  void* allocate  (size_t size, bool is_critical);  // allocates a block of size or returns NULL
-  void  deallocate(void* p);                        // deallocates a block
+  void* allocate (size_t size); // Allocate 'size' bytes in the code cache or return NULL
+  void  deallocate(void* p);    // Deallocate memory
 
   // Attributes
   char* low_boundary() const                     { return _memory.low_boundary (); }
--- a/hotspot/src/share/vm/memory/metaspace.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/memory/metaspace.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -3157,6 +3157,16 @@
     SharedMiscDataSize  = align_size_up(SharedMiscDataSize,  max_alignment);
     SharedMiscCodeSize  = align_size_up(SharedMiscCodeSize,  max_alignment);
 
+    // the min_misc_code_size estimate is based on MetaspaceShared::generate_vtable_methods()
+    uintx min_misc_code_size = align_size_up(
+      (MetaspaceShared::num_virtuals * MetaspaceShared::vtbl_list_size) *
+        (sizeof(void*) + MetaspaceShared::vtbl_method_size) + MetaspaceShared::vtbl_common_code_size,
+          max_alignment);
+
+    if (SharedMiscCodeSize < min_misc_code_size) {
+      report_out_of_shared_space(SharedMiscCode);
+    }
+
     // Initialize with the sum of the shared space sizes.  The read-only
     // and read write metaspace chunks will be allocated out of this and the
     // remainder is the misc code and data chunks.
--- a/hotspot/src/share/vm/memory/metaspaceShared.hpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/memory/metaspaceShared.hpp	Thu Oct 30 22:52:13 2014 -0700
@@ -57,11 +57,16 @@
   static bool _archive_loading_failed;
  public:
   enum {
-    vtbl_list_size = 17, // number of entries in the shared space vtable list.
-    num_virtuals = 200   // maximum number of virtual functions
-                         // If virtual functions are added to Metadata,
-                         // this number needs to be increased.  Also,
-                         // SharedMiscCodeSize will need to be increased.
+    vtbl_list_size         = 17,   // number of entries in the shared space vtable list.
+    num_virtuals           = 200,  // maximum number of virtual functions
+                                   // If virtual functions are added to Metadata,
+                                   // this number needs to be increased.  Also,
+                                   // SharedMiscCodeSize will need to be increased.
+                                   // The following 2 sizes were based on
+                                   // MetaspaceShared::generate_vtable_methods()
+    vtbl_method_size       = 16,   // conservative size of the mov1 and jmp instructions
+                                   // for the x64 platform
+    vtbl_common_code_size  = (1*K) // conservative size of the "common_code" for the x64 platform
   };
 
   enum {
--- a/hotspot/src/share/vm/oops/constantPool.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/oops/constantPool.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -206,7 +206,8 @@
   }
 }
 
-Klass* ConstantPool::klass_at_impl(constantPoolHandle this_cp, int which, TRAPS) {
+Klass* ConstantPool::klass_at_impl(constantPoolHandle this_cp, int which,
+                                   bool save_resolution_error, TRAPS) {
   assert(THREAD->is_Java_thread(), "must be a Java thread");
 
   // A resolved constantPool entry will contain a Klass*, otherwise a Symbol*.
@@ -249,7 +250,18 @@
   // Failed to resolve class. We must record the errors so that subsequent attempts
   // to resolve this constant pool entry fail with the same error (JVMS 5.4.3).
   if (HAS_PENDING_EXCEPTION) {
-    save_and_throw_exception(this_cp, which, constantTag(JVM_CONSTANT_UnresolvedClass), CHECK_0);
+    if (save_resolution_error) {
+      save_and_throw_exception(this_cp, which, constantTag(JVM_CONSTANT_UnresolvedClass), CHECK_NULL);
+      // If CHECK_NULL above doesn't return the exception, that means that
+      // some other thread has beaten us and has resolved the class.
+      // To preserve old behavior, we return the resolved class.
+      entry = this_cp->resolved_klass_at(which);
+      assert(entry.is_resolved(), "must be resolved if exception was cleared");
+      assert(entry.get_klass()->is_klass(), "must be resolved to a klass");
+      return entry.get_klass();
+    } else {
+      return NULL;  // return the pending exception
+    }
   }
 
   // Make this class loader depend upon the class loader owning the class reference
@@ -260,10 +272,10 @@
     // skip resolving the constant pool so that this code gets
     // called the next time some bytecodes refer to this class.
     trace_class_resolution(this_cp, k);
-      return k();
-    } else {
-        this_cp->klass_at_put(which, k());
-      }
+    return k();
+  } else {
+    this_cp->klass_at_put(which, k());
+  }
 
   entry = this_cp->resolved_klass_at(which);
   assert(entry.is_resolved() && entry.get_klass()->is_klass(), "must be resolved at this point");
@@ -573,24 +585,25 @@
     Symbol* message = exception_message(this_cp, which, tag, PENDING_EXCEPTION);
     SystemDictionary::add_resolution_error(this_cp, which, error, message);
     // CAS in the tag.  If a thread beat us to registering this error that's fine.
-    // If another thread resolved the reference, this is an error.  The resolution
-    // must deterministically get an error.   So why do we save this?
-    // We save this because jvmti can add classes to the bootclass path after this
-    // error, so it needs to get the same error if the error is first.
+    // If another thread resolved the reference, this is a race condition. This
+    // thread may have had a security manager or something temporary.
+    // This doesn't deterministically get an error.   So why do we save this?
+    // We save this because jvmti can add classes to the bootclass path after
+    // this error, so it needs to get the same error if the error is first.
     jbyte old_tag = Atomic::cmpxchg((jbyte)error_tag,
                             (jbyte*)this_cp->tag_addr_at(which), (jbyte)tag.value());
-    assert(old_tag == error_tag || old_tag == tag.value(), "should not be resolved otherwise");
+    if (old_tag != error_tag && old_tag != tag.value()) {
+      // MethodHandles and MethodType doesn't change to resolved version.
+      assert(this_cp->tag_at(which).is_klass(), "Wrong tag value");
+      // Forget the exception and use the resolved class.
+      CLEAR_PENDING_EXCEPTION;
+    }
   } else {
     // some other thread put this in error state
     throw_resolution_error(this_cp, which, CHECK);
   }
-
-  // This exits with some pending exception
-  assert(HAS_PENDING_EXCEPTION, "should not be cleared");
 }
 
-
-
 // Called to resolve constants in the constant pool and return an oop.
 // Some constant pool entries cache their resolved oop. This is also
 // called to create oops from constants to use in arguments for invokedynamic
@@ -627,7 +640,7 @@
   case JVM_CONSTANT_Class:
     {
       assert(cache_index == _no_index_sentinel, "should not have been set");
-      Klass* resolved = klass_at_impl(this_cp, index, CHECK_NULL);
+      Klass* resolved = klass_at_impl(this_cp, index, true, CHECK_NULL);
       // ldc wants the java mirror.
       result_oop = resolved->java_mirror();
       break;
@@ -660,7 +673,7 @@
                       ref_kind, index, this_cp->method_handle_index_at(index),
                       callee_index, name->as_C_string(), signature->as_C_string());
       KlassHandle callee;
-      { Klass* k = klass_at_impl(this_cp, callee_index, CHECK_NULL);
+      { Klass* k = klass_at_impl(this_cp, callee_index, true, CHECK_NULL);
         callee = KlassHandle(THREAD, k);
       }
       KlassHandle klass(THREAD, this_cp->pool_holder());
--- a/hotspot/src/share/vm/oops/constantPool.hpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/oops/constantPool.hpp	Thu Oct 30 22:52:13 2014 -0700
@@ -336,7 +336,13 @@
 
   Klass* klass_at(int which, TRAPS) {
     constantPoolHandle h_this(THREAD, this);
-    return klass_at_impl(h_this, which, CHECK_NULL);
+    return klass_at_impl(h_this, which, true, CHECK_NULL);
+  }
+
+  // Version of klass_at that doesn't save the resolution error, called during deopt
+  Klass* klass_at_ignore_error(int which, TRAPS) {
+    constantPoolHandle h_this(THREAD, this);
+    return klass_at_impl(h_this, which, false, CHECK_NULL);
   }
 
   Symbol* klass_name_at(int which);  // Returns the name, w/o resolving.
@@ -793,7 +799,8 @@
 
   // Implementation of methods that needs an exposed 'this' pointer, in order to
   // handle GC while executing the method
-  static Klass* klass_at_impl(constantPoolHandle this_cp, int which, TRAPS);
+  static Klass* klass_at_impl(constantPoolHandle this_cp, int which,
+                              bool save_resolution_error, TRAPS);
   static oop string_at_impl(constantPoolHandle this_cp, int which, int obj_index, TRAPS);
 
   static void trace_class_resolution(constantPoolHandle this_cp, KlassHandle k);
--- a/hotspot/src/share/vm/oops/instanceKlass.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/oops/instanceKlass.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -736,6 +736,41 @@
   }
 }
 
+// Eagerly initialize superinterfaces that declare default methods (concrete instance: any access)
+void InstanceKlass::initialize_super_interfaces(instanceKlassHandle this_k, TRAPS) {
+  if (this_k->has_default_methods()) {
+    for (int i = 0; i < this_k->local_interfaces()->length(); ++i) {
+      Klass* iface = this_k->local_interfaces()->at(i);
+      InstanceKlass* ik = InstanceKlass::cast(iface);
+      if (ik->should_be_initialized()) {
+        if (ik->has_default_methods()) {
+          ik->initialize_super_interfaces(ik, THREAD);
+        }
+        // Only initialize() interfaces that "declare" concrete methods.
+        // has_default_methods drives searching superinterfaces since it
+        // means has_default_methods in its superinterface hierarchy
+        if (!HAS_PENDING_EXCEPTION && ik->declares_default_methods()) {
+          ik->initialize(THREAD);
+        }
+        if (HAS_PENDING_EXCEPTION) {
+          Handle e(THREAD, PENDING_EXCEPTION);
+          CLEAR_PENDING_EXCEPTION;
+          {
+            EXCEPTION_MARK;
+            // Locks object, set state, and notify all waiting threads
+            this_k->set_initialization_state_and_notify(
+                initialization_error, THREAD);
+
+            // ignore any exception thrown, superclass initialization error is
+            // thrown below
+            CLEAR_PENDING_EXCEPTION;
+          }
+          THROW_OOP(e());
+        }
+      }
+    }
+  }
+}
 
 void InstanceKlass::initialize_impl(instanceKlassHandle this_k, TRAPS) {
   // Make sure klass is linked (verified) before initialization
@@ -815,33 +850,11 @@
     }
   }
 
+  // Recursively initialize any superinterfaces that declare default methods
+  // Only need to recurse if has_default_methods which includes declaring and
+  // inheriting default methods
   if (this_k->has_default_methods()) {
-    // Step 7.5: initialize any interfaces which have default methods
-    for (int i = 0; i < this_k->local_interfaces()->length(); ++i) {
-      Klass* iface = this_k->local_interfaces()->at(i);
-      InstanceKlass* ik = InstanceKlass::cast(iface);
-      if (ik->has_default_methods() && ik->should_be_initialized()) {
-        ik->initialize(THREAD);
-
-        if (HAS_PENDING_EXCEPTION) {
-          Handle e(THREAD, PENDING_EXCEPTION);
-          CLEAR_PENDING_EXCEPTION;
-          {
-            EXCEPTION_MARK;
-            // Locks object, set state, and notify all waiting threads
-            this_k->set_initialization_state_and_notify(
-                initialization_error, THREAD);
-
-            // ignore any exception thrown, superclass initialization error is
-            // thrown below
-            CLEAR_PENDING_EXCEPTION;
-          }
-          DTRACE_CLASSINIT_PROBE_WAIT(
-              super__failed, InstanceKlass::cast(this_k()), -1, wait);
-          THROW_OOP(e());
-        }
-      }
-    }
+    this_k->initialize_super_interfaces(this_k, CHECK);
   }
 
   // Step 8
@@ -2779,19 +2792,18 @@
 // On-stack replacement stuff
 void InstanceKlass::add_osr_nmethod(nmethod* n) {
   // only one compilation can be active
-  NEEDS_CLEANUP
-  // This is a short non-blocking critical region, so the no safepoint check is ok.
-  OsrList_lock->lock_without_safepoint_check();
-  assert(n->is_osr_method(), "wrong kind of nmethod");
-  n->set_osr_link(osr_nmethods_head());
-  set_osr_nmethods_head(n);
-  // Raise the highest osr level if necessary
-  if (TieredCompilation) {
-    Method* m = n->method();
-    m->set_highest_osr_comp_level(MAX2(m->highest_osr_comp_level(), n->comp_level()));
+  {
+    // This is a short non-blocking critical region, so the no safepoint check is ok.
+    MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
+    assert(n->is_osr_method(), "wrong kind of nmethod");
+    n->set_osr_link(osr_nmethods_head());
+    set_osr_nmethods_head(n);
+    // Raise the highest osr level if necessary
+    if (TieredCompilation) {
+      Method* m = n->method();
+      m->set_highest_osr_comp_level(MAX2(m->highest_osr_comp_level(), n->comp_level()));
+    }
   }
-  // Remember to unlock again
-  OsrList_lock->unlock();
 
   // Get rid of the osr methods for the same bci that have lower levels.
   if (TieredCompilation) {
@@ -2807,7 +2819,7 @@
 
 void InstanceKlass::remove_osr_nmethod(nmethod* n) {
   // This is a short non-blocking critical region, so the no safepoint check is ok.
-  OsrList_lock->lock_without_safepoint_check();
+  MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
   assert(n->is_osr_method(), "wrong kind of nmethod");
   nmethod* last = NULL;
   nmethod* cur  = osr_nmethods_head();
@@ -2844,13 +2856,27 @@
     }
     m->set_highest_osr_comp_level(max_level);
   }
-  // Remember to unlock again
-  OsrList_lock->unlock();
+}
+
+int InstanceKlass::mark_osr_nmethods(const Method* m) {
+  // This is a short non-blocking critical region, so the no safepoint check is ok.
+  MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
+  nmethod* osr = osr_nmethods_head();
+  int found = 0;
+  while (osr != NULL) {
+    assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
+    if (osr->method() == m) {
+      osr->mark_for_deoptimization();
+      found++;
+    }
+    osr = osr->osr_link();
+  }
+  return found;
 }
 
 nmethod* InstanceKlass::lookup_osr_nmethod(const Method* m, int bci, int comp_level, bool match_level) const {
   // This is a short non-blocking critical region, so the no safepoint check is ok.
-  OsrList_lock->lock_without_safepoint_check();
+  MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
   nmethod* osr = osr_nmethods_head();
   nmethod* best = NULL;
   while (osr != NULL) {
@@ -2866,14 +2892,12 @@
       if (match_level) {
         if (osr->comp_level() == comp_level) {
           // Found a match - return it.
-          OsrList_lock->unlock();
           return osr;
         }
       } else {
         if (best == NULL || (osr->comp_level() > best->comp_level())) {
           if (osr->comp_level() == CompLevel_highest_tier) {
             // Found the best possible - return it.
-            OsrList_lock->unlock();
             return osr;
           }
           best = osr;
@@ -2882,7 +2906,6 @@
     }
     osr = osr->osr_link();
   }
-  OsrList_lock->unlock();
   if (best != NULL && best->comp_level() >= comp_level && match_level == false) {
     return best;
   }
--- a/hotspot/src/share/vm/oops/instanceKlass.hpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/oops/instanceKlass.hpp	Thu Oct 30 22:52:13 2014 -0700
@@ -199,13 +199,14 @@
   bool            _has_unloaded_dependent;
 
   enum {
-    _misc_rewritten            = 1 << 0, // methods rewritten.
-    _misc_has_nonstatic_fields = 1 << 1, // for sizing with UseCompressedOops
-    _misc_should_verify_class  = 1 << 2, // allow caching of preverification
-    _misc_is_anonymous         = 1 << 3, // has embedded _host_klass field
-    _misc_is_contended         = 1 << 4, // marked with contended annotation
-    _misc_has_default_methods  = 1 << 5, // class/superclass/implemented interfaces has default methods
-    _misc_has_been_redefined   = 1 << 6  // class has been redefined
+    _misc_rewritten                = 1 << 0, // methods rewritten.
+    _misc_has_nonstatic_fields     = 1 << 1, // for sizing with UseCompressedOops
+    _misc_should_verify_class      = 1 << 2, // allow caching of preverification
+    _misc_is_anonymous             = 1 << 3, // has embedded _host_klass field
+    _misc_is_contended             = 1 << 4, // marked with contended annotation
+    _misc_has_default_methods      = 1 << 5, // class/superclass/implemented interfaces has default methods
+    _misc_declares_default_methods = 1 << 6, // directly declares default methods (any access)
+    _misc_has_been_redefined       = 1 << 7  // class has been redefined
   };
   u2              _misc_flags;
   u2              _minor_version;        // minor version number of class file
@@ -651,6 +652,17 @@
     }
   }
 
+  bool declares_default_methods() const {
+    return (_misc_flags & _misc_declares_default_methods) != 0;
+  }
+  void set_declares_default_methods(bool b) {
+    if (b) {
+      _misc_flags |= _misc_declares_default_methods;
+    } else {
+      _misc_flags &= ~_misc_declares_default_methods;
+    }
+  }
+
   // for adding methods, ConstMethod::UNSET_IDNUM means no more ids available
   inline u2 next_method_idnum();
   void set_initial_method_idnum(u2 value)             { _idnum_allocated_count = value; }
@@ -742,6 +754,7 @@
   void set_osr_nmethods_head(nmethod* h)     { _osr_nmethods_head = h; };
   void add_osr_nmethod(nmethod* n);
   void remove_osr_nmethod(nmethod* n);
+  int mark_osr_nmethods(const Method* m);
   nmethod* lookup_osr_nmethod(const Method* m, int bci, int level, bool match_level) const;
 
   // Breakpoint support (see methods on Method* for details)
@@ -1022,6 +1035,7 @@
   static bool link_class_impl                           (instanceKlassHandle this_k, bool throw_verifyerror, TRAPS);
   static bool verify_code                               (instanceKlassHandle this_k, bool throw_verifyerror, TRAPS);
   static void initialize_impl                           (instanceKlassHandle this_k, TRAPS);
+  static void initialize_super_interfaces               (instanceKlassHandle this_k, TRAPS);
   static void eager_initialize_impl                     (instanceKlassHandle this_k);
   static void set_initialization_state_and_notify_impl  (instanceKlassHandle this_k, ClassState state, TRAPS);
   static void call_class_initializer_impl               (instanceKlassHandle this_k, TRAPS);
--- a/hotspot/src/share/vm/oops/method.hpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/oops/method.hpp	Thu Oct 30 22:52:13 2014 -0700
@@ -813,6 +813,10 @@
    return method_holder()->lookup_osr_nmethod(this, InvocationEntryBci, level, match_level) != NULL;
   }
 
+  int mark_osr_nmethods() {
+    return method_holder()->mark_osr_nmethods(this);
+  }
+
   nmethod* lookup_osr_nmethod_for(int bci, int level, bool match_level) {
     return method_holder()->lookup_osr_nmethod(this, bci, level, match_level);
   }
--- a/hotspot/src/share/vm/oops/objArrayOop.hpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/oops/objArrayOop.hpp	Thu Oct 30 22:52:13 2014 -0700
@@ -45,9 +45,10 @@
 private:
   // Give size of objArrayOop in HeapWords minus the header
   static int array_size(int length) {
-    const int OopsPerHeapWord = HeapWordSize/heapOopSize;
+    const uint OopsPerHeapWord = HeapWordSize/heapOopSize;
     assert(OopsPerHeapWord >= 1 && (HeapWordSize % heapOopSize == 0),
            "Else the following (new) computation would be in error");
+    uint res = ((uint)length + OopsPerHeapWord - 1)/OopsPerHeapWord;
 #ifdef ASSERT
     // The old code is left in for sanity-checking; it'll
     // go away pretty soon. XXX
@@ -55,16 +56,15 @@
     // oop->length() * HeapWordsPerOop;
     // With narrowOops, HeapWordsPerOop is 1/2 or equal 0 as an integer.
     // The oop elements are aligned up to wordSize
-    const int HeapWordsPerOop = heapOopSize/HeapWordSize;
-    int old_res;
+    const uint HeapWordsPerOop = heapOopSize/HeapWordSize;
+    uint old_res;
     if (HeapWordsPerOop > 0) {
       old_res = length * HeapWordsPerOop;
     } else {
-      old_res = align_size_up(length, OopsPerHeapWord)/OopsPerHeapWord;
+      old_res = align_size_up((uint)length, OopsPerHeapWord)/OopsPerHeapWord;
     }
+    assert(res == old_res, "Inconsistency between old and new.");
 #endif  // ASSERT
-    int res = ((uint)length + OopsPerHeapWord - 1)/OopsPerHeapWord;
-    assert(res == old_res, "Inconsistency between old and new.");
     return res;
   }
 
--- a/hotspot/src/share/vm/oops/typeArrayOop.hpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/oops/typeArrayOop.hpp	Thu Oct 30 22:52:13 2014 -0700
@@ -150,7 +150,7 @@
     DEBUG_ONLY(BasicType etype = Klass::layout_helper_element_type(lh));
     assert(length <= arrayOopDesc::max_array_length(etype), "no overflow");
 
-    julong size_in_bytes = length;
+    julong size_in_bytes = (juint)length;
     size_in_bytes <<= element_shift;
     size_in_bytes += instance_header_size;
     julong size_in_words = ((size_in_bytes + (HeapWordSize-1)) >> LogHeapWordSize);
--- a/hotspot/src/share/vm/opto/c2_globals.hpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/opto/c2_globals.hpp	Thu Oct 30 22:52:13 2014 -0700
@@ -476,6 +476,9 @@
   product(bool, DoEscapeAnalysis, true,                                     \
           "Perform escape analysis")                                        \
                                                                             \
+  product(double, EscapeAnalysisTimeout, 20. DEBUG_ONLY(+40.),              \
+          "Abort EA when it reaches time limit (in sec)")                   \
+                                                                            \
   develop(bool, ExitEscapeAnalysisOnTimeout, true,                          \
           "Exit or throw assert in EA when it reaches time limit")          \
                                                                             \
--- a/hotspot/src/share/vm/opto/callnode.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/opto/callnode.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -939,7 +939,8 @@
 #ifndef PRODUCT
   if (!(call->req() > TypeFunc::Parms &&
         call->in(TypeFunc::Parms) != NULL &&
-        call->in(TypeFunc::Parms)->is_Con())) {
+        call->in(TypeFunc::Parms)->is_Con() &&
+        call->in(TypeFunc::Parms)->bottom_type()->isa_int())) {
     assert(in_dump() != 0, "OK if dumping");
     tty->print("[bad uncommon trap]");
     return 0;
--- a/hotspot/src/share/vm/opto/coalesce.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/opto/coalesce.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -281,9 +281,11 @@
             Block *pred = _phc._cfg.get_block_for_node(b->pred(j));
             Node *copy;
             assert(!m->is_Con() || m->is_Mach(), "all Con must be Mach");
-            // Rematerialize constants instead of copying them
-            if( m->is_Mach() && m->as_Mach()->is_Con() &&
-                m->as_Mach()->rematerialize() ) {
+            // Rematerialize constants instead of copying them.
+            // We do this only for immediate constants, we avoid constant table loads
+            // because that will unsafely extend the live range of the constant table base.
+            if (m->is_Mach() && m->as_Mach()->is_Con() && !m->as_Mach()->is_MachConstant() &&
+                m->as_Mach()->rematerialize()) {
               copy = m->clone();
               // Insert the copy in the predecessor basic block
               pred->add_inst(copy);
@@ -317,8 +319,8 @@
             assert(!m->is_Con() || m->is_Mach(), "all Con must be Mach");
             // At this point it is unsafe to extend live ranges (6550579).
             // Rematerialize only constants as we do for Phi above.
-            if(m->is_Mach() && m->as_Mach()->is_Con() &&
-               m->as_Mach()->rematerialize()) {
+            if (m->is_Mach() && m->as_Mach()->is_Con() && !m->as_Mach()->is_MachConstant() &&
+                m->as_Mach()->rematerialize()) {
               copy = m->clone();
               // Insert the copy in the basic block, just before us
               b->insert_node(copy, l++);
--- a/hotspot/src/share/vm/opto/compile.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/opto/compile.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -535,7 +535,6 @@
     if (scratch_buffer_blob() == NULL) {
       // Let CompilerBroker disable further compilations.
       record_failure("Not enough space for scratch buffer in CodeCache");
-      CompileBroker::handle_full_code_cache(CodeBlobType::NonNMethod);
       return;
     }
   }
--- a/hotspot/src/share/vm/opto/escape.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/opto/escape.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -38,6 +38,8 @@
 
 ConnectionGraph::ConnectionGraph(Compile * C, PhaseIterGVN *igvn) :
   _nodes(C->comp_arena(), C->unique(), C->unique(), NULL),
+  _in_worklist(C->comp_arena()),
+  _next_pidx(0),
   _collecting(true),
   _verify(false),
   _compile(C),
@@ -125,13 +127,19 @@
   if (C->root() != NULL) {
     ideal_nodes.push(C->root());
   }
+  // Processed ideal nodes are unique on ideal_nodes list
+  // but several ideal nodes are mapped to the phantom_obj.
+  // To avoid duplicated entries on the following worklists
+  // add the phantom_obj only once to them.
+  ptnodes_worklist.append(phantom_obj);
+  java_objects_worklist.append(phantom_obj);
   for( uint next = 0; next < ideal_nodes.size(); ++next ) {
     Node* n = ideal_nodes.at(next);
     // Create PointsTo nodes and add them to Connection Graph. Called
     // only once per ideal node since ideal_nodes is Unique_Node list.
     add_node_to_connection_graph(n, &delayed_worklist);
     PointsToNode* ptn = ptnode_adr(n->_idx);
-    if (ptn != NULL) {
+    if (ptn != NULL && ptn != phantom_obj) {
       ptnodes_worklist.append(ptn);
       if (ptn->is_JavaObject()) {
         java_objects_worklist.append(ptn->as_JavaObject());
@@ -415,7 +423,7 @@
     }
     case Op_CreateEx: {
       // assume that all exception objects globally escape
-      add_java_object(n, PointsToNode::GlobalEscape);
+      map_ideal_node(n, phantom_obj);
       break;
     }
     case Op_LoadKlass:
@@ -1074,13 +1082,8 @@
   // on graph complexity. Observed 8 passes in jvm2008 compiler.compiler.
   // Set limit to 20 to catch situation when something did go wrong and
   // bailout Escape Analysis.
-  // Also limit build time to 30 sec (60 in debug VM).
+  // Also limit build time to 20 sec (60 in debug VM), EscapeAnalysisTimeout flag.
 #define CG_BUILD_ITER_LIMIT 20
-#ifdef ASSERT
-#define CG_BUILD_TIME_LIMIT 60.0
-#else
-#define CG_BUILD_TIME_LIMIT 30.0
-#endif
 
   // Propagate GlobalEscape and ArgEscape escape states and check that
   // we still have non-escaping objects. The method pushs on _worklist
@@ -1091,12 +1094,13 @@
   // Now propagate references to all JavaObject nodes.
   int java_objects_length = java_objects_worklist.length();
   elapsedTimer time;
+  bool timeout = false;
   int new_edges = 1;
   int iterations = 0;
   do {
     while ((new_edges > 0) &&
-          (iterations++   < CG_BUILD_ITER_LIMIT) &&
-          (time.seconds() < CG_BUILD_TIME_LIMIT)) {
+           (iterations++ < CG_BUILD_ITER_LIMIT)) {
+      double start_time = time.seconds();
       time.start();
       new_edges = 0;
       // Propagate references to phantom_object for nodes pushed on _worklist
@@ -1105,7 +1109,26 @@
       for (int next = 0; next < java_objects_length; ++next) {
         JavaObjectNode* ptn = java_objects_worklist.at(next);
         new_edges += add_java_object_edges(ptn, true);
+
+#define SAMPLE_SIZE 4
+        if ((next % SAMPLE_SIZE) == 0) {
+          // Each 4 iterations calculate how much time it will take
+          // to complete graph construction.
+          time.stop();
+          double stop_time = time.seconds();
+          double time_per_iter = (stop_time - start_time) / (double)SAMPLE_SIZE;
+          double time_until_end = time_per_iter * (double)(java_objects_length - next);
+          if ((start_time + time_until_end) >= EscapeAnalysisTimeout) {
+            timeout = true;
+            break; // Timeout
+          }
+          start_time = stop_time;
+          time.start();
+        }
+#undef SAMPLE_SIZE
+
       }
+      if (timeout) break;
       if (new_edges > 0) {
         // Update escape states on each iteration if graph was updated.
         if (!find_non_escaped_objects(ptnodes_worklist, non_escaped_worklist)) {
@@ -1113,9 +1136,12 @@
         }
       }
       time.stop();
+      if (time.seconds() >= EscapeAnalysisTimeout) {
+        timeout = true;
+        break;
+      }
     }
-    if ((iterations     < CG_BUILD_ITER_LIMIT) &&
-        (time.seconds() < CG_BUILD_TIME_LIMIT)) {
+    if ((iterations < CG_BUILD_ITER_LIMIT) && !timeout) {
       time.start();
       // Find fields which have unknown value.
       int fields_length = oop_fields_worklist.length();
@@ -1128,18 +1154,21 @@
         }
       }
       time.stop();
+      if (time.seconds() >= EscapeAnalysisTimeout) {
+        timeout = true;
+        break;
+      }
     } else {
       new_edges = 0; // Bailout
     }
   } while (new_edges > 0);
 
   // Bailout if passed limits.
-  if ((iterations     >= CG_BUILD_ITER_LIMIT) ||
-      (time.seconds() >= CG_BUILD_TIME_LIMIT)) {
+  if ((iterations >= CG_BUILD_ITER_LIMIT) || timeout) {
     Compile* C = _compile;
     if (C->log() != NULL) {
       C->log()->begin_elem("connectionGraph_bailout reason='reached ");
-      C->log()->text("%s", (iterations >= CG_BUILD_ITER_LIMIT) ? "iterations" : "time");
+      C->log()->text("%s", timeout ? "time" : "iterations");
       C->log()->end_elem(" limit'");
     }
     assert(ExitEscapeAnalysisOnTimeout, err_msg_res("infinite EA connection graph build (%f sec, %d iterations) with %d nodes and worklist size %d",
@@ -1156,7 +1185,6 @@
 #endif
 
 #undef CG_BUILD_ITER_LIMIT
-#undef CG_BUILD_TIME_LIMIT
 
   // Find fields initialized by NULL for non-escaping Allocations.
   int non_escaped_length = non_escaped_worklist.length();
@@ -1280,8 +1308,8 @@
       }
     }
   }
-  while(_worklist.length() > 0) {
-    PointsToNode* use = _worklist.pop();
+  for (int l = 0; l < _worklist.length(); l++) {
+    PointsToNode* use = _worklist.at(l);
     if (PointsToNode::is_base_use(use)) {
       // Add reference from jobj to field and from field to jobj (field's base).
       use = PointsToNode::get_use_node(use)->as_Field();
@@ -1328,6 +1356,8 @@
       add_field_uses_to_worklist(use->as_Field());
     }
   }
+  _worklist.clear();
+  _in_worklist.Reset();
   return new_edges;
 }
 
@@ -1906,7 +1936,7 @@
     return;
   }
   Compile* C = _compile;
-  ptadr = new (C->comp_arena()) LocalVarNode(C, n, es);
+  ptadr = new (C->comp_arena()) LocalVarNode(this, n, es);
   _nodes.at_put(n->_idx, ptadr);
 }
 
@@ -1917,7 +1947,7 @@
     return;
   }
   Compile* C = _compile;
-  ptadr = new (C->comp_arena()) JavaObjectNode(C, n, es);
+  ptadr = new (C->comp_arena()) JavaObjectNode(this, n, es);
   _nodes.at_put(n->_idx, ptadr);
 }
 
@@ -1933,7 +1963,7 @@
     es = PointsToNode::GlobalEscape;
   }
   Compile* C = _compile;
-  FieldNode* field = new (C->comp_arena()) FieldNode(C, n, es, offset, is_oop);
+  FieldNode* field = new (C->comp_arena()) FieldNode(this, n, es, offset, is_oop);
   _nodes.at_put(n->_idx, field);
 }
 
@@ -1947,7 +1977,7 @@
     return;
   }
   Compile* C = _compile;
-  ptadr = new (C->comp_arena()) ArraycopyNode(C, n, es);
+  ptadr = new (C->comp_arena()) ArraycopyNode(this, n, es);
   _nodes.at_put(n->_idx, ptadr);
   // Add edge from arraycopy node to source object.
   (void)add_edge(ptadr, src);
--- a/hotspot/src/share/vm/opto/escape.hpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/opto/escape.hpp	Thu Oct 30 22:52:13 2014 -0700
@@ -125,6 +125,8 @@
 class FieldNode;
 class ArraycopyNode;
 
+class ConnectionGraph;
+
 // ConnectionGraph nodes
 class PointsToNode : public ResourceObj {
   GrowableArray<PointsToNode*> _edges; // List of nodes this node points to
@@ -137,6 +139,7 @@
 
   Node* const        _node;  // Ideal node corresponding to this PointsTo node.
   const int           _idx;  // Cached ideal node's _idx
+  const uint         _pidx;  // Index of this node
 
 public:
   typedef enum {
@@ -165,17 +168,9 @@
   } NodeFlags;
 
 
-  PointsToNode(Compile *C, Node* n, EscapeState es, NodeType type):
-    _edges(C->comp_arena(), 2, 0, NULL),
-    _uses (C->comp_arena(), 2, 0, NULL),
-    _node(n),
-    _idx(n->_idx),
-    _type((u1)type),
-    _escape((u1)es),
-    _fields_escape((u1)es),
-    _flags(ScalarReplaceable) {
-    assert(n != NULL && es != UnknownEscape, "sanity");
-  }
+  inline PointsToNode(ConnectionGraph* CG, Node* n, EscapeState es, NodeType type);
+
+  uint        pidx()   const { return _pidx; }
 
   Node* ideal_node()   const { return _node; }
   int          idx()   const { return _idx; }
@@ -243,14 +238,14 @@
 
 class LocalVarNode: public PointsToNode {
 public:
-  LocalVarNode(Compile *C, Node* n, EscapeState es):
-    PointsToNode(C, n, es, LocalVar) {}
+  LocalVarNode(ConnectionGraph *CG, Node* n, EscapeState es):
+    PointsToNode(CG, n, es, LocalVar) {}
 };
 
 class JavaObjectNode: public PointsToNode {
 public:
-  JavaObjectNode(Compile *C, Node* n, EscapeState es):
-    PointsToNode(C, n, es, JavaObject) {
+  JavaObjectNode(ConnectionGraph *CG, Node* n, EscapeState es):
+    PointsToNode(CG, n, es, JavaObject) {
       if (es > NoEscape)
         set_scalar_replaceable(false);
     }
@@ -262,8 +257,8 @@
   const bool  _is_oop; // Field points to object
         bool  _has_unknown_base; // Has phantom_object base
 public:
-  FieldNode(Compile *C, Node* n, EscapeState es, int offs, bool is_oop):
-    PointsToNode(C, n, es, Field),
+  FieldNode(ConnectionGraph *CG, Node* n, EscapeState es, int offs, bool is_oop):
+    PointsToNode(CG, n, es, Field),
     _offset(offs), _is_oop(is_oop),
     _has_unknown_base(false) {}
 
@@ -284,8 +279,8 @@
 
 class ArraycopyNode: public PointsToNode {
 public:
-  ArraycopyNode(Compile *C, Node* n, EscapeState es):
-    PointsToNode(C, n, es, Arraycopy) {}
+  ArraycopyNode(ConnectionGraph *CG, Node* n, EscapeState es):
+    PointsToNode(CG, n, es, Arraycopy) {}
 };
 
 // Iterators for PointsTo node's edges:
@@ -323,11 +318,14 @@
 
 
 class ConnectionGraph: public ResourceObj {
+  friend class PointsToNode;
 private:
   GrowableArray<PointsToNode*>  _nodes; // Map from ideal nodes to
                                         // ConnectionGraph nodes.
 
   GrowableArray<PointsToNode*>  _worklist; // Nodes to be processed
+  VectorSet                  _in_worklist;
+  uint                         _next_pidx;
 
   bool            _collecting; // Indicates whether escape information
                                // is still being collected. If false,
@@ -353,6 +351,8 @@
   }
   uint nodes_size() const { return _nodes.length(); }
 
+  uint next_pidx() { return _next_pidx++; }
+
   // Add nodes to ConnectionGraph.
   void add_local_var(Node* n, PointsToNode::EscapeState es);
   void add_java_object(Node* n, PointsToNode::EscapeState es);
@@ -396,15 +396,26 @@
   int add_java_object_edges(JavaObjectNode* jobj, bool populate_worklist);
 
   // Put node on worklist if it is (or was) not there.
-  void add_to_worklist(PointsToNode* pt) {
-    _worklist.push(pt);
-    return;
+  inline void add_to_worklist(PointsToNode* pt) {
+    PointsToNode* ptf = pt;
+    uint pidx_bias = 0;
+    if (PointsToNode::is_base_use(pt)) {
+      // Create a separate entry in _in_worklist for a marked base edge
+      // because _worklist may have an entry for a normal edge pointing
+      // to the same node. To separate them use _next_pidx as bias.
+      ptf = PointsToNode::get_use_node(pt)->as_Field();
+      pidx_bias = _next_pidx;
+    }
+    if (!_in_worklist.test_set(ptf->pidx() + pidx_bias)) {
+      _worklist.append(pt);
+    }
   }
 
   // Put on worklist all uses of this node.
-  void add_uses_to_worklist(PointsToNode* pt) {
-    for (UseIterator i(pt); i.has_next(); i.next())
-      _worklist.push(i.get());
+  inline void add_uses_to_worklist(PointsToNode* pt) {
+    for (UseIterator i(pt); i.has_next(); i.next()) {
+      add_to_worklist(i.get());
+    }
   }
 
   // Put on worklist all field's uses and related field nodes.
@@ -517,8 +528,8 @@
  }
   // Helper functions
   bool   is_oop_field(Node* n, int offset, bool* unsafe);
- static Node* get_addp_base(Node *addp);
- static Node* find_second_addp(Node* addp, Node* n);
+  static Node* get_addp_base(Node *addp);
+  static Node* find_second_addp(Node* addp, Node* n);
   // offset of a field reference
   int address_offset(Node* adr, PhaseTransform *phase);
 
@@ -587,4 +598,17 @@
 #endif
 };
 
+inline PointsToNode::PointsToNode(ConnectionGraph *CG, Node* n, EscapeState es, NodeType type):
+  _edges(CG->_compile->comp_arena(), 2, 0, NULL),
+  _uses (CG->_compile->comp_arena(), 2, 0, NULL),
+  _node(n),
+  _idx(n->_idx),
+  _pidx(CG->next_pidx()),
+  _type((u1)type),
+  _escape((u1)es),
+  _fields_escape((u1)es),
+  _flags(ScalarReplaceable) {
+  assert(n != NULL && es != UnknownEscape, "sanity");
+}
+
 #endif // SHARE_VM_OPTO_ESCAPE_HPP
--- a/hotspot/src/share/vm/opto/memnode.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/opto/memnode.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -1257,6 +1257,16 @@
               result = new ConvI2LNode(phase->transform(result));
             }
 #endif
+            // Boxing/unboxing can be done from signed & unsigned loads (e.g. LoadUB -> ... -> LoadB pair).
+            // Need to preserve unboxing load type if it is unsigned.
+            switch(this->Opcode()) {
+              case Op_LoadUB:
+                result = new AndINode(phase->transform(result), phase->intcon(0xFF));
+                break;
+              case Op_LoadUS:
+                result = new AndINode(phase->transform(result), phase->intcon(0xFFFF));
+                break;
+            }
             return result;
           }
         }
--- a/hotspot/src/share/vm/opto/output.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/opto/output.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -1166,7 +1166,6 @@
   // Have we run out of code space?
   if ((cb->blob() == NULL) || (!CompileBroker::should_compile_new_jobs())) {
     C->record_failure("CodeCache is full");
-    CompileBroker::handle_full_code_cache(CodeBlobType::NonNMethod);
     return NULL;
   }
   // Configure the code buffer.
@@ -1491,7 +1490,6 @@
       cb->insts()->maybe_expand_to_ensure_remaining(MAX_inst_size);
       if ((cb->blob() == NULL) || (!CompileBroker::should_compile_new_jobs())) {
         C->record_failure("CodeCache is full");
-        CompileBroker::handle_full_code_cache(CodeBlobType::NonNMethod);
         return;
       }
 
@@ -1648,7 +1646,6 @@
   // One last check for failed CodeBuffer::expand:
   if ((cb->blob() == NULL) || (!CompileBroker::should_compile_new_jobs())) {
     C->record_failure("CodeCache is full");
-    CompileBroker::handle_full_code_cache(CodeBlobType::NonNMethod);
     return;
   }
 
--- a/hotspot/src/share/vm/prims/jvm.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/prims/jvm.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -3271,8 +3271,10 @@
     THROW_0(vmSymbols::java_lang_NullPointerException());
   }
   oop a = JNIHandles::resolve_non_null(arr);
-  if (!a->is_array() || (type_array_only && !a->is_typeArray())) {
+  if (!a->is_array()) {
     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Argument is not an array");
+  } else if (type_array_only && !a->is_typeArray()) {
+    THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Argument is not an array of primitive type");
   }
   return arrayOop(a);
 }
--- a/hotspot/src/share/vm/prims/jvmtiClassFileReconstituter.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/prims/jvmtiClassFileReconstituter.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -41,6 +41,7 @@
 void JvmtiClassFileReconstituter::write_field_infos() {
   HandleMark hm(thread());
   Array<AnnotationArray*>* fields_anno = ikh()->fields_annotations();
+  Array<AnnotationArray*>* fields_type_anno = ikh()->fields_type_annotations();
 
   // Compute the real number of Java fields
   int java_fields = ikh()->java_fields_count();
@@ -55,6 +56,7 @@
     // int offset = ikh()->field_offset( index );
     int generic_signature_index = fs.generic_signature_index();
     AnnotationArray* anno = fields_anno == NULL ? NULL : fields_anno->at(fs.index());
+    AnnotationArray* type_anno = fields_type_anno == NULL ? NULL : fields_type_anno->at(fs.index());
 
     // JVMSpec|   field_info {
     // JVMSpec|         u2 access_flags;
@@ -80,6 +82,9 @@
     if (anno != NULL) {
       ++attr_count;     // has RuntimeVisibleAnnotations attribute
     }
+    if (type_anno != NULL) {
+      ++attr_count;     // has RuntimeVisibleTypeAnnotations attribute
+    }
 
     write_u2(attr_count);
 
@@ -97,6 +102,9 @@
     if (anno != NULL) {
       write_annotations_attribute("RuntimeVisibleAnnotations", anno);
     }
+    if (type_anno != NULL) {
+      write_annotations_attribute("RuntimeVisibleTypeAnnotations", type_anno);
+    }
   }
 }
 
@@ -537,6 +545,7 @@
   AnnotationArray* anno = method->annotations();
   AnnotationArray* param_anno = method->parameter_annotations();
   AnnotationArray* default_anno = method->annotation_default();
+  AnnotationArray* type_anno = method->type_annotations();
 
   // skip generated default interface methods
   if (method->is_overpass()) {
@@ -572,6 +581,9 @@
   if (param_anno != NULL) {
     ++attr_count;     // has RuntimeVisibleParameterAnnotations attribute
   }
+  if (type_anno != NULL) {
+    ++attr_count;     // has RuntimeVisibleTypeAnnotations attribute
+  }
 
   write_u2(attr_count);
   if (const_method->code_size() > 0) {
@@ -596,6 +608,9 @@
   if (param_anno != NULL) {
     write_annotations_attribute("RuntimeVisibleParameterAnnotations", param_anno);
   }
+  if (type_anno != NULL) {
+    write_annotations_attribute("RuntimeVisibleTypeAnnotations", type_anno);
+  }
 }
 
 // Write the class attributes portion of ClassFile structure
@@ -605,6 +620,7 @@
   u2 inner_classes_length = inner_classes_attribute_length();
   Symbol* generic_signature = ikh()->generic_signature();
   AnnotationArray* anno = ikh()->class_annotations();
+  AnnotationArray* type_anno = ikh()->class_type_annotations();
 
   int attr_count = 0;
   if (generic_signature != NULL) {
@@ -622,6 +638,9 @@
   if (anno != NULL) {
     ++attr_count;     // has RuntimeVisibleAnnotations attribute
   }
+  if (type_anno != NULL) {
+    ++attr_count;     // has RuntimeVisibleTypeAnnotations attribute
+  }
   if (cpool()->operands() != NULL) {
     ++attr_count;
   }
@@ -643,6 +662,9 @@
   if (anno != NULL) {
     write_annotations_attribute("RuntimeVisibleAnnotations", anno);
   }
+  if (type_anno != NULL) {
+    write_annotations_attribute("RuntimeVisibleTypeAnnotations", type_anno);
+  }
   if (cpool()->operands() != NULL) {
     write_bootstrapmethod_attribute();
   }
--- a/hotspot/src/share/vm/prims/jvmtiRedefineClasses.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/prims/jvmtiRedefineClasses.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -1569,6 +1569,29 @@
     return false;
   }
 
+  // rewrite constant pool references in the class_type_annotations:
+  if (!rewrite_cp_refs_in_class_type_annotations(scratch_class, THREAD)) {
+    // propagate failure back to caller
+    return false;
+  }
+
+  // rewrite constant pool references in the fields_type_annotations:
+  if (!rewrite_cp_refs_in_fields_type_annotations(scratch_class, THREAD)) {
+    // propagate failure back to caller
+    return false;
+  }
+
+  // rewrite constant pool references in the methods_type_annotations:
+  if (!rewrite_cp_refs_in_methods_type_annotations(scratch_class, THREAD)) {
+    // propagate failure back to caller
+    return false;
+  }
+
+  // There can be type annotations in the Code part of a method_info attribute.
+  // These annotations are not accessible, even by reflection.
+  // Currently they are not even parsed by the ClassFileParser.
+  // If runtime access is added they will also need to be rewritten.
+
   // rewrite source file name index:
   u2 source_file_name_idx = scratch_class->source_file_name_index();
   if (source_file_name_idx != 0) {
@@ -2239,6 +2262,588 @@
 } // end rewrite_cp_refs_in_methods_default_annotations()
 
 
+// Rewrite constant pool references in a class_type_annotations field.
+bool VM_RedefineClasses::rewrite_cp_refs_in_class_type_annotations(
+       instanceKlassHandle scratch_class, TRAPS) {
+
+  AnnotationArray* class_type_annotations = scratch_class->class_type_annotations();
+  if (class_type_annotations == NULL || class_type_annotations->length() == 0) {
+    // no class_type_annotations so nothing to do
+    return true;
+  }
+
+  RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+    ("class_type_annotations length=%d", class_type_annotations->length()));
+
+  int byte_i = 0;  // byte index into class_type_annotations
+  return rewrite_cp_refs_in_type_annotations_typeArray(class_type_annotations,
+      byte_i, "ClassFile", THREAD);
+} // end rewrite_cp_refs_in_class_type_annotations()
+
+
+// Rewrite constant pool references in a fields_type_annotations field.
+bool VM_RedefineClasses::rewrite_cp_refs_in_fields_type_annotations(
+       instanceKlassHandle scratch_class, TRAPS) {
+
+  Array<AnnotationArray*>* fields_type_annotations = scratch_class->fields_type_annotations();
+  if (fields_type_annotations == NULL || fields_type_annotations->length() == 0) {
+    // no fields_type_annotations so nothing to do
+    return true;
+  }
+
+  RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+    ("fields_type_annotations length=%d", fields_type_annotations->length()));
+
+  for (int i = 0; i < fields_type_annotations->length(); i++) {
+    AnnotationArray* field_type_annotations = fields_type_annotations->at(i);
+    if (field_type_annotations == NULL || field_type_annotations->length() == 0) {
+      // this field does not have any annotations so skip it
+      continue;
+    }
+
+    int byte_i = 0;  // byte index into field_type_annotations
+    if (!rewrite_cp_refs_in_type_annotations_typeArray(field_type_annotations,
+           byte_i, "field_info", THREAD)) {
+      RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+        ("bad field_type_annotations at %d", i));
+      // propagate failure back to caller
+      return false;
+    }
+  }
+
+  return true;
+} // end rewrite_cp_refs_in_fields_type_annotations()
+
+
+// Rewrite constant pool references in a methods_type_annotations field.
+bool VM_RedefineClasses::rewrite_cp_refs_in_methods_type_annotations(
+       instanceKlassHandle scratch_class, TRAPS) {
+
+  for (int i = 0; i < scratch_class->methods()->length(); i++) {
+    Method* m = scratch_class->methods()->at(i);
+    AnnotationArray* method_type_annotations = m->constMethod()->type_annotations();
+
+    if (method_type_annotations == NULL || method_type_annotations->length() == 0) {
+      // this method does not have any annotations so skip it
+      continue;
+    }
+
+    RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+        ("methods type_annotations length=%d", method_type_annotations->length()));
+
+    int byte_i = 0;  // byte index into method_type_annotations
+    if (!rewrite_cp_refs_in_type_annotations_typeArray(method_type_annotations,
+           byte_i, "method_info", THREAD)) {
+      RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+        ("bad method_type_annotations at %d", i));
+      // propagate failure back to caller
+      return false;
+    }
+  }
+
+  return true;
+} // end rewrite_cp_refs_in_methods_type_annotations()
+
+
+// Rewrite constant pool references in a type_annotations
+// field. This "structure" is adapted from the
+// RuntimeVisibleTypeAnnotations_attribute described in
+// section 4.7.20 of the Java SE 8 Edition of the VM spec:
+//
+// type_annotations_typeArray {
+//   u2              num_annotations;
+//   type_annotation annotations[num_annotations];
+// }
+//
+bool VM_RedefineClasses::rewrite_cp_refs_in_type_annotations_typeArray(
+       AnnotationArray* type_annotations_typeArray, int &byte_i_ref,
+       const char * location_mesg, TRAPS) {
+
+  if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {
+    // not enough room for num_annotations field
+    RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+      ("length() is too small for num_annotations field"));
+    return false;
+  }
+
+  u2 num_annotations = Bytes::get_Java_u2((address)
+                         type_annotations_typeArray->adr_at(byte_i_ref));
+  byte_i_ref += 2;
+
+  RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+    ("num_type_annotations=%d", num_annotations));
+
+  int calc_num_annotations = 0;
+  for (; calc_num_annotations < num_annotations; calc_num_annotations++) {
+    if (!rewrite_cp_refs_in_type_annotation_struct(type_annotations_typeArray,
+           byte_i_ref, location_mesg, THREAD)) {
+      RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+        ("bad type_annotation_struct at %d", calc_num_annotations));
+      // propagate failure back to caller
+      return false;
+    }
+  }
+  assert(num_annotations == calc_num_annotations, "sanity check");
+
+  if (byte_i_ref != type_annotations_typeArray->length()) {
+    RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+      ("read wrong amount of bytes at end of processing "
+       "type_annotations_typeArray (%d of %d bytes were read)",
+       byte_i_ref, type_annotations_typeArray->length()));
+    return false;
+  }
+
+  return true;
+} // end rewrite_cp_refs_in_type_annotations_typeArray()
+
+
+// Rewrite constant pool references in a type_annotation
+// field. This "structure" is adapted from the
+// RuntimeVisibleTypeAnnotations_attribute described in
+// section 4.7.20 of the Java SE 8 Edition of the VM spec:
+//
+// type_annotation {
+//   u1 target_type;
+//   union {
+//     type_parameter_target;
+//     supertype_target;
+//     type_parameter_bound_target;
+//     empty_target;
+//     method_formal_parameter_target;
+//     throws_target;
+//     localvar_target;
+//     catch_target;
+//     offset_target;
+//     type_argument_target;
+//   } target_info;
+//   type_path target_path;
+//   annotation anno;
+// }
+//
+bool VM_RedefineClasses::rewrite_cp_refs_in_type_annotation_struct(
+       AnnotationArray* type_annotations_typeArray, int &byte_i_ref,
+       const char * location_mesg, TRAPS) {
+
+  if (!skip_type_annotation_target(type_annotations_typeArray,
+         byte_i_ref, location_mesg, THREAD)) {
+    return false;
+  }
+
+  if (!skip_type_annotation_type_path(type_annotations_typeArray,
+         byte_i_ref, THREAD)) {
+    return false;
+  }
+
+  if (!rewrite_cp_refs_in_annotation_struct(type_annotations_typeArray,
+         byte_i_ref, THREAD)) {
+    return false;
+  }
+
+  return true;
+} // end rewrite_cp_refs_in_type_annotation_struct()
+
+
+// Read, verify and skip over the target_type and target_info part
+// so that rewriting can continue in the later parts of the struct.
+//
+// u1 target_type;
+// union {
+//   type_parameter_target;
+//   supertype_target;
+//   type_parameter_bound_target;
+//   empty_target;
+//   method_formal_parameter_target;
+//   throws_target;
+//   localvar_target;
+//   catch_target;
+//   offset_target;
+//   type_argument_target;
+// } target_info;
+//
+bool VM_RedefineClasses::skip_type_annotation_target(
+       AnnotationArray* type_annotations_typeArray, int &byte_i_ref,
+       const char * location_mesg, TRAPS) {
+
+  if ((byte_i_ref + 1) > type_annotations_typeArray->length()) {
+    // not enough room for a target_type let alone the rest of a type_annotation
+    RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+      ("length() is too small for a target_type"));
+    return false;
+  }
+
+  u1 target_type = type_annotations_typeArray->at(byte_i_ref);
+  byte_i_ref += 1;
+  RC_TRACE_WITH_THREAD(0x02000000, THREAD, ("target_type=0x%.2x", target_type));
+  RC_TRACE_WITH_THREAD(0x02000000, THREAD, ("location=%s", location_mesg));
+
+  // Skip over target_info
+  switch (target_type) {
+    case 0x00:
+    // kind: type parameter declaration of generic class or interface
+    // location: ClassFile
+    case 0x01:
+    // kind: type parameter declaration of generic method or constructor
+    // location: method_info
+
+    {
+      // struct:
+      // type_parameter_target {
+      //   u1 type_parameter_index;
+      // }
+      //
+      if ((byte_i_ref + 1) > type_annotations_typeArray->length()) {
+        RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+          ("length() is too small for a type_parameter_target"));
+        return false;
+      }
+
+      u1 type_parameter_index = type_annotations_typeArray->at(byte_i_ref);
+      byte_i_ref += 1;
+
+      RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+        ("type_parameter_target: type_parameter_index=%d",
+         type_parameter_index));
+    } break;
+
+    case 0x10:
+    // kind: type in extends clause of class or interface declaration
+    //       (including the direct superclass of an anonymous class declaration),
+    //       or in implements clause of interface declaration
+    // location: ClassFile
+
+    {
+      // struct:
+      // supertype_target {
+      //   u2 supertype_index;
+      // }
+      //
+      if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {
+        RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+          ("length() is too small for a supertype_target"));
+        return false;
+      }
+
+      u2 supertype_index = Bytes::get_Java_u2((address)
+                             type_annotations_typeArray->adr_at(byte_i_ref));
+      byte_i_ref += 2;
+
+      RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+        ("supertype_target: supertype_index=%d", supertype_index));
+    } break;
+
+    case 0x11:
+    // kind: type in bound of type parameter declaration of generic class or interface
+    // location: ClassFile
+    case 0x12:
+    // kind: type in bound of type parameter declaration of generic method or constructor
+    // location: method_info
+
+    {
+      // struct:
+      // type_parameter_bound_target {
+      //   u1 type_parameter_index;
+      //   u1 bound_index;
+      // }
+      //
+      if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {
+        RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+          ("length() is too small for a type_parameter_bound_target"));
+        return false;
+      }
+
+      u1 type_parameter_index = type_annotations_typeArray->at(byte_i_ref);
+      byte_i_ref += 1;
+      u1 bound_index = type_annotations_typeArray->at(byte_i_ref);
+      byte_i_ref += 1;
+
+      RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+        ("type_parameter_bound_target: type_parameter_index=%d, bound_index=%d",
+         type_parameter_index, bound_index));
+    } break;
+
+    case 0x13:
+    // kind: type in field declaration
+    // location: field_info
+    case 0x14:
+    // kind: return type of method, or type of newly constructed object
+    // location: method_info
+    case 0x15:
+    // kind: receiver type of method or constructor
+    // location: method_info
+
+    {
+      // struct:
+      // empty_target {
+      // }
+      //
+      RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+        ("empty_target"));
+    } break;
+
+    case 0x16:
+    // kind: type in formal parameter declaration of method, constructor, or lambda expression
+    // location: method_info
+
+    {
+      // struct:
+      // formal_parameter_target {
+      //   u1 formal_parameter_index;
+      // }
+      //
+      if ((byte_i_ref + 1) > type_annotations_typeArray->length()) {
+        RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+          ("length() is too small for a formal_parameter_target"));
+        return false;
+      }
+
+      u1 formal_parameter_index = type_annotations_typeArray->at(byte_i_ref);
+      byte_i_ref += 1;
+
+      RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+        ("formal_parameter_target: formal_parameter_index=%d",
+         formal_parameter_index));
+    } break;
+
+    case 0x17:
+    // kind: type in throws clause of method or constructor
+    // location: method_info
+
+    {
+      // struct:
+      // throws_target {
+      //   u2 throws_type_index
+      // }
+      //
+      if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {
+        RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+          ("length() is too small for a throws_target"));
+        return false;
+      }
+
+      u2 throws_type_index = Bytes::get_Java_u2((address)
+                               type_annotations_typeArray->adr_at(byte_i_ref));
+      byte_i_ref += 2;
+
+      RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+        ("throws_target: throws_type_index=%d", throws_type_index));
+    } break;
+
+    case 0x40:
+    // kind: type in local variable declaration
+    // location: Code
+    case 0x41:
+    // kind: type in resource variable declaration
+    // location: Code
+
+    {
+      // struct:
+      // localvar_target {
+      //   u2 table_length;
+      //   struct {
+      //     u2 start_pc;
+      //     u2 length;
+      //     u2 index;
+      //   } table[table_length];
+      // }
+      //
+      if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {
+        // not enough room for a table_length let alone the rest of a localvar_target
+        RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+          ("length() is too small for a localvar_target table_length"));
+        return false;
+      }
+
+      u2 table_length = Bytes::get_Java_u2((address)
+                          type_annotations_typeArray->adr_at(byte_i_ref));
+      byte_i_ref += 2;
+
+      RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+        ("localvar_target: table_length=%d", table_length));
+
+      int table_struct_size = 2 + 2 + 2; // 3 u2 variables per table entry
+      int table_size = table_length * table_struct_size;
+
+      if ((byte_i_ref + table_size) > type_annotations_typeArray->length()) {
+        // not enough room for a table
+        RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+          ("length() is too small for a table array of length %d", table_length));
+        return false;
+      }
+
+      // Skip over table
+      byte_i_ref += table_size;
+    } break;
+
+    case 0x42:
+    // kind: type in exception parameter declaration
+    // location: Code
+
+    {
+      // struct:
+      // catch_target {
+      //   u2 exception_table_index;
+      // }
+      //
+      if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {
+        RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+          ("length() is too small for a catch_target"));
+        return false;
+      }
+
+      u2 exception_table_index = Bytes::get_Java_u2((address)
+                                   type_annotations_typeArray->adr_at(byte_i_ref));
+      byte_i_ref += 2;
+
+      RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+        ("catch_target: exception_table_index=%d", exception_table_index));
+    } break;
+
+    case 0x43:
+    // kind: type in instanceof expression
+    // location: Code
+    case 0x44:
+    // kind: type in new expression
+    // location: Code
+    case 0x45:
+    // kind: type in method reference expression using ::new
+    // location: Code
+    case 0x46:
+    // kind: type in method reference expression using ::Identifier
+    // location: Code
+
+    {
+      // struct:
+      // offset_target {
+      //   u2 offset;
+      // }
+      //
+      if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {
+        RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+          ("length() is too small for a offset_target"));
+        return false;
+      }
+
+      u2 offset = Bytes::get_Java_u2((address)
+                    type_annotations_typeArray->adr_at(byte_i_ref));
+      byte_i_ref += 2;
+
+      RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+        ("offset_target: offset=%d", offset));
+    } break;
+
+    case 0x47:
+    // kind: type in cast expression
+    // location: Code
+    case 0x48:
+    // kind: type argument for generic constructor in new expression or
+    //       explicit constructor invocation statement
+    // location: Code
+    case 0x49:
+    // kind: type argument for generic method in method invocation expression
+    // location: Code
+    case 0x4A:
+    // kind: type argument for generic constructor in method reference expression using ::new
+    // location: Code
+    case 0x4B:
+    // kind: type argument for generic method in method reference expression using ::Identifier
+    // location: Code
+
+    {
+      // struct:
+      // type_argument_target {
+      //   u2 offset;
+      //   u1 type_argument_index;
+      // }
+      //
+      if ((byte_i_ref + 3) > type_annotations_typeArray->length()) {
+        RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+          ("length() is too small for a type_argument_target"));
+        return false;
+      }
+
+      u2 offset = Bytes::get_Java_u2((address)
+                    type_annotations_typeArray->adr_at(byte_i_ref));
+      byte_i_ref += 2;
+      u1 type_argument_index = type_annotations_typeArray->at(byte_i_ref);
+      byte_i_ref += 1;
+
+      RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+        ("type_argument_target: offset=%d, type_argument_index=%d",
+         offset, type_argument_index));
+    } break;
+
+    default:
+      RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+        ("unknown target_type"));
+#ifdef ASSERT
+      ShouldNotReachHere();
+#endif
+      return false;
+  }
+
+  return true;
+} // end skip_type_annotation_target()
+
+
+// Read, verify and skip over the type_path part so that rewriting
+// can continue in the later parts of the struct.
+//
+// type_path {
+//   u1 path_length;
+//   {
+//     u1 type_path_kind;
+//     u1 type_argument_index;
+//   } path[path_length];
+// }
+//
+bool VM_RedefineClasses::skip_type_annotation_type_path(
+       AnnotationArray* type_annotations_typeArray, int &byte_i_ref, TRAPS) {
+
+  if ((byte_i_ref + 1) > type_annotations_typeArray->length()) {
+    // not enough room for a path_length let alone the rest of the type_path
+    RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+      ("length() is too small for a type_path"));
+    return false;
+  }
+
+  u1 path_length = type_annotations_typeArray->at(byte_i_ref);
+  byte_i_ref += 1;
+
+  RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+    ("type_path: path_length=%d", path_length));
+
+  int calc_path_length = 0;
+  for (; calc_path_length < path_length; calc_path_length++) {
+    if ((byte_i_ref + 1 + 1) > type_annotations_typeArray->length()) {
+      // not enough room for a path
+      RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+        ("length() is too small for path entry %d of %d",
+         calc_path_length, path_length));
+      return false;
+    }
+
+    u1 type_path_kind = type_annotations_typeArray->at(byte_i_ref);
+    byte_i_ref += 1;
+    u1 type_argument_index = type_annotations_typeArray->at(byte_i_ref);
+    byte_i_ref += 1;
+
+    RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+      ("type_path: path[%d]: type_path_kind=%d, type_argument_index=%d",
+       calc_path_length, type_path_kind, type_argument_index));
+
+    if (type_path_kind > 3 || (type_path_kind != 3 && type_argument_index != 0)) {
+      // not enough room for a path
+      RC_TRACE_WITH_THREAD(0x02000000, THREAD,
+        ("inconsistent type_path values"));
+      return false;
+    }
+  }
+  assert(path_length == calc_path_length, "sanity check");
+
+  return true;
+} // end skip_type_annotation_type_path()
+
+
 // Rewrite constant pool references in the method's stackmap table.
 // These "structures" are adapted from the StackMapTable_attribute that
 // is described in section 4.8.4 of the 6.0 version of the VM spec
@@ -3223,23 +3828,6 @@
 
 void VM_RedefineClasses::swap_annotations(instanceKlassHandle the_class,
                                           instanceKlassHandle scratch_class) {
-  // Since there is currently no rewriting of type annotations indexes
-  // into the CP, we null out type annotations on scratch_class before
-  // we swap annotations with the_class rather than facing the
-  // possibility of shipping annotations with broken indexes to
-  // Java-land.
-  ClassLoaderData* loader_data = scratch_class->class_loader_data();
-  AnnotationArray* new_class_type_annotations = scratch_class->class_type_annotations();
-  if (new_class_type_annotations != NULL) {
-    MetadataFactory::free_array<u1>(loader_data, new_class_type_annotations);
-    scratch_class->annotations()->set_class_type_annotations(NULL);
-  }
-  Array<AnnotationArray*>* new_field_type_annotations = scratch_class->fields_type_annotations();
-  if (new_field_type_annotations != NULL) {
-    Annotations::free_contents(loader_data, new_field_type_annotations);
-    scratch_class->annotations()->set_fields_type_annotations(NULL);
-  }
-
   // Swap annotation fields values
   Annotations* old_annotations = the_class->annotations();
   the_class->set_annotations(scratch_class->annotations());
--- a/hotspot/src/share/vm/prims/jvmtiRedefineClasses.hpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/prims/jvmtiRedefineClasses.hpp	Thu Oct 30 22:52:13 2014 -0700
@@ -452,6 +452,17 @@
     instanceKlassHandle scratch_class, TRAPS);
   bool rewrite_cp_refs_in_element_value(
     AnnotationArray* class_annotations, int &byte_i_ref, TRAPS);
+  bool rewrite_cp_refs_in_type_annotations_typeArray(
+    AnnotationArray* type_annotations_typeArray, int &byte_i_ref,
+    const char * location_mesg, TRAPS);
+  bool rewrite_cp_refs_in_type_annotation_struct(
+    AnnotationArray* type_annotations_typeArray, int &byte_i_ref,
+    const char * location_mesg, TRAPS);
+  bool skip_type_annotation_target(
+    AnnotationArray* type_annotations_typeArray, int &byte_i_ref,
+    const char * location_mesg, TRAPS);
+  bool skip_type_annotation_type_path(
+    AnnotationArray* type_annotations_typeArray, int &byte_i_ref, TRAPS);
   bool rewrite_cp_refs_in_fields_annotations(
     instanceKlassHandle scratch_class, TRAPS);
   void rewrite_cp_refs_in_method(methodHandle method,
@@ -463,6 +474,12 @@
     instanceKlassHandle scratch_class, TRAPS);
   bool rewrite_cp_refs_in_methods_parameter_annotations(
     instanceKlassHandle scratch_class, TRAPS);
+  bool rewrite_cp_refs_in_class_type_annotations(
+    instanceKlassHandle scratch_class, TRAPS);
+  bool rewrite_cp_refs_in_fields_type_annotations(
+    instanceKlassHandle scratch_class, TRAPS);
+  bool rewrite_cp_refs_in_methods_type_annotations(
+    instanceKlassHandle scratch_class, TRAPS);
   void rewrite_cp_refs_in_stack_map_table(methodHandle method, TRAPS);
   void rewrite_cp_refs_in_verification_type_info(
          address& stackmap_addr_ref, address stackmap_end, u2 frame_i,
--- a/hotspot/src/share/vm/prims/methodHandles.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/prims/methodHandles.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -36,6 +36,7 @@
 #include "runtime/reflection.hpp"
 #include "runtime/signature.hpp"
 #include "runtime/stubRoutines.hpp"
+#include "utilities/exceptions.hpp"
 
 
 /*
@@ -55,26 +56,30 @@
 bool MethodHandles::_enabled = false; // set true after successful native linkage
 MethodHandlesAdapterBlob* MethodHandles::_adapter_code = NULL;
 
-//------------------------------------------------------------------------------
-// MethodHandles::generate_adapters
-//
-void MethodHandles::generate_adapters() {
-  if (SystemDictionary::MethodHandle_klass() == NULL)  return;
+
+/**
+ * Generates method handle adapters. Returns 'false' if memory allocation
+ * failed and true otherwise.
+ */
+bool MethodHandles::generate_adapters() {
+  if (SystemDictionary::MethodHandle_klass() == NULL) {
+    return true;
+  }
 
   assert(_adapter_code == NULL, "generate only once");
 
   ResourceMark rm;
   TraceTime timer("MethodHandles adapters generation", TraceStartupTime);
   _adapter_code = MethodHandlesAdapterBlob::create(adapter_code_size);
-  if (_adapter_code == NULL)
-    vm_exit_out_of_memory(adapter_code_size, OOM_MALLOC_ERROR,
-                          "CodeCache: no room for MethodHandles adapters");
-  {
-    CodeBuffer code(_adapter_code);
-    MethodHandlesAdapterGenerator g(&code);
-    g.generate();
-    code.log_section_sizes("MethodHandlesAdapterBlob");
+  if (_adapter_code == NULL) {
+     return false;
   }
+
+  CodeBuffer code(_adapter_code);
+  MethodHandlesAdapterGenerator g(&code);
+  g.generate();
+  code.log_section_sizes("MethodHandlesAdapterBlob");
+  return true;
 }
 
 //------------------------------------------------------------------------------
@@ -1401,7 +1406,9 @@
   }
 
   if (enable_MH) {
-    MethodHandles::generate_adapters();
+    if (MethodHandles::generate_adapters() == false) {
+      THROW_MSG(vmSymbols::java_lang_VirtualMachineError(), "Out of space in CodeCache for method handle adapters");
+    }
     MethodHandles::set_enabled(true);
   }
 }
--- a/hotspot/src/share/vm/prims/methodHandles.hpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/prims/methodHandles.hpp	Thu Oct 30 22:52:13 2014 -0700
@@ -69,7 +69,7 @@
   enum { _suppress_defc = 1, _suppress_name = 2, _suppress_type = 4 };
 
   // Generate MethodHandles adapters.
-                              static void generate_adapters();
+  static bool generate_adapters();
 
   // Called from MethodHandlesAdapterGenerator.
   static address generate_method_handle_interpreter_entry(MacroAssembler* _masm, vmIntrinsics::ID iid);
--- a/hotspot/src/share/vm/prims/whitebox.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/prims/whitebox.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -386,19 +386,10 @@
   CHECK_JNI_EXCEPTION_(env, result);
   MutexLockerEx mu(Compile_lock);
   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
-  nmethod* code;
   if (is_osr) {
-    int bci = InvocationEntryBci;
-    while ((code = mh->lookup_osr_nmethod_for(bci, CompLevel_none, false)) != NULL) {
-      code->mark_for_deoptimization();
-      ++result;
-      bci = code->osr_entry_bci() + 1;
-    }
-  } else {
-    code = mh->code();
-  }
-  if (code != NULL) {
-    code->mark_for_deoptimization();
+    result += mh->mark_osr_nmethods();
+  } else if (mh->code() != NULL) {
+    mh->code()->mark_for_deoptimization();
     ++result;
   }
   result += CodeCache::mark_for_deoptimization(mh());
@@ -566,13 +557,13 @@
 WB_END
 
 template <typename T>
-static bool GetVMFlag(JavaThread* thread, JNIEnv* env, jstring name, T* value, bool (*TAt)(const char*, T*)) {
+static bool GetVMFlag(JavaThread* thread, JNIEnv* env, jstring name, T* value, bool (*TAt)(const char*, T*, bool, bool)) {
   if (name == NULL) {
     return false;
   }
   ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
   const char* flag_name = env->GetStringUTFChars(name, NULL);
-  bool result = (*TAt)(flag_name, value);
+  bool result = (*TAt)(flag_name, value, true, true);
   env->ReleaseStringUTFChars(name, flag_name);
   return result;
 }
@@ -619,6 +610,24 @@
   return box(thread, env, vmSymbols::java_lang_Double(), vmSymbols::Double_valueOf_signature(), value);
 }
 
+static Flag* getVMFlag(JavaThread* thread, JNIEnv* env, jstring name) {
+  ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
+  const char* flag_name = env->GetStringUTFChars(name, NULL);
+  Flag* result = Flag::find_flag(flag_name, strlen(flag_name), true, true);
+  env->ReleaseStringUTFChars(name, flag_name);
+  return result;
+}
+
+WB_ENTRY(jboolean, WB_IsConstantVMFlag(JNIEnv* env, jobject o, jstring name))
+  Flag* flag = getVMFlag(thread, env, name);
+  return (flag != NULL) && flag->is_constant_in_binary();
+WB_END
+
+WB_ENTRY(jboolean, WB_IsLockedVMFlag(JNIEnv* env, jobject o, jstring name))
+  Flag* flag = getVMFlag(thread, env, name);
+  return (flag != NULL) && !(flag->is_unlocked() || flag->is_unlocker());
+WB_END
+
 WB_ENTRY(jobject, WB_GetBooleanVMFlag(JNIEnv* env, jobject o, jstring name))
   bool result;
   if (GetVMFlag <bool> (thread, env, name, &result, &CommandLineFlags::boolAt)) {
@@ -1018,6 +1027,8 @@
       CC"(Ljava/lang/reflect/Executable;II)Z",        (void*)&WB_EnqueueMethodForCompilation},
   {CC"clearMethodState",
       CC"(Ljava/lang/reflect/Executable;)V",          (void*)&WB_ClearMethodState},
+  {CC"isConstantVMFlag",   CC"(Ljava/lang/String;)Z", (void*)&WB_IsConstantVMFlag},
+  {CC"isLockedVMFlag",     CC"(Ljava/lang/String;)Z", (void*)&WB_IsLockedVMFlag},
   {CC"setBooleanVMFlag",   CC"(Ljava/lang/String;Z)V",(void*)&WB_SetBooleanVMFlag},
   {CC"setIntxVMFlag",      CC"(Ljava/lang/String;J)V",(void*)&WB_SetIntxVMFlag},
   {CC"setUintxVMFlag",     CC"(Ljava/lang/String;J)V",(void*)&WB_SetUintxVMFlag},
--- a/hotspot/src/share/vm/runtime/arguments.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/runtime/arguments.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -306,6 +306,9 @@
   { "ReflectionWrapResolutionErrors",JDK_Version::jdk(9), JDK_Version::jdk(10) },
   { "VerifyReflectionBytecodes",     JDK_Version::jdk(9), JDK_Version::jdk(10) },
   { "AutoShutdownNMT",               JDK_Version::jdk(9), JDK_Version::jdk(10) },
+  { "NmethodSweepFraction",          JDK_Version::jdk(9), JDK_Version::jdk(10) },
+  { "NmethodSweepCheckInterval",     JDK_Version::jdk(9), JDK_Version::jdk(10) },
+  { "CodeCacheMinimumFreeSpace",     JDK_Version::jdk(9), JDK_Version::jdk(10) },
 #ifndef ZERO
   { "UseFastAccessorMethods",        JDK_Version::jdk(9), JDK_Version::jdk(10) },
   { "UseFastEmptyMethods",           JDK_Version::jdk(9), JDK_Version::jdk(10) },
@@ -2528,7 +2531,7 @@
 
   // Check lower bounds of the code cache
   // Template Interpreter code is approximately 3X larger in debug builds.
-  uint min_code_cache_size = (CodeCacheMinimumUseSpace DEBUG_ONLY(* 3)) + CodeCacheMinimumFreeSpace;
+  uint min_code_cache_size = CodeCacheMinimumUseSpace DEBUG_ONLY(* 3);
   if (InitialCodeCacheSize < (uintx)os::vm_page_size()) {
     jio_fprintf(defaultStream::error_stream(),
                 "Invalid InitialCodeCacheSize=%dK. Must be at least %dK.\n", InitialCodeCacheSize/K,
@@ -2564,10 +2567,11 @@
     status = false;
   }
 
-  status &= verify_interval(NmethodSweepFraction, 1, ReservedCodeCacheSize/K, "NmethodSweepFraction");
   status &= verify_interval(NmethodSweepActivity, 0, 2000, "NmethodSweepActivity");
   status &= verify_interval(CodeCacheMinBlockLength, 1, 100, "CodeCacheMinBlockLength");
   status &= verify_interval(CodeCacheSegmentSize, 1, 1024, "CodeCacheSegmentSize");
+  status &= verify_interval(StartAggressiveSweepingAt, 0, 100, "StartAggressiveSweepingAt");
+
 
   int min_number_of_compiler_threads = get_min_number_of_compiler_threads();
   // The default CICompilerCount's value is CI_COMPILER_COUNT.
@@ -3992,12 +3996,6 @@
 #endif
 #endif
 
-  // Set NmethodSweepFraction after the size of the code cache is adapted (in case of tiered)
-  if (FLAG_IS_DEFAULT(NmethodSweepFraction)) {
-    FLAG_SET_DEFAULT(NmethodSweepFraction, 1 + ReservedCodeCacheSize / (16 * M));
-  }
-
-
   // Set heap size based on available physical memory
   set_heap_size();
 
@@ -4065,13 +4063,6 @@
   }
 
 #ifndef PRODUCT
-  if (CompileTheWorld) {
-    // Force NmethodSweeper to sweep whole CodeCache each time.
-    if (FLAG_IS_DEFAULT(NmethodSweepFraction)) {
-      NmethodSweepFraction = 1;
-    }
-  }
-
   if (!LogVMOutput && FLAG_IS_DEFAULT(LogVMOutput)) {
     if (use_vm_log()) {
       LogVMOutput = true;
--- a/hotspot/src/share/vm/runtime/deoptimization.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/runtime/deoptimization.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -1173,7 +1173,7 @@
 void Deoptimization::load_class_by_index(constantPoolHandle constant_pool, int index, TRAPS) {
   // in case of an unresolved klass entry, load the class.
   if (constant_pool->tag_at(index).is_unresolved_klass()) {
-    Klass* tk = constant_pool->klass_at(index, CHECK);
+    Klass* tk = constant_pool->klass_at_ignore_error(index, CHECK);
     return;
   }
 
--- a/hotspot/src/share/vm/runtime/globals.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/runtime/globals.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -634,8 +634,8 @@
   e.commit();
 }
 
-bool CommandLineFlags::boolAt(const char* name, size_t len, bool* value) {
-  Flag* result = Flag::find_flag(name, len);
+bool CommandLineFlags::boolAt(const char* name, size_t len, bool* value, bool allow_locked, bool return_flag) {
+  Flag* result = Flag::find_flag(name, len, allow_locked, return_flag);
   if (result == NULL) return false;
   if (!result->is_bool()) return false;
   *value = result->get_bool();
@@ -662,8 +662,8 @@
   faddr->set_origin(origin);
 }
 
-bool CommandLineFlags::intxAt(const char* name, size_t len, intx* value) {
-  Flag* result = Flag::find_flag(name, len);
+bool CommandLineFlags::intxAt(const char* name, size_t len, intx* value, bool allow_locked, bool return_flag) {
+  Flag* result = Flag::find_flag(name, len, allow_locked, return_flag);
   if (result == NULL) return false;
   if (!result->is_intx()) return false;
   *value = result->get_intx();
@@ -690,8 +690,8 @@
   faddr->set_origin(origin);
 }
 
-bool CommandLineFlags::uintxAt(const char* name, size_t len, uintx* value) {
-  Flag* result = Flag::find_flag(name, len);
+bool CommandLineFlags::uintxAt(const char* name, size_t len, uintx* value, bool allow_locked, bool return_flag) {
+  Flag* result = Flag::find_flag(name, len, allow_locked, return_flag);
   if (result == NULL) return false;
   if (!result->is_uintx()) return false;
   *value = result->get_uintx();
@@ -718,8 +718,8 @@
   faddr->set_origin(origin);
 }
 
-bool CommandLineFlags::uint64_tAt(const char* name, size_t len, uint64_t* value) {
-  Flag* result = Flag::find_flag(name, len);
+bool CommandLineFlags::uint64_tAt(const char* name, size_t len, uint64_t* value, bool allow_locked, bool return_flag) {
+  Flag* result = Flag::find_flag(name, len, allow_locked, return_flag);
   if (result == NULL) return false;
   if (!result->is_uint64_t()) return false;
   *value = result->get_uint64_t();
@@ -746,8 +746,8 @@
   faddr->set_origin(origin);
 }
 
-bool CommandLineFlags::size_tAt(const char* name, size_t len, size_t* value) {
-  Flag* result = Flag::find_flag(name, len);
+bool CommandLineFlags::size_tAt(const char* name, size_t len, size_t* value, bool allow_locked, bool return_flag) {
+  Flag* result = Flag::find_flag(name, len, allow_locked, return_flag);
   if (result == NULL) return false;
   if (!result->is_size_t()) return false;
   *value = result->get_size_t();
@@ -774,8 +774,8 @@
   faddr->set_origin(origin);
 }
 
-bool CommandLineFlags::doubleAt(const char* name, size_t len, double* value) {
-  Flag* result = Flag::find_flag(name, len);
+bool CommandLineFlags::doubleAt(const char* name, size_t len, double* value, bool allow_locked, bool return_flag) {
+  Flag* result = Flag::find_flag(name, len, allow_locked, return_flag);
   if (result == NULL) return false;
   if (!result->is_double()) return false;
   *value = result->get_double();
@@ -802,8 +802,8 @@
   faddr->set_origin(origin);
 }
 
-bool CommandLineFlags::ccstrAt(const char* name, size_t len, ccstr* value) {
-  Flag* result = Flag::find_flag(name, len);
+bool CommandLineFlags::ccstrAt(const char* name, size_t len, ccstr* value, bool allow_locked, bool return_flag) {
+  Flag* result = Flag::find_flag(name, len, allow_locked, return_flag);
   if (result == NULL) return false;
   if (!result->is_ccstr()) return false;
   *value = result->get_ccstr();
--- a/hotspot/src/share/vm/runtime/globals.hpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/runtime/globals.hpp	Thu Oct 30 22:52:13 2014 -0700
@@ -379,38 +379,38 @@
 
 class CommandLineFlags {
  public:
-  static bool boolAt(const char* name, size_t len, bool* value);
-  static bool boolAt(const char* name, bool* value)      { return boolAt(name, strlen(name), value); }
+  static bool boolAt(const char* name, size_t len, bool* value, bool allow_locked = false, bool return_flag = false);
+  static bool boolAt(const char* name, bool* value, bool allow_locked = false, bool return_flag = false)      { return boolAt(name, strlen(name), value, allow_locked, return_flag); }
   static bool boolAtPut(const char* name, size_t len, bool* value, Flag::Flags origin);
   static bool boolAtPut(const char* name, bool* value, Flag::Flags origin)   { return boolAtPut(name, strlen(name), value, origin); }
 
-  static bool intxAt(const char* name, size_t len, intx* value);
-  static bool intxAt(const char* name, intx* value)      { return intxAt(name, strlen(name), value); }
+  static bool intxAt(const char* name, size_t len, intx* value, bool allow_locked = false, bool return_flag = false);
+  static bool intxAt(const char* name, intx* value, bool allow_locked = false, bool return_flag = false)      { return intxAt(name, strlen(name), value, allow_locked, return_flag); }
   static bool intxAtPut(const char* name, size_t len, intx* value, Flag::Flags origin);
   static bool intxAtPut(const char* name, intx* value, Flag::Flags origin)   { return intxAtPut(name, strlen(name), value, origin); }
 
-  static bool uintxAt(const char* name, size_t len, uintx* value);
-  static bool uintxAt(const char* name, uintx* value)    { return uintxAt(name, strlen(name), value); }
+  static bool uintxAt(const char* name, size_t len, uintx* value, bool allow_locked = false, bool return_flag = false);
+  static bool uintxAt(const char* name, uintx* value, bool allow_locked = false, bool return_flag = false)    { return uintxAt(name, strlen(name), value, allow_locked, return_flag); }
   static bool uintxAtPut(const char* name, size_t len, uintx* value, Flag::Flags origin);
   static bool uintxAtPut(const char* name, uintx* value, Flag::Flags origin) { return uintxAtPut(name, strlen(name), value, origin); }
 
-  static bool size_tAt(const char* name, size_t len, size_t* value);
-  static bool size_tAt(const char* name, size_t* value)    { return size_tAt(name, strlen(name), value); }
+  static bool size_tAt(const char* name, size_t len, size_t* value, bool allow_locked = false, bool return_flag = false);
+  static bool size_tAt(const char* name, size_t* value, bool allow_locked = false, bool return_flag = false)    { return size_tAt(name, strlen(name), value, allow_locked, return_flag); }
   static bool size_tAtPut(const char* name, size_t len, size_t* value, Flag::Flags origin);
   static bool size_tAtPut(const char* name, size_t* value, Flag::Flags origin) { return size_tAtPut(name, strlen(name), value, origin); }
 
-  static bool uint64_tAt(const char* name, size_t len, uint64_t* value);
-  static bool uint64_tAt(const char* name, uint64_t* value) { return uint64_tAt(name, strlen(name), value); }
+  static bool uint64_tAt(const char* name, size_t len, uint64_t* value, bool allow_locked = false, bool return_flag = false);
+  static bool uint64_tAt(const char* name, uint64_t* value, bool allow_locked = false, bool return_flag = false) { return uint64_tAt(name, strlen(name), value, allow_locked, return_flag); }
   static bool uint64_tAtPut(const char* name, size_t len, uint64_t* value, Flag::Flags origin);
   static bool uint64_tAtPut(const char* name, uint64_t* value, Flag::Flags origin) { return uint64_tAtPut(name, strlen(name), value, origin); }
 
-  static bool doubleAt(const char* name, size_t len, double* value);
-  static bool doubleAt(const char* name, double* value)    { return doubleAt(name, strlen(name), value); }
+  static bool doubleAt(const char* name, size_t len, double* value, bool allow_locked = false, bool return_flag = false);
+  static bool doubleAt(const char* name, double* value, bool allow_locked = false, bool return_flag = false)    { return doubleAt(name, strlen(name), value, allow_locked, return_flag); }
   static bool doubleAtPut(const char* name, size_t len, double* value, Flag::Flags origin);
   static bool doubleAtPut(const char* name, double* value, Flag::Flags origin) { return doubleAtPut(name, strlen(name), value, origin); }
 
-  static bool ccstrAt(const char* name, size_t len, ccstr* value);
-  static bool ccstrAt(const char* name, ccstr* value)    { return ccstrAt(name, strlen(name), value); }
+  static bool ccstrAt(const char* name, size_t len, ccstr* value, bool allow_locked = false, bool return_flag = false);
+  static bool ccstrAt(const char* name, ccstr* value, bool allow_locked = false, bool return_flag = false)    { return ccstrAt(name, strlen(name), value, allow_locked, return_flag); }
   // Contract:  Flag will make private copy of the incoming value.
   // Outgoing value is always malloc-ed, and caller MUST call free.
   static bool ccstrAtPut(const char* name, size_t len, ccstr* value, Flag::Flags origin);
@@ -2984,12 +2984,6 @@
   product(intx, SafepointTimeoutDelay, 10000,                               \
           "Delay in milliseconds for option SafepointTimeout")              \
                                                                             \
-  product(intx, NmethodSweepFraction, 16,                                   \
-          "Number of invocations of sweeper to cover all nmethods")         \
-                                                                            \
-  product(intx, NmethodSweepCheckInterval, 5,                               \
-          "Compilers wake up every n seconds to possibly sweep nmethods")   \
-                                                                            \
   product(intx, NmethodSweepActivity, 10,                                   \
           "Removes cold nmethods from code cache if > 0. Higher values "    \
           "result in more aggressive sweeping")                             \
@@ -3378,9 +3372,6 @@
   product_pd(uintx, NonNMethodCodeHeapSize,                                 \
           "Size of code heap with non-nmethods (in bytes)")                 \
                                                                             \
-  product(uintx, CodeCacheMinimumFreeSpace, 500*K,                          \
-          "When less than X space left, we stop compiling")                 \
-                                                                            \
   product_pd(uintx, CodeCacheExpansionSize,                                 \
           "Code cache expansion size (in bytes)")                           \
                                                                             \
@@ -3393,6 +3384,11 @@
   product(bool, UseCodeCacheFlushing, true,                                 \
           "Remove cold/old nmethods from the code cache")                   \
                                                                             \
+  product(uintx, StartAggressiveSweepingAt, 10,                             \
+          "Start aggressive sweeping if X[%] of the code cache is free."    \
+          "Segmented code cache: X[%] of the non-profiled heap."            \
+          "Non-segmented code cache: X[%] of the total code cache")         \
+                                                                            \
   /* interpreter debugging */                                               \
   develop(intx, BinarySwitchThreshold, 5,                                   \
           "Minimal number of lookupswitch entries for rewriting to binary " \
--- a/hotspot/src/share/vm/runtime/mutexLocker.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/runtime/mutexLocker.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -61,7 +61,7 @@
 Mutex*   StringTable_lock             = NULL;
 Monitor* StringDedupQueue_lock        = NULL;
 Mutex*   StringDedupTable_lock        = NULL;
-Mutex*   CodeCache_lock               = NULL;
+Monitor* CodeCache_lock               = NULL;
 Mutex*   MethodData_lock              = NULL;
 Mutex*   RetData_lock                 = NULL;
 Monitor* VMOperationQueue_lock        = NULL;
@@ -205,7 +205,7 @@
   }
   def(ParGCRareEvent_lock          , Mutex  , leaf     ,   true );
   def(DerivedPointerTableGC_lock   , Mutex,   leaf,        true );
-  def(CodeCache_lock               , Mutex  , special,     true );
+  def(CodeCache_lock               , Monitor, special,     true );
   def(Interrupt_lock               , Monitor, special,     true ); // used for interrupt processing
   def(RawMonitor_lock              , Mutex,   special,     true );
   def(OopMapCacheAlloc_lock        , Mutex,   leaf,        true ); // used for oop_map_cache allocation.
--- a/hotspot/src/share/vm/runtime/mutexLocker.hpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/runtime/mutexLocker.hpp	Thu Oct 30 22:52:13 2014 -0700
@@ -53,7 +53,7 @@
 extern Mutex*   StringTable_lock;                // a lock on the interned string table
 extern Monitor* StringDedupQueue_lock;           // a lock on the string deduplication queue
 extern Mutex*   StringDedupTable_lock;           // a lock on the string deduplication table
-extern Mutex*   CodeCache_lock;                  // a lock on the CodeCache, rank is special, use MutexLockerEx
+extern Monitor* CodeCache_lock;                  // a lock on the CodeCache, rank is special, use MutexLockerEx
 extern Mutex*   MethodData_lock;                 // a lock on installation of method data
 extern Mutex*   RetData_lock;                    // a lock on installation of RetData inside method data
 extern Mutex*   DerivedPointerTableGC_lock;      // a lock to protect the derived pointer table
--- a/hotspot/src/share/vm/runtime/os.hpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/runtime/os.hpp	Thu Oct 30 22:52:13 2014 -0700
@@ -680,28 +680,10 @@
   // SocketInterface (ex HPI SocketInterface )
   static int socket(int domain, int type, int protocol);
   static int socket_close(int fd);
-  static int socket_shutdown(int fd, int howto);
   static int recv(int fd, char* buf, size_t nBytes, uint flags);
   static int send(int fd, char* buf, size_t nBytes, uint flags);
   static int raw_send(int fd, char* buf, size_t nBytes, uint flags);
-  static int timeout(int fd, long timeout);
-  static int listen(int fd, int count);
   static int connect(int fd, struct sockaddr* him, socklen_t len);
-  static int bind(int fd, struct sockaddr* him, socklen_t len);
-  static int accept(int fd, struct sockaddr* him, socklen_t* len);
-  static int recvfrom(int fd, char* buf, size_t nbytes, uint flags,
-                      struct sockaddr* from, socklen_t* fromlen);
-  static int get_sock_name(int fd, struct sockaddr* him, socklen_t* len);
-  static int sendto(int fd, char* buf, size_t len, uint flags,
-                    struct sockaddr* to, socklen_t tolen);
-  static int socket_available(int fd, jint* pbytes);
-
-  static int get_sock_opt(int fd, int level, int optname,
-                          char* optval, socklen_t* optlen);
-  static int set_sock_opt(int fd, int level, int optname,
-                          const char* optval, socklen_t optlen);
-  static int get_host_name(char* name, int namelen);
-
   static struct hostent* get_host_by_name(char* name);
 
   // Support for signals (see JVM_RaiseSignal, JVM_RegisterSignal)
--- a/hotspot/src/share/vm/runtime/sharedRuntime.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/runtime/sharedRuntime.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -2421,8 +2421,6 @@
       // CodeCache is full, disable compilation
       // Ought to log this but compile log is only per compile thread
       // and we're some non descript Java thread.
-      MutexUnlocker mu(AdapterHandlerLibrary_lock);
-      CompileBroker::handle_full_code_cache(CodeBlobType::NonNMethod);
       return NULL; // Out of CodeCache space
     }
     entry->relocate(new_adapter->content_begin());
@@ -2594,9 +2592,6 @@
       CompileTask::print_compilation(tty, nm, method->is_static() ? "(static)" : "");
     }
     nm->post_compiled_method_load_event();
-  } else {
-    // CodeCache is full, disable compilation
-    CompileBroker::handle_full_code_cache(CodeBlobType::MethodNonProfiled);
   }
 }
 
--- a/hotspot/src/share/vm/runtime/sweeper.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/runtime/sweeper.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -52,7 +52,6 @@
 class SweeperRecord {
  public:
   int traversal;
-  int invocation;
   int compile_id;
   long traversal_mark;
   int state;
@@ -62,10 +61,9 @@
   int line;
 
   void print() {
-      tty->print_cr("traversal = %d invocation = %d compile_id = %d %s uep = " PTR_FORMAT " vep = "
+      tty->print_cr("traversal = %d compile_id = %d %s uep = " PTR_FORMAT " vep = "
                     PTR_FORMAT " state = %d traversal_mark %d line = %d",
                     traversal,
-                    invocation,
                     compile_id,
                     kind == NULL ? "" : kind,
                     uep,
@@ -117,7 +115,6 @@
   if (_records != NULL) {
     _records[_sweep_index].traversal = _traversals;
     _records[_sweep_index].traversal_mark = nm->_stack_traversal_mark;
-    _records[_sweep_index].invocation = _sweep_fractions_left;
     _records[_sweep_index].compile_id = nm->compile_id();
     _records[_sweep_index].kind = nm->compile_kind();
     _records[_sweep_index].state = nm->_state;
@@ -127,6 +124,14 @@
     _sweep_index = (_sweep_index + 1) % SweeperLogEntries;
   }
 }
+
+void NMethodSweeper::init_sweeper_log() {
+ if (LogSweeper && _records == NULL) {
+   // Create the ring buffer for the logging code
+   _records = NEW_C_HEAP_ARRAY(SweeperRecord, SweeperLogEntries, mtGC);
+   memset(_records, 0, sizeof(SweeperRecord) * SweeperLogEntries);
+  }
+}
 #else
 #define SWEEP(nm)
 #endif
@@ -142,8 +147,6 @@
 int      NMethodSweeper::_marked_for_reclamation_count = 0;    // Nof. nmethods marked for reclaim in current sweep
 
 volatile bool NMethodSweeper::_should_sweep            = true; // Indicates if we should invoke the sweeper
-volatile int  NMethodSweeper::_sweep_fractions_left    = 0;    // Nof. invocations left until we are completed with this pass
-volatile int  NMethodSweeper::_sweep_started           = 0;    // Flag to control conc sweeper
 volatile int  NMethodSweeper::_bytes_changed           = 0;    // Counts the total nmethod size if the nmethod changed from:
                                                                //   1) alive       -> not_entrant
                                                                //   2) not_entrant -> zombie
@@ -190,13 +193,15 @@
   }
   return _hotness_counter_reset_val;
 }
-bool NMethodSweeper::sweep_in_progress() {
-  return !_current.end();
+bool NMethodSweeper::wait_for_stack_scanning() {
+  return _current.end();
 }
 
-// Scans the stacks of all Java threads and marks activations of not-entrant methods.
-// No need to synchronize access, since 'mark_active_nmethods' is always executed at a
-// safepoint.
+/**
+  * Scans the stacks of all Java threads and marks activations of not-entrant methods.
+  * No need to synchronize access, since 'mark_active_nmethods' is always executed at a
+  * safepoint.
+  */
 void NMethodSweeper::mark_active_nmethods() {
   assert(SafepointSynchronize::is_at_safepoint(), "must be executed at a safepoint");
   // If we do not want to reclaim not-entrant or zombie methods there is no need
@@ -210,9 +215,8 @@
 
   // Check for restart
   assert(CodeCache::find_blob_unsafe(_current.method()) == _current.method(), "Sweeper nmethod cached state invalid");
-  if (!sweep_in_progress()) {
+  if (wait_for_stack_scanning()) {
     _seen = 0;
-    _sweep_fractions_left = NmethodSweepFraction;
     _current = NMethodIterator();
     // Initialize to first nmethod
     _current.next();
@@ -231,6 +235,64 @@
 
   OrderAccess::storestore();
 }
+
+/**
+  * This function triggers a VM operation that does stack scanning of active
+  * methods. Stack scanning is mandatory for the sweeper to make progress.
+  */
+void NMethodSweeper::do_stack_scanning() {
+  assert(!CodeCache_lock->owned_by_self(), "just checking");
+  if (wait_for_stack_scanning()) {
+    VM_MarkActiveNMethods op;
+    VMThread::execute(&op);
+    _should_sweep = true;
+  }
+}
+
+void NMethodSweeper::sweeper_loop() {
+  bool timeout;
+  while (true) {
+    {
+      ThreadBlockInVM tbivm(JavaThread::current());
+      MutexLockerEx waiter(CodeCache_lock, Mutex::_no_safepoint_check_flag);
+      const long wait_time = 60*60*24 * 1000;
+      timeout = CodeCache_lock->wait(Mutex::_no_safepoint_check_flag, wait_time);
+    }
+    if (!timeout) {
+      possibly_sweep();
+    }
+  }
+}
+
+/**
+  * Wakes up the sweeper thread to possibly sweep.
+  */
+void NMethodSweeper::notify(int code_blob_type) {
+  // Makes sure that we do not invoke the sweeper too often during startup.
+  double start_threshold = 100.0 / (double)StartAggressiveSweepingAt;
+  double aggressive_sweep_threshold = MIN2(start_threshold, 1.1);
+  if (CodeCache::reverse_free_ratio(code_blob_type) >= aggressive_sweep_threshold) {
+    assert_locked_or_safepoint(CodeCache_lock);
+    CodeCache_lock->notify();
+  }
+}
+
+/**
+ * Handle a safepoint request
+ */
+void NMethodSweeper::handle_safepoint_request() {
+  if (SafepointSynchronize::is_synchronizing()) {
+    if (PrintMethodFlushing && Verbose) {
+      tty->print_cr("### Sweep at %d out of %d, yielding to safepoint", _seen, CodeCache::nof_nmethods());
+    }
+    MutexUnlockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
+
+    JavaThread* thread = JavaThread::current();
+    ThreadBlockInVM tbivm(thread);
+    thread->java_suspend_self();
+  }
+}
+
 /**
  * This function invokes the sweeper if at least one of the three conditions is met:
  *    (1) The code cache is getting full
@@ -239,11 +301,6 @@
  */
 void NMethodSweeper::possibly_sweep() {
   assert(JavaThread::current()->thread_state() == _thread_in_vm, "must run in vm mode");
-  // Only compiler threads are allowed to sweep
-  if (!MethodFlushing || !sweep_in_progress() || !Thread::current()->is_Compiler_thread()) {
-    return;
-  }
-
   // If there was no state change while nmethod sweeping, 'should_sweep' will be false.
   // This is one of the two places where should_sweep can be set to true. The general
   // idea is as follows: If there is enough free space in the code cache, there is no
@@ -280,46 +337,37 @@
     }
   }
 
-  if (_should_sweep && _sweep_fractions_left > 0) {
-    // Only one thread at a time will sweep
-    jint old = Atomic::cmpxchg( 1, &_sweep_started, 0 );
-    if (old != 0) {
-      return;
-    }
-#ifdef ASSERT
-    if (LogSweeper && _records == NULL) {
-      // Create the ring buffer for the logging code
-      _records = NEW_C_HEAP_ARRAY(SweeperRecord, SweeperLogEntries, mtGC);
-      memset(_records, 0, sizeof(SweeperRecord) * SweeperLogEntries);
-    }
-#endif
+  // Force stack scanning if there is only 10% free space in the code cache.
+  // We force stack scanning only non-profiled code heap gets full, since critical
+  // allocation go to the non-profiled heap and we must be make sure that there is
+  // enough space.
+  double free_percent = 1 / CodeCache::reverse_free_ratio(CodeBlobType::MethodNonProfiled) * 100;
+  if (free_percent <= StartAggressiveSweepingAt) {
+    do_stack_scanning();
+  }
 
-    if (_sweep_fractions_left > 0) {
-      sweep_code_cache();
-      _sweep_fractions_left--;
-    }
+  if (_should_sweep) {
+    init_sweeper_log();
+    sweep_code_cache();
+  }
 
-    // We are done with sweeping the code cache once.
-    if (_sweep_fractions_left == 0) {
-      _total_nof_code_cache_sweeps++;
-      _last_sweep = _time_counter;
-      // Reset flag; temporarily disables sweeper
-      _should_sweep = false;
-      // If there was enough state change, 'possibly_enable_sweeper()'
-      // sets '_should_sweep' to true
-      possibly_enable_sweeper();
-      // Reset _bytes_changed only if there was enough state change. _bytes_changed
-      // can further increase by calls to 'report_state_change'.
-      if (_should_sweep) {
-        _bytes_changed = 0;
-      }
-    }
-    // Release work, because another compiler thread could continue.
-    OrderAccess::release_store((int*)&_sweep_started, 0);
+  // We are done with sweeping the code cache once.
+  _total_nof_code_cache_sweeps++;
+  _last_sweep = _time_counter;
+  // Reset flag; temporarily disables sweeper
+  _should_sweep = false;
+  // If there was enough state change, 'possibly_enable_sweeper()'
+  // sets '_should_sweep' to true
+   possibly_enable_sweeper();
+  // Reset _bytes_changed only if there was enough state change. _bytes_changed
+  // can further increase by calls to 'report_state_change'.
+  if (_should_sweep) {
+    _bytes_changed = 0;
   }
 }
 
 void NMethodSweeper::sweep_code_cache() {
+  ResourceMark rm;
   Ticks sweep_start_counter = Ticks::now();
 
   _flushed_count                = 0;
@@ -327,25 +375,10 @@
   _marked_for_reclamation_count = 0;
 
   if (PrintMethodFlushing && Verbose) {
-    tty->print_cr("### Sweep at %d out of %d. Invocations left: %d", _seen, CodeCache::nof_nmethods(), _sweep_fractions_left);
-  }
-
-  if (!CompileBroker::should_compile_new_jobs()) {
-    // If we have turned off compilations we might as well do full sweeps
-    // in order to reach the clean state faster. Otherwise the sleeping compiler
-    // threads will slow down sweeping.
-    _sweep_fractions_left = 1;
+    tty->print_cr("### Sweep at %d out of %d", _seen, CodeCache::nof_nmethods());
   }
 
-  // We want to visit all nmethods after NmethodSweepFraction
-  // invocations so divide the remaining number of nmethods by the
-  // remaining number of invocations.  This is only an estimate since
-  // the number of nmethods changes during the sweep so the final
-  // stage must iterate until it there are no more nmethods.
-  int todo = (CodeCache::nof_nmethods() - _seen) / _sweep_fractions_left;
   int swept_count = 0;
-
-
   assert(!SafepointSynchronize::is_at_safepoint(), "should not be in safepoint when we get here");
   assert(!CodeCache_lock->owned_by_self(), "just checking");
 
@@ -354,19 +387,9 @@
     MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 
     // The last invocation iterates until there are no more nmethods
-    while ((swept_count < todo || _sweep_fractions_left == 1) && !_current.end()) {
+    while (!_current.end()) {
       swept_count++;
-      if (SafepointSynchronize::is_synchronizing()) { // Safepoint request
-        if (PrintMethodFlushing && Verbose) {
-          tty->print_cr("### Sweep at %d out of %d, invocation: %d, yielding to safepoint", _seen, CodeCache::nof_nmethods(), _sweep_fractions_left);
-        }
-        MutexUnlockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
-
-        assert(Thread::current()->is_Java_thread(), "should be java thread");
-        JavaThread* thread = (JavaThread*)Thread::current();
-        ThreadBlockInVM tbivm(thread);
-        thread->java_suspend_self();
-      }
+      handle_safepoint_request();
       // Since we will give up the CodeCache_lock, always skip ahead
       // to the next nmethod.  Other blobs can be deleted by other
       // threads but nmethods are only reclaimed by the sweeper.
@@ -382,7 +405,7 @@
     }
   }
 
-  assert(_sweep_fractions_left > 1 || _current.end(), "must have scanned the whole cache");
+  assert(_current.end(), "must have scanned the whole cache");
 
   const Ticks sweep_end_counter = Ticks::now();
   const Tickspan sweep_time = sweep_end_counter - sweep_start_counter;
@@ -397,7 +420,6 @@
     event.set_starttime(sweep_start_counter);
     event.set_endtime(sweep_end_counter);
     event.set_sweepIndex(_traversals);
-    event.set_sweepFractionIndex(NmethodSweepFraction - _sweep_fractions_left + 1);
     event.set_sweptCount(swept_count);
     event.set_flushedCount(_flushed_count);
     event.set_markedCount(_marked_for_reclamation_count);
@@ -407,15 +429,12 @@
 
 #ifdef ASSERT
   if(PrintMethodFlushing) {
-    tty->print_cr("### sweeper:      sweep time(%d): "
-      INT64_FORMAT, _sweep_fractions_left, (jlong)sweep_time.value());
+    tty->print_cr("### sweeper:      sweep time(%d): ", (jlong)sweep_time.value());
   }
 #endif
 
-  if (_sweep_fractions_left == 1) {
-    _peak_sweep_time = MAX2(_peak_sweep_time, _total_time_this_sweep);
-    log_sweep("finished");
-  }
+  _peak_sweep_time = MAX2(_peak_sweep_time, _total_time_this_sweep);
+  log_sweep("finished");
 
   // Sweeper is the only case where memory is released, check here if it
   // is time to restart the compiler. Only checking if there is a certain
@@ -459,10 +478,12 @@
 
 class NMethodMarker: public StackObj {
  private:
-  CompilerThread* _thread;
+  CodeCacheSweeperThread* _thread;
  public:
   NMethodMarker(nmethod* nm) {
-    _thread = CompilerThread::current();
+    JavaThread* current = JavaThread::current();
+    assert (current->is_Code_cache_sweeper_thread(), "Must be");
+    _thread = (CodeCacheSweeperThread*)JavaThread::current();
     if (!nm->is_zombie() && !nm->is_unloaded()) {
       // Only expose live nmethods for scanning
       _thread->set_scanned_nmethod(nm);
@@ -473,7 +494,7 @@
   }
 };
 
-void NMethodSweeper::release_nmethod(nmethod *nm) {
+void NMethodSweeper::release_nmethod(nmethod* nm) {
   // Clean up any CompiledICHolders
   {
     ResourceMark rm;
@@ -490,7 +511,7 @@
   nm->flush();
 }
 
-int NMethodSweeper::process_nmethod(nmethod *nm) {
+int NMethodSweeper::process_nmethod(nmethod* nm) {
   assert(!CodeCache_lock->owned_by_self(), "just checking");
 
   int freed_memory = 0;
--- a/hotspot/src/share/vm/runtime/sweeper.hpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/runtime/sweeper.hpp	Thu Oct 30 22:52:13 2014 -0700
@@ -49,9 +49,7 @@
 //     remove the nmethod, all inline caches (IC) that point to the the nmethod must be
 //     cleared. After that, the nmethod can be evicted from the code cache. Each nmethod's
 //     state change happens during separate sweeps. It may take at least 3 sweeps before an
-//     nmethod's space is freed. Sweeping is currently done by compiler threads between
-//     compilations or at least each 5 sec (NmethodSweepCheckInterval) when the code cache
-//     is full.
+//     nmethod's space is freed.
 
 class NMethodSweeper : public AllStatic {
   static long      _traversals;                   // Stack scan count, also sweep ID.
@@ -64,7 +62,6 @@
   static int       _zombified_count;              // Nof. nmethods made zombie in current sweep
   static int       _marked_for_reclamation_count; // Nof. nmethods marked for reclaim in current sweep
 
-  static volatile int  _sweep_fractions_left;     // Nof. invocations left until we are completed with this pass
   static volatile int  _sweep_started;            // Flag to control conc sweeper
   static volatile bool _should_sweep;             // Indicates if we should invoke the sweeper
   static volatile int _bytes_changed;             // Counts the total nmethod size if the nmethod changed from:
@@ -85,8 +82,12 @@
   static int  process_nmethod(nmethod *nm);
   static void release_nmethod(nmethod* nm);
 
-  static bool sweep_in_progress();
+  static void init_sweeper_log() NOT_DEBUG_RETURN;
+  static bool wait_for_stack_scanning();
   static void sweep_code_cache();
+  static void handle_safepoint_request();
+  static void do_stack_scanning();
+  static void possibly_sweep();
 
  public:
   static long traversal_count()              { return _traversals; }
@@ -106,7 +107,8 @@
 #endif
 
   static void mark_active_nmethods();      // Invoked at the end of each safepoint
-  static void possibly_sweep();            // Compiler threads call this to sweep
+  static void sweeper_loop();
+  static void notify(int code_blob_type);  // Possibly start the sweeper thread.
 
   static int hotness_counter_reset_val();
   static void report_state_change(nmethod* nm);
--- a/hotspot/src/share/vm/runtime/thread.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/runtime/thread.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -66,6 +66,7 @@
 #include "runtime/sharedRuntime.hpp"
 #include "runtime/statSampler.hpp"
 #include "runtime/stubRoutines.hpp"
+#include "runtime/sweeper.hpp"
 #include "runtime/task.hpp"
 #include "runtime/thread.inline.hpp"
 #include "runtime/threadCritical.hpp"
@@ -1553,6 +1554,7 @@
 
 // Remove this ifdef when C1 is ported to the compiler interface.
 static void compiler_thread_entry(JavaThread* thread, TRAPS);
+static void sweeper_thread_entry(JavaThread* thread, TRAPS);
 
 JavaThread::JavaThread(ThreadFunction entry_point, size_t stack_sz) :
                        Thread()
@@ -3172,6 +3174,10 @@
   CompileBroker::compiler_thread_loop();
 }
 
+static void sweeper_thread_entry(JavaThread* thread, TRAPS) {
+  NMethodSweeper::sweeper_loop();
+}
+
 // Create a CompilerThread
 CompilerThread::CompilerThread(CompileQueue* queue,
                                CompilerCounters* counters)
@@ -3182,7 +3188,6 @@
   _queue = queue;
   _counters = counters;
   _buffer_blob = NULL;
-  _scanned_nmethod = NULL;
   _compiler = NULL;
 
 #ifndef PRODUCT
@@ -3190,7 +3195,12 @@
 #endif
 }
 
-void CompilerThread::oops_do(OopClosure* f, CLDClosure* cld_f, CodeBlobClosure* cf) {
+// Create sweeper thread
+CodeCacheSweeperThread::CodeCacheSweeperThread()
+: JavaThread(&sweeper_thread_entry) {
+  _scanned_nmethod = NULL;
+}
+void CodeCacheSweeperThread::oops_do(OopClosure* f, CLDClosure* cld_f, CodeBlobClosure* cf) {
   JavaThread::oops_do(f, cld_f, cf);
   if (_scanned_nmethod != NULL && cf != NULL) {
     // Safepoints can occur when the sweeper is scanning an nmethod so
--- a/hotspot/src/share/vm/runtime/thread.hpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/runtime/thread.hpp	Thu Oct 30 22:52:13 2014 -0700
@@ -311,6 +311,7 @@
   virtual bool is_VM_thread()       const            { return false; }
   virtual bool is_Java_thread()     const            { return false; }
   virtual bool is_Compiler_thread() const            { return false; }
+  virtual bool is_Code_cache_sweeper_thread() const  { return false; }
   virtual bool is_hidden_from_external_view() const  { return false; }
   virtual bool is_jvmti_agent_thread() const         { return false; }
   // True iff the thread can perform GC operations at a safepoint.
@@ -1755,6 +1756,27 @@
   return (CompilerThread*)this;
 }
 
+// Dedicated thread to sweep the code cache
+class CodeCacheSweeperThread : public JavaThread {
+  nmethod*       _scanned_nmethod; // nmethod being scanned by the sweeper
+ public:
+  CodeCacheSweeperThread();
+  // Track the nmethod currently being scanned by the sweeper
+  void set_scanned_nmethod(nmethod* nm) {
+    assert(_scanned_nmethod == NULL || nm == NULL, "should reset to NULL before writing a new value");
+    _scanned_nmethod = nm;
+  }
+
+  // Hide sweeper thread from external view.
+  bool is_hidden_from_external_view() const { return true; }
+
+  bool is_Code_cache_sweeper_thread() const { return true; }
+  // GC support
+  // Apply "f->do_oop" to all root oops in "this".
+  // Apply "cf->do_code_blob" (if !NULL) to all code blobs active in frames
+  void oops_do(OopClosure* f, CLDClosure* cld_f, CodeBlobClosure* cf);
+};
+
 // A thread used for Compilation.
 class CompilerThread : public JavaThread {
   friend class VMStructs;
@@ -1767,7 +1789,6 @@
   CompileQueue*     _queue;
   BufferBlob*       _buffer_blob;
 
-  nmethod*          _scanned_nmethod;  // nmethod being scanned by the sweeper
   AbstractCompiler* _compiler;
 
  public:
@@ -1801,28 +1822,17 @@
     _log = log;
   }
 
-  // GC support
-  // Apply "f->do_oop" to all root oops in "this".
-  // Apply "cf->do_code_blob" (if !NULL) to all code blobs active in frames
-  void oops_do(OopClosure* f, CLDClosure* cld_f, CodeBlobClosure* cf);
-
 #ifndef PRODUCT
  private:
   IdealGraphPrinter *_ideal_graph_printer;
  public:
-  IdealGraphPrinter *ideal_graph_printer()                       { return _ideal_graph_printer; }
-  void set_ideal_graph_printer(IdealGraphPrinter *n)             { _ideal_graph_printer = n; }
+  IdealGraphPrinter *ideal_graph_printer()           { return _ideal_graph_printer; }
+  void set_ideal_graph_printer(IdealGraphPrinter *n) { _ideal_graph_printer = n; }
 #endif
 
   // Get/set the thread's current task
-  CompileTask*  task()                           { return _task; }
-  void          set_task(CompileTask* task)      { _task = task; }
-
-  // Track the nmethod currently being scanned by the sweeper
-  void          set_scanned_nmethod(nmethod* nm) {
-    assert(_scanned_nmethod == NULL || nm == NULL, "should reset to NULL before writing a new value");
-    _scanned_nmethod = nm;
-  }
+  CompileTask* task()                      { return _task; }
+  void         set_task(CompileTask* task) { _task = task; }
 };
 
 inline CompilerThread* CompilerThread::current() {
--- a/hotspot/src/share/vm/runtime/vm_operations.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/runtime/vm_operations.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -111,6 +111,9 @@
   CodeCache::make_marked_nmethods_zombies();
 }
 
+void VM_MarkActiveNMethods::doit() {
+  NMethodSweeper::mark_active_nmethods();
+}
 
 VM_DeoptimizeFrame::VM_DeoptimizeFrame(JavaThread* thread, intptr_t* id) {
   _thread = thread;
--- a/hotspot/src/share/vm/runtime/vm_operations.hpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/runtime/vm_operations.hpp	Thu Oct 30 22:52:13 2014 -0700
@@ -100,6 +100,7 @@
   template(RotateGCLog)                           \
   template(WhiteBoxOperation)                     \
   template(ClassLoaderStatsOperation)             \
+  template(MarkActiveNMethods)                    \
   template(PrintCompileQueue)                     \
   template(PrintCodeList)                         \
   template(PrintCodeCache)                        \
@@ -252,6 +253,13 @@
   bool allow_nested_vm_operations() const        { return true; }
 };
 
+class VM_MarkActiveNMethods: public VM_Operation {
+ public:
+  VM_MarkActiveNMethods() {}
+  VMOp_Type type() const                         { return VMOp_MarkActiveNMethods; }
+  void doit();
+  bool allow_nested_vm_operations() const        { return true; }
+};
 
 // Deopt helper that can deoptimize frames in threads other than the
 // current thread.  Only used through Deoptimization::deoptimize_frame.
--- a/hotspot/src/share/vm/trace/trace.xml	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/trace/trace.xml	Thu Oct 30 22:52:13 2014 -0700
@@ -383,7 +383,6 @@
     <event id="SweepCodeCache" path="vm/code_sweeper/sweep" label="Sweep Code Cache"
        has_thread="true" is_requestable="false" is_constant="false">
       <value type="INTEGER" field="sweepIndex" label="Sweep Index" relation="SWEEP_ID"/>
-      <value type="USHORT" field="sweepFractionIndex" label="Fraction Index"/>
       <value type="UINT" field="sweptCount" label="Methods Swept"/>
       <value type="UINT" field="flushedCount" label="Methods Flushed"/>
       <value type="UINT" field="markedCount" label="Methods Reclaimed"/>
--- a/hotspot/src/share/vm/utilities/debug.cpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/utilities/debug.cpp	Thu Oct 30 22:52:13 2014 -0700
@@ -256,16 +256,18 @@
   static const char* name[] = {
     "shared read only space",
     "shared read write space",
-    "shared miscellaneous data space"
+    "shared miscellaneous data space",
+    "shared miscellaneous code space"
   };
   static const char* flag[] = {
     "SharedReadOnlySize",
     "SharedReadWriteSize",
-    "SharedMiscDataSize"
+    "SharedMiscDataSize",
+    "SharedMiscCodeSize"
   };
 
    warning("\nThe %s is not large enough\n"
-           "to preload requested classes. Use -XX:%s=\n"
+           "to preload requested classes. Use -XX:%s=<size>\n"
            "to increase the initial size of %s.\n",
            name[shared_space], flag[shared_space], name[shared_space]);
    exit(2);
--- a/hotspot/src/share/vm/utilities/debug.hpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/utilities/debug.hpp	Thu Oct 30 22:52:13 2014 -0700
@@ -245,7 +245,8 @@
 enum SharedSpaceType {
   SharedReadOnly,
   SharedReadWrite,
-  SharedMiscData
+  SharedMiscData,
+  SharedMiscCode
 };
 
 void report_out_of_shared_space(SharedSpaceType space_type);
--- a/hotspot/src/share/vm/utilities/dtrace_disabled.hpp	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/src/share/vm/utilities/dtrace_disabled.hpp	Thu Oct 30 22:52:13 2014 -0700
@@ -27,7 +27,7 @@
 
 /* This file contains dummy provider probes needed when compiling a hotspot
  * that does not support dtrace probes. This could be because we're building
- * on a system that doesn't suuport dtrace or because we're bulding a variant
+ * on a system that doesn't support dtrace or because we're bulding a variant
  * of hotspot (like core) where we do not support dtrace
  */
 #if !defined(DTRACE_ENABLED)
--- a/hotspot/test/TEST.groups	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/test/TEST.groups	Thu Oct 30 22:52:13 2014 -0700
@@ -198,7 +198,8 @@
 
 # Tests that require compact2 API's
 #
-needs_compact2 =
+needs_compact2 = \
+  compiler/jsr292/CreatesInterfaceDotEqualsCallInfo.java
 
 # All tests that run on the most minimal configuration: Minimal VM on Compact 1
 compact1_minimal = \
@@ -443,6 +444,7 @@
   compiler/arraycopy/TestMissingControl.java \
   compiler/ciReplay/TestVM_no_comp_level.sh \
   compiler/classUnloading/anonymousClass/TestAnonymousClassUnloading.java \
+  compiler/codecache/CheckSegmentedCodeCache.java \
   compiler/codecache/CheckUpperLimit.java \
   compiler/codegen/ \
   compiler/cpuflags/RestoreMXCSR.java \
@@ -479,7 +481,6 @@
   compiler/intrinsics/unsafe/UnsafeGetAddressTest.java \
   compiler/jsr292/ConcurrentClassLoadingTest.java \
   compiler/jsr292/CreatesInterfaceDotEqualsCallInfo.java \
-  compiler/jsr292/CreatesInterfaceDotEqualsCallInfo.java \
   compiler/loopopts/TestLogSum.java \
   compiler/macronodes/TestEliminateAllocationPhi.java \
   compiler/membars/TestMemBarAcquire.java \
@@ -602,3 +603,14 @@
   :hotspot_gc \
   :hotspot_runtime \
   :hotspot_serviceability
+
+#All tests that depends on nashorn extension.
+#
+needs_nashorn = \
+  compiler/jsr292/CreatesInterfaceDotEqualsCallInfo.java
+
+#All tests that do not depends on nashorn extension
+#
+not_needs_nashorn = \
+  :jdk \
+  -:needs_nashorh
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/EliminateAutoBox/UnsignedLoads.java	Thu Oct 30 22:52:13 2014 -0700
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @library /testlibrary
+ * @run main/othervm -Xbatch -XX:+EliminateAutoBox
+ *                   -XX:CompileOnly=::valueOf,::byteValue,::shortValue,::testUnsignedByte,::testUnsignedShort
+ *                   UnsignedLoads
+ */
+import static com.oracle.java.testlibrary.Asserts.assertEQ;
+
+public class UnsignedLoads {
+    public static int testUnsignedByte() {
+        byte[] bytes = new byte[] {-1};
+        int res = 0;
+        for (int i = 0; i < 100000; i++) {
+            for (Byte b : bytes) {
+                res = b & 0xff;
+            }
+        }
+        return res;
+    }
+
+    public static int testUnsignedShort() {
+        int res = 0;
+        short[] shorts = new short[] {-1};
+        for (int i = 0; i < 100000; i++) {
+            for (Short s : shorts) {
+                res = s & 0xffff;
+            }
+        }
+        return res;
+    }
+
+    public static void main(String[] args) {
+        assertEQ(testUnsignedByte(),    255);
+        assertEQ(testUnsignedShort(), 65535);
+        System.out.println("TEST PASSED");
+    }
+}
--- a/hotspot/test/compiler/codecache/CheckSegmentedCodeCache.java	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/test/compiler/codecache/CheckSegmentedCodeCache.java	Thu Oct 30 22:52:13 2014 -0700
@@ -22,15 +22,20 @@
  */
 
 import com.oracle.java.testlibrary.*;
+import sun.hotspot.WhiteBox;
 
 /*
  * @test CheckSegmentedCodeCache
  * @bug 8015774
+ * @library /testlibrary /testlibrary/whitebox
  * @summary "Checks VM options related to the segmented code cache"
- * @library /testlibrary
- * @run main/othervm CheckSegmentedCodeCache
+ * @build CheckSegmentedCodeCache
+ * @run main ClassFileInstaller sun.hotspot.WhiteBox
+ *                              sun.hotspot.WhiteBox$WhiteBoxPermission
+ * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI CheckSegmentedCodeCache
  */
 public class CheckSegmentedCodeCache {
+  private static final WhiteBox WHITE_BOX = WhiteBox.getWhiteBox();
   // Code heap names
   private static final String NON_METHOD = "CodeHeap 'non-nmethods'";
   private static final String PROFILED = "CodeHeap 'profiled nmethods'";
@@ -133,8 +138,11 @@
     failsWith(pb, "Invalid code heap sizes");
 
     // Fails if not enough space for VM internal code
+    long minUseSpace = WHITE_BOX.getUintxVMFlag("CodeCacheMinimumUseSpace");
+    // minimum size: CodeCacheMinimumUseSpace DEBUG_ONLY(* 3)
+    long minSize = (Platform.isDebugBuild() ? 3 : 1) * minUseSpace;
     pb = ProcessTools.createJavaProcessBuilder("-XX:+SegmentedCodeCache",
-                                               "-XX:ReservedCodeCacheSize=1700K",
+                                               "-XX:ReservedCodeCacheSize=" + minSize,
                                                "-XX:InitialCodeCacheSize=100K");
     failsWith(pb, "Not enough space in non-nmethod code heap to run VM");
   }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/debug/TraceIterativeGVN.java	Thu Oct 30 22:52:13 2014 -0700
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @run main/othervm -Xbatch -XX:-TieredCompilation
+ *                   -XX:+IgnoreUnrecognizedVMOptions -XX:+TraceIterativeGVN
+ *                   TraceIterativeGVN
+ */
+public class TraceIterativeGVN {
+    public static void main(String[] args) {
+        for (int i = 0; i < 100_000; i++) {
+            Byte.valueOf((byte)0);
+        }
+        System.out.println("TEST PASSED");
+    }
+}
--- a/hotspot/test/compiler/exceptions/CatchInlineExceptions.java	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/test/compiler/exceptions/CatchInlineExceptions.java	Thu Oct 30 22:52:13 2014 -0700
@@ -70,7 +70,7 @@
         if (counter1 != 0) {
             throw new RuntimeException("Failed: counter1(" + counter1  + ") != 0");
         }
-        if (counter2 != counter) {
+        if (counter2 != counter0) {
             throw new RuntimeException("Failed: counter2(" + counter2  + ") != counter0(" + counter0  + ")");
         }
         if (counter2 != counter) {
--- a/hotspot/test/compiler/intrinsics/bmi/TestAndnI.java	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/test/compiler/intrinsics/bmi/TestAndnI.java	Thu Oct 30 22:52:13 2014 -0700
@@ -41,14 +41,14 @@
 
     public static void main(String args[]) throws Throwable {
         if (!CPUInfo.hasFeature("bmi1")) {
-            System.out.println("CPU does not support bmi1 feature. "+
-                               "Test skipped.");
-            return;
+            System.out.println("INFO: CPU does not support bmi1 feature.");
         }
 
         BMITestRunner.runTests(AndnIExpr.class, args,
+                               "-XX:+IgnoreUnrecognizedVMOptions",
                                "-XX:+UseBMI1Instructions");
         BMITestRunner.runTests(AndnICommutativeExpr.class, args,
+                               "-XX:+IgnoreUnrecognizedVMOptions",
                                "-XX:+UseBMI1Instructions");
     }
 
--- a/hotspot/test/compiler/intrinsics/bmi/TestAndnL.java	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/test/compiler/intrinsics/bmi/TestAndnL.java	Thu Oct 30 22:52:13 2014 -0700
@@ -41,14 +41,14 @@
 
     public static void main(String args[]) throws Throwable {
         if (!CPUInfo.hasFeature("bmi1")) {
-            System.out.println("CPU does not support bmi1 feature. " +
-                               "Test skipped.");
-            return;
+            System.out.println("INFO: CPU does not support bmi1 feature.");
         }
 
         BMITestRunner.runTests(AndnLExpr.class, args,
+                               "-XX:+IgnoreUnrecognizedVMOptions",
                                "-XX:+UseBMI1Instructions");
         BMITestRunner.runTests(AndnLCommutativeExpr.class, args,
+                              "-XX:+IgnoreUnrecognizedVMOptions",
                                "-XX:+UseBMI1Instructions");
     }
 
--- a/hotspot/test/compiler/intrinsics/bmi/TestBlsiI.java	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/test/compiler/intrinsics/bmi/TestBlsiI.java	Thu Oct 30 22:52:13 2014 -0700
@@ -41,14 +41,14 @@
 
     public static void main(String args[]) throws Throwable {
         if (!CPUInfo.hasFeature("bmi1")) {
-            System.out.println("CPU does not support bmi1 feature. " +
-                               "Test skipped.");
-            return;
+            System.out.println("INFO: CPU does not support bmi1 feature.");
         }
 
         BMITestRunner.runTests(BlsiIExpr.class, args,
+                               "-XX:+IgnoreUnrecognizedVMOptions",
                                "-XX:+UseBMI1Instructions");
         BMITestRunner.runTests(BlsiICommutativeExpr.class, args,
+                               "-XX:+IgnoreUnrecognizedVMOptions",
                                "-XX:+UseBMI1Instructions");
     }
 
--- a/hotspot/test/compiler/intrinsics/bmi/TestBlsiL.java	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/test/compiler/intrinsics/bmi/TestBlsiL.java	Thu Oct 30 22:52:13 2014 -0700
@@ -41,14 +41,14 @@
 
     public static void main(String args[]) throws Throwable {
         if (!CPUInfo.hasFeature("bmi1")) {
-            System.out.println("CPU does not support bmi1 feature. " +
-                               "Test skipped.");
-            return;
+            System.out.println("INFO: CPU does not support bmi1 feature.");
         }
 
         BMITestRunner.runTests(BlsiLExpr.class, args,
+                               "-XX:+IgnoreUnrecognizedVMOptions",
                                "-XX:+UseBMI1Instructions");
         BMITestRunner.runTests(BlsiLCommutativeExpr.class, args,
+                               "-XX:+IgnoreUnrecognizedVMOptions",
                                "-XX:+UseBMI1Instructions");
     }
 
--- a/hotspot/test/compiler/intrinsics/bmi/TestBlsmskI.java	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/test/compiler/intrinsics/bmi/TestBlsmskI.java	Thu Oct 30 22:52:13 2014 -0700
@@ -41,14 +41,14 @@
 
     public static void main(String args[]) throws Throwable {
         if (!CPUInfo.hasFeature("bmi1")) {
-            System.out.println("CPU does not support bmi1 feature. " +
-                               "Test skipped.");
-            return;
+            System.out.println("INFO: CPU does not support bmi1 feature.");
         }
 
         BMITestRunner.runTests(BlsmskIExpr.class, args,
+                               "-XX:+IgnoreUnrecognizedVMOptions",
                                "-XX:+UseBMI1Instructions");
         BMITestRunner.runTests(BlsmskICommutativeExpr.class, args,
+                               "-XX:+IgnoreUnrecognizedVMOptions",
                                "-XX:+UseBMI1Instructions");
     }
 
--- a/hotspot/test/compiler/intrinsics/bmi/TestBlsmskL.java	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/test/compiler/intrinsics/bmi/TestBlsmskL.java	Thu Oct 30 22:52:13 2014 -0700
@@ -41,14 +41,14 @@
 
     public static void main(String args[]) throws Throwable {
         if (!CPUInfo.hasFeature("bmi1")) {
-            System.out.println("CPU does not support bmi1 feature. " +
-                               "Test skipped.");
-            return;
+            System.out.println("INFO: CPU does not support bmi1 feature.");
         }
 
         BMITestRunner.runTests(BlsmskLExpr.class, args,
+                               "-XX:+IgnoreUnrecognizedVMOptions",
                                "-XX:+UseBMI1Instructions");
         BMITestRunner.runTests(BlsmskLCommutativeExpr.class, args,
+                               "-XX:+IgnoreUnrecognizedVMOptions",
                                "-XX:+UseBMI1Instructions");
     }
 
--- a/hotspot/test/compiler/intrinsics/bmi/TestBlsrI.java	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/test/compiler/intrinsics/bmi/TestBlsrI.java	Thu Oct 30 22:52:13 2014 -0700
@@ -41,14 +41,14 @@
 
     public static void main(String args[]) throws Throwable {
         if (!CPUInfo.hasFeature("bmi1")) {
-            System.out.println("CPU does not support bmi1 feature. " +
-                               "Test skipped.");
-            return;
+            System.out.println("INFO: CPU does not support bmi1 feature.");
         }
 
         BMITestRunner.runTests(BlsrIExpr.class, args,
+                               "-XX:+IgnoreUnrecognizedVMOptions",
                                "-XX:+UseBMI1Instructions");
         BMITestRunner.runTests(BlsrICommutativeExpr.class, args,
+                               "-XX:+IgnoreUnrecognizedVMOptions",
                                "-XX:+UseBMI1Instructions");
     }
 
--- a/hotspot/test/compiler/intrinsics/bmi/TestBlsrL.java	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/test/compiler/intrinsics/bmi/TestBlsrL.java	Thu Oct 30 22:52:13 2014 -0700
@@ -41,14 +41,14 @@
 
     public static void main(String args[]) throws Throwable {
         if (!CPUInfo.hasFeature("bmi1")) {
-            System.out.println("CPU does not support bmi1 feature. " +
-                               "Test skipped.");
-            return;
+            System.out.println("INFO: CPU does not support bmi1 feature.");
         }
 
         BMITestRunner.runTests(BlsrLExpr.class, args,
+                               "-XX:+IgnoreUnrecognizedVMOptions",
                                "-XX:+UseBMI1Instructions");
         BMITestRunner.runTests(BlsrLCommutativeExpr.class, args,
+                               "-XX:+IgnoreUnrecognizedVMOptions",
                                "-XX:+UseBMI1Instructions");
     }
 
--- a/hotspot/test/compiler/intrinsics/bmi/TestLzcntI.java	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/test/compiler/intrinsics/bmi/TestLzcntI.java	Thu Oct 30 22:52:13 2014 -0700
@@ -41,12 +41,11 @@
 
     public static void main(String args[]) throws Throwable {
         if (!CPUInfo.hasFeature("lzcnt")) {
-            System.out.println("CPU does not support lzcnt feature. " +
-                               "Test skipped.");
-            return;
+            System.out.println("INFO: CPU does not support lzcnt feature.");
         }
 
         BMITestRunner.runTests(LzcntIExpr.class, args,
+                               "-XX:+IgnoreUnrecognizedVMOptions",
                                "-XX:+UseCountLeadingZerosInstruction");
     }
 
--- a/hotspot/test/compiler/intrinsics/bmi/TestLzcntL.java	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/test/compiler/intrinsics/bmi/TestLzcntL.java	Thu Oct 30 22:52:13 2014 -0700
@@ -41,12 +41,11 @@
 
     public static void main(String args[]) throws Throwable {
         if (!CPUInfo.hasFeature("lzcnt")) {
-            System.out.println("CPU does not support lzcnt feature. " +
-                               "Test skipped.");
-            return;
+            System.out.println("INFO: CPU does not support lzcnt feature.");
         }
 
         BMITestRunner.runTests(LzcntLExpr.class, args,
+                               "-XX:+IgnoreUnrecognizedVMOptions",
                                "-XX:+UseCountLeadingZerosInstruction");
     }
 
--- a/hotspot/test/compiler/intrinsics/bmi/TestTzcntI.java	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/test/compiler/intrinsics/bmi/TestTzcntI.java	Thu Oct 30 22:52:13 2014 -0700
@@ -41,12 +41,11 @@
 
     public static void main(String args[]) throws Throwable {
         if (!CPUInfo.hasFeature("bmi1")) {
-            System.out.println("CPU does not support bmi1 feature. " +
-                               "Test skipped.");
-            return;
+            System.out.println("INFO: CPU does not support bmi1 feature.");
         }
 
         BMITestRunner.runTests(TzcntIExpr.class, args,
+                               "-XX:+IgnoreUnrecognizedVMOptions",
                                "-XX:+UseCountTrailingZerosInstruction");
     }
 
--- a/hotspot/test/compiler/intrinsics/bmi/TestTzcntL.java	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/test/compiler/intrinsics/bmi/TestTzcntL.java	Thu Oct 30 22:52:13 2014 -0700
@@ -41,12 +41,11 @@
 
     public static void main(String args[]) throws Throwable {
         if (!CPUInfo.hasFeature("bmi1")) {
-            System.out.println("CPU does not support bmi1 feature. " +
-                               "Test skipped.");
-            return;
+            System.out.println("INFO: CPU does not support bmi1 feature.");
         }
 
         BMITestRunner.runTests(TzcntLExpr.class, args,
+                               "-XX:+IgnoreUnrecognizedVMOptions",
                                "-XX:+UseCountTrailingZerosInstruction");
     }
 
--- a/hotspot/test/compiler/startup/SmallCodeCacheStartup.java	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/test/compiler/startup/SmallCodeCacheStartup.java	Thu Oct 30 22:52:13 2014 -0700
@@ -27,10 +27,20 @@
  * @summary Test ensures that there is no crash if there is not enough ReservedCodeacacheSize
  *          to initialize all compiler threads. The option -Xcomp gives the VM more time to
  *          to trigger the old bug.
- * @run main/othervm -XX:ReservedCodeCacheSize=3m -XX:CICompilerCount=64 -Xcomp SmallCodeCacheStartup
+ * @library /testlibrary
  */
+import com.oracle.java.testlibrary.*;
+
 public class SmallCodeCacheStartup {
   public static void main(String[] args) throws Exception {
+    try {
+      ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:ReservedCodeCacheSize=3m",
+                                                                "-XX:CICompilerCount=64",
+                                                                "-Xcomp",
+                                                                "SmallCodeCacheStartup");
+      pb.start();
+    } catch (VirtualMachineError e) {}
+
     System.out.println("TEST PASSED");
   }
 }
--- a/hotspot/test/compiler/whitebox/CompilerWhiteBoxTest.java	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/test/compiler/whitebox/CompilerWhiteBoxTest.java	Thu Oct 30 22:52:13 2014 -0700
@@ -73,8 +73,6 @@
     protected static final int THRESHOLD;
     /** invocation count to trigger OSR compilation */
     protected static final long BACKEDGE_THRESHOLD;
-    /** invocation count to warm up method before triggering OSR compilation */
-    protected static final long OSR_WARMUP = 2000;
     /** Value of {@code java.vm.info} (interpreted|mixed|comp mode) */
     protected static final String MODE = System.getProperty("java.vm.info");
 
@@ -197,7 +195,6 @@
      *                          is compiled, or if {@linkplain #method} has zero
      *                          compilation level.
      */
-
     protected final void checkNotCompiled(int compLevel) {
         if (WHITE_BOX.isMethodQueuedForCompilation(method)) {
             throw new RuntimeException(method + " must not be in queue");
@@ -218,24 +215,30 @@
      *                          compilation level.
      */
     protected final void checkNotCompiled() {
-        if (WHITE_BOX.isMethodCompiled(method, false)) {
-            throw new RuntimeException(method + " must be not compiled");
-        }
-        if (WHITE_BOX.getMethodCompilationLevel(method, false) != 0) {
-            throw new RuntimeException(method + " comp_level must be == 0");
-        }
-        checkNotOsrCompiled();
+        checkNotCompiled(true);
+        checkNotCompiled(false);
     }
 
-    protected final void checkNotOsrCompiled() {
+    /**
+     * Checks, that {@linkplain #method} is not (OSR-)compiled.
+     *
+     * @param isOsr Check for OSR compilation if true
+     * @throws RuntimeException if {@linkplain #method} is in compiler queue or
+     *                          is compiled, or if {@linkplain #method} has zero
+     *                          compilation level.
+     */
+    protected final void checkNotCompiled(boolean isOsr) {
+        waitBackgroundCompilation();
         if (WHITE_BOX.isMethodQueuedForCompilation(method)) {
             throw new RuntimeException(method + " must not be in queue");
         }
-        if (WHITE_BOX.isMethodCompiled(method, true)) {
-            throw new RuntimeException(method + " must be not osr_compiled");
+        if (WHITE_BOX.isMethodCompiled(method, isOsr)) {
+            throw new RuntimeException(method + " must not be " +
+                                       (isOsr ? "osr_" : "") + "compiled");
         }
-        if (WHITE_BOX.getMethodCompilationLevel(method, true) != 0) {
-            throw new RuntimeException(method + " osr_comp_level must be == 0");
+        if (WHITE_BOX.getMethodCompilationLevel(method, isOsr) != 0) {
+            throw new RuntimeException(method + (isOsr ? " osr_" : " ") +
+                                       "comp_level must be == 0");
         }
     }
 
@@ -498,8 +501,7 @@
                 = new Callable<Integer>() {
             @Override
             public Integer call() throws Exception {
-                int result = warmup(OSR_CONSTRUCTOR);
-                return result + new Helper(null, CompilerWhiteBoxTest.BACKEDGE_THRESHOLD).hashCode();
+                return new Helper(null, CompilerWhiteBoxTest.BACKEDGE_THRESHOLD).hashCode();
             }
         };
 
@@ -509,8 +511,7 @@
 
             @Override
             public Integer call() throws Exception {
-                int result = warmup(OSR_METHOD);
-                return result + helper.osrMethod(CompilerWhiteBoxTest.BACKEDGE_THRESHOLD);
+                return helper.osrMethod(CompilerWhiteBoxTest.BACKEDGE_THRESHOLD);
             }
         };
 
@@ -518,66 +519,10 @@
                 = new Callable<Integer>() {
             @Override
             public Integer call() throws Exception {
-                int result = warmup(OSR_STATIC);
-                return result + osrStaticMethod(CompilerWhiteBoxTest.BACKEDGE_THRESHOLD);
+                return osrStaticMethod(CompilerWhiteBoxTest.BACKEDGE_THRESHOLD);
             }
         };
 
-        /**
-         * Deoptimizes all non-osr versions of the given executable after
-         * compilation finished.
-         *
-         * @param e Executable
-         * @throws Exception
-         */
-        private static void waitAndDeoptimize(Executable e) throws Exception {
-            CompilerWhiteBoxTest.waitBackgroundCompilation(e);
-            if (WhiteBox.getWhiteBox().isMethodQueuedForCompilation(e)) {
-                throw new RuntimeException(e + " must not be in queue");
-            }
-            // Deoptimize non-osr versions of executable
-            WhiteBox.getWhiteBox().deoptimizeMethod(e, false);
-        }
-
-        /**
-         * Executes the method multiple times to make sure we have
-         * enough profiling information before triggering an OSR
-         * compilation. Otherwise the C2 compiler may add uncommon traps.
-         *
-         * @param m Method to be executed
-         * @return Number of times the method was executed
-         * @throws Exception
-         */
-        private static int warmup(Method m) throws Exception {
-            Helper helper = new Helper();
-            int result = 0;
-            for (long i = 0; i < CompilerWhiteBoxTest.OSR_WARMUP; ++i) {
-                result += (int)m.invoke(helper, 1);
-            }
-            // Deoptimize non-osr versions
-            waitAndDeoptimize(m);
-            return result;
-        }
-
-        /**
-         * Executes the constructor multiple times to make sure we
-         * have enough profiling information before triggering an OSR
-         * compilation. Otherwise the C2 compiler may add uncommon traps.
-         *
-         * @param c Constructor to be executed
-         * @return Number of times the constructor was executed
-         * @throws Exception
-         */
-        private static int warmup(Constructor c) throws Exception {
-            int result = 0;
-            for (long i = 0; i < CompilerWhiteBoxTest.OSR_WARMUP; ++i) {
-                result += c.newInstance(null, 1).hashCode();
-            }
-            // Deoptimize non-osr versions
-            waitAndDeoptimize(c);
-            return result;
-        }
-
         private static final Constructor CONSTRUCTOR;
         private static final Constructor OSR_CONSTRUCTOR;
         private static final Method METHOD;
@@ -622,16 +567,83 @@
             return 42;
         }
 
-        private static int osrStaticMethod(long limit) {
+        /**
+         * Deoptimizes all non-osr versions of the given executable after
+         * compilation finished.
+         *
+         * @param e Executable
+         * @throws Exception
+         */
+        private static void waitAndDeoptimize(Executable e) {
+            CompilerWhiteBoxTest.waitBackgroundCompilation(e);
+            if (WhiteBox.getWhiteBox().isMethodQueuedForCompilation(e)) {
+                throw new RuntimeException(e + " must not be in queue");
+            }
+            // Deoptimize non-osr versions of executable
+            WhiteBox.getWhiteBox().deoptimizeMethod(e, false);
+        }
+
+        /**
+         * Executes the method multiple times to make sure we have
+         * enough profiling information before triggering an OSR
+         * compilation. Otherwise the C2 compiler may add uncommon traps.
+         *
+         * @param m Method to be executed
+         * @return Number of times the method was executed
+         * @throws Exception
+         */
+        private static int warmup(Method m) throws Exception {
+            waitAndDeoptimize(m);
+            Helper helper = new Helper();
             int result = 0;
+            for (long i = 0; i < CompilerWhiteBoxTest.THRESHOLD; ++i) {
+                result += (int)m.invoke(helper, 1);
+            }
+            // Wait to make sure OSR compilation is not blocked by
+            // non-OSR compilation in the compile queue
+            CompilerWhiteBoxTest.waitBackgroundCompilation(m);
+            return result;
+        }
+
+        /**
+         * Executes the constructor multiple times to make sure we
+         * have enough profiling information before triggering an OSR
+         * compilation. Otherwise the C2 compiler may add uncommon traps.
+         *
+         * @param c Constructor to be executed
+         * @return Number of times the constructor was executed
+         * @throws Exception
+         */
+        private static int warmup(Constructor c) throws Exception {
+            waitAndDeoptimize(c);
+            int result = 0;
+            for (long i = 0; i < CompilerWhiteBoxTest.THRESHOLD; ++i) {
+                result += c.newInstance(null, 1).hashCode();
+            }
+            // Wait to make sure OSR compilation is not blocked by
+            // non-OSR compilation in the compile queue
+            CompilerWhiteBoxTest.waitBackgroundCompilation(c);
+            return result;
+        }
+
+        private static int osrStaticMethod(long limit) throws Exception {
+            int result = 0;
+            if (limit != 1) {
+                result = warmup(OSR_STATIC);
+            }
+            // Trigger osr compilation
             for (long i = 0; i < limit; ++i) {
                 result += staticMethod();
             }
             return result;
         }
 
-        private int osrMethod(long limit) {
+        private int osrMethod(long limit) throws Exception {
             int result = 0;
+            if (limit != 1) {
+                result = warmup(OSR_METHOD);
+            }
+            // Trigger osr compilation
             for (long i = 0; i < limit; ++i) {
                 result += method();
             }
@@ -646,8 +658,12 @@
         }
 
         // for OSR constructor test case
-        private Helper(Object o, long limit) {
+        private Helper(Object o, long limit) throws Exception {
             int result = 0;
+            if (limit != 1) {
+                result = warmup(OSR_CONSTRUCTOR);
+            }
+            // Trigger osr compilation
             for (long i = 0; i < limit; ++i) {
                 result += method();
             }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/whitebox/DeoptimizeMultipleOSRTest.java	Thu Oct 30 22:52:13 2014 -0700
@@ -0,0 +1,95 @@
+/*
+ * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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.
+ */
+
+import sun.hotspot.WhiteBox;
+import java.lang.reflect.Executable;
+import java.lang.reflect.Method;
+
+/*
+ * @test DeoptimizeMultipleOSRTest
+ * @bug 8061817
+ * @library /testlibrary /testlibrary/whitebox
+ * @build DeoptimizeMultipleOSRTest
+ * @run main ClassFileInstaller sun.hotspot.WhiteBox
+ *                              sun.hotspot.WhiteBox$WhiteBoxPermission
+ * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -XX:CompileCommand=compileonly,DeoptimizeMultipleOSRTest::triggerOSR DeoptimizeMultipleOSRTest
+ * @summary testing of WB::deoptimizeMethod()
+ */
+public class DeoptimizeMultipleOSRTest {
+    private static final WhiteBox WHITE_BOX = WhiteBox.getWhiteBox();
+    private static final long BACKEDGE_THRESHOLD = 150000;
+    private Method method;
+    private int counter = 0;
+
+    public static void main(String[] args) throws Exception {
+        DeoptimizeMultipleOSRTest test = new DeoptimizeMultipleOSRTest();
+        test.test();
+    }
+
+    /**
+     * Triggers two different OSR compilations for the same method and
+     * checks if WhiteBox.deoptimizeMethod() deoptimizes both.
+     *
+     * @throws Exception
+     */
+    public void test() throws Exception {
+        method = DeoptimizeMultipleOSRTest.class.getDeclaredMethod("triggerOSR", boolean.class, long.class);
+        // Trigger two OSR compiled versions
+        triggerOSR(true, BACKEDGE_THRESHOLD);
+        triggerOSR(false, BACKEDGE_THRESHOLD);
+        // Wait for compilation
+        CompilerWhiteBoxTest.waitBackgroundCompilation(method);
+        // Deoptimize
+        WHITE_BOX.deoptimizeMethod(method, true);
+        if (WHITE_BOX.isMethodCompiled(method, true)) {
+            throw new AssertionError("Not all OSR compiled versions were deoptimized");
+        }
+    }
+
+    /**
+     * Triggers OSR compilations by executing loops.
+     *
+     * @param first Determines which loop to execute
+     * @param limit The number of loop iterations
+     */
+    public void triggerOSR(boolean first, long limit) {
+        if (limit != 1) {
+            // Warmup method to avoid uncommon traps
+            for (int i = 0; i < limit; ++i) {
+                triggerOSR(first, 1);
+            }
+            CompilerWhiteBoxTest.waitBackgroundCompilation(method);
+        }
+        if (first) {
+            // Trigger OSR compilation 1
+            for (int i = 0; i < limit; ++i) {
+                counter++;
+            }
+        } else {
+            // Trigger OSR compilation 2
+            for (int i = 0; i < limit; ++i) {
+                counter++;
+            }
+        }
+    }
+}
--- a/hotspot/test/compiler/whitebox/MakeMethodNotCompilableTest.java	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/test/compiler/whitebox/MakeMethodNotCompilableTest.java	Thu Oct 30 22:52:13 2014 -0700
@@ -132,14 +132,15 @@
             throw new RuntimeException(method
                     + " is not compilable after clearMethodState()");
         }
-
+        // Make method not (OSR-)compilable (depending on testCase.isOsr())
         makeNotCompilable();
         if (isCompilable()) {
             throw new RuntimeException(method + " must be not compilable");
         }
-
+        // Try to (OSR-)compile method
         compile();
-        checkNotOsrCompiled();
+        // Method should not be (OSR-)compiled
+        checkNotCompiled(testCase.isOsr());
         if (isCompilable()) {
             throw new RuntimeException(method + " must be not compilable");
         }
--- a/hotspot/test/gc/g1/TestHumongousCodeCacheRoots.java	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/test/gc/g1/TestHumongousCodeCacheRoots.java	Thu Oct 30 22:52:13 2014 -0700
@@ -135,7 +135,6 @@
       "-XX:+UnlockDiagnosticVMOptions",
       "-XX:InitiatingHeapOccupancyPercent=1", // strong code root marking
       "-XX:+G1VerifyHeapRegionCodeRoots", "-XX:+VerifyAfterGC", // make sure that verification is run
-      "-XX:NmethodSweepFraction=1", "-XX:NmethodSweepCheckInterval=1",  // make the code cache sweep more predictable
     };
     runTest("-client", baseArguments);
     runTest("-server", baseArguments);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/RedefineTests/RedefineAnnotations.java	Thu Oct 30 22:52:13 2014 -0700
@@ -0,0 +1,410 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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
+ * @library /testlibrary
+ * @summary Test that type annotations are retained after a retransform
+ * @run main RedefineAnnotations buildagent
+ * @run main/othervm -javaagent:redefineagent.jar RedefineAnnotations
+ */
+
+import static com.oracle.java.testlibrary.Asserts.assertTrue;
+import java.io.FileNotFoundException;
+import java.io.PrintWriter;
+import java.lang.NoSuchFieldException;
+import java.lang.NoSuchMethodException;
+import java.lang.RuntimeException;
+import java.lang.annotation.Annotation;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import java.lang.instrument.ClassFileTransformer;
+import java.lang.instrument.IllegalClassFormatException;
+import java.lang.instrument.Instrumentation;
+import java.lang.instrument.UnmodifiableClassException;
+import java.lang.reflect.AnnotatedArrayType;
+import java.lang.reflect.AnnotatedParameterizedType;
+import java.lang.reflect.AnnotatedType;
+import java.lang.reflect.AnnotatedWildcardType;
+import java.lang.reflect.Executable;
+import java.lang.reflect.TypeVariable;
+import java.security.ProtectionDomain;
+import java.util.Arrays;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import jdk.internal.org.objectweb.asm.ClassReader;
+import jdk.internal.org.objectweb.asm.ClassVisitor;
+import jdk.internal.org.objectweb.asm.ClassWriter;
+import jdk.internal.org.objectweb.asm.FieldVisitor;
+import static jdk.internal.org.objectweb.asm.Opcodes.ASM5;
+
+@Retention(RetentionPolicy.RUNTIME)
+@Target(ElementType.TYPE_USE)
+@interface TestAnn {
+    String site();
+}
+
+public class RedefineAnnotations {
+    static Instrumentation inst;
+    public static void premain(String agentArgs, Instrumentation inst) {
+        RedefineAnnotations.inst = inst;
+    }
+
+    static class Transformer implements ClassFileTransformer {
+
+        public byte[] asm(ClassLoader loader, String className,
+                Class<?> classBeingRedefined,
+                ProtectionDomain protectionDomain, byte[] classfileBuffer)
+            throws IllegalClassFormatException {
+
+            ClassWriter cw = new ClassWriter(0);
+            ClassVisitor cv = new ReAddDummyFieldsClassVisitor(ASM5, cw) { };
+            ClassReader cr = new ClassReader(classfileBuffer);
+            cr.accept(cv, 0);
+            return cw.toByteArray();
+        }
+
+        public class ReAddDummyFieldsClassVisitor extends ClassVisitor {
+
+            LinkedList<F> fields = new LinkedList<>();
+
+            public ReAddDummyFieldsClassVisitor(int api, ClassVisitor cv) {
+                super(api, cv);
+            }
+
+            @Override public FieldVisitor visitField(int access, String name,
+                    String desc, String signature, Object value) {
+                if (name.startsWith("dummy")) {
+                    // Remove dummy field
+                    fields.addLast(new F(access, name, desc, signature, value));
+                    return null;
+                }
+                return cv.visitField(access, name, desc, signature, value);
+            }
+
+            @Override public void visitEnd() {
+                F f;
+                while ((f = fields.pollFirst()) != null) {
+                    // Re-add dummy fields
+                    cv.visitField(f.access, f.name, f.desc, f.signature, f.value);
+                }
+            }
+
+            private class F {
+                private int access;
+                private String name;
+                private String desc;
+                private String signature;
+                private Object value;
+                F(int access, String name, String desc, String signature, Object value) {
+                    this.access = access;
+                    this.name = name;
+                    this.desc = desc;
+                    this.signature = signature;
+                    this.value = value;
+                }
+            }
+        }
+
+        @Override public byte[] transform(ClassLoader loader, String className,
+                Class<?> classBeingRedefined,
+                ProtectionDomain protectionDomain, byte[] classfileBuffer)
+            throws IllegalClassFormatException {
+
+            if (className.contains("TypeAnnotatedTestClass")) {
+                try {
+                    // Here we remove and re-add the dummy fields. This shuffles the constant pool
+                    return asm(loader, className, classBeingRedefined, protectionDomain, classfileBuffer);
+                } catch (Throwable e) {
+                    // The retransform native code that called this method does not propagate
+                    // exceptions. Instead of getting an uninformative generic error, catch
+                    // problems here and print it, then exit.
+                    e.printStackTrace();
+                    System.exit(1);
+                }
+            }
+            return null;
+        }
+    }
+
+    private static void buildAgent() {
+        try {
+            ClassFileInstaller.main("RedefineAnnotations");
+        } catch (Exception e) {
+            throw new RuntimeException("Could not write agent classfile", e);
+        }
+
+        try {
+            PrintWriter pw = new PrintWriter("MANIFEST.MF");
+            pw.println("Premain-Class: RedefineAnnotations");
+            pw.println("Agent-Class: RedefineAnnotations");
+            pw.println("Can-Retransform-Classes: true");
+            pw.close();
+        } catch (FileNotFoundException e) {
+            throw new RuntimeException("Could not write manifest file for the agent", e);
+        }
+
+        sun.tools.jar.Main jarTool = new sun.tools.jar.Main(System.out, System.err, "jar");
+        if (!jarTool.run(new String[] { "-cmf", "MANIFEST.MF", "redefineagent.jar", "RedefineAnnotations.class" })) {
+            throw new RuntimeException("Could not write the agent jar file");
+        }
+    }
+
+    public static void main(String argv[]) throws NoSuchFieldException, NoSuchMethodException {
+        if (argv.length == 1 && argv[0].equals("buildagent")) {
+            buildAgent();
+            return;
+        }
+
+        if (inst == null) {
+            throw new RuntimeException("Instrumentation object was null");
+        }
+
+        RedefineAnnotations test = new RedefineAnnotations();
+        test.testTransformAndVerify();
+    }
+
+    // Class type annotations
+    private Annotation classTypeParameterTA;
+    private Annotation extendsTA;
+    private Annotation implementsTA;
+
+    // Field type annotations
+    private Annotation fieldTA;
+    private Annotation innerTA;
+    private Annotation[] arrayTA = new Annotation[4];
+    private Annotation[] mapTA = new Annotation[5];
+
+    // Method type annotations
+    private Annotation returnTA, methodTypeParameterTA, formalParameterTA, throwsTA;
+
+    private void testTransformAndVerify()
+        throws NoSuchFieldException, NoSuchMethodException {
+
+        Class<TypeAnnotatedTestClass> c = TypeAnnotatedTestClass.class;
+        Class<?> myClass = c;
+
+        /*
+         * Verify that the expected annotations are where they should be before transform.
+         */
+        verifyClassTypeAnnotations(c);
+        verifyFieldTypeAnnotations(c);
+        verifyMethodTypeAnnotations(c);
+
+        try {
+            inst.addTransformer(new Transformer(), true);
+            inst.retransformClasses(myClass);
+        } catch (UnmodifiableClassException e) {
+            throw new RuntimeException(e);
+        }
+
+        /*
+         * Verify that the expected annotations are where they should be after transform.
+         * Also verify that before and after are equal.
+         */
+        verifyClassTypeAnnotations(c);
+        verifyFieldTypeAnnotations(c);
+        verifyMethodTypeAnnotations(c);
+    }
+
+    private void verifyClassTypeAnnotations(Class c) {
+        Annotation anno;
+
+        anno = c.getTypeParameters()[0].getAnnotations()[0];
+        verifyTestAnn(classTypeParameterTA, anno, "classTypeParameter");
+        classTypeParameterTA = anno;
+
+        anno = c.getAnnotatedSuperclass().getAnnotations()[0];
+        verifyTestAnn(extendsTA, anno, "extends");
+        extendsTA = anno;
+
+        anno = c.getAnnotatedInterfaces()[0].getAnnotations()[0];
+        verifyTestAnn(implementsTA, anno, "implements");
+        implementsTA = anno;
+    }
+
+    private void verifyFieldTypeAnnotations(Class c)
+        throws NoSuchFieldException, NoSuchMethodException {
+
+        verifyBasicFieldTypeAnnotations(c);
+        verifyInnerFieldTypeAnnotations(c);
+        verifyArrayFieldTypeAnnotations(c);
+        verifyMapFieldTypeAnnotations(c);
+    }
+
+    private void verifyBasicFieldTypeAnnotations(Class c)
+        throws NoSuchFieldException, NoSuchMethodException {
+
+        Annotation anno = c.getDeclaredField("typeAnnotatedBoolean").getAnnotatedType().getAnnotations()[0];
+        verifyTestAnn(fieldTA, anno, "field");
+        fieldTA = anno;
+    }
+
+    private void verifyInnerFieldTypeAnnotations(Class c)
+        throws NoSuchFieldException, NoSuchMethodException {
+
+        AnnotatedType at = c.getDeclaredField("typeAnnotatedInner").getAnnotatedType();
+        Annotation anno = at.getAnnotations()[0];
+        verifyTestAnn(innerTA, anno, "inner");
+        innerTA = anno;
+    }
+
+    private void verifyArrayFieldTypeAnnotations(Class c)
+        throws NoSuchFieldException, NoSuchMethodException {
+
+        Annotation anno;
+        AnnotatedType at;
+
+        at = c.getDeclaredField("typeAnnotatedArray").getAnnotatedType();
+        anno = at.getAnnotations()[0];
+        verifyTestAnn(arrayTA[0], anno, "array1");
+        arrayTA[0] = anno;
+
+        for (int i = 1; i <= 3; i++) {
+            at = ((AnnotatedArrayType) at).getAnnotatedGenericComponentType();
+            anno = at.getAnnotations()[0];
+            verifyTestAnn(arrayTA[i], anno, "array" + (i + 1));
+            arrayTA[i] = anno;
+        }
+    }
+
+    private void verifyMapFieldTypeAnnotations(Class c)
+        throws NoSuchFieldException, NoSuchMethodException {
+
+        Annotation anno;
+        AnnotatedType atBase;
+        AnnotatedType atParameter;
+        atBase = c.getDeclaredField("typeAnnotatedMap").getAnnotatedType();
+
+        anno = atBase.getAnnotations()[0];
+        verifyTestAnn(mapTA[0], anno, "map1");
+        mapTA[0] = anno;
+
+        atParameter =
+            ((AnnotatedParameterizedType) atBase).
+            getAnnotatedActualTypeArguments()[0];
+        anno = ((AnnotatedWildcardType) atParameter).getAnnotations()[0];
+        verifyTestAnn(mapTA[1], anno, "map2");
+        mapTA[1] = anno;
+
+        anno =
+            ((AnnotatedWildcardType) atParameter).
+            getAnnotatedUpperBounds()[0].getAnnotations()[0];
+        verifyTestAnn(mapTA[2], anno, "map3");
+        mapTA[2] = anno;
+
+        atParameter =
+            ((AnnotatedParameterizedType) atBase).
+            getAnnotatedActualTypeArguments()[1];
+        anno = ((AnnotatedParameterizedType) atParameter).getAnnotations()[0];
+        verifyTestAnn(mapTA[3], anno, "map4");
+        mapTA[3] = anno;
+
+        anno =
+            ((AnnotatedParameterizedType) atParameter).
+            getAnnotatedActualTypeArguments()[0].getAnnotations()[0];
+        verifyTestAnn(mapTA[4], anno, "map5");
+        mapTA[4] = anno;
+    }
+
+    private void verifyMethodTypeAnnotations(Class c)
+        throws NoSuchFieldException, NoSuchMethodException {
+        Annotation anno;
+        Executable typeAnnotatedMethod =
+            c.getDeclaredMethod("typeAnnotatedMethod", TypeAnnotatedTestClass.class);
+
+        anno = typeAnnotatedMethod.getAnnotatedReturnType().getAnnotations()[0];
+        verifyTestAnn(returnTA, anno, "return");
+        returnTA = anno;
+
+        anno = typeAnnotatedMethod.getTypeParameters()[0].getAnnotations()[0];
+        verifyTestAnn(methodTypeParameterTA, anno, "methodTypeParameter");
+        methodTypeParameterTA = anno;
+
+        anno = typeAnnotatedMethod.getAnnotatedParameterTypes()[0].getAnnotations()[0];
+        verifyTestAnn(formalParameterTA, anno, "formalParameter");
+        formalParameterTA = anno;
+
+        anno = typeAnnotatedMethod.getAnnotatedExceptionTypes()[0].getAnnotations()[0];
+        verifyTestAnn(throwsTA, anno, "throws");
+        throwsTA = anno;
+    }
+
+    private static void verifyTestAnn(Annotation verifyAgainst, Annotation anno, String expectedSite) {
+        verifyTestAnnSite(anno, expectedSite);
+
+        // When called before transform verifyAgainst will be null, when called
+        // after transform it will be the annotation from before the transform
+        if (verifyAgainst != null) {
+            assertTrue(anno.equals(verifyAgainst),
+                       "Annotations do not match before and after." +
+                       " Before: \"" + verifyAgainst + "\", After: \"" + anno + "\"");
+        }
+    }
+
+    private static void verifyTestAnnSite(Annotation testAnn, String expectedSite) {
+        String expectedAnn = "@TestAnn(site=" + expectedSite + ")";
+        assertTrue(testAnn.toString().equals(expectedAnn),
+                   "Expected \"" + expectedAnn + "\", got \"" + testAnn + "\"");
+    }
+
+    public static class TypeAnnotatedTestClass <@TestAnn(site="classTypeParameter") S,T>
+            extends @TestAnn(site="extends") Thread
+            implements @TestAnn(site="implements") Runnable {
+
+        public @TestAnn(site="field") boolean typeAnnotatedBoolean;
+
+        public
+            RedefineAnnotations.
+            @TestAnn(site="inner") TypeAnnotatedTestClass
+            typeAnnotatedInner;
+
+        public
+            @TestAnn(site="array4") boolean
+            @TestAnn(site="array1") []
+            @TestAnn(site="array2") []
+            @TestAnn(site="array3") []
+            typeAnnotatedArray;
+
+        public @TestAnn(site="map1") Map
+            <@TestAnn(site="map2") ? extends @TestAnn(site="map3") String,
+            @TestAnn(site="map4")  List<@TestAnn(site="map5")  Object>> typeAnnotatedMap;
+
+        public int dummy1;
+        public int dummy2;
+        public int dummy3;
+
+        @TestAnn(site="return") <@TestAnn(site="methodTypeParameter") U,V> Class
+            typeAnnotatedMethod(@TestAnn(site="formalParameter") TypeAnnotatedTestClass arg)
+            throws @TestAnn(site="throws") ClassNotFoundException {
+
+            @TestAnn(site="local_variable_type") int foo = 0;
+            throw new ClassNotFoundException();
+        }
+
+        public void run() {}
+    }
+}
--- a/hotspot/test/runtime/SharedArchiveFile/LimitSharedSizes.java	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/test/runtime/SharedArchiveFile/LimitSharedSizes.java	Thu Oct 30 22:52:13 2014 -0700
@@ -51,9 +51,12 @@
         // Known issue, JDK-8038422 (assert() on Windows)
         // new SharedSizeTestData("-XX:SharedMiscDataSize", "500k",    "miscellaneous data"),
 
-        // This will cause a VM crash; commenting out for now; see bug JDK-8038268
-        // @ignore JDK-8038268
-        // new SharedSizeTestData("-XX:SharedMiscCodeSize", "20k",     "miscellaneous code"),
+        // Too small of a misc code size should not cause a vm crash.
+        // It should result in the following error message:
+        // The shared miscellaneous code space is not large enough
+        // to preload requested classes. Use -XX:SharedMiscCodeSize=
+        // to increase the initial size of shared miscellaneous code space.
+        new SharedSizeTestData("-XX:SharedMiscCodeSize", "20k",     "miscellaneous code"),
 
         // these values are larger than default ones, but should
         // be acceptable and not cause failure
--- a/hotspot/test/runtime/lambda-features/InvokespecialInterface.java	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/test/runtime/lambda-features/InvokespecialInterface.java	Thu Oct 30 22:52:13 2014 -0700
@@ -33,11 +33,12 @@
 import java.util.function.*;
 import java.util.*;
 
+public class InvokespecialInterface {
 interface I {
   default void imethod() { System.out.println("I::imethod"); }
 }
 
-class C implements I {
+static class C implements I {
   public void foo() { I.super.imethod(); }  // invokespecial InterfaceMethod
   public void bar() { I i = this; i.imethod(); } // invokeinterface same
   public void doSomeInvokedynamic() {
@@ -48,7 +49,6 @@
   }
 }
 
-public class InvokespecialInterface {
   public static void main(java.lang.String[] unused) {
      // need to create C and call I::foo()
      C c = new C();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/lambda-features/TestInterfaceInit.java	Thu Oct 30 22:52:13 2014 -0700
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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
+ * @bug 8034275
+ * @summary [JDK 8u40] Test interface initialization: only for interfaces declaring default methods
+ * @run main TestInterfaceInit
+ */
+import java.util.List;
+import java.util.Arrays;
+import java.util.ArrayList;
+
+public class TestInterfaceInit {
+
+   static List<Class<?>> cInitOrder = new ArrayList<>();
+
+   // Declares a default method and initializes
+   interface I {
+       boolean v = TestInterfaceInit.out(I.class);
+        default void x() {}
+   }
+
+   // Declares a default method and initializes
+   interface J extends I {
+       boolean v = TestInterfaceInit.out(J.class);
+       default void x() {}
+   }
+   // No default method, does not initialize
+   interface JN extends J {
+       boolean v = TestInterfaceInit.out(JN.class);
+   }
+
+   // Declares a default method and initializes
+   interface K extends I {
+       boolean v = TestInterfaceInit.out(K.class);
+        default void x() {}
+   }
+
+   // No default method, does not initialize
+   interface KN extends K {
+       boolean v = TestInterfaceInit.out(KN.class);
+   }
+
+   interface L extends JN, KN {
+       boolean v = TestInterfaceInit.out(L.class);
+        default void x() {}
+   }
+
+   public static void main(String[] args) {
+       // Trigger initialization
+       boolean v = L.v;
+
+       List<Class<?>> expectedCInitOrder = Arrays.asList(I.class,J.class,K.class,L.class);
+       if (!cInitOrder.equals(expectedCInitOrder)) {
+         throw new RuntimeException(String.format("Class initialization array %s not equal to expected array %s", cInitOrder, expectedCInitOrder));
+       }
+   }
+
+   static boolean out(Class c) {
+       System.out.println("#: initializing " + c.getName());
+       cInitOrder.add(c);
+       return true;
+   }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/lambda-features/TestInterfaceOrder.java	Thu Oct 30 22:52:13 2014 -0700
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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
+ * @bug 8034275
+ * @summary [JDK 8u40] Test interface initialization order
+ * @run main TestInterfaceOrder
+ */
+
+import java.util.List;
+import java.util.Arrays;
+import java.util.ArrayList;
+
+public class TestInterfaceOrder {
+  static List<Class<?>> cInitOrder = new ArrayList<>();
+
+  public static void main(java.lang.String[] args) {
+    //Trigger initialization
+    C c = new C();
+
+    List<Class<?>> expectedCInitOrder = Arrays.asList(I.class, J.class, A.class, K.class, B.class, L.class, C.class);
+    if (!cInitOrder.equals(expectedCInitOrder)) {
+      throw new RuntimeException(String.format("Class initialization order %s not equal to expected order %s", cInitOrder, expectedCInitOrder));
+    }
+  }
+
+  interface I {
+    boolean v = TestInterfaceOrder.out(I.class);
+   default void i() {}
+  }
+
+  interface J extends I {
+    boolean v = TestInterfaceOrder.out(J.class);
+    default void j() {}
+  }
+
+  static class A implements J {
+    static boolean v = TestInterfaceOrder.out(A.class);
+  }
+
+  interface K extends I {
+    boolean v = TestInterfaceOrder.out(K.class);
+    default void k() {}
+  }
+
+  static class B extends A implements K {
+    static boolean v = TestInterfaceOrder.out(B.class);
+  }
+
+  interface L  {
+    boolean v = TestInterfaceOrder.out(L.class);
+    default void l() {}
+  }
+
+  static class C extends B implements L {
+    static boolean v = TestInterfaceOrder.out(C.class);
+  }
+
+
+   static boolean out(Class c) {
+       System.out.println("#: initializing " + c.getName());
+       cInitOrder.add(c);
+       return true;
+   }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/reflect/ArrayGetIntException.java	Thu Oct 30 22:52:13 2014 -0700
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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
+ * @bug 6191224
+ * @summary (reflect) Misleading detail string in IllegalArgumentException thrown by Array.get<Type>
+ * @run main ArrayGetIntException
+ */
+import java.io.*;
+import java.lang.reflect.Array;
+
+public class ArrayGetIntException {
+    public static void main(String[] args) throws Exception {
+        Object[] objArray = {new Integer(Integer.MAX_VALUE)};
+
+        // this access is legal
+        try {
+            System.out.println(Array.get(objArray, 0));
+            System.out.println("Test #1 PASSES");
+        } catch(Exception e) {
+            failTest("Test #1 FAILS - legal access denied" + e.getMessage());
+        }
+
+        // this access is not legal, but needs to generate the proper exception message
+        try {
+            System.out.println(Array.getInt(objArray, 0));
+            failTest("Test #2 FAILS - no exception");
+        } catch(Exception e) {
+            System.out.println(e);
+            if (e.getMessage().equals("Argument is not an array of primitive type")) {
+                System.out.println("Test #2 PASSES");
+            } else {
+                failTest("Test #2 FAILS - incorrect message: " + e.getMessage());
+            }
+        }
+
+        // this access is not legal, but needs to generate the proper exception message
+        try {
+            System.out.println(Array.getInt(new Object(), 0));
+            failTest("Test #3 FAILS - no exception");
+        } catch(Exception e) {
+            System.out.println(e);
+            if (e.getMessage().equals("Argument is not an array")) {
+                System.out.println("Test #3 PASSES");
+            } else {
+                failTest("Test #3 FAILS - incorrect message: " + e.getMessage());
+            }
+        }
+    }
+
+    private static void failTest(String errStr) {
+        System.out.println(errStr);
+        throw new Error(errStr);
+    }
+}
--- a/hotspot/test/serviceability/dcmd/compiler/CompilerQueueTest.java	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/test/serviceability/dcmd/compiler/CompilerQueueTest.java	Thu Oct 30 22:52:13 2014 -0700
@@ -27,6 +27,7 @@
  * @library ..
  * @build DcmdUtil CompilerQueueTest
  * @run main CompilerQueueTest
+ * @run main/othervm -XX:-TieredCompilation CompilerQueueTest
  * @run main/othervm -Xint CompilerQueueTest
  * @summary Test of diagnostic command Compiler.queue
  */
@@ -87,7 +88,9 @@
     }
 
     private static void validateMethodLine(String str)  throws Exception {
-        String name = str.substring(19);
+        // Skip until package/class name begins. Trim to remove whitespace that
+        // may differ.
+        String name = str.substring(14).trim();
         int sep = name.indexOf("::");
         if (sep == -1) {
             throw new Exception("Failed dcmd queue, didn't find separator :: in: " + name);
--- a/hotspot/test/testlibrary/whitebox/sun/hotspot/WhiteBox.java	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/test/testlibrary/whitebox/sun/hotspot/WhiteBox.java	Thu Oct 30 22:52:13 2014 -0700
@@ -179,6 +179,8 @@
   public native void printRegionInfo(int context);
 
   // VM flags
+  public native boolean isConstantVMFlag(String name);
+  public native boolean isLockedVMFlag(String name);
   public native void    setBooleanVMFlag(String name, boolean value);
   public native void    setIntxVMFlag(String name, long value);
   public native void    setUintxVMFlag(String name, long value);
--- a/hotspot/test/testlibrary_tests/whitebox/vm_flags/BooleanTest.java	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/test/testlibrary_tests/whitebox/vm_flags/BooleanTest.java	Thu Oct 30 22:52:13 2014 -0700
@@ -43,6 +43,7 @@
     private static final Boolean[] TESTS = {true, false, true, true, false};
     private static final String TEST_NAME = "BooleanTest";
     private static final String FLAG_NAME = "PrintCompilation";
+    private static final String FLAG_DEBUG_NAME = "SafepointALot";
     private static final String METHOD = TEST_NAME + "::method";
     private static final String METHOD1 = METHOD + "1";
     private static final String METHOD2 = METHOD + "2";
@@ -54,6 +55,7 @@
                 VmFlagTest.WHITE_BOX::getBooleanVMFlag);
             testFunctional(false);
             testFunctional(true);
+            VmFlagTest.runTest(FLAG_DEBUG_NAME, VmFlagTest.WHITE_BOX::getBooleanVMFlag);
         } else {
             boolean value = Boolean.valueOf(args[0]);
             method1();
--- a/hotspot/test/testlibrary_tests/whitebox/vm_flags/IntxTest.java	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/test/testlibrary_tests/whitebox/vm_flags/IntxTest.java	Thu Oct 30 22:52:13 2014 -0700
@@ -35,6 +35,7 @@
 
 public class IntxTest {
     private static final String FLAG_NAME = "OnStackReplacePercentage";
+    private static final String FLAG_DEBUG_NAME = "InlineFrequencyCount";
     private static final Long[] TESTS = {0L, 100L, -1L,
             (long) Integer.MAX_VALUE, (long) Integer.MIN_VALUE};
 
@@ -42,6 +43,7 @@
         VmFlagTest.runTest(FLAG_NAME, TESTS,
             VmFlagTest.WHITE_BOX::setIntxVMFlag,
             VmFlagTest.WHITE_BOX::getIntxVMFlag);
+        VmFlagTest.runTest(FLAG_DEBUG_NAME, VmFlagTest.WHITE_BOX::getIntxVMFlag);
     }
 }
 
--- a/hotspot/test/testlibrary_tests/whitebox/vm_flags/StringTest.java	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/test/testlibrary_tests/whitebox/vm_flags/StringTest.java	Thu Oct 30 22:52:13 2014 -0700
@@ -35,12 +35,14 @@
 
 public class StringTest {
     private static final String FLAG_NAME = "CompileOnly";
+    private static final String FLAG_DEBUG_NAME = "SuppressErrorAt";
     private static final String[] TESTS = {"StringTest::*", ""};
 
     public static void main(String[] args) throws Exception {
         VmFlagTest.runTest(FLAG_NAME, TESTS,
             VmFlagTest.WHITE_BOX::setStringVMFlag,
             VmFlagTest.WHITE_BOX::getStringVMFlag);
+        VmFlagTest.runTest(FLAG_DEBUG_NAME, VmFlagTest.WHITE_BOX::getStringVMFlag);
     }
 }
 
--- a/hotspot/test/testlibrary_tests/whitebox/vm_flags/UintxTest.java	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/test/testlibrary_tests/whitebox/vm_flags/UintxTest.java	Thu Oct 30 22:52:13 2014 -0700
@@ -36,6 +36,7 @@
 
 public class UintxTest {
     private static final String FLAG_NAME = "VerifyGCStartAt";
+    private static final String FLAG_DEBUG_NAME = "CodeCacheMinimumUseSpace";
     private static final Long[] TESTS = {0L, 100L, (long) Integer.MAX_VALUE,
         (1L << 32L) - 1L, 1L << 32L};
     private static final Long[] EXPECTED_64 = TESTS;
@@ -47,6 +48,7 @@
             Platform.is64bit() ? EXPECTED_64 : EXPECTED_32,
             VmFlagTest.WHITE_BOX::setUintxVMFlag,
             VmFlagTest.WHITE_BOX::getUintxVMFlag);
+        VmFlagTest.runTest(FLAG_DEBUG_NAME, VmFlagTest.WHITE_BOX::getUintxVMFlag);
     }
 }
 
--- a/hotspot/test/testlibrary_tests/whitebox/vm_flags/VmFlagTest.java	Wed Jul 05 20:06:12 2017 +0200
+++ b/hotspot/test/testlibrary_tests/whitebox/vm_flags/VmFlagTest.java	Thu Oct 30 22:52:13 2014 -0700
@@ -37,16 +37,18 @@
     private final BiConsumer<T, T> test;
     private final BiConsumer<String, T> set;
     private final Function<String, T> get;
+    private final boolean isPositive;
 
     protected VmFlagTest(String flagName, BiConsumer<String, T> set,
             Function<String, T> get, boolean isPositive) {
         this.flagName = flagName;
         this.set = set;
         this.get = get;
+        this.isPositive = isPositive;
         if (isPositive) {
-            test = this::testPositive;
+            test = this::testWritePositive;
         } else {
-            test = this::testNegative;
+            test = this::testWriteNegative;
         }
     }
 
@@ -63,6 +65,10 @@
         runTest(existentFlag, tests, tests, set, get);
     }
 
+    protected static <T> void runTest(String existentFlag, Function<String, T> get) {
+        runTest(existentFlag, null, null, null, get);
+    }
+
     protected static <T> void runTest(String existentFlag, T[] tests,
             T[] results, BiConsumer<String, T> set, Function<String, T> get) {
         if (existentFlag != null) {
@@ -72,13 +78,23 @@
     }
 
     public final void test(T[] tests, T[] results) {
-        Asserts.assertEQ(tests.length, results.length, "[TESTBUG] tests.length != results.length");
-        for (int i = 0, n = tests.length ; i < n; ++i) {
-            test.accept(tests[i], results[i]);
+        if (isPositive) {
+            testRead();
+        }
+        if (tests != null) {
+            Asserts.assertEQ(tests.length, results.length, "[TESTBUG] tests.length != results.length");
+            for (int i = 0, n = tests.length ; i < n; ++i) {
+                test.accept(tests[i], results[i]);
+            }
         }
     }
 
     protected String getVMOptionAsString() {
+        if (WHITE_BOX.isConstantVMFlag(flagName) || WHITE_BOX.isLockedVMFlag(flagName)) {
+          // JMM cannot access debug flags in product builds or locked flags,
+          // use whitebox methods to get such flags value.
+          return asString(getValue());
+        }
         HotSpotDiagnosticMXBean diagnostic
                 = ManagementFactoryHelper.getDiagnosticMXBean();
         VMOption tmp;
@@ -90,18 +106,24 @@
         return tmp == null ? null : tmp.getValue();
     }
 
-    private void testPositive(T value, T expected) {
-        String oldValue = getVMOptionAsString();
-        Asserts.assertEQ(oldValue, asString(getValue()));
-        Asserts.assertEQ(oldValue, asString(WHITE_BOX.getVMFlag(flagName)));
-        setNewValue(value);
-        String newValue = getVMOptionAsString();
-        Asserts.assertEQ(newValue, asString(expected));
-        Asserts.assertEQ(newValue, asString(getValue()));
-        Asserts.assertEQ(newValue, asString(WHITE_BOX.getVMFlag(flagName)));
+    private String testRead() {
+        String value = getVMOptionAsString();
+        Asserts.assertNotNull(value);
+        Asserts.assertEQ(value, asString(getValue()));
+        Asserts.assertEQ(value, asString(WHITE_BOX.getVMFlag(flagName)));
+        return value;
     }
 
-    private void testNegative(T value, T expected) {
+    private void testWritePositive(T value, T expected) {
+        setNewValue(value);
+        String newValue = testRead();
+        Asserts.assertEQ(newValue, asString(expected));
+    }
+
+    private void testWriteNegative(T value, T expected) {
+        // Should always return false for non-existing flags
+        Asserts.assertFalse(WHITE_BOX.isConstantVMFlag(flagName));
+        Asserts.assertFalse(WHITE_BOX.isLockedVMFlag(flagName));
         String oldValue = getVMOptionAsString();
         Asserts.assertEQ(oldValue, asString(getValue()));
         Asserts.assertEQ(oldValue, asString(WHITE_BOX.getVMFlag(flagName)));
@@ -114,4 +136,3 @@
         return value == null ? null : "" + value;
     }
 }
-