Merge
authorjwilhelm
Fri, 13 Jan 2017 18:26:34 +0100
changeset 43447 c1a7412d597d
parent 43040 ab2c8b03c328 (current diff)
parent 43445 5d868b60af95 (diff)
child 43448 45b30ca7f9b8
Merge
hotspot/test/compiler/c2/cr7200264/Test7200264.sh
--- a/hotspot/make/ide/CreateVSProject.gmk	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/make/ide/CreateVSProject.gmk	Fri Jan 13 18:26:34 2017 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -121,7 +121,7 @@
       -buildBase $(call FixPath, $(IDE_OUTPUTDIR)/vs-output) \
       -buildSpace $(call FixPath, $(IDE_OUTPUTDIR)) \
       -makeBinary $(call FixPath, $(MAKE)) \
-      -makeOutput $(call FixPath, $(HOTSPOT_OUTPUTDIR)/variant-%f/libjvm) \
+      -makeOutput $(call FixPath, $(JDK_OUTPUTDIR)/bin/server) \
       -absoluteInclude $(call FixPath, $(HOTSPOT_OUTPUTDIR)/variant-server/gensrc) \
       -absoluteSrcInclude $(call FixPath, $(HOTSPOT_OUTPUTDIR)/variant-server/gensrc) \
       $(EXTRACTED_DEFINES_client) \
--- a/hotspot/make/src/classes/build/tools/projectcreator/WinGammaPlatformVC10.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/make/src/classes/build/tools/projectcreator/WinGammaPlatformVC10.java	Fri Jan 13 18:26:34 2017 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -114,8 +114,8 @@
             tag(cfg, "CodeAnalysisRuleAssemblies");
         }
         for (BuildConfig cfg : allConfigs) {
-            tagData(cfg, "NMakeBuildCommandLine", cfg.get("MakeBinary") + " -f ../../Makefile import-hotspot LOG=info");
-            tagData(cfg, "NMakeReBuildCommandLine", cfg.get("MakeBinary") + " -f ../../Makefile clean-hotspot import-hotspot LOG=info");
+            tagData(cfg, "NMakeBuildCommandLine", cfg.get("MakeBinary") + " -f ../../Makefile hotspot LOG=info");
+            tagData(cfg, "NMakeReBuildCommandLine", cfg.get("MakeBinary") + " -f ../../Makefile clean-hotspot hotspot LOG=info");
             tagData(cfg, "NMakeCleanCommandLine", cfg.get("MakeBinary") + " -f ../../Makefile clean-hotspot LOG=info");
             tagData(cfg, "NMakeOutput", cfg.get("MakeOutput") + Util.sep + "jvm.dll");
             tagData(cfg, "NMakePreprocessorDefinitions", Util.join(";", cfg.getDefines()));
--- a/hotspot/src/cpu/aarch64/vm/aarch64.ad	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/cpu/aarch64/vm/aarch64.ad	Fri Jan 13 18:26:34 2017 +0100
@@ -3008,6 +3008,10 @@
     __ notify(Assembler::method_reentry);
   }
 
+  if (StackReservedPages > 0 && C->has_reserved_stack_access()) {
+    __ reserved_stack_check();
+  }
+
   if (do_polling() && C->is_method_compilation()) {
     __ read_polling_page(rscratch1, os::get_polling_page(), relocInfo::poll_return_type);
   }
--- a/hotspot/src/cpu/aarch64/vm/c1_LIRAssembler_aarch64.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/cpu/aarch64/vm/c1_LIRAssembler_aarch64.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -532,8 +532,14 @@
 
 void LIR_Assembler::return_op(LIR_Opr result) {
   assert(result->is_illegal() || !result->is_single_cpu() || result->as_register() == r0, "word returns are in r0,");
+
   // Pop the stack before the safepoint code
   __ remove_frame(initial_frame_size_in_bytes());
+
+  if (StackReservedPages > 0 && compilation()->has_reserved_stack_access()) {
+    __ reserved_stack_check();
+  }
+
   address polling_page(os::get_polling_page());
   __ read_polling_page(rscratch1, polling_page, relocInfo::poll_return_type);
   __ ret(lr);
--- a/hotspot/src/cpu/aarch64/vm/frame_aarch64.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/cpu/aarch64/vm/frame_aarch64.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -629,6 +629,7 @@
     DESCRIBE_FP_OFFSET(interpreter_frame_last_sp);
     DESCRIBE_FP_OFFSET(interpreter_frame_method);
     DESCRIBE_FP_OFFSET(interpreter_frame_mdp);
+    DESCRIBE_FP_OFFSET(interpreter_frame_mirror);
     DESCRIBE_FP_OFFSET(interpreter_frame_cache);
     DESCRIBE_FP_OFFSET(interpreter_frame_locals);
     DESCRIBE_FP_OFFSET(interpreter_frame_bcp);
--- a/hotspot/src/cpu/aarch64/vm/frame_aarch64.hpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/cpu/aarch64/vm/frame_aarch64.hpp	Fri Jan 13 18:26:34 2017 +0100
@@ -46,6 +46,9 @@
 //    [pointer to locals     ]                   = locals()             locals_offset
 //    [constant pool cache   ]                   = cache()              cache_offset
 
+//    [klass of method       ]                   = mirror()             mirror_offset
+//    [padding               ]
+
 //    [methodData            ]                   = mdp()                mdx_offset
 //    [methodOop             ]                   = method()             method_offset
 
--- a/hotspot/src/cpu/aarch64/vm/globalDefinitions_aarch64.hpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/cpu/aarch64/vm/globalDefinitions_aarch64.hpp	Fri Jan 13 18:26:34 2017 +0100
@@ -53,4 +53,6 @@
 // evidence that it's worth doing.
 #define DEOPTIMIZE_WHEN_PATCHING
 
+#define SUPPORT_RESERVED_STACK_AREA
+
 #endif // CPU_AARCH64_VM_GLOBALDEFINITIONS_AARCH64_HPP
--- a/hotspot/src/cpu/aarch64/vm/globals_aarch64.hpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/cpu/aarch64/vm/globals_aarch64.hpp	Fri Jan 13 18:26:34 2017 +0100
@@ -47,7 +47,7 @@
 #define DEFAULT_STACK_YELLOW_PAGES (2)
 #define DEFAULT_STACK_RED_PAGES (1)
 #define DEFAULT_STACK_SHADOW_PAGES (4 DEBUG_ONLY(+5))
-#define DEFAULT_STACK_RESERVED_PAGES (0)
+#define DEFAULT_STACK_RESERVED_PAGES (1)
 
 #define MIN_STACK_YELLOW_PAGES DEFAULT_STACK_YELLOW_PAGES
 #define MIN_STACK_RED_PAGES    DEFAULT_STACK_RED_PAGES
--- a/hotspot/src/cpu/aarch64/vm/interp_masm_aarch64.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/cpu/aarch64/vm/interp_masm_aarch64.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -619,6 +619,22 @@
   // get sender esp
   ldr(esp,
       Address(rfp, frame::interpreter_frame_sender_sp_offset * wordSize));
+  if (StackReservedPages > 0) {
+    // testing if reserved zone needs to be re-enabled
+    Label no_reserved_zone_enabling;
+
+    ldr(rscratch1, Address(rthread, JavaThread::reserved_stack_activation_offset()));
+    cmp(esp, rscratch1);
+    br(Assembler::LS, no_reserved_zone_enabling);
+
+    call_VM_leaf(
+      CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), rthread);
+    call_VM(noreg, CAST_FROM_FN_PTR(address,
+                   InterpreterRuntime::throw_delayed_StackOverflowError));
+    should_not_reach_here();
+
+    bind(no_reserved_zone_enabling);
+  }
   // remove frame anchor
   leave();
   // If we're returning to interpreted code we will shortly be
--- a/hotspot/src/cpu/aarch64/vm/macroAssembler_aarch64.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/cpu/aarch64/vm/macroAssembler_aarch64.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -402,6 +402,30 @@
   }
 }
 
+void MacroAssembler::reserved_stack_check() {
+    // testing if reserved zone needs to be enabled
+    Label no_reserved_zone_enabling;
+
+    ldr(rscratch1, Address(rthread, JavaThread::reserved_stack_activation_offset()));
+    cmp(sp, rscratch1);
+    br(Assembler::LO, no_reserved_zone_enabling);
+
+    enter();   // LR and FP are live.
+    lea(rscratch1, CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone));
+    mov(c_rarg0, rthread);
+    blr(rscratch1);
+    leave();
+
+    // We have already removed our own frame.
+    // throw_delayed_StackOverflowError will think that it's been
+    // called by our caller.
+    lea(rscratch1, RuntimeAddress(StubRoutines::throw_delayed_StackOverflowError_entry()));
+    br(rscratch1);
+    should_not_reach_here();
+
+    bind(no_reserved_zone_enabling);
+}
+
 int MacroAssembler::biased_locking_enter(Register lock_reg,
                                          Register obj_reg,
                                          Register swap_reg,
--- a/hotspot/src/cpu/aarch64/vm/macroAssembler_aarch64.hpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/cpu/aarch64/vm/macroAssembler_aarch64.hpp	Fri Jan 13 18:26:34 2017 +0100
@@ -957,6 +957,9 @@
   // stack overflow + shadow pages.  Also, clobbers tmp
   void bang_stack_size(Register size, Register tmp);
 
+  // Check for reserved stack access in method being exited (for JIT)
+  void reserved_stack_check();
+
   virtual RegisterOrConstant delayed_value_impl(intptr_t* delayed_value_addr,
                                                 Register tmp,
                                                 int offset);
--- a/hotspot/src/cpu/aarch64/vm/stubGenerator_aarch64.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/cpu/aarch64/vm/stubGenerator_aarch64.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -4676,8 +4676,11 @@
     StubRoutines::_throw_StackOverflowError_entry =
       generate_throw_exception("StackOverflowError throw_exception",
                                CAST_FROM_FN_PTR(address,
-                                                SharedRuntime::
-                                                throw_StackOverflowError));
+                                                SharedRuntime::throw_StackOverflowError));
+    StubRoutines::_throw_delayed_StackOverflowError_entry =
+      generate_throw_exception("delayed StackOverflowError throw_exception",
+                               CAST_FROM_FN_PTR(address,
+                                                SharedRuntime::throw_delayed_StackOverflowError));
     if (UseCRC32Intrinsics) {
       // set table address before stub generation which use it
       StubRoutines::_crc_table_adr = (address)StubRoutines::aarch64::_crc_table;
--- a/hotspot/src/cpu/ppc/vm/macroAssembler_ppc.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/cpu/ppc/vm/macroAssembler_ppc.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -2569,7 +2569,7 @@
 }
 
 // Spin and retry if lock is busy.
-// inputs: box_Reg (monitor address)
+// inputs: owner_addr_Reg (monitor address)
 //       : retry_count_Reg
 // output: retry_count_Reg decremented by 1
 // CTR is killed
@@ -2577,15 +2577,22 @@
   Label SpinLoop, doneRetry;
   addic_(retry_count_Reg, retry_count_Reg, -1);
   blt(CCR0, doneRetry);
-  li(R0, RTMSpinLoopCount);
-  mtctr(R0);
+
+  if (RTMSpinLoopCount > 1) {
+    li(R0, RTMSpinLoopCount);
+    mtctr(R0);
+  }
 
   bind(SpinLoop);
   smt_yield(); // Can't use waitrsv(). No permission (SIGILL).
-  bdz(retryLabel);
-  ld(R0, 0, owner_addr_Reg);
-  cmpdi(CCR0, R0, 0);
-  bne(CCR0, SpinLoop);
+
+  if (RTMSpinLoopCount > 1) {
+    bdz(retryLabel);
+    ld(R0, 0, owner_addr_Reg);
+    cmpdi(CCR0, R0, 0);
+    bne(CCR0, SpinLoop);
+  }
+
   b(retryLabel);
 
   bind(doneRetry);
--- a/hotspot/src/cpu/ppc/vm/vm_version_ppc.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/cpu/ppc/vm/vm_version_ppc.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -327,7 +327,10 @@
       warning("RTMAbortRatio must be in the range 0 to 100, resetting it to 50");
       FLAG_SET_DEFAULT(RTMAbortRatio, 50);
     }
-    guarantee(RTMSpinLoopCount > 0, "unsupported");
+    if (RTMSpinLoopCount < 0) {
+      warning("RTMSpinLoopCount must not be a negative value, resetting it to 0");
+      FLAG_SET_DEFAULT(RTMSpinLoopCount, 0);
+    }
 #else
     // Only C2 does RTM locking optimization.
     // Can't continue because UseRTMLocking affects UseBiasedLocking flag
--- a/hotspot/src/cpu/s390/vm/c1_LIRAssembler_s390.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/cpu/s390/vm/c1_LIRAssembler_s390.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -1105,16 +1105,16 @@
       }
     case T_FLOAT :
       if (short_disp) {
-                    __ z_ste(from->as_float_reg(),  disp_value, disp_reg, dest);
+        __ z_ste(from->as_float_reg(),  disp_value, disp_reg, dest);
       } else {
-                    __ z_stey(from->as_float_reg(), disp_value, disp_reg, dest);
+        __ z_stey(from->as_float_reg(), disp_value, disp_reg, dest);
       }
       break;
     case T_DOUBLE:
       if (short_disp) {
-                    __ z_std(from->as_double_reg(),  disp_value, disp_reg, dest);
+        __ z_std(from->as_double_reg(),  disp_value, disp_reg, dest);
       } else {
-                    __ z_stdy(from->as_double_reg(), disp_value, disp_reg, dest);
+        __ z_stdy(from->as_double_reg(), disp_value, disp_reg, dest);
       }
       break;
     default: ShouldNotReachHere();
@@ -1148,6 +1148,10 @@
     __ restore_return_pc();
   }
 
+  if (StackReservedPages > 0 && compilation()->has_reserved_stack_access()) {
+    __ reserved_stack_check(Z_R14);
+  }
+
   // We need to mark the code position where the load from the safepoint
   // polling page was emitted as relocInfo::poll_return_type here.
   __ relocate(relocInfo::poll_return_type);
--- a/hotspot/src/cpu/s390/vm/globalDefinitions_s390.hpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/cpu/s390/vm/globalDefinitions_s390.hpp	Fri Jan 13 18:26:34 2017 +0100
@@ -52,4 +52,6 @@
 // The expected size in bytes of a cache line, used to pad data structures.
 #define DEFAULT_CACHE_LINE_SIZE 256
 
+#define SUPPORT_RESERVED_STACK_AREA
+
 #endif // CPU_S390_VM_GLOBALDEFINITIONS_S390_HPP
--- a/hotspot/src/cpu/s390/vm/globals_s390.hpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/cpu/s390/vm/globals_s390.hpp	Fri Jan 13 18:26:34 2017 +0100
@@ -56,7 +56,7 @@
 // Java_java_net_SocketOutputStream_socketWrite0() uses a 64k buffer on the
 // stack. To pass stack overflow tests we need 20 shadow pages.
 #define DEFAULT_STACK_SHADOW_PAGES   (20 DEBUG_ONLY(+2))
-#define DEFAULT_STACK_RESERVED_PAGES (0)
+#define DEFAULT_STACK_RESERVED_PAGES (1)
 
 #define MIN_STACK_YELLOW_PAGES     DEFAULT_STACK_YELLOW_PAGES
 #define MIN_STACK_RED_PAGES        DEFAULT_STACK_RED_PAGES
--- a/hotspot/src/cpu/s390/vm/interp_masm_s390.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/cpu/s390/vm/interp_masm_s390.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -860,16 +860,39 @@
                                                   bool throw_monitor_exception,
                                                   bool install_monitor_exception,
                                                   bool notify_jvmti) {
-
+  BLOCK_COMMENT("remove_activation {");
   unlock_if_synchronized_method(state, throw_monitor_exception, install_monitor_exception);
 
   // Save result (push state before jvmti call and pop it afterwards) and notify jvmti.
   notify_method_exit(false, state, notify_jvmti ? NotifyJVMTI : SkipNotifyJVMTI);
 
+  if (StackReservedPages > 0) {
+    BLOCK_COMMENT("reserved_stack_check:");
+    // Test if reserved zone needs to be enabled.
+    Label no_reserved_zone_enabling;
+
+    // Compare frame pointers. There is no good stack pointer, as with stack
+    // frame compression we can get different SPs when we do calls. A subsequent
+    // call could have a smaller SP, so that this compare succeeds for an
+    // inner call of the method annotated with ReservedStack.
+    z_lg(Z_R0, Address(Z_SP, (intptr_t)_z_abi(callers_sp)));
+    z_clg(Z_R0, Address(Z_thread, JavaThread::reserved_stack_activation_offset())); // Compare with frame pointer in memory.
+    z_brl(no_reserved_zone_enabling);
+
+    // Enable reserved zone again, throw stack overflow exception.
+    call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), Z_thread);
+    call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_delayed_StackOverflowError));
+
+    should_not_reach_here();
+
+    bind(no_reserved_zone_enabling);
+  }
+
   verify_oop(Z_tos, state);
   verify_thread();
 
   pop_interpreter_frame(return_pc, Z_ARG2, Z_ARG3);
+  BLOCK_COMMENT("} remove_activation");
 }
 
 // lock object
--- a/hotspot/src/cpu/s390/vm/macroAssembler_s390.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/cpu/s390/vm/macroAssembler_s390.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -2666,6 +2666,32 @@
   }
 }
 
+void MacroAssembler::reserved_stack_check(Register return_pc) {
+  // Test if reserved zone needs to be enabled.
+  Label no_reserved_zone_enabling;
+  assert(return_pc == Z_R14, "Return pc must be in R14 before z_br() to StackOverflow stub.");
+  BLOCK_COMMENT("reserved_stack_check {");
+
+  z_clg(Z_SP, Address(Z_thread, JavaThread::reserved_stack_activation_offset()));
+  z_brl(no_reserved_zone_enabling);
+
+  // Enable reserved zone again, throw stack overflow exception.
+  save_return_pc();
+  push_frame_abi160(0);
+  call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), Z_thread);
+  pop_frame();
+  restore_return_pc();
+
+  load_const_optimized(Z_R1, StubRoutines::throw_delayed_StackOverflowError_entry());
+  // Don't use call() or z_basr(), they will invalidate Z_R14 which contains the return pc.
+  z_br(Z_R1);
+
+  should_not_reach_here();
+
+  bind(no_reserved_zone_enabling);
+  BLOCK_COMMENT("} reserved_stack_check");
+}
+
 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
 void MacroAssembler::tlab_allocate(Register obj,
                                    Register var_size_in_bytes,
--- a/hotspot/src/cpu/s390/vm/macroAssembler_s390.hpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/cpu/s390/vm/macroAssembler_s390.hpp	Fri Jan 13 18:26:34 2017 +0100
@@ -627,6 +627,11 @@
   // Stack overflow checking
   void bang_stack_with_offset(int offset);
 
+  // Check for reserved stack access in method being exited. If the reserved
+  // stack area was accessed, protect it again and throw StackOverflowError.
+  // Uses Z_R1.
+  void reserved_stack_check(Register return_pc);
+
   // Atomics
   // -- none?
 
--- a/hotspot/src/cpu/s390/vm/s390.ad	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/cpu/s390/vm/s390.ad	Fri Jan 13 18:26:34 2017 +0100
@@ -909,15 +909,8 @@
   // If this does safepoint polling, then do it here.
   bool need_polling = do_polling() && C->is_method_compilation();
 
-  // Touch the polling page.
-  // Part 1: get the page's address.
-  if (need_polling) {
-    AddressLiteral pp(os::get_polling_page());
-    __ load_const_optimized(Z_R1_scratch, pp);
-  }
-
   // Pop frame, restore return_pc, and all stuff needed by interpreter.
-  // Pop frame by add insted of load (a penny saved is a penny got :-).
+  // Pop frame by add instead of load (a penny saved is a penny got :-).
   int frame_size_in_bytes = Assembler::align((C->frame_slots() << LogBytesPerInt), frame::alignment_in_bytes);
   int retPC_offset        = frame_size_in_bytes + _z_abi16(return_pc);
   if (Displacement::is_validDisp(retPC_offset)) {
@@ -928,9 +921,14 @@
     __ restore_return_pc();
   }
 
-  // Touch the polling page,
-  // part 2: touch the page now.
+  if (StackReservedPages > 0 && C->has_reserved_stack_access()) {
+    __ reserved_stack_check(Z_R14);
+  }
+
+  // Touch the polling page.
   if (need_polling) {
+    AddressLiteral pp(os::get_polling_page());
+    __ load_const_optimized(Z_R1_scratch, pp);
     // We need to mark the code position where the load from the safepoint
     // polling page was emitted as relocInfo::poll_return_type here.
     __ relocate(relocInfo::poll_return_type);
@@ -939,7 +937,7 @@
 }
 
 uint MachEpilogNode::size(PhaseRegAlloc *ra_) const {
-  // variable size. determine dynamically.
+  // Variable size. determine dynamically.
   return MachNode::size(ra_);
 }
 
--- a/hotspot/src/cpu/s390/vm/stubGenerator_s390.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/cpu/s390/vm/stubGenerator_s390.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -2433,13 +2433,12 @@
     StubRoutines::_throw_StackOverflowError_entry          =
       generate_throw_exception("StackOverflowError throw_exception",
                                CAST_FROM_FN_PTR(address, SharedRuntime::throw_StackOverflowError), false);
+    StubRoutines::_throw_delayed_StackOverflowError_entry  =
+      generate_throw_exception("delayed StackOverflowError throw_exception",
+                               CAST_FROM_FN_PTR(address, SharedRuntime::throw_delayed_StackOverflowError), false);
 
     //----------------------------------------------------------------------
     // Entry points that are platform specific.
-    // Build this early so it's available for the interpreter.
-    StubRoutines::_throw_StackOverflowError_entry          =
-      generate_throw_exception("StackOverflowError throw_exception",
-                               CAST_FROM_FN_PTR(address, SharedRuntime::throw_StackOverflowError), false);
 
     if (UseCRC32Intrinsics) {
       // We have no CRC32 table on z/Architecture.
--- a/hotspot/src/cpu/s390/vm/templateInterpreterGenerator_s390.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/cpu/s390/vm/templateInterpreterGenerator_s390.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -1112,16 +1112,21 @@
   // top_frame_size = TOP_IJAVA_FRAME_ABI + max_stack + size of interpreter state
   __ add2reg(top_frame_size,
              frame::z_top_ijava_frame_abi_size +
-               frame::z_ijava_state_size +
-               frame::interpreter_frame_monitor_size() * wordSize,
+             frame::z_ijava_state_size +
+             frame::interpreter_frame_monitor_size() * wordSize,
              max_stack);
 
-  // Check if there's room for the new frame...
-  Register frame_size = max_stack; // Reuse the regiser for max_stack.
-  __ z_lgr(frame_size, Z_SP);
-  __ z_sgr(frame_size, sp_after_resize);
-  __ z_agr(frame_size, top_frame_size);
-  generate_stack_overflow_check(frame_size, fp/*tmp1*/);
+  if (!native_call) {
+    // Stack overflow check.
+    // Native calls don't need the stack size check since they have no
+    // expression stack and the arguments are already on the stack and
+    // we only add a handful of words to the stack.
+    Register frame_size = max_stack; // Reuse the regiser for max_stack.
+    __ z_lgr(frame_size, Z_SP);
+    __ z_sgr(frame_size, sp_after_resize);
+    __ z_agr(frame_size, top_frame_size);
+    generate_stack_overflow_check(frame_size, fp/*tmp1*/);
+  }
 
   DEBUG_ONLY(__ z_cg(Z_R14, _z_abi16(return_pc), Z_SP));
   __ asm_assert_eq("killed Z_R14", 0);
--- a/hotspot/src/cpu/sparc/vm/c1_LIRAssembler_sparc.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/cpu/sparc/vm/c1_LIRAssembler_sparc.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -694,6 +694,7 @@
 int LIR_Assembler::store(LIR_Opr from_reg, Register base, int offset, BasicType type, bool wide, bool unaligned) {
   int store_offset;
   if (!Assembler::is_simm13(offset + (type == T_LONG) ? wordSize : 0)) {
+    assert(base != O7, "destroying register");
     assert(!unaligned, "can't handle this");
     // for offsets larger than a simm13 we setup the offset in O7
     __ set(offset, O7);
@@ -712,9 +713,12 @@
       case T_LONG  :
 #ifdef _LP64
         if (unaligned || PatchALot) {
-          __ srax(from_reg->as_register_lo(), 32, O7);
+          // Don't use O7 here because it may be equal to 'base' (see LIR_Assembler::reg2mem)
+          assert(G3_scratch != base, "can't handle this");
+          assert(G3_scratch != from_reg->as_register_lo(), "can't handle this");
+          __ srax(from_reg->as_register_lo(), 32, G3_scratch);
           __ stw(from_reg->as_register_lo(), base, offset + lo_word_offset_in_bytes);
-          __ stw(O7,                         base, offset + hi_word_offset_in_bytes);
+          __ stw(G3_scratch,                 base, offset + hi_word_offset_in_bytes);
         } else {
           __ stx(from_reg->as_register_lo(), base, offset);
         }
@@ -821,7 +825,7 @@
       case T_SHORT : __ ldsh(base, offset, to_reg->as_register()); break;
       case T_INT   : __ ld(base, offset, to_reg->as_register()); break;
       case T_LONG  :
-        if (!unaligned) {
+        if (!unaligned && !PatchALot) {
 #ifdef _LP64
           __ ldx(base, offset, to_reg->as_register_lo());
 #else
@@ -1297,7 +1301,7 @@
       disp_reg = O7;
     }
   } else if (unaligned || PatchALot) {
-    __ add(src, addr->index()->as_register(), O7);
+    __ add(src, addr->index()->as_pointer_register(), O7);
     src = O7;
   } else {
     disp_reg = addr->index()->as_pointer_register();
@@ -1424,7 +1428,7 @@
       disp_reg = O7;
     }
   } else if (unaligned || PatchALot) {
-    __ add(src, addr->index()->as_register(), O7);
+    __ add(src, addr->index()->as_pointer_register(), O7);
     src = O7;
   } else {
     disp_reg = addr->index()->as_pointer_register();
--- a/hotspot/src/cpu/x86/vm/macroAssembler_x86.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/cpu/x86/vm/macroAssembler_x86.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -3499,12 +3499,12 @@
   }
 }
 
-void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src) {
+void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src, Register scratchReg) {
   if (reachable(src)) {
     movdqu(dst, as_Address(src));
   } else {
-    lea(rscratch1, src);
-    movdqu(dst, Address(rscratch1, 0));
+    lea(scratchReg, src);
+    movdqu(dst, Address(scratchReg, 0));
   }
 }
 
--- a/hotspot/src/cpu/x86/vm/macroAssembler_x86.hpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/cpu/x86/vm/macroAssembler_x86.hpp	Fri Jan 13 18:26:34 2017 +0100
@@ -1085,7 +1085,7 @@
   void movdqu(Address     dst, XMMRegister src);
   void movdqu(XMMRegister dst, Address src);
   void movdqu(XMMRegister dst, XMMRegister src);
-  void movdqu(XMMRegister dst, AddressLiteral src);
+  void movdqu(XMMRegister dst, AddressLiteral src, Register scratchReg = rscratch1);
   // AVX Unaligned forms
   void vmovdqu(Address     dst, XMMRegister src);
   void vmovdqu(XMMRegister dst, Address src);
--- a/hotspot/src/cpu/x86/vm/macroAssembler_x86_sha.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/cpu/x86/vm/macroAssembler_x86_sha.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -817,7 +817,7 @@
   movl(d, Address(CTX, 4*3));
   movl(e, Address(CTX, 4*4));
   movl(f, Address(CTX, 4*5));
-  movl(g, Address(CTX, 4*6));
+  // load g - r10 after it is used as scratch
   movl(h, Address(CTX, 4*7));
 
   pshuffle_byte_flip_mask_addr = pshuffle_byte_flip_mask;
@@ -825,6 +825,8 @@
   vmovdqu(SHUF_00BA, ExternalAddress(pshuffle_byte_flip_mask_addr + 32));     //[_SHUF_00BA wrt rip]
   vmovdqu(SHUF_DC00, ExternalAddress(pshuffle_byte_flip_mask_addr + 64));     //[_SHUF_DC00 wrt rip]
 
+  movl(g, Address(CTX, 4*6));
+
   movq(Address(rsp, _CTX), CTX);           // store
 
 bind(loop0);
@@ -977,7 +979,7 @@
   movl(d, Address(CTX, 4*3));   // 0xa54ff53a
   movl(e, Address(CTX, 4*4));   // 0x510e527f
   movl(f, Address(CTX, 4*5));   // 0x9b05688c
-  movl(g, Address(CTX, 4*6));   // 0x1f83d9ab
+  // load g - r10 after use as scratch
   movl(h, Address(CTX, 4*7));   // 0x5be0cd19
 
 
@@ -986,6 +988,8 @@
   vmovdqu(SHUF_00BA, ExternalAddress(pshuffle_byte_flip_mask_addr + 32));     //[_SHUF_00BA wrt rip]
   vmovdqu(SHUF_DC00, ExternalAddress(pshuffle_byte_flip_mask_addr + 64));     //[_SHUF_DC00 wrt rip]
 
+  movl(g, Address(CTX, 4*6));   // 0x1f83d9ab
+
   movq(Address(rsp, _CTX), CTX);
   jmpb(do_last_block);
 
@@ -1154,9 +1158,8 @@
       // Move to appropriate lanes for calculating w[16] and w[17]
       vperm2f128(xmm4, xmm0, xmm0, 0); //xmm4 = W[-16] + W[-7] + s0{ BABA }
 
-      address MASK_YMM_LO = StubRoutines::x86::pshuffle_byte_flip_mask_addr_sha512();
       //Move to appropriate lanes for calculating w[18] and w[19]
-      vpand(xmm0, xmm0, ExternalAddress(MASK_YMM_LO + 32), AVX_256bit); //xmm0 = W[-16] + W[-7] + s0{ DC00 }
+      vpand(xmm0, xmm0, xmm10, AVX_256bit); //xmm0 = W[-16] + W[-7] + s0{ DC00 }
       //Calculate w[16] and w[17] in both 128 bit lanes
       //Calculate sigma1 for w[16] and w[17] on both 128 bit lanes
       vperm2f128(xmm2, xmm7, xmm7, 17); //xmm2 = W[-2] {BABA}
@@ -1250,6 +1253,7 @@
 
     const XMMRegister& XFER = xmm0; // YTMP0
     const XMMRegister& BYTE_FLIP_MASK = xmm9; // ymm9
+    const XMMRegister& YMM_MASK_LO = xmm10; // ymm10
 #ifdef _WIN64
     const Register& INP = rcx; //1st arg
     const Register& CTX = rdx; //2nd arg
@@ -1368,11 +1372,14 @@
     movq(d, Address(CTX, 8 * 3));
     movq(e, Address(CTX, 8 * 4));
     movq(f, Address(CTX, 8 * 5));
-    movq(g, Address(CTX, 8 * 6));
+    // load g - r10 after it is used as scratch
     movq(h, Address(CTX, 8 * 7));
 
     pshuffle_byte_flip_mask_addr = pshuffle_byte_flip_mask_sha512;
     vmovdqu(BYTE_FLIP_MASK, ExternalAddress(pshuffle_byte_flip_mask_addr + 0)); //PSHUFFLE_BYTE_FLIP_MASK wrt rip
+    vmovdqu(YMM_MASK_LO, ExternalAddress(pshuffle_byte_flip_mask_addr + 32));
+
+    movq(g, Address(CTX, 8 * 6));
 
     bind(loop0);
     lea(TBL, ExternalAddress(K512_W));
--- a/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -3207,7 +3207,7 @@
     const Register len_reg     = c_rarg4;  // src len (must be multiple of blocksize 16)
 #else
     const Address  len_mem(rbp, 6 * wordSize);  // length is on stack on Win64
-    const Register len_reg     = r10;      // pick the first volatile windows register
+    const Register len_reg     = r11;      // pick the volatile windows register
 #endif
     const Register pos         = rax;
 
@@ -3404,7 +3404,7 @@
     const Register len_reg     = c_rarg4;  // src len (must be multiple of blocksize 16)
 #else
     const Address  len_mem(rbp, 6 * wordSize);  // length is on stack on Win64
-    const Register len_reg     = r10;      // pick the first volatile windows register
+    const Register len_reg     = r11;      // pick the volatile windows register
 #endif
     const Register pos         = rax;
 
@@ -3930,7 +3930,7 @@
 
     __ push(rbx); // Save RBX
     __ movdqu(xmm_curr_counter, Address(counter, 0x00)); // initialize counter with initial counter
-    __ movdqu(xmm_counter_shuf_mask, ExternalAddress(StubRoutines::x86::counter_shuffle_mask_addr()));
+    __ movdqu(xmm_counter_shuf_mask, ExternalAddress(StubRoutines::x86::counter_shuffle_mask_addr()), pos); // pos as scratch
     __ pshufb(xmm_curr_counter, xmm_counter_shuf_mask); //counter is shuffled
     __ movptr(pos, 0);
 
@@ -3953,7 +3953,7 @@
     __ movl(Address(used_addr, 0), used);
 
     // key length could be only {11, 13, 15} * 4 = {44, 52, 60}
-    __ movdqu(xmm_key_shuf_mask, ExternalAddress(StubRoutines::x86::key_shuffle_mask_addr()));
+    __ movdqu(xmm_key_shuf_mask, ExternalAddress(StubRoutines::x86::key_shuffle_mask_addr()), rbx); // rbx as scratch
     __ movl(rbx, Address(key, arrayOopDesc::length_offset_in_bytes() - arrayOopDesc::base_offset_in_bytes(T_INT)));
     __ cmpl(rbx, 52);
     __ jcc(Assembler::equal, L_multiBlock_loopTop[1]);
--- a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc.binformat/src/jdk/tools/jaotc/binformat/BinaryContainer.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc.binformat/src/jdk/tools/jaotc/binformat/BinaryContainer.java	Fri Jan 13 18:26:34 2017 +0100
@@ -37,6 +37,7 @@
 import jdk.tools.jaotc.binformat.Symbol.Kind;
 import jdk.tools.jaotc.binformat.elf.JELFRelocObject;
 import org.graalvm.compiler.hotspot.GraalHotSpotVMConfig;
+import org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderConfiguration;
 
 /**
  * A format-agnostic container class that holds various components of a binary.
@@ -257,9 +258,9 @@
      * prefix {@code prefix}. It also initializes internal code container, symbol table and
      * relocation tables.
      */
-    public BinaryContainer(GraalHotSpotVMConfig config, String jvmVersion) {
-        this.codeSegmentSize = config.codeSegmentSize;
-        this.codeEntryAlignment = config.codeEntryAlignment;
+    public BinaryContainer(GraalHotSpotVMConfig graalHotSpotVMConfig, GraphBuilderConfiguration graphBuilderConfig, String jvmVersion) {
+        this.codeSegmentSize = graalHotSpotVMConfig.codeSegmentSize;
+        this.codeEntryAlignment = graalHotSpotVMConfig.codeEntryAlignment;
 
         // read only, code
         codeContainer = new CodeContainer(".text", this);
@@ -289,30 +290,31 @@
 
         addGlobalSymbols();
 
-        recordConfiguration(config);
+        recordConfiguration(graalHotSpotVMConfig, graphBuilderConfig);
     }
 
-    private void recordConfiguration(GraalHotSpotVMConfig config) {
+    private void recordConfiguration(GraalHotSpotVMConfig graalHotSpotVMConfig, GraphBuilderConfiguration graphBuilderConfig) {
         // @formatter:off
-        boolean[] booleanFlags = { config.cAssertions, // Debug VM
-                                   config.useCompressedOops,
-                                   config.useCompressedClassPointers,
-                                   config.compactFields,
-                                   config.useG1GC,
-                                   config.useCMSGC,
-                                   config.useTLAB,
-                                   config.useBiasedLocking,
+        boolean[] booleanFlags = { graalHotSpotVMConfig.cAssertions, // Debug VM
+                                   graalHotSpotVMConfig.useCompressedOops,
+                                   graalHotSpotVMConfig.useCompressedClassPointers,
+                                   graalHotSpotVMConfig.compactFields,
+                                   graalHotSpotVMConfig.useG1GC,
+                                   graalHotSpotVMConfig.useCMSGC,
+                                   graalHotSpotVMConfig.useTLAB,
+                                   graalHotSpotVMConfig.useBiasedLocking,
                                    TieredAOT.getValue(),
-                                   config.enableContended,
-                                   config.restrictContended,
+                                   graalHotSpotVMConfig.enableContended,
+                                   graalHotSpotVMConfig.restrictContended,
+                                   graphBuilderConfig.omitAssertions()
         };
 
-        int[] intFlags         = { config.narrowOopShift,
-                                   config.narrowKlassShift,
-                                   config.contendedPaddingWidth,
-                                   config.fieldsAllocationStyle,
-                                   config.objectAlignment,
-                                   config.codeSegmentSize,
+        int[] intFlags         = { graalHotSpotVMConfig.narrowOopShift,
+                                   graalHotSpotVMConfig.narrowKlassShift,
+                                   graalHotSpotVMConfig.contendedPaddingWidth,
+                                   graalHotSpotVMConfig.fieldsAllocationStyle,
+                                   graalHotSpotVMConfig.objectAlignment,
+                                   graalHotSpotVMConfig.codeSegmentSize,
         };
         // @formatter:on
 
@@ -395,6 +397,10 @@
         return "_aot_narrow_klass_base_address";
     }
 
+    public String getNarrowOopBaseAddressSymbolName() {
+        return "_aot_narrow_oop_base_address";
+    }
+
     public String getLogOfHeapRegionGrainBytesSymbolName() {
         return "_aot_log_of_heap_region_grain_bytes";
     }
@@ -445,6 +451,7 @@
         createGotSymbol(getHeapTopAddressSymbolName());
         createGotSymbol(getHeapEndAddressSymbolName());
         createGotSymbol(getNarrowKlassBaseAddressSymbolName());
+        createGotSymbol(getNarrowOopBaseAddressSymbolName());
         createGotSymbol(getPollingPageSymbolName());
         createGotSymbol(getLogOfHeapRegionGrainBytesSymbolName());
         createGotSymbol(getInlineContiguousAllocationSupportedSymbolName());
--- a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/AOTBackend.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/AOTBackend.java	Fri Jan 13 18:26:34 2017 +0100
@@ -77,10 +77,14 @@
         this.filters = filters;
         providers = backend.getProviders();
         codeCache = providers.getCodeCache();
-        graphBuilderSuite = initGraphBuilderSuite(backend);
+        graphBuilderSuite = initGraphBuilderSuite(backend, main.options.compileWithAssertions);
         highTierContext = new HighTierContext(providers, graphBuilderSuite, OptimisticOptimizations.ALL);
     }
 
+    public PhaseSuite<HighTierContext> getGraphBuilderSuite() {
+        return graphBuilderSuite;
+    }
+
     private Suites getSuites() {
         // create suites every time, as we modify options for the compiler
         return backend.getSuites().getDefaultSuites();
@@ -146,14 +150,14 @@
         return backend.getRuntime().getVMConfig().cAssertions;
     }
 
-    private static PhaseSuite<HighTierContext> initGraphBuilderSuite(HotSpotBackend backend) {
+    private static PhaseSuite<HighTierContext> initGraphBuilderSuite(HotSpotBackend backend, boolean compileWithAssertions) {
         PhaseSuite<HighTierContext> graphBuilderSuite = backend.getSuites().getDefaultGraphBuilderSuite().copy();
         ListIterator<BasePhase<? super HighTierContext>> iterator = graphBuilderSuite.findPhase(GraphBuilderPhase.class);
         GraphBuilderConfiguration baseConfig = ((GraphBuilderPhase) iterator.previous()).getGraphBuilderConfig();
 
         // Use all default plugins.
         Plugins plugins = baseConfig.getPlugins();
-        GraphBuilderConfiguration aotConfig = GraphBuilderConfiguration.getDefault(plugins).withEagerResolving(true);
+        GraphBuilderConfiguration aotConfig = GraphBuilderConfiguration.getDefault(plugins).withEagerResolving(true).withOmitAssertions(!compileWithAssertions);
 
         iterator.next();
         iterator.remove();
--- a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/AOTCompiledClass.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/AOTCompiledClass.java	Fri Jan 13 18:26:34 2017 +0100
@@ -293,12 +293,18 @@
             // Record methods holder
             methodInfo.addDependentKlassData(binaryContainer, resolvedJavaType);
             // Record inlinee classes
-            for (ResolvedJavaMethod m : methodInfo.getCompilationResult().getMethods()) {
-                methodInfo.addDependentKlassData(binaryContainer, (HotSpotResolvedObjectType) m.getDeclaringClass());
+            ResolvedJavaMethod[] inlinees = methodInfo.getCompilationResult().getMethods();
+            if (inlinees != null) {
+                for (ResolvedJavaMethod m : inlinees) {
+                    methodInfo.addDependentKlassData(binaryContainer, (HotSpotResolvedObjectType) m.getDeclaringClass());
+                }
             }
             // Record classes of fields that were accessed
-            for (ResolvedJavaField f : methodInfo.getCompilationResult().getFields()) {
-                methodInfo.addDependentKlassData(binaryContainer, (HotSpotResolvedObjectType) f.getDeclaringClass());
+            ResolvedJavaField[] fields = methodInfo.getCompilationResult().getFields();
+            if (fields != null) {
+                for (ResolvedJavaField f : fields) {
+                    methodInfo.addDependentKlassData(binaryContainer, (HotSpotResolvedObjectType) f.getDeclaringClass());
+                }
             }
         }
     }
--- a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/Main.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/Main.java	Fri Jan 13 18:26:34 2017 +0100
@@ -45,6 +45,7 @@
 import java.util.Date;
 import java.util.LinkedList;
 import java.util.List;
+import java.util.ListIterator;
 import java.util.Set;
 import java.util.stream.Stream;
 
@@ -54,8 +55,14 @@
 import jdk.tools.jaotc.utils.Timer;
 
 import org.graalvm.compiler.api.runtime.GraalJVMCICompiler;
+import org.graalvm.compiler.hotspot.GraalHotSpotVMConfig;
 import org.graalvm.compiler.hotspot.HotSpotGraalRuntimeProvider;
 import org.graalvm.compiler.hotspot.HotSpotHostBackend;
+import org.graalvm.compiler.java.GraphBuilderPhase;
+import org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderConfiguration;
+import org.graalvm.compiler.phases.BasePhase;
+import org.graalvm.compiler.phases.PhaseSuite;
+import org.graalvm.compiler.phases.tiers.HighTierContext;
 import org.graalvm.compiler.runtime.RuntimeProvider;
 
 import jdk.vm.ci.meta.MetaAccessProvider;
@@ -144,11 +151,16 @@
         void process(Main task, String opt, String arg) {
             task.options.methodList = arg;
         }
-    }, new Option("  --compile-for-tiered       Generated profiling code for tiered compilation", false, "--compile-for-tiered") {
+    }, new Option("  --compile-for-tiered       Generate profiling code for tiered compilation", false, "--compile-for-tiered") {
         @Override
         void process(Main task, String opt, String arg) {
             TieredAOT.setValue(true);
         }
+    }, new Option("  --compile-with-assertions  Compile assertions", false, "--compile-with-assertions") {
+        @Override
+        void process(Main task, String opt, String arg) {
+            task.options.compileWithAssertions = true;
+        }
     }, new Option("  --classpath <path>         Specify where to find user class files", true, "--classpath", "--class-path") {
         @Override
         void process(Main task, String opt, String arg) {
@@ -225,15 +237,16 @@
          */
         private static final int COMPILER_THREADS = 16;
 
-        int threads = Integer.min(COMPILER_THREADS, Runtime.getRuntime().availableProcessors());
+        public int threads = Integer.min(COMPILER_THREADS, Runtime.getRuntime().availableProcessors());
 
         public boolean ignoreClassLoadingErrors;
         public boolean exitOnError;
-        boolean info;
-        boolean verbose;
-        boolean debug;
-        boolean help;
-        boolean version;
+        public boolean info;
+        public boolean verbose;
+        public boolean debug;
+        public boolean help;
+        public boolean version;
+        public boolean compileWithAssertions;
     }
 
     /* package */final Options options = new Options();
@@ -356,6 +369,11 @@
             AOTCompiler compiler = new AOTCompiler(this, aotBackend, options.threads);
             classes = compiler.compileClasses(classes);
 
+            GraalHotSpotVMConfig graalHotSpotVMConfig = runtime.getVMConfig();
+            PhaseSuite<HighTierContext> graphBuilderSuite = aotBackend.getGraphBuilderSuite();
+            ListIterator<BasePhase<? super HighTierContext>> iterator = graphBuilderSuite.findPhase(GraphBuilderPhase.class);
+            GraphBuilderConfiguration graphBuilderConfig = ((GraphBuilderPhase) iterator.previous()).getGraphBuilderConfig();
+
             // Free memory!
             try (Timer t = options.verbose ? new Timer(this, "Freeing memory") : null) {
                 printMemoryUsage();
@@ -364,7 +382,7 @@
                 System.gc();
             }
 
-            BinaryContainer binaryContainer = new BinaryContainer(runtime.getVMConfig(), JVM_VERSION);
+            BinaryContainer binaryContainer = new BinaryContainer(graalHotSpotVMConfig, graphBuilderConfig, JVM_VERSION);
             DataBuilder dataBuilder = new DataBuilder(this, backend, classes, binaryContainer);
             dataBuilder.prepareData();
 
--- a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/MarkId.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/MarkId.java	Fri Jan 13 18:26:34 2017 +0100
@@ -48,6 +48,7 @@
     HEAP_TOP_ADDRESS("CodeInstaller::HEAP_TOP_ADDRESS"),
     HEAP_END_ADDRESS("CodeInstaller::HEAP_END_ADDRESS"),
     NARROW_KLASS_BASE_ADDRESS("CodeInstaller::NARROW_KLASS_BASE_ADDRESS"),
+    NARROW_OOP_BASE_ADDRESS("CodeInstaller::NARROW_OOP_BASE_ADDRESS"),
     CRC_TABLE_ADDRESS("CodeInstaller::CRC_TABLE_ADDRESS"),
     LOG_OF_HEAP_REGION_GRAIN_BYTES("CodeInstaller::LOG_OF_HEAP_REGION_GRAIN_BYTES"),
     INLINE_CONTIGUOUS_ALLOCATION_SUPPORTED("CodeInstaller::INLINE_CONTIGUOUS_ALLOCATION_SUPPORTED");
--- a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/MarkProcessor.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/MarkProcessor.java	Fri Jan 13 18:26:34 2017 +0100
@@ -57,6 +57,7 @@
             case HEAP_TOP_ADDRESS:
             case HEAP_END_ADDRESS:
             case NARROW_KLASS_BASE_ADDRESS:
+            case NARROW_OOP_BASE_ADDRESS:
             case CRC_TABLE_ADDRESS:
             case LOG_OF_HEAP_REGION_GRAIN_BYTES:
             case INLINE_CONTIGUOUS_ALLOCATION_SUPPORTED:
@@ -78,6 +79,9 @@
                     case NARROW_KLASS_BASE_ADDRESS:
                         vmSymbolName = binaryContainer.getNarrowKlassBaseAddressSymbolName();
                         break;
+                    case NARROW_OOP_BASE_ADDRESS:
+                        vmSymbolName = binaryContainer.getNarrowOopBaseAddressSymbolName();
+                        break;
                     case CRC_TABLE_ADDRESS:
                         vmSymbolName = binaryContainer.getCrcTableAddressSymbolName();
                         break;
--- a/hotspot/src/jdk.vm.compiler/share/classes/org.graalvm.compiler.hotspot.amd64/src/org/graalvm/compiler/hotspot/amd64/AMD64HotSpotBackend.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/jdk.vm.compiler/share/classes/org.graalvm.compiler.hotspot.amd64/src/org/graalvm/compiler/hotspot/amd64/AMD64HotSpotBackend.java	Fri Jan 13 18:26:34 2017 +0100
@@ -267,10 +267,15 @@
 
             if (config.useCompressedClassPointers) {
                 Register register = r10;
-                AMD64HotSpotMove.decodeKlassPointer(asm, register, providers.getRegisters().getHeapBaseRegister(), src, config.getKlassEncoding());
-                if (config.narrowKlassBase != 0) {
-                    // The heap base register was destroyed above, so restore it
-                    asm.movq(providers.getRegisters().getHeapBaseRegister(), config.narrowOopBase);
+                AMD64HotSpotMove.decodeKlassPointer(crb, asm, register, providers.getRegisters().getHeapBaseRegister(), src, config);
+                if (GeneratePIC.getValue()) {
+                    asm.movq(providers.getRegisters().getHeapBaseRegister(), asm.getPlaceholder(-1));
+                    crb.recordMark(config.MARKID_NARROW_OOP_BASE_ADDRESS);
+                } else {
+                    if (config.narrowKlassBase != 0) {
+                        // The heap base register was destroyed above, so restore it
+                        asm.movq(providers.getRegisters().getHeapBaseRegister(), config.narrowOopBase);
+                    }
                 }
                 asm.cmpq(inlineCacheKlass, register);
             } else {
--- a/hotspot/src/jdk.vm.compiler/share/classes/org.graalvm.compiler.hotspot.amd64/src/org/graalvm/compiler/hotspot/amd64/AMD64HotSpotMove.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/jdk.vm.compiler/share/classes/org.graalvm.compiler.hotspot.amd64/src/org/graalvm/compiler/hotspot/amd64/AMD64HotSpotMove.java	Fri Jan 13 18:26:34 2017 +0100
@@ -265,14 +265,21 @@
         }
     }
 
-    public static void decodeKlassPointer(AMD64MacroAssembler masm, Register register, Register scratch, AMD64Address address, CompressEncoding encoding) {
+    public static void decodeKlassPointer(CompilationResultBuilder crb, AMD64MacroAssembler masm, Register register, Register scratch, AMD64Address address, GraalHotSpotVMConfig config) {
+        CompressEncoding encoding = config.getKlassEncoding();
         masm.movl(register, address);
         if (encoding.shift != 0) {
             assert encoding.alignment == encoding.shift : "Decode algorithm is wrong";
             masm.shlq(register, encoding.alignment);
         }
-        if (encoding.base != 0) {
-            masm.movq(scratch, encoding.base);
+        if (GeneratePIC.getValue() || encoding.base != 0) {
+            if (GeneratePIC.getValue()) {
+                masm.movq(scratch, masm.getPlaceholder(-1));
+                crb.recordMark(config.MARKID_NARROW_KLASS_BASE_ADDRESS);
+            } else {
+                assert encoding.base != 0;
+                masm.movq(scratch, encoding.base);
+            }
             masm.addq(register, scratch);
         }
     }
--- a/hotspot/src/jdk.vm.compiler/share/classes/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/GraalHotSpotVMConfig.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/jdk.vm.compiler/share/classes/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/GraalHotSpotVMConfig.java	Fri Jan 13 18:26:34 2017 +0100
@@ -773,9 +773,10 @@
     public final int MARKID_HEAP_TOP_ADDRESS = getConstant("CodeInstaller::HEAP_TOP_ADDRESS", Integer.class, 17);
     public final int MARKID_HEAP_END_ADDRESS = getConstant("CodeInstaller::HEAP_END_ADDRESS", Integer.class, 18);
     public final int MARKID_NARROW_KLASS_BASE_ADDRESS = getConstant("CodeInstaller::NARROW_KLASS_BASE_ADDRESS", Integer.class, 19);
-    public final int MARKID_CRC_TABLE_ADDRESS = getConstant("CodeInstaller::CRC_TABLE_ADDRESS", Integer.class, 20);
-    public final int MARKID_LOG_OF_HEAP_REGION_GRAIN_BYTES = getConstant("CodeInstaller::LOG_OF_HEAP_REGION_GRAIN_BYTES", Integer.class, 21);
-    public final int MARKID_INLINE_CONTIGUOUS_ALLOCATION_SUPPORTED = getConstant("CodeInstaller::INLINE_CONTIGUOUS_ALLOCATION_SUPPORTED", Integer.class, 22);
+    public final int MARKID_NARROW_OOP_BASE_ADDRESS = getConstant("CodeInstaller::NARROW_OOP_BASE_ADDRESS", Integer.class, 20);
+    public final int MARKID_CRC_TABLE_ADDRESS = getConstant("CodeInstaller::CRC_TABLE_ADDRESS", Integer.class, 21);
+    public final int MARKID_LOG_OF_HEAP_REGION_GRAIN_BYTES = getConstant("CodeInstaller::LOG_OF_HEAP_REGION_GRAIN_BYTES", Integer.class, 22);
+    public final int MARKID_INLINE_CONTIGUOUS_ALLOCATION_SUPPORTED = getConstant("CodeInstaller::INLINE_CONTIGUOUS_ALLOCATION_SUPPORTED", Integer.class, 23);
 
     // Checkstyle: resume
 
--- a/hotspot/src/jdk.vm.compiler/share/classes/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/meta/HotSpotNodePlugin.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/jdk.vm.compiler/share/classes/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/meta/HotSpotNodePlugin.java	Fri Jan 13 18:26:34 2017 +0100
@@ -22,7 +22,6 @@
  */
 package org.graalvm.compiler.hotspot.meta;
 
-import static org.graalvm.compiler.core.common.GraalOptions.GeneratePIC;
 import static org.graalvm.compiler.core.common.GraalOptions.ImmutableCode;
 import static org.graalvm.compiler.hotspot.meta.HotSpotGraalConstantFieldProvider.FieldReadEnabledInImmutableCode;
 
@@ -112,11 +111,6 @@
                 return true;
             }
         }
-        if (GeneratePIC.getValue()) {
-            if (field.isSynthetic() && field.getName().startsWith("$assertionsDisabled")) {
-                return tryReadField(b, field, null);
-            }
-        }
         if (b.parsingIntrinsic() && wordOperationPlugin.handleLoadStaticField(b, field)) {
             return true;
         }
--- a/hotspot/src/os/windows/vm/os_windows.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/os/windows/vm/os_windows.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -778,6 +778,11 @@
   // is already attached to a debugger; debugger must observe
   // the exception below to show the correct name.
 
+  // If there is no debugger attached skip raising the exception
+  if (!IsDebuggerPresent()) {
+    return;
+  }
+
   const DWORD MS_VC_EXCEPTION = 0x406D1388;
   struct {
     DWORD dwType;     // must be 0x1000
--- a/hotspot/src/os_cpu/linux_aarch64/vm/os_linux_aarch64.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/os_cpu/linux_aarch64/vm/os_linux_aarch64.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -87,6 +87,7 @@
 #define SPELL_REG_FP "rbp"
 #else
 #define REG_FP 29
+#define REG_LR 30
 
 #define SPELL_REG_SP "sp"
 #define SPELL_REG_FP "x29"
@@ -182,6 +183,46 @@
   return frame(sp, fp, epc.pc());
 }
 
+bool os::Linux::get_frame_at_stack_banging_point(JavaThread* thread, ucontext_t* uc, frame* fr) {
+  address pc = (address) os::Linux::ucontext_get_pc(uc);
+  if (Interpreter::contains(pc)) {
+    // interpreter performs stack banging after the fixed frame header has
+    // been generated while the compilers perform it before. To maintain
+    // semantic consistency between interpreted and compiled frames, the
+    // method returns the Java sender of the current frame.
+    *fr = os::fetch_frame_from_context(uc);
+    if (!fr->is_first_java_frame()) {
+      assert(fr->safe_for_sender(thread), "Safety check");
+      *fr = fr->java_sender();
+    }
+  } else {
+    // more complex code with compiled code
+    assert(!Interpreter::contains(pc), "Interpreted methods should have been handled above");
+    CodeBlob* cb = CodeCache::find_blob(pc);
+    if (cb == NULL || !cb->is_nmethod() || cb->is_frame_complete_at(pc)) {
+      // Not sure where the pc points to, fallback to default
+      // stack overflow handling
+      return false;
+    } else {
+      // In compiled code, the stack banging is performed before LR
+      // has been saved in the frame.  LR is live, and SP and FP
+      // belong to the caller.
+      intptr_t* fp = os::Linux::ucontext_get_fp(uc);
+      intptr_t* sp = os::Linux::ucontext_get_sp(uc);
+      address pc = (address)(uc->uc_mcontext.regs[REG_LR]
+                         - NativeInstruction::instruction_size);
+      *fr = frame(sp, fp, pc);
+      if (!fr->is_java_frame()) {
+        assert(fr->safe_for_sender(thread), "Safety check");
+        assert(!fr->is_first_frame(), "Safety check");
+        *fr = fr->java_sender();
+      }
+    }
+  }
+  assert(fr->is_java_frame(), "Safety check");
+  return true;
+}
+
 // By default, gcc always saves frame pointer rfp on this stack. This
 // may get turned off by -fomit-frame-pointer.
 frame os::get_sender_for_C_frame(frame* fr) {
@@ -313,6 +354,24 @@
         if (thread->in_stack_yellow_reserved_zone(addr)) {
           thread->disable_stack_yellow_reserved_zone();
           if (thread->thread_state() == _thread_in_Java) {
+            if (thread->in_stack_reserved_zone(addr)) {
+              frame fr;
+              if (os::Linux::get_frame_at_stack_banging_point(thread, uc, &fr)) {
+                assert(fr.is_java_frame(), "Must be a Java frame");
+                frame activation =
+                  SharedRuntime::look_for_reserved_stack_annotated_method(thread, fr);
+                if (activation.sp() != NULL) {
+                  thread->disable_stack_reserved_zone();
+                  if (activation.is_interpreted_frame()) {
+                    thread->set_reserved_stack_activation((address)(
+                      activation.fp() + frame::interpreter_frame_initial_sp_offset));
+                  } else {
+                    thread->set_reserved_stack_activation((address)activation.unextended_sp());
+                  }
+                  return 1;
+                }
+              }
+            }
             // Throw a stack overflow exception.  Guard pages will be reenabled
             // while unwinding the stack.
             stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW);
--- a/hotspot/src/os_cpu/linux_s390/vm/os_linux_s390.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/os_cpu/linux_s390/vm/os_linux_s390.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -144,6 +144,42 @@
   return frame(sp, epc.pc());
 }
 
+bool os::Linux::get_frame_at_stack_banging_point(JavaThread* thread, ucontext_t* uc, frame* fr) {
+  address pc = (address) os::Linux::ucontext_get_pc(uc);
+  if (Interpreter::contains(pc)) {
+    // Interpreter performs stack banging after the fixed frame header has
+    // been generated while the compilers perform it before. To maintain
+    // semantic consistency between interpreted and compiled frames, the
+    // method returns the Java sender of the current frame.
+    *fr = os::fetch_frame_from_context(uc);
+    if (!fr->is_first_java_frame()) {
+      assert(fr->safe_for_sender(thread), "Safety check");
+      *fr = fr->java_sender();
+    }
+  } else {
+    // More complex code with compiled code.
+    assert(!Interpreter::contains(pc), "Interpreted methods should have been handled above");
+    CodeBlob* cb = CodeCache::find_blob(pc);
+    if (cb == NULL || !cb->is_nmethod() || cb->is_frame_complete_at(pc)) {
+      // Not sure where the pc points to, fallback to default
+      // stack overflow handling. In compiled code, we bang before
+      // the frame is complete.
+      return false;
+    } else {
+      intptr_t* fp = os::Linux::ucontext_get_fp(uc);
+      intptr_t* sp = os::Linux::ucontext_get_sp(uc);
+      *fr = frame(sp, (address)*sp);
+      if (!fr->is_java_frame()) {
+        assert(fr->safe_for_sender(thread), "Safety check");
+        assert(!fr->is_first_frame(), "Safety check");
+        *fr = fr->java_sender();
+      }
+    }
+  }
+  assert(fr->is_java_frame(), "Safety check");
+  return true;
+}
+
 frame os::get_sender_for_C_frame(frame* fr) {
   if (*fr->sp() == 0) {
     // fr is the last C frame.
@@ -279,13 +315,31 @@
       if (thread->on_local_stack(addr)) {
         // stack overflow
         if (thread->in_stack_yellow_reserved_zone(addr)) {
-          thread->disable_stack_yellow_reserved_zone();
           if (thread->thread_state() == _thread_in_Java) {
+            if (thread->in_stack_reserved_zone(addr)) {
+              frame fr;
+              if (os::Linux::get_frame_at_stack_banging_point(thread, uc, &fr)) {
+                assert(fr.is_java_frame(), "Must be a Javac frame");
+                frame activation =
+                  SharedRuntime::look_for_reserved_stack_annotated_method(thread, fr);
+                if (activation.sp() != NULL) {
+                  thread->disable_stack_reserved_zone();
+                  if (activation.is_interpreted_frame()) {
+                    thread->set_reserved_stack_activation((address)activation.fp());
+                  } else {
+                    thread->set_reserved_stack_activation((address)activation.unextended_sp());
+                  }
+                  return 1;
+                }
+              }
+            }
             // Throw a stack overflow exception.
             // Guard pages will be reenabled while unwinding the stack.
+            thread->disable_stack_yellow_reserved_zone();
             stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW);
           } else {
             // Thread was in the vm or native code. Return and try to finish.
+            thread->disable_stack_yellow_reserved_zone();
             return 1;
           }
         } else if (thread->in_stack_red_zone(addr)) {
--- a/hotspot/src/share/vm/adlc/formssel.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/share/vm/adlc/formssel.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -650,6 +650,7 @@
   if( strcmp(_matrule->_opType,"MemBarReleaseLock") == 0 ) return true;
   if( strcmp(_matrule->_opType,"MemBarAcquireLock") == 0 ) return true;
   if( strcmp(_matrule->_opType,"MemBarStoreStore") == 0 ) return true;
+  if( strcmp(_matrule->_opType,"MemBarVolatile") == 0 ) return true;
   if( strcmp(_matrule->_opType,"StoreFence") == 0 ) return true;
   if( strcmp(_matrule->_opType,"LoadFence") == 0 ) return true;
 
--- a/hotspot/src/share/vm/aot/aotCodeHeap.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/share/vm/aot/aotCodeHeap.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -25,6 +25,7 @@
 
 #include "aot/aotCodeHeap.hpp"
 #include "aot/aotLoader.hpp"
+#include "classfile/javaAssertions.hpp"
 #include "gc/g1/heapRegion.hpp"
 #include "gc/shared/gcLocker.hpp"
 #include "interpreter/abstractInterpreter.hpp"
@@ -294,6 +295,8 @@
     // When the AOT compiler compiles something big we fail to generate metadata
     // in CodeInstaller::gather_metadata. In that case the scopes_pcs_begin == scopes_pcs_end.
     // In all successful cases we always have 2 entries of scope pcs.
+    log_info(aot, class, resolve)("Failed to load %s (no metadata available)", mh->name_and_sig_as_C_string());
+    _code_to_aot[code_id]._state = invalid;
     return;
   }
 
@@ -536,6 +539,7 @@
     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_heap_end_address", address, (heap->supports_inline_contig_alloc() ? heap->end_addr() : NULL));
     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_polling_page", address, os::get_polling_page());
     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_narrow_klass_base_address", address, Universe::narrow_klass_base());
+    SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_narrow_oop_base_address", address, Universe::narrow_oop_base());
     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_log_of_heap_region_grain_bytes", int, HeapRegion::LogOfHRGrainBytes);
     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_inline_contiguous_allocation_supported", bool, heap->supports_inline_contig_alloc());
     link_shared_runtime_symbols();
@@ -706,6 +710,12 @@
     return false;
   }
 
+  if (_lib->config()->_omitAssertions && JavaAssertions::enabled(kh->name()->as_C_string(), kh->class_loader() == NULL)) {
+    log_trace(aot, class, load)("class  %s  in  %s does not have java assertions in compiled code, but assertions are enabled for this execution.", kh->internal_name(), _lib->name());
+    sweep_dependent_methods(klass_data);
+    return false;
+  }
+
   NOT_PRODUCT( aot_klasses_found++; )
 
   log_trace(aot, class, load)("found  %s  in  %s for classloader %p tid=" INTPTR_FORMAT, kh->internal_name(), _lib->name(), kh->class_loader_data(), p2i(thread));
@@ -714,7 +724,7 @@
   // Set klass's Resolve (second) got cell.
   _metaspace_got[klass_data->_got_index] = kh();
 
-  // Initialize global symbols of the DSO to the correspondingVM symbol values.
+  // Initialize global symbols of the DSO to the corresponding VM symbol values.
   link_global_lib_symbols();
 
   int methods_offset = klass_data->_compiled_methods_offset;
--- a/hotspot/src/share/vm/aot/aotCodeHeap.hpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/share/vm/aot/aotCodeHeap.hpp	Fri Jan 13 18:26:34 2017 +0100
@@ -88,7 +88,7 @@
 } AOTHeader;
 
 typedef struct {
-  enum { CONFIG_SIZE = 11 + 7 * 4 };
+  enum { CONFIG_SIZE = 12 + 7 * 4 };
   int _config_size;
   int _narrowOopShift;
   int _narrowKlassShift;
@@ -108,6 +108,7 @@
   bool _tieredAOT;
   bool _enableContended;
   bool _restrictContended;
+  bool _omitAssertions;
 } AOTConfiguration;
 
 class AOTLib : public CHeapObj<mtCode> {
--- a/hotspot/src/share/vm/ci/bcEscapeAnalyzer.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/share/vm/ci/bcEscapeAnalyzer.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -895,8 +895,32 @@
           ciMethod* target = s.get_method(ignored_will_link, &declared_signature);
           ciKlass*  holder = s.get_declared_method_holder();
           assert(declared_signature != NULL, "cannot be null");
-          // Push appendix argument, if one.
-          if (s.has_appendix()) {
+          // If the current bytecode has an attached appendix argument,
+          // push an unknown object to represent that argument. (Analysis
+          // of dynamic call sites, especially invokehandle calls, needs
+          // the appendix argument on the stack, in addition to "regular" arguments
+          // pushed onto the stack by bytecode instructions preceding the call.)
+          //
+          // The escape analyzer does _not_ use the ciBytecodeStream::has_appendix(s)
+          // method to determine whether the current bytecode has an appendix argument.
+          // The has_appendix() method obtains the appendix from the
+          // ConstantPoolCacheEntry::_f1 field, which can happen concurrently with
+          // resolution of dynamic call sites. Callees in the
+          // ciBytecodeStream::get_method() call above also access the _f1 field;
+          // interleaving the get_method() and has_appendix() calls in the current
+          // method with call site resolution can lead to an inconsistent view of
+          // the current method's argument count. In particular, some interleaving(s)
+          // can cause the method's argument count to not include the appendix, which
+          // then leads to stack over-/underflow in the escape analyzer.
+          //
+          // Instead of pushing the argument if has_appendix() is true, the escape analyzer
+          // pushes an appendix for all call sites targeted by invokedynamic and invokehandle
+          // instructions, except if the call site is the _invokeBasic intrinsic
+          // (that intrinsic is always targeted by an invokehandle instruction but does
+          // not have an appendix argument).
+          if (target->is_loaded() &&
+              Bytecodes::has_optional_appendix(s.cur_bc_raw()) &&
+              target->intrinsic_id() != vmIntrinsics::_invokeBasic) {
             state.apush(unknown_obj);
           }
           // Pass in raw bytecode because we need to see invokehandle instructions.
--- a/hotspot/src/share/vm/ci/ciMethod.hpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/share/vm/ci/ciMethod.hpp	Fri Jan 13 18:26:34 2017 +0100
@@ -136,15 +136,19 @@
     check_is_loaded();
     return _signature->size() + (_flags.is_static() ? 0 : 1);
   }
-  // Report the number of elements on stack when invoking this method.
-  // This is different than the regular arg_size because invokedynamic
-  // has an implicit receiver.
+  // Report the number of elements on stack when invoking the current method.
+  // If the method is loaded, arg_size() gives precise information about the
+  // number of stack elements (using the method's signature and its flags).
+  // However, if the method is not loaded, the number of stack elements must
+  // be determined differently, as the method's flags are not yet available.
+  // The invoke_arg_size() method assumes in that case that all bytecodes except
+  // invokestatic and invokedynamic have a receiver that is also pushed onto the
+  // stack by the caller of the current method.
   int invoke_arg_size(Bytecodes::Code code) const {
     if (is_loaded()) {
       return arg_size();
     } else {
       int arg_size = _signature->size();
-      // Add a receiver argument, maybe:
       if (code != Bytecodes::_invokestatic &&
           code != Bytecodes::_invokedynamic) {
         arg_size++;
--- a/hotspot/src/share/vm/classfile/classLoaderData.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/share/vm/classfile/classLoaderData.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -94,7 +94,7 @@
   _metaspace(NULL), _unloading(false), _klasses(NULL),
   _modules(NULL), _packages(NULL),
   _claimed(0), _jmethod_ids(NULL), _handles(NULL), _deallocate_list(NULL),
-  _next(NULL), _dependencies(dependencies), _shared_class_loader_id(-1),
+  _next(NULL), _dependencies(dependencies),
   _metaspace_lock(new Mutex(Monitor::leaf+1, "Metaspace allocation lock", true,
                             Monitor::_safepoint_check_never)) {
   TRACE_INIT_ID(this);
--- a/hotspot/src/share/vm/classfile/classLoaderData.hpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/share/vm/classfile/classLoaderData.hpp	Fri Jan 13 18:26:34 2017 +0100
@@ -204,9 +204,6 @@
   // Support for walking class loader data objects
   ClassLoaderData* _next; /// Next loader_datas created
 
-  // CDS
-  int _shared_class_loader_id;
-
   // ReadOnly and ReadWrite metaspaces (static because only on the null
   // class loader for now).
   static Metaspace* _ro_metaspace;
@@ -338,15 +335,6 @@
   Metaspace* rw_metaspace();
   void initialize_shared_metaspaces();
 
-  int shared_class_loader_id() const {
-    return _shared_class_loader_id;
-  }
-  void set_shared_class_loader_id(int id) {
-    assert(id >= 0, "sanity");
-    assert(_shared_class_loader_id <0, "cannot be assigned more than once");
-    _shared_class_loader_id = id;
-  }
-
   TRACE_DEFINE_TRACE_ID_METHODS;
 };
 
--- a/hotspot/src/share/vm/classfile/javaClasses.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/share/vm/classfile/javaClasses.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -163,8 +163,8 @@
 
   Klass* k = SystemDictionary::String_klass();
   compute_offset(value_offset,           k, vmSymbols::value_name(),  vmSymbols::byte_array_signature());
-  compute_optional_offset(hash_offset,   k, vmSymbols::hash_name(),   vmSymbols::int_signature());
-  compute_optional_offset(coder_offset,  k, vmSymbols::coder_name(),  vmSymbols::byte_signature());
+  compute_offset(hash_offset,            k, vmSymbols::hash_name(),   vmSymbols::int_signature());
+  compute_offset(coder_offset,           k, vmSymbols::coder_name(),  vmSymbols::byte_signature());
 
   initialized = true;
 }
@@ -3977,12 +3977,8 @@
   // java.lang.String
 
   CHECK_OFFSET("java/lang/String", java_lang_String, value, "[B");
-  if (java_lang_String::has_hash_field()) {
-    CHECK_OFFSET("java/lang/String", java_lang_String, hash, "I");
-  }
-  if (java_lang_String::has_coder_field()) {
-    CHECK_OFFSET("java/lang/String", java_lang_String, coder, "B");
-  }
+  CHECK_OFFSET("java/lang/String", java_lang_String, hash, "I");
+  CHECK_OFFSET("java/lang/String", java_lang_String, coder, "B");
 
   // java.lang.Class
 
--- a/hotspot/src/share/vm/classfile/javaClasses.hpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/share/vm/classfile/javaClasses.hpp	Fri Jan 13 18:26:34 2017 +0100
@@ -81,15 +81,6 @@
   static Handle create_from_platform_dependent_str(const char* str, TRAPS);
   static Handle char_converter(Handle java_string, jchar from_char, jchar to_char, TRAPS);
 
-  static bool has_hash_field()  {
-    assert(initialized, "Must be initialized");
-    return (hash_offset > 0);
-  }
-  static bool has_coder_field()  {
-    assert(initialized, "Must be initialized");
-    return (coder_offset > 0);
-  }
-
   static void set_compact_strings(bool value);
 
   static int value_offset_in_bytes()  {
--- a/hotspot/src/share/vm/classfile/javaClasses.inline.hpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/share/vm/classfile/javaClasses.inline.hpp	Fri Jan 13 18:26:34 2017 +0100
@@ -30,10 +30,8 @@
 #include "oops/oopsHierarchy.hpp"
 
 void java_lang_String::set_coder(oop string, jbyte coder) {
-  assert(initialized, "Must be initialized");
-  if (coder_offset > 0) {
-    string->byte_field_put(coder_offset, coder);
-  }
+  assert(initialized && (coder_offset > 0), "Must be initialized");
+  string->byte_field_put(coder_offset, coder);
 }
 
 void java_lang_String::set_value_raw(oop string, typeArrayOop buffer) {
@@ -61,15 +59,11 @@
   return java_string->int_field(hash_offset);
 }
 bool java_lang_String::is_latin1(oop java_string) {
-  assert(initialized, "Must be initialized");
+  assert(initialized && (coder_offset > 0), "Must be initialized");
   assert(is_instance(java_string), "must be java_string");
-  if (coder_offset > 0) {
-    jbyte coder = java_string->byte_field(coder_offset);
-    assert(CompactStrings || coder == CODER_UTF16, "Must be UTF16 without CompactStrings");
-    return coder == CODER_LATIN1;
-  } else {
-    return false;
-  }
+  jbyte coder = java_string->byte_field(coder_offset);
+  assert(CompactStrings || coder == CODER_UTF16, "Must be UTF16 without CompactStrings");
+  return coder == CODER_LATIN1;
 }
 int java_lang_String::length(oop java_string) {
   assert(initialized, "Must be initialized");
--- a/hotspot/src/share/vm/classfile/systemDictionaryShared.hpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/share/vm/classfile/systemDictionaryShared.hpp	Fri Jan 13 18:26:34 2017 +0100
@@ -29,7 +29,6 @@
 #include "classfile/dictionary.hpp"
 
 class ClassFileStream;
-class SerializeClosure;
 
 class SystemDictionaryShared: public SystemDictionary {
 public:
@@ -79,8 +78,6 @@
     return NULL;
   }
 
-  static void serialize(SerializeClosure* soc) {}
-
   // The (non-application) CDS implementation supports only classes in the boot
   // class loader, which ensures that the verification constraints are the same
   // during archive creation time and runtime. Thus we can do the constraint checks
--- a/hotspot/src/share/vm/code/codeCache.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/share/vm/code/codeCache.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -149,16 +149,17 @@
   size_t total_size = non_nmethod_size + profiled_size + non_profiled_size;
   // Prepare error message
   const char* error = "Invalid code heap sizes";
-  err_msg message("NonNMethodCodeHeapSize (%zuK) + ProfiledCodeHeapSize (%zuK) + NonProfiledCodeHeapSize (%zuK) = %zuK",
+  err_msg message("NonNMethodCodeHeapSize (" SIZE_FORMAT "K) + ProfiledCodeHeapSize (" SIZE_FORMAT "K)"
+                  " + NonProfiledCodeHeapSize (" SIZE_FORMAT "K) = " SIZE_FORMAT "K",
           non_nmethod_size/K, profiled_size/K, non_profiled_size/K, total_size/K);
 
   if (total_size > cache_size) {
     // Some code heap sizes were explicitly set: total_size must be <= cache_size
-    message.append(" is greater than ReservedCodeCacheSize (%zuK).", cache_size/K);
+    message.append(" is greater than ReservedCodeCacheSize (" SIZE_FORMAT "K).", cache_size/K);
     vm_exit_during_initialization(error, message);
   } else if (all_set && total_size != cache_size) {
     // All code heap sizes were explicitly set: total_size must equal cache_size
-    message.append(" is not equal to ReservedCodeCacheSize (%zuK).", cache_size/K);
+    message.append(" is not equal to ReservedCodeCacheSize (" SIZE_FORMAT "K).", cache_size/K);
     vm_exit_during_initialization(error, message);
   }
 }
@@ -267,7 +268,7 @@
   uint min_code_cache_size = CodeCacheMinimumUseSpace DEBUG_ONLY(* 3);
   if (non_nmethod_size < (min_code_cache_size + code_buffers_size)) {
     vm_exit_during_initialization(err_msg(
-        "Not enough space in non-nmethod code heap to run VM: %zuK < %zuK",
+        "Not enough space in non-nmethod code heap to run VM: " SIZE_FORMAT "K < " SIZE_FORMAT "K",
         non_nmethod_size/K, (min_code_cache_size + code_buffers_size)/K));
   }
 
--- a/hotspot/src/share/vm/gc/g1/g1BiasedArray.hpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/share/vm/gc/g1/g1BiasedArray.hpp	Fri Jan 13 18:26:34 2017 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2016, 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
@@ -69,12 +69,12 @@
   void initialize(HeapWord* bottom, HeapWord* end, size_t target_elem_size_in_bytes, size_t mapping_granularity_in_bytes) {
     assert(mapping_granularity_in_bytes > 0, "just checking");
     assert(is_power_of_2(mapping_granularity_in_bytes),
-           "mapping granularity must be power of 2, is %zd", mapping_granularity_in_bytes);
+           "mapping granularity must be power of 2, is " SIZE_FORMAT, mapping_granularity_in_bytes);
     assert((uintptr_t)bottom % mapping_granularity_in_bytes == 0,
-           "bottom mapping area address must be a multiple of mapping granularity %zd, is  " PTR_FORMAT,
+           "bottom mapping area address must be a multiple of mapping granularity " SIZE_FORMAT ", is  " PTR_FORMAT,
            mapping_granularity_in_bytes, p2i(bottom));
     assert((uintptr_t)end % mapping_granularity_in_bytes == 0,
-           "end mapping area address must be a multiple of mapping granularity %zd, is " PTR_FORMAT,
+           "end mapping area address must be a multiple of mapping granularity " SIZE_FORMAT ", is " PTR_FORMAT,
            mapping_granularity_in_bytes, p2i(end));
     size_t num_target_elems = pointer_delta(end, bottom, mapping_granularity_in_bytes);
     idx_t bias = (uintptr_t)bottom / mapping_granularity_in_bytes;
--- a/hotspot/src/share/vm/jvmci/jvmciCodeInstaller.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/share/vm/jvmci/jvmciCodeInstaller.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -554,7 +554,7 @@
   _constants = buffer.consts();
 
   initialize_fields(target(), JNIHandles::resolve(compiled_code_obj), CHECK_OK);
-  JVMCIEnv::CodeInstallResult result = initialize_buffer(buffer, CHECK_OK);
+  JVMCIEnv::CodeInstallResult result = initialize_buffer(buffer, false, CHECK_OK);
   if (result != JVMCIEnv::ok) {
     return result;
   }
@@ -587,7 +587,7 @@
   _constants = buffer.consts();
 
   initialize_fields(target(), JNIHandles::resolve(compiled_code_obj), CHECK_OK);
-  JVMCIEnv::CodeInstallResult result = initialize_buffer(buffer, CHECK_OK);
+  JVMCIEnv::CodeInstallResult result = initialize_buffer(buffer, true, CHECK_OK);
   if (result != JVMCIEnv::ok) {
     return result;
   }
@@ -726,7 +726,7 @@
 }
 
 // perform data and call relocation on the CodeBuffer
-JVMCIEnv::CodeInstallResult CodeInstaller::initialize_buffer(CodeBuffer& buffer, TRAPS) {
+JVMCIEnv::CodeInstallResult CodeInstaller::initialize_buffer(CodeBuffer& buffer, bool check_size, TRAPS) {
   HandleMark hm;
   objArrayHandle sites = this->sites();
   int locs_buffer_size = sites->length() * (relocInfo::length_limit + sizeof(relocInfo));
@@ -738,7 +738,7 @@
   int stubs_size = estimate_stubs_size(CHECK_OK);
   int total_size = round_to(_code_size, buffer.insts()->alignment()) + round_to(_constants_size, buffer.consts()->alignment()) + round_to(stubs_size, buffer.stubs()->alignment());
 
-  if (total_size > JVMCINMethodSizeLimit) {
+  if (check_size && total_size > JVMCINMethodSizeLimit) {
     return JVMCIEnv::code_too_large;
   }
 
@@ -1258,6 +1258,7 @@
       case HEAP_TOP_ADDRESS:
       case HEAP_END_ADDRESS:
       case NARROW_KLASS_BASE_ADDRESS:
+      case NARROW_OOP_BASE_ADDRESS:
       case CRC_TABLE_ADDRESS:
       case LOG_OF_HEAP_REGION_GRAIN_BYTES:
       case INLINE_CONTIGUOUS_ALLOCATION_SUPPORTED:
--- a/hotspot/src/share/vm/jvmci/jvmciCodeInstaller.hpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/share/vm/jvmci/jvmciCodeInstaller.hpp	Fri Jan 13 18:26:34 2017 +0100
@@ -133,9 +133,10 @@
     HEAP_TOP_ADDRESS                       = 17,
     HEAP_END_ADDRESS                       = 18,
     NARROW_KLASS_BASE_ADDRESS              = 19,
-    CRC_TABLE_ADDRESS                      = 20,
-    LOG_OF_HEAP_REGION_GRAIN_BYTES         = 21,
-    INLINE_CONTIGUOUS_ALLOCATION_SUPPORTED = 22,
+    NARROW_OOP_BASE_ADDRESS                = 20,
+    CRC_TABLE_ADDRESS                      = 21,
+    LOG_OF_HEAP_REGION_GRAIN_BYTES         = 22,
+    INLINE_CONTIGUOUS_ALLOCATION_SUPPORTED = 23,
     INVOKE_INVALID                         = -1
   };
 
@@ -227,7 +228,7 @@
   int estimate_stubs_size(TRAPS);
 
   // perform data and call relocation on the CodeBuffer
-  JVMCIEnv::CodeInstallResult initialize_buffer(CodeBuffer& buffer, TRAPS);
+  JVMCIEnv::CodeInstallResult initialize_buffer(CodeBuffer& buffer, bool check_size, TRAPS);
 
   void assumption_NoFinalizableSubclass(Handle assumption);
   void assumption_ConcreteSubtype(Handle assumption);
--- a/hotspot/src/share/vm/jvmci/vmStructs_jvmci.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/share/vm/jvmci/vmStructs_jvmci.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -429,6 +429,7 @@
   declare_constant(CodeInstaller::HEAP_TOP_ADDRESS)                       \
   declare_constant(CodeInstaller::HEAP_END_ADDRESS)                       \
   declare_constant(CodeInstaller::NARROW_KLASS_BASE_ADDRESS)              \
+  declare_constant(CodeInstaller::NARROW_OOP_BASE_ADDRESS)                \
   declare_constant(CodeInstaller::CRC_TABLE_ADDRESS)                      \
   declare_constant(CodeInstaller::LOG_OF_HEAP_REGION_GRAIN_BYTES)         \
   declare_constant(CodeInstaller::INLINE_CONTIGUOUS_ALLOCATION_SUPPORTED) \
--- a/hotspot/src/share/vm/logging/logConfiguration.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/share/vm/logging/logConfiguration.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -478,7 +478,7 @@
 
 void LogConfiguration::print_command_line_help(FILE* out) {
   jio_fprintf(out, "-Xlog Usage: -Xlog[:[what][:[output][:[decorators][:output-options]]]]\n"
-              "\t where 'what' is a combination of tags and levels on the form tag1[+tag2...][*][=level][,...]\n"
+              "\t where 'what' is a combination of tags and levels of the form tag1[+tag2...][*][=level][,...]\n"
               "\t Unless wildcard (*) is specified, only log messages tagged with exactly the tags specified will be matched.\n\n");
 
   jio_fprintf(out, "Available log levels:\n");
@@ -514,6 +514,14 @@
               " -Xlog:gc\n"
               "\t Log messages tagged with 'gc' tag using 'info' level to stdout, with default decorations.\n\n"
 
+              " -Xlog:gc,safepoint\n"
+              "\t Log messages tagged either with 'gc' or 'safepoint' tags, both using 'info' level, to stdout, with default decorations.\n"
+              "\t (Messages tagged with both 'gc' and 'safepoint' will not be logged.)\n\n"
+
+              " -Xlog:gc+ref=debug\n"
+              "\t Log messages tagged with both 'gc' and 'ref' tags, using 'debug' level, to stdout, with default decorations.\n"
+              "\t (Messages tagged only with one of the two tags will not be logged.)\n\n"
+
               " -Xlog:gc=debug:file=gc.txt:none\n"
               "\t Log messages tagged with 'gc' tag using 'debug' level to file 'gc.txt' with no decorations.\n\n"
 
--- a/hotspot/src/share/vm/memory/metaspaceShared.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/share/vm/memory/metaspaceShared.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -145,10 +145,6 @@
   StringTable::serialize(soc, string_space, space_size);
   soc->do_tag(--tag);
 
-  // Dump/restore the misc information for system dictionary
-  SystemDictionaryShared::serialize(soc);
-  soc->do_tag(--tag);
-
   soc->do_tag(666);
 }
 
--- a/hotspot/src/share/vm/oops/instanceKlass.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/share/vm/oops/instanceKlass.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -2139,8 +2139,6 @@
 }
 
 void InstanceKlass::release_C_heap_structures() {
-  assert(!this->is_shared(), "should not be called for a shared class");
-
   // Can't release the constant pool here because the constant pool can be
   // deallocated separately from the InstanceKlass for default methods and
   // redefine classes.
@@ -2191,7 +2189,7 @@
   }
 
   // deallocate the cached class file
-  if (_cached_class_file != NULL) {
+  if (_cached_class_file != NULL && !MetaspaceShared::is_in_shared_space(_cached_class_file)) {
     os::free(_cached_class_file);
     _cached_class_file = NULL;
   }
--- a/hotspot/src/share/vm/opto/graphKit.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/share/vm/opto/graphKit.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -4348,20 +4348,16 @@
 }
 
 Node* GraphKit::load_String_coder(Node* ctrl, Node* str) {
-  if (java_lang_String::has_coder_field()) {
-    if (!CompactStrings) {
-      return intcon(java_lang_String::CODER_UTF16);
-    }
-    int coder_offset = java_lang_String::coder_offset_in_bytes();
-    const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
-                                                       false, NULL, 0);
-    const TypePtr* coder_field_type = string_type->add_offset(coder_offset);
-    int coder_field_idx = C->get_alias_index(coder_field_type);
-    return make_load(ctrl, basic_plus_adr(str, str, coder_offset),
-                     TypeInt::BYTE, T_BYTE, coder_field_idx, MemNode::unordered);
-  } else {
-    return intcon(0); // false
+  if (!CompactStrings) {
+    return intcon(java_lang_String::CODER_UTF16);
   }
+  int coder_offset = java_lang_String::coder_offset_in_bytes();
+  const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
+                                                     false, NULL, 0);
+  const TypePtr* coder_field_type = string_type->add_offset(coder_offset);
+  int coder_field_idx = C->get_alias_index(coder_field_type);
+  return make_load(ctrl, basic_plus_adr(str, str, coder_offset),
+                   TypeInt::BYTE, T_BYTE, coder_field_idx, MemNode::unordered);
 }
 
 void GraphKit::store_String_value(Node* ctrl, Node* str, Node* value) {
--- a/hotspot/src/share/vm/opto/library_call.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/share/vm/opto/library_call.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -6335,7 +6335,7 @@
 
 //------------------------------get_key_start_from_aescrypt_object-----------------------
 Node * LibraryCallKit::get_key_start_from_aescrypt_object(Node *aescrypt_object) {
-#ifdef PPC64
+#if defined(PPC64) || defined(S390)
   // MixColumns for decryption can be reduced by preprocessing MixColumns with round keys.
   // Intel's extention is based on this optimization and AESCrypt generates round keys by preprocessing MixColumns.
   // However, ppc64 vncipher processes MixColumns and requires the same round keys with encryption.
--- a/hotspot/src/share/vm/prims/jniCheck.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/share/vm/prims/jniCheck.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -238,8 +238,8 @@
   size_t live_handles = handles->get_number_of_live_handles();
   if (live_handles > planned_capacity) {
     IN_VM(
-      tty->print_cr("WARNING: JNI local refs: %zu, exceeds capacity: %zu",
-          live_handles, planned_capacity);
+      tty->print_cr("WARNING: JNI local refs: " SIZE_FORMAT ", exceeds capacity: " SIZE_FORMAT,
+                    live_handles, planned_capacity);
       thr->print_stack();
     )
     // Complain just the once, reset to current + warn threshold
--- a/hotspot/src/share/vm/prims/jvmtiEnter.xsl	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/share/vm/prims/jvmtiEnter.xsl	Fri Jan 13 18:26:34 2017 +0100
@@ -1246,7 +1246,7 @@
   <xsl:param name="name"/>
   <xsl:text> </xsl:text>
   <xsl:value-of select="$name"/>
-  <xsl:text>=0x%zx</xsl:text>
+  <xsl:text>=" SIZE_FORMAT_HEX "</xsl:text>
 </xsl:template>
 
 <xsl:template match="jfloat|jdouble" mode="traceInFormat">
--- a/hotspot/src/share/vm/runtime/arguments.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/share/vm/runtime/arguments.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -1854,6 +1854,34 @@
   }
 }
 
+#if INCLUDE_JVMCI
+void Arguments::set_jvmci_specific_flags() {
+  if (UseJVMCICompiler) {
+    if (FLAG_IS_DEFAULT(TypeProfileWidth)) {
+      FLAG_SET_DEFAULT(TypeProfileWidth, 8);
+    }
+    if (FLAG_IS_DEFAULT(OnStackReplacePercentage)) {
+      FLAG_SET_DEFAULT(OnStackReplacePercentage, 933);
+    }
+    if (FLAG_IS_DEFAULT(ReservedCodeCacheSize)) {
+      FLAG_SET_DEFAULT(ReservedCodeCacheSize, 64*M);
+    }
+    if (FLAG_IS_DEFAULT(InitialCodeCacheSize)) {
+      FLAG_SET_DEFAULT(InitialCodeCacheSize, 16*M);
+    }
+    if (FLAG_IS_DEFAULT(MetaspaceSize)) {
+      FLAG_SET_DEFAULT(MetaspaceSize, 12*M);
+    }
+    if (FLAG_IS_DEFAULT(NewSizeThreadIncrease)) {
+      FLAG_SET_DEFAULT(NewSizeThreadIncrease, 4*K);
+    }
+    if (FLAG_IS_DEFAULT(TypeProfileLevel)) {
+      FLAG_SET_DEFAULT(TypeProfileLevel, 0);
+    }
+  }
+}
+#endif
+
 void Arguments::set_ergonomics_flags() {
   select_gc();
 
@@ -2463,14 +2491,6 @@
       warning("forcing ScavengeRootsInCode non-zero because JVMCI is enabled");
       ScavengeRootsInCode = 1;
     }
-    if (FLAG_IS_DEFAULT(TypeProfileLevel)) {
-      TypeProfileLevel = 0;
-    }
-    if (UseJVMCICompiler) {
-      if (FLAG_IS_DEFAULT(TypeProfileWidth)) {
-        TypeProfileWidth = 8;
-      }
-    }
   }
 #endif
 
@@ -4420,6 +4440,10 @@
   // Set flags based on ergonomics.
   set_ergonomics_flags();
 
+#if INCLUDE_JVMCI
+  set_jvmci_specific_flags();
+#endif
+
   set_shared_spaces_flags();
 
   // Check the GC selections again.
--- a/hotspot/src/share/vm/runtime/arguments.hpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/share/vm/runtime/arguments.hpp	Fri Jan 13 18:26:34 2017 +0100
@@ -638,6 +638,7 @@
 #if INCLUDE_JVMCI
   // Check consistency of jvmci vm argument settings.
   static bool check_jvmci_args_consistency();
+  static void set_jvmci_specific_flags();
 #endif
   // Check for consistency in the selection of the garbage collector.
   static bool check_gc_consistency();        // Check user-selected gc
--- a/hotspot/src/share/vm/runtime/globals.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/share/vm/runtime/globals.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -469,14 +469,18 @@
   }
 
   if (!printRanges) {
+    // Use some named constants to make code more readable.
+    const unsigned int nSpaces    = 10;
+    const unsigned int maxFlagLen = 40 + nSpaces;
+
     // The print below assumes that the flag name is 40 characters or less.
     // This works for most flags, but there are exceptions. Our longest flag
     // name right now is UseAdaptiveGenerationSizePolicyAtMajorCollection and
     // its minor collection buddy. These are 48 characters. We use a buffer of
-    // 10 spaces below to adjust the space between the flag value and the
+    // nSpaces spaces below to adjust the space between the flag value and the
     // column of flag type and origin that is printed in the end of the line.
-    char spaces[10 + 1] = "          ";
-    st->print("%9s %-40s = ", _type, _name);
+    char spaces[nSpaces + 1] = "          ";
+    st->print("%9s %-*s = ", _type, maxFlagLen-nSpaces, _name);
 
     if (is_bool()) {
       st->print("%-20s", get_bool() ? "true" : "false");
@@ -509,9 +513,12 @@
       }
       else st->print("%-20s", "");
     }
-    assert(strlen(_name) < 50, "Flag name is longer than expected");
-    spaces[50 - MAX2((size_t)40, strlen(_name))] = '\0';
-    st->print("%s", spaces);
+    // Make sure we do not punch a '\0' at a negative char array index.
+    unsigned int nameLen = (unsigned int)strlen(_name);
+    if (nameLen <= maxFlagLen) {
+      spaces[maxFlagLen - MAX2(maxFlagLen-nSpaces, nameLen)] = '\0';
+      st->print("%s", spaces);
+    }
     print_kind_and_origin(st);
 
 #ifndef PRODUCT
--- a/hotspot/src/share/vm/services/diagnosticCommand.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/share/vm/services/diagnosticCommand.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -292,7 +292,7 @@
       char *opt = (char *)os::malloc(opt_len, mtInternal);
       if (opt == NULL) {
         output()->print_cr("JVMTI agent attach failed: "
-                           "Could not allocate %zu bytes for argument.",
+                           "Could not allocate " SIZE_FORMAT " bytes for argument.",
                            opt_len);
         return;
       }
--- a/hotspot/src/share/vm/utilities/copy.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/src/share/vm/utilities/copy.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -214,7 +214,7 @@
     case 2: do_conjoint_swap<uint16_t,D>(src, dst, byte_count); break;
     case 4: do_conjoint_swap<uint32_t,D>(src, dst, byte_count); break;
     case 8: do_conjoint_swap<uint64_t,D>(src, dst, byte_count); break;
-    default: guarantee(false, "do_conjoint_swap: Invalid elem_size %zd\n", elem_size);
+    default: guarantee(false, "do_conjoint_swap: Invalid elem_size " SIZE_FORMAT "\n", elem_size);
     }
   }
 };
--- a/hotspot/test/ProblemList.txt	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/test/ProblemList.txt	Fri Jan 13 18:26:34 2017 +0100
@@ -55,7 +55,6 @@
 
 gc/g1/humongousObjects/objectGraphTest/TestObjectGraphAfterGC.java 8156755 generic-all
 gc/survivorAlignment/TestPromotionToSurvivor.java 8129886 generic-all
-gc/stress/TestStressG1Humongous.java 8171045 generic-all
 
 #############################################################################
 
@@ -78,5 +77,7 @@
 
 # :hotspot_misc
 
+testlibrary_tests/ctw/JarDirTest.java 8172457 windows-all
+
 #############################################################################
 
--- a/hotspot/test/TEST.ROOT	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/test/TEST.ROOT	Fri Jan 13 18:26:34 2017 +0100
@@ -46,6 +46,7 @@
     vm.gc.Parallel \
     vm.gc.ConcMarkSweep \
     vm.jvmci \
+    vm.cpu.features \
     vm.debug
 
 # Tests using jtreg 4.2 b04 features
--- a/hotspot/test/compiler/aot/AotCompiler.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/test/compiler/aot/AotCompiler.java	Fri Jan 13 18:26:34 2017 +0100
@@ -93,6 +93,7 @@
             }
         }
         List<String> args = new ArrayList<>();
+        args.add("--compile-with-assertions");
         args.add("--output");
         args.add(libName);
         if (file != null) {
--- a/hotspot/test/compiler/aot/RecompilationTest.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/test/compiler/aot/RecompilationTest.java	Fri Jan 13 18:26:34 2017 +0100
@@ -33,6 +33,7 @@
  * @run main compiler.aot.AotCompiler -libname libRecompilationTest1.so
  *     -class compiler.whitebox.SimpleTestCaseHelper
  *     -extraopt -Dgraal.TieredAOT=true -extraopt -Dgraal.ProfileSimpleMethods=true
+ *     -extraopt -Dgraal.ProbabilisticProfiling=false
  *     -extraopt -XX:+UnlockDiagnosticVMOptions -extraopt -XX:+WhiteBoxAPI -extraopt -Xbootclasspath/a:.
  *     -extraopt -XX:-UseCompressedOops
  *     -extraopt -XX:CompileCommand=dontinline,compiler.whitebox.SimpleTestCaseHelper::*
--- a/hotspot/test/compiler/aot/cli/jaotc/JaotcTestHelper.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/test/compiler/aot/cli/jaotc/JaotcTestHelper.java	Fri Jan 13 18:26:34 2017 +0100
@@ -44,6 +44,7 @@
         for (String vmOpt : Utils.getTestJavaOpts()) {
             launcher.addVMArg(vmOpt);
         }
+        launcher.addToolArg("--compile-with-assertions");
         for (String arg : args) {
             launcher.addToolArg(arg);
         }
--- a/hotspot/test/compiler/c1/CanonicalizeArrayLength.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/test/compiler/c1/CanonicalizeArrayLength.java	Fri Jan 13 18:26:34 2017 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug 8150102 8150514 8150534
+ * @bug 8150102 8150514 8150534 8171435
  * @summary C1 crashes in Canonicalizer::do_ArrayLength() after fix for JDK-8150102
  *
  * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:+UnlockDiagnosticVMOptions
@@ -31,7 +31,7 @@
  *                   -XX:-BackgroundCompilation
  *                   compiler.c1.CanonicalizeArrayLength
  * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:+UnlockDiagnosticVMOptions
- *                   -XX:CompileThreshold=100 -XX:+TieredCompilation -XX:TieredStopAtLevel=1
+ *                   -XX:CompileThreshold=100 -XX:+TieredCompilation -XX:TieredStopAtLevel=3
  *                   -XX:-BackgroundCompilation
  *                   -XX:+PatchALot
  *                   compiler.c1.CanonicalizeArrayLength
--- a/hotspot/test/compiler/c2/cr7200264/Test7200264.sh	Wed Jul 05 22:40:29 2017 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,132 +0,0 @@
-#!/bin/sh
-# 
-# Copyright (c) 2012, 2015, 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.
-# 
-# 
-
-## some tests require path to find test source dir
-if [ "${TESTSRC}" = "" ]
-then
-  TESTSRC=${PWD}
-  echo "TESTSRC not set.  Using "${TESTSRC}" as default"
-fi
-echo "TESTSRC=${TESTSRC}"
-## Adding common setup Variables for running shell tests.
-. ${TESTSRC}/../../../test_env.sh
-
-${TESTJAVA}${FS}bin${FS}java ${TESTOPTS} -Xinternalversion | sed 's/amd64/x86/' | grep "x86" | grep "Server VM" | grep "debug"
-
-# Only test fastdebug Server VM on x86
-if [ $? != 0 ]
-then
-    echo "Test Passed"
-    exit 0
-fi
-
-# grep for support integer multiply vectors (cpu with SSE4.1)
-${TESTJAVA}${FS}bin${FS}java ${TESTOPTS} -XX:+PrintMiscellaneous -XX:+Verbose -version | grep "cores per cpu" | grep "sse4.1"
-
-if [ $? != 0 ]
-then
-    SSE=2
-else
-    SSE=4
-fi
-
-cp ${TESTSRC}${FS}TestIntVect.java .
-${COMPILEJAVA}${FS}bin${FS}javac ${TESTJAVACOPTS} -d . TestIntVect.java
-
-# CICompilerCount must be at least 2 with -TieredCompilation
-${TESTJAVA}${FS}bin${FS}java ${TESTOPTS} -Xbatch -XX:-TieredCompilation  \
-        -XX:CICompilerCount=2 -XX:+PrintCompilation -XX:+TraceNewVectors \
-        compiler.c2.cr7200264.TestIntVect > test.out 2>&1
-
-COUNT=`grep AddVI test.out | wc -l | awk '{print $1}'`
-if [ $COUNT -lt 4 ]
-then
-    echo "Test Failed: AddVI $COUNT < 4"
-    exit 1
-fi
-
-# AddVI is generated for test_subc
-COUNT=`grep SubVI test.out | wc -l | awk '{print $1}'`
-if [ $COUNT -lt 4 ]
-then
-    echo "Test Failed: SubVI $COUNT < 4"
-    exit 1
-fi
-
-# MulVI is only supported with SSE4.1.
-if [ $SSE -gt 3 ]
-then
-# LShiftVI+SubVI is generated for test_mulc
-COUNT=`grep MulVI test.out | wc -l | awk '{print $1}'`
-if [ $COUNT -lt 2 ]
-then
-    echo "Test Failed: MulVI $COUNT < 2"
-    exit 1
-fi
-fi
-
-COUNT=`grep AndV test.out | wc -l | awk '{print $1}'`
-if [ $COUNT -lt 3 ]
-then
-    echo "Test Failed: AndV $COUNT < 3"
-    exit 1
-fi
-
-COUNT=`grep OrV test.out | wc -l | awk '{print $1}'`
-if [ $COUNT -lt 3 ]
-then
-    echo "Test Failed: OrV $COUNT < 3"
-    exit 1
-fi
-
-COUNT=`grep XorV test.out | wc -l | awk '{print $1}'`
-if [ $COUNT -lt 3 ]
-then
-    echo "Test Failed: XorV $COUNT < 3"
-    exit 1
-fi
-
-# LShiftVI+SubVI is generated for test_mulc
-COUNT=`grep LShiftVI test.out | wc -l | awk '{print $1}'`
-if [ $COUNT -lt 5 ]
-then
-    echo "Test Failed: LShiftVI $COUNT < 5"
-    exit 1
-fi
-
-COUNT=`grep RShiftVI test.out | sed '/URShiftVI/d' | wc -l | awk '{print $1}'`
-if [ $COUNT -lt 3 ]
-then
-    echo "Test Failed: RShiftVI $COUNT < 3"
-    exit 1
-fi
-
-COUNT=`grep URShiftVI test.out | wc -l | awk '{print $1}'`
-if [ $COUNT -lt 3 ]
-then
-    echo "Test Failed: URShiftVI $COUNT < 3"
-    exit 1
-fi
-
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/c2/cr7200264/TestDriver.java	Fri Jan 13 18:26:34 2017 +0100
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) 2016, 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.
+ */
+
+package compiler.c2.cr7200264;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Pattern;
+
+import jdk.test.lib.Asserts;
+import jdk.test.lib.process.OutputAnalyzer;
+import jdk.test.lib.process.ProcessTools;
+
+public class TestDriver {
+    private final Map<String, Long> expectedVectorizationNumbers
+            = new HashMap<>();
+
+    public void addExpectedVectorization(String v, long num) {
+        expectedVectorizationNumbers.put(v, num);
+    }
+
+    public void run() throws Throwable {
+        verifyVectorizationNumber(executeApplication());
+    }
+
+    private List<String> executeApplication() throws Throwable {
+        OutputAnalyzer outputAnalyzer = ProcessTools.executeTestJvmAllArgs(
+            "-Xbatch",
+            "-XX:-TieredCompilation",
+            "-XX:+PrintCompilation",
+            "-XX:+TraceNewVectors",
+            TestIntVect.class.getName());
+        outputAnalyzer.shouldHaveExitValue(0);
+        return outputAnalyzer.asLines();
+    }
+
+    private void verifyVectorizationNumber(List<String> vectorizationLog) {
+        for (Map.Entry<String, Long> entry : expectedVectorizationNumbers.entrySet()) {
+            String v = "\t" + entry.getKey();
+            long actualNum = vectorizationLog.stream()
+                    .filter(s -> s.contains(v)).count();
+            long expectedNum = entry.getValue();
+            Asserts.assertGTE(actualNum, expectedNum,
+                              "Unexpected " + entry.getKey() + " number");
+        }
+    }
+}
--- a/hotspot/test/compiler/c2/cr7200264/TestIntVect.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/test/compiler/c2/cr7200264/TestIntVect.java	Fri Jan 13 18:26:34 2017 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2016, 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
@@ -21,14 +21,6 @@
  * questions.
  */
 
-/**
- * @test
- * @bug 7200264
- * @summary 7192963 changes disabled shift vectors
- *
- * @run shell Test7200264.sh
- */
-
 package compiler.c2.cr7200264;
 /*
  * Copy of test/compiler/6340864/TestIntVect.java without performance tests.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/c2/cr7200264/TestSSE2IntVect.java	Fri Jan 13 18:26:34 2017 +0100
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2016, 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 7200264
+ * @summary 7192963 changes disabled shift vectors
+ * @requires vm.cpu.features ~= ".*sse2.*" & vm.debug & vm.flavor == "server"
+ * @library /test/lib /
+ * @run driver compiler.c2.cr7200264.TestSSE2IntVect
+ */
+
+package compiler.c2.cr7200264;
+
+public class TestSSE2IntVect {
+    public static void main(String[] args) throws Throwable {
+        TestDriver test = new TestDriver();
+        test.addExpectedVectorization("AddVI", 4);
+        test.addExpectedVectorization("SubVI", 4);
+        test.addExpectedVectorization("AndV", 3);
+        test.addExpectedVectorization("OrV", 3);
+        test.addExpectedVectorization("XorV", 3);
+        test.addExpectedVectorization("LShiftVI", 5);
+        test.addExpectedVectorization("RShiftVI", 3);
+        test.addExpectedVectorization("URShiftVI", 3);
+        test.run();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/c2/cr7200264/TestSSE4IntVect.java	Fri Jan 13 18:26:34 2017 +0100
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2016, 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 7200264
+ * @summary 7192963 changes disabled shift vectors
+ * @requires vm.cpu.features ~= ".*sse4\\.1.*" & vm.debug & vm.flavor == "server"
+ * @library /test/lib /
+ * @run driver compiler.c2.cr7200264.TestSSE4IntVect
+ */
+
+package compiler.c2.cr7200264;
+
+public class TestSSE4IntVect {
+    public static void main(String[] args) throws Throwable {
+        TestDriver test = new TestDriver();
+        test.addExpectedVectorization("MulVI", 2);
+        test.run();
+    }
+}
--- a/hotspot/test/compiler/ciReplay/TestVMNoCompLevel.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/test/compiler/ciReplay/TestVMNoCompLevel.java	Fri Jan 13 18:26:34 2017 +0100
@@ -65,7 +65,11 @@
             throw new Error("Failed to read/write replay data: " + ioe, ioe);
         }
         if (CLIENT_VM_AVAILABLE) {
-            negativeTest(CLIENT_VM_OPTION);
+            if (SERVER_VM_AVAILABLE) {
+                negativeTest(CLIENT_VM_OPTION);
+            } else {
+                positiveTest(CLIENT_VM_OPTION);
+            }
         }
         if (SERVER_VM_AVAILABLE) {
             positiveTest(TIERED_DISABLED_VM_OPTION, SERVER_VM_OPTION);
--- a/hotspot/test/compiler/loopopts/UseCountedLoopSafepointsTest.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/test/compiler/loopopts/UseCountedLoopSafepointsTest.java	Fri Jan 13 18:26:34 2017 +0100
@@ -27,7 +27,7 @@
  * @bug 6869327
  * @summary Test that C2 flag UseCountedLoopSafepoints ensures a safepoint is kept in a CountedLoop
  * @library /test/lib /
- * @requires vm.compMode != "Xint" & vm.flavor == "server" & (vm.opt.TieredStopAtLevel == null | vm.opt.TieredStopAtLevel == 4)
+ * @requires vm.compMode != "Xint" & vm.flavor == "server" & (vm.opt.TieredStopAtLevel == null | vm.opt.TieredStopAtLevel == 4) & vm.debug == true
  * @modules java.base/jdk.internal.misc
  * @build sun.hotspot.WhiteBox
  * @run driver ClassFileInstaller sun.hotspot.WhiteBox
--- a/hotspot/test/gc/g1/TestHumongousShrinkHeap.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/test/gc/g1/TestHumongousShrinkHeap.java	Fri Jan 13 18:26:34 2017 +0100
@@ -27,7 +27,7 @@
  * @requires vm.gc.G1
  * @summary Verify that heap shrinks after GC in the presence of fragmentation
  * due to humongous objects
- * @library /test/lib
+ * @library /test/lib /
  * @modules java.base/jdk.internal.misc
  * @modules java.management/sun.management
  * @run main/othervm -XX:-ExplicitGCInvokesConcurrent -XX:MinHeapFreeRatio=10
@@ -40,6 +40,8 @@
 import java.lang.management.MemoryUsage;
 import java.util.ArrayList;
 import java.util.List;
+import java.text.NumberFormat;
+import gc.testlibrary.Helpers;
 import static jdk.test.lib.Asserts.*;
 
 public class TestHumongousShrinkHeap {
@@ -70,9 +72,9 @@
 
         System.out.format("Running with %s initial heap size of %s maximum heap size. "
                           + "Will allocate humongous object of %s size %d times.%n",
-                          MemoryUsagePrinter.humanReadableByteCount(TOTAL_MEMORY, false),
-                          MemoryUsagePrinter.humanReadableByteCount(MAX_MEMORY, false),
-                          MemoryUsagePrinter.humanReadableByteCount(HUMON_SIZE, false),
+                          MemoryUsagePrinter.NF.format(TOTAL_MEMORY),
+                          MemoryUsagePrinter.NF.format(MAX_MEMORY),
+                          MemoryUsagePrinter.NF.format(HUMON_SIZE),
                           HUMON_COUNT
         );
         new TestHumongousShrinkHeap().test();
@@ -134,24 +136,16 @@
  */
 class MemoryUsagePrinter {
 
-    public static String humanReadableByteCount(long bytes, boolean si) {
-        int unit = si ? 1000 : 1024;
-        if (bytes < unit) {
-            return bytes + " B";
-        }
-        int exp = (int) (Math.log(bytes) / Math.log(unit));
-        String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i");
-        return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
-    }
+    public static final NumberFormat NF = Helpers.numberFormatter();
 
     public static void printMemoryUsage(String label) {
         MemoryUsage memusage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
         float freeratio = 1f - (float) memusage.getUsed() / memusage.getCommitted();
         System.out.format("[%-24s] init: %-7s, used: %-7s, comm: %-7s, freeRatio ~= %.1f%%%n",
                 label,
-                humanReadableByteCount(memusage.getInit(), false),
-                humanReadableByteCount(memusage.getUsed(), false),
-                humanReadableByteCount(memusage.getCommitted(), false),
+                NF.format(memusage.getInit()),
+                NF.format(memusage.getUsed()),
+                NF.format(memusage.getCommitted()),
                 freeratio * 100
         );
     }
--- a/hotspot/test/gc/g1/TestShrinkDefragmentedHeap.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/test/gc/g1/TestShrinkDefragmentedHeap.java	Fri Jan 13 18:26:34 2017 +0100
@@ -31,7 +31,7 @@
  *        "..................................H"
  *     3. invoke gc and check that memory returned to the system (amount of committed memory got down)
  *
- * @library /test/lib
+ * @library /test/lib /
  * @modules java.base/jdk.internal.misc
  *          java.management/sun.management
  */
@@ -39,10 +39,12 @@
 import java.lang.management.MemoryUsage;
 import java.util.ArrayList;
 import java.util.List;
+import java.text.NumberFormat;
 import static jdk.test.lib.Asserts.*;
 import jdk.test.lib.process.OutputAnalyzer;
 import jdk.test.lib.process.ProcessTools;
 import com.sun.management.HotSpotDiagnosticMXBean;
+import gc.testlibrary.Helpers;
 
 public class TestShrinkDefragmentedHeap {
     // Since we store all the small objects, they become old and old regions are also allocated at the bottom of the heap
@@ -114,8 +116,8 @@
 
         private void allocate() {
             System.out.format("Will allocate objects of small size = %s and humongous size = %s",
-                    MemoryUsagePrinter.humanReadableByteCount(SMALL_OBJS_SIZE, false),
-                    MemoryUsagePrinter.humanReadableByteCount(HUMONG_OBJS_SIZE, false)
+                    MemoryUsagePrinter.NF.format(SMALL_OBJS_SIZE),
+                    MemoryUsagePrinter.NF.format(HUMONG_OBJS_SIZE)
             );
 
             for (int i = 0; i < ALLOCATE_COUNT; i++) {
@@ -170,24 +172,16 @@
      */
     static class MemoryUsagePrinter {
 
-        public static String humanReadableByteCount(long bytes, boolean si) {
-            int unit = si ? 1000 : 1024;
-            if (bytes < unit) {
-                return bytes + " B";
-            }
-            int exp = (int) (Math.log(bytes) / Math.log(unit));
-            String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i");
-            return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
-        }
+        public static final NumberFormat NF = Helpers.numberFormatter();
 
         public static void printMemoryUsage(String label) {
             MemoryUsage memusage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
             float freeratio = 1f - (float) memusage.getUsed() / memusage.getCommitted();
             System.out.format("[%-24s] init: %-7s, used: %-7s, comm: %-7s, freeRatio ~= %.1f%%%n",
                     label,
-                    humanReadableByteCount(memusage.getInit(), false),
-                    humanReadableByteCount(memusage.getUsed(), false),
-                    humanReadableByteCount(memusage.getCommitted(), false),
+                    NF.format(memusage.getInit()),
+                    NF.format(memusage.getUsed()),
+                    NF.format(memusage.getCommitted()),
                     freeratio * 100
             );
         }
--- a/hotspot/test/gc/parallel/TestDynShrinkHeap.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/test/gc/parallel/TestDynShrinkHeap.java	Fri Jan 13 18:26:34 2017 +0100
@@ -28,15 +28,17 @@
  * @summary Verify that the heap shrinks after full GC according to the current values of the Min/MaxHeapFreeRatio flags
  * @modules java.base/jdk.internal.misc
  * @modules jdk.management
- * @library /test/lib
+ * @library /test/lib /
  * @run main/othervm -XX:+UseAdaptiveSizePolicyWithSystemGC -XX:+UseParallelGC -XX:MinHeapFreeRatio=0 -XX:MaxHeapFreeRatio=100 -Xmx1g -verbose:gc TestDynShrinkHeap
  */
 import jdk.test.lib.DynamicVMOption;
 import java.lang.management.ManagementFactory;
 import java.lang.management.MemoryUsage;
 import java.util.ArrayList;
+import java.text.NumberFormat;
 import static jdk.test.lib.Asserts.assertLessThan;
 import com.sun.management.HotSpotDiagnosticMXBean;
+import gc.testlibrary.Helpers;
 
 public class TestDynShrinkHeap {
 
@@ -101,24 +103,16 @@
  */
 class MemoryUsagePrinter {
 
-    public static String humanReadableByteCount(long bytes, boolean si) {
-        int unit = si ? 1000 : 1024;
-        if (bytes < unit) {
-            return bytes + " B";
-        }
-        int exp = (int) (Math.log(bytes) / Math.log(unit));
-        String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i");
-        return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
-    }
+    public static final NumberFormat NF = Helpers.numberFormatter();
 
     public static void printMemoryUsage(String label) {
         MemoryUsage memusage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
         float freeratio = 1f - (float) memusage.getUsed() / memusage.getCommitted();
         System.out.format("[%-24s] init: %-7s, used: %-7s, comm: %-7s, freeRatio ~= %.1f%%%n",
                 label,
-                humanReadableByteCount(memusage.getInit(), true),
-                humanReadableByteCount(memusage.getUsed(), true),
-                humanReadableByteCount(memusage.getCommitted(), true),
+                NF.format(memusage.getInit()),
+                NF.format(memusage.getUsed()),
+                NF.format(memusage.getCommitted()),
                 freeratio * 100
         );
     }
--- a/hotspot/test/gc/stress/TestStressG1Humongous.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/test/gc/stress/TestStressG1Humongous.java	Fri Jan 13 18:26:34 2017 +0100
@@ -28,14 +28,9 @@
  * @summary Stress G1 by humongous allocations in situation near OOM
  * @requires vm.gc.G1
  * @requires !vm.flightRecorder
- * @run main/othervm/timeout=200 -Xlog:gc=debug -Xmx1g -XX:+UseG1GC -XX:G1HeapRegionSize=4m
- *              -Dtimeout=120 -Dthreads=3 -Dhumongoussize=1.1 -Dregionsize=4 TestStressG1Humongous
- * @run main/othervm/timeout=200 -Xlog:gc=debug -Xmx1g -XX:+UseG1GC -XX:G1HeapRegionSize=16m
- *              -Dtimeout=120 -Dthreads=5 -Dhumongoussize=2.1 -Dregionsize=16 TestStressG1Humongous
- * @run main/othervm/timeout=200 -Xlog:gc=debug -Xmx1g -XX:+UseG1GC -XX:G1HeapRegionSize=32m
- *              -Dtimeout=120 -Dthreads=4 -Dhumongoussize=0.6 -Dregionsize=32 TestStressG1Humongous
- * @run main/othervm/timeout=700 -Xlog:gc=debug -Xmx1g -XX:+UseG1GC -XX:G1HeapRegionSize=1m
- *              -Dtimeout=600 -Dthreads=7 -Dhumongoussize=0.6 -Dregionsize=1 TestStressG1Humongous
+ * @library /test/lib
+ * @modules java.base/jdk.internal.misc
+ * @run driver/timeout=1300 TestStressG1Humongous
  */
 
 import java.util.ArrayList;
@@ -44,8 +39,45 @@
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.atomic.AtomicInteger;
 
-public class TestStressG1Humongous {
+import jdk.test.lib.Platform;
+import jdk.test.lib.Utils;
+import jdk.test.lib.process.ProcessTools;
+import jdk.test.lib.process.OutputAnalyzer;
+
+public class TestStressG1Humongous{
+
+    public static void main(String[] args) throws Exception {
+        // Limit heap size on 32-bit platforms
+        int heapSize = Platform.is32bit() ? 512 : 1024;
+        // Heap size, region size, threads, humongous size, timeout
+        run(heapSize, 4, 3, 1.1, 120);
+        run(heapSize, 16, 5, 2.1, 120);
+        run(heapSize, 32, 4, 0.6, 120);
+        run(heapSize, 1, 7, 0.6, 600);
+    }
 
+    private static void run(int heapSize, int regionSize, int threads, double humongousSize, int timeout)
+            throws Exception {
+        ArrayList<String> options = new ArrayList<>();
+        Collections.addAll(options, Utils.getTestJavaOpts());
+        Collections.addAll(options,
+                "-Xlog:gc=debug",
+                "-Xmx" + heapSize + "m",
+                "-XX:+UseG1GC",
+                "-XX:G1HeapRegionSize=" + regionSize + "m",
+                "-Dtimeout=" + timeout,
+                "-Dthreads=" + threads,
+                "-Dhumongoussize=" + humongousSize,
+                "-Dregionsize=" + regionSize,
+                TestStressG1HumongousImpl.class.getName()
+        );
+        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(options.toArray(new String[options.size()]));
+        OutputAnalyzer output = new OutputAnalyzer(pb.start());
+        output.shouldHaveExitValue(0);
+    }
+}
+
+class TestStressG1HumongousImpl {
     // Timeout in seconds
     private static final int TIMEOUT = Integer.getInteger("timeout", 60);
     private static final int THREAD_COUNT = Integer.getInteger("threads", 2);
@@ -60,10 +92,10 @@
     public static final List<Object> GARBAGE = Collections.synchronizedList(new ArrayList<>());
 
     public static void main(String[] args) throws InterruptedException {
-        new TestStressG1Humongous().run();
+        new TestStressG1HumongousImpl().run();
     }
 
-    public TestStressG1Humongous() {
+    public TestStressG1HumongousImpl() {
         isRunning = true;
         threads = new Thread[THREAD_COUNT];
         alocatedObjectsCount = new AtomicInteger(0);
--- a/hotspot/test/gc/stress/gcbasher/TestGCBasherWithCMS.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/test/gc/stress/gcbasher/TestGCBasherWithCMS.java	Fri Jan 13 18:26:34 2017 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -31,7 +31,7 @@
  * @requires vm.gc.ConcMarkSweep
  * @requires vm.flavor == "server"
  * @summary Stress the CMS GC by trying to make old objects more likely to be garbage than young objects.
- * @run main/othervm/timeout=200 -Xlog:gc*=info -Xmx128m -server -XX:+UseConcMarkSweepGC TestGCBasherWithCMS 120000
+ * @run main/othervm/timeout=200 -Xlog:gc*=info -Xmx256m -server -XX:+UseConcMarkSweepGC TestGCBasherWithCMS 120000
  */
 public class TestGCBasherWithCMS {
     public static void main(String[] args) throws IOException {
--- a/hotspot/test/gc/stress/gcbasher/TestGCBasherWithG1.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/test/gc/stress/gcbasher/TestGCBasherWithG1.java	Fri Jan 13 18:26:34 2017 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -31,7 +31,7 @@
  * @requires vm.gc.G1
  * @requires vm.flavor == "server"
  * @summary Stress the G1 GC by trying to make old objects more likely to be garbage than young objects.
- * @run main/othervm/timeout=200 -Xlog:gc*=info -Xmx128m -server -XX:+UseG1GC TestGCBasherWithG1 120000
+ * @run main/othervm/timeout=200 -Xlog:gc*=info -Xmx256m -server -XX:+UseG1GC TestGCBasherWithG1 120000
  */
 public class TestGCBasherWithG1 {
     public static void main(String[] args) throws IOException {
--- a/hotspot/test/gc/stress/gcbasher/TestGCBasherWithSerial.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/test/gc/stress/gcbasher/TestGCBasherWithSerial.java	Fri Jan 13 18:26:34 2017 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -31,7 +31,7 @@
  * @requires vm.gc.Serial
  * @requires vm.flavor == "server"
  * @summary Stress the Serial GC by trying to make old objects more likely to be garbage than young objects.
- * @run main/othervm/timeout=200 -Xlog:gc*=info -Xmx128m -server -XX:+UseSerialGC TestGCBasherWithSerial 120000
+ * @run main/othervm/timeout=200 -Xlog:gc*=info -Xmx256m -server -XX:+UseSerialGC TestGCBasherWithSerial 120000
  */
 public class TestGCBasherWithSerial {
     public static void main(String[] args) throws IOException {
--- a/hotspot/test/gc/testlibrary/Helpers.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/test/gc/testlibrary/Helpers.java	Fri Jan 13 18:26:34 2017 +0100
@@ -31,6 +31,9 @@
 import java.io.IOException;
 import java.nio.file.Files;
 import java.nio.file.Path;
+import java.text.DecimalFormat;
+import java.text.DecimalFormatSymbols;
+import java.text.NumberFormat;
 
 public class Helpers {
 
@@ -320,4 +323,16 @@
         }
     }
 
+    /**
+     * @return a number formatter instance which prints numbers in a human
+     * readable form, like 9_223_372_036_854_775_807.
+     */
+    public static NumberFormat numberFormatter() {
+        DecimalFormat df = new DecimalFormat();
+        DecimalFormatSymbols dfs = df.getDecimalFormatSymbols();
+        dfs.setGroupingSeparator('_');
+        dfs.setDecimalSeparator('.');
+        df.setDecimalFormatSymbols(dfs);
+        return df;
+    }
 }
--- a/hotspot/test/native/code/test_dependencyContext.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/test/native/code/test_dependencyContext.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -86,7 +86,7 @@
   NOT_PRODUCT(ASSERT_FALSE(depContext.is_dependent_nmethod(nm)));
 }
 
-TEST(code, dependency_context) {
+TEST_VM(code, dependency_context) {
   test_remove_dependent_nmethod(0, false);
   test_remove_dependent_nmethod(1, false);
   test_remove_dependent_nmethod(2, false);
--- a/hotspot/test/native/gc/g1/test_workerDataArray.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/test/native/gc/g1/test_workerDataArray.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -123,19 +123,19 @@
   }
 };
 
-TEST_F(BasicWorkerDataArrayTest, sum_test) {
+TEST_VM_F(BasicWorkerDataArrayTest, sum_test) {
   ASSERT_EQ(15u, array.sum());
 }
 
-TEST_F(BasicWorkerDataArrayTest, average_test) {
+TEST_VM_F(BasicWorkerDataArrayTest, average_test) {
   ASSERT_NEAR(5.0, array.average(), epsilon);
 }
 
-TEST_F(BasicWorkerDataArrayTest, print_summary_on_test) {
+TEST_VM_F(BasicWorkerDataArrayTest, print_summary_on_test) {
   ASSERT_STREQ(print_expected_summary(), print_summary());
 }
 
-TEST_F(BasicWorkerDataArrayTest, print_details_on_test) {
+TEST_VM_F(BasicWorkerDataArrayTest, print_details_on_test) {
   ASSERT_STREQ(print_expected_details(), print_details());
 }
 
@@ -161,19 +161,19 @@
   }
 };
 
-TEST_F(AddWorkerDataArrayTest, sum_test) {
+TEST_VM_F(AddWorkerDataArrayTest, sum_test) {
   ASSERT_EQ(18u, array.sum());
 }
 
-TEST_F(AddWorkerDataArrayTest, average_test) {
+TEST_VM_F(AddWorkerDataArrayTest, average_test) {
   ASSERT_NEAR(6.0, array.average(), epsilon);
 }
 
-TEST_F(AddWorkerDataArrayTest, print_summary_on_test) {
+TEST_VM_F(AddWorkerDataArrayTest, print_summary_on_test) {
   ASSERT_STREQ(print_expected_summary(), print_summary());
 }
 
-TEST_F(AddWorkerDataArrayTest, print_details_on_test) {
+TEST_VM_F(AddWorkerDataArrayTest, print_details_on_test) {
   ASSERT_STREQ(print_expected_details(), print_details());
 }
 
@@ -195,19 +195,19 @@
   }
 };
 
-TEST_F(UninitializedElementWorkerDataArrayTest, sum_test) {
+TEST_VM_F(UninitializedElementWorkerDataArrayTest, sum_test) {
   ASSERT_EQ(12u, array.sum());
 }
 
-TEST_F(UninitializedElementWorkerDataArrayTest, average_test) {
+TEST_VM_F(UninitializedElementWorkerDataArrayTest, average_test) {
   ASSERT_NEAR(6.0, array.average(), epsilon);
 }
 
-TEST_F(UninitializedElementWorkerDataArrayTest, print_summary_on_test) {
+TEST_VM_F(UninitializedElementWorkerDataArrayTest, print_summary_on_test) {
   ASSERT_STREQ(print_expected_summary(), print_summary());
 }
 
-TEST_F(UninitializedElementWorkerDataArrayTest, print_details_on_test) {
+TEST_VM_F(UninitializedElementWorkerDataArrayTest, print_details_on_test) {
   ASSERT_STREQ(print_expected_details(), print_details());
 }
 
@@ -229,19 +229,19 @@
   }
 };
 
-TEST_F(UninitializedWorkerDataArrayTest, sum_test) {
+TEST_VM_F(UninitializedWorkerDataArrayTest, sum_test) {
   ASSERT_EQ(0u, array.sum());
 }
 
-TEST_F(UninitializedWorkerDataArrayTest, average_test) {
+TEST_VM_F(UninitializedWorkerDataArrayTest, average_test) {
   ASSERT_NEAR(0.0, array.average(), epsilon);
 }
 
-TEST_F(UninitializedWorkerDataArrayTest, print_summary_on_test) {
+TEST_VM_F(UninitializedWorkerDataArrayTest, print_summary_on_test) {
   ASSERT_STREQ(print_expected_summary(), print_summary());
 }
 
-TEST_F(UninitializedWorkerDataArrayTest, print_details_on_test) {
+TEST_VM_F(UninitializedWorkerDataArrayTest, print_details_on_test) {
   ASSERT_STREQ(print_expected_details(), print_details());
 }
 
@@ -265,18 +265,18 @@
   }
 };
 
-TEST_F(UninitializedDoubleElementWorkerDataArrayTest, sum_test) {
+TEST_VM_F(UninitializedDoubleElementWorkerDataArrayTest, sum_test) {
   ASSERT_NEAR(12.3 / MILLIUNITS, array.sum(), epsilon);
 }
 
-TEST_F(UninitializedDoubleElementWorkerDataArrayTest, average_test) {
+TEST_VM_F(UninitializedDoubleElementWorkerDataArrayTest, average_test) {
   ASSERT_NEAR(6.15 / MILLIUNITS, array.average(), epsilon);
 }
 
-TEST_F(UninitializedDoubleElementWorkerDataArrayTest, print_summary_on_test) {
+TEST_VM_F(UninitializedDoubleElementWorkerDataArrayTest, print_summary_on_test) {
   ASSERT_STREQ(print_expected_summary(), print_summary());
 }
 
-TEST_F(UninitializedDoubleElementWorkerDataArrayTest, print_details_on_test) {
+TEST_VM_F(UninitializedDoubleElementWorkerDataArrayTest, print_details_on_test) {
   ASSERT_STREQ(print_expected_details(), print_details());
 }
--- a/hotspot/test/native/logging/test_log.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/test/native/logging/test_log.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -41,14 +41,14 @@
 }
 
 #ifdef ASSERT // 'test' tag is debug only
-TEST_F(LogTest, prefix) {
+TEST_VM_F(LogTest, prefix) {
   set_log_config(TestLogFileName, "logging+test=trace");
   log_trace(logging, test)(LOG_LINE_STR);
   EXPECT_TRUE(file_contains_substring(TestLogFileName, LOG_PREFIX_STR LOG_LINE_STR));
 }
 #endif
 
-TEST_F(LogTest, large_message) {
+TEST_VM_F(LogTest, large_message) {
   char big_msg[4096] = {0};
   char Xchar = '~';
 
@@ -68,7 +68,7 @@
   EXPECT_EQ(sizeof(big_msg) - 1, count);
 }
 
-TEST_F(LogTest, enabled_logtarget) {
+TEST_VM_F(LogTest, enabled_logtarget) {
   set_log_config(TestLogFileName, "gc=debug");
 
   LogTarget(Debug, gc) log;
@@ -80,7 +80,7 @@
   EXPECT_TRUE(file_contains_substring(TestLogFileName, LOG_TEST_STRING_LITERAL));
 }
 
-TEST_F(LogTest, disabled_logtarget) {
+TEST_VM_F(LogTest, disabled_logtarget) {
   set_log_config(TestLogFileName, "gc=info");
 
   LogTarget(Debug, gc) log;
@@ -95,7 +95,7 @@
   EXPECT_FALSE(file_contains_substring(TestLogFileName, LOG_TEST_STRING_LITERAL));
 }
 
-TEST_F(LogTest, enabled_loghandle) {
+TEST_VM_F(LogTest, enabled_loghandle) {
   set_log_config(TestLogFileName, "gc=debug");
 
   Log(gc) log;
@@ -109,7 +109,7 @@
   EXPECT_TRUE(file_contains_substring(TestLogFileName, "3 workers"));
 }
 
-TEST_F(LogTest, disabled_loghandle) {
+TEST_VM_F(LogTest, disabled_loghandle) {
   set_log_config(TestLogFileName, "gc=info");
 
   Log(gc) log;
@@ -126,7 +126,7 @@
   EXPECT_FALSE(file_contains_substring(TestLogFileName, "3 workers"));
 }
 
-TEST_F(LogTest, enabled_logtargethandle) {
+TEST_VM_F(LogTest, enabled_logtargethandle) {
   set_log_config(TestLogFileName, "gc=debug");
 
   LogTarget(Debug, gc) log;
@@ -140,7 +140,7 @@
   EXPECT_TRUE(file_contains_substring(TestLogFileName, "3 workers"));
 }
 
-TEST_F(LogTest, disabled_logtargethandle) {
+TEST_VM_F(LogTest, disabled_logtargethandle) {
   set_log_config(TestLogFileName, "gc=info");
 
   LogTarget(Debug, gc) log;
--- a/hotspot/test/native/logging/test_logConfiguration.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/test/native/logging/test_logConfiguration.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -297,7 +297,7 @@
   }
 }
 
-TEST_F(LogConfigurationTest, configure_stdout) {
+TEST_VM_F(LogConfigurationTest, configure_stdout) {
   // Start out with all logging disabled
   LogConfiguration::disable_logging();
 
@@ -355,7 +355,7 @@
   Test_logconfiguration_subscribe_triggered++;
 }
 
-TEST_F(LogConfigurationTest, subscribe) {
+TEST_VM_F(LogConfigurationTest, subscribe) {
   ResourceMark rm;
   Log(logging) log;
   set_log_config("stdout", "logging*=trace");
--- a/hotspot/test/native/logging/test_logMessageTest.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/test/native/logging/test_logMessageTest.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -65,7 +65,7 @@
 
 // Verify that messages with multiple levels are written
 // to outputs configured for all the corresponding levels
-TEST_F(LogMessageTest, level_inclusion) {
+TEST_VM_F(LogMessageTest, level_inclusion) {
   const size_t message_count = 10;
   LogMessageBuffer msg[message_count];
 
@@ -119,7 +119,7 @@
 }
 
 // Verify that messages are logged in the order they are added to the log message
-TEST_F(LogMessageTest, line_order) {
+TEST_VM_F(LogMessageTest, line_order) {
   LogMessageBuffer msg;
   msg.info("info line").error("error line").trace("trace line")
       .error("another error").warning("warning line").debug("debug line");
@@ -131,7 +131,7 @@
     << "output missing or in incorrect order";
 }
 
-TEST_F(LogMessageTest, long_message) {
+TEST_VM_F(LogMessageTest, long_message) {
   // Write 10K bytes worth of log data
   LogMessageBuffer msg;
   const size_t size = 10 * K;
@@ -155,7 +155,7 @@
   FREE_C_HEAP_ARRAY(char, data);
 }
 
-TEST_F(LogMessageTest, message_with_many_lines) {
+TEST_VM_F(LogMessageTest, message_with_many_lines) {
   const size_t lines = 100;
   const size_t line_length = 16;
 
@@ -188,7 +188,7 @@
   return prefix_len;
 }
 
-TEST_F(LogMessageTest, prefixing) {
+TEST_VM_F(LogMessageTest, prefixing) {
   LogMessageBuffer msg;
   msg.set_prefix(dummy_prefixer);
   for (int i = 0; i < 3; i++) {
@@ -209,7 +209,7 @@
     << "error in prefixed output";
 }
 
-TEST_F(LogMessageTest, scoped_messages) {
+TEST_VM_F(LogMessageTest, scoped_messages) {
   {
     LogMessage(logging) msg;
     msg.info("scoped info");
@@ -223,7 +223,7 @@
     << "missing output from scoped log message";
 }
 
-TEST_F(LogMessageTest, scoped_flushing) {
+TEST_VM_F(LogMessageTest, scoped_flushing) {
   {
     LogMessage(logging) msg;
     msg.info("manual flush info");
@@ -236,7 +236,7 @@
     << "log file contains duplicate lines from single scoped log message";
 }
 
-TEST_F(LogMessageTest, scoped_reset) {
+TEST_VM_F(LogMessageTest, scoped_reset) {
   {
     LogMessage(logging) msg, partial;
     msg.info("%s", "info reset msg");
--- a/hotspot/test/native/logging/test_logTagSetDescriptions.cpp	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/test/native/logging/test_logTagSetDescriptions.cpp	Fri Jan 13 18:26:34 2017 +0100
@@ -30,7 +30,7 @@
 #include "unittest.hpp"
 #include "utilities/ostream.hpp"
 
-TEST(LogTagSetDescriptions, describe) {
+TEST_VM(LogTagSetDescriptions, describe) {
   for (LogTagSetDescription* d = tagset_descriptions; d->tagset != NULL; d++) {
     char expected[1 * K];
     d->tagset->label(expected, sizeof(expected), "+");
@@ -46,7 +46,7 @@
   }
 }
 
-TEST(LogTagSetDescriptions, command_line_help) {
+TEST_VM(LogTagSetDescriptions, command_line_help) {
   const char* filename = "logtagset_descriptions";
   FILE* fp = fopen(filename, "w+");
   ASSERT_NE((void*)NULL, fp);
--- a/hotspot/test/runtime/RedefineTests/RedefinePreviousVersions.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/test/runtime/RedefineTests/RedefinePreviousVersions.java	Fri Jan 13 18:26:34 2017 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -48,20 +48,23 @@
     public static String newRunning =
         "class RedefinePreviousVersions$Running {" +
         "    public static volatile boolean stop = true;" +
+        "    public static volatile boolean running = true;" +
         "    static void localSleep() { }" +
         "    public static void infinite() { }" +
         "}";
 
     static class Running {
         public static volatile boolean stop = false;
+        public static volatile boolean running = false;
         static void localSleep() {
           try{
-            Thread.currentThread().sleep(10);//sleep for 10 ms
+            Thread.sleep(10); // sleep for 10 ms
           } catch(InterruptedException ie) {
           }
         }
 
         public static void infinite() {
+            running = true;
             while (!stop) { localSleep(); }
         }
     }
@@ -70,8 +73,6 @@
 
         if (args.length > 0) {
 
-            String jarFile = System.getProperty("test.src") + "/testcase.jar";
-
             // java -javaagent:redefineagent.jar -Xlog:stuff RedefinePreviousVersions
             ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( "-javaagent:redefineagent.jar",
                "-Xlog:redefine+class+iklass+add=trace,redefine+class+iklass+purge=trace",
@@ -100,6 +101,10 @@
             }
         }.start();
 
+        while (!Running.running) {
+            Thread.sleep(10); // sleep for 10 ms
+        }
+
         // Since a method of newRunning is running, this class should be added to the previous_version_list
         // of Running, and _has_previous_versions should return true at class unloading.
         RedefineClassHelper.redefineClass(Running.class, newRunning);
--- a/hotspot/test/runtime/ReservedStack/ReservedStackTest.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/test/runtime/ReservedStack/ReservedStackTest.java	Fri Jan 13 18:26:34 2017 +0100
@@ -199,7 +199,9 @@
             // corruptions are still possible.
             boolean supportedPlatform =
                 Platform.isAix() ||
-                (Platform.isLinux() && (Platform.isPPC() || Platform.isX64() || Platform.isX86())) ||
+                (Platform.isLinux() &&
+                  (Platform.isPPC() || Platform.isS390x() || Platform.isX64() ||
+                   Platform.isX86() || Platform.isAArch64())) ||
                 Platform.isOSX() ||
                 Platform.isSolaris();
             if (supportedPlatform && !result.contains("PASSED")) {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/modules/AccessCheck/AccessExportTwice.java	Fri Jan 13 18:26:34 2017 +0100
@@ -0,0 +1,146 @@
+/*
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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
+ * @summary Class p1.c1 in an unnamed module cannot read p2.c2 in module second_mod,
+ *          even after p2 is exported to all unnamed. Ensures constant
+ *          access check answers when not accessible due to exportedness.
+ * @library /test/lib
+ * @modules java.base/jdk.internal.misc
+ * @modules java.base/jdk.internal.module
+ * @compile myloaders/MySameClassLoader.java
+ * @compile p2/c2.java
+ * @compile p1/c1.java
+ * @run main/othervm AccessExportTwice
+ */
+
+import static jdk.test.lib.Asserts.*;
+
+import java.lang.module.Configuration;
+import java.lang.module.ModuleDescriptor;
+import java.lang.module.ModuleFinder;
+import java.lang.reflect.Layer;
+import java.lang.reflect.Module;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import myloaders.MySameClassLoader;
+
+//
+// ClassLoader1 --> defines first_mod --> no packages
+//                  defines second_mod --> packages p2
+//
+// first_mod can read second_mod
+// package p2 in second_mod is exported to first_mod
+//
+// class p1.c1 defined in an unnamed module tries to access p2.c2 defined in second_mod
+// Access is not allowed, even after p2 is exported to all unnamed modules.
+
+public class AccessExportTwice {
+
+    // Create a Layer over the boot layer.
+    // Define modules within this layer to test access between
+    // publicly defined classes within packages of those modules.
+    public void createLayerOnBoot() throws Throwable {
+
+        // Define module:     first_mod
+        // Can read:          java.base, second_mod
+        // Packages:          none
+        // Packages exported: none
+        ModuleDescriptor descriptor_first_mod =
+                ModuleDescriptor.module("first_mod")
+                        .requires("java.base")
+                        .requires("second_mod")
+                        .build();
+
+        // Define module:     second_mod
+        // Can read:          java.base
+        // Packages:          p2
+        // Packages exported: p2 is exported to first_mod
+        ModuleDescriptor descriptor_second_mod =
+                ModuleDescriptor.module("second_mod")
+                        .requires("java.base")
+                        .exports("p2", Set.of("first_mod"))
+                        .build();
+
+        // Set up a ModuleFinder containing all modules for this layer
+        ModuleFinder finder = ModuleLibrary.of(descriptor_first_mod, descriptor_second_mod);
+
+        // Resolves "first_mod"
+        Configuration cf = Layer.boot()
+                .configuration()
+                .resolveRequires(finder, ModuleFinder.of(), Set.of("first_mod"));
+
+        // Map each module to the same class loader
+        Map<String, ClassLoader> map = new HashMap<>();
+        map.put("first_mod", MySameClassLoader.loader1);
+        map.put("second_mod", MySameClassLoader.loader1);
+
+        // Create Layer that contains first_mod & second_mod
+        Layer layer = Layer.boot().defineModules(cf, map::get);
+
+        assertTrue(layer.findLoader("first_mod") == MySameClassLoader.loader1);
+        assertTrue(layer.findLoader("second_mod") == MySameClassLoader.loader1);
+        assertTrue(layer.findLoader("java.base") == null);
+
+        Class p2_c2_class = MySameClassLoader.loader1.loadClass("p2.c2");
+        // Use the same loader to load class p1.c1
+        Class p1_c1_class = MySameClassLoader.loader1.loadClass("p1.c1");
+        // First access check for p1.c1
+        try {
+            p1_c1_class.newInstance();
+            throw new RuntimeException("Test Failed, the unnamed module should not have access to public type p2.c2");
+        } catch (IllegalAccessError e) {
+            String message = e.getMessage();
+            if (!(message.contains("cannot access") &&
+                  message.contains("because module second_mod does not export p2 to unnamed module"))) {
+                throw new RuntimeException("Wrong message: " + message);
+            } else {
+                System.out.println("Test Succeeded at attempt #1");
+            }
+        }
+
+        // Export second_mod/p2 to all unnamed modules.
+        Module second_mod = p2_c2_class.getModule();
+        jdk.internal.module.Modules.addExportsToAllUnnamed(second_mod, "p2");
+
+        // Second access check for p1.c1, should have same result as first
+        try {
+            p1_c1_class.newInstance();
+            throw new RuntimeException("Test Failed, access should have been cached above");
+        } catch (IllegalAccessError e) {
+            String message = e.getMessage();
+            if (!(message.contains("cannot access") &&
+                  message.contains("because module second_mod does not export p2 to unnamed module"))) {
+                throw new RuntimeException("Wrong message: " + message);
+            } else {
+                System.out.println("Test Succeeded at attempt #2");
+            }
+        }
+    }
+
+    public static void main(String args[]) throws Throwable {
+      AccessExportTwice test = new AccessExportTwice();
+      test.createLayerOnBoot();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/modules/AccessCheck/AccessReadTwice.java	Fri Jan 13 18:26:34 2017 +0100
@@ -0,0 +1,154 @@
+/*
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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
+ * @summary Class p1.c1 in module first_mod cannot read p2.c2 in module second_mod,
+ *          even after a read edge is added between first_mod and second_mod.
+ *          Ensures constant access check answers when not accessible due to readability.
+ * @library /test/lib
+ * @modules java.base/jdk.internal.misc
+ * @modules java.base/jdk.internal.module
+ * @compile p2/c2.java
+ * @compile p1/c1.java
+ * @compile p4/c4.java
+ * @run main/othervm AccessReadTwice
+ */
+
+import static jdk.test.lib.Asserts.*;
+
+import java.lang.module.Configuration;
+import java.lang.module.ModuleDescriptor;
+import java.lang.module.ModuleFinder;
+import java.lang.reflect.Layer;
+import java.lang.reflect.Module;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+
+//
+// ClassLoader1 --> defines first_mod --> packages p1, p4
+//                  defines second_mod --> package p2
+//
+// package p2 in second_mod is exported to first_mod
+//
+// class p1.c1 defined in first_mod tries to access p2.c2 defined in second_mod
+// Access is not allowed, even after a read edge is added between first_mod and second_mod.
+
+public class AccessReadTwice {
+
+    // Create a Layer over the boot layer.
+    // Define modules within this layer to test access between
+    // publicly defined classes within packages of those modules.
+    public void createLayerOnBoot() throws Throwable {
+
+        // Define module:     first_mod
+        // Can read:          java.base
+        // Packages:          p1, p4
+        // Packages exported: none
+        ModuleDescriptor descriptor_first_mod =
+                ModuleDescriptor.module("first_mod")
+                        .requires("java.base")
+                        .contains(Set.of("p1", "p4"))
+                        .build();
+
+        // Define module:     second_mod
+        // Can read:          java.base
+        // Packages:          p2
+        // Packages exported: p2 is exported to first_mod
+        ModuleDescriptor descriptor_second_mod =
+                ModuleDescriptor.module("second_mod")
+                        .requires("java.base")
+                        .exports("p2", Set.of("first_mod"))
+                        .build();
+
+        // Set up a ModuleFinder containing all modules for this layer
+        ModuleFinder finder = ModuleLibrary.of(descriptor_first_mod, descriptor_second_mod);
+
+        // Resolves "first_mod" and "second_mod"
+        Configuration cf = Layer.boot()
+                .configuration()
+                .resolveRequires(finder, ModuleFinder.of(), Set.of("first_mod", "second_mod"));
+
+        // Map each module to this class loader
+        Map<String, ClassLoader> map = new HashMap<>();
+        ClassLoader loader = AccessReadTwice.class.getClassLoader();
+        map.put("first_mod", loader);
+        map.put("second_mod", loader);
+
+        // Create Layer that contains first_mod & second_mod
+        Layer layer = Layer.boot().defineModules(cf, map::get);
+
+        assertTrue(layer.findLoader("first_mod") == loader);
+        assertTrue(layer.findLoader("second_mod") == loader);
+        assertTrue(layer.findLoader("java.base") == null);
+
+        Class p2_c2_class = loader.loadClass("p2.c2");
+        Class p1_c1_class = loader.loadClass("p1.c1");
+        Class p4_c4_class = loader.loadClass("p4.c4");
+
+        Module first_mod = p1_c1_class.getModule();
+        Module second_mod = p2_c2_class.getModule();
+
+        // Export first_mod/p1 and first_mod/p4 to all unnamed modules so that
+        // this test can use them
+        jdk.internal.module.Modules.addExportsToAllUnnamed(first_mod, "p1");
+        jdk.internal.module.Modules.addExportsToAllUnnamed(first_mod, "p4");
+
+        // First access check for p1.c1
+        try {
+            p1_c1_class.newInstance();
+            throw new RuntimeException("Test Failed, module first_mod should not have access to p2.c2");
+        } catch (IllegalAccessError e) {
+            String message = e.getMessage();
+            if (!(message.contains("cannot access") &&
+                  message.contains("because module first_mod does not read module second_mod"))) {
+                throw new RuntimeException("Wrong message: " + message);
+            } else {
+                System.out.println("Test Succeeded at attempt #1");
+            }
+        }
+
+        // Add a read edge from p4/c4's module (first_mod) to second_mod
+        p4.c4 c4_obj = new p4.c4();
+        c4_obj.addReads(second_mod);
+
+        // Second access check for p1.c1, should have same result as first
+        try {
+            p1_c1_class.newInstance();
+            throw new RuntimeException("Test Failed, access should have been cached above");
+        } catch (IllegalAccessError e) {
+            String message = e.getMessage();
+            if (!(message.contains("cannot access") &&
+                  message.contains("because module first_mod does not read module second_mod"))) {
+                throw new RuntimeException("Wrong message: " + message);
+            } else {
+                System.out.println("Test Succeeded at attempt #2");
+            }
+        }
+    }
+
+    public static void main(String args[]) throws Throwable {
+      AccessReadTwice test = new AccessReadTwice();
+      test.createLayerOnBoot();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/modules/AccessCheck/p4/c4.java	Fri Jan 13 18:26:34 2017 +0100
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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.
+ */
+
+// Small class used by multiple hotspot/runtime/modules/AccessCheck/* tests.
+
+package p4;
+
+import java.lang.reflect.Module;
+
+public class c4 {
+    // Add a read edge from c4's module to given module m
+    public void addReads(Module m) {
+        c4.class.getModule().addReads(m);
+    }
+}
--- a/hotspot/test/serviceability/sa/jmap-hprof/JMapHProfLargeHeapProc.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/test/serviceability/sa/jmap-hprof/JMapHProfLargeHeapProc.java	Fri Jan 13 18:26:34 2017 +0100
@@ -21,12 +21,9 @@
  * questions.
  */
 
-import java.lang.management.ManagementFactory;
-import java.lang.management.RuntimeMXBean;
-import java.lang.reflect.Field;
-import java.lang.reflect.Method;
 import java.util.ArrayList;
 import java.util.List;
+import jdk.test.lib.process.ProcessTools;
 
 import sun.management.VMManagement;
 
@@ -38,7 +35,7 @@
         buildLargeHeap(args);
 
         // Print our pid on stdout
-        System.out.println("PID[" + getProcessId() + "]");
+        System.out.println("PID[" + ProcessTools.getProcessId() + "]");
 
         // Wait for input before termination
         System.in.read();
@@ -50,22 +47,4 @@
         }
     }
 
-    public static int getProcessId() throws Exception {
-
-        // Get the current process id using a reflection hack
-        RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
-        Field jvm = runtime.getClass().getDeclaredField("jvm");
-
-        jvm.setAccessible(true);
-        VMManagement mgmt = (sun.management.VMManagement) jvm.get(runtime);
-
-        Method pid_method = mgmt.getClass().getDeclaredMethod("getProcessId");
-
-        pid_method.setAccessible(true);
-
-        int pid = (Integer) pid_method.invoke(mgmt);
-
-        return pid;
-    }
-
 }
--- a/hotspot/test/serviceability/sa/jmap-hprof/JMapHProfLargeHeapTest.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/test/serviceability/sa/jmap-hprof/JMapHProfLargeHeapTest.java	Fri Jan 13 18:26:34 2017 +0100
@@ -90,6 +90,9 @@
         try (Scanner largeHeapScanner = new Scanner(
                 largeHeapProc.getInputStream());) {
             String pidstring = null;
+            if (!largeHeapScanner.hasNext()) {
+                throw new RuntimeException ("Test failed: could not open largeHeapScanner.");
+            }
             while ((pidstring = largeHeapScanner.findInLine("PID\\[[0-9].*\\]")) == null) {
                 Thread.sleep(500);
             }
--- a/hotspot/test/testlibrary/ctw/src/sun/hotspot/tools/ctw/CompileTheWorld.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/test/testlibrary/ctw/src/sun/hotspot/tools/ctw/CompileTheWorld.java	Fri Jan 13 18:26:34 2017 +0100
@@ -59,6 +59,8 @@
             OUT = os;
         }
 
+        boolean passed = false;
+
         try {
             try {
                 if (ManagementFactory.getCompilationMXBean() == null) {
@@ -84,10 +86,10 @@
                     PathHandler.getClassCount(),
                     Compiler.getMethodCount(),
                     System.currentTimeMillis() - start);
+            passed = true;
         } finally {
-            if (os != null) {
-                os.close();
-            }
+            // <clinit> might have started new threads
+            System.exit(passed ? 0 : 1);
         }
     }
 
--- a/hotspot/test/testlibrary_tests/ctw/ClassesDirTest.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/test/testlibrary_tests/ctw/ClassesDirTest.java	Fri Jan 13 18:26:34 2017 +0100
@@ -30,11 +30,11 @@
  *          java.base/jdk.internal.reflect
  *          java.management
  * @build sun.hotspot.WhiteBox Foo Bar
- * @run main ClassFileInstaller sun.hotspot.WhiteBox Foo Bar
- *                              sun.hotspot.WhiteBox$WhiteBoxPermission
- * @run main ClassesDirTest prepare
- * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Dsun.hotspot.tools.ctw.logfile=ctw.log sun.hotspot.tools.ctw.CompileTheWorld classes
- * @run main ClassesDirTest check ctw.log
+ * @run driver ClassFileInstaller sun.hotspot.WhiteBox Foo Bar
+ *                                sun.hotspot.WhiteBox$WhiteBoxPermission
+ * @run driver ClassesDirTest prepare
+ * @run driver ClassesDirTest compile classes
+ * @run driver ClassesDirTest check
  * @summary testing of CompileTheWorld :: classes in directory
  * @author igor.ignatyev@oracle.com
  */
--- a/hotspot/test/testlibrary_tests/ctw/ClassesListTest.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/test/testlibrary_tests/ctw/ClassesListTest.java	Fri Jan 13 18:26:34 2017 +0100
@@ -30,11 +30,11 @@
  *          java.base/jdk.internal.reflect
  *          java.management
  * @build sun.hotspot.WhiteBox Foo Bar
- * @run main ClassFileInstaller sun.hotspot.WhiteBox Foo Bar
- *                              sun.hotspot.WhiteBox$WhiteBoxPermission
- * @run main ClassesListTest prepare
- * @run main/othervm/timeout=600 -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Dsun.hotspot.tools.ctw.logfile=ctw.log sun.hotspot.tools.ctw.CompileTheWorld classes.lst
- * @run main ClassesListTest check ctw.log
+ * @run driver ClassFileInstaller sun.hotspot.WhiteBox Foo Bar
+ *                                sun.hotspot.WhiteBox$WhiteBoxPermission
+ * @run driver ClassesListTest prepare
+ * @run driver/timeout=600 ClassesListTest compile classes.lst
+ * @run driver ClassesListTest check
  * @summary testing of CompileTheWorld :: list of classes in file
  * @author igor.ignatyev@oracle.com
  */
--- a/hotspot/test/testlibrary_tests/ctw/CtwTest.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/test/testlibrary_tests/ctw/CtwTest.java	Fri Jan 13 18:26:34 2017 +0100
@@ -21,6 +21,7 @@
  * questions.
  */
 
+import java.util.Arrays;
 import java.util.List;
 import java.util.Collections;
 import java.util.ArrayList;
@@ -38,8 +39,20 @@
 
 import jdk.test.lib.JDKToolFinder;
 import jdk.test.lib.process.OutputAnalyzer;
+import jdk.test.lib.process.ProcessTools;
 
 public abstract class CtwTest {
+    private static final String LOG_FILE = "ctw.log";
+    private static final String[] CTW_COMMAND = {
+        "-Xbootclasspath/a:.",
+        "-XX:+UnlockDiagnosticVMOptions",
+        "-XX:+WhiteBoxAPI",
+        "-Dsun.hotspot.tools.ctw.logfile=" + LOG_FILE,
+        "--add-exports", "java.base/jdk.internal.jimage=ALL-UNNAMED",
+        "--add-exports", "java.base/jdk.internal.misc=ALL-UNNAMED",
+        "--add-exports", "java.base/jdk.internal.reflect=ALL-UNNAMED",
+        sun.hotspot.tools.ctw.CompileTheWorld.class.getName(),
+    };
     protected final String[] shouldContain;
     protected CtwTest(String[] shouldContain) {
         this.shouldContain = shouldContain;
@@ -54,7 +67,10 @@
                 prepare();
                 break;
             case "check":
-                check(args);
+                check();
+                break;
+            case "compile":
+                compile(args);
                 break;
             default:
                 throw new Error("unregonized action -- " + args[0]);
@@ -63,20 +79,27 @@
 
     protected void prepare() throws Exception { }
 
-    protected void check(String[] args) throws Exception  {
-        if (args.length < 2) {
-            throw new Error("logfile isn't specified");
-        }
-        String logfile = args[1];
-        try (BufferedReader r = Files.newBufferedReader(Paths.get(logfile),
+    protected void check() throws Exception  {
+        try (BufferedReader r = Files.newBufferedReader(Paths.get(LOG_FILE),
                 Charset.defaultCharset())) {
             OutputAnalyzer output = readOutput(r);
-           for (String test : shouldContain) {
+            for (String test : shouldContain) {
                 output.shouldContain(test);
             }
         }
     }
 
+    protected void compile(String[] args) throws Exception {
+        // concat CTW_COMMAND and args w/o 0th element
+        String[] cmd = Arrays.copyOf(CTW_COMMAND, CTW_COMMAND.length + args.length - 1);
+        System.arraycopy(args, 1, cmd, CTW_COMMAND.length, args.length - 1);
+
+        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(true, cmd);
+        OutputAnalyzer output = new OutputAnalyzer(pb.start());
+        dump(output, "compile");
+        output.shouldHaveExitValue(0);
+    }
+
     private static OutputAnalyzer readOutput(BufferedReader reader)
             throws IOException {
         StringBuilder builder = new StringBuilder();
--- a/hotspot/test/testlibrary_tests/ctw/JarDirTest.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/test/testlibrary_tests/ctw/JarDirTest.java	Fri Jan 13 18:26:34 2017 +0100
@@ -32,11 +32,11 @@
  *          java.management
  *          jdk.jvmstat/sun.jvmstat.monitor
  * @build sun.hotspot.WhiteBox Foo Bar
- * @run main ClassFileInstaller sun.hotspot.WhiteBox Foo Bar
- *                              sun.hotspot.WhiteBox$WhiteBoxPermission
- * @run main JarDirTest prepare
- * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Dsun.hotspot.tools.ctw.logfile=ctw.log sun.hotspot.tools.ctw.CompileTheWorld jars/*
- * @run main JarDirTest check ctw.log
+ * @run driver ClassFileInstaller sun.hotspot.WhiteBox Foo Bar
+ *                                sun.hotspot.WhiteBox$WhiteBoxPermission
+ * @run driver JarDirTest prepare
+ * @run driver JarDirTest compile jars/*
+ * @run driver JarDirTest check
  * @summary testing of CompileTheWorld :: jars in directory
  * @author igor.ignatyev@oracle.com
  */
--- a/hotspot/test/testlibrary_tests/ctw/JarsTest.java	Wed Jul 05 22:40:29 2017 +0200
+++ b/hotspot/test/testlibrary_tests/ctw/JarsTest.java	Fri Jan 13 18:26:34 2017 +0100
@@ -32,11 +32,11 @@
  *          java.management
  *          jdk.jvmstat/sun.jvmstat.monitor
  * @build sun.hotspot.WhiteBox Foo Bar
- * @run main ClassFileInstaller sun.hotspot.WhiteBox Foo Bar
- *                              sun.hotspot.WhiteBox$WhiteBoxPermission
- * @run main JarsTest prepare
- * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Dsun.hotspot.tools.ctw.logfile=ctw.log sun.hotspot.tools.ctw.CompileTheWorld foo.jar bar.jar
- * @run main JarsTest check ctw.log
+ * @run driver ClassFileInstaller sun.hotspot.WhiteBox Foo Bar
+ *                                sun.hotspot.WhiteBox$WhiteBoxPermission
+ * @run driver JarsTest prepare
+ * @run driver JarsTest compile foo.jar bar.jar
+ * @run driver JarsTest check
  * @summary testing of CompileTheWorld :: jars
  * @author igor.ignatyev@oracle.com
  */