changeset 27116:64a78dd93766

Merge
author duke
date Wed, 05 Jul 2017 20:04:39 +0200
parents 2a65d9f1c324 cc60649130bb
children 98b357b2e8a6
files jdk/test/java/security/cert/CertificateFactory/invalidEncodedCerts/invalidcert.pem jdk/test/javax/xml/jaxp/testng/validation/8037819/BaseTest.java jdk/test/javax/xml/jaxp/testng/validation/8037819/BasicTest.java jdk/test/javax/xml/jaxp/testng/validation/8037819/FixedAttrTest.java jdk/test/javax/xml/jaxp/testng/validation/8037819/IdIdrefCheckingTest.java jdk/test/javax/xml/jaxp/testng/validation/8037819/IdentityConstraintCheckingTest.java jdk/test/javax/xml/jaxp/testng/validation/8037819/IgnoreXSITypeTest_A_A.java jdk/test/javax/xml/jaxp/testng/validation/8037819/IgnoreXSITypeTest_A_C.java jdk/test/javax/xml/jaxp/testng/validation/8037819/IgnoreXSITypeTest_C_A.java jdk/test/javax/xml/jaxp/testng/validation/8037819/IgnoreXSITypeTest_C_AC.java jdk/test/javax/xml/jaxp/testng/validation/8037819/IgnoreXSITypeTest_C_C.java jdk/test/javax/xml/jaxp/testng/validation/8037819/IgnoreXSITypeTest_C_CA.java jdk/test/javax/xml/jaxp/testng/validation/8037819/RootTypeDefinitionTest.java jdk/test/javax/xml/jaxp/testng/validation/8037819/SpecialCaseErrorHandler.java jdk/test/javax/xml/jaxp/testng/validation/8037819/TEST.properties jdk/test/javax/xml/jaxp/testng/validation/8037819/UnparsedEntityCheckingTest.java jdk/test/javax/xml/jaxp/testng/validation/8037819/UseGrammarPoolOnlyTest_False.java jdk/test/javax/xml/jaxp/testng/validation/8037819/UseGrammarPoolOnlyTest_True.java jdk/test/javax/xml/jaxp/testng/validation/8037819/base.xml jdk/test/javax/xml/jaxp/testng/validation/8037819/base.xsd jdk/test/javax/xml/jaxp/testng/validation/8037819/fixedAttr.xml jdk/test/javax/xml/jaxp/testng/validation/8037819/idIdref.xml jdk/test/javax/xml/jaxp/testng/validation/8037819/idc.xml jdk/test/javax/xml/jaxp/testng/validation/8037819/idc.xsd jdk/test/javax/xml/jaxp/testng/validation/8037819/otherNamespace.xml jdk/test/javax/xml/jaxp/testng/validation/8037819/otherNamespace.xsd jdk/test/javax/xml/jaxp/testng/validation/8037819/unparsedEntity.dtd jdk/test/javax/xml/jaxp/testng/validation/8037819/unparsedEntity.xml jdk/test/javax/xml/jaxp/testng/validation/8037819/xsitype_A_A.xml jdk/test/javax/xml/jaxp/testng/validation/8037819/xsitype_A_C.xml jdk/test/javax/xml/jaxp/testng/validation/8037819/xsitype_C_A.xml jdk/test/javax/xml/jaxp/testng/validation/8037819/xsitype_C_AC.xml jdk/test/javax/xml/jaxp/testng/validation/8037819/xsitype_C_C.xml jdk/test/javax/xml/jaxp/testng/validation/8037819/xsitype_C_CA.xml jdk/test/tools/jar/normalize/TestNormal.java
diffstat 412 files changed, 13278 insertions(+), 6061 deletions(-) [+]
line wrap: on
line diff
--- a/.hgtags-top-repo	Thu Oct 16 12:02:03 2014 -0700
+++ b/.hgtags-top-repo	Wed Jul 05 20:04:39 2017 +0200
@@ -277,3 +277,4 @@
 7e3512dae8e020d44399c0f1c579ff1fe3090ed6 jdk9-b32
 e4ba01b726e263953ae129be37c94de6ed145b1d jdk9-b33
 087b23f35631e68e950496a36fce8ccca612966a jdk9-b34
+c173ba994245380fb11ef077d1e59823386840eb jdk9-b35
--- a/corba/.hgtags	Thu Oct 16 12:02:03 2014 -0700
+++ b/corba/.hgtags	Wed Jul 05 20:04:39 2017 +0200
@@ -277,3 +277,4 @@
 b5b139354630edb2d06190bf31653acbdcea63a8 jdk9-b32
 cfdac5887952c2dd73c73a1d8d9aa880d0539bbf jdk9-b33
 24a0bad5910f775bb4002d1dacf8b3af87c63cd8 jdk9-b34
+9bc2dbd3dfb8c9fa88e00056b8b93a81ee6d306e jdk9-b35
--- a/hotspot/.hgtags	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/.hgtags	Wed Jul 05 20:04:39 2017 +0200
@@ -437,3 +437,4 @@
 af46576a8d7cb4003028b8ee8bf408cfe227315b jdk9-b32
 9b3f5e4f33725f7c1d9b8e523133fe8383a54d9f jdk9-b33
 821164b0131a47ca065697c7d27d8f215e608c8d jdk9-b34
+438cb613151c4bd290bb732697517cba1cafcb04 jdk9-b35
--- a/hotspot/make/aix/makefiles/fastdebug.make	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/make/aix/makefiles/fastdebug.make	Wed Jul 05 20:04:39 2017 +0200
@@ -67,7 +67,6 @@
 #    not justified.
 LFLAGS_QIPA=
 
-G_SUFFIX = _g
 VERSION = optimized
 SYSDEFS += -DASSERT -DFASTDEBUG
 PICFLAGS = DEFAULT
--- a/hotspot/make/aix/makefiles/mapfile-vers-debug	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/make/aix/makefiles/mapfile-vers-debug	Wed Jul 05 20:04:39 2017 +0200
@@ -84,6 +84,7 @@
                 JVM_EnableCompiler;
                 JVM_Exit;
                 JVM_FillInStackTrace;
+                JVM_FindClassFromCaller;
                 JVM_FindClassFromClass;
                 JVM_FindClassFromClassLoader;
                 JVM_FindClassFromBootLoader;
@@ -117,7 +118,6 @@
                 JVM_GetClassDeclaredMethods;
                 JVM_GetClassFieldsCount;
                 JVM_GetClassInterfaces;
-                JVM_GetClassLoader;
                 JVM_GetClassMethodsCount;
                 JVM_GetClassModifiers;
                 JVM_GetClassName;
--- a/hotspot/make/aix/makefiles/mapfile-vers-product	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/make/aix/makefiles/mapfile-vers-product	Wed Jul 05 20:04:39 2017 +0200
@@ -84,6 +84,7 @@
                 JVM_EnableCompiler;
                 JVM_Exit;
                 JVM_FillInStackTrace;
+                JVM_FindClassFromCaller;
                 JVM_FindClassFromClass;
                 JVM_FindClassFromClassLoader;
                 JVM_FindClassFromBootLoader;
@@ -117,7 +118,6 @@
                 JVM_GetClassDeclaredMethods;
                 JVM_GetClassFieldsCount;
                 JVM_GetClassInterfaces;
-                JVM_GetClassLoader;
                 JVM_GetClassMethodsCount;
                 JVM_GetClassModifiers;
                 JVM_GetClassName;
--- a/hotspot/make/bsd/makefiles/mapfile-vers-darwin-debug	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/make/bsd/makefiles/mapfile-vers-darwin-debug	Wed Jul 05 20:04:39 2017 +0200
@@ -82,6 +82,7 @@
                 _JVM_EnableCompiler
                 _JVM_Exit
                 _JVM_FillInStackTrace
+                _JVM_FindClassFromCaller
                 _JVM_FindClassFromClass
                 _JVM_FindClassFromClassLoader
                 _JVM_FindClassFromBootLoader
@@ -115,7 +116,6 @@
                 _JVM_GetClassDeclaredMethods
                 _JVM_GetClassFieldsCount
                 _JVM_GetClassInterfaces
-                _JVM_GetClassLoader
                 _JVM_GetClassMethodsCount
                 _JVM_GetClassModifiers
                 _JVM_GetClassName
--- a/hotspot/make/bsd/makefiles/mapfile-vers-darwin-product	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/make/bsd/makefiles/mapfile-vers-darwin-product	Wed Jul 05 20:04:39 2017 +0200
@@ -82,6 +82,7 @@
                 _JVM_EnableCompiler
                 _JVM_Exit
                 _JVM_FillInStackTrace
+                _JVM_FindClassFromCaller
                 _JVM_FindClassFromClass
                 _JVM_FindClassFromClassLoader
                 _JVM_FindClassFromBootLoader
@@ -115,7 +116,6 @@
                 _JVM_GetClassDeclaredMethods
                 _JVM_GetClassFieldsCount
                 _JVM_GetClassInterfaces
-                _JVM_GetClassLoader
                 _JVM_GetClassMethodsCount
                 _JVM_GetClassModifiers
                 _JVM_GetClassName
--- a/hotspot/make/bsd/makefiles/mapfile-vers-debug	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/make/bsd/makefiles/mapfile-vers-debug	Wed Jul 05 20:04:39 2017 +0200
@@ -84,6 +84,7 @@
                 JVM_EnableCompiler;
                 JVM_Exit;
                 JVM_FillInStackTrace;
+                JVM_FindClassFromCaller;
                 JVM_FindClassFromClass;
                 JVM_FindClassFromClassLoader;
                 JVM_FindClassFromBootLoader;
@@ -117,7 +118,6 @@
                 JVM_GetClassDeclaredMethods;
                 JVM_GetClassFieldsCount;
                 JVM_GetClassInterfaces;
-                JVM_GetClassLoader;
                 JVM_GetClassMethodsCount;
                 JVM_GetClassModifiers;
                 JVM_GetClassName;
--- a/hotspot/make/bsd/makefiles/mapfile-vers-product	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/make/bsd/makefiles/mapfile-vers-product	Wed Jul 05 20:04:39 2017 +0200
@@ -84,6 +84,7 @@
                 JVM_EnableCompiler;
                 JVM_Exit;
                 JVM_FillInStackTrace;
+                JVM_FindClassFromCaller;
                 JVM_FindClassFromClass;
                 JVM_FindClassFromClassLoader;
                 JVM_FindClassFromBootLoader;
@@ -117,7 +118,6 @@
                 JVM_GetClassDeclaredMethods;
                 JVM_GetClassFieldsCount;
                 JVM_GetClassInterfaces;
-                JVM_GetClassLoader;
                 JVM_GetClassMethodsCount;
                 JVM_GetClassModifiers;
                 JVM_GetClassName;
--- a/hotspot/make/linux/makefiles/mapfile-vers-debug	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/make/linux/makefiles/mapfile-vers-debug	Wed Jul 05 20:04:39 2017 +0200
@@ -84,6 +84,7 @@
                 JVM_EnableCompiler;
                 JVM_Exit;
                 JVM_FillInStackTrace;
+                JVM_FindClassFromCaller;
                 JVM_FindClassFromClass;
                 JVM_FindClassFromClassLoader;
                 JVM_FindClassFromBootLoader;
@@ -117,7 +118,6 @@
                 JVM_GetClassDeclaredMethods;
                 JVM_GetClassFieldsCount;
                 JVM_GetClassInterfaces;
-                JVM_GetClassLoader;
                 JVM_GetClassMethodsCount;
                 JVM_GetClassModifiers;
                 JVM_GetClassName;
--- a/hotspot/make/linux/makefiles/mapfile-vers-product	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/make/linux/makefiles/mapfile-vers-product	Wed Jul 05 20:04:39 2017 +0200
@@ -84,6 +84,7 @@
                 JVM_EnableCompiler;
                 JVM_Exit;
                 JVM_FillInStackTrace;
+                JVM_FindClassFromCaller;
                 JVM_FindClassFromClass;
                 JVM_FindClassFromClassLoader;
                 JVM_FindClassFromBootLoader;
@@ -117,7 +118,6 @@
                 JVM_GetClassDeclaredMethods;
                 JVM_GetClassFieldsCount;
                 JVM_GetClassInterfaces;
-                JVM_GetClassLoader;
                 JVM_GetClassMethodsCount;
                 JVM_GetClassModifiers;
                 JVM_GetClassName;
--- a/hotspot/make/solaris/makefiles/mapfile-vers	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/make/solaris/makefiles/mapfile-vers	Wed Jul 05 20:04:39 2017 +0200
@@ -84,6 +84,7 @@
                 JVM_EnableCompiler;
                 JVM_Exit;
                 JVM_FillInStackTrace;
+                JVM_FindClassFromCaller;
                 JVM_FindClassFromClass;
                 JVM_FindClassFromClassLoader;
                 JVM_FindClassFromBootLoader;
@@ -117,7 +118,6 @@
                 JVM_GetClassDeclaredMethods;
                 JVM_GetClassFieldsCount;
                 JVM_GetClassInterfaces;
-                JVM_GetClassLoader;
                 JVM_GetClassMethodsCount;
                 JVM_GetClassModifiers;
                 JVM_GetClassName;
--- a/hotspot/src/cpu/ppc/vm/assembler_ppc.hpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/cpu/ppc/vm/assembler_ppc.hpp	Wed Jul 05 20:04:39 2017 +0200
@@ -268,8 +268,35 @@
 
     ISEL_OPCODE   = (31u << OPCODE_SHIFT |  15u << 1),
 
-    MTLR_OPCODE   = (31u << OPCODE_SHIFT | 467u << 1 | 8 << SPR_0_4_SHIFT),
-    MFLR_OPCODE   = (31u << OPCODE_SHIFT | 339u << 1 | 8 << SPR_0_4_SHIFT),
+    // Special purpose registers
+    MTSPR_OPCODE  = (31u << OPCODE_SHIFT | 467u << 1),
+    MFSPR_OPCODE  = (31u << OPCODE_SHIFT | 339u << 1),
+
+    MTXER_OPCODE  = (MTSPR_OPCODE | 1 << SPR_0_4_SHIFT),
+    MFXER_OPCODE  = (MFSPR_OPCODE | 1 << SPR_0_4_SHIFT),
+
+    MTDSCR_OPCODE = (MTSPR_OPCODE | 3 << SPR_0_4_SHIFT),
+    MFDSCR_OPCODE = (MFSPR_OPCODE | 3 << SPR_0_4_SHIFT),
+
+    MTLR_OPCODE   = (MTSPR_OPCODE | 8 << SPR_0_4_SHIFT),
+    MFLR_OPCODE   = (MFSPR_OPCODE | 8 << SPR_0_4_SHIFT),
+
+    MTCTR_OPCODE  = (MTSPR_OPCODE | 9 << SPR_0_4_SHIFT),
+    MFCTR_OPCODE  = (MFSPR_OPCODE | 9 << SPR_0_4_SHIFT),
+
+    MTTFHAR_OPCODE   = (MTSPR_OPCODE | 128 << SPR_0_4_SHIFT),
+    MFTFHAR_OPCODE   = (MFSPR_OPCODE | 128 << SPR_0_4_SHIFT),
+    MTTFIAR_OPCODE   = (MTSPR_OPCODE | 129 << SPR_0_4_SHIFT),
+    MFTFIAR_OPCODE   = (MFSPR_OPCODE | 129 << SPR_0_4_SHIFT),
+    MTTEXASR_OPCODE  = (MTSPR_OPCODE | 130 << SPR_0_4_SHIFT),
+    MFTEXASR_OPCODE  = (MFSPR_OPCODE | 130 << SPR_0_4_SHIFT),
+    MTTEXASRU_OPCODE = (MTSPR_OPCODE | 131 << SPR_0_4_SHIFT),
+    MFTEXASRU_OPCODE = (MFSPR_OPCODE | 131 << SPR_0_4_SHIFT),
+
+    MTVRSAVE_OPCODE  = (MTSPR_OPCODE | 256 << SPR_0_4_SHIFT),
+    MFVRSAVE_OPCODE  = (MFSPR_OPCODE | 256 << SPR_0_4_SHIFT),
+
+    MFTB_OPCODE   = (MFSPR_OPCODE | 268 << SPR_0_4_SHIFT),
 
     MTCRF_OPCODE  = (31u << OPCODE_SHIFT | 144u << 1),
     MFCR_OPCODE   = (31u << OPCODE_SHIFT | 19u << 1),
@@ -291,9 +318,6 @@
 
     // CTR-related opcodes
     BCCTR_OPCODE  = (19u << OPCODE_SHIFT | 528u << 1),
-    MTCTR_OPCODE  = (31u << OPCODE_SHIFT | 467u << 1 | 9 << SPR_0_4_SHIFT),
-    MFCTR_OPCODE  = (31u << OPCODE_SHIFT | 339u << 1 | 9 << SPR_0_4_SHIFT),
-
 
     LWZ_OPCODE   = (32u << OPCODE_SHIFT),
     LWZX_OPCODE  = (31u << OPCODE_SHIFT |  23u << 1),
@@ -585,6 +609,37 @@
     MTVSCR_OPCODE  = (4u  << OPCODE_SHIFT | 1604u     ),
     MFVSCR_OPCODE  = (4u  << OPCODE_SHIFT | 1540u     ),
 
+    // AES (introduced with Power 8)
+    VCIPHER_OPCODE      = (4u  << OPCODE_SHIFT | 1288u),
+    VCIPHERLAST_OPCODE  = (4u  << OPCODE_SHIFT | 1289u),
+    VNCIPHER_OPCODE     = (4u  << OPCODE_SHIFT | 1352u),
+    VNCIPHERLAST_OPCODE = (4u  << OPCODE_SHIFT | 1353u),
+    VSBOX_OPCODE        = (4u  << OPCODE_SHIFT | 1480u),
+
+    // SHA (introduced with Power 8)
+    VSHASIGMAD_OPCODE   = (4u  << OPCODE_SHIFT | 1730u),
+    VSHASIGMAW_OPCODE   = (4u  << OPCODE_SHIFT | 1666u),
+
+    // Vector Binary Polynomial Multiplication (introduced with Power 8)
+    VPMSUMB_OPCODE      = (4u  << OPCODE_SHIFT | 1032u),
+    VPMSUMD_OPCODE      = (4u  << OPCODE_SHIFT | 1224u),
+    VPMSUMH_OPCODE      = (4u  << OPCODE_SHIFT | 1096u),
+    VPMSUMW_OPCODE      = (4u  << OPCODE_SHIFT | 1160u),
+
+    // Vector Permute and Xor (introduced with Power 8)
+    VPERMXOR_OPCODE     = (4u  << OPCODE_SHIFT |   45u),
+
+    // Transactional Memory instructions (introduced with Power 8)
+    TBEGIN_OPCODE    = (31u << OPCODE_SHIFT |  654u << 1),
+    TEND_OPCODE      = (31u << OPCODE_SHIFT |  686u << 1),
+    TABORT_OPCODE    = (31u << OPCODE_SHIFT |  910u << 1),
+    TABORTWC_OPCODE  = (31u << OPCODE_SHIFT |  782u << 1),
+    TABORTWCI_OPCODE = (31u << OPCODE_SHIFT |  846u << 1),
+    TABORTDC_OPCODE  = (31u << OPCODE_SHIFT |  814u << 1),
+    TABORTDCI_OPCODE = (31u << OPCODE_SHIFT |  878u << 1),
+    TSR_OPCODE       = (31u << OPCODE_SHIFT |  750u << 1),
+    TCHECK_OPCODE    = (31u << OPCODE_SHIFT |  718u << 1),
+
     // Icache and dcache related instructions
     DCBA_OPCODE    = (31u << OPCODE_SHIFT |  758u << 1),
     DCBZ_OPCODE    = (31u << OPCODE_SHIFT | 1014u << 1),
@@ -1420,6 +1475,25 @@
   inline void mcrf( ConditionRegister crd, ConditionRegister cra);
   inline void mtcr( Register s);
 
+  // Special purpose registers
+  // Exception Register
+  inline void mtxer(Register s1);
+  inline void mfxer(Register d);
+  // Vector Register Save Register
+  inline void mtvrsave(Register s1);
+  inline void mfvrsave(Register d);
+  // Timebase
+  inline void mftb(Register d);
+  // Introduced with Power 8:
+  // Data Stream Control Register
+  inline void mtdscr(Register s1);
+  inline void mfdscr(Register d );
+  // Transactional Memory Registers
+  inline void mftfhar(Register d);
+  inline void mftfiar(Register d);
+  inline void mftexasr(Register d);
+  inline void mftexasru(Register d);
+
   // PPC 1, section 2.4.1 Branch Instructions
   inline void b(  address a, relocInfo::relocType rt = relocInfo::none);
   inline void b(  Label& L);
@@ -1860,6 +1934,39 @@
   inline void mtvscr(   VectorRegister b);
   inline void mfvscr(   VectorRegister d);
 
+  // AES (introduced with Power 8)
+  inline void vcipher(     VectorRegister d, VectorRegister a, VectorRegister b);
+  inline void vcipherlast( VectorRegister d, VectorRegister a, VectorRegister b);
+  inline void vncipher(    VectorRegister d, VectorRegister a, VectorRegister b);
+  inline void vncipherlast(VectorRegister d, VectorRegister a, VectorRegister b);
+  inline void vsbox(       VectorRegister d, VectorRegister a);
+
+  // SHA (introduced with Power 8)
+  // Not yet implemented.
+
+  // Vector Binary Polynomial Multiplication (introduced with Power 8)
+  inline void vpmsumb(  VectorRegister d, VectorRegister a, VectorRegister b);
+  inline void vpmsumd(  VectorRegister d, VectorRegister a, VectorRegister b);
+  inline void vpmsumh(  VectorRegister d, VectorRegister a, VectorRegister b);
+  inline void vpmsumw(  VectorRegister d, VectorRegister a, VectorRegister b);
+
+  // Vector Permute and Xor (introduced with Power 8)
+  inline void vpermxor( VectorRegister d, VectorRegister a, VectorRegister b, VectorRegister c);
+
+  // Transactional Memory instructions (introduced with Power 8)
+  inline void tbegin_();    // R=0
+  inline void tbeginrot_(); // R=1 Rollback-Only Transaction
+  inline void tend_();    // A=0
+  inline void tendall_(); // A=1
+  inline void tabort_(Register a);
+  inline void tabortwc_(int t, Register a, Register b);
+  inline void tabortwci_(int t, Register a, int si);
+  inline void tabortdc_(int t, Register a, Register b);
+  inline void tabortdci_(int t, Register a, int si);
+  inline void tsuspend_(); // tsr with L=0
+  inline void tresume_();  // tsr with L=1
+  inline void tcheck(int f);
+
   // The following encoders use r0 as second operand. These instructions
   // read r0 as '0'.
   inline void lwzx( Register d, Register s2);
--- a/hotspot/src/cpu/ppc/vm/assembler_ppc.inline.hpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/cpu/ppc/vm/assembler_ppc.inline.hpp	Wed Jul 05 20:04:39 2017 +0200
@@ -312,6 +312,25 @@
                                                       { emit_int32(MCRF_OPCODE | bf(crd) | bfa(cra)); }
 inline void Assembler::mtcr( Register s)          { Assembler::mtcrf(0xff, s); }
 
+// Special purpose registers
+// Exception Register
+inline void Assembler::mtxer(Register s1)         { emit_int32(MTXER_OPCODE | rs(s1)); }
+inline void Assembler::mfxer(Register d )         { emit_int32(MFXER_OPCODE | rt(d)); }
+// Vector Register Save Register
+inline void Assembler::mtvrsave(Register s1)      { emit_int32(MTVRSAVE_OPCODE | rs(s1)); }
+inline void Assembler::mfvrsave(Register d )      { emit_int32(MFVRSAVE_OPCODE | rt(d)); }
+// Timebase
+inline void Assembler::mftb(Register d )          { emit_int32(MFTB_OPCODE  | rt(d)); }
+// Introduced with Power 8:
+// Data Stream Control Register
+inline void Assembler::mtdscr(Register s1)        { emit_int32(MTDSCR_OPCODE | rs(s1)); }
+inline void Assembler::mfdscr(Register d )        { emit_int32(MFDSCR_OPCODE | rt(d)); }
+// Transactional Memory Registers
+inline void Assembler::mftfhar(Register d )       { emit_int32(MFTFHAR_OPCODE   | rt(d)); }
+inline void Assembler::mftfiar(Register d )       { emit_int32(MFTFIAR_OPCODE   | rt(d)); }
+inline void Assembler::mftexasr(Register d )      { emit_int32(MFTEXASR_OPCODE  | rt(d)); }
+inline void Assembler::mftexasru(Register d )     { emit_int32(MFTEXASRU_OPCODE | rt(d)); }
+
 // SAP JVM 2006-02-13 PPC branch instruction.
 // PPC 1, section 2.4.1 Branch Instructions
 inline void Assembler::b( address a, relocInfo::relocType rt) { emit_data(BXX_OPCODE| li(disp( intptr_t(a), intptr_t(pc()))) |aa(0)|lk(0), rt); }
@@ -735,6 +754,39 @@
 inline void Assembler::mtvscr(  VectorRegister b)                                     { emit_int32( MTVSCR_OPCODE   | vrb(b)); }
 inline void Assembler::mfvscr(  VectorRegister d)                                     { emit_int32( MFVSCR_OPCODE   | vrt(d)); }
 
+// AES (introduced with Power 8)
+inline void Assembler::vcipher(     VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VCIPHER_OPCODE      | vrt(d) | vra(a) | vrb(b)); }
+inline void Assembler::vcipherlast( VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VCIPHERLAST_OPCODE  | vrt(d) | vra(a) | vrb(b)); }
+inline void Assembler::vncipher(    VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VNCIPHER_OPCODE     | vrt(d) | vra(a) | vrb(b)); }
+inline void Assembler::vncipherlast(VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VNCIPHERLAST_OPCODE | vrt(d) | vra(a) | vrb(b)); }
+inline void Assembler::vsbox(       VectorRegister d, VectorRegister a)                   { emit_int32( VSBOX_OPCODE        | vrt(d) | vra(a)         ); }
+
+// SHA (introduced with Power 8)
+// Not yet implemented.
+
+// Vector Binary Polynomial Multiplication (introduced with Power 8)
+inline void Assembler::vpmsumb(  VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VPMSUMB_OPCODE | vrt(d) | vra(a) | vrb(b)); }
+inline void Assembler::vpmsumd(  VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VPMSUMD_OPCODE | vrt(d) | vra(a) | vrb(b)); }
+inline void Assembler::vpmsumh(  VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VPMSUMH_OPCODE | vrt(d) | vra(a) | vrb(b)); }
+inline void Assembler::vpmsumw(  VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VPMSUMW_OPCODE | vrt(d) | vra(a) | vrb(b)); }
+
+// Vector Permute and Xor (introduced with Power 8)
+inline void Assembler::vpermxor( VectorRegister d, VectorRegister a, VectorRegister b, VectorRegister c) { emit_int32( VPMSUMW_OPCODE | vrt(d) | vra(a) | vrb(b) | vrc(c)); }
+
+// Transactional Memory instructions (introduced with Power 8)
+inline void Assembler::tbegin_()                                { emit_int32( TBEGIN_OPCODE | rc(1)); }
+inline void Assembler::tbeginrot_()                             { emit_int32( TBEGIN_OPCODE | /*R=1*/ 1u << (31-10) | rc(1)); }
+inline void Assembler::tend_()                                  { emit_int32( TEND_OPCODE | rc(1)); }
+inline void Assembler::tendall_()                               { emit_int32( TEND_OPCODE | /*A=1*/ 1u << (31-6) | rc(1)); }
+inline void Assembler::tabort_(Register a)                      { emit_int32( TABORT_OPCODE | ra(a) | rc(1)); }
+inline void Assembler::tabortwc_(int t, Register a, Register b) { emit_int32( TABORTWC_OPCODE | to(t) | ra(a) | rb(b) | rc(1)); }
+inline void Assembler::tabortwci_(int t, Register a, int si)    { emit_int32( TABORTWCI_OPCODE | to(t) | ra(a) | sh1620(si) | rc(1)); }
+inline void Assembler::tabortdc_(int t, Register a, Register b) { emit_int32( TABORTDC_OPCODE | to(t) | ra(a) | rb(b) | rc(1)); }
+inline void Assembler::tabortdci_(int t, Register a, int si)    { emit_int32( TABORTDCI_OPCODE | to(t) | ra(a) | sh1620(si) | rc(1)); }
+inline void Assembler::tsuspend_()                              { emit_int32( TSR_OPCODE | rc(1)); }
+inline void Assembler::tresume_()                               { emit_int32( TSR_OPCODE | /*L=1*/ 1u << (31-10) | rc(1)); }
+inline void Assembler::tcheck(int f)                            { emit_int32( TCHECK_OPCODE | bf(f)); }
+
 // ra0 version
 inline void Assembler::lwzx( Register d, Register s2) { emit_int32( LWZX_OPCODE | rt(d) | rb(s2));}
 inline void Assembler::lwz(  Register d, int si16   ) { emit_int32( LWZ_OPCODE  | rt(d) | d1(si16));}
--- a/hotspot/src/cpu/ppc/vm/globalDefinitions_ppc.hpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/cpu/ppc/vm/globalDefinitions_ppc.hpp	Wed Jul 05 20:04:39 2017 +0200
@@ -37,6 +37,8 @@
 // signatures accordingly.
 const bool CCallingConventionRequiresIntsAsLongs = true;
 
+#define SUPPORTS_NATIVE_CX8
+
 // The PPC CPUs are NOT multiple-copy-atomic.
 #define CPU_NOT_MULTIPLE_COPY_ATOMIC
 
--- a/hotspot/src/cpu/ppc/vm/interp_masm_ppc_64.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/cpu/ppc/vm/interp_masm_ppc_64.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -25,7 +25,6 @@
 
 
 #include "precompiled.hpp"
-#include "asm/assembler.hpp"
 #include "asm/macroAssembler.inline.hpp"
 #include "interp_masm_ppc_64.hpp"
 #include "interpreter/interpreterRuntime.hpp"
--- a/hotspot/src/cpu/ppc/vm/interpreter_ppc.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/cpu/ppc/vm/interpreter_ppc.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -24,7 +24,6 @@
  */
 
 #include "precompiled.hpp"
-#include "asm/assembler.hpp"
 #include "asm/macroAssembler.inline.hpp"
 #include "interpreter/bytecodeHistogram.hpp"
 #include "interpreter/interpreter.hpp"
--- a/hotspot/src/cpu/ppc/vm/macroAssembler_ppc.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/cpu/ppc/vm/macroAssembler_ppc.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -2366,7 +2366,7 @@
 #endif // INCLUDE_ALL_GCS
 
 // Values for last_Java_pc, and last_Java_sp must comply to the rules
-// in frame_ppc64.hpp.
+// in frame_ppc.hpp.
 void MacroAssembler::set_last_Java_frame(Register last_Java_sp, Register last_Java_pc) {
   // Always set last_Java_pc and flags first because once last_Java_sp
   // is visible has_last_Java_frame is true and users will look at the
@@ -2493,6 +2493,7 @@
 }
 
 void MacroAssembler::decode_klass_not_null(Register dst, Register src) {
+  assert(dst != R0, "Dst reg may not be R0, as R0 is used here.");
   if (src == noreg) src = dst;
   Register shifted_src = src;
   if (Universe::narrow_klass_shift() != 0 ||
@@ -2527,14 +2528,11 @@
 
 void MacroAssembler::reinit_heapbase(Register d, Register tmp) {
   if (Universe::heap() != NULL) {
-    if (Universe::narrow_oop_base() == NULL) {
-      Assembler::xorr(R30, R30, R30);
-    } else {
-      load_const(R30, Universe::narrow_ptrs_base(), tmp);
-    }
+    load_const_optimized(R30, Universe::narrow_ptrs_base(), tmp);
   } else {
-    load_const(R30, Universe::narrow_ptrs_base_addr(), tmp);
-    ld(R30, 0, R30);
+    // Heap not yet allocated. Load indirectly.
+    int simm16_offset = load_const_optimized(R30, Universe::narrow_ptrs_base_addr(), tmp, true);
+    ld(R30, simm16_offset, R30);
   }
 }
 
--- a/hotspot/src/cpu/ppc/vm/ppc.ad	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/cpu/ppc/vm/ppc.ad	Wed Jul 05 20:04:39 2017 +0200
@@ -1249,6 +1249,7 @@
 
     // Emit the trampoline stub which will be related to the branch-and-link below.
     CallStubImpl::emit_trampoline_stub(_masm, entry_point_toc_offset, offsets.insts_call_instruction_offset);
+    if (Compile::current()->env()->failing()) { return offsets; } // Code cache may be full.
     __ relocate(rtype);
   }
 
@@ -1410,7 +1411,7 @@
     while (bang_offset <= bang_end) {
       // Need at least one stack bang at end of shadow zone.
 
-      // Again I had to copy code, this time from assembler_ppc64.cpp,
+      // Again I had to copy code, this time from assembler_ppc.cpp,
       // bang_stack_with_offset - see there for comments.
 
       // Stack grows down, caller passes positive offset.
@@ -2000,7 +2001,7 @@
 
   // Inline_cache contains a klass.
   Register ic_klass       = as_Register(Matcher::inline_cache_reg_encode());
-  Register receiver_klass = R0;  // tmp
+  Register receiver_klass = R12_scratch2;  // tmp
 
   assert_different_registers(ic_klass, receiver_klass, R11_scratch1, R3_ARG1);
   assert(R11_scratch1 == R11, "need prologue scratch register");
@@ -3484,6 +3485,7 @@
 
         // Emit the trampoline stub which will be related to the branch-and-link below.
         CallStubImpl::emit_trampoline_stub(_masm, entry_point_toc_offset, start_offset);
+        if (Compile::current()->env()->failing()) { return; } // Code cache may be full.
         __ relocate(_optimized_virtual ?
                     relocInfo::opt_virtual_call_type : relocInfo::static_call_type);
       }
@@ -3527,6 +3529,7 @@
 
       // Emit the trampoline stub which will be related to the branch-and-link below.
       CallStubImpl::emit_trampoline_stub(_masm, entry_point_toc_offset, start_offset);
+      if (ra_->C->env()->failing()) { return; } // Code cache may be full.
       assert(_optimized_virtual, "methodHandle call should be a virtual call");
       __ relocate(relocInfo::opt_virtual_call_type);
     }
@@ -3577,9 +3580,7 @@
       const address entry_point_const = __ address_constant(entry_point, RelocationHolder::none);
       const int entry_point_const_toc_offset = __ offset_to_method_toc(entry_point_const);
       CallStubImpl::emit_trampoline_stub(_masm, entry_point_const_toc_offset, __ offset());
-
-      if (ra_->C->env()->failing())
-        return;
+      if (ra_->C->env()->failing()) { return; } // Code cache may be full.
 
       // Build relocation at call site with ic position as data.
       assert((_load_ic_hi_node != NULL && _load_ic_node == NULL) ||
@@ -5638,19 +5639,6 @@
   ins_pipe(pipe_class_memory);
 %}
 
-//// Load compressed klass and decode it if narrow_klass_shift == 0.
-//// TODO: will narrow_klass_shift ever be 0?
-//instruct decodeNKlass2Klass(iRegPdst dst, memory mem) %{
-//  match(Set dst (DecodeNKlass (LoadNKlass mem)));
-//  predicate(false /* TODO: PPC port Universe::narrow_klass_shift() == 0*);
-//  ins_cost(MEMORY_REF_COST);
-//
-//  format %{ "LWZ     $dst, $mem \t// DecodeNKlass (unscaled)" %}
-//  size(4);
-//  ins_encode( enc_lwz(dst, mem) );
-//  ins_pipe(pipe_class_memory);
-//%}
-
 // Load Klass Pointer
 instruct loadKlass(iRegPdst dst, memoryAlg4 mem) %{
   match(Set dst (LoadKlass mem));
@@ -6070,11 +6058,15 @@
   %}
 %}
 
-instruct loadConNKlass_hi(iRegNdst dst, immNKlass src) %{
+// We have seen a safepoint between the hi and lo parts, and this node was handled
+// as an oop. Therefore this needs a match rule so that build_oop_map knows this is
+// not a narrow oop.
+instruct loadConNKlass_hi(iRegNdst dst, immNKlass_NM src) %{
+  match(Set dst src);
   effect(DEF dst, USE src);
   ins_cost(DEFAULT_COST);
 
-  format %{ "LIS     $dst, $src \t// narrow oop hi" %}
+  format %{ "LIS     $dst, $src \t// narrow klass hi" %}
   size(4);
   ins_encode %{
     // TODO: PPC port $archOpcode(ppc64Opcode_addis);
@@ -6084,6 +6076,21 @@
   ins_pipe(pipe_class_default);
 %}
 
+// As loadConNKlass_hi this must be recognized as narrow klass, not oop!
+instruct loadConNKlass_mask(iRegNdst dst, immNKlass_NM src1, iRegNsrc src2) %{
+  match(Set dst src1);
+  effect(TEMP src2);
+  ins_cost(DEFAULT_COST);
+
+  format %{ "MASK    $dst, $src2, 0xFFFFFFFF" %} // mask
+  size(4);
+  ins_encode %{
+    // TODO: PPC port $archOpcode(ppc64Opcode_rldicl);
+    __ clrldi($dst$$Register, $src2$$Register, 0x20);
+  %}
+  ins_pipe(pipe_class_default);
+%}
+
 // This needs a match rule so that build_oop_map knows this is
 // not a narrow oop.
 instruct loadConNKlass_lo(iRegNdst dst, immNKlass_NM src1, iRegNsrc src2) %{
@@ -6091,10 +6098,10 @@
   effect(TEMP src2);
   ins_cost(DEFAULT_COST);
 
-  format %{ "ADDI    $dst, $src1, $src2 \t// narrow oop lo" %}
-  size(4);
-  ins_encode %{
-    // TODO: PPC port $archOpcode(ppc64Opcode_addi);
+  format %{ "ORI    $dst, $src1, $src2 \t// narrow klass lo" %}
+  size(4);
+  ins_encode %{
+    // TODO: PPC port $archOpcode(ppc64Opcode_ori);
     intptr_t Csrc = Klass::encode_klass((Klass *)$src1$$constant);
     assert(__ oop_recorder() != NULL, "this assembler needs an OopRecorder");
     int klass_index = __ oop_recorder()->find_index((Klass *)$src1$$constant);
@@ -6125,10 +6132,11 @@
     MachNode *m2 = m1;
     if (!Assembler::is_uimm((jlong)Klass::encode_klass((Klass *)op_src->constant()), 31)) {
       // Value might be 1-extended. Mask out these bits.
-      m2 = new clearMs32bNode();
+      m2 = new loadConNKlass_maskNode();
       m2->add_req(NULL, m1);
       m2->_opnds[0] = op_dst;
-      m2->_opnds[1] = op_dst;
+      m2->_opnds[1] = op_src;
+      m2->_opnds[2] = op_dst;
       ra_->set_pair(m2->_idx, ra_->get_reg_second(this), ra_->get_reg_first(this));
       nodes->push(m2);
     }
@@ -6973,7 +6981,7 @@
   size(4);
   ins_encode %{
     // TODO: PPC port $archOpcode(ppc64Opcode_rldicl);
-    __ rldicl($dst$$Register, $src$$Register, 64-Universe::narrow_oop_shift(), 32);
+    __ rldicl($dst$$Register, $src$$Register, 64-Universe::narrow_klass_shift(), 32);
   %}
   ins_pipe(pipe_class_default);
 %}
--- a/hotspot/src/cpu/ppc/vm/stubGenerator_ppc.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/cpu/ppc/vm/stubGenerator_ppc.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -24,7 +24,6 @@
  */
 
 #include "precompiled.hpp"
-#include "asm/assembler.hpp"
 #include "asm/macroAssembler.inline.hpp"
 #include "interpreter/interpreter.hpp"
 #include "nativeInst_ppc.hpp"
@@ -39,9 +38,6 @@
 #include "runtime/stubCodeGenerator.hpp"
 #include "runtime/stubRoutines.hpp"
 #include "utilities/top.hpp"
-#ifdef COMPILER2
-#include "opto/runtime.hpp"
-#endif
 #include "runtime/thread.inline.hpp"
 
 #define __ _masm->
@@ -216,7 +212,7 @@
     {
       BLOCK_COMMENT("Call frame manager or native entry.");
       // Call frame manager or native entry.
-      Register r_new_arg_entry = R14; // PPC_state;
+      Register r_new_arg_entry = R14;
       assert_different_registers(r_new_arg_entry, r_top_of_arguments_addr,
                                  r_arg_method, r_arg_thread);
 
--- a/hotspot/src/cpu/ppc/vm/templateTable_ppc_64.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/cpu/ppc/vm/templateTable_ppc_64.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -353,7 +353,6 @@
   __ sldi(Rscratch1, Rscratch1, LogBytesPerWord);
   __ cmpdi(CCR0, Rscratch2, JVM_CONSTANT_Integer);
   __ bne(CCR0, notInt);
-  __ isync(); // Order load of constant wrt. tags.
   __ lwax(R17_tos, Rcpool, Rscratch1);
   __ push(itos);
   __ b(exit);
@@ -365,7 +364,6 @@
   __ cmpdi(CCR0, Rscratch2, JVM_CONSTANT_Float);
   __ asm_assert_eq("unexpected type", 0x8765);
 #endif
-  __ isync(); // Order load of constant wrt. tags.
   __ lfsx(F15_ftos, Rcpool, Rscratch1);
   __ push(ftos);
 
@@ -424,13 +422,11 @@
   // Check out Conversions.java for an example.
   // Also ConstantPool::header_size() is 20, which makes it very difficult
   // to double-align double on the constant pool. SG, 11/7/97
-  __ isync(); // Order load of constant wrt. tags.
   __ lfdx(F15_ftos, Rcpool, Rindex);
   __ push(dtos);
   __ b(Lexit);
 
   __ bind(Llong);
-  __ isync(); // Order load of constant wrt. tags.
   __ ldx(R17_tos, Rcpool, Rindex);
   __ push(ltos);
 
--- a/hotspot/src/os/aix/vm/perfMemory_aix.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/os/aix/vm/perfMemory_aix.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -1020,7 +1020,3 @@
 
   unmap_shared(addr, bytes);
 }
-
-char* PerfMemory::backing_store_filename() {
-  return backing_store_file_name;
-}
--- a/hotspot/src/os/bsd/vm/perfMemory_bsd.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/os/bsd/vm/perfMemory_bsd.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -1043,7 +1043,3 @@
 
   unmap_shared(addr, bytes);
 }
-
-char* PerfMemory::backing_store_filename() {
-  return backing_store_file_name;
-}
--- a/hotspot/src/os/linux/vm/perfMemory_linux.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/os/linux/vm/perfMemory_linux.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -1049,7 +1049,3 @@
 
   unmap_shared(addr, bytes);
 }
-
-char* PerfMemory::backing_store_filename() {
-  return backing_store_file_name;
-}
--- a/hotspot/src/os/solaris/vm/perfMemory_solaris.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/os/solaris/vm/perfMemory_solaris.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -1068,7 +1068,3 @@
 
   unmap_shared(addr, bytes);
 }
-
-char* PerfMemory::backing_store_filename() {
-  return backing_store_file_name;
-}
--- a/hotspot/src/os/windows/vm/perfMemory_windows.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/os/windows/vm/perfMemory_windows.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -1846,7 +1846,3 @@
     remove_file_mapping(addr);
   }
 }
-
-char* PerfMemory::backing_store_filename() {
-  return sharedmem_fileName;
-}
--- a/hotspot/src/os_cpu/linux_ppc/vm/prefetch_linux_ppc.inline.hpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/os_cpu/linux_ppc/vm/prefetch_linux_ppc.inline.hpp	Wed Jul 05 20:04:39 2017 +0200
@@ -47,4 +47,4 @@
     );
 }
 
-#endif // OS_CPU_LINUX_PPC_VM_PREFETCH_LINUX_OJDKPPC_HPP
+#endif // OS_CPU_LINUX_PPC_VM_PREFETCH_LINUX_PPC_INLINE_HPP
--- a/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -2069,14 +2069,14 @@
   LIR_Opr base_op = base.result();
   LIR_Opr index_op = idx.result();
 #ifndef _LP64
-  if (x->base()->type()->tag() == longTag) {
+  if (base_op->type() == T_LONG) {
     base_op = new_register(T_INT);
     __ convert(Bytecodes::_l2i, base.result(), base_op);
   }
   if (x->has_index()) {
-    if (x->index()->type()->tag() == longTag) {
+    if (index_op->type() == T_LONG) {
       LIR_Opr long_index_op = index_op;
-      if (x->index()->type()->is_constant()) {
+      if (index_op->is_constant()) {
         long_index_op = new_register(T_LONG);
         __ move(index_op, long_index_op);
       }
@@ -2091,14 +2091,14 @@
   assert(!x->has_index() || index_op->type() == T_INT, "index should be an int");
 #else
   if (x->has_index()) {
-    if (x->index()->type()->tag() == intTag) {
-      if (!x->index()->type()->is_constant()) {
+    if (index_op->type() == T_INT) {
+      if (!index_op->is_constant()) {
         index_op = new_register(T_LONG);
         __ convert(Bytecodes::_i2l, idx.result(), index_op);
       }
     } else {
-      assert(x->index()->type()->tag() == longTag, "must be");
-      if (x->index()->type()->is_constant()) {
+      assert(index_op->type() == T_LONG, "must be");
+      if (index_op->is_constant()) {
         index_op = new_register(T_LONG);
         __ move(idx.result(), index_op);
       }
@@ -2179,12 +2179,12 @@
   LIR_Opr index_op = idx.result();
 
 #ifndef _LP64
-  if (x->base()->type()->tag() == longTag) {
+  if (base_op->type() == T_LONG) {
     base_op = new_register(T_INT);
     __ convert(Bytecodes::_l2i, base.result(), base_op);
   }
   if (x->has_index()) {
-    if (x->index()->type()->tag() == longTag) {
+    if (index_op->type() == T_LONG) {
       index_op = new_register(T_INT);
       __ convert(Bytecodes::_l2i, idx.result(), index_op);
     }
@@ -2194,7 +2194,7 @@
   assert(!x->has_index() || (index_op->type() == T_INT && !index_op->is_constant()), "index should be an non-constant int");
 #else
   if (x->has_index()) {
-    if (x->index()->type()->tag() == intTag) {
+    if (index_op->type() == T_INT) {
       index_op = new_register(T_LONG);
       __ convert(Bytecodes::_i2l, idx.result(), index_op);
     }
--- a/hotspot/src/share/vm/classfile/classFileParser.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/classfile/classFileParser.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -2859,6 +2859,11 @@
       "bootstrap_method_index %u has bad constant type in class file %s",
       bootstrap_method_index,
       CHECK);
+
+    guarantee_property((operand_fill_index + 1 + argument_count) < operands->length(),
+      "Invalid BootstrapMethods num_bootstrap_methods or num_bootstrap_arguments value in class file %s",
+      CHECK);
+
     operands->at_put(operand_fill_index++, bootstrap_method_index);
     operands->at_put(operand_fill_index++, argument_count);
 
@@ -2875,8 +2880,6 @@
     }
   }
 
-  assert(ConstantPool::operand_array_length(operands) == attribute_array_length, "correct decode");
-
   u1* current_end = cfs->current();
   guarantee_property(current_end == current_start + attribute_byte_length,
                      "Bad length on BootstrapMethods in class file %s",
--- a/hotspot/src/share/vm/classfile/classLoader.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/classfile/classLoader.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -75,6 +75,7 @@
 typedef jboolean (JNICALL *ReadEntry_t)(jzfile *zip, jzentry *entry, unsigned char *buf, char *namebuf);
 typedef jboolean (JNICALL *ReadMappedEntry_t)(jzfile *zip, jzentry *entry, unsigned char **buf, char *namebuf);
 typedef jzentry* (JNICALL *GetNextEntry_t)(jzfile *zip, jint n);
+typedef jint     (JNICALL *Crc32_t)(jint crc, const jbyte *buf, jint len);
 
 static ZipOpen_t         ZipOpen            = NULL;
 static ZipClose_t        ZipClose           = NULL;
@@ -83,6 +84,7 @@
 static ReadMappedEntry_t ReadMappedEntry    = NULL;
 static GetNextEntry_t    GetNextEntry       = NULL;
 static canonicalize_fn_t CanonicalizeEntry  = NULL;
+static Crc32_t           Crc32              = NULL;
 
 // Globals
 
@@ -799,9 +801,11 @@
   ReadEntry    = CAST_TO_FN_PTR(ReadEntry_t, os::dll_lookup(handle, "ZIP_ReadEntry"));
   ReadMappedEntry = CAST_TO_FN_PTR(ReadMappedEntry_t, os::dll_lookup(handle, "ZIP_ReadMappedEntry"));
   GetNextEntry = CAST_TO_FN_PTR(GetNextEntry_t, os::dll_lookup(handle, "ZIP_GetNextEntry"));
+  Crc32        = CAST_TO_FN_PTR(Crc32_t, os::dll_lookup(handle, "ZIP_CRC32"));
 
   // ZIP_Close is not exported on Windows in JDK5.0 so don't abort if ZIP_Close is NULL
-  if (ZipOpen == NULL || FindEntry == NULL || ReadEntry == NULL || GetNextEntry == NULL) {
+  if (ZipOpen == NULL || FindEntry == NULL || ReadEntry == NULL ||
+      GetNextEntry == NULL || Crc32 == NULL) {
     vm_exit_during_initialization("Corrupted ZIP library", path);
   }
 
@@ -811,6 +815,11 @@
   // This lookup only works on 1.3. Do not check for non-null here
 }
 
+int ClassLoader::crc32(int crc, const char* buf, int len) {
+  assert(Crc32 != NULL, "ZIP_CRC32 is not found");
+  return (*Crc32)(crc, (const jbyte*)buf, len);
+}
+
 // PackageInfo data exists in order to support the java.lang.Package
 // class.  A Package object provides information about a java package
 // (version, vendor, etc.) which originates in the manifest of the jar
--- a/hotspot/src/share/vm/classfile/classLoader.hpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/classfile/classLoader.hpp	Wed Jul 05 20:04:39 2017 +0200
@@ -226,6 +226,7 @@
   // to avoid confusing the zip library
   static bool get_canonical_path(const char* orig, char* out, int len);
  public:
+  static int crc32(int crc, const char* buf, int len);
   static bool update_class_path_entry_list(const char *path,
                                            bool check_for_duplicates,
                                            bool throw_exception=true);
--- a/hotspot/src/share/vm/classfile/stackMapFrame.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/classfile/stackMapFrame.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -148,7 +148,7 @@
     VerificationType* from, VerificationType* to, int32_t len, TRAPS) const {
   int32_t i = 0;
   for (i = 0; i < len; i++) {
-    if (!to[i].is_assignable_from(from[i], verifier(), THREAD)) {
+    if (!to[i].is_assignable_from(from[i], verifier(), false, THREAD)) {
       break;
     }
   }
@@ -245,7 +245,7 @@
   }
   VerificationType top = _stack[--_stack_size];
   bool subtype = type.is_assignable_from(
-    top, verifier(), CHECK_(VerificationType::bogus_type()));
+    top, verifier(), false, CHECK_(VerificationType::bogus_type()));
   if (!subtype) {
     verifier()->verify_error(
         ErrorContext::bad_type(_offset, stack_top_ctx(),
@@ -265,7 +265,7 @@
     return VerificationType::bogus_type();
   }
   bool subtype = type.is_assignable_from(_locals[index],
-    verifier(), CHECK_(VerificationType::bogus_type()));
+    verifier(), false, CHECK_(VerificationType::bogus_type()));
   if (!subtype) {
     verifier()->verify_error(
         ErrorContext::bad_type(_offset,
@@ -288,14 +288,14 @@
         "get long/double overflows locals");
     return;
   }
-  bool subtype = type1.is_assignable_from(_locals[index], verifier(), CHECK);
+  bool subtype = type1.is_assignable_from(_locals[index], verifier(), false, CHECK);
   if (!subtype) {
     verifier()->verify_error(
         ErrorContext::bad_type(_offset,
             TypeOrigin::local(index, this), TypeOrigin::implicit(type1)),
         "Bad local variable type");
   } else {
-    subtype = type2.is_assignable_from(_locals[index + 1], verifier(), CHECK);
+    subtype = type2.is_assignable_from(_locals[index + 1], verifier(), false, CHECK);
     if (!subtype) {
       /* Unreachable? All local store routines convert a split long or double
        * into a TOP during the store.  So we should never end up seeing an
--- a/hotspot/src/share/vm/classfile/stackMapFrame.hpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/classfile/stackMapFrame.hpp	Wed Jul 05 20:04:39 2017 +0200
@@ -234,7 +234,7 @@
     if (_stack_size != 0) {
       VerificationType top = _stack[_stack_size - 1];
       bool subtype = type.is_assignable_from(
-        top, verifier(), CHECK_(VerificationType::bogus_type()));
+        top, verifier(), false, CHECK_(VerificationType::bogus_type()));
       if (subtype) {
         --_stack_size;
         return top;
@@ -249,9 +249,9 @@
     assert(type2.is_long() || type2.is_double(), "must be long/double_2");
     if (_stack_size >= 2) {
       VerificationType top1 = _stack[_stack_size - 1];
-      bool subtype1 = type1.is_assignable_from(top1, verifier(), CHECK);
+      bool subtype1 = type1.is_assignable_from(top1, verifier(), false, CHECK);
       VerificationType top2 = _stack[_stack_size - 2];
-      bool subtype2 = type2.is_assignable_from(top2, verifier(), CHECK);
+      bool subtype2 = type2.is_assignable_from(top2, verifier(), false, CHECK);
       if (subtype1 && subtype2) {
         _stack_size -= 2;
         return;
--- a/hotspot/src/share/vm/classfile/verificationType.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/classfile/verificationType.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -42,7 +42,8 @@
 }
 
 bool VerificationType::is_reference_assignable_from(
-    const VerificationType& from, ClassVerifier* context, TRAPS) const {
+    const VerificationType& from, ClassVerifier* context,
+    bool from_field_is_protected, TRAPS) const {
   instanceKlassHandle klass = context->current_class();
   if (from.is_null()) {
     // null is assignable to any reference
@@ -62,9 +63,11 @@
         Handle(THREAD, klass->protection_domain()), true, CHECK_false);
     KlassHandle this_class(THREAD, obj);
 
-    if (this_class->is_interface()) {
-      // We treat interfaces as java.lang.Object, including
-      // java.lang.Cloneable and java.io.Serializable
+    if (this_class->is_interface() && (!from_field_is_protected ||
+        from.name() != vmSymbols::java_lang_Object())) {
+      // If we are not trying to access a protected field or method in
+      // java.lang.Object then we treat interfaces as java.lang.Object,
+      // including java.lang.Cloneable and java.io.Serializable.
       return true;
     } else if (from.is_object()) {
       Klass* from_class = SystemDictionary::resolve_or_fail(
@@ -76,7 +79,8 @@
     VerificationType comp_this = get_component(context, CHECK_false);
     VerificationType comp_from = from.get_component(context, CHECK_false);
     if (!comp_this.is_bogus() && !comp_from.is_bogus()) {
-      return comp_this.is_assignable_from(comp_from, context, CHECK_false);
+      return comp_this.is_assignable_from(comp_from, context,
+                                          from_field_is_protected, CHECK_false);
     }
   }
   return false;
--- a/hotspot/src/share/vm/classfile/verificationType.hpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/classfile/verificationType.hpp	Wed Jul 05 20:04:39 2017 +0200
@@ -265,7 +265,8 @@
   // is assignable to another.  Returns true if one can assign 'from' to
   // this.
   bool is_assignable_from(
-      const VerificationType& from, ClassVerifier* context, TRAPS) const {
+      const VerificationType& from, ClassVerifier* context,
+      bool from_field_is_protected, TRAPS) const {
     if (equals(from) || is_bogus()) {
       return true;
     } else {
@@ -286,7 +287,9 @@
           return from.is_integer();
         default:
           if (is_reference() && from.is_reference()) {
-            return is_reference_assignable_from(from, context, CHECK_false);
+            return is_reference_assignable_from(from, context,
+                                                from_field_is_protected,
+                                                CHECK_false);
           } else {
             return false;
           }
@@ -308,7 +311,8 @@
  private:
 
   bool is_reference_assignable_from(
-    const VerificationType&, ClassVerifier*, TRAPS) const;
+    const VerificationType&, ClassVerifier*, bool from_field_is_protected,
+    TRAPS) const;
 };
 
 #endif // SHARE_VM_CLASSFILE_VERIFICATIONTYPE_HPP
--- a/hotspot/src/share/vm/classfile/verifier.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/classfile/verifier.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -98,6 +98,14 @@
   HandleMark hm;
   ResourceMark rm(THREAD);
 
+  if (!is_eligible_for_verification(klass, should_verify_class)) {
+    return true;
+  }
+
+  // If the class should be verified, first see if we can use the split
+  // verifier.  If not, or if verification fails and FailOverToOldVerifier
+  // is set, then call the inference verifier.
+
   Symbol* exception_name = NULL;
   const size_t message_buffer_len = klass->name()->utf8_length() + 1024;
   char* message_buffer = NEW_RESOURCE_ARRAY(char, message_buffer_len);
@@ -105,47 +113,42 @@
 
   const char* klassName = klass->external_name();
   bool can_failover = FailOverToOldVerifier &&
-      klass->major_version() < NOFAILOVER_MAJOR_VERSION;
+     klass->major_version() < NOFAILOVER_MAJOR_VERSION;
 
-  // If the class should be verified, first see if we can use the split
-  // verifier.  If not, or if verification fails and FailOverToOldVerifier
-  // is set, then call the inference verifier.
-  if (is_eligible_for_verification(klass, should_verify_class)) {
-    if (TraceClassInitialization) {
-      tty->print_cr("Start class verification for: %s", klassName);
+  if (TraceClassInitialization) {
+    tty->print_cr("Start class verification for: %s", klassName);
+  }
+  if (klass->major_version() >= STACKMAP_ATTRIBUTE_MAJOR_VERSION) {
+    ClassVerifier split_verifier(klass, THREAD);
+    split_verifier.verify_class(THREAD);
+    exception_name = split_verifier.result();
+    if (can_failover && !HAS_PENDING_EXCEPTION &&
+        (exception_name == vmSymbols::java_lang_VerifyError() ||
+         exception_name == vmSymbols::java_lang_ClassFormatError())) {
+      if (TraceClassInitialization || VerboseVerification) {
+        tty->print_cr(
+          "Fail over class verification to old verifier for: %s", klassName);
+      }
+      exception_name = inference_verify(
+        klass, message_buffer, message_buffer_len, THREAD);
     }
-    if (klass->major_version() >= STACKMAP_ATTRIBUTE_MAJOR_VERSION) {
-      ClassVerifier split_verifier(klass, THREAD);
-      split_verifier.verify_class(THREAD);
-      exception_name = split_verifier.result();
-      if (can_failover && !HAS_PENDING_EXCEPTION &&
-          (exception_name == vmSymbols::java_lang_VerifyError() ||
-           exception_name == vmSymbols::java_lang_ClassFormatError())) {
-        if (TraceClassInitialization || VerboseVerification) {
-          tty->print_cr(
-            "Fail over class verification to old verifier for: %s", klassName);
-        }
-        exception_name = inference_verify(
-          klass, message_buffer, message_buffer_len, THREAD);
-      }
-      if (exception_name != NULL) {
-        exception_message = split_verifier.exception_message();
-      }
-    } else {
-      exception_name = inference_verify(
-          klass, message_buffer, message_buffer_len, THREAD);
+    if (exception_name != NULL) {
+      exception_message = split_verifier.exception_message();
     }
+  } else {
+    exception_name = inference_verify(
+        klass, message_buffer, message_buffer_len, THREAD);
+  }
 
-    if (TraceClassInitialization || VerboseVerification) {
-      if (HAS_PENDING_EXCEPTION) {
-        tty->print("Verification for %s has", klassName);
-        tty->print_cr(" exception pending %s ",
-          InstanceKlass::cast(PENDING_EXCEPTION->klass())->external_name());
-      } else if (exception_name != NULL) {
-        tty->print_cr("Verification for %s failed", klassName);
-      }
-      tty->print_cr("End class verification for: %s", klassName);
+  if (TraceClassInitialization || VerboseVerification) {
+    if (HAS_PENDING_EXCEPTION) {
+      tty->print("Verification for %s has", klassName);
+      tty->print_cr(" exception pending %s ",
+        InstanceKlass::cast(PENDING_EXCEPTION->klass())->external_name());
+    } else if (exception_name != NULL) {
+      tty->print_cr("Verification for %s failed", klassName);
     }
+    tty->print_cr("End class verification for: %s", klassName);
   }
 
   if (HAS_PENDING_EXCEPTION) {
@@ -1718,7 +1721,7 @@
       VerificationType throwable =
         VerificationType::reference_type(vmSymbols::java_lang_Throwable());
       bool is_subclass = throwable.is_assignable_from(
-        catch_type, this, CHECK_VERIFY(this));
+        catch_type, this, false, CHECK_VERIFY(this));
       if (!is_subclass) {
         // 4286534: should throw VerifyError according to recent spec change
         verify_error(ErrorContext::bad_type(handler_pc,
@@ -2171,7 +2174,7 @@
         stack_object_type = current_type();
       }
       is_assignable = target_class_type.is_assignable_from(
-        stack_object_type, this, CHECK_VERIFY(this));
+        stack_object_type, this, false, CHECK_VERIFY(this));
       if (!is_assignable) {
         verify_error(ErrorContext::bad_type(bci,
             current_frame->stack_top_ctx(),
@@ -2198,7 +2201,7 @@
         // It's protected access, check if stack object is assignable to
         // current class.
         is_assignable = current_type().is_assignable_from(
-          stack_object_type, this, CHECK_VERIFY(this));
+          stack_object_type, this, true, CHECK_VERIFY(this));
         if (!is_assignable) {
           verify_error(ErrorContext::bad_type(bci,
               current_frame->stack_top_ctx(),
@@ -2472,7 +2475,7 @@
         instanceKlassHandle mh(THREAD, m->method_holder());
         if (m->is_protected() && !mh->is_same_class_package(_klass())) {
           bool assignable = current_type().is_assignable_from(
-            objectref_type, this, CHECK_VERIFY(this));
+            objectref_type, this, true, CHECK_VERIFY(this));
           if (!assignable) {
             verify_error(ErrorContext::bad_type(bci,
                 TypeOrigin::cp(new_class_index, objectref_type),
@@ -2643,11 +2646,11 @@
     bool have_imr_indirect = cp->tag_at(index).value() == JVM_CONSTANT_InterfaceMethodref;
     if (!current_class()->is_anonymous()) {
       subtype = ref_class_type.is_assignable_from(
-                 current_type(), this, CHECK_VERIFY(this));
+                 current_type(), this, false, CHECK_VERIFY(this));
     } else {
       VerificationType host_klass_type =
                         VerificationType::reference_type(current_class()->host_klass()->name());
-      subtype = ref_class_type.is_assignable_from(host_klass_type, this, CHECK_VERIFY(this));
+      subtype = ref_class_type.is_assignable_from(host_klass_type, this, false, CHECK_VERIFY(this));
 
       // If invokespecial of IMR, need to recheck for same or
       // direct interface relative to the host class
@@ -2691,7 +2694,7 @@
           VerificationType top = current_frame->pop_stack(CHECK_VERIFY(this));
           VerificationType hosttype =
             VerificationType::reference_type(current_class()->host_klass()->name());
-          bool subtype = hosttype.is_assignable_from(top, this, CHECK_VERIFY(this));
+          bool subtype = hosttype.is_assignable_from(top, this, false, CHECK_VERIFY(this));
           if (!subtype) {
             verify_error( ErrorContext::bad_type(current_frame->offset(),
               current_frame->stack_top_ctx(),
@@ -2716,7 +2719,7 @@
               // It's protected access, check if stack object is
               // assignable to current class.
               bool is_assignable = current_type().is_assignable_from(
-                stack_object_type, this, CHECK_VERIFY(this));
+                stack_object_type, this, true, CHECK_VERIFY(this));
               if (!is_assignable) {
                 if (ref_class_type.name() == vmSymbols::java_lang_Object()
                     && stack_object_type.is_array()
@@ -2899,7 +2902,7 @@
         "Method expects a return value");
     return;
   }
-  bool match = return_type.is_assignable_from(type, this, CHECK_VERIFY(this));
+  bool match = return_type.is_assignable_from(type, this, false, CHECK_VERIFY(this));
   if (!match) {
     verify_error(ErrorContext::bad_type(bci,
         current_frame->stack_top_ctx(), TypeOrigin::signature(return_type)),
--- a/hotspot/src/share/vm/code/codeCache.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/code/codeCache.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -254,8 +254,7 @@
   if (!SegmentedCodeCache) {
     // No segmentation: use a single code heap
     return (code_blob_type == CodeBlobType::All);
-  } else if ((Arguments::mode() == Arguments::_int) ||
-             (TieredStopAtLevel == CompLevel_none)) {
+  } else if (Arguments::mode() == Arguments::_int) {
     // Interpreter only: we don't need any method code heaps
     return (code_blob_type == CodeBlobType::NonNMethod);
   } else if (TieredCompilation && (TieredStopAtLevel > CompLevel_simple)) {
--- a/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -1683,6 +1683,8 @@
   int  _failures;
   bool _verbose;
 
+  HeapRegionClaimer _hrclaimer;
+
 public:
   G1ParVerifyFinalCountTask(G1CollectedHeap* g1h,
                             BitMap* region_bm, BitMap* card_bm,
@@ -1692,19 +1694,8 @@
       _actual_region_bm(region_bm), _actual_card_bm(card_bm),
       _expected_region_bm(expected_region_bm), _expected_card_bm(expected_card_bm),
       _failures(0), _verbose(false),
-      _n_workers(0) {
+      _n_workers(_g1h->workers()->active_workers()), _hrclaimer(_n_workers) {
     assert(VerifyDuringGC, "don't call this otherwise");
-
-    // Use the value already set as the number of active threads
-    // in the call to run_task().
-    if (G1CollectedHeap::use_parallel_gc_threads()) {
-      assert( _g1h->workers()->active_workers() > 0,
-        "Should have been previously set");
-      _n_workers = _g1h->workers()->active_workers();
-    } else {
-      _n_workers = 1;
-    }
-
     assert(_expected_card_bm->size() == _actual_card_bm->size(), "sanity");
     assert(_expected_region_bm->size() == _actual_region_bm->size(), "sanity");
 
@@ -1721,10 +1712,7 @@
                                             _verbose);
 
     if (G1CollectedHeap::use_parallel_gc_threads()) {
-      _g1h->heap_region_par_iterate_chunked(&verify_cl,
-                                            worker_id,
-                                            _n_workers,
-                                            HeapRegion::VerifyCountClaimValue);
+      _g1h->heap_region_par_iterate(&verify_cl, worker_id, &_hrclaimer);
     } else {
       _g1h->heap_region_iterate(&verify_cl);
     }
@@ -1813,22 +1801,14 @@
   BitMap* _actual_card_bm;
 
   uint    _n_workers;
+  HeapRegionClaimer _hrclaimer;
 
 public:
   G1ParFinalCountTask(G1CollectedHeap* g1h, BitMap* region_bm, BitMap* card_bm)
     : AbstractGangTask("G1 final counting"),
       _g1h(g1h), _cm(_g1h->concurrent_mark()),
       _actual_region_bm(region_bm), _actual_card_bm(card_bm),
-      _n_workers(0) {
-    // Use the value already set as the number of active threads
-    // in the call to run_task().
-    if (G1CollectedHeap::use_parallel_gc_threads()) {
-      assert( _g1h->workers()->active_workers() > 0,
-        "Should have been previously set");
-      _n_workers = _g1h->workers()->active_workers();
-    } else {
-      _n_workers = 1;
-    }
+      _n_workers(_g1h->workers()->active_workers()), _hrclaimer(_n_workers) {
   }
 
   void work(uint worker_id) {
@@ -1839,10 +1819,7 @@
                                                 _actual_card_bm);
 
     if (G1CollectedHeap::use_parallel_gc_threads()) {
-      _g1h->heap_region_par_iterate_chunked(&final_update_cl,
-                                            worker_id,
-                                            _n_workers,
-                                            HeapRegion::FinalCountClaimValue);
+      _g1h->heap_region_par_iterate(&final_update_cl, worker_id, &_hrclaimer);
     } else {
       _g1h->heap_region_iterate(&final_update_cl);
     }
@@ -1929,12 +1906,12 @@
   size_t _max_live_bytes;
   size_t _freed_bytes;
   FreeRegionList* _cleanup_list;
+  HeapRegionClaimer _hrclaimer;
 
 public:
-  G1ParNoteEndTask(G1CollectedHeap* g1h,
-                   FreeRegionList* cleanup_list) :
-    AbstractGangTask("G1 note end"), _g1h(g1h),
-    _max_live_bytes(0), _freed_bytes(0), _cleanup_list(cleanup_list) { }
+  G1ParNoteEndTask(G1CollectedHeap* g1h, FreeRegionList* cleanup_list, uint n_workers) :
+      AbstractGangTask("G1 note end"), _g1h(g1h), _max_live_bytes(0), _freed_bytes(0), _cleanup_list(cleanup_list), _hrclaimer(n_workers) {
+  }
 
   void work(uint worker_id) {
     double start = os::elapsedTime();
@@ -1943,9 +1920,7 @@
     G1NoteEndOfConcMarkClosure g1_note_end(_g1h, &local_cleanup_list,
                                            &hrrs_cleanup_task);
     if (G1CollectedHeap::use_parallel_gc_threads()) {
-      _g1h->heap_region_par_iterate_chunked(&g1_note_end, worker_id,
-                                            _g1h->workers()->active_workers(),
-                                            HeapRegion::NoteEndClaimValue);
+      _g1h->heap_region_par_iterate(&g1_note_end, worker_id, &_hrclaimer);
     } else {
       _g1h->heap_region_iterate(&g1_note_end);
     }
@@ -1991,16 +1966,16 @@
   G1RemSet* _g1rs;
   BitMap* _region_bm;
   BitMap* _card_bm;
+  HeapRegionClaimer _hrclaimer;
+
 public:
-  G1ParScrubRemSetTask(G1CollectedHeap* g1h,
-                       BitMap* region_bm, BitMap* card_bm) :
-    AbstractGangTask("G1 ScrubRS"), _g1rs(g1h->g1_rem_set()),
-    _region_bm(region_bm), _card_bm(card_bm) { }
+  G1ParScrubRemSetTask(G1CollectedHeap* g1h, BitMap* region_bm, BitMap* card_bm, uint n_workers) :
+      AbstractGangTask("G1 ScrubRS"), _g1rs(g1h->g1_rem_set()), _region_bm(region_bm), _card_bm(card_bm), _hrclaimer(n_workers) {
+  }
 
   void work(uint worker_id) {
     if (G1CollectedHeap::use_parallel_gc_threads()) {
-      _g1rs->scrub_par(_region_bm, _card_bm, worker_id,
-                       HeapRegion::ScrubRemSetClaimValue);
+      _g1rs->scrub_par(_region_bm, _card_bm, worker_id, &_hrclaimer);
     } else {
       _g1rs->scrub(_region_bm, _card_bm);
     }
@@ -2043,9 +2018,6 @@
   G1ParFinalCountTask g1_par_count_task(g1h, &_region_bm, &_card_bm);
 
   if (G1CollectedHeap::use_parallel_gc_threads()) {
-   assert(g1h->check_heap_region_claim_values(HeapRegion::InitialClaimValue),
-           "sanity check");
-
     g1h->set_par_threads();
     n_workers = g1h->n_par_threads();
     assert(g1h->n_par_threads() == n_workers,
@@ -2053,9 +2025,6 @@
     g1h->workers()->run_task(&g1_par_count_task);
     // Done with the parallel phase so reset to 0.
     g1h->set_par_threads(0);
-
-    assert(g1h->check_heap_region_claim_values(HeapRegion::FinalCountClaimValue),
-           "sanity check");
   } else {
     n_workers = 1;
     g1_par_count_task.work(0);
@@ -2080,9 +2049,6 @@
       g1h->workers()->run_task(&g1_par_verify_task);
       // Done with the parallel phase so reset to 0.
       g1h->set_par_threads(0);
-
-      assert(g1h->check_heap_region_claim_values(HeapRegion::VerifyCountClaimValue),
-             "sanity check");
     } else {
       g1_par_verify_task.work(0);
     }
@@ -2108,14 +2074,11 @@
   g1h->reset_gc_time_stamp();
 
   // Note end of marking in all heap regions.
-  G1ParNoteEndTask g1_par_note_end_task(g1h, &_cleanup_list);
+  G1ParNoteEndTask g1_par_note_end_task(g1h, &_cleanup_list, n_workers);
   if (G1CollectedHeap::use_parallel_gc_threads()) {
     g1h->set_par_threads((int)n_workers);
     g1h->workers()->run_task(&g1_par_note_end_task);
     g1h->set_par_threads(0);
-
-    assert(g1h->check_heap_region_claim_values(HeapRegion::NoteEndClaimValue),
-           "sanity check");
   } else {
     g1_par_note_end_task.work(0);
   }
@@ -2132,15 +2095,11 @@
   // regions.
   if (G1ScrubRemSets) {
     double rs_scrub_start = os::elapsedTime();
-    G1ParScrubRemSetTask g1_par_scrub_rs_task(g1h, &_region_bm, &_card_bm);
+    G1ParScrubRemSetTask g1_par_scrub_rs_task(g1h, &_region_bm, &_card_bm, n_workers);
     if (G1CollectedHeap::use_parallel_gc_threads()) {
       g1h->set_par_threads((int)n_workers);
       g1h->workers()->run_task(&g1_par_scrub_rs_task);
       g1h->set_par_threads(0);
-
-      assert(g1h->check_heap_region_claim_values(
-                                            HeapRegion::ScrubRemSetClaimValue),
-             "sanity check");
     } else {
       g1_par_scrub_rs_task.work(0);
     }
@@ -3288,6 +3247,7 @@
   BitMap* _cm_card_bm;
   uint _max_worker_id;
   int _active_workers;
+  HeapRegionClaimer _hrclaimer;
 
 public:
   G1AggregateCountDataTask(G1CollectedHeap* g1h,
@@ -3295,18 +3255,18 @@
                            BitMap* cm_card_bm,
                            uint max_worker_id,
                            int n_workers) :
-    AbstractGangTask("Count Aggregation"),
-    _g1h(g1h), _cm(cm), _cm_card_bm(cm_card_bm),
-    _max_worker_id(max_worker_id),
-    _active_workers(n_workers) { }
+      AbstractGangTask("Count Aggregation"),
+      _g1h(g1h), _cm(cm), _cm_card_bm(cm_card_bm),
+      _max_worker_id(max_worker_id),
+      _active_workers(n_workers),
+      _hrclaimer(_active_workers) {
+  }
 
   void work(uint worker_id) {
     AggregateCountDataHRClosure cl(_g1h, _cm_card_bm, _max_worker_id);
 
     if (G1CollectedHeap::use_parallel_gc_threads()) {
-      _g1h->heap_region_par_iterate_chunked(&cl, worker_id,
-                                            _active_workers,
-                                            HeapRegion::AggregateCountClaimValue);
+      _g1h->heap_region_par_iterate(&cl, worker_id, &_hrclaimer);
     } else {
       _g1h->heap_region_iterate(&cl);
     }
@@ -3323,15 +3283,9 @@
                                            _max_worker_id, n_workers);
 
   if (G1CollectedHeap::use_parallel_gc_threads()) {
-    assert(_g1h->check_heap_region_claim_values(HeapRegion::InitialClaimValue),
-           "sanity check");
     _g1h->set_par_threads(n_workers);
     _g1h->workers()->run_task(&g1_par_agg_task);
     _g1h->set_par_threads(0);
-
-    assert(_g1h->check_heap_region_claim_values(HeapRegion::AggregateCountClaimValue),
-           "sanity check");
-    _g1h->reset_heap_region_claim_values();
   } else {
     g1_par_agg_task.work(0);
   }
--- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -90,8 +90,8 @@
 
 // Notes on implementation of parallelism in different tasks.
 //
-// G1ParVerifyTask uses heap_region_par_iterate_chunked() for parallelism.
-// The number of GC workers is passed to heap_region_par_iterate_chunked().
+// G1ParVerifyTask uses heap_region_par_iterate() for parallelism.
+// The number of GC workers is passed to heap_region_par_iterate().
 // It does use run_task() which sets _n_workers in the task.
 // G1ParTask executes g1_process_roots() ->
 // SharedHeap::process_roots() which calls eventually to
@@ -1215,17 +1215,15 @@
 
 class ParRebuildRSTask: public AbstractGangTask {
   G1CollectedHeap* _g1;
+  HeapRegionClaimer _hrclaimer;
+
 public:
-  ParRebuildRSTask(G1CollectedHeap* g1)
-    : AbstractGangTask("ParRebuildRSTask"),
-      _g1(g1)
-  { }
+  ParRebuildRSTask(G1CollectedHeap* g1) :
+      AbstractGangTask("ParRebuildRSTask"), _g1(g1), _hrclaimer(g1->workers()->active_workers()) {}
 
   void work(uint worker_id) {
     RebuildRSOutOfRegionClosure rebuild_rs(_g1, worker_id);
-    _g1->heap_region_par_iterate_chunked(&rebuild_rs, worker_id,
-                                          _g1->workers()->active_workers(),
-                                         HeapRegion::RebuildRSClaimValue);
+    _g1->heap_region_par_iterate(&rebuild_rs, worker_id, &_hrclaimer);
   }
 };
 
@@ -1455,8 +1453,6 @@
         set_par_threads(n_workers);
 
         ParRebuildRSTask rebuild_rs_task(this);
-        assert(check_heap_region_claim_values(
-               HeapRegion::InitialClaimValue), "sanity check");
         assert(UseDynamicNumberOfGCThreads ||
                workers()->active_workers() == workers()->total_workers(),
                "Unless dynamic should use total workers");
@@ -1466,9 +1462,6 @@
         set_par_threads(workers()->active_workers());
         workers()->run_task(&rebuild_rs_task);
         set_par_threads(0);
-        assert(check_heap_region_claim_values(
-               HeapRegion::RebuildRSClaimValue), "sanity check");
-        reset_heap_region_claim_values();
       } else {
         RebuildRSOutOfRegionClosure rebuild_rs(this);
         heap_region_iterate(&rebuild_rs);
@@ -2343,6 +2336,7 @@
     case GCCause::_gc_locker:               return GCLockerInvokesConcurrent;
     case GCCause::_java_lang_system_gc:     return ExplicitGCInvokesConcurrent;
     case GCCause::_g1_humongous_allocation: return true;
+    case GCCause::_update_allocation_context_stats_inc: return true;
     default:                                return false;
   }
 }
@@ -2633,110 +2627,11 @@
 }
 
 void
-G1CollectedHeap::heap_region_par_iterate_chunked(HeapRegionClosure* cl,
-                                                 uint worker_id,
-                                                 uint num_workers,
-                                                 jint claim_value) const {
-  _hrm.par_iterate(cl, worker_id, num_workers, claim_value);
-}
-
-class ResetClaimValuesClosure: public HeapRegionClosure {
-public:
-  bool doHeapRegion(HeapRegion* r) {
-    r->set_claim_value(HeapRegion::InitialClaimValue);
-    return false;
-  }
-};
-
-void G1CollectedHeap::reset_heap_region_claim_values() {
-  ResetClaimValuesClosure blk;
-  heap_region_iterate(&blk);
-}
-
-void G1CollectedHeap::reset_cset_heap_region_claim_values() {
-  ResetClaimValuesClosure blk;
-  collection_set_iterate(&blk);
-}
-
-#ifdef ASSERT
-// This checks whether all regions in the heap have the correct claim
-// value. I also piggy-backed on this a check to ensure that the
-// humongous_start_region() information on "continues humongous"
-// regions is correct.
-
-class CheckClaimValuesClosure : public HeapRegionClosure {
-private:
-  jint _claim_value;
-  uint _failures;
-  HeapRegion* _sh_region;
-
-public:
-  CheckClaimValuesClosure(jint claim_value) :
-    _claim_value(claim_value), _failures(0), _sh_region(NULL) { }
-  bool doHeapRegion(HeapRegion* r) {
-    if (r->claim_value() != _claim_value) {
-      gclog_or_tty->print_cr("Region " HR_FORMAT ", "
-                             "claim value = %d, should be %d",
-                             HR_FORMAT_PARAMS(r),
-                             r->claim_value(), _claim_value);
-      ++_failures;
-    }
-    if (!r->is_humongous()) {
-      _sh_region = NULL;
-    } else if (r->is_starts_humongous()) {
-      _sh_region = r;
-    } else if (r->is_continues_humongous()) {
-      if (r->humongous_start_region() != _sh_region) {
-        gclog_or_tty->print_cr("Region " HR_FORMAT ", "
-                               "HS = "PTR_FORMAT", should be "PTR_FORMAT,
-                               HR_FORMAT_PARAMS(r),
-                               r->humongous_start_region(),
-                               _sh_region);
-        ++_failures;
-      }
-    }
-    return false;
-  }
-  uint failures() { return _failures; }
-};
-
-bool G1CollectedHeap::check_heap_region_claim_values(jint claim_value) {
-  CheckClaimValuesClosure cl(claim_value);
-  heap_region_iterate(&cl);
-  return cl.failures() == 0;
-}
-
-class CheckClaimValuesInCSetHRClosure: public HeapRegionClosure {
-private:
-  jint _claim_value;
-  uint _failures;
-
-public:
-  CheckClaimValuesInCSetHRClosure(jint claim_value) :
-    _claim_value(claim_value), _failures(0) { }
-
-  uint failures() { return _failures; }
-
-  bool doHeapRegion(HeapRegion* hr) {
-    assert(hr->in_collection_set(), "how?");
-    assert(!hr->is_humongous(), "H-region in CSet");
-    if (hr->claim_value() != _claim_value) {
-      gclog_or_tty->print_cr("CSet Region " HR_FORMAT ", "
-                             "claim value = %d, should be %d",
-                             HR_FORMAT_PARAMS(hr),
-                             hr->claim_value(), _claim_value);
-      _failures += 1;
-    }
-    return false;
-  }
-};
-
-bool G1CollectedHeap::check_cset_heap_region_claim_values(jint claim_value) {
-  CheckClaimValuesInCSetHRClosure cl(claim_value);
-  collection_set_iterate(&cl);
-  return cl.failures() == 0;
-}
-#endif // ASSERT
+G1CollectedHeap::heap_region_par_iterate(HeapRegionClosure* cl,
+                                         uint worker_id,
+                                         HeapRegionClaimer *hrclaimer) const {
+  _hrm.par_iterate(cl, worker_id, hrclaimer);
+}
 
 // Clear the cached CSet starting regions and (more importantly)
 // the time stamps. Called when we reset the GC time stamp.
@@ -3251,19 +3146,21 @@
 
 class G1ParVerifyTask: public AbstractGangTask {
 private:
-  G1CollectedHeap* _g1h;
-  VerifyOption     _vo;
-  bool             _failures;
+  G1CollectedHeap*  _g1h;
+  VerifyOption      _vo;
+  bool              _failures;
+  HeapRegionClaimer _hrclaimer;
 
 public:
   // _vo == UsePrevMarking -> use "prev" marking information,
   // _vo == UseNextMarking -> use "next" marking information,
   // _vo == UseMarkWord    -> use mark word from object header.
   G1ParVerifyTask(G1CollectedHeap* g1h, VerifyOption vo) :
-    AbstractGangTask("Parallel verify task"),
-    _g1h(g1h),
-    _vo(vo),
-    _failures(false) { }
+      AbstractGangTask("Parallel verify task"),
+      _g1h(g1h),
+      _vo(vo),
+      _failures(false),
+      _hrclaimer(g1h->workers()->active_workers()) {}
 
   bool failures() {
     return _failures;
@@ -3272,9 +3169,7 @@
   void work(uint worker_id) {
     HandleMark hm;
     VerifyRegionClosure blk(true, _vo);
-    _g1h->heap_region_par_iterate_chunked(&blk, worker_id,
-                                          _g1h->workers()->active_workers(),
-                                          HeapRegion::ParVerifyClaimValue);
+    _g1h->heap_region_par_iterate(&blk, worker_id, &_hrclaimer);
     if (blk.failures()) {
       _failures = true;
     }
@@ -3316,8 +3211,6 @@
 
     if (!silent) { gclog_or_tty->print("HeapRegions "); }
     if (GCParallelVerificationEnabled && ParallelGCThreads > 1) {
-      assert(check_heap_region_claim_values(HeapRegion::InitialClaimValue),
-             "sanity check");
 
       G1ParVerifyTask task(this, vo);
       assert(UseDynamicNumberOfGCThreads ||
@@ -3331,15 +3224,6 @@
         failures = true;
       }
 
-      // Checks that the expected amount of parallel work was done.
-      // The implication is that n_workers is > 0.
-      assert(check_heap_region_claim_values(HeapRegion::ParVerifyClaimValue),
-             "sanity check");
-
-      reset_heap_region_claim_values();
-
-      assert(check_heap_region_claim_values(HeapRegion::InitialClaimValue),
-             "sanity check");
     } else {
       VerifyRegionClosure blk(false, vo);
       heap_region_iterate(&blk);
@@ -3926,8 +3810,6 @@
     }
 
     assert(check_young_list_well_formed(), "young list should be well formed");
-    assert(check_heap_region_claim_values(HeapRegion::InitialClaimValue),
-           "sanity check");
 
     // Don't dynamically change the number of GC threads this early.  A value of
     // 0 is used to indicate serial work.  When parallel work is done,
@@ -4288,26 +4170,12 @@
 }
 
 void G1CollectedHeap::remove_self_forwarding_pointers() {
-  assert(check_cset_heap_region_claim_values(HeapRegion::InitialClaimValue), "sanity");
-
   double remove_self_forwards_start = os::elapsedTime();
 
+  set_par_threads();
   G1ParRemoveSelfForwardPtrsTask rsfp_task(this);
-
-  if (G1CollectedHeap::use_parallel_gc_threads()) {
-    set_par_threads();
-    workers()->run_task(&rsfp_task);
-    set_par_threads(0);
-  } else {
-    rsfp_task.work(0);
-  }
-
-  assert(check_cset_heap_region_claim_values(HeapRegion::ParEvacFailureClaimValue), "sanity");
-
-  // Reset the claim values in the regions in the collection set.
-  reset_cset_heap_region_claim_values();
-
-  assert(check_cset_heap_region_claim_values(HeapRegion::InitialClaimValue), "sanity");
+  workers()->run_task(&rsfp_task);
+  set_par_threads(0);
 
   // Now restore saved marks, if any.
   assert(_objs_with_preserved_marks.size() ==
@@ -5948,11 +5816,6 @@
 
   purge_code_root_memory();
 
-  if (g1_policy()->during_initial_mark_pause()) {
-    // Reset the claim values set during marking the strong code roots
-    reset_heap_region_claim_values();
-  }
-
   finalize_for_evac_failure();
 
   if (evacuation_failed()) {
--- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.hpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.hpp	Wed Jul 05 20:04:39 2017 +0200
@@ -211,6 +211,7 @@
   friend class G1FreeHumongousRegionClosure;
   // Other related classes.
   friend class G1MarkSweep;
+  friend class HeapRegionClaimer;
 
 private:
   // The one and only G1CollectedHeap, so static functions can find it.
@@ -1377,38 +1378,15 @@
 
   inline HeapWord* bottom_addr_for_region(uint index) const;
 
-  // Divide the heap region sequence into "chunks" of some size (the number
-  // of regions divided by the number of parallel threads times some
-  // overpartition factor, currently 4).  Assumes that this will be called
-  // in parallel by ParallelGCThreads worker threads with distinct worker
-  // ids in the range [0..max(ParallelGCThreads-1, 1)], that all parallel
-  // calls will use the same "claim_value", and that that claim value is
-  // different from the claim_value of any heap region before the start of
-  // the iteration.  Applies "blk->doHeapRegion" to each of the regions, by
-  // attempting to claim the first region in each chunk, and, if
-  // successful, applying the closure to each region in the chunk (and
-  // setting the claim value of the second and subsequent regions of the
-  // chunk.)  For now requires that "doHeapRegion" always returns "false",
-  // i.e., that a closure never attempt to abort a traversal.
-  void heap_region_par_iterate_chunked(HeapRegionClosure* cl,
-                                       uint worker_id,
-                                       uint num_workers,
-                                       jint claim_value) const;
-
-  // It resets all the region claim values to the default.
-  void reset_heap_region_claim_values();
-
-  // Resets the claim values of regions in the current
-  // collection set to the default.
-  void reset_cset_heap_region_claim_values();
-
-#ifdef ASSERT
-  bool check_heap_region_claim_values(jint claim_value);
-
-  // Same as the routine above but only checks regions in the
-  // current collection set.
-  bool check_cset_heap_region_claim_values(jint claim_value);
-#endif // ASSERT
+  // Iterate over the heap regions in parallel. Assumes that this will be called
+  // in parallel by ParallelGCThreads worker threads with distinct worker ids
+  // in the range [0..max(ParallelGCThreads-1, 1)]. Applies "blk->doHeapRegion"
+  // to each of the regions, by attempting to claim the region using the
+  // HeapRegionClaimer and, if successful, applying the closure to the claimed
+  // region.
+  void heap_region_par_iterate(HeapRegionClosure* cl,
+                               uint worker_id,
+                               HeapRegionClaimer* hrclaimer) const;
 
   // Clear the cached cset start regions and (more importantly)
   // the time stamps. Called when we reset the GC time stamp.
--- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -1598,19 +1598,17 @@
   CollectionSetChooser* _hrSorted;
   uint _chunk_size;
   G1CollectedHeap* _g1;
+  HeapRegionClaimer _hrclaimer;
+
 public:
-  ParKnownGarbageTask(CollectionSetChooser* hrSorted, uint chunk_size) :
-    AbstractGangTask("ParKnownGarbageTask"),
-    _hrSorted(hrSorted), _chunk_size(chunk_size),
-    _g1(G1CollectedHeap::heap()) { }
+  ParKnownGarbageTask(CollectionSetChooser* hrSorted, uint chunk_size, uint n_workers) :
+      AbstractGangTask("ParKnownGarbageTask"),
+      _hrSorted(hrSorted), _chunk_size(chunk_size),
+      _g1(G1CollectedHeap::heap()), _hrclaimer(n_workers) {}
 
   void work(uint worker_id) {
     ParKnownGarbageHRClosure parKnownGarbageCl(_hrSorted, _chunk_size);
-
-    // Back to zero for the claim value.
-    _g1->heap_region_par_iterate_chunked(&parKnownGarbageCl, worker_id,
-                                         _g1->workers()->active_workers(),
-                                         HeapRegion::InitialClaimValue);
+    _g1->heap_region_par_iterate(&parKnownGarbageCl, worker_id, &_hrclaimer);
   }
 };
 
@@ -1641,12 +1639,8 @@
     }
     _collectionSetChooser->prepare_for_par_region_addition(_g1->num_regions(),
                                                            WorkUnit);
-    ParKnownGarbageTask parKnownGarbageTask(_collectionSetChooser,
-                                            (int) WorkUnit);
+    ParKnownGarbageTask parKnownGarbageTask(_collectionSetChooser, WorkUnit, (uint) no_of_gc_threads);
     _g1->workers()->run_task(&parKnownGarbageTask);
-
-    assert(_g1->check_heap_region_claim_values(HeapRegion::InitialClaimValue),
-           "sanity check");
   } else {
     KnownGarbageClosure knownGarbagecl(_collectionSetChooser);
     _g1->heap_region_iterate(&knownGarbagecl);
--- a/hotspot/src/share/vm/gc_implementation/g1/g1EvacFailure.hpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1EvacFailure.hpp	Wed Jul 05 20:04:39 2017 +0200
@@ -177,16 +177,18 @@
   G1CollectedHeap* _g1h;
   ConcurrentMark* _cm;
   uint _worker_id;
+  HeapRegionClaimer* _hrclaimer;
 
   DirtyCardQueue _dcq;
   UpdateRSetDeferred _update_rset_cl;
 
 public:
   RemoveSelfForwardPtrHRClosure(G1CollectedHeap* g1h,
-                                uint worker_id) :
-    _g1h(g1h), _dcq(&g1h->dirty_card_queue_set()), _update_rset_cl(g1h, &_dcq),
-    _worker_id(worker_id), _cm(_g1h->concurrent_mark()) {
-    }
+                                uint worker_id,
+                                HeapRegionClaimer* hrclaimer) :
+      _g1h(g1h), _dcq(&g1h->dirty_card_queue_set()), _update_rset_cl(g1h, &_dcq),
+      _worker_id(worker_id), _cm(_g1h->concurrent_mark()), _hrclaimer(hrclaimer) {
+  }
 
   bool doHeapRegion(HeapRegion *hr) {
     bool during_initial_mark = _g1h->g1_policy()->during_initial_mark_pause();
@@ -195,7 +197,7 @@
     assert(!hr->is_humongous(), "sanity");
     assert(hr->in_collection_set(), "bad CS");
 
-    if (hr->claimHeapRegion(HeapRegion::ParEvacFailureClaimValue)) {
+    if (_hrclaimer->claim_region(hr->hrm_index())) {
       if (hr->evacuation_failed()) {
         RemoveSelfForwardPtrObjClosure rspc(_g1h, _cm, hr, &_update_rset_cl,
                                             during_initial_mark,
@@ -233,14 +235,15 @@
 class G1ParRemoveSelfForwardPtrsTask: public AbstractGangTask {
 protected:
   G1CollectedHeap* _g1h;
+  HeapRegionClaimer _hrclaimer;
 
 public:
   G1ParRemoveSelfForwardPtrsTask(G1CollectedHeap* g1h) :
-    AbstractGangTask("G1 Remove Self-forwarding Pointers"),
-    _g1h(g1h) { }
+      AbstractGangTask("G1 Remove Self-forwarding Pointers"), _g1h(g1h),
+      _hrclaimer(g1h->workers()->active_workers()) {}
 
   void work(uint worker_id) {
-    RemoveSelfForwardPtrHRClosure rsfp_cl(_g1h, worker_id);
+    RemoveSelfForwardPtrHRClosure rsfp_cl(_g1h, worker_id, &_hrclaimer);
 
     HeapRegion* hr = _g1h->start_cset_region_for_worker(worker_id);
     _g1h->collection_set_iterate_from(hr, &rsfp_cl);
--- a/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -425,13 +425,9 @@
   _g1->heap_region_iterate(&scrub_cl);
 }
 
-void G1RemSet::scrub_par(BitMap* region_bm, BitMap* card_bm,
-                                uint worker_num, int claim_val) {
+void G1RemSet::scrub_par(BitMap* region_bm, BitMap* card_bm, uint worker_num, HeapRegionClaimer *hrclaimer) {
   ScrubRSClosure scrub_cl(region_bm, card_bm);
-  _g1->heap_region_par_iterate_chunked(&scrub_cl,
-                                       worker_num,
-                                       n_workers(),
-                                       claim_val);
+  _g1->heap_region_par_iterate(&scrub_cl, worker_num, hrclaimer);
 }
 
 G1TriggerClosure::G1TriggerClosure() :
--- a/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.hpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.hpp	Wed Jul 05 20:04:39 2017 +0200
@@ -128,10 +128,10 @@
   void scrub(BitMap* region_bm, BitMap* card_bm);
 
   // Like the above, but assumes is called in parallel: "worker_num" is the
-  // parallel thread id of the current thread, and "claim_val" is the
-  // value that should be used to claim heap regions.
+  // parallel thread id of the current thread, and "hrclaimer" is the shared
+  // HeapRegionClaimer that should be used to claim heap regions.
   void scrub_par(BitMap* region_bm, BitMap* card_bm,
-                 uint worker_num, int claim_val);
+                 uint worker_num, HeapRegionClaimer* hrclaimer);
 
   // Refine the card corresponding to "card_ptr".
   // If check_for_refs_into_cset is true, a true result is returned
--- a/hotspot/src/share/vm/gc_implementation/g1/heapRegion.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegion.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -217,7 +217,6 @@
     } else {
       hrrs->clear();
     }
-    _claimed = InitialClaimValue;
   }
   zero_marked_bytes();
 
@@ -294,17 +293,6 @@
   _humongous_start_region = NULL;
 }
 
-bool HeapRegion::claimHeapRegion(jint claimValue) {
-  jint current = _claimed;
-  if (current != claimValue) {
-    jint res = Atomic::cmpxchg(claimValue, &_claimed, current);
-    if (res == current) {
-      return true;
-    }
-  }
-  return false;
-}
-
 HeapRegion::HeapRegion(uint hrm_index,
                        G1BlockOffsetSharedArray* sharedOffsetArray,
                        MemRegion mr) :
@@ -314,7 +302,7 @@
     _humongous_start_region(NULL),
     _in_collection_set(false),
     _next_in_special_set(NULL),
-    _claimed(InitialClaimValue), _evacuation_failed(false),
+    _evacuation_failed(false),
     _prev_marked_bytes(0), _next_marked_bytes(0), _gc_efficiency(0.0),
     _next_young_region(NULL),
     _next_dirty_cards_region(NULL), _next(NULL), _prev(NULL),
--- a/hotspot/src/share/vm/gc_implementation/g1/heapRegion.hpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegion.hpp	Wed Jul 05 20:04:39 2017 +0200
@@ -254,9 +254,6 @@
   HeapRegionSetBase* _containing_set;
 #endif // ASSERT
 
-  // For parallel heapRegion traversal.
-  jint _claimed;
-
   // We use concurrent marking to determine the amount of live data
   // in each heap region.
   size_t _prev_marked_bytes;    // Bytes known to be live via last completed marking.
@@ -336,19 +333,6 @@
   // up once during initialization time.
   static void setup_heap_region_size(size_t initial_heap_size, size_t max_heap_size);
 
-  enum ClaimValues {
-    InitialClaimValue          = 0,
-    FinalCountClaimValue       = 1,
-    NoteEndClaimValue          = 2,
-    ScrubRemSetClaimValue      = 3,
-    ParVerifyClaimValue        = 4,
-    RebuildRSClaimValue        = 5,
-    ParEvacFailureClaimValue   = 6,
-    AggregateCountClaimValue   = 7,
-    VerifyCountClaimValue      = 8,
-    ParMarkRootClaimValue      = 9
-  };
-
   // All allocated blocks are occupied by objects in a HeapRegion
   bool block_is_obj(const HeapWord* p) const;
 
@@ -691,12 +675,6 @@
     return (HeapWord *) obj >= next_top_at_mark_start();
   }
 
-  // For parallel heapRegion traversal.
-  bool claimHeapRegion(int claimValue);
-  jint claim_value() { return _claimed; }
-  // Use this carefully: only when you're sure no one is claiming...
-  void set_claim_value(int claimValue) { _claimed = claimValue; }
-
   // Returns the "evacuation_failed" property of the region.
   bool evacuation_failed() { return _evacuation_failed; }
 
--- a/hotspot/src/share/vm/gc_implementation/g1/heapRegionManager.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegionManager.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -260,20 +260,17 @@
   return num_regions;
 }
 
-uint HeapRegionManager::start_region_for_worker(uint worker_i, uint num_workers, uint num_regions) const {
-  return num_regions * worker_i / num_workers;
-}
-
-void HeapRegionManager::par_iterate(HeapRegionClosure* blk, uint worker_id, uint num_workers, jint claim_value) const {
-  const uint start_index = start_region_for_worker(worker_id, num_workers, _allocated_heapregions_length);
+void HeapRegionManager::par_iterate(HeapRegionClosure* blk, uint worker_id, HeapRegionClaimer* hrclaimer) const {
+  const uint start_index = hrclaimer->start_region_for_worker(worker_id);
 
   // Every worker will actually look at all regions, skipping over regions that
   // are currently not committed.
   // This also (potentially) iterates over regions newly allocated during GC. This
   // is no problem except for some extra work.
-  for (uint count = 0; count < _allocated_heapregions_length; count++) {
-    const uint index = (start_index + count) % _allocated_heapregions_length;
-    assert(0 <= index && index < _allocated_heapregions_length, "sanity");
+  const uint n_regions = hrclaimer->n_regions();
+  for (uint count = 0; count < n_regions; count++) {
+    const uint index = (start_index + count) % n_regions;
+    assert(0 <= index && index < n_regions, "sanity");
     // Skip over unavailable regions
     if (!is_available(index)) {
       continue;
@@ -282,11 +279,11 @@
     // We'll ignore "continues humongous" regions (we'll process them
     // when we come across their corresponding "start humongous"
     // region) and regions already claimed.
-    if (r->claim_value() == claim_value || r->is_continues_humongous()) {
+    if (hrclaimer->is_region_claimed(index) || r->is_continues_humongous()) {
       continue;
     }
     // OK, try to claim it
-    if (!r->claimHeapRegion(claim_value)) {
+    if (!hrclaimer->claim_region(index)) {
       continue;
     }
     // Success!
@@ -306,13 +303,11 @@
         assert(chr->humongous_start_region() == r,
                err_msg("Must work on humongous continuation of the original start region "
                        PTR_FORMAT ", but is " PTR_FORMAT, p2i(r), p2i(chr)));
-        assert(chr->claim_value() != claim_value,
+        assert(!hrclaimer->is_region_claimed(ch_index),
                "Must not have been claimed yet because claiming of humongous continuation first claims the start region");
 
-        bool claim_result = chr->claimHeapRegion(claim_value);
-        // We should always be able to claim it; no one else should
-        // be trying to claim this region.
-        guarantee(claim_result, "We should always be able to claim the is_continues_humongous part of the humongous object");
+        // There's no need to actually claim the continues humongous region, but we can do it in an assert as an extra precaution.
+        assert(hrclaimer->claim_region(ch_index), "We should always be able to claim the continuesHumongous part of the humongous object");
 
         bool res2 = blk->doHeapRegion(chr);
         if (res2) {
@@ -445,3 +440,31 @@
 }
 #endif // PRODUCT
 
+HeapRegionClaimer::HeapRegionClaimer(uint n_workers) :
+    _n_workers(n_workers), _n_regions(G1CollectedHeap::heap()->_hrm._allocated_heapregions_length), _claims(NULL) {
+  assert(n_workers > 0, "Need at least one worker.");
+  _claims = NEW_C_HEAP_ARRAY(uint, _n_regions, mtGC);
+  memset(_claims, Unclaimed, sizeof(*_claims) * _n_regions);
+}
+
+HeapRegionClaimer::~HeapRegionClaimer() {
+  if (_claims != NULL) {
+    FREE_C_HEAP_ARRAY(uint, _claims, mtGC);
+  }
+}
+
+uint HeapRegionClaimer::start_region_for_worker(uint worker_id) const {
+  assert(worker_id < _n_workers, "Invalid worker_id.");
+  return _n_regions * worker_id / _n_workers;
+}
+
+bool HeapRegionClaimer::is_region_claimed(uint region_index) const {
+  assert(region_index < _n_regions, "Invalid index.");
+  return _claims[region_index] == Claimed;
+}
+
+bool HeapRegionClaimer::claim_region(uint region_index) {
+  assert(region_index < _n_regions, "Invalid index.");
+  uint old_val = Atomic::cmpxchg(Claimed, &_claims[region_index], Unclaimed);
+  return old_val == Unclaimed;
+}
--- a/hotspot/src/share/vm/gc_implementation/g1/heapRegionManager.hpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegionManager.hpp	Wed Jul 05 20:04:39 2017 +0200
@@ -31,6 +31,7 @@
 
 class HeapRegion;
 class HeapRegionClosure;
+class HeapRegionClaimer;
 class FreeRegionList;
 
 class G1HeapRegionTable : public G1BiasedMappedArray<HeapRegion*> {
@@ -66,6 +67,7 @@
 
 class HeapRegionManager: public CHeapObj<mtGC> {
   friend class VMStructs;
+  friend class HeapRegionClaimer;
 
   G1HeapRegionTable _regions;
 
@@ -99,9 +101,6 @@
 
   // Notify other data structures about change in the heap layout.
   void update_committed_space(HeapWord* old_end, HeapWord* new_end);
-  // Calculate the starting region for each worker during parallel iteration so
-  // that they do not all start from the same region.
-  uint start_region_for_worker(uint worker_i, uint num_workers, uint num_regions) const;
 
   // Find a contiguous set of empty or uncommitted regions of length num and return
   // the index of the first region or G1_NO_HRM_INDEX if the search was unsuccessful.
@@ -223,7 +222,7 @@
   // terminating the iteration early if doHeapRegion() returns true.
   void iterate(HeapRegionClosure* blk) const;
 
-  void par_iterate(HeapRegionClosure* blk, uint worker_id, uint no_of_par_workers, jint claim_value) const;
+  void par_iterate(HeapRegionClosure* blk, uint worker_id, HeapRegionClaimer* hrclaimer) const;
 
   // Uncommit up to num_regions_to_remove regions that are completely free.
   // Return the actual number of uncommitted regions.
@@ -235,5 +234,33 @@
   void verify_optional() PRODUCT_RETURN;
 };
 
+// The HeapRegionClaimer is used during parallel iteration over heap regions,
+// allowing workers to claim heap regions, gaining exclusive rights to these regions.
+class HeapRegionClaimer : public StackObj {
+  uint  _n_workers;
+  uint  _n_regions;
+  uint* _claims;
+
+  static const uint Unclaimed = 0;
+  static const uint Claimed   = 1;
+
+ public:
+  HeapRegionClaimer(uint n_workers);
+  ~HeapRegionClaimer();
+
+  inline uint n_regions() const {
+    return _n_regions;
+  }
+
+  // Calculate the starting region for given worker so
+  // that they do not all start from the same region.
+  uint start_region_for_worker(uint worker_id) const;
+
+  // Check if region has been claimed with this HRClaimer.
+  bool is_region_claimed(uint region_index) const;
+
+  // Claim the given region, returns true if successfully claimed.
+  bool claim_region(uint region_index);
+};
 #endif // SHARE_VM_GC_IMPLEMENTATION_G1_HEAPREGIONMANAGER_HPP
 
--- a/hotspot/src/share/vm/gc_implementation/g1/vm_operations_g1.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/vm_operations_g1.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -95,8 +95,9 @@
   assert(!_should_initiate_conc_mark ||
   ((_gc_cause == GCCause::_gc_locker && GCLockerInvokesConcurrent) ||
    (_gc_cause == GCCause::_java_lang_system_gc && ExplicitGCInvokesConcurrent) ||
-    _gc_cause == GCCause::_g1_humongous_allocation),
-         "only a GC locker, a System.gc() or a hum allocation induced GC should start a cycle");
+    _gc_cause == GCCause::_g1_humongous_allocation ||
+    _gc_cause == GCCause::_update_allocation_context_stats_inc),
+      "only a GC locker, a System.gc(), stats update or a hum allocation induced GC should start a cycle");
 
   if (_word_size > 0) {
     // An allocation has been requested. So, try to do that first.
--- a/hotspot/src/share/vm/gc_interface/gcCause.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/gc_interface/gcCause.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -54,7 +54,8 @@
     case _wb_young_gc:
       return "WhiteBox Initiated Young GC";
 
-    case _update_allocation_context_stats:
+    case _update_allocation_context_stats_inc:
+    case _update_allocation_context_stats_full:
       return "Update Allocation Context Stats";
 
     case _no_gc:
--- a/hotspot/src/share/vm/gc_interface/gcCause.hpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/gc_interface/gcCause.hpp	Wed Jul 05 20:04:39 2017 +0200
@@ -47,7 +47,8 @@
     _heap_inspection,
     _heap_dump,
     _wb_young_gc,
-    _update_allocation_context_stats,
+    _update_allocation_context_stats_inc,
+    _update_allocation_context_stats_full,
 
     /* implementation independent, but reserved for GC use */
     _no_gc,
--- a/hotspot/src/share/vm/interpreter/linkResolver.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/interpreter/linkResolver.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -246,6 +246,12 @@
   // Ignore overpasses so statics can be found during resolution
   Method* result_oop = klass->uncached_lookup_method(name, signature, Klass::skip_overpass);
 
+  if (klass->oop_is_array()) {
+    // Only consider klass and super klass for arrays
+    result = methodHandle(THREAD, result_oop);
+    return;
+  }
+
   // JDK 8, JVMS 5.4.3.4: Interface method resolution should
   // ignore static and non-public methods of java.lang.Object,
   // like clone, finalize, registerNatives.
@@ -290,6 +296,11 @@
     result = methodHandle(THREAD, super_klass->uncached_lookup_method(name, signature, Klass::normal));
   }
 
+  if (klass->oop_is_array()) {
+    // Only consider klass and super klass for arrays
+    return;
+  }
+
   if (result.is_null()) {
     Array<Method*>* default_methods = InstanceKlass::cast(klass())->default_methods();
     if (default_methods != NULL) {
@@ -545,7 +556,7 @@
   // 2. lookup method in resolved klass and its super klasses
   lookup_method_in_klasses(resolved_method, resolved_klass, method_name, method_signature, true, false, CHECK);
 
-  if (resolved_method.is_null()) { // not found in the class hierarchy
+  if (resolved_method.is_null() && !resolved_klass->oop_is_array()) { // not found in the class hierarchy
     // 3. lookup method in all the interfaces implemented by the resolved klass
     lookup_method_in_interfaces(resolved_method, resolved_klass, method_name, method_signature, CHECK);
 
@@ -558,16 +569,16 @@
         CLEAR_PENDING_EXCEPTION;
       }
     }
+  }
 
-    if (resolved_method.is_null()) {
-      // 4. method lookup failed
-      ResourceMark rm(THREAD);
-      THROW_MSG_CAUSE(vmSymbols::java_lang_NoSuchMethodError(),
-                      Method::name_and_sig_as_C_string(resolved_klass(),
-                                                              method_name,
-                                                              method_signature),
-                      nested_exception);
-    }
+  if (resolved_method.is_null()) {
+    // 4. method lookup failed
+    ResourceMark rm(THREAD);
+    THROW_MSG_CAUSE(vmSymbols::java_lang_NoSuchMethodError(),
+                    Method::name_and_sig_as_C_string(resolved_klass(),
+                                                            method_name,
+                                                            method_signature),
+                    nested_exception);
   }
 
   // 5. access checks, access checking may be turned off when calling from within the VM.
@@ -633,17 +644,18 @@
   // JDK8: also look for static methods
   lookup_method_in_klasses(resolved_method, resolved_klass, method_name, method_signature, false, true, CHECK);
 
-  if (resolved_method.is_null()) {
+  if (resolved_method.is_null() && !resolved_klass->oop_is_array()) {
     // lookup method in all the super-interfaces
     lookup_method_in_interfaces(resolved_method, resolved_klass, method_name, method_signature, CHECK);
-    if (resolved_method.is_null()) {
-      // no method found
-      ResourceMark rm(THREAD);
-      THROW_MSG(vmSymbols::java_lang_NoSuchMethodError(),
-                Method::name_and_sig_as_C_string(resolved_klass(),
-                                                        method_name,
-                                                        method_signature));
-    }
+  }
+
+  if (resolved_method.is_null()) {
+    // no method found
+    ResourceMark rm(THREAD);
+    THROW_MSG(vmSymbols::java_lang_NoSuchMethodError(),
+              Method::name_and_sig_as_C_string(resolved_klass(),
+                                                      method_name,
+                                                      method_signature));
   }
 
   if (check_access) {
@@ -775,7 +787,7 @@
   }
 
   // Resolve instance field
-  KlassHandle sel_klass(THREAD, InstanceKlass::cast(resolved_klass())->find_field(field, sig, &fd));
+  KlassHandle sel_klass(THREAD, resolved_klass->find_field(field, sig, &fd));
   // check if field exists; i.e., if a klass containing the field def has been selected
   if (sel_klass.is_null()) {
     ResourceMark rm(THREAD);
--- a/hotspot/src/share/vm/memory/filemap.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/memory/filemap.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -331,6 +331,14 @@
     return false;
   }
 
+  size_t len = lseek(fd, 0, SEEK_END);
+  struct FileMapInfo::FileMapHeader::space_info* si =
+    &_header->_space[MetaspaceShared::mc];
+  if (si->_file_offset >= len || len - si->_file_offset < si->_used) {
+    fail_continue("The shared archive file has been truncated.");
+    return false;
+  }
+
   _file_offset += (long)n;
   return true;
 }
@@ -431,6 +439,7 @@
   si->_capacity = capacity;
   si->_read_only = read_only;
   si->_allow_exec = allow_exec;
+  si->_crc = ClassLoader::crc32(0, base, (jint)size);
   write_bytes_aligned(base, (int)size);
 }
 
@@ -455,14 +464,15 @@
 // Align file position to an allocation unit boundary.
 
 void FileMapInfo::align_file_position() {
-  long new_file_offset = align_size_up(_file_offset, os::vm_allocation_granularity());
+  size_t new_file_offset = align_size_up(_file_offset,
+                                         os::vm_allocation_granularity());
   if (new_file_offset != _file_offset) {
     _file_offset = new_file_offset;
     if (_file_open) {
       // Seek one byte back from the target and write a byte to insure
       // that the written file is the correct length.
       _file_offset -= 1;
-      if (lseek(_fd, _file_offset, SEEK_SET) < 0) {
+      if (lseek(_fd, (long)_file_offset, SEEK_SET) < 0) {
         fail_stop("Unable to seek.");
       }
       char zero = 0;
@@ -569,6 +579,19 @@
   return base;
 }
 
+bool FileMapInfo::verify_region_checksum(int i) {
+  if (!VerifySharedSpaces) {
+    return true;
+  }
+  const char* buf = _header->_space[i]._base;
+  size_t sz = _header->_space[i]._used;
+  int crc = ClassLoader::crc32(0, buf, (jint)sz);
+  if (crc != _header->_space[i]._crc) {
+    fail_continue("Checksum verification failed.");
+    return false;
+  }
+  return true;
+}
 
 // Unmap a memory region in the address space.
 
@@ -629,7 +652,21 @@
   return true;
 }
 
+int FileMapInfo::FileMapHeader::compute_crc() {
+  char* header = data();
+  // start computing from the field after _crc
+  char* buf = (char*)&_crc + sizeof(int);
+  size_t sz = data_size() - (buf - header);
+  int crc = ClassLoader::crc32(0, buf, (jint)sz);
+  return crc;
+}
+
 bool FileMapInfo::FileMapHeader::validate() {
+  if (VerifySharedSpaces && compute_crc() != _crc) {
+    fail_continue("Header checksum verification failed.");
+    return false;
+  }
+
   if (_version != current_version()) {
     FileMapInfo::fail_continue("The shared archive file is the wrong version.");
     return false;
--- a/hotspot/src/share/vm/memory/filemap.hpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/memory/filemap.hpp	Wed Jul 05 20:04:39 2017 +0200
@@ -61,7 +61,7 @@
 
   bool  _file_open;
   int   _fd;
-  long  _file_offset;
+  size_t  _file_offset;
 
 private:
   static SharedClassPathEntry* _classpath_entry_table;
@@ -87,12 +87,14 @@
     }
 
     int    _magic;                    // identify file type.
+    int    _crc;                      // header crc checksum.
     int    _version;                  // (from enum, above.)
     size_t _alignment;                // how shared archive should be aligned
     int    _obj_alignment;            // value of ObjectAlignmentInBytes
 
     struct space_info {
-      int    _file_offset;   // sizeof(this) rounded to vm page size
+      int    _crc;           // crc checksum of the current space
+      size_t _file_offset;   // sizeof(this) rounded to vm page size
       char*  _base;          // copy-on-write base address
       size_t _capacity;      // for validity checking
       size_t _used;          // for setting space top on read
@@ -135,6 +137,7 @@
 
     virtual bool validate();
     virtual void populate(FileMapInfo* info, size_t alignment);
+    int compute_crc();
   };
 
   FileMapHeader * _header;
@@ -153,6 +156,8 @@
   ~FileMapInfo();
 
   static int current_version()        { return _current_version; }
+  int    compute_header_crc()         { return _header->compute_crc(); }
+  void   set_header_crc(int crc)      { _header->_crc = crc; }
   void   populate_header(size_t alignment);
   bool   validate_header();
   void   invalidate();
@@ -181,6 +186,7 @@
   void  write_bytes_aligned(const void* buffer, int count);
   char* map_region(int i);
   void  unmap_region(int i);
+  bool  verify_region_checksum(int i);
   void  close();
   bool  is_open() { return _file_open; }
   ReservedSpace reserve_shared_memory();
--- a/hotspot/src/share/vm/memory/metaspaceShared.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/memory/metaspaceShared.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -608,6 +608,7 @@
 
   // Pass 2 - write data.
   mapinfo->open_for_write();
+  mapinfo->set_header_crc(mapinfo->compute_header_crc());
   mapinfo->write_header();
   mapinfo->write_space(MetaspaceShared::ro, _loader_data->ro_metaspace(), true);
   mapinfo->write_space(MetaspaceShared::rw, _loader_data->rw_metaspace(), false);
@@ -937,9 +938,13 @@
 
   // Map each shared region
   if ((_ro_base = mapinfo->map_region(ro)) != NULL &&
+       mapinfo->verify_region_checksum(ro) &&
       (_rw_base = mapinfo->map_region(rw)) != NULL &&
+       mapinfo->verify_region_checksum(rw) &&
       (_md_base = mapinfo->map_region(md)) != NULL &&
+       mapinfo->verify_region_checksum(md) &&
       (_mc_base = mapinfo->map_region(mc)) != NULL &&
+       mapinfo->verify_region_checksum(mc) &&
       (image_alignment == (size_t)max_alignment()) &&
       mapinfo->validate_classpath_entry_table()) {
     // Success (no need to do anything)
--- a/hotspot/src/share/vm/oops/arrayKlass.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/oops/arrayKlass.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -64,6 +64,13 @@
   return NULL;
 }
 
+// find field according to JVM spec 5.4.3.2, returns the klass in which the field is defined
+Klass* ArrayKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
+  // There are no fields in an array klass but look to the super class (Object)
+  assert(super(), "super klass must be present");
+  return super()->find_field(name, sig, fd);
+}
+
 Method* ArrayKlass::uncached_lookup_method(Symbol* name, Symbol* signature, MethodLookupMode mode) const {
   // There are no methods in an array klass but the super class (Object) has some
   assert(super(), "super klass must be present");
--- a/hotspot/src/share/vm/oops/arrayKlass.hpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/oops/arrayKlass.hpp	Wed Jul 05 20:04:39 2017 +0200
@@ -28,6 +28,7 @@
 #include "memory/universe.hpp"
 #include "oops/klass.hpp"
 
+class fieldDescriptor;
 class klassVtable;
 
 // ArrayKlass is the abstract baseclass for all array classes
@@ -77,6 +78,9 @@
   virtual oop multi_allocate(int rank, jint* sizes, TRAPS);
   objArrayOop allocate_arrayArray(int n, int length, TRAPS);
 
+  // find field according to JVM spec 5.4.3.2, returns the klass in which the field is defined
+  Klass* find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const;
+
   // Lookup operations
   Method* uncached_lookup_method(Symbol* name, Symbol* signature, MethodLookupMode mode) const;
 
--- a/hotspot/src/share/vm/oops/klass.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/oops/klass.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -130,6 +130,15 @@
   return is_subclass_of(k);
 }
 
+Klass* Klass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
+#ifdef ASSERT
+  tty->print_cr("Error: find_field called on a klass oop."
+                " Likely error: reflection method does not correctly"
+                " wrap return value in a mirror object.");
+#endif
+  ShouldNotReachHere();
+  return NULL;
+}
 
 Method* Klass::uncached_lookup_method(Symbol* name, Symbol* signature, MethodLookupMode mode) const {
 #ifdef ASSERT
--- a/hotspot/src/share/vm/oops/klass.hpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/oops/klass.hpp	Wed Jul 05 20:04:39 2017 +0200
@@ -62,6 +62,7 @@
 class klassVtable;
 class ParCompactionManager;
 class KlassSizeStats;
+class fieldDescriptor;
 
 class Klass : public Metadata {
   friend class VMStructs;
@@ -411,6 +412,7 @@
   virtual void initialize(TRAPS);
   // lookup operation for MethodLookupCache
   friend class MethodLookupCache;
+  virtual Klass* find_field(Symbol* name, Symbol* signature, fieldDescriptor* fd) const;
   virtual Method* uncached_lookup_method(Symbol* name, Symbol* signature, MethodLookupMode mode) const;
  public:
   Method* lookup_method(Symbol* name, Symbol* signature) const {
--- a/hotspot/src/share/vm/opto/compile.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/opto/compile.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -1153,12 +1153,18 @@
   assert(s == start(), "");
 }
 
+/**
+ * Return the 'StartNode'. We must not have a pending failure, since the ideal graph
+ * can be in an inconsistent state, i.e., we can get segmentation faults when traversing
+ * the ideal graph.
+ */
 StartNode* Compile::start() const {
-  assert(!failing(), "");
+  assert (!failing(), err_msg_res("Must not have pending failure. Reason is: %s", failure_reason()));
   for (DUIterator_Fast imax, i = root()->fast_outs(imax); i < imax; i++) {
     Node* start = root()->fast_out(i);
-    if( start->is_Start() )
+    if (start->is_Start()) {
       return start->as_Start();
+    }
   }
   fatal("Did not find Start node!");
   return NULL;
--- a/hotspot/src/share/vm/opto/compile.hpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/opto/compile.hpp	Wed Jul 05 20:04:39 2017 +0200
@@ -707,12 +707,15 @@
   void sort_expensive_nodes();
 
   // Compilation environment.
-  Arena*            comp_arena()                { return &_comp_arena; }
-  ciEnv*            env() const                 { return _env; }
-  CompileLog*       log() const                 { return _log; }
-  bool              failing() const             { return _env->failing() || _failure_reason != NULL; }
-  const char*       failure_reason() { return _failure_reason; }
-  bool              failure_reason_is(const char* r) { return (r==_failure_reason) || (r!=NULL && _failure_reason!=NULL && strcmp(r, _failure_reason)==0); }
+  Arena*      comp_arena()           { return &_comp_arena; }
+  ciEnv*      env() const            { return _env; }
+  CompileLog* log() const            { return _log; }
+  bool        failing() const        { return _env->failing() || _failure_reason != NULL; }
+  const char* failure_reason() const { return (_env->failing()) ? _env->failure_reason() : _failure_reason; }
+
+  bool failure_reason_is(const char* r) const {
+    return (r == _failure_reason) || (r != NULL && _failure_reason != NULL && strcmp(r, _failure_reason) == 0);
+  }
 
   void record_failure(const char* reason);
   void record_method_not_compilable(const char* reason, bool all_tiers = false) {
--- a/hotspot/src/share/vm/opto/doCall.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/opto/doCall.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -802,10 +802,16 @@
     // each arm of the Phi.  If I know something clever about the exceptions
     // I'm loading the class from, I can replace the LoadKlass with the
     // klass constant for the exception oop.
-    if( ex_node->is_Phi() ) {
-      ex_klass_node = new PhiNode( ex_node->in(0), TypeKlassPtr::OBJECT );
-      for( uint i = 1; i < ex_node->req(); i++ ) {
-        Node* p = basic_plus_adr( ex_node->in(i), ex_node->in(i), oopDesc::klass_offset_in_bytes() );
+    if (ex_node->is_Phi()) {
+      ex_klass_node = new PhiNode(ex_node->in(0), TypeKlassPtr::OBJECT);
+      for (uint i = 1; i < ex_node->req(); i++) {
+        Node* ex_in = ex_node->in(i);
+        if (ex_in == top() || ex_in == NULL) {
+          // This path was not taken.
+          ex_klass_node->init_req(i, top());
+          continue;
+        }
+        Node* p = basic_plus_adr(ex_in, ex_in, oopDesc::klass_offset_in_bytes());
         Node* k = _gvn.transform( LoadKlassNode::make(_gvn, immutable_memory(), p, TypeInstPtr::KLASS, TypeKlassPtr::OBJECT) );
         ex_klass_node->init_req( i, k );
       }
--- a/hotspot/src/share/vm/prims/jvm.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/prims/jvm.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -805,6 +805,7 @@
   return (jclass) JNIHandles::make_local(env, k->java_mirror());
 JVM_END
 
+// Not used; JVM_FindClassFromCaller replaces this.
 JVM_ENTRY(jclass, JVM_FindClassFromClassLoader(JNIEnv* env, const char* name,
                                                jboolean init, jobject loader,
                                                jboolean throwError))
@@ -831,6 +832,42 @@
   return result;
 JVM_END
 
+// Find a class with this name in this loader, using the caller's protection domain.
+JVM_ENTRY(jclass, JVM_FindClassFromCaller(JNIEnv* env, const char* name,
+                                          jboolean init, jobject loader,
+                                          jclass caller))
+  JVMWrapper2("JVM_FindClassFromCaller %s throws ClassNotFoundException", name);
+  // Java libraries should ensure that name is never null...
+  if (name == NULL || (int)strlen(name) > Symbol::max_length()) {
+    // It's impossible to create this class;  the name cannot fit
+    // into the constant pool.
+    THROW_MSG_0(vmSymbols::java_lang_ClassNotFoundException(), name);
+  }
+
+  TempNewSymbol h_name = SymbolTable::new_symbol(name, CHECK_NULL);
+
+  oop loader_oop = JNIHandles::resolve(loader);
+  oop from_class = JNIHandles::resolve(caller);
+  oop protection_domain = NULL;
+  // If loader is null, shouldn't call ClassLoader.checkPackageAccess; otherwise get
+  // NPE. Put it in another way, the bootstrap class loader has all permission and
+  // thus no checkPackageAccess equivalence in the VM class loader.
+  // The caller is also passed as NULL by the java code if there is no security
+  // manager to avoid the performance cost of getting the calling class.
+  if (from_class != NULL && loader_oop != NULL) {
+    protection_domain = java_lang_Class::as_Klass(from_class)->protection_domain();
+  }
+
+  Handle h_loader(THREAD, loader_oop);
+  Handle h_prot(THREAD, protection_domain);
+  jclass result = find_class_from_class_loader(env, h_name, init, h_loader,
+                                               h_prot, false, THREAD);
+
+  if (TraceClassResolution && result != NULL) {
+    trace_class_resolution(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(result)));
+  }
+  return result;
+JVM_END
 
 JVM_ENTRY(jclass, JVM_FindClassFromClass(JNIEnv *env, const char *name,
                                          jboolean init, jclass from))
@@ -1073,17 +1110,6 @@
 JVM_END
 
 
-JVM_ENTRY(jobject, JVM_GetClassLoader(JNIEnv *env, jclass cls))
-  JVMWrapper("JVM_GetClassLoader");
-  if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
-    return NULL;
-  }
-  Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
-  oop loader = k->class_loader();
-  return JNIHandles::make_local(env, loader);
-JVM_END
-
-
 JVM_QUICK_ENTRY(jboolean, JVM_IsInterface(JNIEnv *env, jclass cls))
   JVMWrapper("JVM_IsInterface");
   oop mirror = JNIHandles::resolve_non_null(cls);
@@ -3932,10 +3958,15 @@
 
 // Shared JNI/JVM entry points //////////////////////////////////////////////////////////////
 
-jclass find_class_from_class_loader(JNIEnv* env, Symbol* name, jboolean init, Handle loader, Handle protection_domain, jboolean throwError, TRAPS) {
+jclass find_class_from_class_loader(JNIEnv* env, Symbol* name, jboolean init,
+                                    Handle loader, Handle protection_domain,
+                                    jboolean throwError, TRAPS) {
   // Security Note:
   //   The Java level wrapper will perform the necessary security check allowing
-  //   us to pass the NULL as the initiating class loader.
+  //   us to pass the NULL as the initiating class loader.  The VM is responsible for
+  //   the checkPackageAccess relative to the initiating class loader via the
+  //   protection_domain. The protection_domain is passed as NULL by the java code
+  //   if there is no security manager in 3-arg Class.forName().
   Klass* klass = SystemDictionary::resolve_or_fail(name, loader, protection_domain, throwError != 0, CHECK_NULL);
 
   KlassHandle klass_handle(THREAD, klass);
--- a/hotspot/src/share/vm/prims/jvm.h	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/prims/jvm.h	Wed Jul 05 20:04:39 2017 +0200
@@ -420,6 +420,19 @@
 JVM_FindClassFromBootLoader(JNIEnv *env, const char *name);
 
 /*
+ * Find a class from a given class loader.  Throws ClassNotFoundException.
+ *  name:   name of class
+ *  init:   whether initialization is done
+ *  loader: class loader to look up the class. This may not be the same as the caller's
+ *          class loader.
+ *  caller: initiating class. The initiating class may be null when a security
+ *          manager is not installed.
+ */
+JNIEXPORT jclass JNICALL
+JVM_FindClassFromCaller(JNIEnv *env, const char *name, jboolean init,
+                        jobject loader, jclass caller);
+
+/*
  * Find a class from a given class.
  */
 JNIEXPORT jclass JNICALL
@@ -462,9 +475,6 @@
 JNIEXPORT jobjectArray JNICALL
 JVM_GetClassInterfaces(JNIEnv *env, jclass cls);
 
-JNIEXPORT jobject JNICALL
-JVM_GetClassLoader(JNIEnv *env, jclass cls);
-
 JNIEXPORT jboolean JNICALL
 JVM_IsInterface(JNIEnv *env, jclass cls);
 
--- a/hotspot/src/share/vm/runtime/arguments.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/runtime/arguments.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -3836,6 +3836,11 @@
     return JNI_ENOMEM;
   }
 
+  // Set up VerifySharedSpaces
+  if (FLAG_IS_DEFAULT(VerifySharedSpaces) && SharedArchiveFile != NULL) {
+    VerifySharedSpaces = true;
+  }
+
   // Delay warning until here so that we've had a chance to process
   // the -XX:-PrintWarnings flag
   if (needs_hotspotrc_warning) {
--- a/hotspot/src/share/vm/runtime/globals.hpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/runtime/globals.hpp	Wed Jul 05 20:04:39 2017 +0200
@@ -1177,11 +1177,11 @@
           "When true prevents OS-level spurious, or premature, wakeups "    \
           "from Object.wait (Ignored for Windows)")                         \
                                                                             \
-  product(intx, NativeMonitorTimeout, -1, "(Unstable)")                     \
-                                                                            \
-  product(intx, NativeMonitorFlags, 0, "(Unstable)")                        \
-                                                                            \
-  product(intx, NativeMonitorSpinLimit, 20, "(Unstable)")                   \
+  experimental(intx, NativeMonitorTimeout, -1, "(Unstable)")                \
+                                                                            \
+  experimental(intx, NativeMonitorFlags, 0, "(Unstable)")                   \
+                                                                            \
+  experimental(intx, NativeMonitorSpinLimit, 20, "(Unstable)")              \
                                                                             \
   develop(bool, UsePthreads, false,                                         \
           "Use pthread-based instead of libthread-based synchronization "   \
@@ -3790,6 +3790,10 @@
   product(bool, UseSharedSpaces, true,                                      \
           "Use shared spaces for metadata")                                 \
                                                                             \
+  product(bool, VerifySharedSpaces, false,                                  \
+          "Verify shared spaces (false for default archive, true for "      \
+          "archive specified by -XX:SharedArchiveFile)")                    \
+                                                                            \
   product(bool, RequireSharedSpaces, false,                                 \
           "Require shared spaces for metadata")                             \
                                                                             \
--- a/hotspot/src/share/vm/runtime/perfMemory.hpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/runtime/perfMemory.hpp	Wed Jul 05 20:04:39 2017 +0200
@@ -155,9 +155,6 @@
       }
     }
 
-    // filename of backing store or NULL if none.
-    static char* backing_store_filename();
-
     // returns the complete file path of hsperfdata.
     // the caller is expected to free the allocated memory.
     static char* get_perfdata_file_path();
--- a/hotspot/src/share/vm/runtime/reflection.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/runtime/reflection.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -507,7 +507,8 @@
   if (access.is_protected()) {
     if (!protected_restriction) {
       // See if current_class (or outermost host class) is a subclass of field_class
-      if (host_class->is_subclass_of(field_class)) {
+      // An interface may not access protected members of j.l.Object
+      if (!host_class->is_interface() && host_class->is_subclass_of(field_class)) {
         if (access.is_static() || // static fields are ok, see 6622385
             current_class == resolved_class ||
             field_class == resolved_class ||
--- a/hotspot/src/share/vm/runtime/sweeper.cpp	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/src/share/vm/runtime/sweeper.cpp	Wed Jul 05 20:04:39 2017 +0200
@@ -540,17 +540,25 @@
     // If there are no current activations of this method on the
     // stack we can safely convert it to a zombie method
     if (nm->can_not_entrant_be_converted()) {
-      if (PrintMethodFlushing && Verbose) {
-        tty->print_cr("### Nmethod %3d/" PTR_FORMAT " (not entrant) being made zombie", nm->compile_id(), nm);
-      }
       // Clear ICStubs to prevent back patching stubs of zombie or unloaded
       // nmethods during the next safepoint (see ICStub::finalize).
-      MutexLocker cl(CompiledIC_lock);
-      nm->clear_ic_stubs();
-      // Code cache state change is tracked in make_zombie()
-      nm->make_zombie();
-      _zombified_count++;
-      SWEEP(nm);
+      {
+        MutexLocker cl(CompiledIC_lock);
+        nm->clear_ic_stubs();
+      }
+      // Acquiring the CompiledIC_lock may block for a safepoint and set the
+      // nmethod to zombie (see 'CodeCache::make_marked_nmethods_zombies').
+      // Check if nmethod is still non-entrant at this point.
+      if (nm->is_not_entrant()) {
+        if (PrintMethodFlushing && Verbose) {
+          tty->print_cr("### Nmethod %3d/" PTR_FORMAT " (not entrant) being made zombie", nm->compile_id(), nm);
+        }
+        // Code cache state change is tracked in make_zombie()
+        nm->make_zombie();
+        _zombified_count++;
+        SWEEP(nm);
+      }
+      assert(nm->is_zombie(), "nmethod must be zombie");
     } else {
       // Still alive, clean up its inline caches
       MutexLocker cl(CompiledIC_lock);
--- a/hotspot/test/TEST.groups	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/test/TEST.groups	Wed Jul 05 20:04:39 2017 +0200
@@ -447,7 +447,7 @@
   compiler/codegen/ \
   compiler/cpuflags/RestoreMXCSR.java \
   compiler/EscapeAnalysis/ \
-  compiler/exceptions/TestRecursiveReplacedException.java \
+  compiler/exceptions/ \
   compiler/floatingpoint/ModNaN.java \
   compiler/gcbarriers/G1CrashTest.java \
   compiler/inlining/ \
--- a/hotspot/test/compiler/codecache/CheckSegmentedCodeCache.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/hotspot/test/compiler/codecache/CheckSegmentedCodeCache.java	Wed Jul 05 20:04:39 2017 +0200
@@ -38,22 +38,26 @@
 
   private static void verifySegmentedCodeCache(ProcessBuilder pb, boolean enabled) throws Exception {
     OutputAnalyzer out = new OutputAnalyzer(pb.start());
+    out.shouldHaveExitValue(0);
     if (enabled) {
       try {
         // Non-nmethod code heap should be always available with the segmented code cache
         out.shouldContain(NON_METHOD);
       } catch (RuntimeException e) {
-        // TieredCompilation is disabled in a client VM
-        out.shouldContain("TieredCompilation is disabled in this release.");
+        // Check if TieredCompilation is disabled (in a client VM)
+        if(!out.getOutput().contains("TieredCompilation is disabled in this release.")) {
+          // Code cache is not segmented
+          throw new RuntimeException("No code cache segmentation.");
+        }
       }
     } else {
       out.shouldNotContain(NON_METHOD);
     }
-    out.shouldHaveExitValue(0);
   }
 
   private static void verifyCodeHeapNotExists(ProcessBuilder pb, String... heapNames) throws Exception {
     OutputAnalyzer out = new OutputAnalyzer(pb.start());
+    out.shouldHaveExitValue(0);
     for (String name : heapNames) {
       out.shouldNotContain(name);
     }
@@ -86,6 +90,10 @@
                                                "-XX:ReservedCodeCacheSize=240m",
                                                "-XX:+PrintCodeCache", "-version");
     verifySegmentedCodeCache(pb, true);
+    pb = ProcessTools.createJavaProcessBuilder("-XX:+TieredCompilation",
+                                               "-XX:ReservedCodeCacheSize=400m",
+                                               "-XX:+PrintCodeCache", "-version");
+    verifySegmentedCodeCache(pb, true);
 
     // Always enabled if SegmentedCodeCache is set
     pb = ProcessTools.createJavaProcessBuilder("-XX:+SegmentedCodeCache",
@@ -100,12 +108,13 @@
                                                "-Xint",
                                                "-XX:+PrintCodeCache", "-version");
     verifyCodeHeapNotExists(pb, PROFILED, NON_PROFILED);
+
+    // If we stop compilation at CompLevel_none or CompLevel_simple we
+    // don't need a profiled code heap.
     pb = ProcessTools.createJavaProcessBuilder("-XX:+SegmentedCodeCache",
                                                "-XX:TieredStopAtLevel=0",
                                                "-XX:+PrintCodeCache", "-version");
-    verifyCodeHeapNotExists(pb, PROFILED, NON_PROFILED);
-
-    // If we stop compilation at CompLevel_simple
+    verifyCodeHeapNotExists(pb, PROFILED);
     pb = ProcessTools.createJavaProcessBuilder("-XX:+SegmentedCodeCache",
                                                "-XX:TieredStopAtLevel=1",
                                                "-XX:+PrintCodeCache", "-version");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/exceptions/CatchInlineExceptions.java	Wed Jul 05 20:04:39 2017 +0200
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * @test
+ * @bug 8059299
+ * @summary assert(adr_type != NULL) failed: expecting TypeKlassPtr
+ * @run main/othervm -Xbatch CatchInlineExceptions
+ */
+
+class Exception1 extends Exception {};
+class Exception2 extends Exception {};
+
+public class CatchInlineExceptions {
+    private static int counter0;
+    private static int counter1;
+    private static int counter2;
+    private static int counter;
+
+    static void foo(int i) throws Exception {
+        if ((i & 1023) == 2) {
+            counter0++;
+            throw new Exception2();
+        }
+    }
+
+    static void test(int i) throws Exception {
+        try {
+           foo(i);
+        }
+        catch (Exception e) {
+            if (e instanceof Exception1) {
+                counter1++;
+            } else if (e instanceof Exception2) {
+                counter2++;
+            }
+            counter++;
+            throw e;
+        }
+    }
+
+    public static void main(String[] args) throws Throwable {
+        for (int i = 0; i < 15000; i++) {
+            try {
+                test(i);
+            } catch (Exception e) {
+                // expected
+            }
+        }
+        if (counter1 != 0) {
+            throw new RuntimeException("Failed: counter1(" + counter1  + ") != 0");
+        }
+        if (counter2 != counter) {
+            throw new RuntimeException("Failed: counter2(" + counter2  + ") != counter0(" + counter0  + ")");
+        }
+        if (counter2 != counter) {
+            throw new RuntimeException("Failed: counter2(" + counter2  + ") != counter(" + counter  + ")");
+        }
+        System.out.println("TEST PASSED");
+    }
+}
--- a/jaxp/.hgtags	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/.hgtags	Wed Jul 05 20:04:39 2017 +0200
@@ -277,3 +277,4 @@
 b940ca3d2c7e8a279ca850706b89c2ad3a841e82 jdk9-b32
 46b360454dadbb329d42c59bb8192daeb9d59875 jdk9-b33
 6b343b9b7a7008f5f699a2d99881163cab7a2986 jdk9-b34
+b9370464572fc663a38956047aa612d6e7854c3d jdk9-b35
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/DOMConfigurationImpl.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/DOMConfigurationImpl.java	Wed Jul 05 20:04:39 2017 +0200
@@ -1,13 +1,13 @@
 /*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * Copyright 2001-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
@@ -51,8 +51,6 @@
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.Locale;
-import java.util.Vector;
-import javax.xml.XMLConstants;
 import org.w3c.dom.DOMConfiguration;
 import org.w3c.dom.DOMErrorHandler;
 import org.w3c.dom.DOMException;
@@ -976,41 +974,40 @@
      */
     public DOMStringList getParameterNames() {
         if (fRecognizedParameters == null){
-                        Vector parameters = new Vector();
+            ArrayList parameters = new ArrayList();
 
-                        //Add DOM recognized parameters
-                        //REVISIT: Would have been nice to have a list of
-                        //recognized paramters.
-                        parameters.add(Constants.DOM_COMMENTS);
-                        parameters.add(Constants.DOM_DATATYPE_NORMALIZATION);
-                        parameters.add(Constants.DOM_CDATA_SECTIONS);
-                        parameters.add(Constants.DOM_ENTITIES);
-                        parameters.add(Constants.DOM_SPLIT_CDATA);
-                        parameters.add(Constants.DOM_NAMESPACES);
-                        parameters.add(Constants.DOM_VALIDATE);
+            //Add DOM recognized parameters
+            //REVISIT: Would have been nice to have a list of
+            //recognized paramters.
+            parameters.add(Constants.DOM_COMMENTS);
+            parameters.add(Constants.DOM_DATATYPE_NORMALIZATION);
+            parameters.add(Constants.DOM_CDATA_SECTIONS);
+            parameters.add(Constants.DOM_ENTITIES);
+            parameters.add(Constants.DOM_SPLIT_CDATA);
+            parameters.add(Constants.DOM_NAMESPACES);
+            parameters.add(Constants.DOM_VALIDATE);
 
-                        parameters.add(Constants.DOM_INFOSET);
-                        parameters.add(Constants.DOM_NORMALIZE_CHARACTERS);
-                        parameters.add(Constants.DOM_CANONICAL_FORM);
-                        parameters.add(Constants.DOM_VALIDATE_IF_SCHEMA);
-                        parameters.add(Constants.DOM_CHECK_CHAR_NORMALIZATION);
-                        parameters.add(Constants.DOM_WELLFORMED);
+            parameters.add(Constants.DOM_INFOSET);
+            parameters.add(Constants.DOM_NORMALIZE_CHARACTERS);
+            parameters.add(Constants.DOM_CANONICAL_FORM);
+            parameters.add(Constants.DOM_VALIDATE_IF_SCHEMA);
+            parameters.add(Constants.DOM_CHECK_CHAR_NORMALIZATION);
+            parameters.add(Constants.DOM_WELLFORMED);
 
-                        parameters.add(Constants.DOM_NAMESPACE_DECLARATIONS);
-                        parameters.add(Constants.DOM_ELEMENT_CONTENT_WHITESPACE);
+            parameters.add(Constants.DOM_NAMESPACE_DECLARATIONS);
+            parameters.add(Constants.DOM_ELEMENT_CONTENT_WHITESPACE);
 
-                        parameters.add(Constants.DOM_ERROR_HANDLER);
-                        parameters.add(Constants.DOM_SCHEMA_TYPE);
-                        parameters.add(Constants.DOM_SCHEMA_LOCATION);
-                        parameters.add(Constants.DOM_RESOURCE_RESOLVER);
+            parameters.add(Constants.DOM_ERROR_HANDLER);
+            parameters.add(Constants.DOM_SCHEMA_TYPE);
+            parameters.add(Constants.DOM_SCHEMA_LOCATION);
+            parameters.add(Constants.DOM_RESOURCE_RESOLVER);
 
-                        //Add recognized xerces features and properties
-                        parameters.add(GRAMMAR_POOL);
-                        parameters.add(SYMBOL_TABLE);
-                        parameters.add(SEND_PSVI);
+            //Add recognized xerces features and properties
+            parameters.add(GRAMMAR_POOL);
+            parameters.add(SYMBOL_TABLE);
+            parameters.add(SEND_PSVI);
 
-                        fRecognizedParameters = new DOMStringListImpl(parameters);
-
+            fRecognizedParameters = new DOMStringListImpl(parameters);
         }
 
         return fRecognizedParameters;
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/PSVIAttrNSImpl.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/PSVIAttrNSImpl.java	Wed Jul 05 20:04:39 2017 +0200
@@ -1,13 +1,10 @@
 /*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
- */
-/*
- * Copyright 2002-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
@@ -20,14 +17,16 @@
 
 package com.sun.org.apache.xerces.internal.dom;
 
+import com.sun.org.apache.xerces.internal.impl.dv.ValidatedInfo;
+import com.sun.org.apache.xerces.internal.impl.xs.AttributePSVImpl;
+import com.sun.org.apache.xerces.internal.impl.xs.util.StringListImpl;
+import com.sun.org.apache.xerces.internal.xs.*;
+import com.sun.org.apache.xerces.internal.xs.AttributePSVI;
 import java.io.IOException;
 import java.io.NotSerializableException;
 import java.io.ObjectInputStream;
 import java.io.ObjectOutputStream;
 
-import com.sun.org.apache.xerces.internal.xs.AttributePSVI;
-import com.sun.org.apache.xerces.internal.xs.*;
-
 /**
  * Attribute namespace implementation; stores PSVI attribute items.
  *
@@ -67,20 +66,8 @@
      * value in the original document, this is true; otherwise, it is false  */
     protected boolean fSpecified = true;
 
-    /** schema normalized value property */
-    protected String fNormalizedValue = null;
-
-    /** schema actual value */
-    protected Object fActualValue = null;
-
-    /** schema actual value type */
-    protected short fActualValueType = XSConstants.UNAVAILABLE_DT;
-
-    /** actual value types if the value is a list */
-    protected ShortList fItemValueTypes = null;
-
-    /** member type definition against which attribute was validated */
-    protected XSSimpleTypeDefinition fMemberType = null;
+    /** Schema value */
+    protected ValidatedInfo fValue = new ValidatedInfo();
 
     /** validation attempted: none, partial, full */
     protected short fValidationAttempted = AttributePSVI.VALIDATION_NONE;
@@ -91,6 +78,9 @@
     /** error codes */
     protected StringList fErrorCodes = null;
 
+    /** error messages */
+    protected StringList fErrorMessages = null;
+
     /** validation context: could be QName or XPath expression*/
     protected String fValidationContext = null;
 
@@ -98,6 +88,20 @@
     // AttributePSVI methods
     //
 
+    /* (non-Javadoc)
+     * @see org.apache.xerces.xs.ItemPSVI#constant()
+     */
+    public ItemPSVI constant() {
+        return new AttributePSVImpl(true, this);
+    }
+
+    /* (non-Javadoc)
+     * @see org.apache.xerces.xs.ItemPSVI#isConstant()
+     */
+    public boolean isConstant() {
+        return false;
+    }
+
     /**
      * [schema default]
      *
@@ -116,7 +120,7 @@
      * @return the normalized value of this item after validation
      */
     public String getSchemaNormalizedValue() {
-        return fNormalizedValue;
+        return fValue.getNormalizedValue();
     }
 
     /**
@@ -157,7 +161,23 @@
      * @return list of error codes
      */
     public StringList getErrorCodes() {
-        return fErrorCodes;
+        if (fErrorCodes != null) {
+            return fErrorCodes;
+        }
+        return StringListImpl.EMPTY_LIST;
+    }
+
+    /**
+     * A list of error messages generated from the validation attempt or
+     * an empty <code>StringList</code> if no errors occurred during the
+     * validation attempt. The indices of error messages in this list are
+     * aligned with those in the <code>[schema error code]</code> list.
+     */
+    public StringList getErrorMessages() {
+        if (fErrorMessages != null) {
+            return fErrorMessages;
+        }
+        return StringListImpl.EMPTY_LIST;
     }
 
     // This is the only information we can provide in a pipeline.
@@ -177,14 +197,14 @@
     /**
      * If and only if that type definition is a simple type definition
      * with {variety} union, or a complex type definition whose {content type}
-     * is a simple thype definition with {variety} union, then an item isomorphic
+     * is a simple type definition with {variety} union, then an item isomorphic
      * to that member of the union's {member type definitions} which actually
      * validated the element item's normalized value.
      *
      * @return  a simple type declaration
      */
     public XSSimpleTypeDefinition getMemberTypeDefinition() {
-        return fMemberType;
+        return fValue.getMemberTypeDefinition();
     }
 
     /**
@@ -208,12 +228,9 @@
         this.fValidity = attr.getValidity();
         this.fValidationAttempted = attr.getValidationAttempted();
         this.fErrorCodes = attr.getErrorCodes();
-        this.fNormalizedValue = attr.getSchemaNormalizedValue();
-        this.fActualValue = attr.getActualNormalizedValue();
-        this.fActualValueType = attr.getActualNormalizedValueType();
-        this.fItemValueTypes = attr.getItemValueTypes();
+        this.fErrorMessages = attr.getErrorMessages();
+        this.fValue.copyFrom(attr.getSchemaValue());
         this.fTypeDecl = attr.getTypeDefinition();
-        this.fMemberType = attr.getMemberTypeDefinition();
         this.fSpecified = attr.getIsSchemaSpecified();
     }
 
@@ -221,21 +238,28 @@
      * @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#getActualNormalizedValue()
      */
     public Object getActualNormalizedValue() {
-        return this.fActualValue;
+        return fValue.getActualValue();
     }
 
     /* (non-Javadoc)
      * @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#getActualNormalizedValueType()
      */
     public short getActualNormalizedValueType() {
-        return this.fActualValueType;
+        return fValue.getActualValueType();
     }
 
     /* (non-Javadoc)
      * @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#getItemValueTypes()
      */
     public ShortList getItemValueTypes() {
-        return this.fItemValueTypes;
+        return fValue.getListValueTypes();
+    }
+
+    /* (non-Javadoc)
+     * @see org.apache.xerces.xs.ItemPSVI#getSchemaValue()
+     */
+    public XSValue getSchemaValue() {
+        return fValue;
     }
 
     // REVISIT: Forbid serialization of PSVI DOM until
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/PSVIElementNSImpl.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/PSVIElementNSImpl.java	Wed Jul 05 20:04:39 2017 +0200
@@ -1,13 +1,10 @@
 /*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
- */
-/*
- * Copyright 2002-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
@@ -20,14 +17,16 @@
 
 package com.sun.org.apache.xerces.internal.dom;
 
+import com.sun.org.apache.xerces.internal.impl.dv.ValidatedInfo;
+import com.sun.org.apache.xerces.internal.impl.xs.ElementPSVImpl;
+import com.sun.org.apache.xerces.internal.impl.xs.util.StringListImpl;
+import com.sun.org.apache.xerces.internal.xs.*;
+import com.sun.org.apache.xerces.internal.xs.ElementPSVI;
 import java.io.IOException;
 import java.io.NotSerializableException;
 import java.io.ObjectInputStream;
 import java.io.ObjectOutputStream;
 
-import com.sun.org.apache.xerces.internal.xs.ElementPSVI;
-import com.sun.org.apache.xerces.internal.xs.*;
-
 /**
  * Element namespace implementation; stores PSVI element items.
  *
@@ -72,24 +71,12 @@
      */
     protected boolean fSpecified = true;
 
-    /** schema normalized value property */
-    protected String fNormalizedValue = null;
-
-    /** schema actual value */
-    protected Object fActualValue = null;
-
-    /** schema actual value type */
-    protected short fActualValueType = XSConstants.UNAVAILABLE_DT;
-
-    /** actual value types if the value is a list */
-    protected ShortList fItemValueTypes = null;
+    /** Schema value */
+    protected ValidatedInfo fValue = new ValidatedInfo();
 
     /** http://www.w3.org/TR/xmlschema-1/#e-notation*/
     protected XSNotationDeclaration fNotation = null;
 
-    /** member type definition against which element was validated */
-    protected XSSimpleTypeDefinition fMemberType = null;
-
     /** validation attempted: none, partial, full */
     protected short fValidationAttempted = ElementPSVI.VALIDATION_NONE;
 
@@ -99,6 +86,9 @@
     /** error codes */
     protected StringList fErrorCodes = null;
 
+    /** error messages */
+    protected StringList fErrorMessages = null;
+
     /** validation context: could be QName or XPath expression*/
     protected String fValidationContext = null;
 
@@ -109,6 +99,20 @@
     // ElementPSVI methods
     //
 
+    /* (non-Javadoc)
+     * @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#constant()
+     */
+    public ItemPSVI constant() {
+        return new ElementPSVImpl(true, this);
+    }
+
+    /* (non-Javadoc)
+     * @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#isConstant()
+     */
+    public boolean isConstant() {
+        return false;
+    }
+
     /**
      * [schema default]
      *
@@ -127,7 +131,7 @@
      * @return the normalized value of this item after validation
      */
     public String getSchemaNormalizedValue() {
-        return fNormalizedValue;
+        return fValue.getNormalizedValue();
     }
 
     /**
@@ -167,9 +171,24 @@
      * @return Array of error codes
      */
     public StringList getErrorCodes() {
-        return fErrorCodes;
+        if (fErrorCodes != null) {
+            return fErrorCodes;
+        }
+        return StringListImpl.EMPTY_LIST;
     }
 
+    /**
+     * A list of error messages generated from the validation attempt or
+     * an empty <code>StringList</code> if no errors occurred during the
+     * validation attempt. The indices of error messages in this list are
+     * aligned with those in the <code>[schema error code]</code> list.
+     */
+    public StringList getErrorMessages() {
+        if (fErrorMessages != null) {
+            return fErrorMessages;
+        }
+        return StringListImpl.EMPTY_LIST;
+    }
 
     // This is the only information we can provide in a pipeline.
     public String getValidationContext() {
@@ -213,7 +232,7 @@
      * @return  a simple type declaration
      */
     public XSSimpleTypeDefinition getMemberTypeDefinition() {
-        return fMemberType;
+        return fValue.getMemberTypeDefinition();
     }
 
     /**
@@ -239,7 +258,7 @@
     /**
      * Copy PSVI properties from another psvi item.
      *
-     * @param attr  the source of attribute PSVI items
+     * @param elem  the source of element PSVI items
      */
     public void setPSVI(ElementPSVI elem) {
         this.fDeclaration = elem.getElementDeclaration();
@@ -250,11 +269,15 @@
         this.fValidity = elem.getValidity();
         this.fValidationAttempted = elem.getValidationAttempted();
         this.fErrorCodes = elem.getErrorCodes();
-        this.fNormalizedValue = elem.getSchemaNormalizedValue();
-        this.fActualValue = elem.getActualNormalizedValue();
-        this.fActualValueType = elem.getActualNormalizedValueType();
-        this.fItemValueTypes = elem.getItemValueTypes();
-        this.fMemberType = elem.getMemberTypeDefinition();
+        this.fErrorMessages = elem.getErrorMessages();
+        if (fTypeDecl instanceof XSSimpleTypeDefinition ||
+                fTypeDecl instanceof XSComplexTypeDefinition &&
+                ((XSComplexTypeDefinition)fTypeDecl).getContentType() == XSComplexTypeDefinition.CONTENTTYPE_SIMPLE) {
+            this.fValue.copyFrom(elem.getSchemaValue());
+        }
+        else {
+            this.fValue.reset();
+        }
         this.fSpecified = elem.getIsSchemaSpecified();
         this.fNil = elem.getNil();
     }
@@ -263,21 +286,28 @@
      * @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#getActualNormalizedValue()
      */
     public Object getActualNormalizedValue() {
-        return this.fActualValue;
+        return fValue.getActualValue();
     }
 
     /* (non-Javadoc)
      * @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#getActualNormalizedValueType()
      */
     public short getActualNormalizedValueType() {
-        return this.fActualValueType;
+        return fValue.getActualValueType();
     }
 
     /* (non-Javadoc)
      * @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#getItemValueTypes()
      */
     public ShortList getItemValueTypes() {
-        return this.fItemValueTypes;
+        return fValue.getListValueTypes();
+    }
+
+    /* (non-Javadoc)
+     * @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#getSchemaValue()
+     */
+    public XSValue getSchemaValue() {
+        return fValue;
     }
 
     // REVISIT: Forbid serialization of PSVI DOM until
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/Constants.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/Constants.java	Wed Jul 05 20:04:39 2017 +0200
@@ -1,3 +1,6 @@
+/*
+ * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
+ */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
  * contributor license agreements.  See the NOTICE file distributed with
@@ -632,9 +635,12 @@
     /** Validation manager property ("internal/validation-manager"). */
     public static final String VALIDATION_MANAGER_PROPERTY = "internal/validation-manager";
 
-    /** Schema type of the root element in a document ("validation/schema/root-type-definition"). */
+    /** Schema type for the root element in a document ("validation/schema/root-type-definition"). */
     public static final String ROOT_TYPE_DEFINITION_PROPERTY = "validation/schema/root-type-definition";
 
+    /** Schema element declaration for the root element in a document ("validation/schema/root-element-declaration"). */
+    public static final String ROOT_ELEMENT_DECLARATION_PROPERTY = "validation/schema/root-element-declaration";
+
     /** XPointer Schema property ("xpointer-schema"). */
     public static final String XPOINTER_SCHEMA_PROPERTY = "xpointer-schema";
 
@@ -803,6 +809,7 @@
             BUFFER_SIZE_PROPERTY,
             SECURITY_MANAGER_PROPERTY,
             ROOT_TYPE_DEFINITION_PROPERTY,
+            ROOT_ELEMENT_DECLARATION_PROPERTY,
             LOCALE_PROPERTY,
             SCHEMA_DV_FACTORY_PROPERTY,
     };
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLDocumentFragmentScannerImpl.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLDocumentFragmentScannerImpl.java	Wed Jul 05 20:04:39 2017 +0200
@@ -611,9 +611,9 @@
         //fElementStack2.clear();
         //fReplaceEntityReferences = true;
         //fSupportExternalEntities = true;
-        Boolean bo = (Boolean)propertyManager.getProperty(XMLInputFactoryImpl.IS_REPLACING_ENTITY_REFERENCES);
+        Boolean bo = (Boolean)propertyManager.getProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES);
         fReplaceEntityReferences = bo.booleanValue();
-        bo = (Boolean)propertyManager.getProperty(XMLInputFactoryImpl.IS_SUPPORTING_EXTERNAL_ENTITIES);
+        bo = (Boolean)propertyManager.getProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES);
         fSupportExternalEntities = bo.booleanValue();
         Boolean cdata = (Boolean)propertyManager.getProperty(Constants.ZEPHYR_PROPERTY_PREFIX + Constants.STAX_REPORT_CDATA_EVENT) ;
         if(cdata != null)
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLEntityManager.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLEntityManager.java	Wed Jul 05 20:04:39 2017 +0200
@@ -1,6 +1,5 @@
 /*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -22,11 +21,11 @@
 package com.sun.org.apache.xerces.internal.impl ;
 
 import com.sun.org.apache.xerces.internal.impl.Constants;
+import com.sun.org.apache.xerces.internal.impl.XMLEntityHandler;
 import com.sun.org.apache.xerces.internal.impl.io.ASCIIReader;
 import com.sun.org.apache.xerces.internal.impl.io.UCSReader;
 import com.sun.org.apache.xerces.internal.impl.io.UTF8Reader;
 import com.sun.org.apache.xerces.internal.impl.msg.XMLMessageFormatter;
-import com.sun.org.apache.xerces.internal.impl.XMLEntityHandler;
 import com.sun.org.apache.xerces.internal.impl.validation.ValidationManager;
 import com.sun.org.apache.xerces.internal.util.*;
 import com.sun.org.apache.xerces.internal.util.URI;
@@ -54,6 +53,7 @@
 import java.util.Map;
 import java.util.Stack;
 import java.util.StringTokenizer;
+import javax.xml.stream.XMLInputFactory;
 
 
 /**
@@ -305,6 +305,11 @@
     /** Property Manager. This is used from Stax */
     protected PropertyManager fPropertyManager ;
 
+    /** StAX properties */
+    boolean fSupportDTD = true;
+    boolean fReplaceEntityReferences = true;
+    boolean fSupportExternalEntities = true;
+
     /** used to restrict external access */
     protected String fAccessExternalDTD = EXTERNAL_ACCESS_DEFAULT;
 
@@ -1136,7 +1141,8 @@
             boolean parameter = entityName.startsWith("%");
             boolean general = !parameter;
             if (unparsed || (general && !fExternalGeneralEntities) ||
-                    (parameter && !fExternalParameterEntities)) {
+                    (parameter && !fExternalParameterEntities) ||
+                    !fSupportDTD || !fSupportExternalEntities) {
 
                 if (fEntityHandler != null) {
                     fResourceIdentifier.clear();
@@ -1431,6 +1437,10 @@
             fStaxEntityResolver = null;
         }
 
+        fSupportDTD = ((Boolean)propertyManager.getProperty(XMLInputFactory.SUPPORT_DTD)).booleanValue();
+        fReplaceEntityReferences = ((Boolean)propertyManager.getProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES)).booleanValue();
+        fSupportExternalEntities = ((Boolean)propertyManager.getProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES)).booleanValue();
+
         // Zephyr feature ignore-external-dtd is the opposite of Xerces' load-external-dtd
         fLoadExternalDTD = !((Boolean)propertyManager.getProperty(Constants.ZEPHYR_PROPERTY_PREFIX + Constants.IGNORE_EXTERNAL_DTD)).booleanValue();
 
@@ -1502,6 +1512,11 @@
         fSecurityManager = (XMLSecurityManager)componentManager.getProperty(SECURITY_MANAGER, null);
         entityExpansionIndex = fSecurityManager.getIndex(Constants.JDK_ENTITY_EXPANSION_LIMIT);
 
+        //StAX Property
+        fSupportDTD = true;
+        fReplaceEntityReferences = true;
+        fSupportExternalEntities = true;
+
         // JAXP 1.5 feature
         XMLSecurityPropertyManager spm = (XMLSecurityPropertyManager) componentManager.getProperty(XML_SECURITY_PROPERTY_MANAGER, null);
         if (spm == null) {
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLErrorReporter.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLErrorReporter.java	Wed Jul 05 20:04:39 2017 +0200
@@ -3,60 +3,20 @@
  * DO NOT REMOVE OR ALTER!
  */
 /*
- * The Apache Software License, Version 1.1
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
  *
+ *      http://www.apache.org/licenses/LICENSE-2.0
  *
- * Copyright (c) 1999-2004 The Apache Software Foundation.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *
- * 3. The end-user documentation included with the redistribution,
- *    if any, must include the following acknowledgment:
- *       "This product includes software developed by the
- *        Apache Software Foundation (http://www.apache.org/)."
- *    Alternately, this acknowledgment may appear in the software itself,
- *    if and wherever such third-party acknowledgments normally appear.
- *
- * 4. The names "Xerces" and "Apache Software Foundation" must
- *    not be used to endorse or promote products derived from this
- *    software without prior written permission. For written
- *    permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache",
- *    nor may "Apache" appear in their name, without prior written
- *    permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation and was
- * originally based on software copyright (c) 1999, International
- * Business Machines, Inc., http://www.apache.org.  For more
- * information on the Apache Software Foundation, please see
- * <http://www.apache.org/>.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
  */
 
 package com.sun.org.apache.xerces.internal.impl;
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dtd/XMLDTDValidator.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dtd/XMLDTDValidator.java	Wed Jul 05 20:04:39 2017 +0200
@@ -3,11 +3,12 @@
  * DO NOT REMOVE OR ALTER!
  */
 /*
- * Copyright 1999-2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
@@ -51,6 +52,7 @@
 import com.sun.org.apache.xerces.internal.xni.parser.XMLConfigurationException;
 import com.sun.org.apache.xerces.internal.xni.parser.XMLDocumentFilter;
 import com.sun.org.apache.xerces.internal.xni.parser.XMLDocumentSource;
+import java.util.Iterator;
 
 /**
  * The DTD validator. The validator implements a document
@@ -334,7 +336,7 @@
     // temporary variables
 
     /** Temporary element declaration. */
-    private XMLElementDecl fTempElementDecl = new XMLElementDecl();
+    private final XMLElementDecl fTempElementDecl = new XMLElementDecl();
 
     /** Temporary atribute declaration. */
     private final XMLAttributeDecl fTempAttDecl = new XMLAttributeDecl();
@@ -2020,12 +2022,14 @@
             //   IDREF and IDREFS attr (V_IDREF0)
             //
             if (fPerformValidation) {
-                String value = fValidationState.checkIDRefID();
-                if (value != null) {
-                    fErrorReporter.reportError( XMLMessageFormatter.XML_DOMAIN,
-                                                "MSG_ELEMENT_WITH_ID_REQUIRED",
-                                                new Object[]{value},
-                                                XMLErrorReporter.SEVERITY_ERROR );
+                Iterator invIdRefs = fValidationState.checkIDRefID();
+                if (invIdRefs != null) {
+                    while (invIdRefs.hasNext()) {
+                        fErrorReporter.reportError( XMLMessageFormatter.XML_DOMAIN,
+                                "MSG_ELEMENT_WITH_ID_REQUIRED",
+                                new Object[]{invIdRefs.next()},
+                                XMLErrorReporter.SEVERITY_ERROR );
+                    }
                 }
             }
             return;
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dtd/models/CMNode.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dtd/models/CMNode.java	Wed Jul 05 20:04:39 2017 +0200
@@ -1,62 +1,21 @@
 /*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2006, 2009, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * The Apache Software License, Version 1.1
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
  *
+ *      http://www.apache.org/licenses/LICENSE-2.0
  *
- * Copyright (c) 1999-2002 The Apache Software Foundation.  All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *
- * 3. The end-user documentation included with the redistribution,
- *    if any, must include the following acknowledgment:
- *       "This product includes software developed by the
- *        Apache Software Foundation (http://www.apache.org/)."
- *    Alternately, this acknowledgment may appear in the software itself,
- *    if and wherever such third-party acknowledgments normally appear.
- *
- * 4. The names "Xerces" and "Apache Software Foundation" must
- *    not be used to endorse or promote products derived from this
- *    software without prior written permission. For written
- *    permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache",
- *    nor may "Apache" appear in their name, without prior written
- *    permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation and was
- * originally based on software copyright (c) 1999, International
- * Business Machines, Inc., http://www.apache.org.  For more
- * information on the Apache Software Foundation, please see
- * <http://www.apache.org/>.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
  */
 
 package com.sun.org.apache.xerces.internal.impl.dtd.models;
@@ -125,6 +84,14 @@
         fMaxStates = maxStates;
     }
 
+    public boolean isCompactedForUPA() {
+        return fCompactedForUPA;
+    }
+
+    public void setIsCompactUPAModel(boolean value) {
+        fCompactedForUPA = value;
+    }
+
     /**
      * Allows the user to set arbitrary data on this content model
      * node. This is used by the a{n,m} optimization that runs
@@ -181,10 +148,16 @@
     //      init to to -1 so it will cause an error if its used without
     //      being initialized.
     // -------------------------------------------------------------------
-    private int         fType;
-    private CMStateSet  fFirstPos   = null;
-    private CMStateSet  fFollowPos  = null;
-    private CMStateSet  fLastPos    = null;
-    private int         fMaxStates  = -1;
+    private final int  fType;
+    private CMStateSet fFirstPos   = null;
+    private CMStateSet fFollowPos  = null;
+    private CMStateSet fLastPos    = null;
+    private int        fMaxStates  = -1;
     private Object      fUserData   = null;
+    /*
+     * This boolean is true if the model represented by the CMNode does not represent
+     * the true model from the schema, but has had its min/maxOccurs modified for a
+     * more compact representation (for purposes of UPA).
+     */
+    private boolean fCompactedForUPA = false;
 };
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dv/ValidatedInfo.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dv/ValidatedInfo.java	Wed Jul 05 20:04:39 2017 +0200
@@ -1,3 +1,7 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
  * contributor license agreements.  See the NOTICE file distributed with
@@ -17,8 +21,13 @@
 
 package com.sun.org.apache.xerces.internal.impl.dv;
 
+import com.sun.org.apache.xerces.internal.impl.xs.util.ShortListImpl;
+import com.sun.org.apache.xerces.internal.impl.xs.util.XSObjectListImpl;
 import com.sun.org.apache.xerces.internal.xs.ShortList;
 import com.sun.org.apache.xerces.internal.xs.XSConstants;
+import com.sun.org.apache.xerces.internal.xs.XSObjectList;
+import com.sun.org.apache.xerces.internal.xs.XSSimpleTypeDefinition;
+import com.sun.org.apache.xerces.internal.xs.XSValue;
 
 /**
  * Class to get the information back after content is validated. This info
@@ -29,7 +38,7 @@
  * @author Neeraj Bajaj, Sun Microsystems, inc.
  *
  */
-public class ValidatedInfo {
+public class ValidatedInfo implements XSValue {
 
     /**
      * The normalized value of a string value
@@ -51,6 +60,11 @@
     public short actualValueType;
 
     /**
+     * The declared type of the value.
+     */
+    public XSSimpleType actualType;
+
+    /**
      * If the type is a union type, then the member type which
      * actually validated the string value.
      */
@@ -79,8 +93,11 @@
     public void reset() {
         this.normalizedValue = null;
         this.actualValue = null;
+        this.actualValueType = XSConstants.UNAVAILABLE_DT;
+        this.actualType = null;
         this.memberType = null;
         this.memberTypes = null;
+        this.itemValueTypes = null;
     }
 
     /**
@@ -88,10 +105,12 @@
      * value, use toString; otherwise, use the normalized value.
      */
     public String stringValue() {
-        if (actualValue == null)
+        if (actualValue == null) {
             return normalizedValue;
-        else
+        }
+        else {
             return actualValue.toString();
+        }
     }
 
     /**
@@ -149,4 +168,72 @@
         /** Other types. */
         return valueType;
     }
+
+    // XSValue methods
+
+    public Object getActualValue() {
+        return actualValue;
+    }
+
+    public short getActualValueType() {
+        return actualValueType;
+    }
+
+    public ShortList getListValueTypes() {
+        return itemValueTypes == null ? ShortListImpl.EMPTY_LIST : itemValueTypes;
+    }
+
+    public XSObjectList getMemberTypeDefinitions() {
+        if (memberTypes == null) {
+            return XSObjectListImpl.EMPTY_LIST;
+        }
+        return new XSObjectListImpl(memberTypes, memberTypes.length);
+    }
+
+    public String getNormalizedValue() {
+        return normalizedValue;
+    }
+
+    public XSSimpleTypeDefinition getTypeDefinition() {
+        return actualType;
+    }
+
+    public XSSimpleTypeDefinition getMemberTypeDefinition() {
+        return memberType;
+    }
+
+    public void copyFrom(XSValue o) {
+        if (o == null) {
+            reset();
+        }
+        else if (o instanceof ValidatedInfo) {
+            ValidatedInfo other = (ValidatedInfo)o;
+            normalizedValue = other.normalizedValue;
+            actualValue = other.actualValue;
+            actualValueType = other.actualValueType;
+            actualType = other.actualType;
+            memberType = other.memberType;
+            memberTypes = other.memberTypes;
+            itemValueTypes = other.itemValueTypes;
+        }
+        else {
+            normalizedValue = o.getNormalizedValue();
+            actualValue = o.getActualValue();
+            actualValueType = o.getActualValueType();
+            actualType = (XSSimpleType)o.getTypeDefinition();
+            memberType = (XSSimpleType)o.getMemberTypeDefinition();
+            XSSimpleType realType = memberType == null ? actualType : memberType;
+            if (realType != null && realType.getBuiltInKind() == XSConstants.LISTOFUNION_DT) {
+                XSObjectList members = o.getMemberTypeDefinitions();
+                memberTypes = new XSSimpleType[members.getLength()];
+                for (int i = 0; i < members.getLength(); i++) {
+                    memberTypes[i] = (XSSimpleType)members.get(i);
+                }
+            }
+            else {
+                memberTypes = null;
+            }
+            itemValueTypes = o.getListValueTypes();
+        }
+    }
 }
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dv/util/ByteListImpl.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dv/util/ByteListImpl.java	Wed Jul 05 20:04:39 2017 +0200
@@ -3,11 +3,12 @@
  * DO NOT REMOVE OR ALTER!
  */
 /*
- * Copyright 2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
@@ -17,6 +18,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package com.sun.org.apache.xerces.internal.impl.dv.util;
 
 import java.util.AbstractList;
@@ -102,4 +104,10 @@
     public int size() {
         return getLength();
     }
+
+    public byte[] toByteArray() {
+        byte[] ret = new byte[data.length];
+        System.arraycopy(data, 0, ret, 0, data.length);
+        return ret;
+    }
 }
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dv/xs/XSSimpleTypeDecl.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dv/xs/XSSimpleTypeDecl.java	Wed Jul 05 20:04:39 2017 +0200
@@ -3,11 +3,12 @@
  * DO NOT REMOVE OR ALTER!
  */
 /*
- * Copyright 2001-2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
@@ -20,11 +21,6 @@
 
 package com.sun.org.apache.xerces.internal.impl.dv.xs;
 
-import java.util.AbstractList;
-import java.util.Locale;
-import java.util.StringTokenizer;
-import java.util.Vector;
-
 import com.sun.org.apache.xerces.internal.impl.Constants;
 import com.sun.org.apache.xerces.internal.impl.dv.DatatypeException;
 import com.sun.org.apache.xerces.internal.impl.dv.InvalidDatatypeFacetException;
@@ -33,9 +29,10 @@
 import com.sun.org.apache.xerces.internal.impl.dv.ValidationContext;
 import com.sun.org.apache.xerces.internal.impl.dv.XSFacets;
 import com.sun.org.apache.xerces.internal.impl.dv.XSSimpleType;
+import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;
 import com.sun.org.apache.xerces.internal.impl.xpath.regex.RegularExpression;
-import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;
 import com.sun.org.apache.xerces.internal.impl.xs.SchemaSymbols;
+import com.sun.org.apache.xerces.internal.impl.xs.util.ObjectListImpl;
 import com.sun.org.apache.xerces.internal.impl.xs.util.ShortListImpl;
 import com.sun.org.apache.xerces.internal.impl.xs.util.StringListImpl;
 import com.sun.org.apache.xerces.internal.impl.xs.util.XSObjectListImpl;
@@ -48,10 +45,16 @@
 import com.sun.org.apache.xerces.internal.xs.XSFacet;
 import com.sun.org.apache.xerces.internal.xs.XSMultiValueFacet;
 import com.sun.org.apache.xerces.internal.xs.XSNamespaceItem;
+import com.sun.org.apache.xerces.internal.xs.XSObject;
 import com.sun.org.apache.xerces.internal.xs.XSObjectList;
 import com.sun.org.apache.xerces.internal.xs.XSSimpleTypeDefinition;
 import com.sun.org.apache.xerces.internal.xs.XSTypeDefinition;
 import com.sun.org.apache.xerces.internal.xs.datatypes.ObjectList;
+import java.math.BigInteger;
+import java.util.AbstractList;
+import java.util.Locale;
+import java.util.StringTokenizer;
+import java.util.Vector;
 import org.w3c.dom.TypeInfo;
 
 /**
@@ -267,9 +270,8 @@
     private int fFractionDigits = -1;
     private Vector fPattern;
     private Vector fPatternStr;
-    private Vector fEnumeration;
-    private short[] fEnumerationType;
-    private ShortList[] fEnumerationItemType;   // used in case fenumerationType value is LIST or LISTOFUNION
+    private ValidatedInfo[] fEnumeration;
+    private int fEnumerationSize;
     private ShortList fEnumerationTypeList;
     private ObjectList fEnumerationItemTypeList;
     private StringList fLexicalPattern;
@@ -387,8 +389,7 @@
         fPattern = fBase.fPattern;
         fPatternStr = fBase.fPatternStr;
         fEnumeration = fBase.fEnumeration;
-        fEnumerationType = fBase.fEnumerationType;
-        fEnumerationItemType = fBase.fEnumerationItemType;
+        fEnumerationSize = fBase.fEnumerationSize;
         fWhiteSpace = fBase.fWhiteSpace;
         fMaxExclusive = fBase.fMaxExclusive;
         fMaxInclusive = fBase.fMaxInclusive;
@@ -508,8 +509,7 @@
         fPattern = fBase.fPattern;
         fPatternStr = fBase.fPatternStr;
         fEnumeration = fBase.fEnumeration;
-        fEnumerationType = fBase.fEnumerationType;
-        fEnumerationItemType = fBase.fEnumerationItemType;
+        fEnumerationSize = fBase.fEnumerationSize;
         fWhiteSpace = fBase.fWhiteSpace;
         fMaxExclusive = fBase.fMaxExclusive;
         fMaxInclusive = fBase.fMaxInclusive;
@@ -873,22 +873,20 @@
             if ((allowedFacet & FACET_ENUMERATION) == 0) {
                 reportError("cos-applicable-facets", new Object[]{"enumeration", fTypeName});
             } else {
-                fEnumeration = new Vector();
                 Vector enumVals = facets.enumeration;
-                fEnumerationType = new short[enumVals.size()];
-                fEnumerationItemType = new ShortList[enumVals.size()];
+                int size = enumVals.size();
+                fEnumeration = new ValidatedInfo[size];
                 Vector enumNSDecls = facets.enumNSDecls;
                 ValidationContextImpl ctx = new ValidationContextImpl(context);
                 enumerationAnnotations = facets.enumAnnotations;
-                for (int i = 0; i < enumVals.size(); i++) {
+                fEnumerationSize = 0;
+                for (int i = 0; i < size; i++) {
                     if (enumNSDecls != null)
                         ctx.setNSContext((NamespaceContext)enumNSDecls.elementAt(i));
                     try {
-                        ValidatedInfo info = getActualEnumValue((String)enumVals.elementAt(i), ctx, tempInfo);
+                        ValidatedInfo info = getActualEnumValue((String)enumVals.elementAt(i), ctx, null);
                         // check 4.3.5.c0 must: enumeration values from the value space of base
-                        fEnumeration.addElement(info.actualValue);
-                        fEnumerationType[i] = info.actualValueType;
-                        fEnumerationItemType[i] = info.itemValueTypes;
+                        fEnumeration[fEnumerationSize++] = info;
                     } catch (InvalidDatatypeValueException ide) {
                         reportError("enumeration-valid-restriction", new Object[]{enumVals.elementAt(i), this.getBaseType().getName()});
                     }
@@ -1478,6 +1476,7 @@
         if ((fFacetsDefined & FACET_ENUMERATION) == 0 && (fBase.fFacetsDefined & FACET_ENUMERATION) != 0) {
             fFacetsDefined |= FACET_ENUMERATION;
             fEnumeration = fBase.fEnumeration;
+            fEnumerationSize = fBase.fEnumerationSize;
             enumerationAnnotations = fBase.enumerationAnnotations;
         }
         // inherit maxExclusive
@@ -1673,16 +1672,16 @@
         //enumeration
         if ( ((fFacetsDefined & FACET_ENUMERATION) != 0 ) ) {
             boolean present = false;
-            final int enumSize = fEnumeration.size();
+            final int enumSize = fEnumerationSize;
             final short primitiveType1 = convertToPrimitiveKind(type);
             for (int i = 0; i < enumSize; i++) {
-                final short primitiveType2 = convertToPrimitiveKind(fEnumerationType[i]);
+                final short primitiveType2 = convertToPrimitiveKind(fEnumeration[i].actualValueType);
                 if ((primitiveType1 == primitiveType2 ||
                         primitiveType1 == XSConstants.ANYSIMPLETYPE_DT && primitiveType2 == XSConstants.STRING_DT ||
                         primitiveType1 == XSConstants.STRING_DT && primitiveType2 == XSConstants.ANYSIMPLETYPE_DT)
-                        && fEnumeration.elementAt(i).equals(ob)) {
+                        && fEnumeration[i].actualValue.equals(ob)) {
                     if (primitiveType1 == XSConstants.LIST_DT || primitiveType1 == XSConstants.LISTOFUNION_DT) {
-                        ShortList enumItemType = fEnumerationItemType[i];
+                        ShortList enumItemType = fEnumeration[i].itemValueTypes;
                         final int typeList1Length = itemType != null ? itemType.getLength() : 0;
                         final int typeList2Length = enumItemType != null ? enumItemType.getLength() : 0;
                         if (typeList1Length == typeList2Length) {
@@ -1711,8 +1710,10 @@
                 }
             }
             if(!present){
+                StringBuffer sb = new StringBuffer();
+                appendEnumString(sb);
                 throw new InvalidDatatypeValueException("cvc-enumeration-valid",
-                        new Object [] {content, fEnumeration.toString()});
+                        new Object [] {content, sb.toString()});
             }
         }
 
@@ -1827,12 +1828,6 @@
             nvalue = content.toString();
         }
         if ( (fFacetsDefined & FACET_PATTERN ) != 0 ) {
-            if (fPattern.size()==0 && nvalue.length()>0) {
-                        throw new InvalidDatatypeValueException("cvc-pattern-valid",
-                                new Object[]{content,
-                                "(empty string)",
-                                fTypeName});
-            }
             RegularExpression regex;
             for (int idx = fPattern.size()-1; idx >= 0; idx--) {
                 regex = (RegularExpression)fPattern.elementAt(idx);
@@ -1840,6 +1835,7 @@
                     throw new InvalidDatatypeValueException("cvc-pattern-valid",
                             new Object[]{content,
                             fPatternStr.elementAt(idx),
+
                             fTypeName});
                 }
             }
@@ -1873,6 +1869,7 @@
             Object avalue = fDVs[fValidationDV].getActualValue(nvalue, context);
             validatedInfo.actualValue = avalue;
             validatedInfo.actualValueType = fBuiltInKind;
+            validatedInfo.actualType = this;
 
             return avalue;
 
@@ -1910,6 +1907,8 @@
             validatedInfo.memberTypes = memberTypes;
             validatedInfo.itemValueTypes = new ShortListImpl(itemTypes, itemTypes.length);
             validatedInfo.normalizedValue = nvalue;
+            // Need to set it here or it will become the item type
+            validatedInfo.actualType = this;
 
             return v;
 
@@ -1929,6 +1928,8 @@
                         fMemberTypes[i].checkFacets(validatedInfo);
                     }
                     validatedInfo.memberType = fMemberTypes[i];
+                    // Need to set it here or it will become the member type
+                    validatedInfo.actualType = this;
                     return aValue;
                 } catch(InvalidDatatypeValueException invalidValue) {
                 }
@@ -1946,14 +1947,8 @@
                 }
                 typesBuffer.append(decl.fTypeName);
                 if(decl.fEnumeration != null) {
-                    Vector v = decl.fEnumeration;
-                    typesBuffer.append(" : [");
-                    for(int j = 0;j < v.size(); j++) {
-                        if(j != 0)
-                            typesBuffer.append(',');
-                        typesBuffer.append(v.elementAt(j));
-                    }
-                    typesBuffer.append(']');
+                    typesBuffer.append(" : ");
+                    decl.appendEnumString(typesBuffer);
                 }
             }
             throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.3",
@@ -2245,10 +2240,10 @@
         if (fLexicalEnumeration == null){
             if (fEnumeration == null)
                 return StringListImpl.EMPTY_LIST;
-            int size = fEnumeration.size();
+            int size = fEnumerationSize;
             String[] strs = new String[size];
             for (int i = 0; i < size; i++)
-                strs[i] = fEnumeration.elementAt(i).toString();
+                strs[i] = fEnumeration[i].normalizedValue;
             fLexicalEnumeration = new StringListImpl(strs, size);
         }
         return fLexicalEnumeration;
@@ -2262,16 +2257,24 @@
         if (fActualEnumeration == null) {
             fActualEnumeration = new AbstractObjectList() {
                 public int getLength() {
-                    return (fEnumeration != null) ? fEnumeration.size() : 0;
+                    return (fEnumeration != null) ? fEnumerationSize : 0;
                 }
                 public boolean contains(Object item) {
-                    return (fEnumeration != null && fEnumeration.contains(item));
+                    if (fEnumeration == null) {
+                        return false;
+                    }
+                    for (int i = 0; i < fEnumerationSize; i++) {
+                        if (fEnumeration[i].getActualValue().equals(item)) {
+                            return true;
+                        }
+                    }
+                    return false;
                 }
                 public Object item(int index) {
                     if (index < 0 || index >= getLength()) {
                         return null;
                     }
-                    return fEnumeration.elementAt(index);
+                    return fEnumeration[index].getActualValue();
                 }
             };
         }
@@ -2284,17 +2287,18 @@
      */
     public ObjectList getEnumerationItemTypeList() {
         if (fEnumerationItemTypeList == null) {
-            if(fEnumerationItemType == null)
+            if (fEnumeration == null) {
                 return null;
+            }
             fEnumerationItemTypeList = new AbstractObjectList() {
                 public int getLength() {
-                    return (fEnumerationItemType != null) ? fEnumerationItemType.length : 0;
+                    return (fEnumeration != null) ? fEnumerationSize : 0;
                 }
                 public boolean contains(Object item) {
-                    if(fEnumerationItemType == null || !(item instanceof ShortList))
+                    if (fEnumeration == null || !(item instanceof ShortList))
                         return false;
-                    for(int i = 0;i < fEnumerationItemType.length; i++)
-                        if(fEnumerationItemType[i] == item)
+                    for (int i = 0;i < fEnumerationSize; i++)
+                        if (fEnumeration[i].itemValueTypes == item)
                             return true;
                     return false;
                 }
@@ -2302,7 +2306,7 @@
                     if (index < 0 || index >= getLength()) {
                         return null;
                     }
-                    return fEnumerationItemType[index];
+                    return fEnumeration[index].itemValueTypes;
                 }
             };
         }
@@ -2311,10 +2315,14 @@
 
     public ShortList getEnumerationTypeList() {
         if (fEnumerationTypeList == null) {
-            if (fEnumerationType == null) {
+            if (fEnumeration == null) {
                 return ShortListImpl.EMPTY_LIST;
             }
-            fEnumerationTypeList = new ShortListImpl (fEnumerationType, fEnumerationType.length);
+            short[] list = new short[fEnumerationSize];
+            for (int i = 0; i < fEnumerationSize; i++) {
+                list[i] = fEnumeration[i].actualValueType;
+            }
+            fEnumerationTypeList = new ShortListImpl(list, fEnumerationSize);
         }
         return fEnumerationTypeList;
     }
@@ -2978,10 +2986,11 @@
         fPattern = null;
         fPatternStr = null;
         fEnumeration = null;
-        fEnumerationType = null;
-        fEnumerationItemType = null;
         fLexicalPattern = null;
         fLexicalEnumeration = null;
+        fActualEnumeration = null;
+        fEnumerationTypeList = null;
+        fEnumerationItemTypeList = null;
         fMaxInclusive = null;
         fMaxExclusive = null;
         fMinExclusive = null;
@@ -3043,6 +3052,8 @@
                     new XSFacetImpl(
                             FACET_WHITESPACE,
                             WS_FACET_STRING[fWhiteSpace],
+                            0,
+                            null,
                             (fFixedFacet & FACET_WHITESPACE) != 0,
                             whiteSpaceAnnotation);
                 count++;
@@ -3052,6 +3063,8 @@
                     new XSFacetImpl(
                             FACET_LENGTH,
                             Integer.toString(fLength),
+                            fLength,
+                            null,
                             (fFixedFacet & FACET_LENGTH) != 0,
                             lengthAnnotation);
                 count++;
@@ -3061,6 +3074,8 @@
                     new XSFacetImpl(
                             FACET_MINLENGTH,
                             Integer.toString(fMinLength),
+                            fMinLength,
+                            null,
                             (fFixedFacet & FACET_MINLENGTH) != 0,
                             minLengthAnnotation);
                 count++;
@@ -3070,6 +3085,8 @@
                     new XSFacetImpl(
                             FACET_MAXLENGTH,
                             Integer.toString(fMaxLength),
+                            fMaxLength,
+                            null,
                             (fFixedFacet & FACET_MAXLENGTH) != 0,
                             maxLengthAnnotation);
                 count++;
@@ -3079,6 +3096,8 @@
                     new XSFacetImpl(
                             FACET_TOTALDIGITS,
                             Integer.toString(fTotalDigits),
+                            fTotalDigits,
+                            null,
                             (fFixedFacet & FACET_TOTALDIGITS) != 0,
                             totalDigitsAnnotation);
                 count++;
@@ -3088,6 +3107,8 @@
                     new XSFacetImpl(
                             FACET_FRACTIONDIGITS,
                             "0",
+                            0,
+                            null,
                             true,
                             fractionDigitsAnnotation);
                 count++;
@@ -3097,6 +3118,8 @@
                     new XSFacetImpl(
                             FACET_FRACTIONDIGITS,
                             Integer.toString(fFractionDigits),
+                            fFractionDigits,
+                            null,
                             (fFixedFacet & FACET_FRACTIONDIGITS) != 0,
                             fractionDigitsAnnotation);
                 count++;
@@ -3106,6 +3129,8 @@
                     new XSFacetImpl(
                             FACET_MAXINCLUSIVE,
                             fMaxInclusive.toString(),
+                            0,
+                            fMaxInclusive,
                             (fFixedFacet & FACET_MAXINCLUSIVE) != 0,
                             maxInclusiveAnnotation);
                 count++;
@@ -3115,6 +3140,8 @@
                     new XSFacetImpl(
                             FACET_MAXEXCLUSIVE,
                             fMaxExclusive.toString(),
+                            0,
+                            fMaxExclusive,
                             (fFixedFacet & FACET_MAXEXCLUSIVE) != 0,
                             maxExclusiveAnnotation);
                 count++;
@@ -3124,6 +3151,8 @@
                     new XSFacetImpl(
                             FACET_MINEXCLUSIVE,
                             fMinExclusive.toString(),
+                            0,
+                            fMinExclusive,
                             (fFixedFacet & FACET_MINEXCLUSIVE) != 0,
                             minExclusiveAnnotation);
                 count++;
@@ -3133,6 +3162,8 @@
                     new XSFacetImpl(
                             FACET_MININCLUSIVE,
                             fMinInclusive.toString(),
+                            0,
+                            fMinInclusive,
                             (fFixedFacet & FACET_MININCLUSIVE) != 0,
                             minInclusiveAnnotation);
                 count++;
@@ -3142,6 +3173,28 @@
         return (fFacets != null) ? fFacets : XSObjectListImpl.EMPTY_LIST;
     }
 
+    public XSObject getFacet(int facetType) {
+        if (facetType == FACET_ENUMERATION || facetType == FACET_PATTERN) {
+            XSObjectList list = getMultiValueFacets();
+            for (int i = 0; i < list.getLength(); i++) {
+                XSMultiValueFacet f = (XSMultiValueFacet)list.item(i);
+                if (f.getFacetKind() == facetType) {
+                    return f;
+                }
+            }
+        }
+        else {
+            XSObjectList list = getFacets();
+            for (int i = 0; i < list.getLength(); i++) {
+                XSFacet f = (XSFacet)list.item(i);
+                if (f.getFacetKind() == facetType) {
+                    return f;
+                }
+            }
+        }
+        return null;
+    }
+
     /**
      *  A list of enumeration and pattern constraining facets if it exists,
      * otherwise an empty <code>XSObjectList</code>.
@@ -3162,6 +3215,7 @@
                     new XSMVFacetImpl(
                             FACET_PATTERN,
                             this.getLexicalPattern(),
+                            null,
                             patternAnnotations);
                 count++;
             }
@@ -3170,6 +3224,7 @@
                     new XSMVFacetImpl(
                             FACET_ENUMERATION,
                             this.getLexicalEnumeration(),
+                            new ObjectListImpl(fEnumeration, fEnumerationSize),
                             enumerationAnnotations);
                 count++;
             }
@@ -3201,13 +3256,17 @@
 
     private static final class XSFacetImpl implements XSFacet {
         final short kind;
-        final String value;
+        final String svalue;
+        final int ivalue;
+        Object avalue;
         final boolean fixed;
         final XSObjectList annotations;
 
-        public XSFacetImpl(short kind, String value, boolean fixed, XSAnnotation annotation) {
+        public XSFacetImpl(short kind, String svalue, int ivalue, Object avalue, boolean fixed, XSAnnotation annotation) {
             this.kind = kind;
-            this.value = value;
+            this.svalue = svalue;
+            this.ivalue = ivalue;
+            this.avalue = avalue;
             this.fixed = fixed;
 
             if (annotation != null) {
@@ -3254,7 +3313,24 @@
          * @see com.sun.org.apache.xerces.internal.xs.XSFacet#getLexicalFacetValue()
          */
         public String getLexicalFacetValue() {
-            return value;
+            return svalue;
+        }
+
+        public Object getActualFacetValue() {
+            if (avalue == null) {
+                if (kind == FACET_WHITESPACE) {
+                    avalue = svalue;
+                }
+                else {
+                    // Must a facet with an integer value. Use BigInteger.
+                    avalue = BigInteger.valueOf(ivalue);
+                }
+            }
+            return avalue;
+        }
+
+        public int getIntFacetValue() {
+            return ivalue;
         }
 
         /* (non-Javadoc)
@@ -3298,11 +3374,13 @@
     private static final class XSMVFacetImpl implements XSMultiValueFacet {
         final short kind;
         final XSObjectList annotations;
-        final StringList values;
-
-        public XSMVFacetImpl(short kind, StringList values, XSObjectList annotations) {
+        final StringList svalues;
+        final ObjectList avalues;
+
+        public XSMVFacetImpl(short kind, StringList svalues, ObjectList avalues, XSObjectList annotations) {
             this.kind = kind;
-            this.values = values;
+            this.svalues = svalues;
+            this.avalues = avalues;
             this.annotations = (annotations != null) ? annotations : XSObjectListImpl.EMPTY_LIST;
         }
 
@@ -3324,7 +3402,11 @@
          * @see com.sun.org.apache.xerces.internal.xs.XSMultiValueFacet#getLexicalFacetValues()
          */
         public StringList getLexicalFacetValues() {
-            return values;
+            return svalues;
+        }
+
+        public ObjectList getEnumerationValues() {
+            return avalues;
         }
 
         /* (non-Javadoc)
@@ -3394,4 +3476,14 @@
         return valueType;
     }
 
+    private void appendEnumString(StringBuffer sb) {
+        sb.append('[');
+        for (int i = 0; i < fEnumerationSize; i++) {
+            if (i != 0) {
+                sb.append(", ");
+            }
+            sb.append(fEnumeration[i].actualValue);
+        }
+        sb.append(']');
+    }
 } // class XSSimpleTypeDecl
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dv/xs/XSSimpleTypeDelegate.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/dv/xs/XSSimpleTypeDelegate.java	Wed Jul 05 20:04:39 2017 +0200
@@ -30,6 +30,7 @@
 import com.sun.org.apache.xerces.internal.impl.dv.XSSimpleType;
 import com.sun.org.apache.xerces.internal.xs.StringList;
 import com.sun.org.apache.xerces.internal.xs.XSNamespaceItem;
+import com.sun.org.apache.xerces.internal.xs.XSObject;
 import com.sun.org.apache.xerces.internal.xs.XSObjectList;
 import com.sun.org.apache.xerces.internal.xs.XSSimpleTypeDefinition;
 import com.sun.org.apache.xerces.internal.xs.XSTypeDefinition;
@@ -76,6 +77,10 @@
         return type.getFacets();
     }
 
+    public XSObject getFacet(int facetType) {
+        return type.getFacet(facetType);
+    }
+
     public boolean getFinite() {
         return type.getFinite();
     }
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/msg/XMLSchemaMessages.properties	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/msg/XMLSchemaMessages.properties	Wed Jul 05 20:04:39 2017 +0200
@@ -41,7 +41,13 @@
         cvc-complex-type.2.4.b = cvc-complex-type.2.4.b: The content of element ''{0}'' is not complete. One of ''{1}'' is expected.
         cvc-complex-type.2.4.c = cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element ''{0}''.
         cvc-complex-type.2.4.d = cvc-complex-type.2.4.d: Invalid content was found starting with element ''{0}''. No child element is expected at this point.
-        cvc-complex-type.2.4.e = cvc-complex-type.2.4.d: Invalid content was found starting with element ''{0}''. No child element ''{1}'' is expected at this point.
+        cvc-complex-type.2.4.d.1 = cvc-complex-type.2.4.d: Invalid content was found starting with element ''{0}''. No child element ''{1}'' is expected at this point.
+        cvc-complex-type.2.4.e = cvc-complex-type.2.4.e: ''{0}'' can occur a maximum of ''{2}'' times in the current sequence. This limit was exceeded. At this point one of ''{1}'' is expected.
+        cvc-complex-type.2.4.f = cvc-complex-type.2.4.f: ''{0}'' can occur a maximum of ''{1}'' times in the current sequence. This limit was exceeded. No child element is expected at this point.
+        cvc-complex-type.2.4.g = cvc-complex-type.2.4.g: Invalid content was found starting with element ''{0}''. ''{1}'' is expected to occur a minimum of ''{2}'' times in the current sequence. One more instance is required to satisfy this constraint.
+        cvc-complex-type.2.4.h = cvc-complex-type.2.4.h: Invalid content was found starting with element ''{0}''. ''{1}'' is expected to occur a minimum of ''{2}'' times in the current sequence. ''{3}'' more instances are required to satisfy this constraint.
+        cvc-complex-type.2.4.i = cvc-complex-type.2.4.i: The content of element ''{0}'' is not complete. ''{1}'' is expected to occur a minimum of ''{2}'' times. One more instance is required to satisfy this constraint.
+        cvc-complex-type.2.4.j = cvc-complex-type.2.4.j: The content of element ''{0}'' is not complete. ''{1}'' is expected to occur a minimum of ''{2}'' times. ''{3}'' more instances are required to satisfy this constraint.
         cvc-complex-type.3.1 = cvc-complex-type.3.1: Value ''{2}'' of attribute ''{1}'' of element ''{0}'' is not valid with respect to the corresponding attribute use. Attribute ''{1}'' has a fixed value of ''{3}''.
         cvc-complex-type.3.2.1 = cvc-complex-type.3.2.1: Element ''{0}'' does not have an attribute wildcard for attribute ''{1}''.
         cvc-complex-type.3.2.2 = cvc-complex-type.3.2.2: Attribute ''{1}'' is not allowed to appear in element ''{0}''.
@@ -51,7 +57,8 @@
         cvc-datatype-valid.1.2.1 = cvc-datatype-valid.1.2.1: ''{0}'' is not a valid value for ''{1}''.
         cvc-datatype-valid.1.2.2 = cvc-datatype-valid.1.2.2: ''{0}'' is not a valid value of list type ''{1}''.
         cvc-datatype-valid.1.2.3 = cvc-datatype-valid.1.2.3: ''{0}'' is not a valid value of union type ''{1}''.
-        cvc-elt.1 = cvc-elt.1: Cannot find the declaration of element ''{0}''.
+        cvc-elt.1.a = cvc-elt.1.a: Cannot find the declaration of element ''{0}''.
+        cvc-elt.1.b = cvc-elt.1.b: The name of the element does not match the name of the element declaration. Saw ''{0}''. Expected ''{1}''.
         cvc-elt.2 = cvc-elt.2: The value of '{'abstract'}' in the element declaration for ''{0}'' must be false.
         cvc-elt.3.1 = cvc-elt.3.1: Attribute ''{1}'' must not appear on element ''{0}'', because the '{'nillable'}' property of ''{0}'' is false.
         cvc-elt.3.2.1 = cvc-elt.3.2.1: Element ''{0}'' cannot have character or element information [children], because ''{1}'' is specified.
@@ -289,3 +296,10 @@
         TargetNamespace.2 = TargetNamespace.2: Expecting no namespace, but the schema document has a target namespace of ''{1}''.
         UndeclaredEntity = UndeclaredEntity: Entity ''{0}'' is not declared.
         UndeclaredPrefix = UndeclaredPrefix: Cannot resolve ''{0}'' as a QName: the prefix ''{1}'' is not declared.
+
+
+# JAXP 1.2 schema source property errors
+
+        jaxp12-schema-source-type.1 = The ''http://java.sun.com/xml/jaxp/properties/schemaSource'' property cannot have a value of type ''{0}''. Possible types of the value supported are String, File, InputStream, InputSource or an array of these types.
+        jaxp12-schema-source-type.2 = The ''http://java.sun.com/xml/jaxp/properties/schemaSource'' property cannot have an array value of type ''{0}''. Possible types of the array supported are Object, String, File, InputStream and InputSource.
+        jaxp12-schema-source-ns = When using an array of Objects as the value of the 'http://java.sun.com/xml/jaxp/properties/schemaSource' property, it is illegal to have two schemas that share the same target namespace.
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/validation/ConfigurableValidationState.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/validation/ConfigurableValidationState.java	Wed Jul 05 20:04:39 2017 +0200
@@ -1,9 +1,14 @@
 /*
- * Copyright 2006 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
@@ -16,6 +21,8 @@
 
 package com.sun.org.apache.xerces.internal.impl.validation;
 
+import java.util.Iterator;
+
 /**
  * <p>An extension of ValidationState which can be configured to turn
  * off checking for ID/IDREF errors and unparsed entity errors.</p>
@@ -49,7 +56,7 @@
 
     /**
      * Turns checking for ID/IDREF errors on and off.
-     * @param setting: true to turn on error checking
+     * @param setting true to turn on error checking,
      *                 false to turn off error checking
      */
     public void setIdIdrefChecking(boolean setting) {
@@ -58,7 +65,7 @@
 
     /**
      * Turns checking for unparsed entity errors on and off.
-     * @param setting: true to turn on error checking
+     * @param setting true to turn on error checking,
      *                 false to turn off error checking
      */
     public void setUnparsedEntityChecking(boolean setting) {
@@ -70,7 +77,7 @@
      * @return null, if ID/IDREF checking is turned off
      *         otherwise, returns the value of the super implementation
      */
-    public String checkIDRefID() {
+    public Iterator checkIDRefID() {
         return (fIdIdrefChecking) ? super.checkIDRefID() : null;
     }
 
@@ -103,7 +110,7 @@
 
     /**
      * Adds the ID, if ID/IDREF checking is enabled.
-     * @param the ID to add
+     * @param name the ID to add
      */
     public void addId(String name) {
         if (fIdIdrefChecking) {
@@ -113,7 +120,7 @@
 
     /**
      * Adds the IDREF, if ID/IDREF checking is enabled.
-     * @param the IDREF to add
+     * @param name the IDREF to add
      */
     public void addIdRef(String name) {
         if (fIdIdrefChecking) {
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/validation/ValidationState.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/validation/ValidationState.java	Wed Jul 05 20:04:39 2017 +0200
@@ -3,11 +3,12 @@
  * DO NOT REMOVE OR ALTER!
  */
 /*
- * Copyright 2001, 2002,2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
@@ -20,11 +21,12 @@
 
 package com.sun.org.apache.xerces.internal.impl.validation;
 
+import com.sun.org.apache.xerces.internal.impl.dv.ValidationContext;
 import com.sun.org.apache.xerces.internal.util.SymbolTable;
-import com.sun.org.apache.xerces.internal.impl.dv.ValidationContext;
-
 import com.sun.org.apache.xerces.internal.xni.NamespaceContext;
 import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Iterator;
 import java.util.Locale;
 
 /**
@@ -86,25 +88,24 @@
 
     /**
      * return null if all IDREF values have a corresponding ID value;
-     * otherwise return the first IDREF value without a matching ID value.
+     * otherwise return an iterator for all the IDREF values without
+     * a matching ID value.
      */
-    public String checkIDRefID () {
-        if (fIdList == null) {
-            if (fIdRefList != null) {
-                return fIdRefList.get(0);
-            }
-        }
-
+    public Iterator checkIDRefID () {
+        HashSet missingIDs = null;
         if (fIdRefList != null) {
             String key;
             for (int i = 0; i < fIdRefList.size(); i++) {
                 key = fIdRefList.get(i);
-                if (!fIdList.contains(key)) {
-                      return key;
+                if (fIdList == null || !fIdList.contains(key)) {
+                    if (missingIDs == null) {
+                        missingIDs = new HashSet();
+                    }
+                    missingIDs.add(key);
                 }
             }
         }
-        return null;
+        return (missingIDs != null) ? missingIDs.iterator() : null;
     }
 
     public void reset () {
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/AttributePSVImpl.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/AttributePSVImpl.java	Wed Jul 05 20:04:39 2017 +0200
@@ -3,11 +3,12 @@
  * DO NOT REMOVE OR ALTER!
  */
 /*
- * Copyright 2000-2002,2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
@@ -20,14 +21,17 @@
 
 package com.sun.org.apache.xerces.internal.impl.xs;
 
+import com.sun.org.apache.xerces.internal.impl.dv.ValidatedInfo;
+import com.sun.org.apache.xerces.internal.impl.xs.util.StringListImpl;
+import com.sun.org.apache.xerces.internal.xs.AttributePSVI;
+import com.sun.org.apache.xerces.internal.xs.ItemPSVI;
 import com.sun.org.apache.xerces.internal.xs.ShortList;
 import com.sun.org.apache.xerces.internal.xs.StringList;
 import com.sun.org.apache.xerces.internal.xs.XSAttributeDeclaration;
+import com.sun.org.apache.xerces.internal.xs.XSConstants;
 import com.sun.org.apache.xerces.internal.xs.XSSimpleTypeDefinition;
 import com.sun.org.apache.xerces.internal.xs.XSTypeDefinition;
-import com.sun.org.apache.xerces.internal.impl.xs.util.StringListImpl;
-import com.sun.org.apache.xerces.internal.xs.AttributePSVI;
-import com.sun.org.apache.xerces.internal.xs.XSConstants;
+import com.sun.org.apache.xerces.internal.xs.XSValue;
 
 /**
  * Attribute PSV infoset augmentations implementation.
@@ -49,20 +53,8 @@
      * value in the original document, this is false; otherwise, it is true */
     protected boolean fSpecified = false;
 
-    /** schema normalized value property */
-    protected String fNormalizedValue = null;
-
-    /** schema actual value */
-    protected Object fActualValue = null;
-
-    /** schema actual value type */
-    protected short fActualValueType = XSConstants.UNAVAILABLE_DT;
-
-    /** actual value types if the value is a list */
-    protected ShortList fItemValueTypes = null;
-
-    /** member type definition against which attribute was validated */
-    protected XSSimpleTypeDefinition fMemberType = null;
+    /** Schema value */
+    protected ValidatedInfo fValue = new ValidatedInfo();
 
     /** validation attempted: none, partial, full */
     protected short fValidationAttempted = AttributePSVI.VALIDATION_NONE;
@@ -70,16 +62,67 @@
     /** validity: valid, invalid, unknown */
     protected short fValidity = AttributePSVI.VALIDITY_NOTKNOWN;
 
-    /** error codes */
-    protected String[] fErrorCodes = null;
+    /** error codes and error messages */
+    protected String[] fErrors = null;
 
     /** validation context: could be QName or XPath expression*/
     protected String fValidationContext = null;
 
+    /** true if this object is immutable **/
+    protected boolean fIsConstant;
+
+    public AttributePSVImpl() {}
+
+    public AttributePSVImpl(boolean isConstant, AttributePSVI attrPSVI) {
+        fDeclaration = attrPSVI.getAttributeDeclaration();
+        fTypeDecl = attrPSVI.getTypeDefinition();
+        fSpecified = attrPSVI.getIsSchemaSpecified();
+        fValue.copyFrom(attrPSVI.getSchemaValue());
+        fValidationAttempted = attrPSVI.getValidationAttempted();
+        fValidity = attrPSVI.getValidity();
+        if (attrPSVI instanceof AttributePSVImpl) {
+            final AttributePSVImpl attrPSVIImpl = (AttributePSVImpl) attrPSVI;
+            fErrors = (attrPSVIImpl.fErrors != null) ?
+                    (String[]) attrPSVIImpl.fErrors.clone() : null;
+        }
+        else {
+            final StringList errorCodes = attrPSVI.getErrorCodes();
+            final int length = errorCodes.getLength();
+            if (length > 0) {
+                final StringList errorMessages = attrPSVI.getErrorMessages();
+                final String[] errors = new String[length << 1];
+                for (int i = 0, j = 0; i < length; ++i) {
+                    errors[j++] = errorCodes.item(i);
+                    errors[j++] = errorMessages.item(i);
+                }
+                fErrors = errors;
+            }
+        }
+        fValidationContext = attrPSVI.getValidationContext();
+        fIsConstant = isConstant;
+    }
+
     //
     // AttributePSVI methods
     //
 
+    /* (non-Javadoc)
+     * @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#constant()
+     */
+    public ItemPSVI constant() {
+        if (isConstant()) {
+            return this;
+        }
+        return new AttributePSVImpl(true, this);
+    }
+
+    /* (non-Javadoc)
+     * @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#isConstant()
+     */
+    public boolean isConstant() {
+        return fIsConstant;
+    }
+
     /**
      * [schema default]
      *
@@ -98,7 +141,7 @@
      * @return the normalized value of this item after validation
      */
     public String getSchemaNormalizedValue() {
-        return fNormalizedValue;
+        return fValue.getNormalizedValue();
     }
 
     /**
@@ -139,9 +182,23 @@
      * @return list of error codes
      */
     public StringList getErrorCodes() {
-        if (fErrorCodes == null)
-            return null;
-        return new StringListImpl(fErrorCodes, fErrorCodes.length);
+        if (fErrors == null || fErrors.length == 0) {
+            return StringListImpl.EMPTY_LIST;
+        }
+        return new PSVIErrorList(fErrors, true);
+    }
+
+    /**
+     * A list of error messages generated from the validation attempt or
+     * an empty <code>StringList</code> if no errors occurred during the
+     * validation attempt. The indices of error messages in this list are
+     * aligned with those in the <code>[schema error code]</code> list.
+     */
+    public StringList getErrorMessages() {
+        if (fErrors == null || fErrors.length == 0) {
+            return StringListImpl.EMPTY_LIST;
+        }
+        return new PSVIErrorList(fErrors, false);
     }
 
     // This is the only information we can provide in a pipeline.
@@ -168,7 +225,7 @@
      * @return  a simple type declaration
      */
     public XSSimpleTypeDefinition getMemberTypeDefinition() {
-        return fMemberType;
+        return fValue.getMemberTypeDefinition();
     }
 
     /**
@@ -185,38 +242,41 @@
      * @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#getActualNormalizedValue()
      */
     public Object getActualNormalizedValue() {
-        return this.fActualValue;
+        return fValue.getActualValue();
     }
 
     /* (non-Javadoc)
      * @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#getActualNormalizedValueType()
      */
     public short getActualNormalizedValueType() {
-        return this.fActualValueType;
+        return fValue.getActualValueType();
     }
 
     /* (non-Javadoc)
      * @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#getItemValueTypes()
      */
     public ShortList getItemValueTypes() {
-        return this.fItemValueTypes;
+        return fValue.getListValueTypes();
+    }
+
+    /* (non-Javadoc)
+     * @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#getSchemaValue()
+     */
+    public XSValue getSchemaValue() {
+        return fValue;
     }
 
     /**
      * Reset()
      */
     public void reset() {
-        fNormalizedValue = null;
-        fActualValue = null;
-        fActualValueType = XSConstants.UNAVAILABLE_DT;
-        fItemValueTypes = null;
+        fValue.reset();
         fDeclaration = null;
         fTypeDecl = null;
         fSpecified = false;
-        fMemberType = null;
         fValidationAttempted = AttributePSVI.VALIDATION_NONE;
         fValidity = AttributePSVI.VALIDITY_NOTKNOWN;
-        fErrorCodes = null;
+        fErrors = null;
         fValidationContext = null;
     }
 }
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/ElementPSVImpl.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/ElementPSVImpl.java	Wed Jul 05 20:04:39 2017 +0200
@@ -3,11 +3,12 @@
  * DO NOT REMOVE OR ALTER!
  */
 /*
- * Copyright 2000-2002,2004,2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
@@ -20,16 +21,19 @@
 
 package com.sun.org.apache.xerces.internal.impl.xs;
 
+import com.sun.org.apache.xerces.internal.impl.dv.ValidatedInfo;
+import com.sun.org.apache.xerces.internal.impl.xs.util.StringListImpl;
+import com.sun.org.apache.xerces.internal.xs.ElementPSVI;
+import com.sun.org.apache.xerces.internal.xs.ItemPSVI;
 import com.sun.org.apache.xerces.internal.xs.ShortList;
 import com.sun.org.apache.xerces.internal.xs.StringList;
+import com.sun.org.apache.xerces.internal.xs.XSConstants;
 import com.sun.org.apache.xerces.internal.xs.XSElementDeclaration;
 import com.sun.org.apache.xerces.internal.xs.XSModel;
 import com.sun.org.apache.xerces.internal.xs.XSNotationDeclaration;
 import com.sun.org.apache.xerces.internal.xs.XSSimpleTypeDefinition;
 import com.sun.org.apache.xerces.internal.xs.XSTypeDefinition;
-import com.sun.org.apache.xerces.internal.impl.xs.util.StringListImpl;
-import com.sun.org.apache.xerces.internal.xs.ElementPSVI;
-import com.sun.org.apache.xerces.internal.xs.XSConstants;
+import com.sun.org.apache.xerces.internal.xs.XSValue;
 
 /**
  * Element PSV infoset augmentations implementation.
@@ -61,32 +65,20 @@
      */
     protected boolean fSpecified = false;
 
-    /** schema normalized value property */
-    protected String fNormalizedValue = null;
-
-    /** schema actual value */
-    protected Object fActualValue = null;
-
-    /** schema actual value type */
-    protected short fActualValueType = XSConstants.UNAVAILABLE_DT;
-
-    /** actual value types if the value is a list */
-    protected ShortList fItemValueTypes = null;
+    /** Schema value */
+    protected ValidatedInfo fValue = new ValidatedInfo();
 
     /** http://www.w3.org/TR/xmlschema-1/#e-notation*/
     protected XSNotationDeclaration fNotation = null;
 
-    /** member type definition against which element was validated */
-    protected XSSimpleTypeDefinition fMemberType = null;
-
     /** validation attempted: none, partial, full */
     protected short fValidationAttempted = ElementPSVI.VALIDATION_NONE;
 
     /** validity: valid, invalid, unknown */
     protected short fValidity = ElementPSVI.VALIDITY_NOTKNOWN;
 
-    /** error codes */
-    protected String[] fErrorCodes = null;
+    /** error codes and error messages */
+    protected String[] fErrors = null;
 
     /** validation context: could be QName or XPath expression*/
     protected String fValidationContext = null;
@@ -97,10 +89,65 @@
     /** the schema information property */
     protected XSModel fSchemaInformation = null;
 
+    /** true if this object is immutable **/
+    protected boolean fIsConstant;
+
+    public ElementPSVImpl() {}
+
+    public ElementPSVImpl(boolean isConstant, ElementPSVI elementPSVI) {
+        fDeclaration = elementPSVI.getElementDeclaration();
+        fTypeDecl = elementPSVI.getTypeDefinition();
+        fNil = elementPSVI.getNil();
+        fSpecified = elementPSVI.getIsSchemaSpecified();
+        fValue.copyFrom(elementPSVI.getSchemaValue());
+        fNotation = elementPSVI.getNotation();
+        fValidationAttempted = elementPSVI.getValidationAttempted();
+        fValidity = elementPSVI.getValidity();
+        fValidationContext = elementPSVI.getValidationContext();
+        if (elementPSVI instanceof ElementPSVImpl) {
+            final ElementPSVImpl elementPSVIImpl = (ElementPSVImpl) elementPSVI;
+            fErrors = (elementPSVIImpl.fErrors != null) ?
+                    (String[]) elementPSVIImpl.fErrors.clone() : null;
+            elementPSVIImpl.copySchemaInformationTo(this);
+        }
+        else {
+            final StringList errorCodes = elementPSVI.getErrorCodes();
+            final int length = errorCodes.getLength();
+            if (length > 0) {
+                final StringList errorMessages = elementPSVI.getErrorMessages();
+                final String[] errors = new String[length << 1];
+                for (int i = 0, j = 0; i < length; ++i) {
+                    errors[j++] = errorCodes.item(i);
+                    errors[j++] = errorMessages.item(i);
+                }
+                fErrors = errors;
+            }
+            fSchemaInformation = elementPSVI.getSchemaInformation();
+        }
+        fIsConstant = isConstant;
+    }
+
     //
     // ElementPSVI methods
     //
 
+    /* (non-Javadoc)
+     * @see org.apache.xerces.xs.ItemPSVI#constant()
+     */
+    public ItemPSVI constant() {
+        if (isConstant()) {
+            return this;
+        }
+        return new ElementPSVImpl(true, this);
+    }
+
+    /* (non-Javadoc)
+     * @see org.apache.xerces.xs.ItemPSVI#isConstant()
+     */
+    public boolean isConstant() {
+        return fIsConstant;
+    }
+
     /**
      * [schema default]
      *
@@ -119,7 +166,7 @@
      * @return the normalized value of this item after validation
      */
     public String getSchemaNormalizedValue() {
-        return fNormalizedValue;
+        return fValue.getNormalizedValue();
     }
 
     /**
@@ -159,11 +206,24 @@
      * @return Array of error codes
      */
     public StringList getErrorCodes() {
-        if (fErrorCodes == null)
-            return null;
-        return new StringListImpl(fErrorCodes, fErrorCodes.length);
+        if (fErrors == null || fErrors.length == 0) {
+            return StringListImpl.EMPTY_LIST;
+        }
+        return new PSVIErrorList(fErrors, true);
     }
 
+    /**
+     * A list of error messages generated from the validation attempt or
+     * an empty <code>StringList</code> if no errors occurred during the
+     * validation attempt. The indices of error messages in this list are
+     * aligned with those in the <code>[schema error code]</code> list.
+     */
+    public StringList getErrorMessages() {
+        if (fErrors == null || fErrors.length == 0) {
+            return StringListImpl.EMPTY_LIST;
+        }
+        return new PSVIErrorList(fErrors, false);
+    }
 
     // This is the only information we can provide in a pipeline.
     public String getValidationContext() {
@@ -207,7 +267,7 @@
      * @return  a simple type declaration
      */
     public XSSimpleTypeDefinition getMemberTypeDefinition() {
-        return fMemberType;
+        return fValue.getMemberTypeDefinition();
     }
 
     /**
@@ -237,21 +297,28 @@
      * @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#getActualNormalizedValue()
      */
     public Object getActualNormalizedValue() {
-        return this.fActualValue;
+        return fValue.getActualValue();
     }
 
     /* (non-Javadoc)
      * @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#getActualNormalizedValueType()
      */
     public short getActualNormalizedValueType() {
-        return this.fActualValueType;
+        return fValue.getActualValueType();
     }
 
     /* (non-Javadoc)
      * @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#getItemValueTypes()
      */
     public ShortList getItemValueTypes() {
-        return this.fItemValueTypes;
+        return fValue.getListValueTypes();
+    }
+
+    /* (non-Javadoc)
+     * @see com.sun.org.apache.xerces.internal.xs.ItemPSVI#getSchemaValue()
+     */
+    public XSValue getSchemaValue() {
+        return fValue;
     }
 
     /**
@@ -263,15 +330,15 @@
         fNil = false;
         fSpecified = false;
         fNotation = null;
-        fMemberType = null;
         fValidationAttempted = ElementPSVI.VALIDATION_NONE;
         fValidity = ElementPSVI.VALIDITY_NOTKNOWN;
-        fErrorCodes = null;
+        fErrors = null;
         fValidationContext = null;
-        fNormalizedValue = null;
-        fActualValue = null;
-        fActualValueType = XSConstants.UNAVAILABLE_DT;
-        fItemValueTypes = null;
+        fValue.reset();
     }
 
+    public void copySchemaInformationTo(ElementPSVImpl target) {
+        target.fGrammars = fGrammars;
+        target.fSchemaInformation = fSchemaInformation;
+    }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/PSVIErrorList.java	Wed Jul 05 20:04:39 2017 +0200
@@ -0,0 +1,92 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.sun.org.apache.xerces.internal.impl.xs;
+
+import java.util.AbstractList;
+
+import com.sun.org.apache.xerces.internal.xs.StringList;
+
+/**
+ * StringList implementation for schema error codes and error messages.
+ *
+ * @xerces.internal
+ *
+ * @author Michael Glavassevich, IBM
+ *
+ */
+final class PSVIErrorList extends AbstractList implements StringList {
+
+    private final String[] fArray;
+    private final int fLength;
+    private final int fOffset;
+
+    public PSVIErrorList(String[] array, boolean even) {
+        fArray = array;
+        fLength = (fArray.length >> 1);
+        fOffset = even ? 0 : 1;
+    }
+
+    public boolean contains(String item) {
+        if (item == null) {
+            for (int i = 0; i < fLength; ++i) {
+                if (fArray[(i << 1) + fOffset] == null) {
+                    return true;
+                }
+            }
+        }
+        else {
+            for (int i = 0; i < fLength; ++i) {
+                if (item.equals(fArray[(i << 1) + fOffset])) {
+                    return true;
+                }
+            }
+        }
+        return false;
+    }
+
+    public int getLength() {
+        return fLength;
+    }
+
+    public String item(int index) {
+        if (index < 0 || index >= fLength) {
+            return null;
+        }
+        return fArray[(index << 1) + fOffset];
+    }
+
+    /*
+     * List methods
+     */
+
+    public Object get(int index) {
+        if (index >= 0 && index < fLength) {
+            return fArray[(index << 1) + fOffset];
+        }
+        throw new IndexOutOfBoundsException("Index: " + index);
+    }
+
+    public int size() {
+        return getLength();
+    }
+
+} // class PSVIErrorList
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/SchemaGrammar.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/SchemaGrammar.java	Wed Jul 05 20:04:39 2017 +0200
@@ -3,11 +3,12 @@
  * DO NOT REMOVE OR ALTER!
  */
 /*
- * Copyright 2001-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
@@ -20,9 +21,6 @@
 
 package com.sun.org.apache.xerces.internal.impl.xs;
 
-import java.lang.ref.SoftReference;
-import java.util.Vector;
-
 import com.sun.org.apache.xerces.internal.impl.Constants;
 import com.sun.org.apache.xerces.internal.impl.dv.SchemaDVFactory;
 import com.sun.org.apache.xerces.internal.impl.dv.ValidatedInfo;
@@ -49,6 +47,7 @@
 import com.sun.org.apache.xerces.internal.xs.XSAttributeGroupDefinition;
 import com.sun.org.apache.xerces.internal.xs.XSConstants;
 import com.sun.org.apache.xerces.internal.xs.XSElementDeclaration;
+import com.sun.org.apache.xerces.internal.xs.XSIDCDefinition;
 import com.sun.org.apache.xerces.internal.xs.XSModel;
 import com.sun.org.apache.xerces.internal.xs.XSModelGroupDefinition;
 import com.sun.org.apache.xerces.internal.xs.XSNamedMap;
@@ -59,6 +58,8 @@
 import com.sun.org.apache.xerces.internal.xs.XSTypeDefinition;
 import com.sun.org.apache.xerces.internal.xs.XSWildcard;
 import com.sun.org.apache.xerces.internal.xs.datatypes.ObjectList;
+import java.lang.ref.SoftReference;
+import java.util.Vector;
 import org.xml.sax.SAXException;
 
 /**
@@ -135,7 +136,7 @@
      * Default constructor.
      *
      * @param targetNamespace
-     * @param grammarDesc the XMLGrammarDescription corresponding to this objec
+     * @param grammarDesc the XMLGrammarDescription corresponding to this object
      *          at the least a systemId should always be known.
      * @param symbolTable   needed for annotation support
      */
@@ -145,35 +146,39 @@
         fGrammarDescription = grammarDesc;
         fSymbolTable = symbolTable;
 
-        // REVISIT: do we know the numbers of the following global decls
-        // when creating this grammar? If so, we can pass the numbers in,
-        // and use that number to initialize the following hashtables.
-        fGlobalAttrDecls  = new SymbolHash();
-        fGlobalAttrGrpDecls = new SymbolHash();
-        fGlobalElemDecls = new SymbolHash();
-        fGlobalGroupDecls = new SymbolHash();
-        fGlobalNotationDecls = new SymbolHash();
-        fGlobalIDConstraintDecls = new SymbolHash();
+        // REVISIT: the initial sizes being chosen for each SymbolHash
+        // may not be ideal and could still be tuned. They were chosen
+        // somewhat arbitrarily to reduce the initial footprint of
+        // SymbolHash buckets from 1,515 to 177 (about 12% of the
+        // default size).
+        fGlobalAttrDecls  = new SymbolHash(12);
+        fGlobalAttrGrpDecls = new SymbolHash(5);
+        fGlobalElemDecls = new SymbolHash(25);
+        fGlobalGroupDecls = new SymbolHash(5);
+        fGlobalNotationDecls = new SymbolHash(1);
+        fGlobalIDConstraintDecls = new SymbolHash(3);
 
         // Extended tables
-        fGlobalAttrDeclsExt  = new SymbolHash();
-        fGlobalAttrGrpDeclsExt = new SymbolHash();
-        fGlobalElemDeclsExt = new SymbolHash();
-        fGlobalGroupDeclsExt = new SymbolHash();
-        fGlobalNotationDeclsExt = new SymbolHash();
-        fGlobalIDConstraintDeclsExt = new SymbolHash();
-        fGlobalTypeDeclsExt = new SymbolHash();
+        fGlobalAttrDeclsExt  = new SymbolHash(12);
+        fGlobalAttrGrpDeclsExt = new SymbolHash(5);
+        fGlobalElemDeclsExt = new SymbolHash(25);
+        fGlobalGroupDeclsExt = new SymbolHash(5);
+        fGlobalNotationDeclsExt = new SymbolHash(1);
+        fGlobalIDConstraintDeclsExt = new SymbolHash(3);
+        fGlobalTypeDeclsExt = new SymbolHash(25);
 
         // All global elements table
-        fAllGlobalElemDecls = new SymbolHash();
+        fAllGlobalElemDecls = new SymbolHash(25);
 
         // if we are parsing S4S, put built-in types in first
         // they might get overwritten by the types from S4S, but that's
         // considered what the application wants to do.
-        if (fTargetNamespace == SchemaSymbols.URI_SCHEMAFORSCHEMA)
+        if (fTargetNamespace == SchemaSymbols.URI_SCHEMAFORSCHEMA) {
             fGlobalTypeDecls = SG_SchemaNS.fGlobalTypeDecls.makeClone();
-        else
-            fGlobalTypeDecls = new SymbolHash();
+        }
+        else {
+            fGlobalTypeDecls = new SymbolHash(25);
+        }
     } // <init>(String, XSDDescription)
 
     // Clone an existing schema grammar
@@ -232,7 +237,7 @@
             fRedefinedGroupDecls = new XSGroupDecl[grammar.fRedefinedGroupDecls.length];
             fRGLocators = new SimpleLocator[grammar.fRGLocators.length];
             System.arraycopy(grammar.fRedefinedGroupDecls, 0, fRedefinedGroupDecls, 0, fRGCount);
-            System.arraycopy(grammar.fRGLocators, 0, fRGLocators, 0, fRGCount);
+            System.arraycopy(grammar.fRGLocators, 0, fRGLocators, 0, fRGCount/2);
         }
 
         // List of imported grammars
@@ -626,19 +631,19 @@
             // fill complex types
             annotationType.setValues("#AnonType_" + SchemaSymbols.ELT_ANNOTATION, fTargetNamespace, SchemaGrammar.fAnyType,
                     XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
-                    XSComplexTypeDecl.CONTENTTYPE_ELEMENT, false, annotationAttrs, null, annotationParticle, new XSObjectListImpl(null, 0));
+                    XSComplexTypeDecl.CONTENTTYPE_ELEMENT, false, annotationAttrs, null, annotationParticle, XSObjectListImpl.EMPTY_LIST);
             annotationType.setName("#AnonType_" + SchemaSymbols.ELT_ANNOTATION);
             annotationType.setIsAnonymous();
 
             documentationType.setValues("#AnonType_" + SchemaSymbols.ELT_DOCUMENTATION, fTargetNamespace, SchemaGrammar.fAnyType,
                     XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
-                    XSComplexTypeDecl.CONTENTTYPE_MIXED, false, documentationAttrs, null, anyWCSequenceParticle, new XSObjectListImpl(null, 0));
+                    XSComplexTypeDecl.CONTENTTYPE_MIXED, false, documentationAttrs, null, anyWCSequenceParticle, XSObjectListImpl.EMPTY_LIST);
             documentationType.setName("#AnonType_" + SchemaSymbols.ELT_DOCUMENTATION);
             documentationType.setIsAnonymous();
 
             appinfoType.setValues("#AnonType_" + SchemaSymbols.ELT_APPINFO, fTargetNamespace, SchemaGrammar.fAnyType,
                     XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
-                    XSComplexTypeDecl.CONTENTTYPE_MIXED, false, appinfoAttrs, null, anyWCSequenceParticle, new XSObjectListImpl(null, 0));
+                    XSComplexTypeDecl.CONTENTTYPE_MIXED, false, appinfoAttrs, null, anyWCSequenceParticle, XSObjectListImpl.EMPTY_LIST);
             appinfoType.setName("#AnonType_" + SchemaSymbols.ELT_APPINFO);
             appinfoType.setIsAnonymous();
 
@@ -1178,8 +1183,8 @@
             fDerivedBy = XSConstants.DERIVATION_RESTRICTION;
             fContentType = XSComplexTypeDecl.CONTENTTYPE_MIXED;
 
-            fParticle = null;
-            fAttrGrp = null;
+            fParticle = createParticle();
+            fAttrGrp = createAttrGrp();
         }
 
         // overridden methods
@@ -1211,11 +1216,15 @@
             // null implementation
         }
 
-        public XSObjectList getAttributeUses() {
+        public XSObjectList getAnnotations() {
             return XSObjectListImpl.EMPTY_LIST;
         }
 
-        public XSAttributeGroupDecl getAttrGrp() {
+        public XSNamespaceItem getNamespaceItem() {
+            return SG_SchemaNS;
+        }
+
+        private XSAttributeGroupDecl createAttrGrp() {
             XSWildcardDecl wildcard = new XSWildcardDecl();
             wildcard.fProcessContents = XSWildcardDecl.PC_LAX;
             XSAttributeGroupDecl attrGrp = new XSAttributeGroupDecl();
@@ -1223,13 +1232,7 @@
             return attrGrp;
         }
 
-        public XSWildcard getAttributeWildcard() {
-            XSWildcardDecl wildcard = new XSWildcardDecl();
-            wildcard.fProcessContents = XSWildcardDecl.PC_LAX;
-            return wildcard;
-        }
-
-        public XSParticle getParticle() {
+        private XSParticleDecl createParticle() {
             // the wildcard used in anyType (content and attribute)
             // the spec will change strict to skip for anyType
             XSWildcardDecl wildcard = new XSWildcardDecl();
@@ -1253,14 +1256,6 @@
 
             return particleG;
         }
-
-        public XSObjectList getAnnotations() {
-            return XSObjectListImpl.EMPTY_LIST;
-        }
-
-        public XSNamespaceItem getNamespaceItem() {
-            return SG_SchemaNS;
-        }
     }
     private static class BuiltinAttrDecl extends XSAttributeDecl {
         public BuiltinAttrDecl(String name, String tns,
@@ -1347,7 +1342,7 @@
                                                   false,    // model group
                                                   false,    // particle
                                                   false,    // wildcard
-                                                  false,    // idc
+                                                  true,    // idc
                                                   true,     // notation
                                                   false,    // annotation
                                                   false,    // facet
@@ -1484,6 +1479,9 @@
             case XSConstants.NOTATION_DECLARATION:
                 table = fGlobalNotationDecls;
                 break;
+            case XSConstants.IDENTITY_CONSTRAINT:
+                table = this.fGlobalIDConstraintDecls;
+                break;
             }
 
             // for complex/simple types, create a special implementation,
@@ -1533,6 +1531,9 @@
             case XSConstants.NOTATION_DECLARATION:
                 table = fGlobalNotationDeclsExt;
                 break;
+            case XSConstants.IDENTITY_CONSTRAINT:
+                table = this.fGlobalIDConstraintDeclsExt;
+                break;
             }
 
             Object[] entries = table.getEntries();
@@ -1610,6 +1611,10 @@
         return getGlobalNotationDecl(name);
     }
 
+    public XSIDCDefinition getIDCDefinition(String name) {
+        return getIDConstraintDecl(name);
+    }
+
 
     /**
      * [document location]
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/SubstitutionGroupHandler.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/SubstitutionGroupHandler.java	Wed Jul 05 20:04:39 2017 +0200
@@ -3,11 +3,12 @@
  * DO NOT REMOVE OR ALTER!
  */
 /*
- * Copyright 2001-2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
@@ -40,14 +41,14 @@
 
     private static final XSElementDecl[] EMPTY_GROUP = new XSElementDecl[0];
 
-    // grammar resolver
-    XSGrammarBucket fGrammarBucket;
+    // global element declaration resolver
+    private final XSElementDeclHelper fXSElementDeclHelper;
 
     /**
      * Default constructor
      */
-    public SubstitutionGroupHandler(XSGrammarBucket grammarBucket) {
-        fGrammarBucket = grammarBucket;
+    public SubstitutionGroupHandler(XSElementDeclHelper elementDeclHelper) {
+        fXSElementDeclHelper = elementDeclHelper;
     }
 
     // 3.9.4 Element Sequence Locally Valid (Particle) 2.3.3
@@ -60,26 +61,25 @@
 
         // if the exemplar is not a global element decl, then it's not possible
         // to be substituted by another element.
-        if (exemplar.fScope != XSConstants.SCOPE_GLOBAL)
+        if (exemplar.fScope != XSConstants.SCOPE_GLOBAL) {
             return null;
+        }
 
         // if the decl blocks substitution, return false
-        if ((exemplar.fBlock & XSConstants.DERIVATION_SUBSTITUTION) != 0)
+        if ((exemplar.fBlock & XSConstants.DERIVATION_SUBSTITUTION) != 0) {
             return null;
-
-        // get grammar of the element
-        SchemaGrammar sGrammar = fGrammarBucket.getGrammar(element.uri);
-        if (sGrammar == null)
-            return null;
+        }
 
         // get the decl for the element
-        XSElementDecl eDecl = sGrammar.getGlobalElementDecl(element.localpart);
-        if (eDecl == null)
+        XSElementDecl eDecl = fXSElementDeclHelper.getGlobalElementDecl(element);
+        if (eDecl == null) {
             return null;
+        }
 
         // and check by using substitutionGroup information
-        if (substitutionGroupOK(eDecl, exemplar, exemplar.fBlock))
+        if (substitutionGroupOK(eDecl, exemplar, exemplar.fBlock)) {
             return eDecl;
+        }
 
         return null;
     }
@@ -89,13 +89,15 @@
     protected boolean substitutionGroupOK(XSElementDecl element, XSElementDecl exemplar, short blockingConstraint) {
         // For an element declaration (call it D) to be validly substitutable for another element declaration (call it C) subject to a blocking constraint (a subset of {substitution, extension, restriction}, the value of a {disallowed substitutions}) one of the following must be true:
         // 1. D and C are the same element declaration.
-        if (element == exemplar)
+        if (element == exemplar) {
             return true;
+        }
 
         // 2 All of the following must be true:
         // 2.1 The blocking constraint does not contain substitution.
-        if ((blockingConstraint & XSConstants.DERIVATION_SUBSTITUTION) != 0)
+        if ((blockingConstraint & XSConstants.DERIVATION_SUBSTITUTION) != 0) {
             return false;
+        }
 
         // 2.2 There is a chain of {substitution group affiliation}s from D to C, that is, either D's {substitution group affiliation} is C, or D's {substitution group affiliation}'s {substitution group affiliation} is C, or . . .
         XSElementDecl subGroup = element.fSubGroup;
@@ -103,14 +105,16 @@
             subGroup = subGroup.fSubGroup;
         }
 
-        if (subGroup == null)
+        if (subGroup == null) {
             return false;
+        }
 
         // 2.3 The set of all {derivation method}s involved in the derivation of D's {type definition} from C's {type definition} does not intersect with the union of the blocking constraint, C's {prohibited substitutions} (if C is complex, otherwise the empty set) and the {prohibited substitutions} (respectively the empty set) of any intermediate {type definition}s in the derivation of D's {type definition} from C's {type definition}.
         // prepare the combination of {derivation method} and
         // {disallowed substitution}
         return typeDerivationOK(element.fType, exemplar.fType, blockingConstraint);
     }
+
     private boolean typeDerivationOK(XSTypeDefinition derived, XSTypeDefinition base, short blockingConstraint) {
 
         short devMethod = 0, blockConstraint = blockingConstraint;
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaLoader.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaLoader.java	Wed Jul 05 20:04:39 2017 +0200
@@ -1,13 +1,13 @@
 /*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * Copyright 2000-2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
@@ -20,26 +20,12 @@
 
 package com.sun.org.apache.xerces.internal.impl.xs;
 
-import java.io.BufferedInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.Reader;
-import java.io.StringReader;
-import java.util.Hashtable;
-import java.util.Locale;
-import java.util.StringTokenizer;
-import java.util.Vector;
-
 import com.sun.org.apache.xerces.internal.dom.DOMErrorImpl;
 import com.sun.org.apache.xerces.internal.dom.DOMMessageFormatter;
 import com.sun.org.apache.xerces.internal.dom.DOMStringListImpl;
 import com.sun.org.apache.xerces.internal.impl.Constants;
 import com.sun.org.apache.xerces.internal.impl.XMLEntityManager;
 import com.sun.org.apache.xerces.internal.impl.XMLErrorReporter;
-import com.sun.org.apache.xerces.internal.impl.dv.DVFactoryException;
 import com.sun.org.apache.xerces.internal.impl.dv.InvalidDatatypeValueException;
 import com.sun.org.apache.xerces.internal.impl.dv.SchemaDVFactory;
 import com.sun.org.apache.xerces.internal.impl.dv.xs.SchemaDVFactoryImpl;
@@ -49,13 +35,16 @@
 import com.sun.org.apache.xerces.internal.util.DOMEntityResolverWrapper;
 import com.sun.org.apache.xerces.internal.util.DOMErrorHandlerWrapper;
 import com.sun.org.apache.xerces.internal.util.DefaultErrorHandler;
+import com.sun.org.apache.xerces.internal.util.MessageFormatter;
 import com.sun.org.apache.xerces.internal.util.ParserConfigurationSettings;
 import com.sun.org.apache.xerces.internal.util.Status;
 import com.sun.org.apache.xerces.internal.util.SymbolTable;
+import com.sun.org.apache.xerces.internal.util.URI.MalformedURIException;
 import com.sun.org.apache.xerces.internal.util.XMLSymbols;
 import com.sun.org.apache.xerces.internal.utils.SecuritySupport;
 import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager;
 import com.sun.org.apache.xerces.internal.utils.XMLSecurityPropertyManager;
+import com.sun.org.apache.xerces.internal.xni.QName;
 import com.sun.org.apache.xerces.internal.xni.XNIException;
 import com.sun.org.apache.xerces.internal.xni.grammars.Grammar;
 import com.sun.org.apache.xerces.internal.xni.grammars.XMLGrammarDescription;
@@ -72,14 +61,26 @@
 import com.sun.org.apache.xerces.internal.xs.StringList;
 import com.sun.org.apache.xerces.internal.xs.XSLoader;
 import com.sun.org.apache.xerces.internal.xs.XSModel;
+import java.io.BufferedInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.Reader;
+import java.io.StringReader;
+import java.util.ArrayList;
 import java.util.HashMap;
+import java.util.Locale;
 import java.util.Map;
+import java.util.StringTokenizer;
+import java.util.WeakHashMap;
 import javax.xml.XMLConstants;
 import org.w3c.dom.DOMConfiguration;
 import org.w3c.dom.DOMError;
 import org.w3c.dom.DOMErrorHandler;
+import org.w3c.dom.DOMException;
 import org.w3c.dom.DOMStringList;
-import org.w3c.dom.DOMException;
 import org.w3c.dom.ls.LSInput;
 import org.w3c.dom.ls.LSResourceResolver;
 import org.xml.sax.InputSource;
@@ -101,7 +102,7 @@
  * @author Neil Graham, IBM
  */
 
-public class XMLSchemaLoader implements XMLGrammarLoader, XMLComponent,
+public class XMLSchemaLoader implements XMLGrammarLoader, XMLComponent, XSElementDeclHelper,
 // XML Component API
 XSLoader, DOMConfiguration {
 
@@ -249,8 +250,7 @@
     // Data
 
     // features and properties
-    private ParserConfigurationSettings fLoaderConfig = new ParserConfigurationSettings();
-    private SymbolTable fSymbolTable = null;
+    private final ParserConfigurationSettings fLoaderConfig = new ParserConfigurationSettings();
     private XMLErrorReporter fErrorReporter = new XMLErrorReporter ();
     private XMLEntityManager fEntityManager = null;
     private XMLEntityResolver fUserEntityResolver = null;
@@ -276,7 +276,7 @@
     private XSDDescription fXSDDescription = new XSDDescription();
     private String faccessExternalSchema = Constants.EXTERNAL_ACCESS_DEFAULT;
 
-    private Map fJAXPCache;
+    private WeakHashMap fJAXPCache;
     private Locale fLocale = Locale.getDefault();
 
     // XSLoader attributes
@@ -350,8 +350,8 @@
             grammarBucket = new XSGrammarBucket();
         }
         fGrammarBucket = grammarBucket;
-        if(sHandler == null) {
-            sHandler = new SubstitutionGroupHandler(fGrammarBucket);
+        if (sHandler == null) {
+            sHandler = new SubstitutionGroupHandler(this);
         }
         fSubGroupHandler = sHandler;
 
@@ -360,10 +360,7 @@
         }
         fCMBuilder = builder;
         fSchemaHandler = new XSDHandler(fGrammarBucket);
-        if (fDeclPool != null) {
-            fDeclPool.reset();
-        }
-        fJAXPCache = new HashMap();
+        fJAXPCache = new WeakHashMap();
 
         fSettingsChanged = true;
     }
@@ -527,8 +524,8 @@
      * Returns a Grammar object by parsing the contents of the
      * entities pointed to by sources.
      *
-     * @param source[]  the locations of the entity which forms
-     *                      the staring point of the grammars to be constructed
+     * @param source the locations of the entity which forms
+     * the staring point of the grammars to be constructed
      * @throws IOException  when a problem is encounted reading the entity
      * @throws XNIException when a condition arises (such as a FatalError) that requires parsing
      *                          of the entity be terminated
@@ -618,7 +615,8 @@
         return grammar;
     } // loadSchema(XSDDescription, XMLInputSource):  SchemaGrammar
 
-    /** This method tries to resolve location of the given schema.
+    /**
+     * This method tries to resolve location of the given schema.
      * The loader stores the namespace/location pairs in a hashtable (use "" as the
      * namespace of absent namespace). When resolving an entity, loader first tries
      * to find in the hashtable whether there is a value for that namespace,
@@ -627,7 +625,7 @@
      * @param desc
      * @param locationPairs
      * @param entityResolver
-     * @return
+     * @return the XMLInputSource
      * @throws IOException
      */
     public static XMLInputSource resolveDocument(XSDDescription desc, Map locationPairs,
@@ -671,7 +669,7 @@
                 XSAttributeDecl attrDecl = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_SCHEMALOCATION);
                 // validation the string value to get the list of URI's
                 attrDecl.fType.validate(sl, null, null);
-                if (!tokenizeSchemaLocationStr(sl, locations)) {
+                if (!tokenizeSchemaLocationStr(sl, locations, null)) {
                     // report warning (odd number of items)
                     er.reportError(XSMessageFormatter.SCHEMA_DOMAIN,
                             "SchemaLocation",
@@ -714,7 +712,7 @@
     // @param schemaStr     The schemaLocation string to tokenize
     // @param locations     HashMap mapping namespaces to LocationArray objects holding lists of locaitons
     // @return true if no problems; false if string could not be tokenized
-    public static boolean tokenizeSchemaLocationStr(String schemaStr, Map locations) {
+    public static boolean tokenizeSchemaLocationStr(String schemaStr, Map locations, String base) {
         if (schemaStr!= null) {
             StringTokenizer t = new StringTokenizer(schemaStr, " \n\t\r");
             String namespace, location;
@@ -729,6 +727,12 @@
                     la = new LocationArray();
                     locations.put(namespace, la);
                 }
+                if (base != null) {
+                    try {
+                        location = XMLEntityManager.expandSystemId(location, base, false);
+                    } catch (MalformedURIException e) {
+                    }
+                }
                 la.addLocation(location);
             }
         }
@@ -756,10 +760,10 @@
         String sid = null;
         if (componentType == null) {
             // Not an array
-            if(fJAXPSource instanceof InputStream ||
+            if (fJAXPSource instanceof InputStream ||
                     fJAXPSource instanceof InputSource) {
                 SchemaGrammar g = (SchemaGrammar)fJAXPCache.get(fJAXPSource);
-                if(g != null) {
+                if (g != null) {
                     fGrammarBucket.putGrammar(g);
                     return;
                 }
@@ -776,38 +780,40 @@
             }
             SchemaGrammar g = loadSchema(fXSDDescription, xis, locationPairs);
             // it is possible that we won't be able to resolve JAXP schema-source location
-            if (g != null){
-                if(fJAXPSource instanceof InputStream ||
+            if (g != null) {
+                if (fJAXPSource instanceof InputStream ||
                         fJAXPSource instanceof InputSource) {
                     fJAXPCache.put(fJAXPSource, g);
-                    if(fIsCheckedFully) {
+                    if (fIsCheckedFully) {
                         XSConstraints.fullSchemaChecking(fGrammarBucket, fSubGroupHandler, fCMBuilder, fErrorReporter);
                     }
                 }
                 fGrammarBucket.putGrammar(g);
             }
-            return ;
-        } else if ( (componentType != Object.class) &&
+            return;
+        }
+        else if ( (componentType != Object.class) &&
                 (componentType != String.class) &&
-                (componentType != File.class) &&
-                (componentType != InputStream.class) &&
-                (componentType != InputSource.class)
+                !File.class.isAssignableFrom(componentType) &&
+                !InputStream.class.isAssignableFrom(componentType) &&
+                !InputSource.class.isAssignableFrom(componentType) &&
+                !componentType.isInterface()
         ) {
             // Not an Object[], String[], File[], InputStream[], InputSource[]
+            MessageFormatter mf = fErrorReporter.getMessageFormatter(XSMessageFormatter.SCHEMA_DOMAIN);
             throw new XMLConfigurationException(
-                    Status.NOT_SUPPORTED, "\""+JAXP_SCHEMA_SOURCE+
-                    "\" property cannot have an array of type {"+componentType.getName()+
-                    "}. Possible types of the array supported are Object, String, File, "+
-            "InputStream, InputSource.");
+                    Status.NOT_SUPPORTED,
+                    mf.formatMessage(fErrorReporter.getLocale(), "jaxp12-schema-source-type.2",
+                    new Object [] {componentType.getName()}));
         }
 
         // JAXP spec. allow []s of type String, File, InputStream,
         // InputSource also, apart from [] of type Object.
         Object[] objArr = (Object[]) fJAXPSource;
-        //make local vector for storing targetn namespaces of schemasources specified in object arrays.
-        Vector jaxpSchemaSourceNamespaces = new Vector() ;
+        // make local array for storing target namespaces of schemasources specified in object arrays.
+        ArrayList jaxpSchemaSourceNamespaces = new ArrayList();
         for (int i = 0; i < objArr.length; i++) {
-            if(objArr[i] instanceof InputStream ||
+            if (objArr[i] instanceof InputStream ||
                     objArr[i] instanceof InputSource) {
                 SchemaGrammar g = (SchemaGrammar)fJAXPCache.get(objArr[i]);
                 if (g != null) {
@@ -829,18 +835,18 @@
             // load schema
             SchemaGrammar grammar = fSchemaHandler.parseSchema(xis,fXSDDescription, locationPairs);
 
-            if(fIsCheckedFully) {
+            if (fIsCheckedFully) {
                 XSConstraints.fullSchemaChecking(fGrammarBucket, fSubGroupHandler, fCMBuilder, fErrorReporter);
             }
-            if(grammar != null){
-                targetNamespace = grammar.getTargetNamespace() ;
-                if(jaxpSchemaSourceNamespaces.contains(targetNamespace)){
-                    //when an array of objects is passed it is illegal to have two schemas that share same namespace.
-                    throw new java.lang.IllegalArgumentException(
-                            " When using array of Objects as the value of SCHEMA_SOURCE property , " +
-                    "no two Schemas should share the same targetNamespace. " );
+            if (grammar != null) {
+                targetNamespace = grammar.getTargetNamespace();
+                if (jaxpSchemaSourceNamespaces.contains(targetNamespace)) {
+                    // when an array of objects is passed it is illegal to have two schemas that share same namespace.
+                    MessageFormatter mf = fErrorReporter.getMessageFormatter(XSMessageFormatter.SCHEMA_DOMAIN);
+                    throw new java.lang.IllegalArgumentException(mf.formatMessage(fErrorReporter.getLocale(),
+                            "jaxp12-schema-source-ns", null));
                 }
-                else{
+                else {
                     jaxpSchemaSourceNamespaces.add(targetNamespace) ;
                 }
                 if(objArr[i] instanceof InputStream ||
@@ -849,15 +855,13 @@
                 }
                 fGrammarBucket.putGrammar(grammar);
             }
-            else{
+            else {
                 //REVISIT: What should be the acutal behavior if grammar can't be loaded as specified in schema source?
             }
         }
     }//processJAXPSchemaSource
 
-    private XMLInputSource xsdToXMLInputSource(
-            Object val)
-    {
+    private XMLInputSource xsdToXMLInputSource(Object val) {
         if (val instanceof String) {
             // String value is treated as a URI that is passed through the
             // EntityResolver
@@ -867,7 +871,8 @@
             XMLInputSource xis = null;
             try {
                 xis = fEntityManager.resolveEntity(fXSDDescription);
-            } catch (IOException ex) {
+            }
+            catch (IOException ex) {
                 fErrorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN,
                         "schema_reference.4",
                         new Object[] { loc }, XMLErrorReporter.SEVERITY_ERROR);
@@ -878,12 +883,15 @@
                 return new XMLInputSource(null, loc, null);
             }
             return xis;
-        } else if (val instanceof InputSource) {
+        }
+        else if (val instanceof InputSource) {
             return saxToXMLInputSource((InputSource) val);
-        } else if (val instanceof InputStream) {
+        }
+        else if (val instanceof InputStream) {
             return new XMLInputSource(null, null, null,
                     (InputStream) val, null);
-        } else if (val instanceof File) {
+        }
+        else if (val instanceof File) {
             File file = (File) val;
             InputStream is = null;
             try {
@@ -893,13 +901,13 @@
                         "schema_reference.4", new Object[] { file.toString() },
                         XMLErrorReporter.SEVERITY_ERROR);
             }
-            return new XMLInputSource(null, null, null, is, null);
+            return new XMLInputSource(null, file.toURI().toString(), null, is, null);
         }
+        MessageFormatter mf = fErrorReporter.getMessageFormatter(XSMessageFormatter.SCHEMA_DOMAIN);
         throw new XMLConfigurationException(
-                Status.NOT_SUPPORTED, "\""+JAXP_SCHEMA_SOURCE+
-                "\" property cannot have a value of type {"+val.getClass().getName()+
-                "}. Possible types of the value supported are String, File, InputStream, "+
-        "InputSource OR an array of these types.");
+                Status.NOT_SUPPORTED,
+                mf.formatMessage(fErrorReporter.getLocale(), "jaxp12-schema-source-type.1",
+                new Object [] {val != null ? val.getClass().getName() : "null"}));
     }
 
 
@@ -999,13 +1007,22 @@
 
         fSubGroupHandler.reset();
 
-        boolean parser_settings = componentManager.getFeature(PARSER_SETTINGS, true);
+        boolean parser_settings = true;
+        // If the component manager is the loader config don't bother querying it since it doesn't
+        // recognize the PARSER_SETTINGS feature. Prevents an XMLConfigurationException from being
+        // thrown.
+        if (componentManager != fLoaderConfig) {
+            parser_settings = componentManager.getFeature(PARSER_SETTINGS, true);
+        }
 
         if (!parser_settings || !fSettingsChanged){
             // need to reprocess JAXP schema sources
             fJAXPProcessed = false;
             // reinitialize grammar bucket
             initGrammarBucket();
+            if (fDeclPool != null) {
+                fDeclPool.reset();
+            }
             return;
         }
 
@@ -1028,26 +1045,6 @@
             fSchemaHandler.setDVFactory(dvFactory);
         }
 
-        boolean psvi = componentManager.getFeature(AUGMENT_PSVI, false);
-
-        if (!psvi) {
-            if (fDeclPool != null) {
-                fDeclPool.reset();
-            }
-            else {
-                fDeclPool = new XSDeclarationPool();
-            }
-            fCMBuilder.setDeclPool(fDeclPool);
-            fSchemaHandler.setDeclPool(fDeclPool);
-            if (dvFactory instanceof SchemaDVFactoryImpl) {
-                fDeclPool.setDVFactory((SchemaDVFactoryImpl)dvFactory);
-                ((SchemaDVFactoryImpl)dvFactory).setDeclPool(fDeclPool);
-            }
-        } else {
-            fCMBuilder.setDeclPool(null);
-            fSchemaHandler.setDeclPool(null);
-        }
-
         // get schema location properties
         try {
             fExternalSchemas = (String) componentManager.getProperty(SCHEMA_LOCATION);
@@ -1064,6 +1061,36 @@
         // clear grammars, and put the one for schema namespace there
         fGrammarPool = (XMLGrammarPool) componentManager.getProperty(XMLGRAMMAR_POOL, null);
         initGrammarBucket();
+
+        boolean psvi = componentManager.getFeature(AUGMENT_PSVI, false);
+
+        // Only use the decl pool when there is no chance that the schema
+        // components will be exposed or cached.
+        // TODO: when someone calls loadGrammar(XMLInputSource), the schema is
+        // always exposed even without the use of a grammar pool.
+        // Disabling the "decl pool" feature for now until we understand when
+        // it can be safely used.
+        if (!psvi && fGrammarPool == null && false) {
+            if (fDeclPool != null) {
+                fDeclPool.reset();
+            }
+            else {
+                fDeclPool = new XSDeclarationPool();
+            }
+            fCMBuilder.setDeclPool(fDeclPool);
+            fSchemaHandler.setDeclPool(fDeclPool);
+            if (dvFactory instanceof SchemaDVFactoryImpl) {
+                fDeclPool.setDVFactory((SchemaDVFactoryImpl)dvFactory);
+                ((SchemaDVFactoryImpl)dvFactory).setDeclPool(fDeclPool);
+            }
+        } else {
+            fCMBuilder.setDeclPool(null);
+            fSchemaHandler.setDeclPool(null);
+            if (dvFactory instanceof SchemaDVFactoryImpl) {
+                ((SchemaDVFactoryImpl)dvFactory).setDeclPool(null);
+            }
+        }
+
         // get continue-after-fatal-error feature
         try {
             boolean fatalError = componentManager.getFeature(CONTINUE_AFTER_FATAL_ERROR, false);
@@ -1083,7 +1110,8 @@
     private void initGrammarBucket(){
         if(fGrammarPool != null) {
             Grammar [] initialGrammars = fGrammarPool.retrieveInitialGrammarSet(XMLGrammarDescription.XML_SCHEMA);
-            for (int i = 0; i < initialGrammars.length; i++) {
+            final int length = (initialGrammars != null) ? initialGrammars.length : 0;
+            for (int i = 0; i < length; ++i) {
                 // put this grammar into the bucket, along with grammars
                 // imported by it (directly or indirectly)
                 if (!fGrammarBucket.putGrammar((SchemaGrammar)(initialGrammars[i]), true)) {
@@ -1119,7 +1147,7 @@
     }
 
     /* (non-Javadoc)
-     * @see com.sun.org.apache.xerces.internal.xs.XSLoader#loadInputList(com.sun.org.apache.xerces.internal.xs.DOMInputList)
+     * @see com.sun.org.apache.xerces.internal.xs.XSLoader#loadInputList(com.sun.org.apache.xerces.internal.xs.LSInputList)
      */
     public XSModel loadInputList(LSInputList is) {
         int length = is.getLength();
@@ -1250,7 +1278,7 @@
      */
     public DOMStringList getParameterNames() {
         if (fRecognizedParameters == null){
-            Vector v = new Vector();
+            ArrayList v = new ArrayList();
             v.add(Constants.DOM_VALIDATE);
             v.add(Constants.DOM_ERROR_HANDLER);
             v.add(Constants.DOM_RESOURCE_RESOLVER);
@@ -1391,4 +1419,13 @@
         return xis;
     }
 
+    // Implements XSElementDeclHelper interface
+    public XSElementDecl getGlobalElementDecl(QName element) {
+        SchemaGrammar sGrammar = fGrammarBucket.getGrammar(element.uri);
+        if (sGrammar != null) {
+            return sGrammar.getGlobalElementDecl(element.localpart);
+        }
+        return null;
+    }
+
 } // XMLGrammarLoader
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaValidator.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaValidator.java	Wed Jul 05 20:04:39 2017 +0200
@@ -1,3 +1,6 @@
+/*
+ * Copyright (c) 2006, 2014, Oracle and/or its affiliates. All rights reserved.
+ */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
  * contributor license agreements.  See the NOTICE file distributed with
@@ -25,7 +28,6 @@
 import java.util.Map;
 import java.util.Stack;
 import java.util.Vector;
-import java.util.ArrayList;
 import javax.xml.XMLConstants;
 import com.sun.org.apache.xerces.internal.impl.Constants;
 import com.sun.org.apache.xerces.internal.impl.RevalidationHandler;
@@ -35,6 +37,7 @@
 import com.sun.org.apache.xerces.internal.impl.dv.InvalidDatatypeValueException;
 import com.sun.org.apache.xerces.internal.impl.dv.ValidatedInfo;
 import com.sun.org.apache.xerces.internal.impl.dv.XSSimpleType;
+import com.sun.org.apache.xerces.internal.impl.dv.xs.XSSimpleTypeDecl;
 import com.sun.org.apache.xerces.internal.impl.validation.ConfigurableValidationState;
 import com.sun.org.apache.xerces.internal.impl.validation.ValidationManager;
 import com.sun.org.apache.xerces.internal.impl.validation.ValidationState;
@@ -49,6 +52,7 @@
 import com.sun.org.apache.xerces.internal.impl.xs.models.CMBuilder;
 import com.sun.org.apache.xerces.internal.impl.xs.models.CMNodeFactory;
 import com.sun.org.apache.xerces.internal.impl.xs.models.XSCMValidator;
+import com.sun.org.apache.xerces.internal.impl.xs.util.XS10TypeHelper;
 import com.sun.org.apache.xerces.internal.util.AugmentationsImpl;
 import com.sun.org.apache.xerces.internal.util.IntStack;
 import com.sun.org.apache.xerces.internal.util.SymbolTable;
@@ -107,7 +111,7 @@
  * @author Neeraj Bajaj, Sun Microsystems, inc.
  */
 public class XMLSchemaValidator
-    implements XMLComponent, XMLDocumentFilter, FieldActivator, RevalidationHandler {
+    implements XMLComponent, XMLDocumentFilter, FieldActivator, RevalidationHandler, XSElementDeclHelper {
 
     //
     // Constants
@@ -246,6 +250,10 @@
     protected static final String ROOT_TYPE_DEF =
         Constants.XERCES_PROPERTY_PREFIX + Constants.ROOT_TYPE_DEFINITION_PROPERTY;
 
+    /** Property identifier: root element declaration. */
+    protected static final String ROOT_ELEMENT_DECL =
+        Constants.XERCES_PROPERTY_PREFIX + Constants.ROOT_ELEMENT_DECLARATION_PROPERTY;
+
     /** Property identifier: Schema DV Factory */
     protected static final String SCHEMA_DV_FACTORY =
         Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_DV_FACTORY_PROPERTY;
@@ -279,7 +287,7 @@
             NAMESPACE_GROWTH,
             TOLERATE_DUPLICATES,
             USE_SERVICE_MECHANISM
-    };
+        };
 
     /** Feature defaults. */
     private static final Boolean[] FEATURE_DEFAULTS = { null,
@@ -324,19 +332,26 @@
             JAXP_SCHEMA_SOURCE,
             JAXP_SCHEMA_LANGUAGE,
             ROOT_TYPE_DEF,
+            ROOT_ELEMENT_DECL,
             SCHEMA_DV_FACTORY,
             XML_SECURITY_PROPERTY_MANAGER
-            };
+        };
 
     /** Property defaults. */
     private static final Object[] PROPERTY_DEFAULTS =
-        { null, null, null, null, null, null, null, null, null, null, null};
+        { null, null, null, null, null, null, null, null, null, null, null, null};
 
     // this is the number of valuestores of each kind
     // we expect an element to have.  It's almost
     // never > 1; so leave it at that.
     protected static final int ID_CONSTRAINT_NUM = 1;
 
+    // xsi:* attribute declarations
+    static final XSAttributeDecl XSI_TYPE = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_TYPE);
+    static final XSAttributeDecl XSI_NIL = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_NIL);
+    static final XSAttributeDecl XSI_SCHEMALOCATION = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_SCHEMALOCATION);
+    static final XSAttributeDecl XSI_NONAMESPACESCHEMALOCATION = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION);
+
     //
     private static final Hashtable EMPTY_TABLE = new Hashtable();
 
@@ -354,12 +369,6 @@
     // clear this before we introduce it into the pipeline.
     protected final AugmentationsImpl fAugmentations = new AugmentationsImpl();
 
-    /**
-     * Map which is used to catch instance documents that try
-     * and match a field several times in the same scope.
-     */
-    protected final HashMap fMayMatchFieldMap = new HashMap();
-
     // this is included for the convenience of handleEndElement
     protected XMLString fDefaultValue;
 
@@ -485,9 +494,10 @@
 
         public void reportError(String domain, String key, Object[] arguments, short severity)
             throws XNIException {
-            fErrorReporter.reportError(domain, key, arguments, severity);
+            String message = fErrorReporter.reportError(domain, key, arguments, severity);
             if (fAugPSVI) {
                 fErrors.addElement(key);
+                fErrors.addElement(message);
             }
         } // reportError(String,String,Object[],short)
 
@@ -498,9 +508,10 @@
             Object[] arguments,
             short severity)
             throws XNIException {
-            fErrorReporter.reportError(location, domain, key, arguments, severity);
+            String message = fErrorReporter.reportError(location, domain, key, arguments, severity);
             if (fAugPSVI) {
                 fErrors.addElement(key);
+                fErrors.addElement(message);
             }
         } // reportError(XMLLocator,String,String,Object[],short)
     }
@@ -594,7 +605,32 @@
      */
     public void setProperty(String propertyId, Object value) throws XMLConfigurationException {
         if (propertyId.equals(ROOT_TYPE_DEF)) {
-            fRootTypeQName = (javax.xml.namespace.QName)value;
+            if (value == null) {
+                fRootTypeQName = null;
+                fRootTypeDefinition = null;
+            }
+            else if (value instanceof javax.xml.namespace.QName) {
+                fRootTypeQName = (javax.xml.namespace.QName) value;
+                fRootTypeDefinition = null;
+            }
+            else {
+                fRootTypeDefinition = (XSTypeDefinition) value;
+                fRootTypeQName = null;
+            }
+        }
+        else if (propertyId.equals(ROOT_ELEMENT_DECL)) {
+            if (value == null) {
+                fRootElementDeclQName = null;
+                fRootElementDeclaration = null;
+            }
+            else if (value instanceof javax.xml.namespace.QName) {
+                fRootElementDeclQName = (javax.xml.namespace.QName) value;
+                fRootElementDeclaration = null;
+            }
+            else {
+                fRootElementDeclaration = (XSElementDecl) value;
+                fRootElementDeclQName = null;
+            }
         }
     } // setProperty(String,Object)
 
@@ -868,6 +904,7 @@
      * @throws XNIException Thrown by handler to signal an error.
      */
     public void ignorableWhitespace(XMLString text, Augmentations augs) throws XNIException {
+
         handleIgnorableWhitespace(text);
         // call handlers
         if (fDocumentHandler != null) {
@@ -1160,7 +1197,7 @@
 
     /** Schema grammar resolver. */
     private final XSGrammarBucket fGrammarBucket = new XSGrammarBucket();
-    private final SubstitutionGroupHandler fSubGroupHandler = new SubstitutionGroupHandler(fGrammarBucket);
+    private final SubstitutionGroupHandler fSubGroupHandler = new SubstitutionGroupHandler(this);
 
     /** the DV usd to convert xsi:type to a QName */
     // REVISIT: in new simple type design, make things in DVs static,
@@ -1248,7 +1285,7 @@
     private boolean[] fStrictAssessStack = new boolean[INITIAL_STACK_SIZE];
 
     /** Temporary string buffers. */
-    private final StringBuffer fBuffer = new StringBuffer();
+    private final StringBuilder fBuffer = new StringBuilder();
 
     /** Whether need to append characters to fBuffer */
     private boolean fAppendBuffer = true;
@@ -1268,7 +1305,13 @@
     /** temporary qname */
     private final QName fTempQName = new QName();
 
+    /** value of the "root-type-definition" property. */
     private javax.xml.namespace.QName fRootTypeQName = null;
+    private XSTypeDefinition fRootTypeDefinition = null;
+
+    /** value of the "root-element-declaration" property. */
+    private javax.xml.namespace.QName fRootElementDeclQName = null;
+    private XSElementDecl fRootElementDeclaration = null;
 
     private int fIgnoreXSITypeDepth;
 
@@ -1341,9 +1384,6 @@
         // cleanup id table
         fValidationState.resetIDTables();
 
-        //pass the component manager to the factory..
-        nodeFactory.reset(componentManager);
-
         // reset schema loader
         fSchemaLoader.reset(componentManager);
 
@@ -1364,19 +1404,16 @@
 
         fMatcherStack.clear();
 
-        if (!fMayMatchFieldMap.isEmpty()) {
-            // should only clear this if the last schema had identity constraints.
-            fMayMatchFieldMap.clear();
-        }
-
         // get error reporter
         fXSIErrorReporter.reset((XMLErrorReporter) componentManager.getProperty(ERROR_REPORTER));
 
         boolean parser_settings = componentManager.getFeature(PARSER_SETTINGS, true);
 
-        if (!parser_settings){
+        if (!parser_settings) {
             // parser settings have not been changed
             fValidationManager.addValidationState(fValidationState);
+            // the node limit on the SecurityManager may have changed so need to refresh.
+            nodeFactory.reset();
             // Re-parse external schema location properties.
             XMLSchemaLoader.processExternalHints(
                 fExternalSchemas,
@@ -1386,6 +1423,8 @@
             return;
         }
 
+        // pass the component manager to the factory..
+        nodeFactory.reset(componentManager);
 
         // get symbol table. if it's a new one, add symbols to it.
         SymbolTable symbolTable = (SymbolTable) componentManager.getProperty(SYMBOL_TABLE);
@@ -1413,8 +1452,8 @@
         fAugPSVI = componentManager.getFeature(SCHEMA_AUGMENT_PSVI, true);
 
         fSchemaType =
-                (String) componentManager.getProperty(
-                    Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_LANGUAGE, null);
+            (String) componentManager.getProperty(
+                Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_LANGUAGE, null);
 
         fUseGrammarPoolOnly = componentManager.getFeature(USE_GRAMMAR_POOL_ONLY, false);
 
@@ -1424,13 +1463,48 @@
         fValidationManager.addValidationState(fValidationState);
         fValidationState.setSymbolTable(fSymbolTable);
 
-        boolean ignoreXSIType;
         try {
-            ignoreXSIType = componentManager.getFeature(IGNORE_XSI_TYPE);
+            final Object rootType = componentManager.getProperty(ROOT_TYPE_DEF);
+            if (rootType == null) {
+                fRootTypeQName = null;
+                fRootTypeDefinition = null;
+            }
+            else if (rootType instanceof javax.xml.namespace.QName) {
+                fRootTypeQName = (javax.xml.namespace.QName) rootType;
+                fRootTypeDefinition = null;
+            }
+            else {
+                fRootTypeDefinition = (XSTypeDefinition) rootType;
+                fRootTypeQName = null;
+            }
         }
         catch (XMLConfigurationException e) {
-            ignoreXSIType = false;
+            fRootTypeQName = null;
+            fRootTypeDefinition = null;
         }
+
+        try {
+            final Object rootDecl = componentManager.getProperty(ROOT_ELEMENT_DECL);
+            if (rootDecl == null) {
+                fRootElementDeclQName = null;
+                fRootElementDeclaration = null;
+            }
+            else if (rootDecl instanceof javax.xml.namespace.QName) {
+                fRootElementDeclQName = (javax.xml.namespace.QName) rootDecl;
+                fRootElementDeclaration = null;
+            }
+            else {
+                fRootElementDeclaration = (XSElementDecl) rootDecl;
+                fRootElementDeclQName = null;
+            }
+        }
+        catch (XMLConfigurationException e) {
+            fRootElementDeclQName = null;
+            fRootElementDeclaration = null;
+        }
+
+        boolean ignoreXSIType = componentManager.getFeature(IGNORE_XSI_TYPE, false);
+
         // An initial value of -1 means that the root element considers itself
         // below the depth where xsi:type stopped being ignored (which means that
         // xsi:type attributes will not be ignored for the entire document)
@@ -1515,8 +1589,7 @@
     public XPathMatcher activateField(Field field, int initialDepth) {
         ValueStore valueStore =
             fValueStoreCache.getValueStoreFor(field.getIdentityConstraint(), initialDepth);
-        setMayMatch(field, Boolean.TRUE);
-        XPathMatcher matcher = field.createMatcher(this, valueStore);
+        XPathMatcher matcher = field.createMatcher(valueStore);
         fMatcherStack.addMatcher(matcher);
         matcher.startDocumentFragment();
         return matcher;
@@ -1535,28 +1608,6 @@
 
     } // endValueScopeFor(IdentityConstraint)
 
-    /**
-     * Sets whether the given field is permitted to match a value.
-     * This should be used to catch instance documents that try
-     * and match a field several times in the same scope.
-     *
-     * @param field The field that may be permitted to be matched.
-     * @param state Boolean indiciating whether the field may be matched.
-     */
-    public void setMayMatch(Field field, Boolean state) {
-        fMayMatchFieldMap.put(field, state);
-    } // setMayMatch(Field, Boolean)
-
-    /**
-     * Returns whether the given field is permitted to match a value.
-     *
-     * @param field The field that may be permitted to be matched.
-     * @return Boolean indicating whether the field may be matched.
-     */
-    public Boolean mayMatch(Field field) {
-        return (Boolean) fMayMatchFieldMap.get(field);
-    } // mayMatch(Field):Boolean
-
     // a utility method for Identity constraints
     private void activateSelectorFor(IdentityConstraint ic) {
         Selector selector = ic.getSelector();
@@ -1568,6 +1619,21 @@
         matcher.startDocumentFragment();
     }
 
+    // Implements XSElementDeclHelper interface
+    public XSElementDecl getGlobalElementDecl(QName element) {
+        final SchemaGrammar sGrammar =
+            findSchemaGrammar(
+                XSDDescription.CONTEXT_ELEMENT,
+                element.uri,
+                null,
+                element,
+                null);
+        if (sGrammar != null) {
+            return sGrammar.getGlobalElementDecl(element.localpart);
+        }
+        return null;
+    }
+
     //
     // Protected methods
     //
@@ -1823,16 +1889,17 @@
         }
 
         // get xsi:schemaLocation and xsi:noNamespaceSchemaLocation attributes,
-        // parse them to get the grammars
-
-        String sLocation =
-            attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_SCHEMALOCATION);
-        String nsLocation =
-            attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION);
-        //store the location hints..  we need to do it so that we can defer the loading of grammar until
-        //there is a reference to a component from that namespace. To provide location hints to the
-        //application for a namespace
-        storeLocations(sLocation, nsLocation);
+        // parse them to get the grammars. But only do this if the grammar can grow.
+        if (!fUseGrammarPoolOnly) {
+            String sLocation =
+                attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_SCHEMALOCATION);
+            String nsLocation =
+                attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION);
+            //store the location hints..  we need to do it so that we can defer the loading of grammar until
+            //there is a reference to a component from that namespace. To provide location hints to the
+            //application for a namespace
+            storeLocations(sLocation, nsLocation);
+        }
 
         // if we are in the content of "skip", then just skip this element
         // REVISIT:  is this the correct behaviour for ID constraints?  -NG
@@ -1843,15 +1910,6 @@
             return augs;
         }
 
-        //try to find schema grammar by different means..
-        SchemaGrammar sGrammar =
-            findSchemaGrammar(
-                XSDDescription.CONTEXT_ELEMENT,
-                element.uri,
-                null,
-                element,
-                attributes);
-
         // if we are not skipping this element, and there is a content model,
         // we try to find the corresponding decl object for this element.
         // the reason we move this part of code here is to make sure the
@@ -1864,15 +1922,57 @@
             if (fCurrCMState[0] == XSCMValidator.FIRST_ERROR) {
                 XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType;
                 //REVISIT: is it the only case we will have particle = null?
-                Vector next;
+                ArrayList next;
                 if (ctype.fParticle != null
                     && (next = fCurrentCM.whatCanGoHere(fCurrCMState)).size() > 0) {
                     String expected = expectedStr(next);
-                    reportSchemaError(
-                        "cvc-complex-type.2.4.a",
-                        new Object[] { element.rawname, expected });
-                } else {
-                    reportSchemaError("cvc-complex-type.2.4.d", new Object[] { element.rawname });
+                    final int[] occurenceInfo = fCurrentCM.occurenceInfo(fCurrCMState);
+                    String elemExpandedQname = (element.uri != null) ? "{"+'"'+element.uri+'"'+":"+element.localpart+"}" : element.localpart;
+                    if (occurenceInfo != null) {
+                        final int minOccurs = occurenceInfo[0];
+                        final int maxOccurs = occurenceInfo[1];
+                        final int count = occurenceInfo[2];
+                        // Check if this is a violation of minOccurs
+                        if (count < minOccurs) {
+                            final int required = minOccurs - count;
+                            if (required > 1) {
+                                reportSchemaError("cvc-complex-type.2.4.h", new Object[] { element.rawname,
+                                        fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs), Integer.toString(required) });
+                            }
+                            else {
+                                reportSchemaError("cvc-complex-type.2.4.g", new Object[] { element.rawname,
+                                        fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs) });
+                            }
+                        }
+                        // Check if this is a violation of maxOccurs
+                        else if (count >= maxOccurs && maxOccurs != SchemaSymbols.OCCURRENCE_UNBOUNDED) {
+                            reportSchemaError("cvc-complex-type.2.4.e", new Object[] { element.rawname,
+                                    expected, Integer.toString(maxOccurs) });
+                        }
+                        else {
+                            reportSchemaError("cvc-complex-type.2.4.a", new Object[] { elemExpandedQname, expected });
+                        }
+                    }
+                    else {
+                        reportSchemaError("cvc-complex-type.2.4.a", new Object[] { elemExpandedQname, expected });
+                    }
+                }
+                else {
+                    final int[] occurenceInfo = fCurrentCM.occurenceInfo(fCurrCMState);
+                    if (occurenceInfo != null) {
+                        final int maxOccurs = occurenceInfo[1];
+                        final int count = occurenceInfo[2];
+                        // Check if this is a violation of maxOccurs
+                        if (count >= maxOccurs && maxOccurs != SchemaSymbols.OCCURRENCE_UNBOUNDED) {
+                            reportSchemaError("cvc-complex-type.2.4.f", new Object[] { fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(maxOccurs) });
+                        }
+                        else {
+                            reportSchemaError("cvc-complex-type.2.4.d", new Object[] { element.rawname });
+                        }
+                    }
+                    else {
+                        reportSchemaError("cvc-complex-type.2.4.d", new Object[] { element.rawname });
+                    }
                 }
             }
         }
@@ -1926,23 +2026,21 @@
             return augs;
         }
 
-        // 1.2.1.1 A type definition was stipulated by the processor
-        if (fElementDepth == 0 && fRootTypeQName != null) {
-            String rootTypeNamespace = fRootTypeQName.getNamespaceURI();
-            if (rootTypeNamespace != null && rootTypeNamespace.equals(XMLConstants.NULL_NS_URI)) {
-                rootTypeNamespace = null;
+        if (fElementDepth == 0) {
+            // 1.1.1.1 An element declaration was stipulated by the processor
+            if (fRootElementDeclaration != null) {
+                fCurrentElemDecl = fRootElementDeclaration;
+                checkElementMatchesRootElementDecl(fCurrentElemDecl, element);
             }
-            SchemaGrammar grammarForRootType =
-                findSchemaGrammar(
-                        XSDDescription.CONTEXT_ELEMENT, rootTypeNamespace, null, null, null);
-            if (grammarForRootType != null) {
-                fCurrentType = grammarForRootType.getGlobalTypeDecl(fRootTypeQName.getLocalPart());
+            else if (fRootElementDeclQName != null) {
+                processRootElementDeclQName(fRootElementDeclQName, element);
             }
-            if (fCurrentType == null) {
-                String typeName = (fRootTypeQName.getPrefix().equals(XMLConstants.DEFAULT_NS_PREFIX)) ?
-                        fRootTypeQName.getLocalPart() :
-                            fRootTypeQName.getPrefix()+":"+fRootTypeQName.getLocalPart();
-                        reportSchemaError("cvc-type.1", new Object[] {typeName});
+            // 1.2.1.1 A type definition was stipulated by the processor
+            else if (fRootTypeDefinition != null) {
+                fCurrentType = fRootTypeDefinition;
+            }
+            else if (fRootTypeQName != null) {
+                processRootTypeQName(fRootTypeQName);
             }
         }
 
@@ -1952,6 +2050,14 @@
             // case 1: find declaration for root element
             // case 2: find declaration for element from another namespace
             if (fCurrentElemDecl == null) {
+                // try to find schema grammar by different means..
+                SchemaGrammar sGrammar =
+                    findSchemaGrammar(
+                        XSDDescription.CONTEXT_ELEMENT,
+                        element.uri,
+                        null,
+                        element,
+                        attributes);
                 if (sGrammar != null) {
                     fCurrentElemDecl = sGrammar.getGlobalElementDecl(element.localpart);
                 }
@@ -1963,7 +2069,6 @@
             }
         }
 
-
         // check if we should be ignoring xsi:type on this element
         if (fElementDepth == fIgnoreXSITypeDepth && fCurrentElemDecl == null) {
             fIgnoreXSITypeDepth++;
@@ -2012,7 +2117,7 @@
                 // of this. - SG
                 fXSIErrorReporter.fErrorReporter.reportError(
                     XSMessageFormatter.SCHEMA_DOMAIN,
-                    "cvc-elt.1",
+                    "cvc-elt.1.a",
                     new Object[] { element.rawname },
                     XMLErrorReporter.SEVERITY_ERROR);
             }
@@ -2189,6 +2294,8 @@
             fCurrentPSVI.fTypeDecl = fCurrentType;
             // PSVI: add notation attribute
             fCurrentPSVI.fNotation = fNotation;
+            // PSVI: add nil
+            fCurrentPSVI.fNil = fNil;
         }
 
         return augs;
@@ -2234,7 +2341,7 @@
             // validation attempted, validity, and error codes
 
             // check extra schema constraints on root element
-            if (fElementDepth == -1 && fFullChecking) {
+            if (fElementDepth == -1 && fFullChecking && !fUseGrammarPoolOnly) {
                 XSConstraints.fullSchemaChecking(
                     fGrammarBucket,
                     fSubGroupHandler,
@@ -2258,10 +2365,10 @@
             int oldCount = fMatcherStack.getMatcherCount();
             for (int i = oldCount - 1; i >= 0; i--) {
                 XPathMatcher matcher = fMatcherStack.getMatcherAt(i);
-                if (fCurrentElemDecl == null)
-                    matcher.endElement(element, null, false, fValidatedInfo.actualValue, fValidatedInfo.actualValueType, fValidatedInfo.itemValueTypes);
-
-                else
+                if (fCurrentElemDecl == null) {
+                    matcher.endElement(element, fCurrentType, false, fValidatedInfo.actualValue, fValidatedInfo.actualValueType, fValidatedInfo.itemValueTypes);
+                }
+                else {
                     matcher.endElement(
                             element,
                             fCurrentType,
@@ -2275,6 +2382,7 @@
                             fDefaultValue == null
                                 ? fValidatedInfo.itemValueTypes
                                 : fCurrentElemDecl.fDefault.itemValueTypes);
+                }
             }
 
             if (fMatcherStack.size() > 0) {
@@ -2305,7 +2413,9 @@
                             && id.getCategory() == IdentityConstraint.IC_KEYREF) {
                         ValueStoreBase values =
                             fValueStoreCache.getValueStoreFor(id, selMatcher.getInitialDepth());
-                        if (values != null) // nothing to do if nothing matched!
+                        // nothing to do if nothing matched, or if not all
+                        // fields are present.
+                        if (values != null && values.fValuesCount == values.fFieldCount)
                             values.endDocumentFragment();
                     }
                 }
@@ -2324,13 +2434,15 @@
         // have we reached the end tag of the validation root?
         if (fElementDepth == 0) {
             // 7 If the element information item is the validation root, it must be valid per Validation Root Valid (ID/IDREF) (3.3.4).
-            String invIdRef = fValidationState.checkIDRefID();
+            Iterator invIdRefs = fValidationState.checkIDRefID();
             fValidationState.resetIDTables();
-            if (invIdRef != null) {
-                reportSchemaError("cvc-id.1", new Object[] { invIdRef });
+            if (invIdRefs != null) {
+                while (invIdRefs.hasNext()) {
+                    reportSchemaError("cvc-id.1", new Object[] { invIdRefs.next() });
+                }
             }
             // check extra schema constraints
-            if (fFullChecking) {
+            if (fFullChecking && !fUseGrammarPoolOnly) {
                 XSConstraints.fullSchemaChecking(
                     fGrammarBucket,
                     fSubGroupHandler,
@@ -2390,11 +2502,12 @@
         if (fAugPSVI) {
             augs = getEmptyAugs(augs);
 
-            // the 4 properties sent on startElement calls
+            // the 5 properties sent on startElement calls
             fCurrentPSVI.fDeclaration = this.fCurrentElemDecl;
             fCurrentPSVI.fTypeDecl = this.fCurrentType;
             fCurrentPSVI.fNotation = this.fNotation;
             fCurrentPSVI.fValidationContext = this.fValidationRoot;
+            fCurrentPSVI.fNil = this.fNil;
             // PSVI: validation attempted
             // nothing below or at the same level has none or partial
             // (which means this level is strictly assessed, and all chidren
@@ -2423,12 +2536,7 @@
 
             if (fDefaultValue != null)
                 fCurrentPSVI.fSpecified = true;
-            fCurrentPSVI.fNil = fNil;
-            fCurrentPSVI.fMemberType = fValidatedInfo.memberType;
-            fCurrentPSVI.fNormalizedValue = fValidatedInfo.normalizedValue;
-            fCurrentPSVI.fActualValue = fValidatedInfo.actualValue;
-            fCurrentPSVI.fActualValueType = fValidatedInfo.actualValueType;
-            fCurrentPSVI.fItemValueTypes = fValidatedInfo.itemValueTypes;
+            fCurrentPSVI.fValue.copyFrom(fValidatedInfo);
 
             if (fStrictAssess) {
                 // get all errors for the current element, its attribute,
@@ -2438,7 +2546,7 @@
                 String[] errors = fXSIErrorReporter.mergeContext();
 
                 // PSVI: error codes
-                fCurrentPSVI.fErrorCodes = errors;
+                fCurrentPSVI.fErrors = errors;
                 // PSVI: validity
                 fCurrentPSVI.fValidity =
                     (errors == null) ? ElementPSVI.VALIDITY_VALID : ElementPSVI.VALIDITY_INVALID;
@@ -2475,7 +2583,7 @@
 
     void storeLocations(String sLocation, String nsLocation) {
         if (sLocation != null) {
-            if (!XMLSchemaLoader.tokenizeSchemaLocationStr(sLocation, fLocationPairs)) {
+            if (!XMLSchemaLoader.tokenizeSchemaLocationStr(sLocation, fLocationPairs, fLocator == null ? null : fLocator.getExpandedSystemId())) {
                 // error!
                 fXSIErrorReporter.reportError(
                     XSMessageFormatter.SCHEMA_DOMAIN,
@@ -2491,6 +2599,12 @@
                 la = new XMLSchemaLoader.LocationArray();
                 fLocationPairs.put(XMLSymbols.EMPTY_STRING, la);
             }
+            if (fLocator != null) {
+                try {
+                    nsLocation = XMLEntityManager.expandSystemId(nsLocation, fLocator.getExpandedSystemId(), false);
+                } catch (MalformedURIException e) {
+                }
+            }
             la.addLocation(nsLocation);
         }
 
@@ -2503,7 +2617,7 @@
         short contextType,
         String namespace,
         QName enclosingElement,
-        QName triggeringComponet,
+        QName triggeringComponent,
         XMLAttributes attributes) {
         SchemaGrammar grammar = null;
         //get the grammar from local pool...
@@ -2530,12 +2644,14 @@
                 }
             }
         }
-        if ((grammar == null && !fUseGrammarPoolOnly) || fNamespaceGrowth) {
+
+        if (!fUseGrammarPoolOnly && (grammar == null ||
+            (fNamespaceGrowth && !hasSchemaComponent(grammar, contextType, triggeringComponent)))) {
             fXSDDescription.reset();
             fXSDDescription.fContextType = contextType;
             fXSDDescription.setNamespace(namespace);
             fXSDDescription.fEnclosedElementName = enclosingElement;
-            fXSDDescription.fTriggeringComponent = triggeringComponet;
+            fXSDDescription.fTriggeringComponent = triggeringComponent;
             fXSDDescription.fAttributes = attributes;
             if (fLocator != null) {
                 fXSDDescription.setBaseSystemId(fLocator.getExpandedSystemId());
@@ -2579,13 +2695,14 @@
                     if (toParseSchema) {
                         grammar = fSchemaLoader.loadSchema(fXSDDescription, xis, fLocationPairs);
                     }
-                } catch (IOException ex) {
+                }
+                catch (IOException ex) {
                     final String [] locationHints = fXSDDescription.getLocationHints();
                     fXSIErrorReporter.fErrorReporter.reportError(
                         XSMessageFormatter.SCHEMA_DOMAIN,
                         "schema_reference.4",
                         new Object[] { locationHints != null ? locationHints[0] : XMLSymbols.EMPTY_STRING },
-                        XMLErrorReporter.SEVERITY_WARNING);
+                        XMLErrorReporter.SEVERITY_WARNING, ex);
                 }
             }
         }
@@ -2593,6 +2710,24 @@
         return grammar;
 
     } //findSchemaGrammar
+
+    private boolean hasSchemaComponent(SchemaGrammar grammar, short contextType, QName triggeringComponent) {
+        if (grammar != null && triggeringComponent != null) {
+            String localName = triggeringComponent.localpart;
+            if (localName != null && localName.length() > 0) {
+                switch (contextType) {
+                    case XSDDescription.CONTEXT_ELEMENT:
+                        return grammar.getElementDeclaration(localName) != null;
+                    case XSDDescription.CONTEXT_ATTRIBUTE:
+                        return grammar.getAttributeDeclaration(localName) != null;
+                    case XSDDescription.CONTEXT_XSITYPE:
+                        return grammar.getTypeDefinition(localName) != null;
+                }
+            }
+        }
+        return false;
+    }
+
     private void setLocationHints(XSDDescription desc, String[] locations, SchemaGrammar grammar) {
         int length = locations.length;
         if (grammar == null) {
@@ -2610,13 +2745,8 @@
         int counter = 0;
 
         for (int i=0; i<length; i++) {
-            try {
-                String id = XMLEntityManager.expandSystemId(locations[i], desc.getBaseSystemId(), false);
-                if (!docLocations.contains(id)) {
-                    hints[counter++] = locations[i];
-                }
-            }
-            catch (MalformedURIException e) {
+            if (!docLocations.contains(locations[i])) {
+                hints[counter++] = locations[i];
             }
         }
 
@@ -2631,7 +2761,6 @@
         }
     }
 
-
     XSTypeDefinition getAndCheckXsiType(QName element, String xsiType, XMLAttributes attributes) {
         // This method also deals with clause 1.2.1.2 of the constraint
         // Validation Rule: Schema-Validity Assessment (Element)
@@ -2696,7 +2825,7 @@
             if (!XSConstraints.checkTypeDerivationOk(type, fCurrentType, block)) {
                 reportSchemaError(
                         "cvc-elt.4.3",
-                        new Object[] { element.rawname, xsiType, fCurrentType.getName()});
+                        new Object[] { element.rawname, xsiType, XS10TypeHelper.getSchemaTypeName(fCurrentType)});
             }
         }
 
@@ -2793,18 +2922,18 @@
             // for the 4 xsi attributes, get appropriate decl, and validate
             if (fTempQName.uri == SchemaSymbols.URI_XSI) {
                 XSAttributeDecl attrDecl = null;
-                if (fTempQName.localpart == SchemaSymbols.XSI_SCHEMALOCATION)
-                    attrDecl =
-                        SchemaGrammar.SG_XSI.getGlobalAttributeDecl(
-                            SchemaSymbols.XSI_SCHEMALOCATION);
-                else if (fTempQName.localpart == SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION)
-                    attrDecl =
-                        SchemaGrammar.SG_XSI.getGlobalAttributeDecl(
-                            SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION);
-                else if (fTempQName.localpart == SchemaSymbols.XSI_NIL)
-                    attrDecl = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_NIL);
-                else if (fTempQName.localpart == SchemaSymbols.XSI_TYPE)
-                    attrDecl = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_TYPE);
+                if (fTempQName.localpart == SchemaSymbols.XSI_TYPE) {
+                    attrDecl = XSI_TYPE;
+                }
+                else if (fTempQName.localpart == SchemaSymbols.XSI_NIL) {
+                    attrDecl = XSI_NIL;
+                }
+                else if (fTempQName.localpart == SchemaSymbols.XSI_SCHEMALOCATION) {
+                    attrDecl = XSI_SCHEMALOCATION;
+                }
+                else if (fTempQName.localpart == SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION) {
+                    attrDecl = XSI_NONAMESPACESCHEMALOCATION;
+                }
                 if (attrDecl != null) {
                     processOneAttribute(element, attributes, index, attrDecl, null, attrPSVI);
                     continue;
@@ -2849,6 +2978,10 @@
                     reportSchemaError(
                         "cvc-complex-type.3.2.2",
                         new Object[] { element.rawname, fTempQName.rawname });
+
+                    // We have seen an attribute that was not declared
+                    fNFullValidationDepth = fElementDepth;
+
                     continue;
                 }
             }
@@ -2936,17 +3069,9 @@
         try {
             actualValue = attDV.validate(attrValue, fValidationState, fValidatedInfo);
             // store the normalized value
-            if (fNormalizeData)
+            if (fNormalizeData) {
                 attributes.setValue(index, fValidatedInfo.normalizedValue);
-            if (attributes instanceof XMLAttributesImpl) {
-                XMLAttributesImpl attrs = (XMLAttributesImpl) attributes;
-                boolean schemaId =
-                    fValidatedInfo.memberType != null
-                        ? fValidatedInfo.memberType.isIDType()
-                        : attDV.isIDType();
-                attrs.setSchemaId(index, schemaId);
             }
-
             // PSVI: element notation
             if (attDV.getVariety() == XSSimpleType.VARIETY_ATOMIC
                 && attDV.getPrimitiveKind() == XSSimpleType.PRIMITIVE_NOTATION) {
@@ -2963,16 +3088,18 @@
                     fNotation = grammar.getGlobalNotationDecl(qName.localpart);
                 }
             }
-        } catch (InvalidDatatypeValueException idve) {
+        }
+        catch (InvalidDatatypeValueException idve) {
             reportSchemaError(idve.getKey(), idve.getArgs());
             reportSchemaError(
                 "cvc-attribute.3",
-                new Object[] { element.rawname, fTempQName.rawname, attrValue, attDV.getName()});
+                new Object[] { element.rawname, fTempQName.rawname, attrValue,
+                        (attDV instanceof XSSimpleTypeDecl) ?
+                                ((XSSimpleTypeDecl) attDV).getTypeName() : attDV.getName()});
         }
 
         // get the value constraint from use or decl
-        // 4 The item's actual value must match the value of the {value constraint}, if it is present and fixed.
-        // now check the value against the simpleType
+        // 4 The item's actual value must match the value of the {value constraint}, if it is present and fixed.                 // now check the value against the simpleType
         if (actualValue != null && currDecl.getConstraintType() == XSConstants.VC_FIXED) {
             if (!ValidatedInfo.isComparable(fValidatedInfo, currDecl.fDefault) || !actualValue.equals(currDecl.fDefault.actualValue)) {
                 reportSchemaError(
@@ -3000,7 +3127,7 @@
             }
         }
         if (fIdConstraint) {
-            attrPSVI.fActualValue = actualValue;
+            attrPSVI.fValue.copyFrom(fValidatedInfo);
         }
 
         if (fAugPSVI) {
@@ -3009,25 +3136,25 @@
             // PSVI: attribute type
             attrPSVI.fTypeDecl = attDV;
 
-            // PSVI: attribute memberType
-            attrPSVI.fMemberType = fValidatedInfo.memberType;
             // PSVI: attribute normalized value
             // NOTE: we always store the normalized value, even if it's invlid,
             // because it might still be useful to the user. But when the it's
             // not valid, the normalized value is not trustable.
-            attrPSVI.fNormalizedValue = fValidatedInfo.normalizedValue;
-            attrPSVI.fActualValue = fValidatedInfo.actualValue;
-            attrPSVI.fActualValueType = fValidatedInfo.actualValueType;
-            attrPSVI.fItemValueTypes = fValidatedInfo.itemValueTypes;
-
-
+            attrPSVI.fValue.copyFrom(fValidatedInfo);
 
             // PSVI: validation attempted:
             attrPSVI.fValidationAttempted = AttributePSVI.VALIDATION_FULL;
 
+            // We have seen an attribute that was declared.
+            if (!fUseGrammarPoolOnly &&
+                    !(fElementDepth < fIgnoreXSITypeDepth && fCurrentElemDecl == null)) {
+                //only when USE_GRAMMAR_POOL_ONLY and IGNORE_XSI_TYPE are not set
+                fNNoneValidationDepth = fElementDepth;
+            }
+
             String[] errors = fXSIErrorReporter.mergeContext();
             // PSVI: error codes
-            attrPSVI.fErrorCodes = errors;
+            attrPSVI.fErrors = errors;
             // PSVI: validity
             attrPSVI.fValidity =
                 (errors == null) ? AttributePSVI.VALIDITY_VALID : AttributePSVI.VALIDITY_INVALID;
@@ -3085,15 +3212,14 @@
                 attName =
                     new QName(null, currDecl.fName, currDecl.fName, currDecl.fTargetNamespace);
                 String normalized = (defaultValue != null) ? defaultValue.stringValue() : "";
-                int attrIndex = attributes.addAttribute(attName, "CDATA", normalized);
+                int attrIndex;
                 if (attributes instanceof XMLAttributesImpl) {
                     XMLAttributesImpl attrs = (XMLAttributesImpl) attributes;
-                    boolean schemaId =
-                        defaultValue != null
-                            && defaultValue.memberType != null
-                                ? defaultValue.memberType.isIDType()
-                                : currDecl.fType.isIDType();
-                    attrs.setSchemaId(attrIndex, schemaId);
+                    attrIndex = attrs.getLength();
+                    attrs.addAttributeNS(attName, "CDATA", normalized);
+                }
+                else {
+                    attrIndex = attributes.addAttribute(attName, "CDATA", normalized);
                 }
 
                 if (fAugPSVI) {
@@ -3105,11 +3231,7 @@
 
                     attrPSVI.fDeclaration = currDecl;
                     attrPSVI.fTypeDecl = currDecl.fType;
-                    attrPSVI.fMemberType = defaultValue.memberType;
-                    attrPSVI.fNormalizedValue = normalized;
-                    attrPSVI.fActualValue = defaultValue.actualValue;
-                    attrPSVI.fActualValueType = defaultValue.actualValueType;
-                    attrPSVI.fItemValueTypes = defaultValue.itemValueTypes;
+                    attrPSVI.fValue.copyFrom(defaultValue);
                     attrPSVI.fValidationContext = fValidationRoot;
                     attrPSVI.fValidity = AttributePSVI.VALIDITY_VALID;
                     attrPSVI.fValidationAttempted = AttributePSVI.VALIDATION_FULL;
@@ -3346,9 +3468,29 @@
                 }
                 if (fCurrCMState[0] >= 0 && !fCurrentCM.endContentModel(fCurrCMState)) {
                     String expected = expectedStr(fCurrentCM.whatCanGoHere(fCurrCMState));
-                    reportSchemaError(
-                        "cvc-complex-type.2.4.b",
-                        new Object[] { element.rawname, expected });
+                    final int[] occurenceInfo = fCurrentCM.occurenceInfo(fCurrCMState);
+                    if (occurenceInfo != null) {
+                        final int minOccurs = occurenceInfo[0];
+                        final int count = occurenceInfo[2];
+                        // Check if this is a violation of minOccurs
+                        if (count < minOccurs) {
+                            final int required = minOccurs - count;
+                            if (required > 1) {
+                                reportSchemaError("cvc-complex-type.2.4.j", new Object[] { element.rawname,
+                                        fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs), Integer.toString(required) });
+                            }
+                            else {
+                                reportSchemaError("cvc-complex-type.2.4.i", new Object[] { element.rawname,
+                                        fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs) });
+                            }
+                        }
+                        else {
+                            reportSchemaError("cvc-complex-type.2.4.b", new Object[] { element.rawname, expected });
+                        }
+                    }
+                    else {
+                        reportSchemaError("cvc-complex-type.2.4.b", new Object[] { element.rawname, expected });
+                    }
                 } else {
                     // Constant space algorithm for a{n,m} for n > 1 and m <= unbounded
                     // After the DFA has completed, check minOccurs and maxOccurs
@@ -3363,11 +3505,70 @@
                         }
                     }
                 }
-             }
+            }
         }
         return actualValue;
     } // elementLocallyValidComplexType
 
+    void processRootTypeQName(final javax.xml.namespace.QName rootTypeQName) {
+        String rootTypeNamespace = rootTypeQName.getNamespaceURI();
+        // Add namespace to symbol table, to make sure it's interned.
+        // This namespace may be later compared with other values using ==.
+        rootTypeNamespace = fSymbolTable.addSymbol(rootTypeNamespace);
+        if (rootTypeNamespace != null && rootTypeNamespace.equals(XMLConstants.NULL_NS_URI)) {
+            rootTypeNamespace = null;
+        }
+        if (SchemaSymbols.URI_SCHEMAFORSCHEMA.equals(rootTypeNamespace)) {
+            fCurrentType = SchemaGrammar.SG_SchemaNS.getGlobalTypeDecl(rootTypeQName.getLocalPart());
+        }
+        else {
+            final SchemaGrammar grammarForRootType = findSchemaGrammar(
+                    XSDDescription.CONTEXT_ELEMENT, rootTypeNamespace, null, null, null);
+            if (grammarForRootType != null) {
+                fCurrentType = grammarForRootType.getGlobalTypeDecl(rootTypeQName.getLocalPart());
+            }
+        }
+        if (fCurrentType == null) {
+            String typeName = (rootTypeQName.getPrefix().equals(XMLConstants.DEFAULT_NS_PREFIX)) ?
+                    rootTypeQName.getLocalPart() :
+                        rootTypeQName.getPrefix()+":"+rootTypeQName.getLocalPart();
+                    reportSchemaError("cvc-type.1", new Object[] {typeName});
+        }
+    } // processRootTypeQName
+
+    void processRootElementDeclQName(final javax.xml.namespace.QName rootElementDeclQName, final QName element) {
+        String rootElementDeclNamespace = rootElementDeclQName.getNamespaceURI();
+        // Add namespace to symbol table, to make sure it's interned.
+        // This namespace may be later compared with other values using ==.
+        rootElementDeclNamespace = fSymbolTable.addSymbol(rootElementDeclNamespace);
+        if (rootElementDeclNamespace != null && rootElementDeclNamespace.equals(XMLConstants.NULL_NS_URI)) {
+            rootElementDeclNamespace = null;
+        }
+        final SchemaGrammar grammarForRootElement = findSchemaGrammar(
+                XSDDescription.CONTEXT_ELEMENT, rootElementDeclNamespace, null, null, null);
+        if (grammarForRootElement != null) {
+            fCurrentElemDecl = grammarForRootElement.getGlobalElementDecl(rootElementDeclQName.getLocalPart());
+        }
+        if (fCurrentElemDecl == null) {
+            String declName = (rootElementDeclQName.getPrefix().equals(XMLConstants.DEFAULT_NS_PREFIX)) ?
+                    rootElementDeclQName.getLocalPart() :
+                        rootElementDeclQName.getPrefix()+":"+rootElementDeclQName.getLocalPart();
+                    reportSchemaError("cvc-elt.1.a", new Object[] {declName});
+        }
+        else {
+            checkElementMatchesRootElementDecl(fCurrentElemDecl, element);
+        }
+    } // processRootElementDeclQName
+
+    void checkElementMatchesRootElementDecl(final XSElementDecl rootElementDecl, final QName element) {
+        // Report an error if the name of the element does
+        // not match the name of the specified element declaration.
+        if (element.localpart != rootElementDecl.fName ||
+            element.uri != rootElementDecl.fTargetNamespace) {
+            reportSchemaError("cvc-elt.1.b", new Object[] {element.rawname, rootElementDecl.fName});
+        }
+    } // checkElementMatchesRootElementDecl
+
     void reportSchemaError(String key, Object[] arguments) {
         if (fDoValidation)
             fXSIErrorReporter.reportError(
@@ -3377,14 +3578,13 @@
                 XMLErrorReporter.SEVERITY_ERROR);
     }
 
-
-    private String expectedStr(Vector expected) {
-        StringBuffer ret = new StringBuffer("{");
+    private String expectedStr(ArrayList expected) {
+        StringBuilder ret = new StringBuilder("{");
         int size = expected.size();
         for (int i = 0; i < size; i++) {
             if (i > 0)
                 ret.append(", ");
-            ret.append(expected.elementAt(i).toString());
+            ret.append(expected.get(i).toString());
         }
         ret.append('}');
         return ret.toString();
@@ -3520,7 +3720,7 @@
         private ShortList fItemValueType = null;
 
         /** buffer for error messages */
-        final StringBuffer fTempBuffer = new StringBuffer();
+        final StringBuilder fTempBuffer = new StringBuilder();
 
         //
         // Constructors
@@ -3645,9 +3845,12 @@
          * @param field The field associated to the value. This reference
          *              is used to ensure that each field only adds a value
          *              once within a selection scope.
+         * @param mayMatch a flag indiciating whether the field may be matched.
          * @param actualValue The value to add.
+         * @param valueType Type of the value to add.
+         * @param itemValueType If the value is a list, a list of types for each of the values in the list.
          */
-        public void addValue(Field field, Object actualValue, short valueType, ShortList itemValueType) {
+        public void addValue(Field field, boolean mayMatch, Object actualValue, short valueType, ShortList itemValueType) {
             int i;
             for (i = fFieldCount - 1; i > -1; i--) {
                 if (fFields[i] == field) {
@@ -3662,11 +3865,12 @@
                 reportSchemaError(code, new Object[] { field.toString(), eName, cName });
                 return;
             }
-            if (Boolean.TRUE != mayMatch(field)) {
+            if (!mayMatch) {
                 String code = "FieldMultipleMatch";
                 String cName = fIdentityConstraint.getIdentityConstraintName();
                 reportSchemaError(code, new Object[] { field.toString(), cName });
-            } else {
+            }
+            else {
                 fValuesCount++;
             }
             fLocalValues[i] = actualValue;
@@ -3815,7 +4019,7 @@
             }
 
             // construct value string
-            StringBuffer str = new StringBuffer();
+            StringBuilder str = new StringBuilder();
             for (int i = 0; i < length; i++) {
                 if (i > 0) {
                     str.append(',');
@@ -4075,7 +4279,7 @@
         // values stores
 
         /** stores all global Values stores. */
-        protected final Vector fValueStores = new Vector();
+        protected final ArrayList fValueStores = new ArrayList();
 
         /**
          * Values stores associated to specific identity constraints.
@@ -4086,7 +4290,7 @@
          * descendant-or-self axes occur on recursively-defined
          * elements.
          */
-        protected final Hashtable fIdentityConstraint2ValueStoreMap = new Hashtable();
+        protected final HashMap fIdentityConstraint2ValueStoreMap = new HashMap();
 
         // sketch of algorithm:
         // - when a constraint is first encountered, its
@@ -4108,7 +4312,7 @@
         // the fGlobalIDConstraintMap contains descendants+self.
         // keyrefs can only match descendants+self.
         protected final Stack fGlobalMapStack = new Stack();
-        protected final Hashtable fGlobalIDConstraintMap = new Hashtable();
+        protected final HashMap fGlobalIDConstraintMap = new HashMap();
 
         //
         // Constructors
@@ -4124,7 +4328,7 @@
 
         /** Resets the identity constraint cache. */
         public void startDocument() {
-            fValueStores.removeAllElements();
+            fValueStores.clear();
             fIdentityConstraint2ValueStoreMap.clear();
             fGlobalIDConstraintMap.clear();
             fGlobalMapStack.removeAllElements();
@@ -4133,7 +4337,7 @@
         // startElement:  pushes the current fGlobalIDConstraintMap
         // onto fGlobalMapStack and clears fGlobalIDConstraint map.
         public void startElement() {
-            // only clone the hashtable when there are elements
+            // only clone the map when there are elements
             if (fGlobalIDConstraintMap.size() > 0)
                 fGlobalMapStack.push(fGlobalIDConstraintMap.clone());
             else
@@ -4148,7 +4352,7 @@
             if (fGlobalMapStack.isEmpty()) {
                 return; // must be an invalid doc!
             }
-            Hashtable oldMap = (Hashtable) fGlobalMapStack.pop();
+            HashMap oldMap = (HashMap) fGlobalMapStack.pop();
             // return if there is no element
             if (oldMap == null) {
                 return;
@@ -4193,7 +4397,7 @@
                         } else {
                             uniqueValueStore.clear();
                         }
-                        fValueStores.addElement(uniqueValueStore);
+                        fValueStores.add(uniqueValueStore);
                         activateSelectorFor(icArray[i]);
                         break;
                     case (IdentityConstraint.IC_KEY) :
@@ -4208,7 +4412,7 @@
                         } else {
                             keyValueStore.clear();
                         }
-                        fValueStores.addElement(keyValueStore);
+                        fValueStores.add(keyValueStore);
                         activateSelectorFor(icArray[i]);
                         break;
                     case (IdentityConstraint.IC_KEYREF) :
@@ -4223,7 +4427,7 @@
                         } else {
                             keyRefValueStore.clear();
                         }
-                        fValueStores.addElement(keyRefValueStore);
+                        fValueStores.add(keyRefValueStore);
                         activateSelectorFor(icArray[i]);
                         break;
                 }
@@ -4267,7 +4471,7 @@
 
             int count = fValueStores.size();
             for (int i = 0; i < count; i++) {
-                ValueStoreBase valueStore = (ValueStoreBase) fValueStores.elementAt(i);
+                ValueStoreBase valueStore = (ValueStoreBase) fValueStores.get(i);
                 valueStore.endDocument();
             }
 
@@ -4295,7 +4499,7 @@
 
     // the purpose of this class is to enable IdentityConstraint,int
     // pairs to be used easily as keys in Hashtables.
-    protected class LocalIDKey {
+    protected static final class LocalIDKey {
 
         public IdentityConstraint fId;
         public int fDepth;
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSAttributeDecl.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSAttributeDecl.java	Wed Jul 05 20:04:39 2017 +0200
@@ -3,11 +3,12 @@
  * DO NOT REMOVE OR ALTER!
  */
 /*
- * Copyright 2001-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
@@ -32,6 +33,7 @@
 import com.sun.org.apache.xerces.internal.xs.XSNamespaceItem;
 import com.sun.org.apache.xerces.internal.xs.XSObjectList;
 import com.sun.org.apache.xerces.internal.xs.XSSimpleTypeDefinition;
+import com.sun.org.apache.xerces.internal.xs.XSValue;
 
 /**
  * The XML representation for an attribute declaration
@@ -211,4 +213,8 @@
                fDefault.itemValueTypes;
     }
 
+    public XSValue getValueConstraintValue() {
+        return fDefault;
+    }
+
 } // class XSAttributeDecl
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSAttributeUseImpl.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSAttributeUseImpl.java	Wed Jul 05 20:04:39 2017 +0200
@@ -3,11 +3,12 @@
  * DO NOT REMOVE OR ALTER!
  */
 /*
- * Copyright 1999-2002,2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
@@ -28,6 +29,7 @@
 import com.sun.org.apache.xerces.internal.xs.XSConstants;
 import com.sun.org.apache.xerces.internal.xs.XSNamespaceItem;
 import com.sun.org.apache.xerces.internal.xs.XSObjectList;
+import com.sun.org.apache.xerces.internal.xs.XSValue;
 
 /**
  * The XML representation for an attribute use
@@ -142,6 +144,10 @@
                fDefault.itemValueTypes;
     }
 
+    public XSValue getValueConstraintValue() {
+        return fDefault;
+    }
+
     /**
      * Optional. Annotations.
      */
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSComplexTypeDecl.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSComplexTypeDecl.java	Wed Jul 05 20:04:39 2017 +0200
@@ -3,11 +3,12 @@
  * DO NOT REMOVE OR ALTER!
  */
 /*
- * Copyright 2001-2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
@@ -77,7 +78,7 @@
     volatile XSCMValidator fCMValidator = null;
 
     // the content model that's sufficient for computing UPA
-    XSCMValidator fUPACMValidator = null;
+    volatile XSCMValidator fUPACMValidator = null;
 
     // list of annotations affiliated with this type
     XSObjectListImpl fAnnotations = null;
@@ -165,12 +166,28 @@
             fContentType == XSComplexTypeDecl.CONTENTTYPE_EMPTY) {
             return null;
         }
-        if (fCMValidator == null)
-            synchronized (this) {
-                if (fCMValidator == null) {
-                    fCMValidator = cmBuilder.getContentModel(this);
+        if (fCMValidator == null) {
+            fCMValidator = getContentModel(cmBuilder, false);
+        }
+        return fCMValidator;
+    }
+
+    public synchronized XSCMValidator getContentModel(CMBuilder cmBuilder, boolean forUPA) {
+        if (fCMValidator == null) {
+            if (forUPA) {
+                if (fUPACMValidator == null) {
+                    fUPACMValidator = cmBuilder.getContentModel(this, true);
+
+                    if (fUPACMValidator != null && !fUPACMValidator.isCompactedForUPA()) {
+                        fCMValidator = fUPACMValidator;
+                    }
                 }
+                return fUPACMValidator;
             }
+            else {
+                fCMValidator = cmBuilder.getContentModel(this, false);
+            }
+        }
         return fCMValidator;
     }
 
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSConstraints.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSConstraints.java	Wed Jul 05 20:04:39 2017 +0200
@@ -3,11 +3,12 @@
  * DO NOT REMOVE OR ALTER!
  */
 /*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
@@ -488,7 +489,7 @@
                 }
                 // 3. UPA
                 // get the content model and check UPA
-                XSCMValidator cm = types[j].getContentModel(cmBuilder);
+                XSCMValidator cm = types[j].getContentModel(cmBuilder, true);
                 further = false;
                 if (cm != null) {
                     try {
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSElementDecl.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSElementDecl.java	Wed Jul 05 20:04:39 2017 +0200
@@ -3,11 +3,12 @@
  * DO NOT REMOVE OR ALTER!
  */
 /*
- * Copyright 2001-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
@@ -34,6 +35,7 @@
 import com.sun.org.apache.xerces.internal.xs.XSNamespaceItem;
 import com.sun.org.apache.xerces.internal.xs.XSObjectList;
 import com.sun.org.apache.xerces.internal.xs.XSTypeDefinition;
+import com.sun.org.apache.xerces.internal.xs.XSValue;
 
 /**
  * The XML representation for an element declaration
@@ -384,4 +386,8 @@
                fDefault.itemValueTypes;
     }
 
+    public XSValue getValueConstraintValue() {
+        return fDefault;
+    }
+
 } // class XSElementDecl
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSElementDeclHelper.java	Wed Jul 05 20:04:39 2017 +0200
@@ -0,0 +1,34 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.sun.org.apache.xerces.internal.impl.xs;
+
+import com.sun.org.apache.xerces.internal.xni.QName;
+
+/**
+ * @xerces.internal
+ *
+ * @version $Id$
+ */
+public interface XSElementDeclHelper {
+
+    public XSElementDecl getGlobalElementDecl(QName element);
+}
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSModelImpl.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XSModelImpl.java	Wed Jul 05 20:04:39 2017 +0200
@@ -3,11 +3,12 @@
  * DO NOT REMOVE OR ALTER!
  */
 /*
- * Copyright 2002-2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
@@ -20,13 +21,6 @@
 
 package com.sun.org.apache.xerces.internal.impl.xs;
 
-import java.lang.reflect.Array;
-import java.util.AbstractList;
-import java.util.Iterator;
-import java.util.ListIterator;
-import java.util.NoSuchElementException;
-import java.util.Vector;
-
 import com.sun.org.apache.xerces.internal.impl.Constants;
 import com.sun.org.apache.xerces.internal.impl.xs.util.StringListImpl;
 import com.sun.org.apache.xerces.internal.impl.xs.util.XSNamedMap4Types;
@@ -39,6 +33,7 @@
 import com.sun.org.apache.xerces.internal.xs.XSAttributeGroupDefinition;
 import com.sun.org.apache.xerces.internal.xs.XSConstants;
 import com.sun.org.apache.xerces.internal.xs.XSElementDeclaration;
+import com.sun.org.apache.xerces.internal.xs.XSIDCDefinition;
 import com.sun.org.apache.xerces.internal.xs.XSModel;
 import com.sun.org.apache.xerces.internal.xs.XSModelGroupDefinition;
 import com.sun.org.apache.xerces.internal.xs.XSNamedMap;
@@ -48,6 +43,12 @@
 import com.sun.org.apache.xerces.internal.xs.XSObject;
 import com.sun.org.apache.xerces.internal.xs.XSObjectList;
 import com.sun.org.apache.xerces.internal.xs.XSTypeDefinition;
+import java.lang.reflect.Array;
+import java.util.AbstractList;
+import java.util.Iterator;
+import java.util.ListIterator;
+import java.util.NoSuchElementException;
+import java.util.Vector;
 
 /**
  * Implements XSModel:  a read-only interface that represents an XML Schema,
@@ -72,7 +73,7 @@
                                                   false,    // model group
                                                   false,    // particle
                                                   false,    // wildcard
-                                                  false,    // idc
+                                                  true,    // idc
                                                   true,     // notation
                                                   false,    // annotation
                                                   false,    // facet
@@ -326,6 +327,9 @@
                 case XSConstants.NOTATION_DECLARATION:
                     tables[i] = fGrammarList[i].fGlobalNotationDecls;
                     break;
+                case XSConstants.IDENTITY_CONSTRAINT:
+                    tables[i] = fGrammarList[i].fGlobalIDConstraintDecls;
+                    break;
                 }
             }
             // for complex/simple types, create a special implementation,
@@ -405,6 +409,9 @@
             case XSConstants.NOTATION_DECLARATION:
                 table = fGrammarList[i].fGlobalNotationDecls;
                 break;
+            case XSConstants.IDENTITY_CONSTRAINT:
+                table = fGrammarList[i].fGlobalIDConstraintDecls;
+                break;
             }
 
             // for complex/simple types, create a special implementation,
@@ -595,6 +602,40 @@
         return sg.getGlobalGroupDecl(name, loc);
     }
 
+    /**
+     * Convenience method. Returns a top-level model group definition.
+     *
+     * @param name      The name of the definition.
+     * @param namespace The namespace of the definition, otherwise null.
+     * @return A top-level model group definition definition or null if such
+     *         definition does not exist.
+     */
+    public XSIDCDefinition getIDCDefinition(String name, String namespace) {
+        SchemaGrammar sg = (SchemaGrammar)fGrammarMap.get(null2EmptyString(namespace));
+        if (sg == null) {
+            return null;
+        }
+        return (XSIDCDefinition)sg.fGlobalIDConstraintDecls.get(name);
+    }
+
+    /**
+     * Convenience method. Returns a top-level model group definition.
+     *
+     * @param name      The name of the definition.
+     * @param namespace The namespace of the definition, otherwise null.
+     * @param loc The schema location where the component was defined
+     * @return A top-level model group definition definition or null if such
+     *         definition does not exist.
+     */
+    public XSIDCDefinition getIDCDefinition(String name, String namespace,
+                                                          String loc) {
+        SchemaGrammar sg = (SchemaGrammar)fGrammarMap.get(null2EmptyString(namespace));
+        if (sg == null) {
+            return null;
+        }
+        return sg.getIDConstraintDecl(name, loc);
+    }
+
 
     /**
      * @see org.apache.xerces.xs.XSModel#getNotationDeclaration(String, String)
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/identity/Field.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/identity/Field.java	Wed Jul 05 20:04:39 2017 +0200
@@ -3,11 +3,12 @@
  * DO NOT REMOVE OR ALTER!
  */
 /*
- * Copyright 2001-2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
@@ -23,6 +24,7 @@
 import com.sun.org.apache.xerces.internal.impl.xpath.XPathException;
 import com.sun.org.apache.xerces.internal.impl.xs.util.ShortListImpl;
 import com.sun.org.apache.xerces.internal.util.SymbolTable;
+import com.sun.org.apache.xerces.internal.util.XMLChar;
 import com.sun.org.apache.xerces.internal.xni.NamespaceContext;
 import com.sun.org.apache.xerces.internal.xs.ShortList;
 import com.sun.org.apache.xerces.internal.xs.XSComplexTypeDefinition;
@@ -43,11 +45,11 @@
     //
 
     /** Field XPath. */
-    protected Field.XPath fXPath;
+    protected final Field.XPath fXPath;
 
 
     /** Identity constraint. */
-    protected IdentityConstraint fIdentityConstraint;
+    protected final IdentityConstraint fIdentityConstraint;
 
     //
     // Constructors
@@ -67,7 +69,7 @@
     /** Returns the field XPath. */
     public com.sun.org.apache.xerces.internal.impl.xpath.XPath getXPath() {
         return fXPath;
-    } // getXPath():com.sun.org.apache.xerces.internal.impl.v1.schema.identity.XPath
+    } // getXPath():org.apache.xerces.impl.v1.schema.identity.XPath
 
     /** Returns the identity constraint. */
     public IdentityConstraint getIdentityConstraint() {
@@ -77,8 +79,8 @@
     // factory method
 
     /** Creates a field matcher. */
-    public XPathMatcher createMatcher(FieldActivator activator, ValueStore store) {
-        return new Field.Matcher(fXPath, activator, store);
+    public XPathMatcher createMatcher(ValueStore store) {
+        return new Field.Matcher(fXPath, store);
     } // createMatcher(ValueStore):XPathMatcher
 
     //
@@ -110,15 +112,7 @@
         public XPath(String xpath,
                      SymbolTable symbolTable,
                      NamespaceContext context) throws XPathException {
-            // NOTE: We have to prefix the field XPath with "./" in
-            //       order to handle selectors such as "@attr" that
-            //       select the attribute because the fields could be
-            //       relative to the selector element. -Ac
-            //       Unless xpath starts with a descendant node -Achille Fokoue
-            //      ... or a / or a . - NG
-            super(((xpath.trim().startsWith("/") ||xpath.trim().startsWith("."))?
-                    xpath:"./"+xpath),
-                  symbolTable, context);
+            super(fixupXPath(xpath), symbolTable, context);
 
             // verify that only one attribute is selected per branch
             for (int i=0;i<fLocationPaths.length;i++) {
@@ -133,6 +127,73 @@
             }
         } // <init>(String,SymbolTable,NamespacesContext)
 
+        /** Fixup XPath expression. Avoid creating a new String if possible. */
+        private static String fixupXPath(String xpath) {
+
+            final int end = xpath.length();
+            int offset = 0;
+            boolean whitespace = true;
+            char c;
+
+            // NOTE: We have to prefix the field XPath with "./" in
+            //       order to handle selectors such as "@attr" that
+            //       select the attribute because the fields could be
+            //       relative to the selector element. -Ac
+            //       Unless xpath starts with a descendant node -Achille Fokoue
+            //      ... or a / or a . - NG
+            for (; offset < end; ++offset) {
+                c = xpath.charAt(offset);
+                if (whitespace) {
+                    if (!XMLChar.isSpace(c)) {
+                        if (c == '.' || c == '/') {
+                            whitespace = false;
+                        }
+                        else if (c != '|') {
+                            return fixupXPath2(xpath, offset, end);
+                        }
+                    }
+                }
+                else if (c == '|') {
+                    whitespace = true;
+                }
+            }
+            return xpath;
+
+        } // fixupXPath(String):String
+
+        private static String fixupXPath2(String xpath, int offset, final int end) {
+
+            StringBuffer buffer = new StringBuffer(end + 2);
+            for (int i = 0; i < offset; ++i) {
+                buffer.append(xpath.charAt(i));
+            }
+            buffer.append("./");
+
+            boolean whitespace = false;
+            char c;
+
+            for (; offset < end; ++offset) {
+                c = xpath.charAt(offset);
+                if (whitespace) {
+                    if (!XMLChar.isSpace(c)) {
+                        if (c == '.' || c == '/') {
+                            whitespace = false;
+                        }
+                        else if (c != '|') {
+                            buffer.append("./");
+                            whitespace = false;
+                        }
+                    }
+                }
+                else if (c == '|') {
+                    whitespace = true;
+                }
+                buffer.append(c);
+            }
+            return buffer.toString();
+
+        } // fixupXPath2(String, int, int):String
+
     } // class XPath
 
     /**
@@ -147,20 +208,19 @@
         // Data
         //
 
-        /** Field activator. */
-        protected FieldActivator fFieldActivator;
+        /** Value store for data values. */
+        protected final ValueStore fStore;
 
-        /** Value store for data values. */
-        protected ValueStore fStore;
+        /** A flag indicating whether the field is allowed to match a value. */
+        protected boolean fMayMatch = true;
 
         //
         // Constructors
         //
 
         /** Constructs a field matcher. */
-        public Matcher(Field.XPath xpath, FieldActivator activator, ValueStore store) {
+        public Matcher(Field.XPath xpath, ValueStore store) {
             super(xpath);
-            fFieldActivator = activator;
             fStore = store;
         } // <init>(Field.XPath,ValueStore)
 
@@ -179,11 +239,11 @@
                 fStore.reportError(code,
                     new Object[]{fIdentityConstraint.getElementName(), fIdentityConstraint.getIdentityConstraintName()});
             }
-            fStore.addValue(Field.this, actualValue, convertToPrimitiveKind(valueType), convertToPrimitiveKind(itemValueType));
+            fStore.addValue(Field.this, fMayMatch, actualValue, convertToPrimitiveKind(valueType), convertToPrimitiveKind(itemValueType));
             // once we've stored the value for this field, we set the mayMatch
-            // member to false so that, in the same scope, we don't match any more
+            // member to false so that in the same scope, we don't match any more
             // values (and throw an error instead).
-            fFieldActivator.setMayMatch(Field.this, Boolean.FALSE);
+            fMayMatch = false;
         } // matched(String)
 
         private short convertToPrimitiveKind(short valueType) {
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/identity/FieldActivator.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/identity/FieldActivator.java	Wed Jul 05 20:04:39 2017 +0200
@@ -3,11 +3,12 @@
  * DO NOT REMOVE OR ALTER!
  */
 /*
- * Copyright 2001,2002,2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
@@ -51,8 +52,6 @@
     /**
      * Request to activate the specified field. This method returns the
      * matcher for the field.
-     * It's also important for the implementor to ensure that it marks whether a Field
-     * is permitted to match a value--that is, to call the setMayMatch(Field, Boolean) method.
      *
      * @param field The field to activate.
      * @param initialDepth the 0-indexed depth in the instance document at which the Selector began to match.
@@ -60,24 +59,6 @@
     public XPathMatcher activateField(Field field, int initialDepth);
 
     /**
-     * Sets whether the given field is permitted to match a value.
-     * This should be used to catch instance documents that try
-     * and match a field several times in the same scope.
-     *
-     * @param field The field that may be permitted to be matched.
-     * @param state Boolean indiciating whether the field may be matched.
-     */
-    public void setMayMatch(Field field, Boolean state);
-
-    /**
-     * Returns whether the given field is permitted to match a value.
-     *
-     * @param field The field that may be permitted to be matched.
-     * @return Boolean indicating whether the field may be matched.
-     */
-    public Boolean mayMatch(Field field);
-
-    /**
      * Ends the value scope for the specified identity constraint.
      *
      * @param identityConstraint The identity constraint.
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/identity/ValueStore.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/identity/ValueStore.java	Wed Jul 05 20:04:39 2017 +0200
@@ -3,11 +3,12 @@
  * DO NOT REMOVE OR ALTER!
  */
 /*
- * Copyright 2001, 2002,2004,2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
@@ -54,9 +55,12 @@
      * @param field The field associated to the value. This reference
      *              is used to ensure that each field only adds a value
      *              once within a selection scope.
+     * @param mayMatch a flag indiciating whether the field may be matched.
      * @param actualValue The value to add.
+     * @param valueType Type of the value to add.
+     * @param itemValueType If the value is a list, a list of types for each of the values in the list.
      */
-    public void addValue(Field field, Object actualValue, short valueType, ShortList itemValueType);
+    public void addValue(Field field, boolean mayMatch, Object actualValue, short valueType, ShortList itemValueType);
 
     /**
      * Since the valueStore will have access to an error reporter, this
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/models/CMBuilder.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/models/CMBuilder.java	Wed Jul 05 20:04:39 2017 +0200
@@ -1,13 +1,13 @@
 /*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2006, 2009, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * Copyright 2001-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
@@ -65,9 +65,10 @@
      * Get content model for the a given type
      *
      * @param typeDecl  get content model for which complex type
+     * @param forUPA    a flag indicating whether it is for UPA
      * @return          a content model validator
      */
-    public XSCMValidator getContentModel(XSComplexTypeDecl typeDecl) {
+    public XSCMValidator getContentModel(XSComplexTypeDecl typeDecl, boolean forUPA) {
 
         // for complex type with empty or simple content,
         // there is no content model validator
@@ -92,7 +93,7 @@
             cmValidator = createAllCM(particle);
         }
         else {
-            cmValidator = createDFACM(particle);
+            cmValidator = createDFACM(particle, forUPA);
         }
 
         //now we are throught building content model and have passed sucessfully of the nodecount check
@@ -124,11 +125,11 @@
         return allContent;
     }
 
-    XSCMValidator createDFACM(XSParticleDecl particle) {
+    XSCMValidator createDFACM(XSParticleDecl particle, boolean forUPA) {
         fLeafCount = 0;
         fParticleCount = 0;
         // convert particle tree to CM tree
-        CMNode node = useRepeatingLeafNodes(particle) ? buildCompactSyntaxTree(particle) : buildSyntaxTree(particle, true);
+        CMNode node = useRepeatingLeafNodes(particle) ? buildCompactSyntaxTree(particle) : buildSyntaxTree(particle, forUPA, true);
         if (node == null)
             return null;
         // build DFA content model from the CM tree
@@ -141,10 +142,31 @@
     // 3. convert model groups (a, b, c, ...) or (a | b | c | ...) to
     //    binary tree: (((a,b),c),...) or (((a|b)|c)|...)
     // 4. make sure each leaf node (XSCMLeaf) has a distinct position
-    private CMNode buildSyntaxTree(XSParticleDecl particle, boolean optimize) {
+    private CMNode buildSyntaxTree(XSParticleDecl particle, boolean forUPA, boolean optimize) {
 
         int maxOccurs = particle.fMaxOccurs;
         int minOccurs = particle.fMinOccurs;
+
+        boolean compactedForUPA = false;
+        if (forUPA) {
+            // When doing UPA, we reduce the size of the minOccurs/maxOccurs values to make
+            // processing the DFA faster.  For UPA the exact values don't matter.
+            if (minOccurs > 1) {
+                if (maxOccurs > minOccurs || particle.getMaxOccursUnbounded()) {
+                    minOccurs = 1;
+                    compactedForUPA = true;
+                }
+                else { // maxOccurs == minOccurs
+                    minOccurs = 2;
+                    compactedForUPA = true;
+                }
+            }
+            if (maxOccurs > 1) {
+                maxOccurs = 2;
+                compactedForUPA = true;
+            }
+        }
+
         short type = particle.fType;
         CMNode nodeRet = null;
 
@@ -159,6 +181,9 @@
             nodeRet = fNodeFactory.getCMLeafNode(particle.fType, particle.fValue, fParticleCount++, fLeafCount++);
             // (task 2) expand occurrence values
             nodeRet = expandContentModel(nodeRet, minOccurs, maxOccurs, optimize);
+            if (nodeRet != null) {
+                nodeRet.setIsCompactUPAModel(compactedForUPA);
+            }
         }
         else if (type == XSParticleDecl.PARTICLE_MODELGROUP) {
             // (task 1,3) convert model groups to binary trees
@@ -178,12 +203,14 @@
             for (int i = 0; i < group.fParticleCount; i++) {
                 // first convert each child to a CM tree
                 temp = buildSyntaxTree(group.fParticles[i],
+                        forUPA,
                         optimize &&
                         minOccurs == 1 && maxOccurs == 1 &&
                         (group.fCompositor == XSModelGroupImpl.MODELGROUP_SEQUENCE ||
                          group.fParticleCount == 1));
                 // then combine them using binary operation
                 if (temp != null) {
+                    compactedForUPA |= temp.isCompactedForUPA();
                     if (nodeRet == null) {
                         nodeRet = temp;
                     }
@@ -205,6 +232,7 @@
                     nodeRet = fNodeFactory.getCMUniOpNode(XSParticleDecl.PARTICLE_ZERO_OR_ONE, nodeRet);
                 }
                 nodeRet = expandContentModel(nodeRet, minOccurs, maxOccurs, false);
+                nodeRet.setIsCompactUPAModel(compactedForUPA);
             }
         }
 
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/models/CMNodeFactory.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/models/CMNodeFactory.java	Wed Jul 05 20:04:39 2017 +0200
@@ -1,6 +1,5 @@
 /*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Copyright 2003-2004 The Apache Software Foundation.
@@ -73,14 +72,11 @@
     public CMNodeFactory() {
     }
 
-    public void reset(XMLComponentManager componentManager){
+    public void reset(XMLComponentManager componentManager) {
         fErrorReporter = (XMLErrorReporter)componentManager.getProperty(ERROR_REPORTER);
         try {
             fSecurityManager = (XMLSecurityManager)componentManager.getProperty(SECURITY_MANAGER);
-            //we are setting the limit of number of nodes to 3times the maxOccur value..
-            if(fSecurityManager != null){
-                maxNodeLimit = fSecurityManager.getLimit(XMLSecurityManager.Limit.MAX_OCCUR_NODE_LIMIT) * MULTIPLICITY ;
-            }
+            reset();
         }
         catch (XMLConfigurationException e) {
             fSecurityManager = null;
@@ -88,6 +84,13 @@
 
     }//reset()
 
+    public void reset() {
+        // we are setting the limit of number of nodes to 3 times the maxOccurs value.
+        if (fSecurityManager != null) {
+            maxNodeLimit = fSecurityManager.getLimit(XMLSecurityManager.Limit.MAX_OCCUR_NODE_LIMIT) * MULTIPLICITY ;
+        }
+    }
+
     public CMNode getCMLeafNode(int type, Object leaf, int id, int position) {
         return new XSCMLeaf(type, leaf, id, position) ;
     }
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/models/XSAllCM.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/models/XSAllCM.java	Wed Jul 05 20:04:39 2017 +0200
@@ -1,13 +1,13 @@
 /*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2006, 2009, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
@@ -25,8 +25,6 @@
 import com.sun.org.apache.xerces.internal.impl.xs.SubstitutionGroupHandler;
 import com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaException;
 import com.sun.org.apache.xerces.internal.impl.xs.XSConstraints;
-
-import java.util.Vector;
 import java.util.ArrayList;
 
 /**
@@ -202,16 +200,17 @@
      * have been seen.
      *
      * @param state  the current state
-     * @return       a Vector whose entries are instances of
+     * @return       a list whose entries are instances of
      *               either XSWildcardDecl or XSElementDecl.
      */
-    public Vector whatCanGoHere(int[] state) {
-        Vector ret = new Vector();
+    public ArrayList whatCanGoHere(int[] state) {
+        ArrayList ret = new ArrayList();
         for (int i = 0; i < fNumElements; i++) {
             // we only try to look for a matching decl if we have not seen
             // this element yet.
-            if (state[i+1] == STATE_START)
-                ret.addElement(fAllElements[i]);
+            if (state[i+1] == STATE_START) {
+                ret.add(fAllElements[i]);
+            }
         }
         return ret;
     }
@@ -220,4 +219,15 @@
         return null;
     }
 
+    public int [] occurenceInfo(int[] state) {
+        return null;
+    }
+
+    public String getTermName(int termId) {
+        return null;
+    }
+
+    public boolean isCompactedForUPA() {
+        return false;
+    }
 } // class XSAllCM
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/models/XSCMValidator.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/models/XSCMValidator.java	Wed Jul 05 20:04:39 2017 +0200
@@ -1,13 +1,13 @@
 /*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2006, 2009, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * Copyright 2001-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
@@ -23,8 +23,6 @@
 import com.sun.org.apache.xerces.internal.xni.QName;
 import com.sun.org.apache.xerces.internal.impl.xs.SubstitutionGroupHandler;
 import com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaException;
-
-import java.util.Vector;
 import java.util.ArrayList;
 
 /**
@@ -87,24 +85,60 @@
      * have been seen.
      *
      * @param state  the current state
-     * @return       a Vector whose entries are instances of
+     * @return       a list whose entries are instances of
      *               either XSWildcardDecl or XSElementDecl.
      */
-    public Vector whatCanGoHere(int[] state);
+    public ArrayList whatCanGoHere(int[] state);
 
     /**
      * Used by constant space algorithm for a{n,m} for n > 1 and
      * m <= unbounded. Called by a validator if validation of
      * countent model succeeds after subsuming a{n,m} to a*
      * (or a+) to check the n and m bounds.
-     * Returns <code>null</code> if validation of bounds is
+     *
+     * @return <code>null</code> if validation of bounds is
      * successful. Returns a list of strings with error info
      * if not. Even entries in list returned are error codes
      * (used to look up properties) and odd entries are parameters
      * to be passed when formatting error message. Each parameter
-     * is associated with the error code that preceeds it in
+     * is associated with the error code that proceeds it in
      * the list.
      */
     public ArrayList checkMinMaxBounds();
 
+     /**
+     * <p>Returns an array containing information about the current repeating term
+     * or <code>null</code> if no occurrence counting was being performed at the
+     * current state.</p>
+     *
+     * <p>If an array is returned it will have a length == 4 and will contain:
+     *  <ul>
+     *   <li>a[0] :: min occurs</li>
+     *   <li>a[1] :: max occurs</li>
+     *   <li>a[2] :: current value of the counter</li>
+     *   <li>a[3] :: identifier for the repeating term</li>
+     *  </ul>
+     * </p>
+     *
+     * @param state the current state
+     * @return an array containing information about the current repeating term
+     */
+    public int [] occurenceInfo(int[] state);
+
+    /**
+     * Returns the name of the term (element or wildcard) for the given identifier.
+     *
+     * @param termId identifier for the element declaration or wildcard
+     * @return the name of the element declaration or wildcard
+     */
+    public String getTermName(int termId);
+
+    /**
+     * Checks if this content model has had its min/maxOccurs values reduced for
+     * purposes of speeding up UPA.  If so, this content model should not be used
+     * for any purpose other than checking unique particle attribution
+     *
+     * @return a boolean that says whether this content has been compacted for UPA
+     */
+    public boolean isCompactedForUPA();
 } // XSCMValidator
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/models/XSDFACM.java	Thu Oct 16 12:02:03 2014 -0700
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/models/XSDFACM.java	Wed Jul 05 20:04:39 2017 +0200
@@ -1,13 +1,13 @@
 /*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2006, 2009, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
@@ -31,8 +31,6 @@
 import com.sun.org.apache.xerces.internal.impl.xs.XSWildcardDecl;
 import com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaException;
 import com.sun.org.apache.xerces.internal.impl.xs.XSConstraints;
-
-import java.util.Vector;
 import java.util.ArrayList;
 import java.util.HashMap;
 
@@ -166,6 +164,8 @@
      */
     private int fTransTableSize = 0;
 
+    private boolean fIsCompactedForUPA;
+
     /**
      * Array of counters for all the for elements (or wildcards)
      * of the form a{n,m} where n > 1 and m <= unbounded. Used
@@ -1165,10 +1165,10 @@
      * have been seen.
      *
      * @param state  the current state
-     * @return       a Vector whose entries are instances of
+     * @return       a list whose entries are instances of
      *               either XSWildcardDecl or XSElementDecl.
      */
-    public Vector whatCanGoHere(int[] state) {
+    public ArrayList whatCanGoHere(int[] state) {
         int curState = state[0];
         if (curState < 0)
             curState = state[1];
@@ -1176,7 +1176,7 @@
                 fCountingStates[curState] : null;
         int count = state[2];
 
-        Vector ret = new Vector();
+        ArrayList ret = new ArrayList();
         for (int elemIndex = 0; elemIndex < fElemMapSize; elemIndex++) {
             int nextState = fTransTable[curState][elemIndex];
             if (nextState != -1) {
@@ -1196,7 +1196,7 @@
                         continue;
                     }
                 }
-                ret.addElement(fElemMap[elemIndex]);
+                ret.add(fElemMap[elemIndex]);
             }
         }
         return ret;
@@ -1231,11 +1231,38 @@
             }
             if (maxOccurs != -1 && count > maxOccurs) {
                 if (result == null) result = new ArrayList();
-                result.add("cvc-complex-type.2.4.e");
+                result.add("cvc-complex-type.2.4.d.1");
                 result.add("{" + fElemMap[elemIndex] + "}");
             }
         }
         return result;
     }
 
+    public int [] occurenceInfo(int[] state) {
+        if (fCountingStates != null) {
+            int curState = state[0];
+            if (curState < 0) {
+                curState = state[1];
+            }
+            Occurence o = fCountingStates[curState];
+            if (o != null) {
+                int [] occurenceInfo = new int[4];
+                occurenceInfo[0] = o.minOccurs;
+                occurenceInfo[1] = o.maxOccurs;
+                occurenceInfo[2] = state[2];
+                occurenceInfo[3] = o.elemIndex;
+                return occurenceInfo;
+            }
+        }
+        return null;
+    }
+