Merge tag jb8u202-b1483.39

Change-Id: I80a7207d2b76081d4fa5167ef038b235e3614397
diff --git a/.hgtags b/.hgtags
index f6bfb8d..07e7624 100644
--- a/.hgtags
+++ b/.hgtags
@@ -931,6 +931,8 @@
 b28d012a24cab8f4ceeee0c9d3252969757423ed jdk8u112-b15
 e134dc1879b72124e478be01680b0646a2fbf585 jdk8u112-b16
 87440ed4e1de7753a436f957d35555d8b4e26f1d jdk8u112-b31
+ba25f5833a128b8062e597f794efda26b30f095d jdk8u112-b32
+919ffdca10c2721ee0f6f233e704709174556510 jdk8u112-b33
 3b0e5f01891f5ebbf67797b1aae786196f1bb4f6 jdk8u121-b00
 251a2493b1857f2ff4f11eab2dfd8b2fe8ed441b jdk8u121-b01
 70c4a50f576a01ec975d0a02b3642ee33db39ed8 jdk8u121-b02
@@ -945,6 +947,146 @@
 11f91811e4d7e5ddfaf938dcf386ec8fe5bf7b7c jdk8u121-b11
 b132b08b28bf23a26329928cf6b4ffda5857f4d3 jdk8u121-b12
 90f94521c3515e5f27af0ab9b31d036e88bb322a jdk8u121-b13
+351bf1d4ff9a41137f91e2ec97ec59ed29a38d8b jdk8u121-b31
+41daac438a2ac5a80755dc3de88b76e4ac66750a jdk8u121-b32
+eb9e617d6f64d4ad689feac0707b5e4335b00ce2 jdk8u121-b33
+c60b0994e8eee152666252c3ba4105db65c004db jdk8u121-b34
+0612a789929b88612509668bea4b3138613e91e4 jdk8u121-b35
+0ea269e49511a890e6fabfd468638dd1c0ed0be3 jdk8u121-b36
+c0a1ba0df20fda10ddb8599e888eb56ad98b3874 jdk8u131-b00
+0b85ccd6240991e1a501602ff5addec6b88ae0af jdk8u131-b01
+ef90c721a4e59b01ca36f25619010a1afe9ed4d5 jdk8u131-b02
+0ca47d0811b01ecf8651b6045a1e33a4a9bed0ee jdk8u131-b03
+dab1d597165207e14b6886b1823c1e990bc776a3 jdk8u131-b04
+c965fc1aa840a0903709ad69aa0e2100330ccd84 jdk8u131-b05
+6e4cfbc7534f83902692132efb61683528c04a59 jdk8u131-b06
+5b3cb4fbdbc7bdeb7c78a8703c3084ce068f6691 jdk8u131-b07
+db221c0a423e776bec5c3198d11d3f26827bd786 jdk8u131-b08
+56e71d16083904ceddfdd1d66312582a42781646 jdk8u131-b09
+1da23ae49386608550596502d90a381ee6c1dfaa jdk8u131-b10
+829ea9b92cda9545652f1b309f56c57383024ebb jdk8u131-b11
+41e0713bcca27cef5d6a9afd44c7ca4811937713 jdk8u131-b31
+e318654a4fa352a06935dd56eebf88ae387b31f9 jdk8u131-b32
+32998fc932dc58c6bbac185cc17d2752fa6dba4c jdk8u131-b33
+50b3fa6791f46bc582528bdc7f6311b3b6832c51 jdk8u131-b34
+692bc6b674dcab72453de08ee9da0856a7e41c0f jdk8u141-b00
+0cee0db0180b64655751e7058c251103f9660f85 jdk8u141-b01
+82435799636c8b50a090aebcb5af49946afa7bb5 jdk8u141-b02
+678f11cc769eb79d35d49a94c769304df67a9cef jdk8u141-b03
+62b0b4a31b44e8b159bff106c04ecfabc9d78d9b jdk8u141-b04
+53a48dc8e4418ed422c69361193add798cb4ed55 jdk8u141-b05
+4b7067065b0ad08c41a6334b44877319cbb2de54 jdk8u141-b06
+42f196fd7c589e439c4e6d86b7d845ff024cfe45 jdk8u141-b07
+37ba410ffd431c76961255b87398f6ace7b6794f jdk8u141-b08
+b23c5879a33cf2c2e7c3e2cdfb0285bb7e64198e jdk8u141-b09
+1a3f8a55df45dd79cb566d172e925faa464534f0 jdk8u141-b10
+de803a292be4add77fd8a1e034481f0692c89f95 jdk8u141-b11
+d6e7c7d2c6f69906b4cb643a6813eccba0de988f jdk8u141-b12
+df6af363337eff5b22ae7940b0981231fdf5dfb4 jdk8u141-b13
+3a1543e089c32592be9c201c6e021295fbf5fdc1 jdk8u141-b14
+23f1790147d838ddb1133cc79dc08e7c9ba5ab44 jdk8u141-b15
+eea89df81a8e414813d921eeeeef9b6795f56698 jdk8u144-b00
+db36f4d498b1bde975700a800b5ce732941c04b7 jdk8u144-b01
+9ffa0d7ed932045a0b4ceb095fb52444eed39c1b jdk8u141-b31
+ae8cae699f62b845703c891e0e7633e2089a3ec4 jdk8u141-b32
+eea89df81a8e414813d921eeeeef9b6795f56698 jdk8u144-b00
+db36f4d498b1bde975700a800b5ce732941c04b7 jdk8u144-b01
+f5ded236c4130415259efc3234a92cc69fd7d2c5 jdk8u144-b31
+d89d36d67c9417151b470eb8254504bd2a90cc1e jdk8u144-b32
+3d505f6c7af1c522d03644eda168d77732a5e7e5 jdk8u144-b33
+0becf604dfcc98fb13a17121a43bef7fc77a9ed7 jdk8u144-b34
+2d5100bddeb80cf767485b787fc3051311e3d7b9 jdk8u151-b00
+596b584c68b73ec635347807571463580deb955f jdk8u151-b01
+1f6f436360d5cd375b806aec1c78abb8fcb4e5f6 jdk8u151-b02
+0aaeb48ae39e4fc558caf1b0c7ee504a49fec441 jdk8u151-b03
+e48302d521d59c2fe62f874f1f5d34bc46517da7 jdk8u151-b04
+507af6ef977a5d0306a8723dec66e34befc1ae81 jdk8u151-b05
+e1dc36cddcbc36b78e3d0558f87bbf459191e479 jdk8u151-b06
+e2a930243efa63b0a789e85a523e69574d53ac92 jdk8u151-b07
+158904fa31b28f1e027dc5b5a833ee673e89a84b jdk8u151-b08
+8b0169692abbf8fb7972920cd79cee7dcab959c3 jdk8u151-b09
+e352e54382928eb8d5ec70455ef251973c332ccb jdk8u151-b10
+0f06584f52ffc8627b78f4d461a3eba2b703a8f7 jdk8u151-b11
+856e341587d52114a753e48674517e7e307fceff jdk8u151-b12
+5aa8c4ca51f0e666d368a4f119ed734d3ac59d7c jdk8u122-b00
+2198ef7e1c1702b3506b95b5d8c886ad5a12bbe5 jdk8u122-b01
+58d961f47dd4ee1d516512b7744e0f1fc83d8f52 jdk8u122-b02
+b0f2296a0bc85e400e4389306219fcfd2076c9b5 jdk8u122-b03
+b0f2296a0bc85e400e4389306219fcfd2076c9b5 jdk8u122-b03
+0000000000000000000000000000000000000000 jdk8u122-b03
+0000000000000000000000000000000000000000 jdk8u122-b03
+65601f3eae818a49a5246c73fb4872f5467a230c jdk8u122-b03
+fb8ea28efb05cd89e5416665232165ef0d2eef29 jdk8u122-b04
+92aff007ba7fd9b69adcf212c5280b9152f3d667 jdk8u132-b00
+8cc092b845ce5dae4fa450d23d8bb9abf509e1a0 jdk8u152-b00
+77d9c9da7188ef4d5fe9c409362d63911c4794e8 jdk8u152-b01
+60d621df6c586e325c0a2cf045c8fc68b7f979fe jdk8u152-b02
+d63e731a896c711b8e0c30ac9ae2d900d4e024f6 jdk8u152-b03
+0bd600d6d77b5b41780074bcbfa133032dadf657 jdk8u152-b04
+68758c5ab0c1ef01e89bea8a9b799714831a177f jdk8u152-b05
+98fb3d75fe567bda30a3667c58a9f83ad2acbdf3 jdk8u152-b06
+4af38194b12580bdc885ab3873d7efefa990f543 jdk8u152-b07
+285fcd09ae9994ac836a2759f6615520b2568432 jdk8u152-b08
+70f18ab733f55856cbd880fe8ba3034ff4d7265d jdk8u152-b09
+39967c81d3f3b8d20584d1400e6f4b2490f0c822 jdk8u152-b10
+cbb6bc4b8c867ea69962fd5b6c79ffe3aa9fd77d jdk8u152-b11
+cdfe7ec6f29293d7c2f64239518e8947733ad85c jdk8u152-b12
+3dd92151df1b3b7c21756f241b49607024b6fe5a jdk8u152-b13
+0a9d8db98fc5f0302da6520ba329f41baa092ae0 jdk8u152-b14
+c1bf165d3b27e864a9f8eec5bb0c1e746a972ad5 jdk8u152-b15
+98b4b0661837817cc39047000e1a7efa6015af7c jdk8u152-b16
+91894ffc746c1681172aaa37e2cf5bff69560f20 jdk8u152-b31
+d278f122e65dfb5d239ed420a534df75f527a504 jdk8u152-b32
+c066fe30d0a141b14ab7788cbbd35eba11196e72 jdk8u152-b33
+12a0cebfae93a638dc69a34f8276e1ef43b11b7a jdk8u152-b34
+f6719c3d02787da6e232703f61efc931ead7683b jdk8u152-b35
+2d5100bddeb80cf767485b787fc3051311e3d7b9 jdk8u151-b00
+596b584c68b73ec635347807571463580deb955f jdk8u151-b01
+1f6f436360d5cd375b806aec1c78abb8fcb4e5f6 jdk8u151-b02
+0aaeb48ae39e4fc558caf1b0c7ee504a49fec441 jdk8u151-b03
+e48302d521d59c2fe62f874f1f5d34bc46517da7 jdk8u151-b04
+507af6ef977a5d0306a8723dec66e34befc1ae81 jdk8u151-b05
+e1dc36cddcbc36b78e3d0558f87bbf459191e479 jdk8u151-b06
+5aa8c4ca51f0e666d368a4f119ed734d3ac59d7c jdk8u122-b00
+2198ef7e1c1702b3506b95b5d8c886ad5a12bbe5 jdk8u122-b01
+58d961f47dd4ee1d516512b7744e0f1fc83d8f52 jdk8u122-b02
+b0f2296a0bc85e400e4389306219fcfd2076c9b5 jdk8u122-b03
+b0f2296a0bc85e400e4389306219fcfd2076c9b5 jdk8u122-b03
+0000000000000000000000000000000000000000 jdk8u122-b03
+0000000000000000000000000000000000000000 jdk8u122-b03
+65601f3eae818a49a5246c73fb4872f5467a230c jdk8u122-b03
+fb8ea28efb05cd89e5416665232165ef0d2eef29 jdk8u122-b04
+92aff007ba7fd9b69adcf212c5280b9152f3d667 jdk8u132-b00
+8cc092b845ce5dae4fa450d23d8bb9abf509e1a0 jdk8u152-b00
+77d9c9da7188ef4d5fe9c409362d63911c4794e8 jdk8u152-b01
+60d621df6c586e325c0a2cf045c8fc68b7f979fe jdk8u152-b02
+d63e731a896c711b8e0c30ac9ae2d900d4e024f6 jdk8u152-b03
+0bd600d6d77b5b41780074bcbfa133032dadf657 jdk8u152-b04
+68758c5ab0c1ef01e89bea8a9b799714831a177f jdk8u152-b05
+98fb3d75fe567bda30a3667c58a9f83ad2acbdf3 jdk8u152-b06
+4af38194b12580bdc885ab3873d7efefa990f543 jdk8u152-b07
+285fcd09ae9994ac836a2759f6615520b2568432 jdk8u152-b08
+70f18ab733f55856cbd880fe8ba3034ff4d7265d jdk8u152-b09
+5aa8c4ca51f0e666d368a4f119ed734d3ac59d7c jdk8u122-b00
+2198ef7e1c1702b3506b95b5d8c886ad5a12bbe5 jdk8u122-b01
+58d961f47dd4ee1d516512b7744e0f1fc83d8f52 jdk8u122-b02
+b0f2296a0bc85e400e4389306219fcfd2076c9b5 jdk8u122-b03
+b0f2296a0bc85e400e4389306219fcfd2076c9b5 jdk8u122-b03
+0000000000000000000000000000000000000000 jdk8u122-b03
+0000000000000000000000000000000000000000 jdk8u122-b03
+65601f3eae818a49a5246c73fb4872f5467a230c jdk8u122-b03
+fb8ea28efb05cd89e5416665232165ef0d2eef29 jdk8u122-b04
+92aff007ba7fd9b69adcf212c5280b9152f3d667 jdk8u132-b00
+8cc092b845ce5dae4fa450d23d8bb9abf509e1a0 jdk8u152-b00
+77d9c9da7188ef4d5fe9c409362d63911c4794e8 jdk8u152-b01
+60d621df6c586e325c0a2cf045c8fc68b7f979fe jdk8u152-b02
+d63e731a896c711b8e0c30ac9ae2d900d4e024f6 jdk8u152-b03
+0bd600d6d77b5b41780074bcbfa133032dadf657 jdk8u152-b04
+68758c5ab0c1ef01e89bea8a9b799714831a177f jdk8u152-b05
+98fb3d75fe567bda30a3667c58a9f83ad2acbdf3 jdk8u152-b06
+4af38194b12580bdc885ab3873d7efefa990f543 jdk8u152-b07
+02d5e7b64b288429f3836dcfb8ac304774775965 jdk8u161-b00
+0aaeb48ae39e4fc558caf1b0c7ee504a49fec441 jdk8u151-b03
 5aa8c4ca51f0e666d368a4f119ed734d3ac59d7c jdk8u122-b00
 2198ef7e1c1702b3506b95b5d8c886ad5a12bbe5 jdk8u122-b01
 58d961f47dd4ee1d516512b7744e0f1fc83d8f52 jdk8u122-b02
@@ -986,5 +1128,120 @@
 d63e731a896c711b8e0c30ac9ae2d900d4e024f6 jdk8u152-b03
 0bd600d6d77b5b41780074bcbfa133032dadf657 jdk8u152-b04
 68758c5ab0c1ef01e89bea8a9b799714831a177f jdk8u152-b05
+98fb3d75fe567bda30a3667c58a9f83ad2acbdf3 jdk8u152-b06
+02d5e7b64b288429f3836dcfb8ac304774775965 jdk8u161-b00
+432f92e99174244479f0011169baf828368506c7 jdk8u161-b01
+a17bab9405474602b18cd62e060a09b17d6413ac jdk8u161-b02
+4cf0fd9f1fe53e3140413623d72f6a00e587830d jdk8u161-b03
+4022d56fc6b83eab7213c92e1277e7ce9753a21f jdk8u161-b04
+37e8b74faccc8e795be1a171033487e2270dc605 jdk8u161-b05
+a769f683df5daa694fd5124c4825a9c6ad9d72d2 jdk8u161-b06
+3eb5127534005ac1f6f50db95adcff7b19a7e636 jdk8u161-b07
+796d399766f27aa0724a7951ee319c5e490a32cb jdk8u161-b08
+6e5cabb7995ef8357c5c61c16af659bf7cc1d2ff jdk8u161-b09
+b9a9aa038ad84a3fe6c91e27e359b95da8eb8629 jdk8u161-b10
+b1606443958a9a64020b596327ff586ca5c8ae1d jdk8u161-b11
+210f7ef62595c608d69fc8bf442a4f5b0bceddb5 jdk8u161-b12
 7b96cfeed22242bb68a387d1680e602e37e48050 jdk8u162-b00
 92693f9dd704467ddd5fbae5a5908c1713a08ee0 jdk8u162-b01
+741b7a6743c0e02eae7e4a864f378fa1df0da112 jdk8u162-b02
+e0c000e8eb7588501637873c6dcd255306c9c5cc jdk8u162-b03
+18366fa39fe0839291b672ce4f8f12605d88b0d0 jdk8u162-b04
+e34428c12886692f9d562263a10bc72c8d222613 jdk8u162-b05
+cd7f8ee4553d0f884ddc150ceefcb5b48b12ca21 jdk8u162-b06
+7be95092ed8b37b7b55ae341c8d62d377d7310df jdk8u162-b07
+080cfab193208aeb198f5b98841782fbf51ab851 jdk8u162-b08
+02f9409295f9ea7350cc2d25eeabf3c2b13b1df6 jdk8u162-b09
+c3618e1cdefdda6c262f082791bfd988e0e9d9c9 jdk8u162-b10
+39e2895b795aded8b584626fb019d35f12e9d1e7 jdk8u162-b11
+69aec2ca5d905dde1d0f29a89076d02a531808a3 jdk8u162-b12
+caac74fe3cfa9a8c859c28c97d1046a58252af27 jdk8u162-b31
+c9b7abadf150328d2187de05b9e8a9cba2486e47 jdk8u162-b32
+e8041f2ec96eb6a41307732e6cf6ed90901438ae jdk8u162-b33
+bf2e8b1e8e8e6bc1f9b9475de54ba0329a6b24b1 jdk8u162-b34
+9b3f207379cf6ecfb8603640269e31ff4e064294 jdk8u162-b35
+d2ebd6530396b0afc700cd1a8eaf1f7a7f9fce8d jdk8u162-b36
+700ad8745f3fdc5ba3702616fc5ed6a6248dfa78 jdk8u162-b37
+405800ccc4c7b81475b01392f2145cc3675d1f86 jdk8u162-b38
+a17bab9405474602b18cd62e060a09b17d6413ac jdk8u171-b00
+ebfd57cc21e6b7f0c22b17c666b6b28c9340e207 jdk8u171-b01
+1acd7c1b80241def8fac90f70b0df16356adad47 jdk8u171-b02
+5587cde50bbc2aa031aefb47eaa36b041f5e7c4b jdk8u181-b00
+5587cde50bbc2aa031aefb47eaa36b041f5e7c4b jdk8u171-b03
+99ef466523302cfbd00496cf6575a00c8637b884 jdk8u171-b04
+08326a76b14888908523cf2bb1105de63b43544d jdk8u171-b05
+4e1445535b6d9c25ed34aba2768139da283847d0 jdk8u171-b06
+fd0e42431b94c889b3fea8d8aad048f51d559761 jdk8u171-b07
+56123fdca84a3b253b8ea6f72be85bd2ebf39fd0 jdk8u171-b08
+4fefe015a728955c9c25ef79e51501b68839ae75 jdk8u171-b09
+6d890180aeb43ee727b2f2cc0952ae0e1b8566c8 jdk8u171-b10
+23addae1b843a5027df6b4194f8c8de788da55ae jdk8u171-b11
+f299cf0b7baea1ae85f139f97adb9ab5499f402a jdk8u172-b00
+d10254debf7c1342416062bf1ba5258f16a8ce00 jdk8u172-b01
+653d9e0cd3f4023675c9eece7f0d563287f1d34f jdk8u172-b02
+771d9e1fbe1ae2ec4d5d937ebcbfd18e9c800098 jdk8u172-b03
+efd7a4e211e8fddf52053d4b033d8d307f356bc3 jdk8u172-b04
+5587cde50bbc2aa031aefb47eaa36b041f5e7c4b jdk8u181-b00
+8f3131e04030eb35434a27c1a0866fc3651af6d5 jdk8u191-b00
+4235fb1dceebde1192498ef388a32e56b1ed5a46 jdk8u172-b05
+68b234d5df6f01f3c677a114ecd6878c25f23f3c jdk8u172-b06
+a311a45523b19d59f77e76b0441a2085bb5355c8 jdk8u172-b07
+5c1f180db1650f0f33e6005c1366f0d68242f1ad jdk8u172-b08
+aafd1bb21e2636ba982d3eae162f5c635a1df03a jdk8u172-b09
+dcd3ace969fcde4eedaddba629647656289d4264 jdk8u172-b10
+083a9d6562100353708e4b73656282b21a78f714 jdk8u172-b11
+6e2be123a2e1c7671086c767e79ffe8ad5d4f9ca jdk8u181-b01
+1d0b6fcff115a57ca02081da84589630ba282789 jdk8u181-b02
+1127faef22f14d56cdd6c0c8bded598f492c2611 jdk8u181-b03
+d5a33d109309138a1e9bed43d2a2bda04356dbac jdk8u172-b31
+b62c44a689e4d339b1129bffceee94119c84b1b2 jdk8u172-b32
+e8745ad08d55bb56b2ac5a70ec0a972c38fa6ca2 jdk8u172-b33
+74350ee9c013a39acb6af32049599a26e6dc3911 jdk8u172-b34
+0d1b5f9b3ab040eb9023cde206cd67d4b5a54535 jdk8u172-b35
+1e7855b1ecd3d069bcaaf35259d35f79a7c66987 jdk8u172-b36
+6a9482b43d79e3e017f58a23ec4574dd696e04db jdk8u172-b37
+6e2be123a2e1c7671086c767e79ffe8ad5d4f9ca jdk8u181-b01
+1d0b6fcff115a57ca02081da84589630ba282789 jdk8u181-b02
+1127faef22f14d56cdd6c0c8bded598f492c2611 jdk8u181-b03
+c53e56e8904926f4efdde8a0483109ed3c60c064 jdk8u181-b04
+cea033df30750958ffc999d647ee43587d4a06b2 jdk8u181-b05
+2198f5b865507118b644830293dc9f0ec3b4439e jdk8u181-b06
+892e637195c74dc83ee2c22c93125f0209216007 jdk8u181-b07
+9ffa7549c389c6361e643f69ddf6a3e76118de13 jdk8u181-b08
+b46904cf3eaf0ca150aee9f0d8bdf85e2691e74f jdk8u181-b09
+08b5e1f3d022fbe122b11b6f45f62b5a4ce92ed9 jdk8u181-b10
+e4f39d283b55faf6074308797615298bd1a45a66 jdk8u181-b11
+464ed8cea5d6cdbfacc9be7035297af88f57f708 jdk8u181-b12
+eed8e846c982d7474dd07fc873ba02f83ad1f847 jdk8u181-b13
+21a3fffc43418f4d75c2091bf03478330b8a9a98 jdk8u191-b01
+5aa3d728164a674d08ad847811be6bdd853e9bf8 jdk8u191-b02
+dd79b482625361458b2b34e7d669ee982eee06a4 jdk8u191-b03
+541c205d7fd15ab840f48aaeeaea3f63209d1687 jdk8u191-b04
+14c62eae2f8f56f571abfc8435055bb6094c8440 jdk8u191-b05
+6cfec782c42c25f772bfd51a8b47e6926aa8f69f jdk8u191-b06
+96be5f6ab83349c971edd9aeb35cafce267d3bf8 jdk8u191-b07
+113b4a1676db205922668f5b9c69b3dce22a095e jdk8u191-b08
+a339c1437badce44c7137da58d817159c9c80e4f jdk8u191-b09
+c0bd247ecd1cd09a129040e3fa1745c64db43b35 jdk8u191-b10
+055e1c867479452dd5d8c08905f7475aab25fcc1 jdk8u191-b25
+12e4de4b2499e9d9a1ae4fb0b63ca277cca150f4 jdk8u191-b11
+4fc288749a236f6dd235336a46855a3133f83bde jdk8u191-b12
+ab9258f7206ea8745908e19de159888067939945 jdk8u191-b26
+c19c5b73704e3d188bedfe52a473b408ca39009f jdk8u182-b00
+0341fa6dbb363ee4dc5dbf5bfc4f820523400a72 jdk8u192-b00
+5792d995ed26eec0417d96a2423446bbcd6951a9 jdk8u192-b01
+792ccf73293ac2a93cf19cb827d06bcaa896caea jdk8u192-b02
+1c0a59cee0e4e680dd0973f022b86de5637b9b75 jdk8u192-b03
+1c0a59cee0e4e680dd0973f022b86de5637b9b75 jdk8u202-b00
+a8d61d7f13b0de755da1335c15b72c53c59e92b5 jdk8u192-b04
+65409bcab2ad83d7043d508448a04fe18cf1c262 jdk8u192-b05
+7070edbacb29f03b9a77dbe09425da2c888625f1 jdk8u192-b06
+cd19ee45aa6b6c81dbf981fd71abed7b7888d499 jdk8u192-b07
+c8010d92392ff0081edd6bfd1882ec1f3397a6db jdk8u192-b08
+79ba5ca0aabb29480dd94c6d32d22dceac019700 jdk8u192-b09
+b675533489ae1dc55469885471c9a29eca584d38 jdk8u192-b10
+338c85978b2283a975b762eead2fccc6d25a2bc2 jdk8u192-b25
+8df818c645d6081a387cf4fe9b9c14c0b5b639b1 jdk8u192-b11
+1f822ff877d1a250165d5d2d52faf6957f8fcd00 jdk8u192-b12
+e0e4c3a86ef0e4daf4fe96bd058045a2b13ebf84 jdk8u192-b26
+79b4c0a88c00226dcd14496652adf84d53b5cb9c jdk8u202-b01
diff --git a/THIRD_PARTY_README b/THIRD_PARTY_README
index 046a6a7..a1662fe 100644
--- a/THIRD_PARTY_README
+++ b/THIRD_PARTY_README
@@ -7,7 +7,7 @@
 
 --- begin of LICENSE ---
 
-Copyright (c) 2000-2011 France Télécom
+Copyright (c) 2000-2011 France T??l??com
 All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
@@ -181,6 +181,192 @@
 
 -------------------------------------------------------------------------------
 
+%% This notice is provided with respect to DejaVu fonts v2.34, which may be
+included with JRE 8, and JDK 8, and OpenJDK 8.
+
+--- begin of LICENSE ---
+
+Fonts are (c) Bitstream (see below). DejaVu changes are in public domain.
+Glyphs imported from Arev fonts are (c) Tavmjong Bah (see below)
+
+
+Bitstream Vera Fonts Copyright
+------------------------------
+
+Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is
+a trademark of Bitstream, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of the fonts accompanying this license ("Fonts") and associated
+documentation files (the "Font Software"), to reproduce and distribute the
+Font Software, including without limitation the rights to use, copy, merge,
+publish, distribute, and/or sell copies of the Font Software, and to permit
+persons to whom the Font Software is furnished to do so, subject to the
+following conditions:
+
+The above copyright and trademark notices and this permission notice shall
+be included in all copies of one or more of the Font Software typefaces.
+
+The Font Software may be modified, altered, or added to, and in particular
+the designs of glyphs or characters in the Fonts may be modified and
+additional glyphs or characters may be added to the Fonts, only if the fonts
+are renamed to names not containing either the words "Bitstream" or the word
+"Vera".
+
+This License becomes null and void to the extent applicable to Fonts or Font
+Software that has been modified and is distributed under the "Bitstream
+Vera" names.
+
+The Font Software may be sold as part of a larger software package but no
+copy of one or more of the Font Software typefaces may be sold by itself.
+
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT,
+TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME
+FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING
+ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
+WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
+THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE
+FONT SOFTWARE.
+
+Except as contained in this notice, the names of Gnome, the Gnome
+Foundation, and Bitstream Inc., shall not be used in advertising or
+otherwise to promote the sale, use or other dealings in this Font Software
+without prior written authorization from the Gnome Foundation or Bitstream
+Inc., respectively. For further information, contact: fonts at gnome dot
+org.
+
+Arev Fonts Copyright
+------------------------------
+
+Copyright (c) 2006 by Tavmjong Bah. All Rights Reserved.
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the fonts accompanying this license ("Fonts") and
+associated documentation files (the "Font Software"), to reproduce
+and distribute the modifications to the Bitstream Vera Font Software,
+including without limitation the rights to use, copy, merge, publish,
+distribute, and/or sell copies of the Font Software, and to permit
+persons to whom the Font Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright and trademark notices and this permission notice
+shall be included in all copies of one or more of the Font Software
+typefaces.
+
+The Font Software may be modified, altered, or added to, and in
+particular the designs of glyphs or characters in the Fonts may be
+modified and additional glyphs or characters may be added to the
+Fonts, only if the fonts are renamed to names not containing either
+the words "Tavmjong Bah" or the word "Arev".
+
+This License becomes null and void to the extent applicable to Fonts
+or Font Software that has been modified and is distributed under the
+"Tavmjong Bah Arev" names.
+
+The Font Software may be sold as part of a larger software package but
+no copy of one or more of the Font Software typefaces may be sold by
+itself.
+
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL
+TAVMJONG BAH BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
+
+Except as contained in this notice, the name of Tavmjong Bah shall not
+be used in advertising or otherwise to promote the sale, use or other
+dealings in this Font Software without prior written authorization
+from Tavmjong Bah. For further information, contact: tavmjong @ free
+. fr.
+
+TeX Gyre DJV Math
+-----------------
+Fonts are (c) Bitstream (see below). DejaVu changes are in public domain.
+
+Math extensions done by B. Jackowski, P. Strzelczyk and P. Pianowski
+(on behalf of TeX users groups) are in public domain.
+
+Letters imported from Euler Fraktur from AMSfonts are (c) American
+Mathematical Society (see below).
+Bitstream Vera Fonts Copyright
+Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera
+is a trademark of Bitstream, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of the fonts accompanying this license ("Fonts") and associated documentation
+files (the "Font Software"), to reproduce and distribute the Font Software,
+including without limitation the rights to use, copy, merge, publish,
+distribute, and/or sell copies of the Font Software, and to permit persons
+to whom the Font Software is furnished to do so, subject to the following
+conditions:
+
+The above copyright and trademark notices and this permission notice
+shall be included in all copies of one or more of the Font Software typefaces.
+
+The Font Software may be modified, altered, or added to, and in particular
+the designs of glyphs or characters in the Fonts may be modified and
+additional glyphs or characters may be added to the Fonts, only if the
+fonts are renamed to names not containing either the words "Bitstream"
+or the word "Vera".
+
+This License becomes null and void to the extent applicable to Fonts or
+Font Software that has been modified and is distributed under the
+"Bitstream Vera" names.
+
+The Font Software may be sold as part of a larger software package but
+no copy of one or more of the Font Software typefaces may be sold by itself.
+
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT,
+TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME
+FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING
+ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
+WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
+OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN
+THE FONT SOFTWARE.
+Except as contained in this notice, the names of GNOME, the GNOME
+Foundation, and Bitstream Inc., shall not be used in advertising or 
+otherwise to promote the sale, use or other dealings in this Font Software
+without prior written authorization from the GNOME Foundation or 
+Bitstream Inc., respectively.
+For further information, contact: fonts at gnome dot org.
+
+AMSFonts (v. 2.2) copyright
+
+The PostScript Type 1 implementation of the AMSFonts produced by and
+previously distributed by Blue Sky Research and Y&Y, Inc. are now freely
+available for general use. This has been accomplished through the
+cooperation
+of a consortium of scientific publishers with Blue Sky Research and Y&Y.
+Members of this consortium include:
+
+Elsevier Science IBM Corporation Society for Industrial and Applied
+Mathematics (SIAM) Springer-Verlag American Mathematical Society (AMS)
+
+In order to assure the authenticity of these fonts, copyright will be
+held by the American Mathematical Society. This is not meant to restrict
+in any way the legitimate use of the fonts, such as (but not limited to)
+electronic distribution of documents containing these fonts, inclusion of
+these fonts into other public domain or commercial font collections or computer
+applications, use of the outline data to create derivative fonts and/or
+faces, etc. However, the AMS does require that the AMS copyright notice be
+removed from any derivative versions of the fonts which have been altered in
+any way. In addition, to ensure the fidelity of TeX documents using Computer
+Modern fonts, Professor Donald Knuth, creator of the Computer Modern faces,
+has requested that any alterations which yield different font metrics be
+given a different name.
+
+--- end of LICENSE ---
+
+-------------------------------------------------------------------------------
+
 %% This notice is provided with respect to Document Object Model (DOM) Level 2
 & 3, which may be included with JRE 8, JDK 8, and OpenJDK 8.
 
@@ -849,7 +1035,7 @@
 --- begin of LICENSE ---
 
 Copyright notice
-Copyright © 2011 Ecma International
+Copyright ?? 2011 Ecma International
 Ecma International
 Rue du Rhone 114
 CH-1204 Geneva
@@ -916,7 +1102,7 @@
 
 --- begin of LICENSE ---
 
-Copyright © 2001,2003 Keith Packard
+Copyright ?? 2001,2003 Keith Packard
 
 Permission to use, copy, modify, distribute, and sell this software and its
 documentation for any purpose is hereby granted without fee, provided that the
@@ -1311,7 +1497,7 @@
 
 -------------------------------------------------------------------------------
 
-%% This notice is provided with respect to libpng 1.6.16, which may be 
+%% This notice is provided with respect to libpng 1.6.35, which may be
 included with JRE 8, JDK 8, and OpenJDK 8.
 
 --- begin of LICENSE ---
@@ -1327,21 +1513,21 @@
 
 This code is released under the libpng license.
 
-libpng versions 1.2.6, August 15, 2004, through 1.6.16, December 22, 2014, are
-Copyright (c) 2004, 2006-2014 Glenn Randers-Pehrson, and are
-distributed according to the same disclaimer and license as libpng-1.2.5
-with the following individual added to the list of Contributing Authors
-
-   Cosmin Truta
-
-libpng versions 1.0.7, July 1, 2000, through 1.2.5 - October 3, 2002, are
-Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
-distributed according to the same disclaimer and license as libpng-1.0.6
-with the following individuals added to the list of Contributing Authors
+libpng versions 1.0.7, July 1, 2000 through 1.6.35, July 15, 2018 are
+Copyright (c) 2000-2002, 2004, 2006-2018 Glenn Randers-Pehrson, are
+derived from libpng-1.0.6, and are distributed according to the same
+disclaimer and license as libpng-1.0.6 with the following individuals
+added to the list of Contributing Authors:
 
    Simon-Pierre Cadieux
    Eric S. Raymond
+   Mans Rullgard
+   Cosmin Truta
    Gilles Vollant
+   James Yu
+   Mandar Sahastrabuddhe
+   Google Inc.
+   Vadim Barkov
 
 and with the following additions to the disclaimer:
 
@@ -1352,19 +1538,25 @@
    risk of satisfactory quality, performance, accuracy, and effort is with
    the user.
 
+Some files in the "contrib" directory and some configure-generated
+files that are distributed with libpng have other copyright owners and
+are released under other open source licenses.
+
 libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
-Copyright (c) 1998, 1999 Glenn Randers-Pehrson, and are
-distributed according to the same disclaimer and license as libpng-0.96,
-with the following individuals added to the list of Contributing Authors:
+Copyright (c) 1998-2000 Glenn Randers-Pehrson, are derived from
+libpng-0.96, and are distributed according to the same disclaimer and
+license as libpng-0.96, with the following individuals added to the list
+of Contributing Authors:
 
    Tom Lane
    Glenn Randers-Pehrson
    Willem van Schaik
 
 libpng versions 0.89, June 1996, through 0.96, May 1997, are
-Copyright (c) 1996, 1997 Andreas Dilger
-Distributed according to the same disclaimer and license as libpng-0.88,
-with the following individuals added to the list of Contributing Authors:
+Copyright (c) 1996-1997 Andreas Dilger, are derived from libpng-0.88,
+and are distributed according to the same disclaimer and license as
+libpng-0.88, with the following individuals added to the list of
+Contributing Authors:
 
    John Bowler
    Kevin Bracey
@@ -1373,8 +1565,11 @@
    Greg Roelofs
    Tom Tanner
 
+Some files in the "scripts" directory have other copyright owners
+but are released under this license.
+
 libpng versions 0.5, May 1995, through 0.88, January 1996, are
-Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
+Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.
 
 For the purposes of this copyright and license, "Contributing Authors"
 is defined as the following set of individuals:
@@ -1397,13 +1592,13 @@
 source code, or portions hereof, for any purpose, without fee, subject
 to the following restrictions:
 
-1. The origin of this source code must not be misrepresented.
+  1. The origin of this source code must not be misrepresented.
 
-2. Altered versions must be plainly marked as such and must not
-   be misrepresented as being the original source.
+  2. Altered versions must be plainly marked as such and must not
+     be misrepresented as being the original source.
 
-3. This Copyright notice may not be removed or altered from any
-   source or altered source distribution.
+  3. This Copyright notice may not be removed or altered from any
+     source or altered source distribution.
 
 The Contributing Authors and Group 42, Inc. specifically permit, without
 fee, and encourage the use of this source code as a component to
@@ -1411,21 +1606,34 @@
 source code in a product, acknowledgment is not required but would be
 appreciated.
 
+END OF COPYRIGHT NOTICE, DISCLAIMER, and LICENSE.
 
-A "png_get_copyright" function is available, for convenient use in "about"
-boxes and the like:
+TRADEMARK:
 
-   printf("%s",png_get_copyright(NULL));
+The name "libpng" has not been registered by the Copyright owner
+as a trademark in any jurisdiction.  However, because libpng has
+been distributed and maintained world-wide, continually since 1995,
+the Copyright owner claims "common-law trademark protection" in any
+jurisdiction where common-law trademark is recognized.
 
-Also, the PNG logo (in PNG format, of course) is supplied in the
-files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
+OSI CERTIFICATION:
 
-Libpng is OSI Certified Open Source Software.  OSI Certified Open Source is a
-certification mark of the Open Source Initiative.
+Libpng is OSI Certified Open Source Software.  OSI Certified Open Source is
+a certification mark of the Open Source Initiative. OSI has not addressed
+the additional disclaimers inserted at version 1.0.7.
+
+EXPORT CONTROL:
+
+The Copyright owner believes that the Export Control Classification
+Number (ECCN) for libpng is EAR99, which means not subject to export
+controls or International Traffic in Arms Regulations (ITAR) because
+it is open source, publicly available software, that does not contain
+any encryption software.  See the EAR, paragraphs 734.3(b)(3) and
+734.7(b).
 
 Glenn Randers-Pehrson
 glennrp at users.sourceforge.net
-December 22, 2014
+July 15, 2018
 
 --- end of LICENSE ---
 
@@ -2212,16 +2420,16 @@
 Unicode Terms of Use
 
 For the general privacy policy governing access to this site, see the Unicode
-Privacy Policy. For trademark usage, see the Unicode® Consortium Name and
+Privacy Policy. For trademark usage, see the Unicode?? Consortium Name and
 Trademark Usage Policy.
 
 A. Unicode Copyright.
-   1. Copyright © 1991-2013 Unicode, Inc. All rights reserved.
+   1. Copyright ?? 1991-2013 Unicode, Inc. All rights reserved.
 
    2. Certain documents and files on this website contain a legend indicating
       that "Modification is permitted." Any person is hereby authorized,
       without fee, to modify such documents and files to create derivative
-      works conforming to the Unicode® Standard, subject to Terms and
+      works conforming to the Unicode?? Standard, subject to Terms and
       Conditions herein.
 
     3. Any person is hereby authorized, without fee, to view, use, reproduce,
@@ -2287,14 +2495,14 @@
 
 E.Trademarks & Logos.
    1. The Unicode Word Mark and the Unicode Logo are trademarks of Unicode,
-      Inc.  “The Unicode Consortium” and “Unicode, Inc.” are trade names of
+      Inc.  ???The Unicode Consortium??? and ???Unicode, Inc.??? are trade names of
       Unicode, Inc.  Use of the information and materials found on this
-      website indicates your acknowledgement of Unicode, Inc.’s exclusive
+      website indicates your acknowledgement of Unicode, Inc.???s exclusive
       worldwide rights in the Unicode Word Mark, the Unicode Logo, and the
       Unicode trade names.
 
-   2. The Unicode Consortium Name and Trademark Usage Policy (“Trademark
-      Policy”) are incorporated herein by reference and you agree to abide by
+   2. The Unicode Consortium Name and Trademark Usage Policy (???Trademark
+      Policy???) are incorporated herein by reference and you agree to abide by
       the provisions of the Trademark Policy, which may be changed from time
       to time in the sole discretion of Unicode, Inc.
 
@@ -2317,12 +2525,12 @@
 
    2. Modification by Unicode.  Unicode shall have the right to modify this
       Agreement at any time by posting it to this site. The user may not
-      assign any part of this Agreement without Unicode’s prior written
+      assign any part of this Agreement without Unicode???s prior written
       consent.
 
    3. Taxes. The user agrees to pay any taxes arising from access to this
       website or use of the information herein, except for those based on
-      Unicode’s net income.
+      Unicode???s net income.
 
    4. Severability.  If any provision of this Agreement is declared invalid or
       unenforceable, the remaining provisions of this Agreement shall remain
@@ -2351,7 +2559,7 @@
 
 COPYRIGHT AND PERMISSION NOTICE
 
-Copyright © 1991-2012 Unicode, Inc. All rights reserved. Distributed under the
+Copyright ?? 1991-2012 Unicode, Inc. All rights reserved. Distributed under the
 Terms of Use in http://www.unicode.org/copyright.html.
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
@@ -2672,35 +2880,6 @@
 */
 
 _____________________________
-Copyright notice for extutil.h:
-Copyright 1989, 1998 The Open Group
-
-All Rights Reserved.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
-*
-* Author: Jim Fulton, MIT The Open Group
-*
-* Xlib Extension-Writing Utilities
-*
-* This package contains utilities for writing the client API for various
-* protocol extensions. THESE INTERFACES ARE NOT PART OF THE X STANDARD AND
-* ARE SUBJECT TO CHANGE!
-*/
-
-_____________________________
 Copyright notice for HPkeysym.h:
 /*
 
@@ -2808,12 +2987,12 @@
 
 -------------------------------------------------------------------------------
 
-%% This notice is provided with respect to zlib v1.2.8, which may be included 
+%% This notice is provided with respect to zlib v1.2.11, which may be included 
 with JRE 8, JDK 8, and OpenJDK 8.
 
 --- begin of LICENSE ---
 
-  version 1.2.8, April 28th, 2013
+  version 1.2.11, January 15th, 2017
 
   Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler
 
diff --git a/agent/src/os/linux/Makefile b/agent/src/os/linux/Makefile
index dfbb0b9..dc4850e 100644
--- a/agent/src/os/linux/Makefile
+++ b/agent/src/os/linux/Makefile
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -76,6 +76,9 @@
 endif
 LFLAGS_LIBSA += $(LDFLAGS_HASH_STYLE)
 
+LDFLAGS_NO_EXEC_STACK="-Wl,-z,noexecstack"
+LFLAGS_LIBSA += $(LDFLAGS_NO_EXEC_STACK)
+
 $(LIBSA): $(ARCH) $(OBJS) mapfile
         $(GCC) -shared $(LFLAGS_LIBSA) -o $(LIBSA) $(OBJS) $(LIBS)
 
diff --git a/agent/src/os/solaris/proc/salibproc.h b/agent/src/os/solaris/proc/salibproc.h
index 1e6d9cf..ddc68d9 100644
--- a/agent/src/os/solaris/proc/salibproc.h
+++ b/agent/src/os/solaris/proc/salibproc.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -46,6 +46,17 @@
 extern "C" {
 #endif
 
+/* extended symbol table information */
+typedef struct {
+        const char      *prs_object;            /* object name */
+        const char      *prs_name;              /* symbol name */
+        Lmid_t          prs_lmid;               /* link map id */
+        uint_t          prs_id;                 /* symbol id */
+        uint_t          prs_table;              /* symbol table id */
+} prsyminfo_t;
+
+typedef struct ps_prochandle ps_prochandle_t;
+
 /*
  * 'object_name' is the name of a load object obtained from an
  * iteration over the process's address space mappings (Pmapping_iter),
@@ -53,8 +64,10 @@
  * or else it is one of the special PR_OBJ_* values above.
  */
 
-extern int Plookup_by_addr(struct ps_prochandle *,
-    uintptr_t, char *, size_t, GElf_Sym *);
+extern int Plookup_by_addr(ps_prochandle_t *, uintptr_t, char *,
+                           size_t, GElf_Sym *, prsyminfo_t *);
+extern ps_prochandle_t *proc_arg_grab(const char *, int, int,
+                                      int *, const char **);
 
 typedef int proc_map_f(void *, const prmap_t *, const char *);
 extern int Pobject_iter(struct ps_prochandle *, proc_map_f *, void *);
@@ -88,7 +101,6 @@
 #define G_ELF           13      /* Libelf error, elf_errno() is meaningful */
 #define G_NOTE          14      /* Required PT_NOTE Phdr not present in core */
 
-extern struct ps_prochandle *proc_arg_grab(const char *, int, int, int *);
 extern  const pstatus_t *Pstatus(struct ps_prochandle *);
 
 /* Flags accepted by Prelease (partial) */
diff --git a/agent/src/os/solaris/proc/saproc.cpp b/agent/src/os/solaris/proc/saproc.cpp
index 3f0e6b2..42a13c5 100644
--- a/agent/src/os/solaris/proc/saproc.cpp
+++ b/agent/src/os/solaris/proc/saproc.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -755,7 +755,8 @@
 #endif
 
   // connect to process/core
-  struct ps_prochandle* ph = proc_arg_grab(cmdLine_cstr, (isProcess? PR_ARG_PIDS : PR_ARG_CORES), PGRAB_FORCE, &gcode);
+  ps_prochandle_t* ph = proc_arg_grab(cmdLine_cstr, (isProcess? PR_ARG_PIDS : PR_ARG_CORES), PGRAB_FORCE, &gcode, NULL);
+
   env->ReleaseStringUTFChars(cmdLine, cmdLine_cstr);
   if (! ph) {
      if (gcode > 0 && gcode < sizeof(proc_arg_grab_errmsgs)/sizeof(const char*)) {
@@ -1233,7 +1234,8 @@
    char nameBuf[SYMBOL_BUF_SIZE + 1];
    GElf_Sym sym;
    int res = Plookup_by_addr((struct ps_prochandle*) p_ps_prochandle, (uintptr_t) address,
-                                 nameBuf, sizeof(nameBuf), &sym);
+                             nameBuf, sizeof(nameBuf), &sym, NULL);
+
    if (res != 0) { // failed
       return 0;
    }
diff --git a/agent/src/share/classes/sun/jvm/hotspot/CLHSDB.java b/agent/src/share/classes/sun/jvm/hotspot/CLHSDB.java
index a539310..b1f8d83 100644
--- a/agent/src/share/classes/sun/jvm/hotspot/CLHSDB.java
+++ b/agent/src/share/classes/sun/jvm/hotspot/CLHSDB.java
@@ -113,7 +113,8 @@
     private String coreFilename;
 
     private void doUsage() {
-        System.out.println("Usage:  java CLHSDB [[pid] | [path-to-java-executable [path-to-corefile]] | help ]");
+        // With JDK-8059038 launchers for this class exist. Print usage for those launchers.
+        System.out.println("Usage:  clhsdb [[pid] | [path-to-java-executable [path-to-corefile]] | help | -help ]");
         System.out.println("           pid:                     attach to the process whose id is 'pid'");
         System.out.println("           path-to-java-executable: Debug a core file produced by this program");
         System.out.println("           path-to-corefile:        Debug this corefile.  The default is 'core'");
diff --git a/agent/src/share/classes/sun/jvm/hotspot/HSDB.java b/agent/src/share/classes/sun/jvm/hotspot/HSDB.java
index 9ae362b..97726c4 100644
--- a/agent/src/share/classes/sun/jvm/hotspot/HSDB.java
+++ b/agent/src/share/classes/sun/jvm/hotspot/HSDB.java
@@ -82,7 +82,8 @@
   private String coreFilename;
 
   private void doUsage() {
-    System.out.println("Usage:  java HSDB [[pid] | [path-to-java-executable [path-to-corefile]] | help ]");
+    // With JDK-8059038 launchers for this class exist. Print usage for those launchers.
+    System.out.println("Usage:  hsdb [[pid] | [path-to-java-executable [path-to-corefile]] | help | -help ]");
     System.out.println("           pid:                     attach to the process whose id is 'pid'");
     System.out.println("           path-to-java-executable: Debug a core file produced by this program");
     System.out.println("           path-to-corefile:        Debug this corefile.  The default is 'core'");
diff --git a/agent/src/share/classes/sun/jvm/hotspot/debugger/linux/x86/LinuxX86CFrame.java b/agent/src/share/classes/sun/jvm/hotspot/debugger/linux/x86/LinuxX86CFrame.java
index 53a2e26..95fa38d 100644
--- a/agent/src/share/classes/sun/jvm/hotspot/debugger/linux/x86/LinuxX86CFrame.java
+++ b/agent/src/share/classes/sun/jvm/hotspot/debugger/linux/x86/LinuxX86CFrame.java
@@ -55,7 +55,15 @@
 
    public CFrame sender(ThreadProxy thread) {
       X86ThreadContext context = (X86ThreadContext) thread.getContext();
-      Address esp = context.getRegisterAsAddress(X86ThreadContext.ESP);
+      /*
+       * Native code fills in the stack pointer register value using index
+       * X86ThreadContext.SP.
+       * See file LinuxDebuggerLocal.c macro REG_INDEX(reg).
+       *
+       * Be sure to use SP, or UESP which is aliased to SP in Java code,
+       * for the frame pointer validity check.
+       */
+      Address esp = context.getRegisterAsAddress(X86ThreadContext.SP);
 
       if ( (ebp == null) || ebp.lessThan(esp) ) {
         return null;
diff --git a/agent/src/share/classes/sun/jvm/hotspot/debugger/windows/x86/WindowsX86CFrame.java b/agent/src/share/classes/sun/jvm/hotspot/debugger/windows/x86/WindowsX86CFrame.java
index dbc8b71..1d5e015 100644
--- a/agent/src/share/classes/sun/jvm/hotspot/debugger/windows/x86/WindowsX86CFrame.java
+++ b/agent/src/share/classes/sun/jvm/hotspot/debugger/windows/x86/WindowsX86CFrame.java
@@ -46,7 +46,15 @@
 
   public CFrame sender(ThreadProxy thread) {
     X86ThreadContext context = (X86ThreadContext) thread.getContext();
-    Address esp = context.getRegisterAsAddress(X86ThreadContext.ESP);
+    /*
+     * Native code fills in the stack pointer register value using index
+     * X86ThreadContext.SP.
+     * See file sawindbg.cpp macro REG_INDEX(x).
+     *
+     * Be sure to use SP, or UESP which is aliased to SP in Java code,
+     * for the frame pointer validity check.
+     */
+    Address esp = context.getRegisterAsAddress(X86ThreadContext.SP);
 
     if ( (ebp == null) || ebp.lessThan(esp) ) {
       return null;
diff --git a/agent/src/share/classes/sun/jvm/hotspot/oops/CompiledICHolder.java b/agent/src/share/classes/sun/jvm/hotspot/oops/CompiledICHolder.java
index 249430a..5a062b7 100644
--- a/agent/src/share/classes/sun/jvm/hotspot/oops/CompiledICHolder.java
+++ b/agent/src/share/classes/sun/jvm/hotspot/oops/CompiledICHolder.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -40,10 +40,10 @@
   }
 
   private static synchronized void initialize(TypeDataBase db) throws WrongTypeException {
-    Type type    = db.lookupType("CompiledICHolder");
-    holderMethod = new MetadataField(type.getAddressField("_holder_method"), 0);
-    holderKlass  = new MetadataField(type.getAddressField("_holder_klass"), 0);
-    headerSize   = type.getSize();
+    Type type      = db.lookupType("CompiledICHolder");
+    holderMetadata = new MetadataField(type.getAddressField("_holder_metadata"), 0);
+    holderKlass    = new MetadataField(type.getAddressField("_holder_klass"), 0);
+    headerSize     = type.getSize();
   }
 
   public CompiledICHolder(Address addr) {
@@ -55,12 +55,12 @@
   private static long headerSize;
 
   // Fields
-  private static MetadataField holderMethod;
+  private static MetadataField holderMetadata;
   private static MetadataField holderKlass;
 
   // Accessors for declared fields
-  public Method getHolderMethod() { return (Method) holderMethod.getValue(this); }
-  public Klass  getHolderKlass()  { return (Klass)  holderKlass.getValue(this); }
+  public Metadata getHolderMetadata() { return (Metadata) holderMetadata.getValue(this); }
+  public Klass    getHolderKlass()    { return (Klass)    holderKlass.getValue(this); }
 
   public void printValueOn(PrintStream tty) {
     tty.print("CompiledICHolder");
diff --git a/agent/src/share/classes/sun/jvm/hotspot/oops/ConstantPool.java b/agent/src/share/classes/sun/jvm/hotspot/oops/ConstantPool.java
index 0b3783e..8b4127c 100644
--- a/agent/src/share/classes/sun/jvm/hotspot/oops/ConstantPool.java
+++ b/agent/src/share/classes/sun/jvm/hotspot/oops/ConstantPool.java
@@ -259,13 +259,12 @@
 
   public static int  decodeInvokedynamicIndex(int i) { Assert.that(isInvokedynamicIndex(i),  ""); return ~i; }
 
-  // The invokedynamic points at the object index.  The object map points at
-  // the cpCache index and the cpCache entry points at the original constant
-  // pool index.
+  // The invokedynamic points at a CP cache entry.  This entry points back
+  // at the original CP entry (CONSTANT_InvokeDynamic) and also (via f2) at an entry
+  // in the resolved_references array (which provides the appendix argument).
   public int invokedynamicCPCacheIndex(int index) {
     Assert.that(isInvokedynamicIndex(index), "should be a invokedynamic index");
-    int rawIndex = decodeInvokedynamicIndex(index);
-    return referenceMap().at(rawIndex);
+    return decodeInvokedynamicIndex(index);
   }
 
   ConstantPoolCacheEntry invokedynamicCPCacheEntryAt(int index) {
diff --git a/make/aix/makefiles/jsig.make b/make/aix/makefiles/jsig.make
index 301aa84..f8bf938 100644
--- a/make/aix/makefiles/jsig.make
+++ b/make/aix/makefiles/jsig.make
@@ -45,7 +45,7 @@
 # cause problems with interposing. See CR: 6466665
 # LFLAGS_JSIG += $(MAPFLAG:FILENAME=$(LIBJSIG_MAPFILE))
 
-LFLAGS_JSIG += -D_GNU_SOURCE -D_REENTRANT $(LDFLAGS_HASH_STYLE)
+LFLAGS_JSIG += -D_GNU_SOURCE -D_REENTRANT $(LDFLAGS_HASH_STYLE) $(EXTRA_LDFLAGS)
 
 LFLAGS_JSIG += $(BIN_UTILS)
 
diff --git a/make/aix/makefiles/mapfile-vers-debug b/make/aix/makefiles/mapfile-vers-debug
index 0a9d3e9..8f28690 100644
--- a/make/aix/makefiles/mapfile-vers-debug
+++ b/make/aix/makefiles/mapfile-vers-debug
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -63,6 +63,7 @@
                 JVM_ConstantPoolGetSize;
                 JVM_ConstantPoolGetStringAt;
                 JVM_ConstantPoolGetUTF8At;
+                JVM_CopySwapMemory;
                 JVM_CountStackFrames;
                 JVM_CurrentClassLoader;
                 JVM_CurrentLoadedClass;
diff --git a/make/aix/makefiles/mapfile-vers-product b/make/aix/makefiles/mapfile-vers-product
index f748a10..adcb3fc 100644
--- a/make/aix/makefiles/mapfile-vers-product
+++ b/make/aix/makefiles/mapfile-vers-product
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -63,6 +63,7 @@
                 JVM_ConstantPoolGetSize;
                 JVM_ConstantPoolGetStringAt;
                 JVM_ConstantPoolGetUTF8At;
+                JVM_CopySwapMemory;
                 JVM_CountStackFrames;
                 JVM_CurrentClassLoader;
                 JVM_CurrentLoadedClass;
diff --git a/make/aix/makefiles/saproc.make b/make/aix/makefiles/saproc.make
index a7f2891..d515ac2 100644
--- a/make/aix/makefiles/saproc.make
+++ b/make/aix/makefiles/saproc.make
@@ -66,7 +66,7 @@
 endif
 
 
-SA_LFLAGS = $(MAPFLAG:FILENAME=$(SAMAPFILE)) $(LDFLAGS_HASH_STYLE)
+SA_LFLAGS = $(MAPFLAG:FILENAME=$(SAMAPFILE)) $(LDFLAGS_HASH_STYLE) $(EXTRA_LDFLAGS)
 
 $(LIBSAPROC): $(SASRCFILES) $(SAMAPFILE)
 	$(QUIETLY) if [ "$(BOOT_JAVA_HOME)" = "" ]; then \
diff --git a/make/aix/makefiles/vm.make b/make/aix/makefiles/vm.make
index ab994a3..d989dab 100644
--- a/make/aix/makefiles/vm.make
+++ b/make/aix/makefiles/vm.make
@@ -117,7 +117,7 @@
 
 # Extra flags from gnumake's invocation or environment
 CFLAGS += $(EXTRA_CFLAGS)
-LFLAGS += $(EXTRA_CFLAGS)
+LFLAGS += $(EXTRA_CFLAGS) $(EXTRA_LDFLAGS)
 
 # Don't set excutable bit on stack segment
 # the same could be done by separate execstack command
diff --git a/make/bsd/makefiles/jsig.make b/make/bsd/makefiles/jsig.make
index 67cb429..29779b0 100644
--- a/make/bsd/makefiles/jsig.make
+++ b/make/bsd/makefiles/jsig.make
@@ -52,7 +52,7 @@
 # cause problems with interposing. See CR: 6466665
 # LFLAGS_JSIG += $(MAPFLAG:FILENAME=$(LIBJSIG_MAPFILE))
 
-LFLAGS_JSIG += -D_GNU_SOURCE -pthread $(LDFLAGS_HASH_STYLE)
+LFLAGS_JSIG += -D_GNU_SOURCE -pthread $(LDFLAGS_HASH_STYLE) $(EXTRA_LDFLAGS)
 
 # DEBUG_BINARIES overrides everything, use full -g debug information
 ifeq ($(DEBUG_BINARIES), true)
diff --git a/make/bsd/makefiles/mapfile-vers-debug b/make/bsd/makefiles/mapfile-vers-debug
index a94bf88..5e4a6a5 100644
--- a/make/bsd/makefiles/mapfile-vers-debug
+++ b/make/bsd/makefiles/mapfile-vers-debug
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -61,6 +61,7 @@
                 _JVM_ConstantPoolGetSize
                 _JVM_ConstantPoolGetStringAt
                 _JVM_ConstantPoolGetUTF8At
+                _JVM_CopySwapMemory
                 _JVM_CountStackFrames
                 _JVM_CurrentClassLoader
                 _JVM_CurrentLoadedClass
diff --git a/make/bsd/makefiles/mapfile-vers-product b/make/bsd/makefiles/mapfile-vers-product
index 6be8042..b8a83d6 100644
--- a/make/bsd/makefiles/mapfile-vers-product
+++ b/make/bsd/makefiles/mapfile-vers-product
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -61,6 +61,7 @@
                 _JVM_ConstantPoolGetSize
                 _JVM_ConstantPoolGetStringAt
                 _JVM_ConstantPoolGetUTF8At
+                _JVM_CopySwapMemory
                 _JVM_CountStackFrames
                 _JVM_CurrentClassLoader
                 _JVM_CurrentLoadedClass
diff --git a/make/bsd/makefiles/saproc.make b/make/bsd/makefiles/saproc.make
index 77dc9f7..8967910 100644
--- a/make/bsd/makefiles/saproc.make
+++ b/make/bsd/makefiles/saproc.make
@@ -114,7 +114,7 @@
 # bring in minimum version argument or we'll fail on OSX 10.10
 SA_LFLAGS = $(LFLAGS)
 endif
-SA_LFLAGS += $(LDFLAGS_HASH_STYLE)
+SA_LFLAGS += $(LDFLAGS_HASH_STYLE) $(EXTRA_LDFLAGS)
 
 BOOT_JAVA_INCLUDES = -I$(BOOT_JAVA_HOME)/include \
   -I$(BOOT_JAVA_HOME)/include/$(shell uname -s | tr "[:upper:]" "[:lower:]")
diff --git a/make/bsd/makefiles/vm.make b/make/bsd/makefiles/vm.make
index 93640d8..60d3a20 100644
--- a/make/bsd/makefiles/vm.make
+++ b/make/bsd/makefiles/vm.make
@@ -119,7 +119,7 @@
 
 # Extra flags from gnumake's invocation or environment
 CFLAGS += $(EXTRA_CFLAGS)
-LFLAGS += $(EXTRA_CFLAGS)
+LFLAGS += $(EXTRA_CFLAGS) $(EXTRA_LDFLAGS)
 
 # Don't set excutable bit on stack segment
 # the same could be done by separate execstack command
diff --git a/make/defs.make b/make/defs.make
index b5a4123..1e97a4c 100644
--- a/make/defs.make
+++ b/make/defs.make
@@ -285,7 +285,7 @@
 
   # Use uname output for SRCARCH, but deal with platform differences. If ARCH
   # is not explicitly listed below, it is treated as x86.
-  SRCARCH    ?= $(ARCH/$(filter sparc sparc64 ia64 amd64 x86_64 ppc ppc64 zero,$(ARCH)))
+  SRCARCH    ?= $(ARCH/$(filter sparc sparc64 ia64 amd64 x86_64 ppc ppc64 ppc64le zero,$(ARCH)))
   ARCH/       = x86
   ARCH/sparc  = sparc
   ARCH/sparc64= sparc
@@ -293,6 +293,7 @@
   ARCH/amd64  = x86
   ARCH/x86_64 = x86
   ARCH/ppc64  = ppc
+  ARCH/ppc64le= ppc
   ARCH/ppc    = ppc
   ARCH/zero   = zero
 
@@ -316,7 +317,12 @@
     endif
   endif
 
-  # LIBARCH is 1:1 mapping from BUILDARCH
+  # LIBARCH is 1:1 mapping from BUILDARCH, except for ARCH=ppc64le
+  ifeq ($(ARCH),ppc64le)
+    LIBARCH      ?= ppc64le
+  else
+    LIBARCH      ?= $(LIBARCH/$(BUILDARCH))
+  endif
   LIBARCH        ?= $(LIBARCH/$(BUILDARCH))
   LIBARCH/i486    = i386
   LIBARCH/amd64   = amd64
diff --git a/make/linux/makefiles/adlc.make b/make/linux/makefiles/adlc.make
index 4e47232..0bc8973 100644
--- a/make/linux/makefiles/adlc.make
+++ b/make/linux/makefiles/adlc.make
@@ -105,9 +105,15 @@
 
 all: $(EXEC)
 
+ADLC_LD_FLAGS=
+ifeq ($(STATIC_CXX), true)
+  ADLC_LD_FLAGS = $(STATIC_LIBGCC) $(ADLC_STATIC_STDCXX)
+endif
+
+
 $(EXEC) : $(OBJECTS)
 	@echo Making adlc
-	$(QUIETLY) $(filter-out $(ARCHFLAG),$(HOST.LINK_NOPROF.CXX)) -o $(EXEC) $(OBJECTS)
+	$(QUIETLY) $(filter-out $(ARCHFLAG),$(HOST.LINK_NOPROF.CXX)) $(ADLC_LD_FLAGS) -o $(EXEC) $(OBJECTS)
 
 # Random dependencies:
 $(OBJECTS): opcodes.hpp classes.hpp adlc.hpp adlcVMDeps.hpp adlparse.hpp archDesc.hpp arena.hpp dict2.hpp filebuff.hpp forms.hpp formsopt.hpp formssel.hpp
diff --git a/make/linux/makefiles/defs.make b/make/linux/makefiles/defs.make
index 3af5878..496c3e1 100644
--- a/make/linux/makefiles/defs.make
+++ b/make/linux/makefiles/defs.make
@@ -239,10 +239,12 @@
 # client and server subdirectories have symbolic links to ../libjsig.so
 EXPORT_LIST += $(EXPORT_JRE_LIB_ARCH_DIR)/libjsig.$(LIBRARY_SUFFIX)
 ifeq ($(ENABLE_FULL_DEBUG_SYMBOLS),1)
-  ifeq ($(ZIP_DEBUGINFO_FILES),1)
-    EXPORT_LIST += $(EXPORT_JRE_LIB_ARCH_DIR)/libjsig.diz
-  else
-    EXPORT_LIST += $(EXPORT_JRE_LIB_ARCH_DIR)/libjsig.debuginfo
+  ifneq ($(STRIP_POLICY),no_strip)
+    ifeq ($(ZIP_DEBUGINFO_FILES),1)
+      EXPORT_LIST += $(EXPORT_JRE_LIB_ARCH_DIR)/libjsig.diz
+    else
+      EXPORT_LIST += $(EXPORT_JRE_LIB_ARCH_DIR)/libjsig.debuginfo
+    endif
   endif
 endif
 EXPORT_SERVER_DIR = $(EXPORT_JRE_LIB_ARCH_DIR)/server
@@ -253,10 +255,12 @@
   EXPORT_LIST += $(EXPORT_SERVER_DIR)/Xusage.txt
   EXPORT_LIST += $(EXPORT_SERVER_DIR)/libjvm.$(LIBRARY_SUFFIX)
   ifeq ($(ENABLE_FULL_DEBUG_SYMBOLS),1)
-    ifeq ($(ZIP_DEBUGINFO_FILES),1)
-      EXPORT_LIST += $(EXPORT_SERVER_DIR)/libjvm.diz
-    else
-      EXPORT_LIST += $(EXPORT_SERVER_DIR)/libjvm.debuginfo
+    ifneq ($(STRIP_POLICY),no_strip)
+      ifeq ($(ZIP_DEBUGINFO_FILES),1)
+        EXPORT_LIST += $(EXPORT_SERVER_DIR)/libjvm.diz
+      else
+        EXPORT_LIST += $(EXPORT_SERVER_DIR)/libjvm.debuginfo
+      endif
     endif
   endif
 endif
@@ -265,10 +269,12 @@
   EXPORT_LIST += $(EXPORT_CLIENT_DIR)/Xusage.txt
   EXPORT_LIST += $(EXPORT_CLIENT_DIR)/libjvm.$(LIBRARY_SUFFIX)
   ifeq ($(ENABLE_FULL_DEBUG_SYMBOLS),1)
-    ifeq ($(ZIP_DEBUGINFO_FILES),1)
-      EXPORT_LIST += $(EXPORT_CLIENT_DIR)/libjvm.diz
-    else
-      EXPORT_LIST += $(EXPORT_CLIENT_DIR)/libjvm.debuginfo
+    ifneq ($(STRIP_POLICY),no_strip)
+      ifeq ($(ZIP_DEBUGINFO_FILES),1)
+        EXPORT_LIST += $(EXPORT_CLIENT_DIR)/libjvm.diz
+      else
+        EXPORT_LIST += $(EXPORT_CLIENT_DIR)/libjvm.debuginfo
+      endif
     endif
   endif
 endif
@@ -278,10 +284,12 @@
   EXPORT_LIST += $(EXPORT_MINIMAL_DIR)/libjvm.$(LIBRARY_SUFFIX)
 
   ifeq ($(ENABLE_FULL_DEBUG_SYMBOLS),1)
-    ifeq ($(ZIP_DEBUGINFO_FILES),1)
-	EXPORT_LIST += $(EXPORT_MINIMAL_DIR)/libjvm.diz
-    else
-	EXPORT_LIST += $(EXPORT_MINIMAL_DIR)/libjvm.debuginfo
+    ifneq ($(STRIP_POLICY),no_strip)
+      ifeq ($(ZIP_DEBUGINFO_FILES),1)
+          EXPORT_LIST += $(EXPORT_MINIMAL_DIR)/libjvm.diz
+      else
+          EXPORT_LIST += $(EXPORT_MINIMAL_DIR)/libjvm.debuginfo
+      endif
     endif
   endif
 endif
@@ -293,12 +301,14 @@
 ADD_SA_BINARIES/sparc = $(EXPORT_JRE_LIB_ARCH_DIR)/libsaproc.$(LIBRARY_SUFFIX) \
                         $(EXPORT_LIB_DIR)/sa-jdi.jar
 ifeq ($(ENABLE_FULL_DEBUG_SYMBOLS),1)
-  ifeq ($(ZIP_DEBUGINFO_FILES),1)
-    ADD_SA_BINARIES/x86   += $(EXPORT_JRE_LIB_ARCH_DIR)/libsaproc.diz
-    ADD_SA_BINARIES/sparc += $(EXPORT_JRE_LIB_ARCH_DIR)/libsaproc.diz
-  else
-    ADD_SA_BINARIES/x86   += $(EXPORT_JRE_LIB_ARCH_DIR)/libsaproc.debuginfo
-    ADD_SA_BINARIES/sparc += $(EXPORT_JRE_LIB_ARCH_DIR)/libsaproc.debuginfo
+  ifneq ($(STRIP_POLICY),no_strip)
+    ifeq ($(ZIP_DEBUGINFO_FILES),1)
+      ADD_SA_BINARIES/x86   += $(EXPORT_JRE_LIB_ARCH_DIR)/libsaproc.diz
+      ADD_SA_BINARIES/sparc += $(EXPORT_JRE_LIB_ARCH_DIR)/libsaproc.diz
+    else
+      ADD_SA_BINARIES/x86   += $(EXPORT_JRE_LIB_ARCH_DIR)/libsaproc.debuginfo
+      ADD_SA_BINARIES/sparc += $(EXPORT_JRE_LIB_ARCH_DIR)/libsaproc.debuginfo
+    endif
   endif
 endif
 ADD_SA_BINARIES/ppc   =
diff --git a/make/linux/makefiles/gcc.make b/make/linux/makefiles/gcc.make
index 06c881f..631ec22 100644
--- a/make/linux/makefiles/gcc.make
+++ b/make/linux/makefiles/gcc.make
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -184,6 +184,10 @@
 LFLAGS     += $(ARCHFLAG)
 ASFLAGS    += $(ARCHFLAG)
 
+ifeq ($(DEBUG_BINARIES), true)
+  ASFLAGS    += $(ASFLAGS_DEBUG_SYMBOLS)
+endif
+
 # Use C++ Interpreter
 ifdef CC_INTERP
   CFLAGS += -DCC_INTERP
@@ -284,6 +288,8 @@
 
 # statically link libstdc++.so, work with gcc but ignored by g++
 STATIC_STDCXX = -Wl,-Bstatic -lstdc++ -Wl,-Bdynamic
+# While the VM needs the above line, adlc needs a separate setting:
+ADLC_STATIC_STDCXX = -static-libstdc++
 
 ifeq ($(USE_CLANG),)
   # statically link libgcc and/or libgcc_s, libgcc does not exist before gcc-3.x.
@@ -314,6 +320,8 @@
 
 LFLAGS += $(LDFLAGS_HASH_STYLE)
 
+LDFLAGS_NO_EXEC_STACK="-Wl,-z,noexecstack"
+
 # Use $(MAPFLAG:FILENAME=real_file_name) to specify a map file.
 MAPFLAG = -Xlinker --version-script=FILENAME
 
@@ -340,50 +348,20 @@
 ifeq ($(DEBUG_BINARIES), true)
   CFLAGS += -g
 else
-  # Use the stabs format for debugging information (this is the default
-  # on gcc-2.91). It's good enough, has all the information about line
-  # numbers and local variables, and libjvm.so is only about 16M.
-  # Change this back to "-g" if you want the most expressive format.
-  # (warning: that could easily inflate libjvm.so to 150M!)
-  # Note: The Itanium gcc compiler crashes when using -gstabs.
-  DEBUG_CFLAGS/ia64  = -g
-  DEBUG_CFLAGS/amd64 = -g
-  DEBUG_CFLAGS/ppc64 = -g
   DEBUG_CFLAGS += $(DEBUG_CFLAGS/$(BUILDARCH))
   ifeq ($(DEBUG_CFLAGS/$(BUILDARCH)),)
-      ifeq ($(USE_CLANG), true)
-        # Clang doesn't understand -gstabs
-        DEBUG_CFLAGS/$(BUILDARCH) = -g
-      else
-        DEBUG_CFLAGS/$(BUILDARCH) = -gstabs
-      endif
+    DEBUG_CFLAGS += -g
   endif
   
   ifeq ($(ENABLE_FULL_DEBUG_SYMBOLS),1)
-    FASTDEBUG_CFLAGS/ia64  = -g
-    FASTDEBUG_CFLAGS/amd64 = -g
-    FASTDEBUG_CFLAGS/ppc64 = -g
     FASTDEBUG_CFLAGS += $(FASTDEBUG_CFLAGS/$(BUILDARCH))
     ifeq ($(FASTDEBUG_CFLAGS/$(BUILDARCH)),)
-      ifeq ($(USE_CLANG), true)
-        # Clang doesn't understand -gstabs
-        FASTDEBUG_CFLAGS/$(BUILDARCH) = -g
-      else
-        FASTDEBUG_CFLAGS/$(BUILDARCH) = -gstabs
-      endif
+      FASTDEBUG_CFLAGS/$(BUILDARCH) = -g
     endif
   
-    OPT_CFLAGS/ia64  = -g
-    OPT_CFLAGS/amd64 = -g
-    OPT_CFLAGS/ppc64 = -g
     OPT_CFLAGS += $(OPT_CFLAGS/$(BUILDARCH))
     ifeq ($(OPT_CFLAGS/$(BUILDARCH)),)
-      ifeq ($(USE_CLANG), true)
-        # Clang doesn't understand -gstabs
-        OPT_CFLAGS/$(BUILDARCH) = -g
-      else
-        OPT_CFLAGS/$(BUILDARCH) = -gstabs
-      endif
+      OPT_CFLAGS/$(BUILDARCH) = -g
     endif
   endif
 endif
diff --git a/make/linux/makefiles/jsig.make b/make/linux/makefiles/jsig.make
index 6e13959..9bf3b73 100644
--- a/make/linux/makefiles/jsig.make
+++ b/make/linux/makefiles/jsig.make
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -44,7 +44,7 @@
 # cause problems with interposing. See CR: 6466665
 # LFLAGS_JSIG += $(MAPFLAG:FILENAME=$(LIBJSIG_MAPFILE))
 
-LFLAGS_JSIG += -D_GNU_SOURCE -D_REENTRANT $(LDFLAGS_HASH_STYLE)
+LFLAGS_JSIG += -D_GNU_SOURCE -D_REENTRANT $(LDFLAGS_HASH_STYLE) $(LDFLAGS_NO_EXEC_STACK) $(EXTRA_LDFLAGS)
 
 # DEBUG_BINARIES overrides everything, use full -g debug information
 ifeq ($(DEBUG_BINARIES), true)
@@ -56,19 +56,23 @@
 	$(QUIETLY) $(CC) $(SYMFLAG) $(ARCHFLAG) $(SHARED_FLAG) $(PICFLAG) \
                          $(LFLAGS_JSIG) $(JSIG_DEBUG_CFLAGS) $(EXTRA_CFLAGS) -o $@ $< -ldl
 ifeq ($(ENABLE_FULL_DEBUG_SYMBOLS),1)
+  ifneq ($(STRIP_POLICY),no_strip)
 	$(QUIETLY) $(OBJCOPY) --only-keep-debug $@ $(LIBJSIG_DEBUGINFO)
 	$(QUIETLY) $(OBJCOPY) --add-gnu-debuglink=$(LIBJSIG_DEBUGINFO) $@
+  endif
   ifeq ($(STRIP_POLICY),all_strip)
 	$(QUIETLY) $(STRIP) $@
   else
     ifeq ($(STRIP_POLICY),min_strip)
 	$(QUIETLY) $(STRIP) -g $@
-    # implied else here is no stripping at all
     endif
+    # implied else here is no stripping at all
   endif
-  ifeq ($(ZIP_DEBUGINFO_FILES),1)
+  ifneq ($(STRIP_POLICY),no_strip)
+    ifeq ($(ZIP_DEBUGINFO_FILES),1)
 	$(ZIPEXE) -q -y $(LIBJSIG_DIZ) $(LIBJSIG_DEBUGINFO)
 	$(RM) $(LIBJSIG_DEBUGINFO)
+    endif
   endif
 endif
 
diff --git a/make/linux/makefiles/mapfile-vers-debug b/make/linux/makefiles/mapfile-vers-debug
index 2da4b7d..f16822b 100644
--- a/make/linux/makefiles/mapfile-vers-debug
+++ b/make/linux/makefiles/mapfile-vers-debug
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -63,6 +63,7 @@
                 JVM_ConstantPoolGetSize;
                 JVM_ConstantPoolGetStringAt;
                 JVM_ConstantPoolGetUTF8At;
+                JVM_CopySwapMemory;
                 JVM_CountStackFrames;
                 JVM_CurrentClassLoader;
                 JVM_CurrentLoadedClass;
diff --git a/make/linux/makefiles/mapfile-vers-product b/make/linux/makefiles/mapfile-vers-product
index 4ec3d5b..f96c86b 100644
--- a/make/linux/makefiles/mapfile-vers-product
+++ b/make/linux/makefiles/mapfile-vers-product
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -63,6 +63,7 @@
                 JVM_ConstantPoolGetSize;
                 JVM_ConstantPoolGetStringAt;
                 JVM_ConstantPoolGetUTF8At;
+                JVM_CopySwapMemory;
                 JVM_CountStackFrames;
                 JVM_CurrentClassLoader;
                 JVM_CurrentLoadedClass;
diff --git a/make/linux/makefiles/saproc.make b/make/linux/makefiles/saproc.make
index 6579c8e..ffc0ec5 100644
--- a/make/linux/makefiles/saproc.make
+++ b/make/linux/makefiles/saproc.make
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -59,6 +59,11 @@
   SA_DEBUG_CFLAGS = -g
 endif
 
+# Optimize saproc lib at level -O3 unless it's a slowdebug build
+ifneq ($(BUILD_FLAVOR), debug)
+  SA_OPT_FLAGS = $(OPT_CFLAGS)
+endif
+
 # if $(AGENT_DIR) does not exist, we don't build SA
 # also, we don't build SA on Itanium or zero.
 
@@ -73,7 +78,8 @@
 else
 ALT_SAINCDIR=
 endif
-SA_LFLAGS = $(MAPFLAG:FILENAME=$(SAMAPFILE)) $(LDFLAGS_HASH_STYLE)
+SA_LFLAGS = $(MAPFLAG:FILENAME=$(SAMAPFILE)) $(LDFLAGS_HASH_STYLE) \
+            $(LDFLAGS_NO_EXEC_STACK) $(EXTRA_LDFLAGS)
 
 SAARCH ?= $(BUILDARCH)
 
@@ -94,23 +100,28 @@
 	           $(SASRCFILES)                                        \
 	           $(SA_LFLAGS)                                         \
 	           $(SA_DEBUG_CFLAGS)                                   \
+	           $(SA_OPT_FLAGS)                                      \
 	           $(EXTRA_CFLAGS)                                      \
 	           -o $@                                                \
-	           -lthread_db
+	           -lthread_db -ldl
 ifeq ($(ENABLE_FULL_DEBUG_SYMBOLS),1)
+  ifneq ($(STRIP_POLICY),no_strip)
 	$(QUIETLY) $(OBJCOPY) --only-keep-debug $@ $(LIBSAPROC_DEBUGINFO)
 	$(QUIETLY) $(OBJCOPY) --add-gnu-debuglink=$(LIBSAPROC_DEBUGINFO) $@
+  endif
   ifeq ($(STRIP_POLICY),all_strip)
 	$(QUIETLY) $(STRIP) $@
   else
     ifeq ($(STRIP_POLICY),min_strip)
 	$(QUIETLY) $(STRIP) -g $@
-    # implied else here is no stripping at all
     endif
+    # implied else here is no stripping at all
   endif
-  ifeq ($(ZIP_DEBUGINFO_FILES),1)
+  ifneq ($(STRIP_POLICY),no_strip)
+    ifeq ($(ZIP_DEBUGINFO_FILES),1)
 	$(ZIPEXE) -q -y $(LIBSAPROC_DIZ) $(LIBSAPROC_DEBUGINFO)
 	$(RM) $(LIBSAPROC_DEBUGINFO)
+    endif
   endif
 endif
 
diff --git a/make/linux/makefiles/vm.make b/make/linux/makefiles/vm.make
index 1a48df9..05e9bc0 100644
--- a/make/linux/makefiles/vm.make
+++ b/make/linux/makefiles/vm.make
@@ -122,7 +122,7 @@
 
 # Extra flags from gnumake's invocation or environment
 CFLAGS += $(EXTRA_CFLAGS)
-LFLAGS += $(EXTRA_CFLAGS)
+LFLAGS += $(EXTRA_CFLAGS) $(EXTRA_LDFLAGS)
 
 # Don't set excutable bit on stack segment
 # the same could be done by separate execstack command
@@ -357,19 +357,23 @@
 	}
 
 ifeq ($(ENABLE_FULL_DEBUG_SYMBOLS),1)
+  ifneq ($(STRIP_POLICY),no_strip)
 	$(QUIETLY) $(OBJCOPY) --only-keep-debug $@ $(LIBJVM_DEBUGINFO)
 	$(QUIETLY) $(OBJCOPY) --add-gnu-debuglink=$(LIBJVM_DEBUGINFO) $@
+  endif
   ifeq ($(STRIP_POLICY),all_strip)
 	$(QUIETLY) $(STRIP) $@
   else
     ifeq ($(STRIP_POLICY),min_strip)
 	$(QUIETLY) $(STRIP) -g $@
-    # implied else here is no stripping at all
     endif
+    # implied else here is no stripping at all
   endif
-  ifeq ($(ZIP_DEBUGINFO_FILES),1)
+  ifneq ($(STRIP_POLICY),no_strip)
+    ifeq ($(ZIP_DEBUGINFO_FILES),1)
 	$(ZIPEXE) -q -y $(LIBJVM_DIZ) $(LIBJVM_DEBUGINFO)
 	$(RM) $(LIBJVM_DEBUGINFO)
+    endif
   endif
 endif
 
diff --git a/make/solaris/makefiles/adlc.make b/make/solaris/makefiles/adlc.make
index 88d9d2b..ef87d3e 100644
--- a/make/solaris/makefiles/adlc.make
+++ b/make/solaris/makefiles/adlc.make
@@ -76,6 +76,11 @@
 ifeq ($(shell expr $(COMPILER_REV_NUMERIC) \>= 509), 1)
   CFLAGS_WARN = +w -errwarn
 endif
+# When using compiler version 5.13 (Solaris Studio 12.4), calls to explicitly 
+# instantiated template functions trigger this warning when +w is active.
+ifeq ($(shell expr $(COMPILER_REV_NUMERIC) \>= 513), 1)
+  CFLAGS_WARN += -erroff=notemsource
+endif
 CFLAGS += $(CFLAGS_WARN)
 
 ifeq ("${Platform_compiler}", "sparcWorks")
diff --git a/make/solaris/makefiles/mapfile-vers b/make/solaris/makefiles/mapfile-vers
index 7ebaaaa..d76be6c 100644
--- a/make/solaris/makefiles/mapfile-vers
+++ b/make/solaris/makefiles/mapfile-vers
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -64,6 +64,7 @@
                 JVM_ConstantPoolGetStringAt;
                 JVM_ConstantPoolGetUTF8At;
                 JVM_CountStackFrames;
+                JVM_CopySwapMemory;
                 JVM_CurrentClassLoader;
                 JVM_CurrentLoadedClass;
                 JVM_CurrentThread;
diff --git a/make/windows/makefiles/compile.make b/make/windows/makefiles/compile.make
index a936f2e..c867a1a 100644
--- a/make/windows/makefiles/compile.make
+++ b/make/windows/makefiles/compile.make
@@ -112,6 +112,46 @@
 #    closer to VS2003 in terms of option spellings, so we use 1399 for that
 #    1400 version that really isn't 1400.
 #    See the file get_msc_ver.sh for more info.
+!if "x$(MSC_VER)" == "x"
+COMPILER_NAME=$(DEFAULT_COMPILER_NAME)
+!else
+!if "$(MSC_VER)" == "1200"
+COMPILER_NAME=VC6
+!endif
+!if "$(MSC_VER)" == "1300"
+COMPILER_NAME=VS2003
+!endif
+!if "$(MSC_VER)" == "1310"
+COMPILER_NAME=VS2003
+!endif
+!if "$(MSC_VER)" == "1399"
+# Compiler might say 1400, but if it's 14.00.30701, it isn't really VS2005
+COMPILER_NAME=VS2003
+!endif
+!if "$(MSC_VER)" == "1400"
+COMPILER_NAME=VS2005
+!endif
+!if "$(MSC_VER)" == "1500"
+COMPILER_NAME=VS2008
+!endif
+!if "$(MSC_VER)" == "1600"
+COMPILER_NAME=VS2010
+!endif
+!if "$(MSC_VER)" == "1700"
+COMPILER_NAME=VS2012
+!endif
+!if "$(MSC_VER)" == "1800"
+COMPILER_NAME=VS2013
+!endif
+!if "$(MSC_VER)" == "1900"
+COMPILER_NAME=VS2015
+!endif
+!if "$(MSC_VER)" == "1912"
+COMPILER_NAME=VS2017
+!endif
+!if "$(MSC_VER)" == "1913"
+COMPILER_NAME=VS2017
+!endif
 
 # By default, we do not want to use the debug version of the msvcrt.dll file
 #   but if MFC_DEBUG is defined in the environment it will be used.
@@ -143,6 +183,72 @@
 !if "$(BUILDARCH)" == "i486"
 LD_FLAGS = /SAFESEH $(LD_FLAGS)
 !endif
+!endif
+
+!if "$(COMPILER_NAME)" == "VS2012"
+PRODUCT_OPT_OPTION   = /O2 /Oy-
+FASTDEBUG_OPT_OPTION = /O2 /Oy-
+DEBUG_OPT_OPTION     = /Od
+GX_OPTION = /EHsc
+LD_FLAGS = /manifest $(LD_FLAGS)
+MP_FLAG = /MP
+# Manifest Tool - used in VS2005 and later to adjust manifests stored
+# as resources inside build artifacts.
+!if "x$(MT)" == "x"
+MT=mt.exe
+!endif
+SAFESEH_FLAG = /SAFESEH
+!endif
+
+!if "$(COMPILER_NAME)" == "VS2013"
+PRODUCT_OPT_OPTION   = /O2 /Oy-
+FASTDEBUG_OPT_OPTION = /O2 /Oy-
+DEBUG_OPT_OPTION     = /Od
+GX_OPTION = /EHsc
+LD_FLAGS = /manifest $(LD_FLAGS)
+MP_FLAG = /MP
+# Manifest Tool - used in VS2005 and later to adjust manifests stored
+# as resources inside build artifacts.
+!if "x$(MT)" == "x"
+MT=mt.exe
+!endif
+SAFESEH_FLAG = /SAFESEH
+!endif
+
+
+!if "$(COMPILER_NAME)" == "VS2015"
+PRODUCT_OPT_OPTION   = /O2 /Oy-
+FASTDEBUG_OPT_OPTION = /O2 /Oy-
+DEBUG_OPT_OPTION     = /Od
+GX_OPTION = /EHsc
+LD_FLAGS = /manifest $(LD_FLAGS)
+MP_FLAG = /MP
+# Manifest Tool - used in VS2005 and later to adjust manifests stored
+# as resources inside build artifacts.
+!if "x$(MT)" == "x"
+MT=mt.exe
+!endif
+SAFESEH_FLAG = /SAFESEH
+!endif
+
+!if "$(COMPILER_NAME)" == "VS2017"
+PRODUCT_OPT_OPTION   = /O2 /Oy-
+FASTDEBUG_OPT_OPTION = /O2 /Oy-
+DEBUG_OPT_OPTION     = /Od
+GX_OPTION = /EHsc
+LD_FLAGS = /manifest $(LD_FLAGS)
+MP_FLAG = /MP
+# Manifest Tool - used in VS2005 and later to adjust manifests stored
+# as resources inside build artifacts.
+!if "x$(MT)" == "x"
+MT=mt.exe
+!endif
+SAFESEH_FLAG = /SAFESEH
+!endif
+
+!if "$(BUILDARCH)" == "i486"
+LD_FLAGS = $(SAFESEH_FLAG) $(LD_FLAGS)
+!endif
 
 CXX_FLAGS = $(CXX_FLAGS) $(MP_FLAG)
 
diff --git a/make/windows/makefiles/sa.make b/make/windows/makefiles/sa.make
index 5242b33..3cf42e6 100644
--- a/make/windows/makefiles/sa.make
+++ b/make/windows/makefiles/sa.make
@@ -81,22 +81,38 @@
 
 checkAndBuildSA:: $(SAWINDBG)
 
-# These do not need to be optimized (don't run a lot of code) and it
-# will be useful to have the assertion checks in place
+!if "$(BUILD_FLAVOR)" == "debug"
+SA_EXTRA_CFLAGS = -Od -D "_DEBUG"
+!if "$(BUILDARCH)" == "i486"
+SA_EXTRA_CFLAGS = $(SA_EXTRA_CFLAGS) -RTC1
+!endif
+!elseif "$(BUILD_FLAVOR)" == "fastdebug"
+SA_EXTRA_CFLAGS = -O2 -D "_DEBUG"
+!else
+SA_EXTRA_CFLAGS = -O2
+!endif
 
 !if "$(BUILDARCH)" == "ia64"
-SA_CFLAGS = -nologo $(MS_RUNTIME_OPTION) -W3 $(GX_OPTION) -Od -D "WIN32" -D "WIN64" -D "_WINDOWS" -D "_DEBUG" -D "_CONSOLE" -D "_MBCS" -FD -c
+SA_CFLAGS = -nologo $(MS_RUNTIME_OPTION) -W3 $(GX_OPTION) -D "WIN32" -D "WIN64" -D "_WINDOWS"  -D "_CONSOLE" -D "_MBCS" -YX -FD -c
 !elseif "$(BUILDARCH)" == "amd64"
-SA_CFLAGS = -nologo $(MS_RUNTIME_OPTION) -W3 $(GX_OPTION) -Od -D "WIN32" -D "WIN64" -D "_WINDOWS" -D "_DEBUG" -D "_CONSOLE" -D "_MBCS" -FD -c
+SA_CFLAGS = -nologo $(MS_RUNTIME_OPTION) -W3 $(GX_OPTION) -D "WIN32" -D "WIN64" -D "_WINDOWS" -D "_CONSOLE" -D "_MBCS" -YX -FD -c
+!if "$(COMPILER_NAME)" == "VS2005"
+# On amd64, VS2005 compiler requires bufferoverflowU.lib on the link command line, 
+# otherwise we get missing __security_check_cookie externals at link time. 
+SA_LD_FLAGS = bufferoverflowU.lib
+!endif
 !else
-SA_CFLAGS = -nologo $(MS_RUNTIME_OPTION) -W3 $(GX_OPTION) -Od -D "WIN32" -D "_WINDOWS" -D "_DEBUG" -D "_CONSOLE" -D "_MBCS" -FD -RTC1 -c
+SA_CFLAGS = -nologo $(MS_RUNTIME_OPTION) -W3 -Gm $(GX_OPTION) -D "WIN32" -D "_WINDOWS" -D "_CONSOLE" -D "_MBCS" -YX -FD -c
 !if "$(ENABLE_FULL_DEBUG_SYMBOLS)" == "1"
-SA_CFLAGS = $(SA_CFLAGS) -ZI
+# -ZI is incompatible with -O2 used for release/fastdebug builds.
+# Using -Zi instead.
+SA_CFLAGS = $(SA_CFLAGS) -Zi
 !endif
 !endif
 !if "$(MT)" != ""
 SA_LD_FLAGS = -manifest $(SA_LD_FLAGS)
 !endif
+SA_CFLAGS = $(SA_CFLAGS) $(SA_EXTRA_CFLAGS)
 
 SASRCFILES = $(AGENT_DIR)/src/os/win32/windbg/sawindbg.cpp \
 		$(AGENT_DIR)/src/share/native/sadis.c
diff --git a/make/windows/makefiles/sanity.make b/make/windows/makefiles/sanity.make
index b502cfa..5a76ad7 100644
--- a/make/windows/makefiles/sanity.make
+++ b/make/windows/makefiles/sanity.make
@@ -28,8 +28,15 @@
 
 checkCL:
 	@ if "$(MSC_VER)" NEQ "1310" if "$(MSC_VER)" NEQ "1399" if "$(MSC_VER)" NEQ "1400" if "$(MSC_VER)" NEQ "1500" if "$(MSC_VER)" NEQ "1600" if "$(MSC_VER)" NEQ "1700" \
+	if "$(MSC_VER)" NEQ "1800" \
+	if "$(MSC_VER)" NEQ "1900" \
+	if "$(MSC_VER)" NEQ "1912" \
 	echo *** WARNING *** unrecognized cl.exe version $(MSC_VER) ($(RAW_MSC_VER)).  Use FORCE_MSC_VER to override automatic detection.
 
 checkLink:
 	@ if "$(LD_VER)" NEQ "710" if "$(LD_VER)" NEQ "800" if "$(LD_VER)" NEQ "900" if "$(LD_VER)" NEQ "1000" if "$(LD_VER)" NEQ "1100" \
+	if "$(LD_VER)" NEQ "1200" \
+	if "$(LD_VER)" NEQ "1300" \
+	if "$(LD_VER)" NEQ "1400" \
+	if "$(LD_VER)" NEQ "1412" \
 	echo *** WARNING *** unrecognized link.exe version $(LD_VER) ($(RAW_LD_VER)).  Use FORCE_LD_VER to override automatic detection.
diff --git a/make/windows/makefiles/vm.make b/make/windows/makefiles/vm.make
index f082846..61a8f08 100644
--- a/make/windows/makefiles/vm.make
+++ b/make/windows/makefiles/vm.make
@@ -56,10 +56,6 @@
 
 # The following variables are defined in the generated local.make file.
 CXX_FLAGS=$(CXX_FLAGS) /D "HOTSPOT_RELEASE_VERSION=\"$(HS_BUILD_VER)\""
-CXX_FLAGS=$(CXX_FLAGS) /D "JDK_MAJOR_VERSION=\"$(JDK_MAJOR_VERSION)\""
-CXX_FLAGS=$(CXX_FLAGS) /D "JDK_MINOR_VERSION=\"$(JDK_MINOR_VERSION)\""
-CXX_FLAGS=$(CXX_FLAGS) /D "JDK_MICRO_VERSION=\"$(JDK_MICRO_VERSION)\""
-CXX_FLAGS=$(CXX_FLAGS) /D "JDK_BUILD_NUMBER=\"$(JDK_BUILD_NUMBER)\""
 CXX_FLAGS=$(CXX_FLAGS) /D "JRE_RELEASE_VERSION=\"$(JRE_RELEASE_VER)\""
 CXX_FLAGS=$(CXX_FLAGS) /D "HOTSPOT_LIB_ARCH=\"$(HOTSPOT_LIB_ARCH)\""
 CXX_FLAGS=$(CXX_FLAGS) /D "HOTSPOT_BUILD_TARGET=\"$(BUILD_FLAVOR)\""
@@ -132,8 +128,8 @@
 
 !if "$(USE_PRECOMPILED_HEADER)" != "0"
 CXX_USE_PCH=/Fp"vm.pch" /Yu"precompiled.hpp"
-!if "$(MSC_VER)" > "1600"
-# VS2012 requires this object file to be listed:
+!if "$(COMPILER_NAME)" == "VS2012" || "$(COMPILER_NAME)" == "VS2013" || "$(COMPILER_NAME)" == "VS2015" || "$(COMPILER_NAME)" == "VS2017"
+# VS2012 and later require this object file to be listed:
 LD_FLAGS=$(LD_FLAGS) _build_pch_file.obj
 !endif
 !else
diff --git a/src/cpu/ppc/vm/assembler_ppc.hpp b/src/cpu/ppc/vm/assembler_ppc.hpp
index a488d6d..ddd0751 100644
--- a/src/cpu/ppc/vm/assembler_ppc.hpp
+++ b/src/cpu/ppc/vm/assembler_ppc.hpp
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
- * Copyright 2012, 2013 SAP AG. All rights reserved.
+ * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018, SAP SE. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -468,6 +468,10 @@
     LVSL_OPCODE    = (31u << OPCODE_SHIFT |    6u << 1),
     LVSR_OPCODE    = (31u << OPCODE_SHIFT |   38u << 1),
 
+    // Vector-Scalar (VSX) instruction support.
+    MTVSRD_OPCODE  = (31u << OPCODE_SHIFT |  179u << 1),
+    MFVSRD_OPCODE  = (31u << OPCODE_SHIFT |   51u << 1),
+
     // Vector Permute and Formatting
     VPKPX_OPCODE   = (4u  << OPCODE_SHIFT |  782u     ),
     VPKSHSS_OPCODE = (4u  << OPCODE_SHIFT |  398u     ),
@@ -1180,6 +1184,8 @@
   inline void mullw_( Register d, Register a, Register b);
   inline void mulhw(  Register d, Register a, Register b);
   inline void mulhw_( Register d, Register a, Register b);
+  inline void mulhwu( Register d, Register a, Register b);
+  inline void mulhwu_(Register d, Register a, Register b);
   inline void mulhd(  Register d, Register a, Register b);
   inline void mulhd_( Register d, Register a, Register b);
   inline void mulhdu( Register d, Register a, Register b);
@@ -1832,7 +1838,7 @@
   inline void vperm(    VectorRegister d, VectorRegister a, VectorRegister b, VectorRegister c);
   inline void vsel(     VectorRegister d, VectorRegister a, VectorRegister b, VectorRegister c);
   inline void vsl(      VectorRegister d, VectorRegister a, VectorRegister b);
-  inline void vsldoi(   VectorRegister d, VectorRegister a, VectorRegister b, int si4);
+  inline void vsldoi(   VectorRegister d, VectorRegister a, VectorRegister b, int ui4);
   inline void vslo(     VectorRegister d, VectorRegister a, VectorRegister b);
   inline void vsr(      VectorRegister d, VectorRegister a, VectorRegister b);
   inline void vsro(     VectorRegister d, VectorRegister a, VectorRegister b);
@@ -1936,6 +1942,10 @@
   inline void mtvscr(   VectorRegister b);
   inline void mfvscr(   VectorRegister d);
 
+  // Vector-Scalar (VSX) instructions.
+  inline void mtvrd(    VectorRegister  d, Register a);
+  inline void mfvrd(    Register        a, 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);
diff --git a/src/cpu/ppc/vm/assembler_ppc.inline.hpp b/src/cpu/ppc/vm/assembler_ppc.inline.hpp
index 0f76435..3c66cbb 100644
--- a/src/cpu/ppc/vm/assembler_ppc.inline.hpp
+++ b/src/cpu/ppc/vm/assembler_ppc.inline.hpp
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
- * Copyright 2012, 2014 SAP AG. All rights reserved.
+ * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018, SAP SE. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -109,6 +109,8 @@
 inline void Assembler::mullw_( Register d, Register a, Register b) { emit_int32(MULLW_OPCODE  | rt(d) | ra(a) | rb(b) | oe(0) | rc(1)); }
 inline void Assembler::mulhw(  Register d, Register a, Register b) { emit_int32(MULHW_OPCODE  | rt(d) | ra(a) | rb(b) | rc(0)); }
 inline void Assembler::mulhw_( Register d, Register a, Register b) { emit_int32(MULHW_OPCODE  | rt(d) | ra(a) | rb(b) | rc(1)); }
+inline void Assembler::mulhwu( Register d, Register a, Register b) { emit_int32(MULHWU_OPCODE | rt(d) | ra(a) | rb(b) | rc(0)); }
+inline void Assembler::mulhwu_(Register d, Register a, Register b) { emit_int32(MULHWU_OPCODE | rt(d) | ra(a) | rb(b) | rc(1)); }
 inline void Assembler::mulhd(  Register d, Register a, Register b) { emit_int32(MULHD_OPCODE  | rt(d) | ra(a) | rb(b) | rc(0)); }
 inline void Assembler::mulhd_( Register d, Register a, Register b) { emit_int32(MULHD_OPCODE  | rt(d) | ra(a) | rb(b) | rc(1)); }
 inline void Assembler::mulhdu( Register d, Register a, Register b) { emit_int32(MULHDU_OPCODE | rt(d) | ra(a) | rb(b) | rc(0)); }
@@ -621,6 +623,10 @@
 inline void Assembler::lvsl(  VectorRegister d, Register s1, Register s2) { emit_int32( LVSL_OPCODE   | vrt(d) | ra0mem(s1) | rb(s2)); }
 inline void Assembler::lvsr(  VectorRegister d, Register s1, Register s2) { emit_int32( LVSR_OPCODE   | vrt(d) | ra0mem(s1) | rb(s2)); }
 
+// Vector-Scalar (VSX) instructions.
+inline void Assembler::mtvrd(  VectorRegister  d, Register a)               { emit_int32( MTVSRD_OPCODE  | vrt(d)  | ra(a)  | 1u); } // 1u: d is treated as Vector (VMX/Altivec).
+inline void Assembler::mfvrd(  Register        a, VectorRegister d)         { emit_int32( MFVSRD_OPCODE  | vrt(d)  | ra(a)  | 1u); } // 1u: d is treated as Vector (VMX/Altivec).
+
 inline void Assembler::vpkpx(   VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VPKPX_OPCODE   | vrt(d) | vra(a) | vrb(b)); }
 inline void Assembler::vpkshss( VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VPKSHSS_OPCODE | vrt(d) | vra(a) | vrb(b)); }
 inline void Assembler::vpkswss( VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VPKSWSS_OPCODE | vrt(d) | vra(a) | vrb(b)); }
@@ -651,7 +657,7 @@
 inline void Assembler::vperm(   VectorRegister d, VectorRegister a, VectorRegister b, VectorRegister c){ emit_int32( VPERM_OPCODE | vrt(d) | vra(a) | vrb(b) | vrc(c)); }
 inline void Assembler::vsel(    VectorRegister d, VectorRegister a, VectorRegister b, VectorRegister c){ emit_int32( VSEL_OPCODE  | vrt(d) | vra(a) | vrb(b) | vrc(c)); }
 inline void Assembler::vsl(     VectorRegister d, VectorRegister a, VectorRegister b)                  { emit_int32( VSL_OPCODE   | vrt(d) | vra(a) | vrb(b)); }
-inline void Assembler::vsldoi(  VectorRegister d, VectorRegister a, VectorRegister b, int si4)         { emit_int32( VSLDOI_OPCODE| vrt(d) | vra(a) | vrb(b) | vsldoi_shb(simm(si4,4))); }
+inline void Assembler::vsldoi(  VectorRegister d, VectorRegister a, VectorRegister b, int ui4)         { emit_int32( VSLDOI_OPCODE| vrt(d) | vra(a) | vrb(b) | vsldoi_shb(uimm(ui4,4))); }
 inline void Assembler::vslo(    VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VSLO_OPCODE    | vrt(d) | vra(a) | vrb(b)); }
 inline void Assembler::vsr(     VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VSR_OPCODE     | vrt(d) | vra(a) | vrb(b)); }
 inline void Assembler::vsro(    VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VSRO_OPCODE    | vrt(d) | vra(a) | vrb(b)); }
diff --git a/src/cpu/ppc/vm/c2_init_ppc.cpp b/src/cpu/ppc/vm/c2_init_ppc.cpp
index 94b59db..74f50f6 100644
--- a/src/cpu/ppc/vm/c2_init_ppc.cpp
+++ b/src/cpu/ppc/vm/c2_init_ppc.cpp
@@ -45,4 +45,10 @@
       FLAG_SET_ERGO(bool, InsertEndGroupPPC64, true);
     }
   }
+
+  if (OptimizeFill) {
+    warning("OptimizeFill is not supported on this CPU.");
+    FLAG_SET_DEFAULT(OptimizeFill, false);
+  }
+
 }
diff --git a/src/cpu/ppc/vm/interpreterGenerator_ppc.hpp b/src/cpu/ppc/vm/interpreterGenerator_ppc.hpp
index 74f6001..5c9ef8d 100644
--- a/src/cpu/ppc/vm/interpreterGenerator_ppc.hpp
+++ b/src/cpu/ppc/vm/interpreterGenerator_ppc.hpp
@@ -33,5 +33,7 @@
   address generate_abstract_entry(void);
   address generate_accessor_entry(void);
   address generate_Reference_get_entry(void);
+  address generate_CRC32_update_entry();
+  address generate_CRC32_updateBytes_entry(AbstractInterpreter::MethodKind kind);
 
 #endif // CPU_PPC_VM_INTERPRETERGENERATOR_PPC_HPP
diff --git a/src/cpu/ppc/vm/macroAssembler_ppc.cpp b/src/cpu/ppc/vm/macroAssembler_ppc.cpp
index a96e310..a140b36 100644
--- a/src/cpu/ppc/vm/macroAssembler_ppc.cpp
+++ b/src/cpu/ppc/vm/macroAssembler_ppc.cpp
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
- * Copyright 2012, 2014 SAP AG. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018, SAP SE. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -49,6 +49,7 @@
 #else
 #define BLOCK_COMMENT(str) block_comment(str)
 #endif
+#define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
 
 #ifdef ASSERT
 // On RISC, there's no benefit to verifying instruction boundaries.
@@ -1531,11 +1532,10 @@
                                              RegisterOrConstant itable_index,
                                              Register method_result,
                                              Register scan_temp,
-                                             Register sethi_temp,
-                                             Label& L_no_such_interface) {
+                                             Register temp2,
+                                             Label& L_no_such_interface,
+                                             bool return_method) {
   assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
-  assert(itable_index.is_constant() || itable_index.as_register() == method_result,
-         "caller must use same register for non-constant itable index as for method");
 
   // Compute start of first itableOffsetEntry (which is at the end of the vtable).
   int vtable_base = InstanceKlass::vtable_start_offset() * wordSize;
@@ -1553,15 +1553,18 @@
   add(scan_temp, recv_klass, scan_temp);
 
   // Adjust recv_klass by scaled itable_index, so we can free itable_index.
-  if (itable_index.is_register()) {
-    Register itable_offset = itable_index.as_register();
-    sldi(itable_offset, itable_offset, logMEsize);
-    if (itentry_off) addi(itable_offset, itable_offset, itentry_off);
-    add(recv_klass, itable_offset, recv_klass);
-  } else {
-    long itable_offset = (long)itable_index.as_constant();
-    load_const_optimized(sethi_temp, (itable_offset<<logMEsize)+itentry_off); // static address, no relocation
-    add(recv_klass, sethi_temp, recv_klass);
+  if (return_method) {
+    if (itable_index.is_register()) {
+      Register itable_offset = itable_index.as_register();
+      sldi(method_result, itable_offset, logMEsize);
+      if (itentry_off) { addi(method_result, method_result, itentry_off); }
+      add(method_result, method_result, recv_klass);
+    } else {
+      long itable_offset = (long)itable_index.as_constant();
+      // static address, no relocation
+      load_const_optimized(temp2, (itable_offset << logMEsize) + itentry_off); // static address, no relocation
+      add(method_result, temp2, recv_klass);
+    }
   }
 
   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
@@ -1574,12 +1577,12 @@
   for (int peel = 1; peel >= 0; peel--) {
     // %%%% Could load both offset and interface in one ldx, if they were
     // in the opposite order. This would save a load.
-    ld(method_result, itableOffsetEntry::interface_offset_in_bytes(), scan_temp);
+    ld(temp2, itableOffsetEntry::interface_offset_in_bytes(), scan_temp);
 
     // Check that this entry is non-null. A null entry means that
     // the receiver class doesn't implement the interface, and wasn't the
     // same as when the caller was compiled.
-    cmpd(CCR0, method_result, intf_klass);
+    cmpd(CCR0, temp2, intf_klass);
 
     if (peel) {
       beq(CCR0, found_method);
@@ -1592,7 +1595,7 @@
 
     bind(search);
 
-    cmpdi(CCR0, method_result, 0);
+    cmpdi(CCR0, temp2, 0);
     beq(CCR0, L_no_such_interface);
     addi(scan_temp, scan_temp, scan_step);
   }
@@ -1600,9 +1603,11 @@
   bind(found_method);
 
   // Got a hit.
-  int ito_offset = itableOffsetEntry::offset_offset_in_bytes();
-  lwz(scan_temp, ito_offset, scan_temp);
-  ldx(method_result, scan_temp, recv_klass);
+  if (return_method) {
+    int ito_offset = itableOffsetEntry::offset_offset_in_bytes();
+    lwz(scan_temp, ito_offset, scan_temp);
+    ldx(method_result, scan_temp, method_result);
+  }
 }
 
 // virtual method calling
@@ -3018,6 +3023,977 @@
   bind(Ldone_false);
 }
 
+// Helpers for Intrinsic Emitters
+//
+// Revert the byte order of a 32bit value in a register
+//   src: 0x44556677
+//   dst: 0x77665544
+// Three steps to obtain the result:
+//  1) Rotate src (as doubleword) left 5 bytes. That puts the leftmost byte of the src word
+//     into the rightmost byte position. Afterwards, everything left of the rightmost byte is cleared.
+//     This value initializes dst.
+//  2) Rotate src (as word) left 3 bytes. That puts the rightmost byte of the src word into the leftmost
+//     byte position. Furthermore, byte 5 is rotated into byte 6 position where it is supposed to go.
+//     This value is mask inserted into dst with a [0..23] mask of 1s.
+//  3) Rotate src (as word) left 1 byte. That puts byte 6 into byte 5 position.
+//     This value is mask inserted into dst with a [8..15] mask of 1s.
+void MacroAssembler::load_reverse_32(Register dst, Register src) {
+  assert_different_registers(dst, src);
+
+  rldicl(dst, src, (4+1)*8, 56);       // Rotate byte 4 into position 7 (rightmost), clear all to the left.
+  rlwimi(dst, src,     3*8,  0, 23);   // Insert byte 5 into position 6, 7 into 4, leave pos 7 alone.
+  rlwimi(dst, src,     1*8,  8, 15);   // Insert byte 6 into position 5, leave the rest alone.
+}
+
+// Calculate the column addresses of the crc32 lookup table into distinct registers.
+// This loop-invariant calculation is moved out of the loop body, reducing the loop
+// body size from 20 to 16 instructions.
+// Returns the offset that was used to calculate the address of column tc3.
+// Due to register shortage, setting tc3 may overwrite table. With the return offset
+// at hand, the original table address can be easily reconstructed.
+int MacroAssembler::crc32_table_columns(Register table, Register tc0, Register tc1, Register tc2, Register tc3) {
+
+#ifdef VM_LITTLE_ENDIAN
+  // This is what we implement (the DOLIT4 part):
+  // ========================================================================= */
+  // #define DOLIT4 c ^= *buf4++; \
+  //         c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
+  //             crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
+  // #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
+  // ========================================================================= */
+  const int ix0 = 3*(4*CRC32_COLUMN_SIZE);
+  const int ix1 = 2*(4*CRC32_COLUMN_SIZE);
+  const int ix2 = 1*(4*CRC32_COLUMN_SIZE);
+  const int ix3 = 0*(4*CRC32_COLUMN_SIZE);
+#else
+  // This is what we implement (the DOBIG4 part):
+  // =========================================================================
+  // #define DOBIG4 c ^= *++buf4; \
+  //         c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
+  //             crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
+  // #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
+  // =========================================================================
+  const int ix0 = 4*(4*CRC32_COLUMN_SIZE);
+  const int ix1 = 5*(4*CRC32_COLUMN_SIZE);
+  const int ix2 = 6*(4*CRC32_COLUMN_SIZE);
+  const int ix3 = 7*(4*CRC32_COLUMN_SIZE);
+#endif
+  assert_different_registers(table, tc0, tc1, tc2);
+  assert(table == tc3, "must be!");
+
+  if (ix0 != 0) addi(tc0, table, ix0);
+  if (ix1 != 0) addi(tc1, table, ix1);
+  if (ix2 != 0) addi(tc2, table, ix2);
+  if (ix3 != 0) addi(tc3, table, ix3);
+
+  return ix3;
+}
+
+/**
+ * uint32_t crc;
+ * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
+ */
+void MacroAssembler::fold_byte_crc32(Register crc, Register val, Register table, Register tmp) {
+  assert_different_registers(crc, table, tmp);
+  assert_different_registers(val, table);
+
+  if (crc == val) {                   // Must rotate first to use the unmodified value.
+    rlwinm(tmp, val, 2, 24-2, 31-2);  // Insert (rightmost) byte 7 of val, shifted left by 2, into byte 6..7 of tmp, clear the rest.
+                                      // As we use a word (4-byte) instruction, we have to adapt the mask bit positions.
+    srwi(crc, crc, 8);                // Unsigned shift, clear leftmost 8 bits.
+  } else {
+    srwi(crc, crc, 8);                // Unsigned shift, clear leftmost 8 bits.
+    rlwinm(tmp, val, 2, 24-2, 31-2);  // Insert (rightmost) byte 7 of val, shifted left by 2, into byte 6..7 of tmp, clear the rest.
+  }
+  lwzx(tmp, table, tmp);
+  xorr(crc, crc, tmp);
+}
+
+/**
+ * uint32_t crc;
+ * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
+ */
+void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
+  fold_byte_crc32(crc, crc, table, tmp);
+}
+
+/**
+ * Emits code to update CRC-32 with a byte value according to constants in table.
+ *
+ * @param [in,out]crc   Register containing the crc.
+ * @param [in]val       Register containing the byte to fold into the CRC.
+ * @param [in]table     Register containing the table of crc constants.
+ *
+ * uint32_t crc;
+ * val = crc_table[(val ^ crc) & 0xFF];
+ * crc = val ^ (crc >> 8);
+ */
+void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
+  BLOCK_COMMENT("update_byte_crc32:");
+  xorr(val, val, crc);
+  fold_byte_crc32(crc, val, table, val);
+}
+
+/**
+ * @param crc   register containing existing CRC (32-bit)
+ * @param buf   register pointing to input byte buffer (byte*)
+ * @param len   register containing number of bytes
+ * @param table register pointing to CRC table
+ */
+void MacroAssembler::update_byteLoop_crc32(Register crc, Register buf, Register len, Register table,
+                                           Register data, bool loopAlignment, bool invertCRC) {
+  assert_different_registers(crc, buf, len, table, data);
+
+  Label L_mainLoop, L_done;
+  const int mainLoop_stepping  = 1;
+  const int mainLoop_alignment = loopAlignment ? 32 : 4; // (InputForNewCode > 4 ? InputForNewCode : 32) : 4;
+
+  // Process all bytes in a single-byte loop.
+  cmpdi(CCR0, len, 0);                           // Anything to do?
+  mtctr(len);
+  beq(CCR0, L_done);
+
+  if (invertCRC) {
+    nand(crc, crc, crc);                         // ~c
+  }
+
+  align(mainLoop_alignment);
+  BIND(L_mainLoop);
+    lbz(data, 0, buf);                           // Byte from buffer, zero-extended.
+    addi(buf, buf, mainLoop_stepping);           // Advance buffer position.
+    update_byte_crc32(crc, data, table);
+    bdnz(L_mainLoop);                            // Iterate.
+
+  if (invertCRC) {
+    nand(crc, crc, crc);                         // ~c
+  }
+
+  bind(L_done);
+}
+
+/**
+ * Emits code to update CRC-32 with a 4-byte value according to constants in table
+ * Implementation according to jdk/src/share/native/java/util/zip/zlib-1.2.8/crc32.c
+ */
+// A not on the lookup table address(es):
+// The lookup table consists of two sets of four columns each.
+// The columns {0..3} are used for little-endian machines.
+// The columns {4..7} are used for big-endian machines.
+// To save the effort of adding the column offset to the table address each time
+// a table element is looked up, it is possible to pass the pre-calculated
+// column addresses.
+// Uses R9..R12 as work register. Must be saved/restored by caller, if necessary.
+void MacroAssembler::update_1word_crc32(Register crc, Register buf, Register table, int bufDisp, int bufInc,
+                                        Register t0,  Register t1,  Register t2,  Register t3,
+                                        Register tc0, Register tc1, Register tc2, Register tc3) {
+  assert_different_registers(crc, t3);
+
+  // XOR crc with next four bytes of buffer.
+  lwz(t3, bufDisp, buf);
+  if (bufInc != 0) {
+    addi(buf, buf, bufInc);
+  }
+  xorr(t3, t3, crc);
+
+  // Chop crc into 4 single-byte pieces, shifted left 2 bits, to form the table indices.
+  rlwinm(t0, t3,  2,         24-2, 31-2);  // ((t1 >>  0) & 0xff) << 2
+  rlwinm(t1, t3,  32+(2- 8), 24-2, 31-2);  // ((t1 >>  8) & 0xff) << 2
+  rlwinm(t2, t3,  32+(2-16), 24-2, 31-2);  // ((t1 >> 16) & 0xff) << 2
+  rlwinm(t3, t3,  32+(2-24), 24-2, 31-2);  // ((t1 >> 24) & 0xff) << 2
+
+  // Use the pre-calculated column addresses.
+  // Load pre-calculated table values.
+  lwzx(t0, tc0, t0);
+  lwzx(t1, tc1, t1);
+  lwzx(t2, tc2, t2);
+  lwzx(t3, tc3, t3);
+
+  // Calculate new crc from table values.
+  xorr(t0,  t0, t1);
+  xorr(t2,  t2, t3);
+  xorr(crc, t0, t2);  // Now crc contains the final checksum value.
+}
+
+/**
+ * @param crc   register containing existing CRC (32-bit)
+ * @param buf   register pointing to input byte buffer (byte*)
+ * @param len   register containing number of bytes
+ * @param table register pointing to CRC table
+ *
+ * Uses R9..R12 as work register. Must be saved/restored by caller!
+ */
+void MacroAssembler::kernel_crc32_2word(Register crc, Register buf, Register len, Register table,
+                                        Register t0,  Register t1,  Register t2,  Register t3,
+                                        Register tc0, Register tc1, Register tc2, Register tc3) {
+  assert_different_registers(crc, buf, len, table);
+
+  Label L_mainLoop, L_tail;
+  Register  tmp  = t0;
+  Register  data = t0;
+  Register  tmp2 = t1;
+  const int mainLoop_stepping  = 8;
+  const int tailLoop_stepping  = 1;
+  const int log_stepping       = exact_log2(mainLoop_stepping);
+  const int mainLoop_alignment = 32; // InputForNewCode > 4 ? InputForNewCode : 32;
+  const int complexThreshold   = 2*mainLoop_stepping;
+
+  // Don't test for len <= 0 here. This pathological case should not occur anyway.
+  // Optimizing for it by adding a test and a branch seems to be a waste of CPU cycles.
+  // The situation itself is detected and handled correctly by the conditional branches
+  // following  aghi(len, -stepping) and aghi(len, +stepping).
+  assert(tailLoop_stepping == 1, "check tailLoop_stepping!");
+
+  BLOCK_COMMENT("kernel_crc32_2word {");
+
+  nand(crc, crc, crc);                           // ~c
+
+  // Check for short (<mainLoop_stepping) buffer.
+  cmpdi(CCR0, len, complexThreshold);
+  blt(CCR0, L_tail);
+
+  // Pre-mainLoop alignment did show a slight (1%) positive effect on performance.
+  // We leave the code in for reference. Maybe we need alignment when we exploit vector instructions.
+  {
+    // Align buf addr to mainLoop_stepping boundary.
+    neg(tmp2, buf);                           // Calculate # preLoop iterations for alignment.
+    rldicl(tmp2, tmp2, 0, 64-log_stepping);   // Rotate tmp2 0 bits, insert into tmp2, anding with mask with 1s from 62..63.
+
+    if (complexThreshold > mainLoop_stepping) {
+      sub(len, len, tmp2);                       // Remaining bytes for main loop (>=mainLoop_stepping is guaranteed).
+    } else {
+      sub(tmp, len, tmp2);                       // Remaining bytes for main loop.
+      cmpdi(CCR0, tmp, mainLoop_stepping);
+      blt(CCR0, L_tail);                         // For less than one mainloop_stepping left, do only tail processing
+      mr(len, tmp);                              // remaining bytes for main loop (>=mainLoop_stepping is guaranteed).
+    }
+    update_byteLoop_crc32(crc, buf, tmp2, table, data, false, false);
+  }
+
+  srdi(tmp2, len, log_stepping);                 // #iterations for mainLoop
+  andi(len, len, mainLoop_stepping-1);           // remaining bytes for tailLoop
+  mtctr(tmp2);
+
+#ifdef VM_LITTLE_ENDIAN
+  Register crc_rv = crc;
+#else
+  Register crc_rv = tmp;                         // Load_reverse needs separate registers to work on.
+                                                 // Occupies tmp, but frees up crc.
+  load_reverse_32(crc_rv, crc);                  // Revert byte order because we are dealing with big-endian data.
+  tmp = crc;
+#endif
+
+  int reconstructTableOffset = crc32_table_columns(table, tc0, tc1, tc2, tc3);
+
+  align(mainLoop_alignment);                     // Octoword-aligned loop address. Shows 2% improvement.
+  BIND(L_mainLoop);
+    update_1word_crc32(crc_rv, buf, table, 0, 0, crc_rv, t1, t2, t3, tc0, tc1, tc2, tc3);
+    update_1word_crc32(crc_rv, buf, table, 4, mainLoop_stepping, crc_rv, t1, t2, t3, tc0, tc1, tc2, tc3);
+    bdnz(L_mainLoop);
+
+#ifndef VM_LITTLE_ENDIAN
+  load_reverse_32(crc, crc_rv);                  // Revert byte order because we are dealing with big-endian data.
+  tmp = crc_rv;                                  // Tmp uses it's original register again.
+#endif
+
+  // Restore original table address for tailLoop.
+  if (reconstructTableOffset != 0) {
+    addi(table, table, -reconstructTableOffset);
+  }
+
+  // Process last few (<complexThreshold) bytes of buffer.
+  BIND(L_tail);
+  update_byteLoop_crc32(crc, buf, len, table, data, false, false);
+
+  nand(crc, crc, crc);                           // ~c
+  BLOCK_COMMENT("} kernel_crc32_2word");
+}
+
+/**
+ * @param crc   register containing existing CRC (32-bit)
+ * @param buf   register pointing to input byte buffer (byte*)
+ * @param len   register containing number of bytes
+ * @param table register pointing to CRC table
+ *
+ * uses R9..R12 as work register. Must be saved/restored by caller!
+ */
+void MacroAssembler::kernel_crc32_1word(Register crc, Register buf, Register len, Register table,
+                                        Register t0,  Register t1,  Register t2,  Register t3,
+                                        Register tc0, Register tc1, Register tc2, Register tc3) {
+  assert_different_registers(crc, buf, len, table);
+
+  Label L_mainLoop, L_tail;
+  Register  tmp          = t0;
+  Register  data         = t0;
+  Register  tmp2         = t1;
+  const int mainLoop_stepping  = 4;
+  const int tailLoop_stepping  = 1;
+  const int log_stepping       = exact_log2(mainLoop_stepping);
+  const int mainLoop_alignment = 32; // InputForNewCode > 4 ? InputForNewCode : 32;
+  const int complexThreshold   = 2*mainLoop_stepping;
+
+  // Don't test for len <= 0 here. This pathological case should not occur anyway.
+  // Optimizing for it by adding a test and a branch seems to be a waste of CPU cycles.
+  // The situation itself is detected and handled correctly by the conditional branches
+  // following  aghi(len, -stepping) and aghi(len, +stepping).
+  assert(tailLoop_stepping == 1, "check tailLoop_stepping!");
+
+  BLOCK_COMMENT("kernel_crc32_1word {");
+
+  nand(crc, crc, crc);                           // ~c
+
+  // Check for short (<mainLoop_stepping) buffer.
+  cmpdi(CCR0, len, complexThreshold);
+  blt(CCR0, L_tail);
+
+  // Pre-mainLoop alignment did show a slight (1%) positive effect on performance.
+  // We leave the code in for reference. Maybe we need alignment when we exploit vector instructions.
+  {
+    // Align buf addr to mainLoop_stepping boundary.
+    neg(tmp2, buf);                              // Calculate # preLoop iterations for alignment.
+    rldicl(tmp2, tmp2, 0, 64-log_stepping);      // Rotate tmp2 0 bits, insert into tmp2, anding with mask with 1s from 62..63.
+
+    if (complexThreshold > mainLoop_stepping) {
+      sub(len, len, tmp2);                       // Remaining bytes for main loop (>=mainLoop_stepping is guaranteed).
+    } else {
+      sub(tmp, len, tmp2);                       // Remaining bytes for main loop.
+      cmpdi(CCR0, tmp, mainLoop_stepping);
+      blt(CCR0, L_tail);                         // For less than one mainloop_stepping left, do only tail processing
+      mr(len, tmp);                              // remaining bytes for main loop (>=mainLoop_stepping is guaranteed).
+    }
+    update_byteLoop_crc32(crc, buf, tmp2, table, data, false, false);
+  }
+
+  srdi(tmp2, len, log_stepping);                 // #iterations for mainLoop
+  andi(len, len, mainLoop_stepping-1);           // remaining bytes for tailLoop
+  mtctr(tmp2);
+
+#ifdef VM_LITTLE_ENDIAN
+  Register crc_rv = crc;
+#else
+  Register crc_rv = tmp;                         // Load_reverse needs separate registers to work on.
+                                                 // Occupies tmp, but frees up crc.
+  load_reverse_32(crc_rv, crc);                  // evert byte order because we are dealing with big-endian data.
+  tmp = crc;
+#endif
+
+  int reconstructTableOffset = crc32_table_columns(table, tc0, tc1, tc2, tc3);
+
+  align(mainLoop_alignment);                     // Octoword-aligned loop address. Shows 2% improvement.
+  BIND(L_mainLoop);
+    update_1word_crc32(crc_rv, buf, table, 0, mainLoop_stepping, crc_rv, t1, t2, t3, tc0, tc1, tc2, tc3);
+    bdnz(L_mainLoop);
+
+#ifndef VM_LITTLE_ENDIAN
+  load_reverse_32(crc, crc_rv);                  // Revert byte order because we are dealing with big-endian data.
+  tmp = crc_rv;                                  // Tmp uses it's original register again.
+#endif
+
+  // Restore original table address for tailLoop.
+  if (reconstructTableOffset != 0) {
+    addi(table, table, -reconstructTableOffset);
+  }
+
+  // Process last few (<complexThreshold) bytes of buffer.
+  BIND(L_tail);
+  update_byteLoop_crc32(crc, buf, len, table, data, false, false);
+
+  nand(crc, crc, crc);                           // ~c
+  BLOCK_COMMENT("} kernel_crc32_1word");
+}
+
+/**
+ * @param crc   register containing existing CRC (32-bit)
+ * @param buf   register pointing to input byte buffer (byte*)
+ * @param len   register containing number of bytes
+ * @param table register pointing to CRC table
+ *
+ * Uses R7_ARG5, R8_ARG6 as work registers.
+ */
+void MacroAssembler::kernel_crc32_1byte(Register crc, Register buf, Register len, Register table,
+                                        Register t0,  Register t1,  Register t2,  Register t3) {
+  assert_different_registers(crc, buf, len, table);
+
+  Register  data = t0;                   // Holds the current byte to be folded into crc.
+
+  BLOCK_COMMENT("kernel_crc32_1byte {");
+
+  // Process all bytes in a single-byte loop.
+  update_byteLoop_crc32(crc, buf, len, table, data, true, true);
+
+  BLOCK_COMMENT("} kernel_crc32_1byte");
+}
+
+/**
+ * @param crc             register containing existing CRC (32-bit)
+ * @param buf             register pointing to input byte buffer (byte*)
+ * @param len             register containing number of bytes
+ * @param table           register pointing to CRC table
+ * @param constants       register pointing to CRC table for 128-bit aligned memory
+ * @param barretConstants register pointing to table for barrett reduction
+ * @param t0              volatile register
+ * @param t1              volatile register
+ * @param t2              volatile register
+ * @param t3              volatile register
+ */
+void MacroAssembler::kernel_crc32_1word_vpmsumd(Register crc, Register buf, Register len, Register table,
+                        Register constants,  Register barretConstants,
+                        Register t0,  Register t1, Register t2, Register t3, Register t4) {
+  assert_different_registers(crc, buf, len, table);
+
+  Label L_alignedHead, L_tail, L_alignTail, L_start, L_end;
+
+  Register  prealign     = t0;
+  Register  postalign    = t0;
+
+  BLOCK_COMMENT("kernel_crc32_1word_vpmsumb {");
+
+  // 1. use kernel_crc32_1word for shorter than 384bit
+  clrldi(len, len, 32);
+  cmpdi(CCR0, len, 384);
+  bge(CCR0, L_start);
+
+    Register tc0 = t4;
+    Register tc1 = constants;
+    Register tc2 = barretConstants;
+    kernel_crc32_1word(crc, buf, len, table,t0, t1, t2, t3, tc0, tc1, tc2, table);
+    b(L_end);
+
+  BIND(L_start);
+
+    // 2. ~c
+    nand(crc, crc, crc);
+
+    // 3. calculate from 0 to first 128bit-aligned address
+    clrldi_(prealign, buf, 57);
+    beq(CCR0, L_alignedHead);
+
+    subfic(prealign, prealign, 128);
+
+    subf(len, prealign, len);
+    update_byteLoop_crc32(crc, buf, prealign, table, t2, false, false);
+
+    // 4. calculate from first 128bit-aligned address to last 128bit-aligned address
+    BIND(L_alignedHead);
+
+    clrldi(postalign, len, 57);
+    subf(len, postalign, len);
+
+    // len must be more than 256bit
+    kernel_crc32_1word_aligned(crc, buf, len, constants, barretConstants, t1, t2, t3);
+
+    // 5. calculate remaining
+    cmpdi(CCR0, postalign, 0);
+    beq(CCR0, L_tail);
+
+    update_byteLoop_crc32(crc, buf, postalign, table, t2, false, false);
+
+    BIND(L_tail);
+
+    // 6. ~c
+    nand(crc, crc, crc);
+
+  BIND(L_end);
+
+  BLOCK_COMMENT("} kernel_crc32_1word_vpmsumb");
+}
+
+/**
+ * @param crc             register containing existing CRC (32-bit)
+ * @param buf             register pointing to input byte buffer (byte*)
+ * @param len             register containing number of bytes
+ * @param constants       register pointing to CRC table for 128-bit aligned memory
+ * @param barretConstants register pointing to table for barrett reduction
+ * @param t0              volatile register
+ * @param t1              volatile register
+ * @param t2              volatile register
+ */
+void MacroAssembler::kernel_crc32_1word_aligned(Register crc, Register buf, Register len,
+    Register constants, Register barretConstants, Register t0, Register t1, Register t2) {
+  Label L_mainLoop, L_tail, L_alignTail, L_barrett_reduction, L_end, L_first_warm_up_done, L_first_cool_down, L_second_cool_down, L_XOR, L_test;
+  Label L_lv0, L_lv1, L_lv2, L_lv3, L_lv4, L_lv5, L_lv6, L_lv7, L_lv8, L_lv9, L_lv10, L_lv11, L_lv12, L_lv13, L_lv14, L_lv15;
+  Label L_1, L_2, L_3, L_4;
+
+  Register  rLoaded      = t0;
+  Register  rTmp1        = t1;
+  Register  rTmp2        = t2;
+  Register  off16        = R22;
+  Register  off32        = R23;
+  Register  off48        = R24;
+  Register  off64        = R25;
+  Register  off80        = R26;
+  Register  off96        = R27;
+  Register  off112       = R28;
+  Register  rIdx         = R29;
+  Register  rMax         = R30;
+  Register  constantsPos = R31;
+
+  VectorRegister mask_32bit = VR24;
+  VectorRegister mask_64bit = VR25;
+  VectorRegister zeroes     = VR26;
+  VectorRegister const1     = VR27;
+  VectorRegister const2     = VR28;
+
+  // Save non-volatile vector registers (frameless).
+  Register offset = t1;   int offsetInt = 0;
+  offsetInt -= 16; li(offset, -16);           stvx(VR20, offset, R1_SP);
+  offsetInt -= 16; addi(offset, offset, -16); stvx(VR21, offset, R1_SP);
+  offsetInt -= 16; addi(offset, offset, -16); stvx(VR22, offset, R1_SP);
+  offsetInt -= 16; addi(offset, offset, -16); stvx(VR23, offset, R1_SP);
+  offsetInt -= 16; addi(offset, offset, -16); stvx(VR24, offset, R1_SP);
+  offsetInt -= 16; addi(offset, offset, -16); stvx(VR25, offset, R1_SP);
+  offsetInt -= 16; addi(offset, offset, -16); stvx(VR26, offset, R1_SP);
+  offsetInt -= 16; addi(offset, offset, -16); stvx(VR27, offset, R1_SP);
+  offsetInt -= 16; addi(offset, offset, -16); stvx(VR28, offset, R1_SP);
+  offsetInt -= 8; std(R22, offsetInt, R1_SP);
+  offsetInt -= 8; std(R23, offsetInt, R1_SP);
+  offsetInt -= 8; std(R24, offsetInt, R1_SP);
+  offsetInt -= 8; std(R25, offsetInt, R1_SP);
+  offsetInt -= 8; std(R26, offsetInt, R1_SP);
+  offsetInt -= 8; std(R27, offsetInt, R1_SP);
+  offsetInt -= 8; std(R28, offsetInt, R1_SP);
+  offsetInt -= 8; std(R29, offsetInt, R1_SP);
+  offsetInt -= 8; std(R30, offsetInt, R1_SP);
+  offsetInt -= 8; std(R31, offsetInt, R1_SP);
+
+  // Set constants
+  li(off16, 16);
+  li(off32, 32);
+  li(off48, 48);
+  li(off64, 64);
+  li(off80, 80);
+  li(off96, 96);
+  li(off112, 112);
+
+  clrldi(crc, crc, 32);
+
+  vxor(zeroes, zeroes, zeroes);
+  vspltisw(VR0, -1);
+
+  vsldoi(mask_32bit, zeroes, VR0, 4);
+  vsldoi(mask_64bit, zeroes, VR0, 8);
+
+  // Get the initial value into v8
+  vxor(VR8, VR8, VR8);
+  mtvrd(VR8, crc);
+  vsldoi(VR8, zeroes, VR8, 8); // shift into bottom 32 bits
+
+  li (rLoaded, 0);
+
+  rldicr(rIdx, len, 0, 56);
+
+  {
+    BIND(L_1);
+    // Checksum in blocks of MAX_SIZE (32768)
+    lis(rMax, 0);
+    ori(rMax, rMax, 32768);
+    mr(rTmp2, rMax);
+    cmpd(CCR0, rIdx, rMax);
+    bgt(CCR0, L_2);
+    mr(rMax, rIdx);
+
+    BIND(L_2);
+    subf(rIdx, rMax, rIdx);
+
+    // our main loop does 128 bytes at a time
+    srdi(rMax, rMax, 7);
+
+    /*
+     * Work out the offset into the constants table to start at. Each
+     * constant is 16 bytes, and it is used against 128 bytes of input
+     * data - 128 / 16 = 8
+     */
+    sldi(rTmp1, rMax, 4);
+    srdi(rTmp2, rTmp2, 3);
+    subf(rTmp1, rTmp1, rTmp2);
+
+    // We reduce our final 128 bytes in a separate step
+    addi(rMax, rMax, -1);
+    mtctr(rMax);
+
+    // Find the start of our constants
+    add(constantsPos, constants, rTmp1);
+
+    // zero VR0-v7 which will contain our checksums
+    vxor(VR0, VR0, VR0);
+    vxor(VR1, VR1, VR1);
+    vxor(VR2, VR2, VR2);
+    vxor(VR3, VR3, VR3);
+    vxor(VR4, VR4, VR4);
+    vxor(VR5, VR5, VR5);
+    vxor(VR6, VR6, VR6);
+    vxor(VR7, VR7, VR7);
+
+    lvx(const1, constantsPos);
+
+    /*
+     * If we are looping back to consume more data we use the values
+     * already in VR16-v23.
+     */
+    cmpdi(CCR0, rLoaded, 1);
+    beq(CCR0, L_3);
+    {
+
+      // First warm up pass
+      lvx(VR16, buf);
+      lvx(VR17, off16, buf);
+      lvx(VR18, off32, buf);
+      lvx(VR19, off48, buf);
+      lvx(VR20, off64, buf);
+      lvx(VR21, off80, buf);
+      lvx(VR22, off96, buf);
+      lvx(VR23, off112, buf);
+      addi(buf, buf, 8*16);
+
+      // xor in initial value
+      vxor(VR16, VR16, VR8);
+    }
+
+    BIND(L_3);
+    bdz(L_first_warm_up_done);
+
+    addi(constantsPos, constantsPos, 16);
+    lvx(const2, constantsPos);
+
+    // Second warm up pass
+    vpmsumd(VR8, VR16, const1);
+    lvx(VR16, buf);
+
+    vpmsumd(VR9, VR17, const1);
+    lvx(VR17, off16, buf);
+
+    vpmsumd(VR10, VR18, const1);
+    lvx(VR18, off32, buf);
+
+    vpmsumd(VR11, VR19, const1);
+    lvx(VR19, off48, buf);
+
+    vpmsumd(VR12, VR20, const1);
+    lvx(VR20, off64, buf);
+
+    vpmsumd(VR13, VR21, const1);
+    lvx(VR21, off80, buf);
+
+    vpmsumd(VR14, VR22, const1);
+    lvx(VR22, off96, buf);
+
+    vpmsumd(VR15, VR23, const1);
+    lvx(VR23, off112, buf);
+
+    addi(buf, buf, 8 * 16);
+
+    bdz(L_first_cool_down);
+
+    /*
+     * main loop. We modulo schedule it such that it takes three iterations
+     * to complete - first iteration load, second iteration vpmsum, third
+     * iteration xor.
+     */
+    {
+      BIND(L_4);
+      lvx(const1, constantsPos); addi(constantsPos, constantsPos, 16);
+
+      vxor(VR0, VR0, VR8);
+      vpmsumd(VR8, VR16, const2);
+      lvx(VR16, buf);
+
+      vxor(VR1, VR1, VR9);
+      vpmsumd(VR9, VR17, const2);
+      lvx(VR17, off16, buf);
+
+      vxor(VR2, VR2, VR10);
+      vpmsumd(VR10, VR18, const2);
+      lvx(VR18, off32, buf);
+
+      vxor(VR3, VR3, VR11);
+      vpmsumd(VR11, VR19, const2);
+      lvx(VR19, off48, buf);
+      lvx(const2, constantsPos);
+
+      vxor(VR4, VR4, VR12);
+      vpmsumd(VR12, VR20, const1);
+      lvx(VR20, off64, buf);
+
+      vxor(VR5, VR5, VR13);
+      vpmsumd(VR13, VR21, const1);
+      lvx(VR21, off80, buf);
+
+      vxor(VR6, VR6, VR14);
+      vpmsumd(VR14, VR22, const1);
+      lvx(VR22, off96, buf);
+
+      vxor(VR7, VR7, VR15);
+      vpmsumd(VR15, VR23, const1);
+      lvx(VR23, off112, buf);
+
+      addi(buf, buf, 8 * 16);
+
+      bdnz(L_4);
+    }
+
+    BIND(L_first_cool_down);
+
+    // First cool down pass
+    lvx(const1, constantsPos);
+    addi(constantsPos, constantsPos, 16);
+
+    vxor(VR0, VR0, VR8);
+    vpmsumd(VR8, VR16, const1);
+
+    vxor(VR1, VR1, VR9);
+    vpmsumd(VR9, VR17, const1);
+
+    vxor(VR2, VR2, VR10);
+    vpmsumd(VR10, VR18, const1);
+
+    vxor(VR3, VR3, VR11);
+    vpmsumd(VR11, VR19, const1);
+
+    vxor(VR4, VR4, VR12);
+    vpmsumd(VR12, VR20, const1);
+
+    vxor(VR5, VR5, VR13);
+    vpmsumd(VR13, VR21, const1);
+
+    vxor(VR6, VR6, VR14);
+    vpmsumd(VR14, VR22, const1);
+
+    vxor(VR7, VR7, VR15);
+    vpmsumd(VR15, VR23, const1);
+
+    BIND(L_second_cool_down);
+    // Second cool down pass
+    vxor(VR0, VR0, VR8);
+    vxor(VR1, VR1, VR9);
+    vxor(VR2, VR2, VR10);
+    vxor(VR3, VR3, VR11);
+    vxor(VR4, VR4, VR12);
+    vxor(VR5, VR5, VR13);
+    vxor(VR6, VR6, VR14);
+    vxor(VR7, VR7, VR15);
+
+    /*
+     * vpmsumd produces a 96 bit result in the least significant bits
+     * of the register. Since we are bit reflected we have to shift it
+     * left 32 bits so it occupies the least significant bits in the
+     * bit reflected domain.
+     */
+    vsldoi(VR0, VR0, zeroes, 4);
+    vsldoi(VR1, VR1, zeroes, 4);
+    vsldoi(VR2, VR2, zeroes, 4);
+    vsldoi(VR3, VR3, zeroes, 4);
+    vsldoi(VR4, VR4, zeroes, 4);
+    vsldoi(VR5, VR5, zeroes, 4);
+    vsldoi(VR6, VR6, zeroes, 4);
+    vsldoi(VR7, VR7, zeroes, 4);
+
+    // xor with last 1024 bits
+    lvx(VR8, buf);
+    lvx(VR9, off16, buf);
+    lvx(VR10, off32, buf);
+    lvx(VR11, off48, buf);
+    lvx(VR12, off64, buf);
+    lvx(VR13, off80, buf);
+    lvx(VR14, off96, buf);
+    lvx(VR15, off112, buf);
+    addi(buf, buf, 8 * 16);
+
+    vxor(VR16, VR0, VR8);
+    vxor(VR17, VR1, VR9);
+    vxor(VR18, VR2, VR10);
+    vxor(VR19, VR3, VR11);
+    vxor(VR20, VR4, VR12);
+    vxor(VR21, VR5, VR13);
+    vxor(VR22, VR6, VR14);
+    vxor(VR23, VR7, VR15);
+
+    li(rLoaded, 1);
+    cmpdi(CCR0, rIdx, 0);
+    addi(rIdx, rIdx, 128);
+    bne(CCR0, L_1);
+  }
+
+  // Work out how many bytes we have left
+  andi_(len, len, 127);
+
+  // Calculate where in the constant table we need to start
+  subfic(rTmp1, len, 128);
+  add(constantsPos, constantsPos, rTmp1);
+
+  // How many 16 byte chunks are in the tail
+  srdi(rIdx, len, 4);
+  mtctr(rIdx);
+
+  /*
+   * Reduce the previously calculated 1024 bits to 64 bits, shifting
+   * 32 bits to include the trailing 32 bits of zeros
+   */
+  lvx(VR0, constantsPos);
+  lvx(VR1, off16, constantsPos);
+  lvx(VR2, off32, constantsPos);
+  lvx(VR3, off48, constantsPos);
+  lvx(VR4, off64, constantsPos);
+  lvx(VR5, off80, constantsPos);
+  lvx(VR6, off96, constantsPos);
+  lvx(VR7, off112, constantsPos);
+  addi(constantsPos, constantsPos, 8 * 16);
+
+  vpmsumw(VR0, VR16, VR0);
+  vpmsumw(VR1, VR17, VR1);
+  vpmsumw(VR2, VR18, VR2);
+  vpmsumw(VR3, VR19, VR3);
+  vpmsumw(VR4, VR20, VR4);
+  vpmsumw(VR5, VR21, VR5);
+  vpmsumw(VR6, VR22, VR6);
+  vpmsumw(VR7, VR23, VR7);
+
+  // Now reduce the tail (0 - 112 bytes)
+  cmpdi(CCR0, rIdx, 0);
+  beq(CCR0, L_XOR);
+
+  lvx(VR16, buf); addi(buf, buf, 16);
+  lvx(VR17, constantsPos);
+  vpmsumw(VR16, VR16, VR17);
+  vxor(VR0, VR0, VR16);
+  beq(CCR0, L_XOR);
+
+  lvx(VR16, buf); addi(buf, buf, 16);
+  lvx(VR17, off16, constantsPos);
+  vpmsumw(VR16, VR16, VR17);
+  vxor(VR0, VR0, VR16);
+  beq(CCR0, L_XOR);
+
+  lvx(VR16, buf); addi(buf, buf, 16);
+  lvx(VR17, off32, constantsPos);
+  vpmsumw(VR16, VR16, VR17);
+  vxor(VR0, VR0, VR16);
+  beq(CCR0, L_XOR);
+
+  lvx(VR16, buf); addi(buf, buf, 16);
+  lvx(VR17, off48,constantsPos);
+  vpmsumw(VR16, VR16, VR17);
+  vxor(VR0, VR0, VR16);
+  beq(CCR0, L_XOR);
+
+  lvx(VR16, buf); addi(buf, buf, 16);
+  lvx(VR17, off64, constantsPos);
+  vpmsumw(VR16, VR16, VR17);
+  vxor(VR0, VR0, VR16);
+  beq(CCR0, L_XOR);
+
+  lvx(VR16, buf); addi(buf, buf, 16);
+  lvx(VR17, off80, constantsPos);
+  vpmsumw(VR16, VR16, VR17);
+  vxor(VR0, VR0, VR16);
+  beq(CCR0, L_XOR);
+
+  lvx(VR16, buf); addi(buf, buf, 16);
+  lvx(VR17, off96, constantsPos);
+  vpmsumw(VR16, VR16, VR17);
+  vxor(VR0, VR0, VR16);
+
+  // Now xor all the parallel chunks together
+  BIND(L_XOR);
+  vxor(VR0, VR0, VR1);
+  vxor(VR2, VR2, VR3);
+  vxor(VR4, VR4, VR5);
+  vxor(VR6, VR6, VR7);
+
+  vxor(VR0, VR0, VR2);
+  vxor(VR4, VR4, VR6);
+
+  vxor(VR0, VR0, VR4);
+
+  b(L_barrett_reduction);
+
+  BIND(L_first_warm_up_done);
+  lvx(const1, constantsPos);
+  addi(constantsPos, constantsPos, 16);
+  vpmsumd(VR8,  VR16, const1);
+  vpmsumd(VR9,  VR17, const1);
+  vpmsumd(VR10, VR18, const1);
+  vpmsumd(VR11, VR19, const1);
+  vpmsumd(VR12, VR20, const1);
+  vpmsumd(VR13, VR21, const1);
+  vpmsumd(VR14, VR22, const1);
+  vpmsumd(VR15, VR23, const1);
+  b(L_second_cool_down);
+
+  BIND(L_barrett_reduction);
+
+  lvx(const1, barretConstants);
+  addi(barretConstants, barretConstants, 16);
+  lvx(const2, barretConstants);
+
+  vsldoi(VR1, VR0, VR0, 8);
+  vxor(VR0, VR0, VR1);    // xor two 64 bit results together
+
+  // shift left one bit
+  vspltisb(VR1, 1);
+  vsl(VR0, VR0, VR1);
+
+  vand(VR0, VR0, mask_64bit);
+
+  /*
+   * The reflected version of Barrett reduction. Instead of bit
+   * reflecting our data (which is expensive to do), we bit reflect our
+   * constants and our algorithm, which means the intermediate data in
+   * our vector registers goes from 0-63 instead of 63-0. We can reflect
+   * the algorithm because we don't carry in mod 2 arithmetic.
+   */
+  vand(VR1, VR0, mask_32bit);  // bottom 32 bits of a
+  vpmsumd(VR1, VR1, const1);   // ma
+  vand(VR1, VR1, mask_32bit);  // bottom 32bits of ma
+  vpmsumd(VR1, VR1, const2);   // qn */
+  vxor(VR0, VR0, VR1);         // a - qn, subtraction is xor in GF(2)
+
+  /*
+   * Since we are bit reflected, the result (ie the low 32 bits) is in
+   * the high 32 bits. We just need to shift it left 4 bytes
+   * V0 [ 0 1 X 3 ]
+   * V0 [ 0 X 2 3 ]
+   */
+  vsldoi(VR0, VR0, zeroes, 4);    // shift result into top 64 bits of
+
+  // Get it into r3
+  mfvrd(crc, VR0);
+
+  BIND(L_end);
+
+  offsetInt = 0;
+  // Restore non-volatile Vector registers (frameless).
+  offsetInt -= 16; li(offset, -16);           lvx(VR20, offset, R1_SP);
+  offsetInt -= 16; addi(offset, offset, -16); lvx(VR21, offset, R1_SP);
+  offsetInt -= 16; addi(offset, offset, -16); lvx(VR22, offset, R1_SP);
+  offsetInt -= 16; addi(offset, offset, -16); lvx(VR23, offset, R1_SP);
+  offsetInt -= 16; addi(offset, offset, -16); lvx(VR24, offset, R1_SP);
+  offsetInt -= 16; addi(offset, offset, -16); lvx(VR25, offset, R1_SP);
+  offsetInt -= 16; addi(offset, offset, -16); lvx(VR26, offset, R1_SP);
+  offsetInt -= 16; addi(offset, offset, -16); lvx(VR27, offset, R1_SP);
+  offsetInt -= 16; addi(offset, offset, -16); lvx(VR28, offset, R1_SP);
+  offsetInt -= 8;  ld(R22, offsetInt, R1_SP);
+  offsetInt -= 8;  ld(R23, offsetInt, R1_SP);
+  offsetInt -= 8;  ld(R24, offsetInt, R1_SP);
+  offsetInt -= 8;  ld(R25, offsetInt, R1_SP);
+  offsetInt -= 8;  ld(R26, offsetInt, R1_SP);
+  offsetInt -= 8;  ld(R27, offsetInt, R1_SP);
+  offsetInt -= 8;  ld(R28, offsetInt, R1_SP);
+  offsetInt -= 8;  ld(R29, offsetInt, R1_SP);
+  offsetInt -= 8;  ld(R30, offsetInt, R1_SP);
+  offsetInt -= 8;  ld(R31, offsetInt, R1_SP);
+}
+
+void MacroAssembler::kernel_crc32_singleByte(Register crc, Register buf, Register len, Register table, Register tmp) {
+  assert_different_registers(crc, buf, /* len,  not used!! */ table, tmp);
+
+  BLOCK_COMMENT("kernel_crc32_singleByte:");
+  nand(crc, crc, crc);       // ~c
+
+  lbz(tmp, 0, buf);          // Byte from buffer, zero-extended.
+  update_byte_crc32(crc, tmp, table);
+
+  nand(crc, crc, crc);       // ~c
+}
+
 
 void MacroAssembler::asm_assert(bool check_equal, const char *msg, int id) {
 #ifdef ASSERT
diff --git a/src/cpu/ppc/vm/macroAssembler_ppc.hpp b/src/cpu/ppc/vm/macroAssembler_ppc.hpp
index c7e8de4..0f4e8da 100644
--- a/src/cpu/ppc/vm/macroAssembler_ppc.hpp
+++ b/src/cpu/ppc/vm/macroAssembler_ppc.hpp
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
- * Copyright 2012, 2014 SAP AG. All rights reserved.
+ * Copyright (c) 2002, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright 2012, 2017 SAP AG. 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
@@ -441,7 +441,8 @@
                                RegisterOrConstant itable_index,
                                Register method_result,
                                Register temp_reg, Register temp2_reg,
-                               Label& no_such_interface);
+                               Label& no_such_interface,
+                               bool return_method = true);
 
   // virtual method calling
   void lookup_virtual_method(Register recv_klass,
@@ -636,6 +637,34 @@
   void char_arrays_equalsImm(Register str1_reg, Register str2_reg, int cntval, Register result_reg,
                              Register tmp1_reg, Register tmp2_reg);
 
+  // CRC32 Intrinsics.
+  void load_reverse_32(Register dst, Register src);
+  int  crc32_table_columns(Register table, Register tc0, Register tc1, Register tc2, Register tc3);
+  void fold_byte_crc32(Register crc, Register val, Register table, Register tmp);
+  void fold_8bit_crc32(Register crc, Register table, Register tmp);
+  void update_byte_crc32(Register crc, Register val, Register table);
+  void update_byteLoop_crc32(Register crc, Register buf, Register len, Register table,
+                             Register data, bool loopAlignment, bool invertCRC);
+  void update_1word_crc32(Register crc, Register buf, Register table, int bufDisp, int bufInc,
+                          Register t0,  Register t1,  Register t2,  Register t3,
+                          Register tc0, Register tc1, Register tc2, Register tc3);
+  void kernel_crc32_2word(Register crc, Register buf, Register len, Register table,
+                          Register t0,  Register t1,  Register t2,  Register t3,
+                          Register tc0, Register tc1, Register tc2, Register tc3);
+  void kernel_crc32_1word(Register crc, Register buf, Register len, Register table,
+                          Register t0,  Register t1,  Register t2,  Register t3,
+                          Register tc0, Register tc1, Register tc2, Register tc3);
+  void kernel_crc32_1byte(Register crc, Register buf, Register len, Register table,
+                          Register t0,  Register t1,  Register t2,  Register t3);
+  void kernel_crc32_1word_vpmsumd(Register crc, Register buf, Register len, Register table,
+                          Register constants, Register barretConstants,
+                          Register t0,  Register t1, Register t2, Register t3, Register t4);
+  void kernel_crc32_1word_aligned(Register crc, Register buf, Register len,
+                          Register constants, Register barretConstants,
+                          Register t0, Register t1, Register t2);
+
+  void kernel_crc32_singleByte(Register crc, Register buf, Register len, Register table, Register tmp);
+
   //
   // Debugging
   //
diff --git a/src/cpu/ppc/vm/methodHandles_ppc.cpp b/src/cpu/ppc/vm/methodHandles_ppc.cpp
index 89c0344..c105f03 100644
--- a/src/cpu/ppc/vm/methodHandles_ppc.cpp
+++ b/src/cpu/ppc/vm/methodHandles_ppc.cpp
@@ -463,7 +463,7 @@
   bool has_mh = (strstr(adaptername, "/static") == NULL &&
                  strstr(adaptername, "linkTo") == NULL);    // static linkers don't have MH
   const char* mh_reg_name = has_mh ? "R23_method_handle" : "G23";
-  tty->print_cr("MH %s %s="INTPTR_FORMAT " sp=" INTPTR_FORMAT,
+  tty->print_cr("MH %s %s=" INTPTR_FORMAT " sp=" INTPTR_FORMAT,
                 adaptername, mh_reg_name, (intptr_t) mh, (intptr_t) entry_sp);
 
   if (Verbose) {
diff --git a/src/cpu/ppc/vm/ppc.ad b/src/cpu/ppc/vm/ppc.ad
index c3a64d3..566e765 100644
--- a/src/cpu/ppc/vm/ppc.ad
+++ b/src/cpu/ppc/vm/ppc.ad
@@ -1,6 +1,6 @@
 //
-// Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
-// Copyright 2012, 2014 SAP AG. All rights reserved.
+// Copyright (c) 2011, 2018, Oracle and/or its affiliates. All rights reserved.
+// Copyright (c) 2012, 2017 SAP SE. All rights reserved.
 // DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 //
 // This code is free software; you can redistribute it and/or modify it
@@ -2174,12 +2174,12 @@
 }
 
 // Vector ideal reg.
-const int Matcher::vector_ideal_reg(int size) {
+const uint Matcher::vector_ideal_reg(int size) {
   assert(MaxVectorSize == 8 && size == 8, "");
   return Op_RegL;
 }
 
-const int Matcher::vector_shift_count_ideal_reg(int size) {
+const uint Matcher::vector_shift_count_ideal_reg(int size) {
   fatal("vector shift is not supported");
   return Node::NotAMachineReg;
 }
@@ -8610,6 +8610,44 @@
   ins_pipe(pipe_class_default);
 %}
 
+// Bitfield Extract: URShiftI + AndI
+instruct andI_urShiftI_regI_immI_immIpow2minus1(iRegIdst dst, iRegIsrc src1, immI src2, immIpow2minus1 src3) %{
+  match(Set dst (AndI (URShiftI src1 src2) src3));
+
+  format %{ "EXTRDI  $dst, $src1, shift=$src2, mask=$src3 \t// int bitfield extract" %}
+  size(4);
+  ins_encode %{
+    // TODO: PPC port $archOpcode(ppc64Opcode_rldicl);
+    int rshift = ($src2$$constant) & 0x1f;
+    int length = log2_long(((jlong) $src3$$constant) + 1);
+    if (rshift + length > 32) {
+      // if necessary, adjust mask to omit rotated bits.
+      length = 32 - rshift;
+    }
+    __ extrdi($dst$$Register, $src1$$Register, length, 64 - (rshift + length));
+  %}
+  ins_pipe(pipe_class_default);
+%}
+
+// Bitfield Extract: URShiftL + AndL
+instruct andL_urShiftL_regL_immI_immLpow2minus1(iRegLdst dst, iRegLsrc src1, immI src2, immLpow2minus1 src3) %{
+  match(Set dst (AndL (URShiftL src1 src2) src3));
+
+  format %{ "EXTRDI  $dst, $src1, shift=$src2, mask=$src3 \t// long bitfield extract" %}
+  size(4);
+  ins_encode %{
+    // TODO: PPC port $archOpcode(ppc64Opcode_rldicl);
+    int rshift  = ($src2$$constant) & 0x3f;
+    int length = log2_long(((jlong) $src3$$constant) + 1);
+    if (rshift + length > 64) {
+      // if necessary, adjust mask to omit rotated bits.
+      length = 64 - rshift;
+    }
+    __ extrdi($dst$$Register, $src1$$Register, length, 64 - (rshift + length));
+  %}
+  ins_pipe(pipe_class_default);
+%}
+
 instruct sxtI_reg(iRegIdst dst, iRegIsrc src) %{
   match(Set dst (ConvL2I (ConvI2L src)));
 
@@ -8889,6 +8927,19 @@
   ins_pipe(pipe_class_default);
 %}
 
+// Left shifted Immediate And
+instruct andI_reg_immIhi16(iRegIdst dst, iRegIsrc src1, immIhi16  src2, flagsRegCR0 cr0) %{
+  match(Set dst (AndI src1 src2));
+  effect(KILL cr0);
+  format %{ "ANDIS   $dst, $src1, $src2.hi" %}
+  size(4);
+  ins_encode %{
+    // TODO: PPC port $archOpcode(ppc64Opcode_andis_);
+    __ andis_($dst$$Register, $src1$$Register, (int)((unsigned short)(($src2$$constant & 0xFFFF0000) >> 16)));
+  %}
+  ins_pipe(pipe_class_default);
+%}
+
 // Immediate And
 instruct andI_reg_uimm16(iRegIdst dst, iRegIsrc src1, uimmI16 src2, flagsRegCR0 cr0) %{
   match(Set dst (AndI src1 src2));
@@ -10571,6 +10622,17 @@
   ins_pipe(pipe_class_compare);
 %}
 
+instruct cmpP_reg_null(flagsReg crx, iRegP_N2P src1, immP_0or1 src2) %{
+  match(Set crx (CmpP src1 src2));
+  format %{ "CMPLDI   $crx, $src1, $src2 \t// ptr" %}
+  size(4);
+  ins_encode %{
+    // TODO: PPC port $archOpcode(ppc64Opcode_cmpl);
+    __ cmpldi($crx$$CondRegister, $src1$$Register, (int)((short)($src2$$constant & 0xFFFF)));
+  %}
+  ins_pipe(pipe_class_compare);
+%}
+
 // Used in postalloc expand.
 instruct cmpP_reg_imm16(flagsReg crx, iRegPsrc src1, immL16 src2) %{
   // This match rule prevents reordering of node before a safepoint.
diff --git a/src/cpu/ppc/vm/sharedRuntime_ppc.cpp b/src/cpu/ppc/vm/sharedRuntime_ppc.cpp
index 6685eaa..047779e 100644
--- a/src/cpu/ppc/vm/sharedRuntime_ppc.cpp
+++ b/src/cpu/ppc/vm/sharedRuntime_ppc.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * Copyright 2012, 2014 SAP AG. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -42,6 +42,8 @@
 #include "opto/runtime.hpp"
 #endif
 
+#include <alloca.h>
+
 #define __ masm->
 
 #ifdef PRODUCT
@@ -1193,7 +1195,7 @@
   // Argument is valid and klass is as expected, continue.
 
   // Extract method from inline cache, verified entry point needs it.
-  __ ld(R19_method, CompiledICHolder::holder_method_offset(), ic);
+  __ ld(R19_method, CompiledICHolder::holder_metadata_offset(), ic);
   assert(R19_method == ic, "the inline cache register is dead here");
 
   __ ld(code, method_(code));
@@ -3268,3 +3270,245 @@
   return RuntimeStub::new_runtime_stub(name, &buffer, frame_complete, frame_size_in_bytes/wordSize,
                                        oop_maps, true);
 }
+
+
+//------------------------------Montgomery multiplication------------------------
+//
+
+// Subtract 0:b from carry:a. Return carry.
+static unsigned long
+sub(unsigned long a[], unsigned long b[], unsigned long carry, long len) {
+  long i = 0;
+  unsigned long tmp, tmp2;
+  __asm__ __volatile__ (
+    "subfc  %[tmp], %[tmp], %[tmp]   \n" // pre-set CA
+    "mtctr  %[len]                   \n"
+    "0:                              \n"
+    "ldx    %[tmp], %[i], %[a]       \n"
+    "ldx    %[tmp2], %[i], %[b]      \n"
+    "subfe  %[tmp], %[tmp2], %[tmp]  \n" // subtract extended
+    "stdx   %[tmp], %[i], %[a]       \n"
+    "addi   %[i], %[i], 8            \n"
+    "bdnz   0b                       \n"
+    "addme  %[tmp], %[carry]         \n" // carry + CA - 1
+    : [i]"+b"(i), [tmp]"=&r"(tmp), [tmp2]"=&r"(tmp2)
+    : [a]"r"(a), [b]"r"(b), [carry]"r"(carry), [len]"r"(len)
+    : "ctr", "xer", "memory"
+  );
+  return tmp;
+}
+
+// Multiply (unsigned) Long A by Long B, accumulating the double-
+// length result into the accumulator formed of T0, T1, and T2.
+inline void MACC(unsigned long A, unsigned long B, unsigned long &T0, unsigned long &T1, unsigned long &T2) {
+  unsigned long hi, lo;
+  __asm__ __volatile__ (
+    "mulld  %[lo], %[A], %[B]    \n"
+    "mulhdu %[hi], %[A], %[B]    \n"
+    "addc   %[T0], %[T0], %[lo]  \n"
+    "adde   %[T1], %[T1], %[hi]  \n"
+    "addze  %[T2], %[T2]         \n"
+    : [hi]"=&r"(hi), [lo]"=&r"(lo), [T0]"+r"(T0), [T1]"+r"(T1), [T2]"+r"(T2)
+    : [A]"r"(A), [B]"r"(B)
+    : "xer"
+  );
+}
+
+// As above, but add twice the double-length result into the
+// accumulator.
+inline void MACC2(unsigned long A, unsigned long B, unsigned long &T0, unsigned long &T1, unsigned long &T2) {
+  unsigned long hi, lo;
+  __asm__ __volatile__ (
+    "mulld  %[lo], %[A], %[B]    \n"
+    "mulhdu %[hi], %[A], %[B]    \n"
+    "addc   %[T0], %[T0], %[lo]  \n"
+    "adde   %[T1], %[T1], %[hi]  \n"
+    "addze  %[T2], %[T2]         \n"
+    "addc   %[T0], %[T0], %[lo]  \n"
+    "adde   %[T1], %[T1], %[hi]  \n"
+    "addze  %[T2], %[T2]         \n"
+    : [hi]"=&r"(hi), [lo]"=&r"(lo), [T0]"+r"(T0), [T1]"+r"(T1), [T2]"+r"(T2)
+    : [A]"r"(A), [B]"r"(B)
+    : "xer"
+  );
+}
+
+// Fast Montgomery multiplication. The derivation of the algorithm is
+// in "A Cryptographic Library for the Motorola DSP56000,
+// Dusse and Kaliski, Proc. EUROCRYPT 90, pp. 230-237".
+static void
+montgomery_multiply(unsigned long a[], unsigned long b[], unsigned long n[],
+                    unsigned long m[], unsigned long inv, int len) {
+  unsigned long t0 = 0, t1 = 0, t2 = 0; // Triple-precision accumulator
+  int i;
+
+  assert(inv * n[0] == -1UL, "broken inverse in Montgomery multiply");
+
+  for (i = 0; i < len; i++) {
+    int j;
+    for (j = 0; j < i; j++) {
+      MACC(a[j], b[i-j], t0, t1, t2);
+      MACC(m[j], n[i-j], t0, t1, t2);
+    }
+    MACC(a[i], b[0], t0, t1, t2);
+    m[i] = t0 * inv;
+    MACC(m[i], n[0], t0, t1, t2);
+
+    assert(t0 == 0, "broken Montgomery multiply");
+
+    t0 = t1; t1 = t2; t2 = 0;
+  }
+
+  for (i = len; i < 2*len; i++) {
+    int j;
+    for (j = i-len+1; j < len; j++) {
+      MACC(a[j], b[i-j], t0, t1, t2);
+      MACC(m[j], n[i-j], t0, t1, t2);
+    }
+    m[i-len] = t0;
+    t0 = t1; t1 = t2; t2 = 0;
+  }
+
+  while (t0) {
+    t0 = sub(m, n, t0, len);
+  }
+}
+
+// Fast Montgomery squaring. This uses asymptotically 25% fewer
+// multiplies so it should be up to 25% faster than Montgomery
+// multiplication. However, its loop control is more complex and it
+// may actually run slower on some machines.
+static void
+montgomery_square(unsigned long a[], unsigned long n[],
+                  unsigned long m[], unsigned long inv, int len) {
+  unsigned long t0 = 0, t1 = 0, t2 = 0; // Triple-precision accumulator
+  int i;
+
+  assert(inv * n[0] == -1UL, "broken inverse in Montgomery multiply");
+
+  for (i = 0; i < len; i++) {
+    int j;
+    int end = (i+1)/2;
+    for (j = 0; j < end; j++) {
+      MACC2(a[j], a[i-j], t0, t1, t2);
+      MACC(m[j], n[i-j], t0, t1, t2);
+    }
+    if ((i & 1) == 0) {
+      MACC(a[j], a[j], t0, t1, t2);
+    }
+    for (; j < i; j++) {
+      MACC(m[j], n[i-j], t0, t1, t2);
+    }
+    m[i] = t0 * inv;
+    MACC(m[i], n[0], t0, t1, t2);
+
+    assert(t0 == 0, "broken Montgomery square");
+
+    t0 = t1; t1 = t2; t2 = 0;
+  }
+
+  for (i = len; i < 2*len; i++) {
+    int start = i-len+1;
+    int end = start + (len - start)/2;
+    int j;
+    for (j = start; j < end; j++) {
+      MACC2(a[j], a[i-j], t0, t1, t2);
+      MACC(m[j], n[i-j], t0, t1, t2);
+    }
+    if ((i & 1) == 0) {
+      MACC(a[j], a[j], t0, t1, t2);
+    }
+    for (; j < len; j++) {
+      MACC(m[j], n[i-j], t0, t1, t2);
+    }
+    m[i-len] = t0;
+    t0 = t1; t1 = t2; t2 = 0;
+  }
+
+  while (t0) {
+    t0 = sub(m, n, t0, len);
+  }
+}
+
+// The threshold at which squaring is advantageous was determined
+// experimentally on an i7-3930K (Ivy Bridge) CPU @ 3.5GHz.
+// Doesn't seem to be relevant for Power8 so we use the same value.
+#define MONTGOMERY_SQUARING_THRESHOLD 64
+
+// Copy len longwords from s to d, word-swapping as we go. The
+// destination array is reversed.
+static void reverse_words(unsigned long *s, unsigned long *d, int len) {
+  d += len;
+  while(len-- > 0) {
+    d--;
+    unsigned long s_val = *s;
+    // Swap words in a longword on little endian machines.
+#ifdef VM_LITTLE_ENDIAN
+     s_val = (s_val << 32) | (s_val >> 32);
+#endif
+    *d = s_val;
+    s++;
+  }
+}
+
+void SharedRuntime::montgomery_multiply(jint *a_ints, jint *b_ints, jint *n_ints,
+                                        jint len, jlong inv,
+                                        jint *m_ints) {
+  assert(len % 2 == 0, "array length in montgomery_multiply must be even");
+  int longwords = len/2;
+  assert(longwords > 0, "unsupported");
+
+  // Make very sure we don't use so much space that the stack might
+  // overflow. 512 jints corresponds to an 16384-bit integer and
+  // will use here a total of 8k bytes of stack space.
+  int total_allocation = longwords * sizeof (unsigned long) * 4;
+  guarantee(total_allocation <= 8192, "must be");
+  unsigned long *scratch = (unsigned long *)alloca(total_allocation);
+
+  // Local scratch arrays
+  unsigned long
+    *a = scratch + 0 * longwords,
+    *b = scratch + 1 * longwords,
+    *n = scratch + 2 * longwords,
+    *m = scratch + 3 * longwords;
+
+  reverse_words((unsigned long *)a_ints, a, longwords);
+  reverse_words((unsigned long *)b_ints, b, longwords);
+  reverse_words((unsigned long *)n_ints, n, longwords);
+
+  ::montgomery_multiply(a, b, n, m, (unsigned long)inv, longwords);
+
+  reverse_words(m, (unsigned long *)m_ints, longwords);
+}
+
+void SharedRuntime::montgomery_square(jint *a_ints, jint *n_ints,
+                                      jint len, jlong inv,
+                                      jint *m_ints) {
+  assert(len % 2 == 0, "array length in montgomery_square must be even");
+  int longwords = len/2;
+  assert(longwords > 0, "unsupported");
+
+  // Make very sure we don't use so much space that the stack might
+  // overflow. 512 jints corresponds to an 16384-bit integer and
+  // will use here a total of 6k bytes of stack space.
+  int total_allocation = longwords * sizeof (unsigned long) * 3;
+  guarantee(total_allocation <= 8192, "must be");
+  unsigned long *scratch = (unsigned long *)alloca(total_allocation);
+
+  // Local scratch arrays
+  unsigned long
+    *a = scratch + 0 * longwords,
+    *n = scratch + 1 * longwords,
+    *m = scratch + 2 * longwords;
+
+  reverse_words((unsigned long *)a_ints, a, longwords);
+  reverse_words((unsigned long *)n_ints, n, longwords);
+
+  if (len >= MONTGOMERY_SQUARING_THRESHOLD) {
+    ::montgomery_square(a, n, m, (unsigned long)inv, longwords);
+  } else {
+    ::montgomery_multiply(a, a, n, m, (unsigned long)inv, longwords);
+  }
+
+  reverse_words(m, (unsigned long *)m_ints, longwords);
+}
diff --git a/src/cpu/ppc/vm/stubGenerator_ppc.cpp b/src/cpu/ppc/vm/stubGenerator_ppc.cpp
index 325b527..1b7fb41 100644
--- a/src/cpu/ppc/vm/stubGenerator_ppc.cpp
+++ b/src/cpu/ppc/vm/stubGenerator_ppc.cpp
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
- * Copyright 2012, 2014 SAP AG. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018, SAP SE. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -2023,7 +2023,7 @@
     __ vspltisb        (vTmp2, -16);
     __ vrld            (keyPerm, keyPerm, vTmp2);
     __ vrld            (keyPerm, keyPerm, vTmp2);
-    __ vsldoi          (keyPerm, keyPerm, keyPerm, -8);
+    __ vsldoi          (keyPerm, keyPerm, keyPerm, 8);
 
     // load the 1st round key to vKey1
     __ li              (keypos, 0);
@@ -2223,7 +2223,7 @@
     __ vspltisb        (vTmp2, -16);
     __ vrld            (keyPerm, keyPerm, vTmp2);
     __ vrld            (keyPerm, keyPerm, vTmp2);
-    __ vsldoi          (keyPerm, keyPerm, keyPerm, -8);
+    __ vsldoi          (keyPerm, keyPerm, keyPerm, 8);
 
     __ cmpwi           (CCR0, keylen, 44);
     __ beq             (CCR0, L_do44);
@@ -2473,6 +2473,86 @@
     __ blr();
   }
 
+  /**
+   * Arguments:
+   *
+   * Inputs:
+   *   R3_ARG1    - int   crc
+   *   R4_ARG2    - byte* buf
+   *   R5_ARG3    - int   length (of buffer)
+   *
+   * scratch:
+   *   R2, R6-R12
+   *
+   * Ouput:
+   *   R3_RET     - int   crc result
+   */
+  // Compute CRC32 function.
+  address generate_CRC32_updateBytes(const char* name) {
+    __ align(CodeEntryAlignment);
+    StubCodeMark mark(this, "StubRoutines", name);
+    address start = __ function_entry();  // Remember stub start address (is rtn value).
+
+    // arguments to kernel_crc32:
+    const Register crc     = R3_ARG1;  // Current checksum, preset by caller or result from previous call.
+    const Register data    = R4_ARG2;  // source byte array
+    const Register dataLen = R5_ARG3;  // #bytes to process
+
+    const Register table   = R6;       // crc table address
+
+#ifdef VM_LITTLE_ENDIAN
+    if (VM_Version::has_vpmsumb()) {
+      const Register constants    = R2;  // constants address
+      const Register bconstants   = R8;  // barret table address
+
+      const Register t0      = R9;
+      const Register t1      = R10;
+      const Register t2      = R11;
+      const Register t3      = R12;
+      const Register t4      = R7;
+
+      BLOCK_COMMENT("Stub body {");
+      assert_different_registers(crc, data, dataLen, table);
+
+      StubRoutines::ppc64::generate_load_crc_table_addr(_masm, table);
+      StubRoutines::ppc64::generate_load_crc_constants_addr(_masm, constants);
+      StubRoutines::ppc64::generate_load_crc_barret_constants_addr(_masm, bconstants);
+
+      __ kernel_crc32_1word_vpmsumd(crc, data, dataLen, table, constants, bconstants, t0, t1, t2, t3, t4);
+
+      BLOCK_COMMENT("return");
+      __ mr_if_needed(R3_RET, crc);      // Updated crc is function result. No copying required (R3_ARG1 == R3_RET).
+      __ blr();
+
+      BLOCK_COMMENT("} Stub body");
+    } else
+#endif
+    {
+      const Register t0      = R2;
+      const Register t1      = R7;
+      const Register t2      = R8;
+      const Register t3      = R9;
+      const Register tc0     = R10;
+      const Register tc1     = R11;
+      const Register tc2     = R12;
+
+      BLOCK_COMMENT("Stub body {");
+      assert_different_registers(crc, data, dataLen, table);
+
+      StubRoutines::ppc64::generate_load_crc_table_addr(_masm, table);
+
+      __ kernel_crc32_1word(crc, data, dataLen, table, t0, t1, t2, t3, tc0, tc1, tc2, table);
+
+      BLOCK_COMMENT("return");
+      __ mr_if_needed(R3_RET, crc);      // Updated crc is function result. No copying required (R3_ARG1 == R3_RET).
+      __ blr();
+
+      BLOCK_COMMENT("} Stub body");
+    }
+
+    return start;
+  }
+
   // Initialization
   void generate_initial() {
     // Generates all stubs and initializes the entry points
@@ -2491,6 +2571,12 @@
     StubRoutines::_throw_StackOverflowError_entry   =
       generate_throw_exception("StackOverflowError throw_exception",
                                CAST_FROM_FN_PTR(address, SharedRuntime::throw_StackOverflowError), false);
+
+    // CRC32 Intrinsics.
+    if (UseCRC32Intrinsics) {
+      StubRoutines::_crc_table_adr    = (address)StubRoutines::ppc64::_crc_table;
+      StubRoutines::_updateBytesCRC32 = generate_CRC32_updateBytes("CRC32_updateBytes");
+    }
   }
 
   void generate_all() {
@@ -2524,6 +2610,14 @@
       StubRoutines::_aescrypt_decryptBlock = generate_aescrypt_decryptBlock();
     }
 
+    if (UseMontgomeryMultiplyIntrinsic) {
+      StubRoutines::_montgomeryMultiply
+        = CAST_FROM_FN_PTR(address, SharedRuntime::montgomery_multiply);
+    }
+    if (UseMontgomerySquareIntrinsic) {
+      StubRoutines::_montgomerySquare
+        = CAST_FROM_FN_PTR(address, SharedRuntime::montgomery_square);
+    }
   }
 
  public:
diff --git a/src/cpu/ppc/vm/stubRoutines_ppc_64.cpp b/src/cpu/ppc/vm/stubRoutines_ppc_64.cpp
index 0c1b93b..eb9b0b6 100644
--- a/src/cpu/ppc/vm/stubRoutines_ppc_64.cpp
+++ b/src/cpu/ppc/vm/stubRoutines_ppc_64.cpp
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
- * Copyright 2012, 2014 SAP AG. All rights reserved.
+ * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018 SAP SE. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,766 @@
  *
  */
 
+#include "asm/macroAssembler.inline.hpp"
+#include "runtime/stubRoutines.hpp"
+
 // Implementation of the platform-specific part of StubRoutines - for
 // a description of how to extend it, see the stubRoutines.hpp file.
 
 
+#define __ masm->
+
+// CRC32 Intrinsics.
+void StubRoutines::ppc64::generate_load_crc_table_addr(MacroAssembler* masm, Register table) {
+  __ load_const(table, StubRoutines::_crc_table_adr);
+}
+
+void StubRoutines::ppc64::generate_load_crc_constants_addr(MacroAssembler* masm, Register table) {
+  __ load_const_optimized(table, (address)StubRoutines::ppc64::_constants, R0);
+}
+
+void StubRoutines::ppc64::generate_load_crc_barret_constants_addr(MacroAssembler* masm, Register table) {
+  __ load_const_optimized(table, (address)StubRoutines::ppc64::_barret_constants, R0);
+}
+
+juint* StubRoutines::ppc64::generate_crc_constants() {
+  juint constants[CRC32_CONSTANTS_SIZE] = {
+      // Reduce 262144 kbits to 1024 bits
+      0x99ea94a8UL, 0x00000000UL, 0x651797d2UL, 0x00000001UL,       // x^261120 mod p(x)` << 1, x^261184 mod p(x)` << 1
+      0x945a8420UL, 0x00000000UL, 0x21e0d56cUL, 0x00000000UL,       // x^260096 mod p(x)` << 1, x^260160 mod p(x)` << 1
+      0x30762706UL, 0x00000000UL, 0x0f95ecaaUL, 0x00000000UL,       // x^259072 mod p(x)` << 1, x^259136 mod p(x)` << 1
+      0xa52fc582UL, 0x00000001UL, 0xebd224acUL, 0x00000001UL,       // x^258048 mod p(x)` << 1, x^258112 mod p(x)` << 1
+      0xa4a7167aUL, 0x00000001UL, 0x0ccb97caUL, 0x00000000UL,       // x^257024 mod p(x)` << 1, x^257088 mod p(x)` << 1
+      0x0c18249aUL, 0x00000000UL, 0x006ec8a8UL, 0x00000001UL,       // x^256000 mod p(x)` << 1, x^256064 mod p(x)` << 1
+      0xa924ae7cUL, 0x00000000UL, 0x4f58f196UL, 0x00000001UL,       // x^254976 mod p(x)` << 1, x^255040 mod p(x)` << 1
+      0xe12ccc12UL, 0x00000001UL, 0xa7192ca6UL, 0x00000001UL,       // x^253952 mod p(x)` << 1, x^254016 mod p(x)` << 1
+      0xa0b9d4acUL, 0x00000000UL, 0x9a64bab2UL, 0x00000001UL,       // x^252928 mod p(x)` << 1, x^252992 mod p(x)` << 1
+      0x95e8ddfeUL, 0x00000000UL, 0x14f4ed2eUL, 0x00000000UL,       // x^251904 mod p(x)` << 1, x^251968 mod p(x)` << 1
+      0x233fddc4UL, 0x00000000UL, 0x1092b6a2UL, 0x00000001UL,       // x^250880 mod p(x)` << 1, x^250944 mod p(x)` << 1
+      0xb4529b62UL, 0x00000001UL, 0xc8a1629cUL, 0x00000000UL,       // x^249856 mod p(x)` << 1, x^249920 mod p(x)` << 1
+      0xa7fa0e64UL, 0x00000001UL, 0x7bf32e8eUL, 0x00000001UL,       // x^248832 mod p(x)` << 1, x^248896 mod p(x)` << 1
+      0xb5334592UL, 0x00000001UL, 0xf8cc6582UL, 0x00000001UL,       // x^247808 mod p(x)` << 1, x^247872 mod p(x)` << 1
+      0x1f8ee1b4UL, 0x00000001UL, 0x8631ddf0UL, 0x00000000UL,       // x^246784 mod p(x)` << 1, x^246848 mod p(x)` << 1
+      0x6252e632UL, 0x00000000UL, 0x7e5a76d0UL, 0x00000000UL,       // x^245760 mod p(x)` << 1, x^245824 mod p(x)` << 1
+      0xab973e84UL, 0x00000000UL, 0x2b09b31cUL, 0x00000000UL,       // x^244736 mod p(x)` << 1, x^244800 mod p(x)` << 1
+      0x7734f5ecUL, 0x00000000UL, 0xb2df1f84UL, 0x00000001UL,       // x^243712 mod p(x)` << 1, x^243776 mod p(x)` << 1
+      0x7c547798UL, 0x00000000UL, 0xd6f56afcUL, 0x00000001UL,       // x^242688 mod p(x)` << 1, x^242752 mod p(x)` << 1
+      0x7ec40210UL, 0x00000000UL, 0xb9b5e70cUL, 0x00000001UL,       // x^241664 mod p(x)` << 1, x^241728 mod p(x)` << 1
+      0xab1695a8UL, 0x00000001UL, 0x34b626d2UL, 0x00000000UL,       // x^240640 mod p(x)` << 1, x^240704 mod p(x)` << 1
+      0x90494bbaUL, 0x00000000UL, 0x4c53479aUL, 0x00000001UL,       // x^239616 mod p(x)` << 1, x^239680 mod p(x)` << 1
+      0x123fb816UL, 0x00000001UL, 0xa6d179a4UL, 0x00000001UL,       // x^238592 mod p(x)` << 1, x^238656 mod p(x)` << 1
+      0xe188c74cUL, 0x00000001UL, 0x5abd16b4UL, 0x00000001UL,       // x^237568 mod p(x)` << 1, x^237632 mod p(x)` << 1
+      0xc2d3451cUL, 0x00000001UL, 0x018f9852UL, 0x00000000UL,       // x^236544 mod p(x)` << 1, x^236608 mod p(x)` << 1
+      0xf55cf1caUL, 0x00000000UL, 0x1fb3084aUL, 0x00000000UL,       // x^235520 mod p(x)` << 1, x^235584 mod p(x)` << 1
+      0xa0531540UL, 0x00000001UL, 0xc53dfb04UL, 0x00000000UL,       // x^234496 mod p(x)` << 1, x^234560 mod p(x)` << 1
+      0x32cd7ebcUL, 0x00000001UL, 0xe10c9ad6UL, 0x00000000UL,       // x^233472 mod p(x)` << 1, x^233536 mod p(x)` << 1
+      0x73ab7f36UL, 0x00000000UL, 0x25aa994aUL, 0x00000000UL,       // x^232448 mod p(x)` << 1, x^232512 mod p(x)` << 1
+      0x41aed1c2UL, 0x00000000UL, 0xfa3a74c4UL, 0x00000000UL,       // x^231424 mod p(x)` << 1, x^231488 mod p(x)` << 1
+      0x36c53800UL, 0x00000001UL, 0x33eb3f40UL, 0x00000000UL,       // x^230400 mod p(x)` << 1, x^230464 mod p(x)` << 1
+      0x26835a30UL, 0x00000001UL, 0x7193f296UL, 0x00000001UL,       // x^229376 mod p(x)` << 1, x^229440 mod p(x)` << 1
+      0x6241b502UL, 0x00000000UL, 0x43f6c86aUL, 0x00000000UL,       // x^228352 mod p(x)` << 1, x^228416 mod p(x)` << 1
+      0xd5196ad4UL, 0x00000000UL, 0x6b513ec6UL, 0x00000001UL,       // x^227328 mod p(x)` << 1, x^227392 mod p(x)` << 1
+      0x9cfa769aUL, 0x00000000UL, 0xc8f25b4eUL, 0x00000000UL,       // x^226304 mod p(x)` << 1, x^226368 mod p(x)` << 1
+      0x920e5df4UL, 0x00000000UL, 0xa45048ecUL, 0x00000001UL,       // x^225280 mod p(x)` << 1, x^225344 mod p(x)` << 1
+      0x69dc310eUL, 0x00000001UL, 0x0c441004UL, 0x00000000UL,       // x^224256 mod p(x)` << 1, x^224320 mod p(x)` << 1
+      0x09fc331cUL, 0x00000000UL, 0x0e17cad6UL, 0x00000000UL,       // x^223232 mod p(x)` << 1, x^223296 mod p(x)` << 1
+      0x0d94a81eUL, 0x00000001UL, 0x253ae964UL, 0x00000001UL,       // x^222208 mod p(x)` << 1, x^222272 mod p(x)` << 1
+      0x27a20ab2UL, 0x00000000UL, 0xd7c88ebcUL, 0x00000001UL,       // x^221184 mod p(x)` << 1, x^221248 mod p(x)` << 1
+      0x14f87504UL, 0x00000001UL, 0xe7ca913aUL, 0x00000001UL,       // x^220160 mod p(x)` << 1, x^220224 mod p(x)` << 1
+      0x4b076d96UL, 0x00000000UL, 0x33ed078aUL, 0x00000000UL,       // x^219136 mod p(x)` << 1, x^219200 mod p(x)` << 1
+      0xda4d1e74UL, 0x00000000UL, 0xe1839c78UL, 0x00000000UL,       // x^218112 mod p(x)` << 1, x^218176 mod p(x)` << 1
+      0x1b81f672UL, 0x00000000UL, 0x322b267eUL, 0x00000001UL,       // x^217088 mod p(x)` << 1, x^217152 mod p(x)` << 1
+      0x9367c988UL, 0x00000000UL, 0x638231b6UL, 0x00000000UL,       // x^216064 mod p(x)` << 1, x^216128 mod p(x)` << 1
+      0x717214caUL, 0x00000001UL, 0xee7f16f4UL, 0x00000001UL,       // x^215040 mod p(x)` << 1, x^215104 mod p(x)` << 1
+      0x9f47d820UL, 0x00000000UL, 0x17d9924aUL, 0x00000001UL,       // x^214016 mod p(x)` << 1, x^214080 mod p(x)` << 1
+      0x0d9a47d2UL, 0x00000001UL, 0xe1a9e0c4UL, 0x00000000UL,       // x^212992 mod p(x)` << 1, x^213056 mod p(x)` << 1
+      0xa696c58cUL, 0x00000000UL, 0x403731dcUL, 0x00000001UL,       // x^211968 mod p(x)` << 1, x^212032 mod p(x)` << 1
+      0x2aa28ec6UL, 0x00000000UL, 0xa5ea9682UL, 0x00000001UL,       // x^210944 mod p(x)` << 1, x^211008 mod p(x)` << 1
+      0xfe18fd9aUL, 0x00000001UL, 0x01c5c578UL, 0x00000001UL,       // x^209920 mod p(x)` << 1, x^209984 mod p(x)` << 1
+      0x9d4fc1aeUL, 0x00000001UL, 0xdddf6494UL, 0x00000000UL,       // x^208896 mod p(x)` << 1, x^208960 mod p(x)` << 1
+      0xba0e3deaUL, 0x00000001UL, 0xf1c3db28UL, 0x00000000UL,       // x^207872 mod p(x)` << 1, x^207936 mod p(x)` << 1
+      0x74b59a5eUL, 0x00000000UL, 0x3112fb9cUL, 0x00000001UL,       // x^206848 mod p(x)` << 1, x^206912 mod p(x)` << 1
+      0xf2b5ea98UL, 0x00000000UL, 0xb680b906UL, 0x00000000UL,       // x^205824 mod p(x)` << 1, x^205888 mod p(x)` << 1
+      0x87132676UL, 0x00000001UL, 0x1a282932UL, 0x00000000UL,       // x^204800 mod p(x)` << 1, x^204864 mod p(x)` << 1
+      0x0a8c6ad4UL, 0x00000001UL, 0x89406e7eUL, 0x00000000UL,       // x^203776 mod p(x)` << 1, x^203840 mod p(x)` << 1
+      0xe21dfe70UL, 0x00000001UL, 0xdef6be8cUL, 0x00000001UL,       // x^202752 mod p(x)` << 1, x^202816 mod p(x)` << 1
+      0xda0050e4UL, 0x00000001UL, 0x75258728UL, 0x00000000UL,       // x^201728 mod p(x)` << 1, x^201792 mod p(x)` << 1
+      0x772172aeUL, 0x00000000UL, 0x9536090aUL, 0x00000001UL,       // x^200704 mod p(x)` << 1, x^200768 mod p(x)` << 1
+      0xe47724aaUL, 0x00000000UL, 0xf2455bfcUL, 0x00000000UL,       // x^199680 mod p(x)` << 1, x^199744 mod p(x)` << 1
+      0x3cd63ac4UL, 0x00000000UL, 0x8c40baf4UL, 0x00000001UL,       // x^198656 mod p(x)` << 1, x^198720 mod p(x)` << 1
+      0xbf47d352UL, 0x00000001UL, 0x4cd390d4UL, 0x00000000UL,       // x^197632 mod p(x)` << 1, x^197696 mod p(x)` << 1
+      0x8dc1d708UL, 0x00000001UL, 0xe4ece95aUL, 0x00000001UL,       // x^196608 mod p(x)` << 1, x^196672 mod p(x)` << 1
+      0x2d4620a4UL, 0x00000000UL, 0x1a3ee918UL, 0x00000000UL,       // x^195584 mod p(x)` << 1, x^195648 mod p(x)` << 1
+      0x58fd1740UL, 0x00000000UL, 0x7c652fb8UL, 0x00000000UL,       // x^194560 mod p(x)` << 1, x^194624 mod p(x)` << 1
+      0xdadd9bfcUL, 0x00000000UL, 0x1c67842cUL, 0x00000001UL,       // x^193536 mod p(x)` << 1, x^193600 mod p(x)` << 1
+      0xea2140beUL, 0x00000001UL, 0x254f759cUL, 0x00000000UL,       // x^192512 mod p(x)` << 1, x^192576 mod p(x)` << 1
+      0x9de128baUL, 0x00000000UL, 0x7ece94caUL, 0x00000000UL,       // x^191488 mod p(x)` << 1, x^191552 mod p(x)` << 1
+      0x3ac3aa8eUL, 0x00000001UL, 0x38f258c2UL, 0x00000000UL,       // x^190464 mod p(x)` << 1, x^190528 mod p(x)` << 1
+      0x99980562UL, 0x00000000UL, 0xcdf17b00UL, 0x00000001UL,       // x^189440 mod p(x)` << 1, x^189504 mod p(x)` << 1
+      0xc1579c86UL, 0x00000001UL, 0x1f882c16UL, 0x00000001UL,       // x^188416 mod p(x)` << 1, x^188480 mod p(x)` << 1
+      0x68dbbf94UL, 0x00000000UL, 0x00093fc8UL, 0x00000001UL,       // x^187392 mod p(x)` << 1, x^187456 mod p(x)` << 1
+      0x4509fb04UL, 0x00000000UL, 0xcd684f16UL, 0x00000001UL,       // x^186368 mod p(x)` << 1, x^186432 mod p(x)` << 1
+      0x202f6398UL, 0x00000001UL, 0x4bc6a70aUL, 0x00000000UL,       // x^185344 mod p(x)` << 1, x^185408 mod p(x)` << 1
+      0x3aea243eUL, 0x00000001UL, 0x4fc7e8e4UL, 0x00000000UL,       // x^184320 mod p(x)` << 1, x^184384 mod p(x)` << 1
+      0xb4052ae6UL, 0x00000001UL, 0x30103f1cUL, 0x00000001UL,       // x^183296 mod p(x)` << 1, x^183360 mod p(x)` << 1
+      0xcd2a0ae8UL, 0x00000001UL, 0x11b0024cUL, 0x00000001UL,       // x^182272 mod p(x)` << 1, x^182336 mod p(x)` << 1
+      0xfe4aa8b4UL, 0x00000001UL, 0x0b3079daUL, 0x00000001UL,       // x^181248 mod p(x)` << 1, x^181312 mod p(x)` << 1
+      0xd1559a42UL, 0x00000001UL, 0x0192bcc2UL, 0x00000001UL,       // x^180224 mod p(x)` << 1, x^180288 mod p(x)` << 1
+      0xf3e05eccUL, 0x00000001UL, 0x74838d50UL, 0x00000000UL,       // x^179200 mod p(x)` << 1, x^179264 mod p(x)` << 1
+      0x04ddd2ccUL, 0x00000001UL, 0x1b20f520UL, 0x00000000UL,       // x^178176 mod p(x)` << 1, x^178240 mod p(x)` << 1
+      0x5393153cUL, 0x00000001UL, 0x50c3590aUL, 0x00000000UL,       // x^177152 mod p(x)` << 1, x^177216 mod p(x)` << 1
+      0x57e942c6UL, 0x00000000UL, 0xb41cac8eUL, 0x00000000UL,       // x^176128 mod p(x)` << 1, x^176192 mod p(x)` << 1
+      0x2c633850UL, 0x00000001UL, 0x0c72cc78UL, 0x00000000UL,       // x^175104 mod p(x)` << 1, x^175168 mod p(x)` << 1
+      0xebcaae4cUL, 0x00000000UL, 0x30cdb032UL, 0x00000000UL,       // x^174080 mod p(x)` << 1, x^174144 mod p(x)` << 1
+      0x3ee532a6UL, 0x00000001UL, 0x3e09fc32UL, 0x00000001UL,       // x^173056 mod p(x)` << 1, x^173120 mod p(x)` << 1
+      0xbf0cbc7eUL, 0x00000001UL, 0x1ed624d2UL, 0x00000000UL,       // x^172032 mod p(x)` << 1, x^172096 mod p(x)` << 1
+      0xd50b7a5aUL, 0x00000000UL, 0x781aee1aUL, 0x00000000UL,       // x^171008 mod p(x)` << 1, x^171072 mod p(x)` << 1
+      0x02fca6e8UL, 0x00000000UL, 0xc4d8348cUL, 0x00000001UL,       // x^169984 mod p(x)` << 1, x^170048 mod p(x)` << 1
+      0x7af40044UL, 0x00000000UL, 0x57a40336UL, 0x00000000UL,       // x^168960 mod p(x)` << 1, x^169024 mod p(x)` << 1
+      0x16178744UL, 0x00000000UL, 0x85544940UL, 0x00000000UL,       // x^167936 mod p(x)` << 1, x^168000 mod p(x)` << 1
+      0x4c177458UL, 0x00000001UL, 0x9cd21e80UL, 0x00000001UL,       // x^166912 mod p(x)` << 1, x^166976 mod p(x)` << 1
+      0x1b6ddf04UL, 0x00000001UL, 0x3eb95bc0UL, 0x00000001UL,       // x^165888 mod p(x)` << 1, x^165952 mod p(x)` << 1
+      0xf3e29cccUL, 0x00000001UL, 0xdfc9fdfcUL, 0x00000001UL,       // x^164864 mod p(x)` << 1, x^164928 mod p(x)` << 1
+      0x35ae7562UL, 0x00000001UL, 0xcd028bc2UL, 0x00000000UL,       // x^163840 mod p(x)` << 1, x^163904 mod p(x)` << 1
+      0x90ef812cUL, 0x00000001UL, 0x90db8c44UL, 0x00000000UL,       // x^162816 mod p(x)` << 1, x^162880 mod p(x)` << 1
+      0x67a2c786UL, 0x00000000UL, 0x0010a4ceUL, 0x00000001UL,       // x^161792 mod p(x)` << 1, x^161856 mod p(x)` << 1
+      0x48b9496cUL, 0x00000000UL, 0xc8f4c72cUL, 0x00000001UL,       // x^160768 mod p(x)` << 1, x^160832 mod p(x)` << 1
+      0x5a422de6UL, 0x00000001UL, 0x1c26170cUL, 0x00000000UL,       // x^159744 mod p(x)` << 1, x^159808 mod p(x)` << 1
+      0xef0e3640UL, 0x00000001UL, 0xe3fccf68UL, 0x00000000UL,       // x^158720 mod p(x)` << 1, x^158784 mod p(x)` << 1
+      0x006d2d26UL, 0x00000001UL, 0xd513ed24UL, 0x00000000UL,       // x^157696 mod p(x)` << 1, x^157760 mod p(x)` << 1
+      0x170d56d6UL, 0x00000001UL, 0x141beadaUL, 0x00000000UL,       // x^156672 mod p(x)` << 1, x^156736 mod p(x)` << 1
+      0xa5fb613cUL, 0x00000000UL, 0x1071aea0UL, 0x00000001UL,       // x^155648 mod p(x)` << 1, x^155712 mod p(x)` << 1
+      0x40bbf7fcUL, 0x00000000UL, 0x2e19080aUL, 0x00000001UL,       // x^154624 mod p(x)` << 1, x^154688 mod p(x)` << 1
+      0x6ac3a5b2UL, 0x00000001UL, 0x00ecf826UL, 0x00000001UL,       // x^153600 mod p(x)` << 1, x^153664 mod p(x)` << 1
+      0xabf16230UL, 0x00000000UL, 0x69b09412UL, 0x00000000UL,       // x^152576 mod p(x)` << 1, x^152640 mod p(x)` << 1
+      0xebe23facUL, 0x00000001UL, 0x22297bacUL, 0x00000001UL,       // x^151552 mod p(x)` << 1, x^151616 mod p(x)` << 1
+      0x8b6a0894UL, 0x00000000UL, 0xe9e4b068UL, 0x00000000UL,       // x^150528 mod p(x)` << 1, x^150592 mod p(x)` << 1
+      0x288ea478UL, 0x00000001UL, 0x4b38651aUL, 0x00000000UL,       // x^149504 mod p(x)` << 1, x^149568 mod p(x)` << 1
+      0x6619c442UL, 0x00000001UL, 0x468360e2UL, 0x00000001UL,       // x^148480 mod p(x)` << 1, x^148544 mod p(x)` << 1
+      0x86230038UL, 0x00000000UL, 0x121c2408UL, 0x00000000UL,       // x^147456 mod p(x)` << 1, x^147520 mod p(x)` << 1
+      0x7746a756UL, 0x00000001UL, 0xda7e7d08UL, 0x00000000UL,       // x^146432 mod p(x)` << 1, x^146496 mod p(x)` << 1
+      0x91b8f8f8UL, 0x00000001UL, 0x058d7652UL, 0x00000001UL,       // x^145408 mod p(x)` << 1, x^145472 mod p(x)` << 1
+      0x8e167708UL, 0x00000000UL, 0x4a098a90UL, 0x00000001UL,       // x^144384 mod p(x)` << 1, x^144448 mod p(x)` << 1
+      0x48b22d54UL, 0x00000001UL, 0x20dbe72eUL, 0x00000000UL,       // x^143360 mod p(x)` << 1, x^143424 mod p(x)` << 1
+      0x44ba2c3cUL, 0x00000000UL, 0x1e7323e8UL, 0x00000001UL,       // x^142336 mod p(x)` << 1, x^142400 mod p(x)` << 1
+      0xb54d2b52UL, 0x00000000UL, 0xd5d4bf94UL, 0x00000000UL,       // x^141312 mod p(x)` << 1, x^141376 mod p(x)` << 1
+      0x05a4fd8aUL, 0x00000000UL, 0x99d8746cUL, 0x00000001UL,       // x^140288 mod p(x)` << 1, x^140352 mod p(x)` << 1
+      0x39f9fc46UL, 0x00000001UL, 0xce9ca8a0UL, 0x00000000UL,       // x^139264 mod p(x)` << 1, x^139328 mod p(x)` << 1
+      0x5a1fa824UL, 0x00000001UL, 0x136edeceUL, 0x00000000UL,       // x^138240 mod p(x)` << 1, x^138304 mod p(x)` << 1
+      0x0a61ae4cUL, 0x00000000UL, 0x9b92a068UL, 0x00000001UL,       // x^137216 mod p(x)` << 1, x^137280 mod p(x)` << 1
+      0x45e9113eUL, 0x00000001UL, 0x71d62206UL, 0x00000000UL,       // x^136192 mod p(x)` << 1, x^136256 mod p(x)` << 1
+      0x6a348448UL, 0x00000000UL, 0xdfc50158UL, 0x00000000UL,       // x^135168 mod p(x)` << 1, x^135232 mod p(x)` << 1
+      0x4d80a08cUL, 0x00000000UL, 0x517626bcUL, 0x00000001UL,       // x^134144 mod p(x)` << 1, x^134208 mod p(x)` << 1
+      0x4b6837a0UL, 0x00000001UL, 0x48d1e4faUL, 0x00000001UL,       // x^133120 mod p(x)` << 1, x^133184 mod p(x)` << 1
+      0x6896a7fcUL, 0x00000001UL, 0x94d8266eUL, 0x00000000UL,       // x^132096 mod p(x)` << 1, x^132160 mod p(x)` << 1
+      0x4f187140UL, 0x00000001UL, 0x606c5e34UL, 0x00000000UL,       // x^131072 mod p(x)` << 1, x^131136 mod p(x)` << 1
+      0x9581b9daUL, 0x00000001UL, 0x9766beaaUL, 0x00000001UL,       // x^130048 mod p(x)` << 1, x^130112 mod p(x)` << 1
+      0x091bc984UL, 0x00000001UL, 0xd80c506cUL, 0x00000001UL,       // x^129024 mod p(x)` << 1, x^129088 mod p(x)` << 1
+      0x1067223cUL, 0x00000000UL, 0x1e73837cUL, 0x00000000UL,       // x^128000 mod p(x)` << 1, x^128064 mod p(x)` << 1
+      0xab16ea02UL, 0x00000001UL, 0x64d587deUL, 0x00000000UL,       // x^126976 mod p(x)` << 1, x^127040 mod p(x)` << 1
+      0x3c4598a8UL, 0x00000001UL, 0xf4a507b0UL, 0x00000000UL,       // x^125952 mod p(x)` << 1, x^126016 mod p(x)` << 1
+      0xb3735430UL, 0x00000000UL, 0x40e342fcUL, 0x00000000UL,       // x^124928 mod p(x)` << 1, x^124992 mod p(x)` << 1
+      0xbb3fc0c0UL, 0x00000001UL, 0xd5ad9c3aUL, 0x00000001UL,       // x^123904 mod p(x)` << 1, x^123968 mod p(x)` << 1
+      0x570ae19cUL, 0x00000001UL, 0x94a691a4UL, 0x00000000UL,       // x^122880 mod p(x)` << 1, x^122944 mod p(x)` << 1
+      0xea910712UL, 0x00000001UL, 0x271ecdfaUL, 0x00000001UL,       // x^121856 mod p(x)` << 1, x^121920 mod p(x)` << 1
+      0x67127128UL, 0x00000001UL, 0x9e54475aUL, 0x00000000UL,       // x^120832 mod p(x)` << 1, x^120896 mod p(x)` << 1
+      0x19e790a2UL, 0x00000000UL, 0xc9c099eeUL, 0x00000000UL,       // x^119808 mod p(x)` << 1, x^119872 mod p(x)` << 1
+      0x3788f710UL, 0x00000000UL, 0x9a2f736cUL, 0x00000000UL,       // x^118784 mod p(x)` << 1, x^118848 mod p(x)` << 1
+      0x682a160eUL, 0x00000001UL, 0xbb9f4996UL, 0x00000000UL,       // x^117760 mod p(x)` << 1, x^117824 mod p(x)` << 1
+      0x7f0ebd2eUL, 0x00000000UL, 0xdb688050UL, 0x00000001UL,       // x^116736 mod p(x)` << 1, x^116800 mod p(x)` << 1
+      0x2b032080UL, 0x00000000UL, 0xe9b10af4UL, 0x00000000UL,       // x^115712 mod p(x)` << 1, x^115776 mod p(x)` << 1
+      0xcfd1664aUL, 0x00000000UL, 0x2d4545e4UL, 0x00000001UL,       // x^114688 mod p(x)` << 1, x^114752 mod p(x)` << 1
+      0xaa1181c2UL, 0x00000000UL, 0x0361139cUL, 0x00000000UL,       // x^113664 mod p(x)` << 1, x^113728 mod p(x)` << 1
+      0xddd08002UL, 0x00000000UL, 0xa5a1a3a8UL, 0x00000001UL,       // x^112640 mod p(x)` << 1, x^112704 mod p(x)` << 1
+      0xe8dd0446UL, 0x00000000UL, 0x6844e0b0UL, 0x00000000UL,       // x^111616 mod p(x)` << 1, x^111680 mod p(x)` << 1
+      0xbbd94a00UL, 0x00000001UL, 0xc3762f28UL, 0x00000000UL,       // x^110592 mod p(x)` << 1, x^110656 mod p(x)` << 1
+      0xab6cd180UL, 0x00000000UL, 0xd26287a2UL, 0x00000001UL,       // x^109568 mod p(x)` << 1, x^109632 mod p(x)` << 1
+      0x31803ce2UL, 0x00000000UL, 0xf6f0bba8UL, 0x00000001UL,       // x^108544 mod p(x)` << 1, x^108608 mod p(x)` << 1
+      0x24f40b0cUL, 0x00000000UL, 0x2ffabd62UL, 0x00000000UL,       // x^107520 mod p(x)` << 1, x^107584 mod p(x)` << 1
+      0xba1d9834UL, 0x00000001UL, 0xfb4516b8UL, 0x00000000UL,       // x^106496 mod p(x)` << 1, x^106560 mod p(x)` << 1
+      0x04de61aaUL, 0x00000001UL, 0x8cfa961cUL, 0x00000001UL,       // x^105472 mod p(x)` << 1, x^105536 mod p(x)` << 1
+      0x13e40d46UL, 0x00000001UL, 0x9e588d52UL, 0x00000001UL,       // x^104448 mod p(x)` << 1, x^104512 mod p(x)` << 1
+      0x415598a0UL, 0x00000001UL, 0x180f0bbcUL, 0x00000001UL,       // x^103424 mod p(x)` << 1, x^103488 mod p(x)` << 1
+      0xbf6c8c90UL, 0x00000000UL, 0xe1d9177aUL, 0x00000000UL,       // x^102400 mod p(x)` << 1, x^102464 mod p(x)` << 1
+      0x788b0504UL, 0x00000001UL, 0x05abc27cUL, 0x00000001UL,       // x^101376 mod p(x)` << 1, x^101440 mod p(x)` << 1
+      0x38385d02UL, 0x00000000UL, 0x972e4a58UL, 0x00000000UL,       // x^100352 mod p(x)` << 1, x^100416 mod p(x)` << 1
+      0xb6c83844UL, 0x00000001UL, 0x83499a5eUL, 0x00000001UL,       // x^99328 mod p(x)` << 1, x^99392 mod p(x)` << 1
+      0x51061a8aUL, 0x00000000UL, 0xc96a8ccaUL, 0x00000001UL,       // x^98304 mod p(x)` << 1, x^98368 mod p(x)` << 1
+      0x7351388aUL, 0x00000001UL, 0xa1a5b60cUL, 0x00000001UL,       // x^97280 mod p(x)` << 1, x^97344 mod p(x)` << 1
+      0x32928f92UL, 0x00000001UL, 0xe4b6ac9cUL, 0x00000000UL,       // x^96256 mod p(x)` << 1, x^96320 mod p(x)` << 1
+      0xe6b4f48aUL, 0x00000000UL, 0x807e7f5aUL, 0x00000001UL,       // x^95232 mod p(x)` << 1, x^95296 mod p(x)` << 1
+      0x39d15e90UL, 0x00000000UL, 0x7a7e3bc8UL, 0x00000001UL,       // x^94208 mod p(x)` << 1, x^94272 mod p(x)` << 1
+      0x312d6074UL, 0x00000000UL, 0xd73975daUL, 0x00000000UL,       // x^93184 mod p(x)` << 1, x^93248 mod p(x)` << 1
+      0x7bbb2cc4UL, 0x00000001UL, 0x7375d038UL, 0x00000001UL,       // x^92160 mod p(x)` << 1, x^92224 mod p(x)` << 1
+      0x6ded3e18UL, 0x00000001UL, 0x193680bcUL, 0x00000000UL,       // x^91136 mod p(x)` << 1, x^91200 mod p(x)` << 1
+      0xf1638b16UL, 0x00000000UL, 0x999b06f6UL, 0x00000000UL,       // x^90112 mod p(x)` << 1, x^90176 mod p(x)` << 1
+      0xd38b9eccUL, 0x00000001UL, 0xf685d2b8UL, 0x00000001UL,       // x^89088 mod p(x)` << 1, x^89152 mod p(x)` << 1
+      0x8b8d09dcUL, 0x00000001UL, 0xf4ecbed2UL, 0x00000001UL,       // x^88064 mod p(x)` << 1, x^88128 mod p(x)` << 1
+      0xe7bc27d2UL, 0x00000000UL, 0xba16f1a0UL, 0x00000000UL,       // x^87040 mod p(x)` << 1, x^87104 mod p(x)` << 1
+      0x275e1e96UL, 0x00000000UL, 0x15aceac4UL, 0x00000001UL,       // x^86016 mod p(x)` << 1, x^86080 mod p(x)` << 1
+      0xe2e3031eUL, 0x00000000UL, 0xaeff6292UL, 0x00000001UL,       // x^84992 mod p(x)` << 1, x^85056 mod p(x)` << 1
+      0x041c84d8UL, 0x00000001UL, 0x9640124cUL, 0x00000000UL,       // x^83968 mod p(x)` << 1, x^84032 mod p(x)` << 1
+      0x706ce672UL, 0x00000000UL, 0x14f41f02UL, 0x00000001UL,       // x^82944 mod p(x)` << 1, x^83008 mod p(x)` << 1
+      0x5d5070daUL, 0x00000001UL, 0x9c5f3586UL, 0x00000000UL,       // x^81920 mod p(x)` << 1, x^81984 mod p(x)` << 1
+      0x38f9493aUL, 0x00000000UL, 0x878275faUL, 0x00000001UL,       // x^80896 mod p(x)` << 1, x^80960 mod p(x)` << 1
+      0xa3348a76UL, 0x00000000UL, 0xddc42ce8UL, 0x00000000UL,       // x^79872 mod p(x)` << 1, x^79936 mod p(x)` << 1
+      0xad0aab92UL, 0x00000001UL, 0x81d2c73aUL, 0x00000001UL,       // x^78848 mod p(x)` << 1, x^78912 mod p(x)` << 1
+      0x9e85f712UL, 0x00000001UL, 0x41c9320aUL, 0x00000001UL,       // x^77824 mod p(x)` << 1, x^77888 mod p(x)` << 1
+      0x5a871e76UL, 0x00000000UL, 0x5235719aUL, 0x00000001UL,       // x^76800 mod p(x)` << 1, x^76864 mod p(x)` << 1
+      0x7249c662UL, 0x00000001UL, 0xbe27d804UL, 0x00000000UL,       // x^75776 mod p(x)` << 1, x^75840 mod p(x)` << 1
+      0x3a084712UL, 0x00000000UL, 0x6242d45aUL, 0x00000000UL,       // x^74752 mod p(x)` << 1, x^74816 mod p(x)` << 1
+      0xed438478UL, 0x00000000UL, 0x9a53638eUL, 0x00000000UL,       // x^73728 mod p(x)` << 1, x^73792 mod p(x)` << 1
+      0xabac34ccUL, 0x00000000UL, 0x001ecfb6UL, 0x00000001UL,       // x^72704 mod p(x)` << 1, x^72768 mod p(x)` << 1
+      0x5f35ef3eUL, 0x00000000UL, 0x6d7c2d64UL, 0x00000001UL,       // x^71680 mod p(x)` << 1, x^71744 mod p(x)` << 1
+      0x47d6608cUL, 0x00000000UL, 0xd0ce46c0UL, 0x00000001UL,       // x^70656 mod p(x)` << 1, x^70720 mod p(x)` << 1
+      0x2d01470eUL, 0x00000000UL, 0x24c907b4UL, 0x00000001UL,       // x^69632 mod p(x)` << 1, x^69696 mod p(x)` << 1
+      0x58bbc7b0UL, 0x00000001UL, 0x18a555caUL, 0x00000000UL,       // x^68608 mod p(x)` << 1, x^68672 mod p(x)` << 1
+      0xc0a23e8eUL, 0x00000000UL, 0x6b0980bcUL, 0x00000000UL,       // x^67584 mod p(x)` << 1, x^67648 mod p(x)` << 1
+      0xebd85c88UL, 0x00000001UL, 0x8bbba964UL, 0x00000000UL,       // x^66560 mod p(x)` << 1, x^66624 mod p(x)` << 1
+      0x9ee20bb2UL, 0x00000001UL, 0x070a5a1eUL, 0x00000001UL,       // x^65536 mod p(x)` << 1, x^65600 mod p(x)` << 1
+      0xacabf2d6UL, 0x00000001UL, 0x2204322aUL, 0x00000000UL,       // x^64512 mod p(x)` << 1, x^64576 mod p(x)` << 1
+      0xb7963d56UL, 0x00000001UL, 0xa27524d0UL, 0x00000000UL,       // x^63488 mod p(x)` << 1, x^63552 mod p(x)` << 1
+      0x7bffa1feUL, 0x00000001UL, 0x20b1e4baUL, 0x00000000UL,       // x^62464 mod p(x)` << 1, x^62528 mod p(x)` << 1
+      0x1f15333eUL, 0x00000000UL, 0x32cc27fcUL, 0x00000000UL,       // x^61440 mod p(x)` << 1, x^61504 mod p(x)` << 1
+      0x8593129eUL, 0x00000001UL, 0x44dd22b8UL, 0x00000000UL,       // x^60416 mod p(x)` << 1, x^60480 mod p(x)` << 1
+      0x9cb32602UL, 0x00000001UL, 0xdffc9e0aUL, 0x00000000UL,       // x^59392 mod p(x)` << 1, x^59456 mod p(x)` << 1
+      0x42b05cc8UL, 0x00000001UL, 0xb7a0ed14UL, 0x00000001UL,       // x^58368 mod p(x)` << 1, x^58432 mod p(x)` << 1
+      0xbe49e7a4UL, 0x00000001UL, 0xc7842488UL, 0x00000000UL,       // x^57344 mod p(x)` << 1, x^57408 mod p(x)` << 1
+      0x08f69d6cUL, 0x00000001UL, 0xc02a4feeUL, 0x00000001UL,       // x^56320 mod p(x)` << 1, x^56384 mod p(x)` << 1
+      0x6c0971f0UL, 0x00000000UL, 0x3c273778UL, 0x00000000UL,       // x^55296 mod p(x)` << 1, x^55360 mod p(x)` << 1
+      0x5b16467aUL, 0x00000000UL, 0xd63f8894UL, 0x00000001UL,       // x^54272 mod p(x)` << 1, x^54336 mod p(x)` << 1
+      0x551a628eUL, 0x00000001UL, 0x6be557d6UL, 0x00000000UL,       // x^53248 mod p(x)` << 1, x^53312 mod p(x)` << 1
+      0x9e42ea92UL, 0x00000001UL, 0x6a7806eaUL, 0x00000000UL,       // x^52224 mod p(x)` << 1, x^52288 mod p(x)` << 1
+      0x2fa83ff2UL, 0x00000001UL, 0x6155aa0cUL, 0x00000001UL,       // x^51200 mod p(x)` << 1, x^51264 mod p(x)` << 1
+      0x1ca9cde0UL, 0x00000001UL, 0x908650acUL, 0x00000000UL,       // x^50176 mod p(x)` << 1, x^50240 mod p(x)` << 1
+      0xc8e5cd74UL, 0x00000000UL, 0xaa5a8084UL, 0x00000000UL,       // x^49152 mod p(x)` << 1, x^49216 mod p(x)` << 1
+      0x96c27f0cUL, 0x00000000UL, 0x91bb500aUL, 0x00000001UL,       // x^48128 mod p(x)` << 1, x^48192 mod p(x)` << 1
+      0x2baed926UL, 0x00000000UL, 0x64e9bed0UL, 0x00000000UL,       // x^47104 mod p(x)` << 1, x^47168 mod p(x)` << 1
+      0x7c8de8d2UL, 0x00000001UL, 0x9444f302UL, 0x00000000UL,       // x^46080 mod p(x)` << 1, x^46144 mod p(x)` << 1
+      0xd43d6068UL, 0x00000000UL, 0x9db07d3cUL, 0x00000001UL,       // x^45056 mod p(x)` << 1, x^45120 mod p(x)` << 1
+      0xcb2c4b26UL, 0x00000000UL, 0x359e3e6eUL, 0x00000001UL,       // x^44032 mod p(x)` << 1, x^44096 mod p(x)` << 1
+      0x45b8da26UL, 0x00000001UL, 0xe4f10dd2UL, 0x00000001UL,       // x^43008 mod p(x)` << 1, x^43072 mod p(x)` << 1
+      0x8fff4b08UL, 0x00000001UL, 0x24f5735eUL, 0x00000001UL,       // x^41984 mod p(x)` << 1, x^42048 mod p(x)` << 1
+      0x50b58ed0UL, 0x00000001UL, 0x24760a4cUL, 0x00000001UL,       // x^40960 mod p(x)` << 1, x^41024 mod p(x)` << 1
+      0x549f39bcUL, 0x00000001UL, 0x0f1fc186UL, 0x00000000UL,       // x^39936 mod p(x)` << 1, x^40000 mod p(x)` << 1
+      0xef4d2f42UL, 0x00000000UL, 0x150e4cc4UL, 0x00000000UL,       // x^38912 mod p(x)` << 1, x^38976 mod p(x)` << 1
+      0xb1468572UL, 0x00000001UL, 0x2a6204e8UL, 0x00000000UL,       // x^37888 mod p(x)` << 1, x^37952 mod p(x)` << 1
+      0x3d7403b2UL, 0x00000001UL, 0xbeb1d432UL, 0x00000000UL,       // x^36864 mod p(x)` << 1, x^36928 mod p(x)` << 1
+      0xa4681842UL, 0x00000001UL, 0x35f3f1f0UL, 0x00000001UL,       // x^35840 mod p(x)` << 1, x^35904 mod p(x)` << 1
+      0x67714492UL, 0x00000001UL, 0x74fe2232UL, 0x00000000UL,       // x^34816 mod p(x)` << 1, x^34880 mod p(x)` << 1
+      0xe599099aUL, 0x00000001UL, 0x1ac6e2baUL, 0x00000000UL,       // x^33792 mod p(x)` << 1, x^33856 mod p(x)` << 1
+      0xfe128194UL, 0x00000000UL, 0x13fca91eUL, 0x00000000UL,       // x^32768 mod p(x)` << 1, x^32832 mod p(x)` << 1
+      0x77e8b990UL, 0x00000000UL, 0x83f4931eUL, 0x00000001UL,       // x^31744 mod p(x)` << 1, x^31808 mod p(x)` << 1
+      0xa267f63aUL, 0x00000001UL, 0xb6d9b4e4UL, 0x00000000UL,       // x^30720 mod p(x)` << 1, x^30784 mod p(x)` << 1
+      0x945c245aUL, 0x00000001UL, 0xb5188656UL, 0x00000000UL,       // x^29696 mod p(x)` << 1, x^29760 mod p(x)` << 1
+      0x49002e76UL, 0x00000001UL, 0x27a81a84UL, 0x00000000UL,       // x^28672 mod p(x)` << 1, x^28736 mod p(x)` << 1
+      0xbb8310a4UL, 0x00000001UL, 0x25699258UL, 0x00000001UL,       // x^27648 mod p(x)` << 1, x^27712 mod p(x)` << 1
+      0x9ec60bccUL, 0x00000001UL, 0xb23de796UL, 0x00000001UL,       // x^26624 mod p(x)` << 1, x^26688 mod p(x)` << 1
+      0x2d8590aeUL, 0x00000001UL, 0xfe4365dcUL, 0x00000000UL,       // x^25600 mod p(x)` << 1, x^25664 mod p(x)` << 1
+      0x65b00684UL, 0x00000000UL, 0xc68f497aUL, 0x00000000UL,       // x^24576 mod p(x)` << 1, x^24640 mod p(x)` << 1
+      0x5e5aeadcUL, 0x00000001UL, 0xfbf521eeUL, 0x00000000UL,       // x^23552 mod p(x)` << 1, x^23616 mod p(x)` << 1
+      0xb77ff2b0UL, 0x00000000UL, 0x5eac3378UL, 0x00000001UL,       // x^22528 mod p(x)` << 1, x^22592 mod p(x)` << 1
+      0x88da2ff6UL, 0x00000001UL, 0x34914b90UL, 0x00000001UL,       // x^21504 mod p(x)` << 1, x^21568 mod p(x)` << 1
+      0x63da929aUL, 0x00000000UL, 0x16335cfeUL, 0x00000000UL,       // x^20480 mod p(x)` << 1, x^20544 mod p(x)` << 1
+      0x389caa80UL, 0x00000001UL, 0x0372d10cUL, 0x00000001UL,       // x^19456 mod p(x)` << 1, x^19520 mod p(x)` << 1
+      0x3db599d2UL, 0x00000001UL, 0x5097b908UL, 0x00000001UL,       // x^18432 mod p(x)` << 1, x^18496 mod p(x)` << 1
+      0x22505a86UL, 0x00000001UL, 0x227a7572UL, 0x00000001UL,       // x^17408 mod p(x)` << 1, x^17472 mod p(x)` << 1
+      0x6bd72746UL, 0x00000001UL, 0x9a8f75c0UL, 0x00000000UL,       // x^16384 mod p(x)` << 1, x^16448 mod p(x)` << 1
+      0xc3faf1d4UL, 0x00000001UL, 0x682c77a2UL, 0x00000000UL,       // x^15360 mod p(x)` << 1, x^15424 mod p(x)` << 1
+      0x111c826cUL, 0x00000001UL, 0x231f091cUL, 0x00000000UL,       // x^14336 mod p(x)` << 1, x^14400 mod p(x)` << 1
+      0x153e9fb2UL, 0x00000000UL, 0x7d4439f2UL, 0x00000000UL,       // x^13312 mod p(x)` << 1, x^13376 mod p(x)` << 1
+      0x2b1f7b60UL, 0x00000000UL, 0x7e221efcUL, 0x00000001UL,       // x^12288 mod p(x)` << 1, x^12352 mod p(x)` << 1
+      0xb1dba570UL, 0x00000000UL, 0x67457c38UL, 0x00000001UL,       // x^11264 mod p(x)` << 1, x^11328 mod p(x)` << 1
+      0xf6397b76UL, 0x00000001UL, 0xbdf081c4UL, 0x00000000UL,       // x^10240 mod p(x)` << 1, x^10304 mod p(x)` << 1
+      0x56335214UL, 0x00000001UL, 0x6286d6b0UL, 0x00000001UL,       // x^9216 mod p(x)` << 1, x^9280 mod p(x)` << 1
+      0xd70e3986UL, 0x00000001UL, 0xc84f001cUL, 0x00000000UL,       // x^8192 mod p(x)` << 1, x^8256 mod p(x)` << 1
+      0x3701a774UL, 0x00000000UL, 0x64efe7c0UL, 0x00000000UL,       // x^7168 mod p(x)` << 1, x^7232 mod p(x)` << 1
+      0xac81ef72UL, 0x00000000UL, 0x0ac2d904UL, 0x00000000UL,       // x^6144 mod p(x)` << 1, x^6208 mod p(x)` << 1
+      0x33212464UL, 0x00000001UL, 0xfd226d14UL, 0x00000000UL,       // x^5120 mod p(x)` << 1, x^5184 mod p(x)` << 1
+      0xe4e45610UL, 0x00000000UL, 0x1cfd42e0UL, 0x00000001UL,       // x^4096 mod p(x)` << 1, x^4160 mod p(x)` << 1
+      0x0c1bd370UL, 0x00000000UL, 0x6e5a5678UL, 0x00000001UL,       // x^3072 mod p(x)` << 1, x^3136 mod p(x)` << 1
+      0xa7b9e7a6UL, 0x00000001UL, 0xd888fe22UL, 0x00000001UL,       // x^2048 mod p(x)` << 1, x^2112 mod p(x)` << 1
+      0x7d657a10UL, 0x00000000UL, 0xaf77fcd4UL, 0x00000001UL,       // x^1024 mod p(x)` << 1, x^1088 mod p(x)` << 1
+
+      // Reduce final 1024-2048 bits to 64 bits, shifting 32 bits to include the trailing 32 bits of zeros
+      0xec447f11UL, 0x99168a18UL, 0x13e8221eUL, 0xed837b26UL,       // x^2048 mod p(x)`, x^2016 mod p(x)`, x^1984 mod p(x)`, x^1952 mod p(x)`
+      0x8fd2cd3cUL, 0xe23e954eUL, 0x47b9ce5aUL, 0xc8acdd81UL,       // x^1920 mod p(x)`, x^1888 mod p(x)`, x^1856 mod p(x)`, x^1824 mod p(x)`
+      0x6b1d2b53UL, 0x92f8befeUL, 0xd4277e25UL, 0xd9ad6d87UL,       // x^1792 mod p(x)`, x^1760 mod p(x)`, x^1728 mod p(x)`, x^1696 mod p(x)`
+      0x291ea462UL, 0xf38a3556UL, 0x33fbca3bUL, 0xc10ec5e0UL,       // x^1664 mod p(x)`, x^1632 mod p(x)`, x^1600 mod p(x)`, x^1568 mod p(x)`
+      0x62b6ca4bUL, 0x974ac562UL, 0x82e02e2fUL, 0xc0b55b0eUL,       // x^1536 mod p(x)`, x^1504 mod p(x)`, x^1472 mod p(x)`, x^1440 mod p(x)`
+      0x784d2a56UL, 0x855712b3UL, 0xe172334dUL, 0x71aa1df0UL,       // x^1408 mod p(x)`, x^1376 mod p(x)`, x^1344 mod p(x)`, x^1312 mod p(x)`
+      0x0eaee722UL, 0xa5abe9f8UL, 0x3969324dUL, 0xfee3053eUL,       // x^1280 mod p(x)`, x^1248 mod p(x)`, x^1216 mod p(x)`, x^1184 mod p(x)`
+      0xdb54814cUL, 0x1fa0943dUL, 0x3eb2bd08UL, 0xf44779b9UL,       // x^1152 mod p(x)`, x^1120 mod p(x)`, x^1088 mod p(x)`, x^1056 mod p(x)`
+      0xd7bbfe6aUL, 0xa53ff440UL, 0x00cc3374UL, 0xf5449b3fUL,       // x^1024 mod p(x)`, x^992 mod p(x)`,  x^960 mod p(x)`,  x^928 mod p(x)`
+      0x6325605cUL, 0xebe7e356UL, 0xd777606eUL, 0x6f8346e1UL,       // x^896 mod p(x)`,  x^864 mod p(x)`,  x^832 mod p(x)`,  x^800 mod p(x)`
+      0xe5b592b8UL, 0xc65a272cUL, 0xc0b95347UL, 0xe3ab4f2aUL,       // x^768 mod p(x)`,  x^736 mod p(x)`,  x^704 mod p(x)`,  x^672 mod p(x)`
+      0x4721589fUL, 0x5705a9caUL, 0x329ecc11UL, 0xaa2215eaUL,       // x^640 mod p(x)`,  x^608 mod p(x)`,  x^576 mod p(x)`,  x^544 mod p(x)`
+      0x88d14467UL, 0xe3720acbUL, 0xd95efd26UL, 0x1ed8f66eUL,       // x^512 mod p(x)`,  x^480 mod p(x)`,  x^448 mod p(x)`,  x^416 mod p(x)`
+      0x15141c31UL, 0xba1aca03UL, 0xa700e96aUL, 0x78ed02d5UL,       // x^384 mod p(x)`,  x^352 mod p(x)`,  x^320 mod p(x)`,  x^288 mod p(x)`
+      0xed627daeUL, 0xad2a31b3UL, 0x32b39da3UL, 0xba8ccbe8UL,       // x^256 mod p(x)`,  x^224 mod p(x)`,  x^192 mod p(x)`,  x^160 mod p(x)`
+      0xa06a2517UL, 0x6655004fUL, 0xb1e6b092UL, 0xedb88320UL        // x^128 mod p(x)`,  x^96 mod p(x)`,   x^64 mod p(x)`,   x^32 mod p(x)`
+  };
+
+  juint* ptr = (juint*) malloc(sizeof(juint) * CRC32_CONSTANTS_SIZE);
+  guarantee(((intptr_t)ptr & 0xF) == 0, "16-byte alignment needed");
+  guarantee(ptr != NULL, "allocation error of a crc table");
+  memcpy((void*)ptr, constants, sizeof(juint) * CRC32_CONSTANTS_SIZE);
+  return ptr;
+}
+
+juint* StubRoutines::ppc64::generate_crc_barret_constants() {
+  juint barret_constants[CRC32_BARRET_CONSTANTS] = {
+      0xf7011641UL, 0x00000001UL, 0x00000000UL, 0x00000000UL,
+      0xdb710641UL, 0x00000001UL, 0x00000000UL, 0x00000000UL
+  };
+  juint* ptr = (juint*) malloc(sizeof(juint) * CRC32_CONSTANTS_SIZE);
+  guarantee(((intptr_t)ptr & 0xF) == 0, "16-byte alignment needed");
+  guarantee(ptr != NULL, "allocation error of a crc table");
+  memcpy((void*) ptr, barret_constants, sizeof(juint) * CRC32_BARRET_CONSTANTS);
+  return ptr;
+}
+
+// CRC32 Intrinsics.
+/**
+ *  crc_table[] from jdk/src/share/native/java/util/zip/zlib-1.2.8/crc32.h
+ */
+juint StubRoutines::ppc64::_crc_table[CRC32_TABLES][CRC32_COLUMN_SIZE] = {
+  {
+    0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
+    0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
+    0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
+    0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
+    0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
+    0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
+    0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
+    0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
+    0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
+    0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
+    0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
+    0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
+    0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
+    0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
+    0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
+    0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
+    0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
+    0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
+    0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
+    0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
+    0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
+    0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
+    0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
+    0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
+    0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
+    0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
+    0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
+    0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
+    0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
+    0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
+    0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
+    0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
+    0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
+    0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
+    0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
+    0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
+    0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
+    0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
+    0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
+    0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
+    0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
+    0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
+    0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
+    0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
+    0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
+    0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
+    0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
+    0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
+    0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
+    0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
+    0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
+    0x2d02ef8dUL
+#ifdef  CRC32_BYFOUR
+  },
+  {
+    0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
+    0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
+    0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
+    0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
+    0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
+    0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
+    0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
+    0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
+    0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
+    0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
+    0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
+    0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
+    0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
+    0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
+    0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
+    0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
+    0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
+    0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
+    0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
+    0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
+    0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
+    0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
+    0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
+    0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
+    0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
+    0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
+    0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
+    0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
+    0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
+    0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
+    0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
+    0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
+    0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
+    0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
+    0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
+    0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
+    0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
+    0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
+    0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
+    0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
+    0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
+    0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
+    0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
+    0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
+    0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
+    0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
+    0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
+    0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
+    0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
+    0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
+    0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
+    0x9324fd72UL
+  },
+  {
+    0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
+    0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
+    0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
+    0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
+    0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
+    0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
+    0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
+    0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
+    0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
+    0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
+    0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
+    0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
+    0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
+    0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
+    0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
+    0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
+    0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
+    0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
+    0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
+    0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
+    0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
+    0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
+    0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
+    0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
+    0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
+    0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
+    0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
+    0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
+    0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
+    0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
+    0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
+    0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
+    0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
+    0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
+    0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
+    0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
+    0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
+    0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
+    0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
+    0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
+    0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
+    0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
+    0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
+    0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
+    0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
+    0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
+    0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
+    0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
+    0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
+    0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
+    0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
+    0xbe9834edUL
+  },
+  {
+    0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
+    0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
+    0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
+    0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
+    0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
+    0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
+    0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
+    0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
+    0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
+    0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
+    0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
+    0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
+    0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
+    0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
+    0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
+    0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
+    0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
+    0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
+    0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
+    0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
+    0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
+    0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
+    0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
+    0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
+    0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
+    0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
+    0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
+    0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
+    0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
+    0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
+    0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
+    0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
+    0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
+    0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
+    0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
+    0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
+    0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
+    0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
+    0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
+    0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
+    0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
+    0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
+    0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
+    0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
+    0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
+    0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
+    0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
+    0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
+    0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
+    0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
+    0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
+    0xde0506f1UL
+  },
+  {
+    0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
+    0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
+    0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
+    0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
+    0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
+    0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
+    0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
+    0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
+    0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
+    0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
+    0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
+    0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
+    0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
+    0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
+    0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
+    0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
+    0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
+    0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
+    0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
+    0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
+    0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
+    0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
+    0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
+    0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
+    0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
+    0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
+    0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
+    0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
+    0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
+    0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
+    0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
+    0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
+    0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
+    0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
+    0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
+    0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
+    0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
+    0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
+    0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
+    0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
+    0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
+    0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
+    0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
+    0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
+    0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
+    0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
+    0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
+    0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
+    0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
+    0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
+    0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
+    0x8def022dUL
+  },
+  {
+    0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
+    0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
+    0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
+    0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
+    0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
+    0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
+    0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
+    0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
+    0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
+    0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
+    0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
+    0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
+    0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
+    0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
+    0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
+    0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
+    0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
+    0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
+    0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
+    0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
+    0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
+    0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
+    0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
+    0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
+    0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
+    0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
+    0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
+    0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
+    0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
+    0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
+    0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
+    0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
+    0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
+    0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
+    0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
+    0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
+    0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
+    0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
+    0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
+    0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
+    0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
+    0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
+    0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
+    0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
+    0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
+    0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
+    0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
+    0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
+    0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
+    0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
+    0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
+    0x72fd2493UL
+  },
+  {
+    0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
+    0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
+    0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
+    0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
+    0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
+    0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
+    0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
+    0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
+    0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
+    0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
+    0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
+    0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
+    0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
+    0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
+    0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
+    0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
+    0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
+    0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
+    0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
+    0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
+    0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
+    0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
+    0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
+    0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
+    0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
+    0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
+    0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
+    0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
+    0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
+    0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
+    0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
+    0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
+    0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
+    0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
+    0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
+    0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
+    0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
+    0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
+    0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
+    0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
+    0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
+    0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
+    0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
+    0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
+    0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
+    0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
+    0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
+    0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
+    0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
+    0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
+    0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
+    0xed3498beUL
+  },
+  {
+    0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
+    0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
+    0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
+    0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
+    0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
+    0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
+    0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
+    0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
+    0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
+    0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
+    0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
+    0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
+    0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
+    0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
+    0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
+    0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
+    0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
+    0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
+    0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
+    0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
+    0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
+    0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
+    0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
+    0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
+    0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
+    0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
+    0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
+    0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
+    0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
+    0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
+    0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
+    0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
+    0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
+    0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
+    0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
+    0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
+    0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
+    0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
+    0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
+    0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
+    0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
+    0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
+    0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
+    0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
+    0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
+    0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
+    0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
+    0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
+    0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
+    0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
+    0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
+    0xf10605deUL
+#endif
+  }
+};
+
+juint* StubRoutines::ppc64::_constants = StubRoutines::ppc64::generate_crc_constants();
+
+juint* StubRoutines::ppc64::_barret_constants = StubRoutines::ppc64::generate_crc_barret_constants();
diff --git a/src/cpu/ppc/vm/stubRoutines_ppc_64.hpp b/src/cpu/ppc/vm/stubRoutines_ppc_64.hpp
index d33a346..3655c1f 100644
--- a/src/cpu/ppc/vm/stubRoutines_ppc_64.hpp
+++ b/src/cpu/ppc/vm/stubRoutines_ppc_64.hpp
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
- * Copyright 2012, 2013 SAP AG. All rights reserved.
+ * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018 SAP SE. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -30,11 +30,43 @@
 // definition. See stubRoutines.hpp for a description on how to
 // extend it.
 
-static bool    returns_to_call_stub(address return_pc)   { return return_pc == _call_stub_return_address; }
+static bool returns_to_call_stub(address return_pc) { return return_pc == _call_stub_return_address; }
 
 enum platform_dependent_constants {
   code_size1 = 20000,          // simply increase if too small (assembler will crash if too small)
   code_size2 = 20000           // simply increase if too small (assembler will crash if too small)
 };
 
+// CRC32 Intrinsics.
+#define CRC32_COLUMN_SIZE 256
+#define CRC32_BYFOUR
+#ifdef  CRC32_BYFOUR
+  #define CRC32_TABLES 8
+#else
+  #define CRC32_TABLES 1
+#endif
+#define CRC32_CONSTANTS_SIZE 1084
+#define CRC32_BARRET_CONSTANTS 10
+
+class ppc64 {
+ friend class StubGenerator;
+
+ private:
+
+  // CRC32 Intrinsics.
+  static juint _crc_table[CRC32_TABLES][CRC32_COLUMN_SIZE];
+  static juint* _constants;
+  static juint* _barret_constants;
+
+ public:
+
+  // CRC32 Intrinsics.
+  static void generate_load_crc_table_addr(MacroAssembler* masm, Register table);
+  static void generate_load_crc_constants_addr(MacroAssembler* masm, Register table);
+  static void generate_load_crc_barret_constants_addr(MacroAssembler* masm, Register table);
+  static juint* generate_crc_constants();
+  static juint* generate_crc_barret_constants();
+
+};
+
 #endif // CPU_PPC_VM_STUBROUTINES_PPC_64_HPP
diff --git a/src/cpu/ppc/vm/templateInterpreter_ppc.cpp b/src/cpu/ppc/vm/templateInterpreter_ppc.cpp
index de148ae..42dd8f2 100644
--- a/src/cpu/ppc/vm/templateInterpreter_ppc.cpp
+++ b/src/cpu/ppc/vm/templateInterpreter_ppc.cpp
@@ -57,7 +57,7 @@
 #define BLOCK_COMMENT(str) __ block_comment(str)
 #endif
 
-#define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
+#define BIND(label)        __ bind(label); BLOCK_COMMENT(#label ":")
 
 //-----------------------------------------------------------------------------
 
@@ -265,7 +265,7 @@
       __ cmpdi(CCR0, Rmdo, 0);
       __ beq(CCR0, no_mdo);
 
-      // Increment backedge counter in the MDO.
+      // Increment invocation counter in the MDO.
       const int mdo_bc_offs = in_bytes(MethodData::backedge_counter_offset()) + in_bytes(InvocationCounter::counter_offset());
       __ lwz(Rscratch2, mdo_bc_offs, Rmdo);
       __ addi(Rscratch2, Rscratch2, increment);
@@ -277,12 +277,12 @@
     }
 
     // Increment counter in MethodCounters*.
-    const int mo_bc_offs = in_bytes(MethodCounters::backedge_counter_offset()) + in_bytes(InvocationCounter::counter_offset());
+    const int mo_ic_offs = in_bytes(MethodCounters::invocation_counter_offset()) + in_bytes(InvocationCounter::counter_offset());
     __ bind(no_mdo);
     __ get_method_counters(R19_method, R3_counters, done);
-    __ lwz(Rscratch2, mo_bc_offs, R3_counters);
+    __ lwz(Rscratch2, mo_ic_offs, R3_counters);
     __ addi(Rscratch2, Rscratch2, increment);
-    __ stw(Rscratch2, mo_bc_offs, R3_counters);
+    __ stw(Rscratch2, mo_ic_offs, R3_counters);
     __ load_const_optimized(Rscratch1, mask, R0);
     __ and_(Rscratch1, Rscratch2, Rscratch1);
     __ beq(CCR0, *overflow);
@@ -783,7 +783,7 @@
     }
     generate_counter_incr(&invocation_counter_overflow, NULL, NULL);
 
-    __ BIND(continue_after_compile);
+    BIND(continue_after_compile);
     // Reset the _do_not_unlock_if_synchronized flag.
     if (synchronized) {
       __ li(R0, 0);
@@ -843,7 +843,7 @@
   __ ld(signature_handler_fd, method_(signature_handler));
   __ twi_0(signature_handler_fd); // Order wrt. load of klass mirror and entry point (isync is below).
 
-  __ BIND(call_signature_handler);
+  BIND(call_signature_handler);
 
   // Before we call the signature handler we push a new frame to
   // protect the interpreter frame volatile registers when we return
@@ -913,7 +913,7 @@
     __ std(R0/*mirror*/, _ijava_state_neg(oop_tmp), R11_scratch1);
     // R4_ARG2 = &state->_oop_temp;
     __ addi(R4_ARG2, R11_scratch1, _ijava_state_neg(oop_tmp));
-    __ BIND(method_is_not_static);
+    BIND(method_is_not_static);
   }
 
   // At this point, arguments have been copied off the stack into
@@ -1126,14 +1126,14 @@
   // interpreter will do the correct thing. If it isn't interpreted
   // (call stub/compiled code) we will change our return and continue.
 
-  __ BIND(exception_return_sync_check);
+  BIND(exception_return_sync_check);
 
   if (synchronized) {
     // Don't check for exceptions since we're still in the i2n frame. Do that
     // manually afterwards.
     unlock_method(false);
   }
-  __ BIND(exception_return_sync_check_already_unlocked);
+  BIND(exception_return_sync_check_already_unlocked);
 
   const Register return_pc = R31;
 
@@ -1327,6 +1327,12 @@
   case Interpreter::java_lang_math_exp     : entry_point = ((InterpreterGenerator*) this)->generate_math_entry(kind);    break;
   case Interpreter::java_lang_ref_reference_get
                                            : entry_point = ((InterpreterGenerator*)this)->generate_Reference_get_entry(); break;
+  case Interpreter::java_util_zip_CRC32_update
+                                           : entry_point = ((InterpreterGenerator*)this)->generate_CRC32_update_entry(); break;
+  case Interpreter::java_util_zip_CRC32_updateBytes
+                                           : // fall thru
+  case Interpreter::java_util_zip_CRC32_updateByteBuffer
+                                           : entry_point = ((InterpreterGenerator*)this)->generate_CRC32_updateBytes_entry(kind); break;
   default                                  : ShouldNotReachHere();                                                       break;
   }
 
@@ -1337,6 +1343,179 @@
   return ((InterpreterGenerator*) this)->generate_normal_entry(synchronized);
 }
 
+// CRC32 Intrinsics.
+//
+// Contract on scratch and work registers.
+// =======================================
+//
+// On ppc, the register set {R2..R12} is available in the interpreter as scratch/work registers.
+// You should, however, keep in mind that {R3_ARG1..R10_ARG8} is the C-ABI argument register set.
+// You can't rely on these registers across calls.
+//
+// The generators for CRC32_update and for CRC32_updateBytes use the
+// scratch/work register set internally, passing the work registers
+// as arguments to the MacroAssembler emitters as required.
+//
+// R3_ARG1..R6_ARG4 are preset to hold the incoming java arguments.
+// Their contents is not constant but may change according to the requirements
+// of the emitted code.
+//
+// All other registers from the scratch/work register set are used "internally"
+// and contain garbage (i.e. unpredictable values) once blr() is reached.
+// Basically, only R3_RET contains a defined value which is the function result.
+//
+/**
+ * Method entry for static native methods:
+ *   int java.util.zip.CRC32.update(int crc, int b)
+ */
+address InterpreterGenerator::generate_CRC32_update_entry() {
+  address start = __ pc();  // Remember stub start address (is rtn value).
+
+  if (UseCRC32Intrinsics) {
+    Label slow_path;
+
+    // Safepoint check
+    const Register sync_state = R11_scratch1;
+    int sync_state_offs = __ load_const_optimized(sync_state, SafepointSynchronize::address_of_state(), /*temp*/R0, true);
+    __ lwz(sync_state, sync_state_offs, sync_state);
+    __ cmpwi(CCR0, sync_state, SafepointSynchronize::_not_synchronized);
+    __ bne(CCR0, slow_path);
+
+    // We don't generate local frame and don't align stack because
+    // we not even call stub code (we generate the code inline)
+    // and there is no safepoint on this path.
+
+    // Load java parameters.
+    // R15_esp is callers operand stack pointer, i.e. it points to the parameters.
+    const Register argP    = R15_esp;
+    const Register crc     = R3_ARG1;  // crc value
+    const Register data    = R4_ARG2;  // address of java byte value (kernel_crc32 needs address)
+    const Register dataLen = R5_ARG3;  // source data len (1 byte). Not used because calling the single-byte emitter.
+    const Register table   = R6_ARG4;  // address of crc32 table
+    const Register tmp     = dataLen;  // Reuse unused len register to show we don't actually need a separate tmp here.
+
+    BLOCK_COMMENT("CRC32_update {");
+
+    // Arguments are reversed on java expression stack
+#ifdef VM_LITTLE_ENDIAN
+    __ addi(data, argP, 0+1*wordSize); // (stack) address of byte value. Emitter expects address, not value.
+                                       // Being passed as an int, the single byte is at offset +0.
+#else
+    __ addi(data, argP, 3+1*wordSize); // (stack) address of byte value. Emitter expects address, not value.
+                                       // Being passed from java as an int, the single byte is at offset +3.
+#endif
+    __ lwz(crc,  2*wordSize, argP);    // Current crc state, zero extend to 64 bit to have a clean register.
+
+    StubRoutines::ppc64::generate_load_crc_table_addr(_masm, table);
+    __ kernel_crc32_singleByte(crc, data, dataLen, table, tmp);
+
+    // Restore caller sp for c2i case and return.
+    __ mr(R1_SP, R21_sender_SP); // Cut the stack back to where the caller started.
+    __ blr();
+
+    // Generate a vanilla native entry as the slow path.
+    BLOCK_COMMENT("} CRC32_update");
+    BIND(slow_path);
+  }
+
+  (void) generate_native_entry(false);
+
+  return start;
+}
+
+// CRC32 Intrinsics.
+/**
+ * Method entry for static native methods:
+ *   int java.util.zip.CRC32.updateBytes(     int crc, byte[] b,  int off, int len)
+ *   int java.util.zip.CRC32.updateByteBuffer(int crc, long* buf, int off, int len)
+ */
+address InterpreterGenerator::generate_CRC32_updateBytes_entry(AbstractInterpreter::MethodKind kind) {
+  address start = __ pc();  // Remember stub start address (is rtn value).
+
+  if (UseCRC32Intrinsics) {
+    Label slow_path;
+
+    // Safepoint check
+    const Register sync_state = R11_scratch1;
+    int sync_state_offs = __ load_const_optimized(sync_state, SafepointSynchronize::address_of_state(), /*temp*/R0, true);
+    __ lwz(sync_state, sync_state_offs, sync_state);
+    __ cmpwi(CCR0, sync_state, SafepointSynchronize::_not_synchronized);
+    __ bne(CCR0, slow_path);
+
+    // We don't generate local frame and don't align stack because
+    // we not even call stub code (we generate the code inline)
+    // and there is no safepoint on this path.
+
+    // Load parameters.
+    // Z_esp is callers operand stack pointer, i.e. it points to the parameters.
+    const Register argP    = R15_esp;
+    const Register crc     = R3_ARG1;  // crc value
+    const Register data    = R4_ARG2;  // address of java byte array
+    const Register dataLen = R5_ARG3;  // source data len
+    const Register table   = R6_ARG4;  // address of crc32 table
+
+    const Register t0      = R9;       // scratch registers for crc calculation
+    const Register t1      = R10;
+    const Register t2      = R11;
+    const Register t3      = R12;
+
+    const Register tc0     = R2;       // registers to hold pre-calculated column addresses
+    const Register tc1     = R7;
+    const Register tc2     = R8;
+    const Register tc3     = table;    // table address is reconstructed at the end of kernel_crc32_* emitters
+
+    const Register tmp     = t0;       // Only used very locally to calculate byte buffer address.
+
+    // Arguments are reversed on java expression stack.
+    // Calculate address of start element.
+    if (kind == Interpreter::java_util_zip_CRC32_updateByteBuffer) { // Used for "updateByteBuffer direct".
+      BLOCK_COMMENT("CRC32_updateByteBuffer {");
+      // crc     @ (SP + 5W) (32bit)
+      // buf     @ (SP + 3W) (64bit ptr to long array)
+      // off     @ (SP + 2W) (32bit)
+      // dataLen @ (SP + 1W) (32bit)
+      // data = buf + off
+      __ ld(  data,    3*wordSize, argP);  // start of byte buffer
+      __ lwa( tmp,     2*wordSize, argP);  // byte buffer offset
+      __ lwa( dataLen, 1*wordSize, argP);  // #bytes to process
+      __ lwz( crc,     5*wordSize, argP);  // current crc state
+      __ add( data, data, tmp);            // Add byte buffer offset.
+    } else {                                                         // Used for "updateBytes update".
+      BLOCK_COMMENT("CRC32_updateBytes {");
+      // crc     @ (SP + 4W) (32bit)
+      // buf     @ (SP + 3W) (64bit ptr to byte array)
+      // off     @ (SP + 2W) (32bit)
+      // dataLen @ (SP + 1W) (32bit)
+      // data = buf + off + base_offset
+      __ ld(  data,    3*wordSize, argP);  // start of byte buffer
+      __ lwa( tmp,     2*wordSize, argP);  // byte buffer offset
+      __ lwa( dataLen, 1*wordSize, argP);  // #bytes to process
+      __ add( data, data, tmp);            // add byte buffer offset
+      __ lwz( crc,     4*wordSize, argP);  // current crc state
+      __ addi(data, data, arrayOopDesc::base_offset_in_bytes(T_BYTE));
+    }
+
+    StubRoutines::ppc64::generate_load_crc_table_addr(_masm, table);
+
+    // Performance measurements show the 1word and 2word variants to be almost equivalent,
+    // with very light advantages for the 1word variant. We chose the 1word variant for
+    // code compactness.
+    __ kernel_crc32_1word(crc, data, dataLen, table, t0, t1, t2, t3, tc0, tc1, tc2, tc3);
+
+    // Restore caller sp for c2i case and return.
+    __ mr(R1_SP, R21_sender_SP); // Cut the stack back to where the caller started.
+    __ blr();
+
+    // Generate a vanilla native entry as the slow path.
+    BLOCK_COMMENT("} CRC32_updateBytes(Buffer)");
+    BIND(slow_path);
+  }
+
+  (void) generate_native_entry(false);
+
+  return start;
+}
+
 // These should never be compiled since the interpreter will prefer
 // the compiled version to the intrinsic version.
 bool AbstractInterpreter::can_be_compiled(methodHandle m) {
diff --git a/src/cpu/ppc/vm/templateTable_ppc_64.cpp b/src/cpu/ppc/vm/templateTable_ppc_64.cpp
index ee7b925..708d5b3 100644
--- a/src/cpu/ppc/vm/templateTable_ppc_64.cpp
+++ b/src/cpu/ppc/vm/templateTable_ppc_64.cpp
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- * Copyright 2013, 2014 SAP AG. All rights reserved.
+ * Copyright (c) 2014, 2017 Oracle and/or its affiliates. All rights reserved.
+ * Copyright 2013, 2017 SAP AG. 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
@@ -3418,11 +3418,11 @@
 void TemplateTable::invokeinterface_object_method(Register Rrecv_klass,
                                                   Register Rret,
                                                   Register Rflags,
-                                                  Register Rindex,
+                                                  Register Rmethod,
                                                   Register Rtemp1,
                                                   Register Rtemp2) {
 
-  assert_different_registers(Rindex, Rret, Rrecv_klass, Rflags, Rtemp1, Rtemp2);
+  assert_different_registers(Rmethod, Rret, Rrecv_klass, Rflags, Rtemp1, Rtemp2);
   Label LnotFinal;
 
   // Check for vfinal.
@@ -3434,14 +3434,14 @@
   // Final call case.
   __ profile_final_call(Rtemp1, Rscratch);
   // Argument and return type profiling.
-  __ profile_arguments_type(Rindex, Rscratch, Rrecv_klass /* scratch */, true);
+  __ profile_arguments_type(Rmethod, Rscratch, Rrecv_klass /* scratch */, true);
   // Do the final call - the index (f2) contains the method.
-  __ call_from_interpreter(Rindex, Rret, Rscratch, Rrecv_klass /* scratch */);
+  __ call_from_interpreter(Rmethod, Rret, Rscratch, Rrecv_klass /* scratch */);
 
   // Non-final callc case.
   __ bind(LnotFinal);
   __ profile_virtual_call(Rrecv_klass, Rtemp1, Rscratch, false);
-  generate_vtable_call(Rrecv_klass, Rindex, Rret, Rscratch);
+  generate_vtable_call(Rrecv_klass, Rmethod, Rret, Rscratch);
 }
 
 void TemplateTable::invokeinterface(int byte_no) {
@@ -3450,58 +3450,61 @@
 
   const Register Rscratch1        = R11_scratch1,
                  Rscratch2        = R12_scratch2,
-                 Rscratch3        = R9_ARG7,
-                 Rscratch4        = R10_ARG8,
-                 Rtable_addr      = Rscratch2,
+                 Rmethod          = R6_ARG4,
+                 Rmethod2         = R9_ARG7,
                  Rinterface_klass = R5_ARG3,
-                 Rret_type        = R8_ARG6,
-                 Rret_addr        = Rret_type,
-                 Rindex           = R6_ARG4,
-                 Rreceiver        = R4_ARG2,
-                 Rrecv_klass      = Rreceiver,
+                 Rret_addr        = R8_ARG6,
+                 Rindex           = R10_ARG8,
+                 Rreceiver        = R3_ARG1,
+                 Rrecv_klass      = R4_ARG2,
                  Rflags           = R7_ARG5;
 
-  prepare_invoke(byte_no, Rinterface_klass, Rret_addr, Rindex, Rreceiver, Rflags, Rscratch1);
+  prepare_invoke(byte_no, Rinterface_klass, Rret_addr, Rmethod, Rreceiver, Rflags, Rscratch1);
 
   // Get receiver klass.
-  __ null_check_throw(Rreceiver, oopDesc::klass_offset_in_bytes(), Rscratch3);
+  __ null_check_throw(Rreceiver, oopDesc::klass_offset_in_bytes(), Rscratch2);
   __ load_klass(Rrecv_klass, Rreceiver);
 
   // Check corner case object method.
-  Label LobjectMethod;
-
+  Label LobjectMethod, L_no_such_interface, Lthrow_ame;
   __ testbitdi(CCR0, R0, Rflags, ConstantPoolCacheEntry::is_forced_virtual_shift);
   __ btrue(CCR0, LobjectMethod);
 
-  // Fallthrough: The normal invokeinterface case.
+  __ lookup_interface_method(Rrecv_klass, Rinterface_klass, noreg, noreg, Rscratch1, Rscratch2,
+                             L_no_such_interface, /*return_method=*/false);
+
   __ profile_virtual_call(Rrecv_klass, Rscratch1, Rscratch2, false);
 
   // Find entry point to call.
-  Label Lthrow_icc, Lthrow_ame;
-  // Result will be returned in Rindex.
-  __ mr(Rscratch4, Rrecv_klass);
-  __ mr(Rscratch3, Rindex);
-  __ lookup_interface_method(Rrecv_klass, Rinterface_klass, Rindex, Rindex, Rscratch1, Rscratch2, Lthrow_icc);
 
-  __ cmpdi(CCR0, Rindex, 0);
+  // Get declaring interface class from method
+  __ ld(Rinterface_klass, in_bytes(Method::const_offset()), Rmethod);
+  __ ld(Rinterface_klass, in_bytes(ConstMethod::constants_offset()), Rinterface_klass);
+  __ ld(Rinterface_klass, ConstantPool::pool_holder_offset_in_bytes(), Rinterface_klass);
+
+  // Get itable index from method
+  __ lwa(Rindex, in_bytes(Method::itable_index_offset()), Rmethod);
+  __ subfic(Rindex, Rindex, Method::itable_index_max);
+
+  __ lookup_interface_method(Rrecv_klass, Rinterface_klass, Rindex, Rmethod2, Rscratch1, Rscratch2,
+                             L_no_such_interface);
+
+  __ cmpdi(CCR0, Rmethod2, 0);
   __ beq(CCR0, Lthrow_ame);
   // Found entry. Jump off!
   // Argument and return type profiling.
-  __ profile_arguments_type(Rindex, Rscratch1, Rscratch2, true);
-  __ call_from_interpreter(Rindex, Rret_addr, Rscratch1, Rscratch2);
+  __ profile_arguments_type(Rmethod2, Rscratch1, Rscratch2, true);
+  //__ profile_called_method(Rindex, Rscratch1);
+  __ call_from_interpreter(Rmethod2, Rret_addr, Rscratch1, Rscratch2);
 
   // Vtable entry was NULL => Throw abstract method error.
   __ bind(Lthrow_ame);
-  __ mr(Rrecv_klass, Rscratch4);
-  __ mr(Rindex, Rscratch3);
   call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_AbstractMethodError));
 
   // Interface was not found => Throw incompatible class change error.
-  __ bind(Lthrow_icc);
-  __ mr(Rrecv_klass, Rscratch4);
+  __ bind(L_no_such_interface);
   call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_IncompatibleClassChangeError));
-
-  __ should_not_reach_here();
+  DEBUG_ONLY( __ should_not_reach_here(); )
 
   // Special case of invokeinterface called for virtual method of
   // java.lang.Object. See ConstantPoolCacheEntry::set_method() for details:
@@ -3509,7 +3512,7 @@
   // to handle this corner case. This code isn't produced by javac, but could
   // be produced by another compliant java compiler.
   __ bind(LobjectMethod);
-  invokeinterface_object_method(Rrecv_klass, Rret_addr, Rflags, Rindex, Rscratch1, Rscratch2);
+  invokeinterface_object_method(Rrecv_klass, Rret_addr, Rflags, Rmethod, Rscratch1, Rscratch2);
 }
 
 void TemplateTable::invokedynamic(int byte_no) {
diff --git a/src/cpu/ppc/vm/vm_version_ppc.cpp b/src/cpu/ppc/vm/vm_version_ppc.cpp
index d8214a8..eb47bb2 100644
--- a/src/cpu/ppc/vm/vm_version_ppc.cpp
+++ b/src/cpu/ppc/vm/vm_version_ppc.cpp
@@ -102,7 +102,7 @@
   // Create and print feature-string.
   char buf[(num_features+1) * 16]; // Max 16 chars per feature.
   jio_snprintf(buf, sizeof(buf),
-               "ppc64%s%s%s%s%s%s%s%s%s",
+               "ppc64%s%s%s%s%s%s%s%s%s%s",
                (has_fsqrt()   ? " fsqrt"   : ""),
                (has_isel()    ? " isel"    : ""),
                (has_lxarxeh() ? " lxarxeh" : ""),
@@ -112,7 +112,8 @@
                (has_popcntw() ? " popcntw" : ""),
                (has_fcfids()  ? " fcfids"  : ""),
                (has_vand()    ? " vand"    : ""),
-               (has_vcipher() ? " aes"     : "")
+               (has_vcipher() ? " aes"     : ""),
+               (has_vpmsumb() ? " vpmsumb" : "")
                // Make sure number of %s matches num_features!
               );
   _features_str = strdup(buf);
@@ -150,10 +151,12 @@
 
   assert(AllocatePrefetchStyle >= 0, "AllocatePrefetchStyle should be positive");
 
-  if (UseCRC32Intrinsics) {
-    if (!FLAG_IS_DEFAULT(UseCRC32Intrinsics))
-      warning("CRC32 intrinsics  are not available on this CPU");
-    FLAG_SET_DEFAULT(UseCRC32Intrinsics, false);
+  // Implementation does not use any of the vector instructions
+  // available with Power8. Their exploitation is still pending.
+  if (!UseCRC32Intrinsics) {
+    if (FLAG_IS_DEFAULT(UseCRC32Intrinsics)) {
+      FLAG_SET_DEFAULT(UseCRC32Intrinsics, true);
+    }
   }
 
   // The AES intrinsic stubs require AES instruction support.
@@ -201,6 +204,12 @@
     FLAG_SET_DEFAULT(UseSHA512Intrinsics, false);
   }
 
+  if (FLAG_IS_DEFAULT(UseMontgomeryMultiplyIntrinsic)) {
+    UseMontgomeryMultiplyIntrinsic = true;
+  }
+  if (FLAG_IS_DEFAULT(UseMontgomerySquareIntrinsic)) {
+    UseMontgomerySquareIntrinsic = true;
+  }
 }
 
 void VM_Version::print_features() {
@@ -477,6 +486,7 @@
   a->fcfids(F3, F4);                           // code[8] -> fcfids
   a->vand(VR0, VR0, VR0);                      // code[9] -> vand
   a->vcipher(VR0, VR1, VR2);                   // code[10] -> vcipher
+  a->vpmsumb(VR0, VR1, VR2);                   // code[11] -> vpmsumb
   a->blr();
 
   // Emit function to set one cache line to zero. Emit function descriptor and get pointer to it.
@@ -521,6 +531,7 @@
   if (code[feature_cntr++]) features |= fcfids_m;
   if (code[feature_cntr++]) features |= vand_m;
   if (code[feature_cntr++]) features |= vcipher_m;
+  if (code[feature_cntr++]) features |= vpmsumb_m;
 
   // Print the detection code.
   if (PrintAssembly) {
diff --git a/src/cpu/ppc/vm/vm_version_ppc.hpp b/src/cpu/ppc/vm/vm_version_ppc.hpp
index d7839b4..55442f7 100644
--- a/src/cpu/ppc/vm/vm_version_ppc.hpp
+++ b/src/cpu/ppc/vm/vm_version_ppc.hpp
@@ -43,6 +43,7 @@
     vand,
     dcba,
     vcipher,
+    vpmsumb,
     num_features // last entry to count features
   };
   enum Feature_Flag_Set {
@@ -58,6 +59,7 @@
     vand_m                = (1 << vand   ),
     dcba_m                = (1 << dcba   ),
     vcipher_m             = (1 << vcipher),
+    vpmsumb_m             = (1 << vpmsumb),
     all_features_m        = -1
   };
   static int  _features;
@@ -86,6 +88,7 @@
   static bool has_vand()    { return (_features & vand_m) != 0; }
   static bool has_dcba()    { return (_features & dcba_m) != 0; }
   static bool has_vcipher() { return (_features & vcipher_m) != 0; }
+  static bool has_vpmsumb() { return (_features & vpmsumb_m) != 0; }
 
   static const char* cpu_features() { return _features_str; }
 
diff --git a/src/cpu/ppc/vm/vtableStubs_ppc_64.cpp b/src/cpu/ppc/vm/vtableStubs_ppc_64.cpp
index 5931afd..17c91d0 100644
--- a/src/cpu/ppc/vm/vtableStubs_ppc_64.cpp
+++ b/src/cpu/ppc/vm/vtableStubs_ppc_64.cpp
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
- * Copyright 2012, 2014 SAP AG. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright 2012, 2017 SAP AG. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -29,6 +29,7 @@
 #include "code/vtableStubs.hpp"
 #include "interp_masm_ppc_64.hpp"
 #include "memory/resourceArea.hpp"
+#include "oops/compiledICHolder.hpp"
 #include "oops/instanceKlass.hpp"
 #include "oops/klassVtable.hpp"
 #include "runtime/sharedRuntime.hpp"
@@ -56,17 +57,22 @@
   // PPC port: use fixed size.
   const int code_length = VtableStub::pd_code_size_limit(true);
   VtableStub* s = new (code_length) VtableStub(true, vtable_index);
+
+  // Can be NULL if there is no free space in the code cache.
+  if (s == NULL) {
+    return NULL;
+  }
+
   ResourceMark rm;
   CodeBuffer cb(s->entry_point(), code_length);
   MacroAssembler* masm = new MacroAssembler(&cb);
-  address start_pc;
 
 #ifndef PRODUCT
   if (CountCompiledCalls) {
-    __ load_const(R11_scratch1, SharedRuntime::nof_megamorphic_calls_addr());
-    __ lwz(R12_scratch2, 0, R11_scratch1);
+    int offs = __ load_const_optimized(R11_scratch1, SharedRuntime::nof_megamorphic_calls_addr(), R12_scratch2, true);
+    __ lwz(R12_scratch2, offs, R11_scratch1);
     __ addi(R12_scratch2, R12_scratch2, 1);
-    __ stw(R12_scratch2, 0, R11_scratch1);
+    __ stw(R12_scratch2, offs, R11_scratch1);
   }
 #endif
 
@@ -116,6 +122,7 @@
   __ load_with_trap_null_check(R12_scratch2, in_bytes(Method::from_compiled_offset()), R19_method);
   __ mtctr(R12_scratch2);
   __ bctr();
+
   masm->flush();
 
   guarantee(__ pc() <= s->code_end(), "overflowed buffer");
@@ -125,10 +132,16 @@
   return s;
 }
 
-VtableStub* VtableStubs::create_itable_stub(int vtable_index) {
+VtableStub* VtableStubs::create_itable_stub(int itable_index) {
   // PPC port: use fixed size.
   const int code_length = VtableStub::pd_code_size_limit(false);
-  VtableStub* s = new (code_length) VtableStub(false, vtable_index);
+  VtableStub* s = new (code_length) VtableStub(false, itable_index);
+
+  // Can be NULL if there is no free space in the code cache.
+  if (s == NULL) {
+    return NULL;
+  }
+
   ResourceMark rm;
   CodeBuffer cb(s->entry_point(), code_length);
   MacroAssembler* masm = new MacroAssembler(&cb);
@@ -136,10 +149,10 @@
 
 #ifndef PRODUCT
   if (CountCompiledCalls) {
-    __ load_const(R11_scratch1, SharedRuntime::nof_megamorphic_calls_addr());
-    __ lwz(R12_scratch2, 0, R11_scratch1);
+    int offs = __ load_const_optimized(R11_scratch1, SharedRuntime::nof_megamorphic_calls_addr(), R12_scratch2, true);
+    __ lwz(R12_scratch2, offs, R11_scratch1);
     __ addi(R12_scratch2, R12_scratch2, 1);
-    __ stw(R12_scratch2, 0, R11_scratch1);
+    __ stw(R12_scratch2, offs, R11_scratch1);
   }
 #endif
 
@@ -148,61 +161,27 @@
   // Entry arguments:
   //  R19_method: Interface
   //  R3_ARG1:    Receiver
-  //
 
-  const Register rcvr_klass = R11_scratch1;
-  const Register vtable_len = R12_scratch2;
-  const Register itable_entry_addr = R21_tmp1;
-  const Register itable_interface = R22_tmp2;
+  Label L_no_such_interface;
+  const Register rcvr_klass = R11_scratch1,
+                 interface  = R12_scratch2,
+                 tmp1       = R21_tmp1,
+                 tmp2       = R22_tmp2;
 
-  // Get receiver klass.
-
-  // We might implicit NULL fault here.
   address npe_addr = __ pc(); // npe = null pointer exception
   __ load_klass_with_trap_null_check(rcvr_klass, R3_ARG1);
 
-  BLOCK_COMMENT("Load start of itable entries into itable_entry.");
-  __ lwz(vtable_len, InstanceKlass::vtable_length_offset() * wordSize, rcvr_klass);
-  __ slwi(vtable_len, vtable_len, exact_log2(vtableEntry::size() * wordSize));
-  __ add(itable_entry_addr, vtable_len, rcvr_klass);
+  // Receiver subtype check against REFC.
+  __ ld(interface, CompiledICHolder::holder_klass_offset(), R19_method);
+  __ lookup_interface_method(rcvr_klass, interface, noreg,
+                             R0, tmp1, tmp2,
+                             L_no_such_interface, /*return_method=*/ false);
 
-  // Loop over all itable entries until desired interfaceOop(Rinterface) found.
-  BLOCK_COMMENT("Increment itable_entry_addr in loop.");
-  const int vtable_base_offset = InstanceKlass::vtable_start_offset() * wordSize;
-  __ addi(itable_entry_addr, itable_entry_addr, vtable_base_offset + itableOffsetEntry::interface_offset_in_bytes());
-
-  const int itable_offset_search_inc = itableOffsetEntry::size() * wordSize;
-  Label search;
-  __ bind(search);
-  __ ld(itable_interface, 0, itable_entry_addr);
-
-  // Handle IncompatibleClassChangeError in itable stubs.
-  // If the entry is NULL then we've reached the end of the table
-  // without finding the expected interface, so throw an exception.
-  BLOCK_COMMENT("Handle IncompatibleClassChangeError in itable stubs.");
-  Label throw_icce;
-  __ cmpdi(CCR1, itable_interface, 0);
-  __ cmpd(CCR0, itable_interface, R19_method);
-  __ addi(itable_entry_addr, itable_entry_addr, itable_offset_search_inc);
-  __ beq(CCR1, throw_icce);
-  __ bne(CCR0, search);
-
-  // Entry found and itable_entry_addr points to it, get offset of vtable for interface.
-
-  const Register vtable_offset = R12_scratch2;
-  const Register itable_method = R11_scratch1;
-
-  const int vtable_offset_offset = (itableOffsetEntry::offset_offset_in_bytes() -
-                                    itableOffsetEntry::interface_offset_in_bytes()) -
-                                   itable_offset_search_inc;
-  __ lwz(vtable_offset, vtable_offset_offset, itable_entry_addr);
-
-  // Compute itableMethodEntry and get method and entry point for compiler.
-  const int method_offset = (itableMethodEntry::size() * wordSize * vtable_index) +
-    itableMethodEntry::method_offset_in_bytes();
-
-  __ add(itable_method, rcvr_klass, vtable_offset);
-  __ ld(R19_method, method_offset, itable_method);
+  // Get Method* and entrypoint for compiler
+  __ ld(interface, CompiledICHolder::holder_metadata_offset(), R19_method);
+  __ lookup_interface_method(rcvr_klass, interface, itable_index,
+                             R19_method, tmp1, tmp2,
+                             L_no_such_interface, /*return_method=*/ true);
 
 #ifndef PRODUCT
   if (DebugVtables) {
@@ -224,7 +203,7 @@
       __ trap_null_check(R19_method);
     } else {
       __ cmpdi(CCR0, R19_method, 0);
-      __ beq(CCR0, throw_icce);
+      __ beq(CCR0, L_no_such_interface);
     }
   }
   __ ld(R12_scratch2, in_bytes(Method::from_compiled_offset()), R19_method);
@@ -236,8 +215,8 @@
   // We force resolving of the call site by jumping to the "handle
   // wrong method" stub, and so let the interpreter runtime do all the
   // dirty work.
-  __ bind(throw_icce);
-  __ load_const(R11_scratch1, SharedRuntime::get_handle_wrong_method_stub());
+  __ bind(L_no_such_interface);
+  __ load_const_optimized(R11_scratch1, SharedRuntime::get_handle_wrong_method_stub(), R12_scratch2);
   __ mtctr(R11_scratch1);
   __ bctr();
 
@@ -252,14 +231,15 @@
 int VtableStub::pd_code_size_limit(bool is_vtable_stub) {
   if (TraceJumps || DebugVtables || CountCompiledCalls || VerifyOops) {
     return 1000;
-  } else {
-    int decode_klass_size = MacroAssembler::instr_size_for_decode_klass_not_null();
-    if (is_vtable_stub) {
-      return 20 + decode_klass_size +  8 + 8;   // Plain + cOops + Traps + safety
-    } else {
-      return 96 + decode_klass_size + 12 + 8;   // Plain + cOops + Traps + safety
-    }
   }
+  int size = is_vtable_stub ? 20 + 8 : 164 + 20; // Plain + safety
+  if (UseCompressedClassPointers) {
+    size += MacroAssembler::instr_size_for_decode_klass_not_null();
+  }
+  if (!ImplicitNullChecks || !os::zero_page_read_protected()) {
+    size += is_vtable_stub ? 8 : 12;
+  }
+  return size;
 }
 
 int VtableStub::pd_code_alignment() {
diff --git a/src/cpu/sparc/vm/macroAssembler_sparc.cpp b/src/cpu/sparc/vm/macroAssembler_sparc.cpp
index 4dfc1db..19e388d 100644
--- a/src/cpu/sparc/vm/macroAssembler_sparc.cpp
+++ b/src/cpu/sparc/vm/macroAssembler_sparc.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -2183,9 +2183,10 @@
                                              Register method_result,
                                              Register scan_temp,
                                              Register sethi_temp,
-                                             Label& L_no_such_interface) {
+                                             Label& L_no_such_interface,
+                                             bool return_method) {
   assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
-  assert(itable_index.is_constant() || itable_index.as_register() == method_result,
+  assert(!return_method || itable_index.is_constant() || itable_index.as_register() == method_result,
          "caller must use same register for non-constant itable index as for method");
 
   Label L_no_such_interface_restore;
@@ -2229,11 +2230,13 @@
   }
   add(recv_klass, scan_temp, scan_temp);
 
-  // Adjust recv_klass by scaled itable_index, so we can free itable_index.
-  RegisterOrConstant itable_offset = itable_index;
-  itable_offset = regcon_sll_ptr(itable_index, exact_log2(itableMethodEntry::size() * wordSize), itable_offset);
-  itable_offset = regcon_inc_ptr(itable_offset, itableMethodEntry::method_offset_in_bytes(), itable_offset);
-  add(recv_klass, ensure_simm13_or_reg(itable_offset, sethi_temp), recv_klass);
+  if (return_method) {
+    // Adjust recv_klass by scaled itable_index, so we can free itable_index.
+    RegisterOrConstant itable_offset = itable_index;
+    itable_offset = regcon_sll_ptr(itable_index, exact_log2(itableMethodEntry::size() * wordSize), itable_offset);
+    itable_offset = regcon_inc_ptr(itable_offset, itableMethodEntry::method_offset_in_bytes(), itable_offset);
+    add(recv_klass, ensure_simm13_or_reg(itable_offset, sethi_temp), recv_klass);
+  }
 
   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
   //   if (scan->interface() == intf) {
@@ -2268,12 +2271,14 @@
 
   bind(L_found_method);
 
-  // Got a hit.
-  int ito_offset = itableOffsetEntry::offset_offset_in_bytes();
-  // scan_temp[-scan_step] points to the vtable offset we need
-  ito_offset -= scan_step;
-  lduw(scan_temp, ito_offset, scan_temp);
-  ld_ptr(recv_klass, scan_temp, method_result);
+  if (return_method) {
+    // Got a hit.
+    int ito_offset = itableOffsetEntry::offset_offset_in_bytes();
+    // scan_temp[-scan_step] points to the vtable offset we need
+    ito_offset -= scan_step;
+    lduw(scan_temp, ito_offset, scan_temp);
+    ld_ptr(recv_klass, scan_temp, method_result);
+  }
 
   if (did_save) {
     Label L_done;
diff --git a/src/cpu/sparc/vm/macroAssembler_sparc.hpp b/src/cpu/sparc/vm/macroAssembler_sparc.hpp
index f03dc8e..9894f33 100644
--- a/src/cpu/sparc/vm/macroAssembler_sparc.hpp
+++ b/src/cpu/sparc/vm/macroAssembler_sparc.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1347,7 +1347,8 @@
                                RegisterOrConstant itable_index,
                                Register method_result,
                                Register temp_reg, Register temp2_reg,
-                               Label& no_such_interface);
+                               Label& no_such_interface,
+                               bool return_method = true);
 
   // virtual method calling
   void lookup_virtual_method(Register recv_klass,
diff --git a/src/cpu/sparc/vm/methodHandles_sparc.cpp b/src/cpu/sparc/vm/methodHandles_sparc.cpp
index af6d628..f152cf0 100644
--- a/src/cpu/sparc/vm/methodHandles_sparc.cpp
+++ b/src/cpu/sparc/vm/methodHandles_sparc.cpp
@@ -481,7 +481,7 @@
   bool has_mh = (strstr(adaptername, "/static") == NULL &&
                  strstr(adaptername, "linkTo") == NULL);    // static linkers don't have MH
   const char* mh_reg_name = has_mh ? "G3_mh" : "G3";
-  tty->print_cr("MH %s %s="INTPTR_FORMAT " saved_sp=" INTPTR_FORMAT " args=" INTPTR_FORMAT,
+  tty->print_cr("MH %s %s=" INTPTR_FORMAT " saved_sp=" INTPTR_FORMAT " args=" INTPTR_FORMAT,
                 adaptername, mh_reg_name,
                 (intptr_t) mh, saved_sp, args);
 
diff --git a/src/cpu/sparc/vm/sharedRuntime_sparc.cpp b/src/cpu/sparc/vm/sharedRuntime_sparc.cpp
index 16f3d3b..7e72da8 100644
--- a/src/cpu/sparc/vm/sharedRuntime_sparc.cpp
+++ b/src/cpu/sparc/vm/sharedRuntime_sparc.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1045,7 +1045,7 @@
 
     Label ok, ok2;
     __ brx(Assembler::equal, false, Assembler::pt, ok);
-    __ delayed()->ld_ptr(G5_method, CompiledICHolder::holder_method_offset(), G5_method);
+    __ delayed()->ld_ptr(G5_method, CompiledICHolder::holder_metadata_offset(), G5_method);
     __ jump_to(ic_miss, G3_scratch);
     __ delayed()->nop();
 
diff --git a/src/cpu/sparc/vm/sparc.ad b/src/cpu/sparc/vm/sparc.ad
index 112ffe6..20ec462 100644
--- a/src/cpu/sparc/vm/sparc.ad
+++ b/src/cpu/sparc/vm/sparc.ad
@@ -1,5 +1,5 @@
 //
-// Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
+// Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved.
 // DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 //
 // This code is free software; you can redistribute it and/or modify it
@@ -1877,12 +1877,12 @@
 }
 
 // Vector ideal reg
-const int Matcher::vector_ideal_reg(int size) {
+const uint Matcher::vector_ideal_reg(int size) {
   assert(MaxVectorSize == 8, "");
   return Op_RegD;
 }
 
-const int Matcher::vector_shift_count_ideal_reg(int size) {
+const uint Matcher::vector_shift_count_ideal_reg(int size) {
   fatal("vector shift is not supported");
   return Node::NotAMachineReg;
 }
diff --git a/src/cpu/sparc/vm/templateTable_sparc.cpp b/src/cpu/sparc/vm/templateTable_sparc.cpp
index 43e8265..9d063f7 100644
--- a/src/cpu/sparc/vm/templateTable_sparc.cpp
+++ b/src/cpu/sparc/vm/templateTable_sparc.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -3165,15 +3165,15 @@
   assert(byte_no == f1_byte, "use this argument");
 
   const Register Rinterface  = G1_scratch;
+  const Register Rmethod     = Lscratch;
   const Register Rret        = G3_scratch;
-  const Register Rindex      = Lscratch;
   const Register O0_recv     = O0;
   const Register O1_flags    = O1;
   const Register O2_Klass    = O2;
   const Register Rscratch    = G4_scratch;
   assert_different_registers(Rscratch, G5_method);
 
-  prepare_invoke(byte_no, Rinterface, Rret, Rindex, O0_recv, O1_flags);
+  prepare_invoke(byte_no, Rinterface, Rret, Rmethod, O0_recv, O1_flags);
 
   // get receiver klass
   __ null_check(O0_recv, oopDesc::klass_offset_in_bytes());
@@ -3193,58 +3193,40 @@
 
   __ bind(notMethod);
 
+  Register Rtemp = O1_flags;
+
+  Label L_no_such_interface;
+
+  // Receiver subtype check against REFC.
+  __ lookup_interface_method(// inputs: rec. class, interface, itable index
+                             O2_Klass, Rinterface, noreg,
+                             // outputs: temp reg1, temp reg2, temp reg3
+                             G5_method, Rscratch, Rtemp,
+                             L_no_such_interface,
+                             /*return_method=*/false);
+
   __ profile_virtual_call(O2_Klass, O4);
 
   //
   // find entry point to call
   //
 
-  // compute start of first itableOffsetEntry (which is at end of vtable)
-  const int base = InstanceKlass::vtable_start_offset() * wordSize;
-  Label search;
-  Register Rtemp = O1_flags;
+  // Get declaring interface class from method
+  __ ld_ptr(Rmethod, Method::const_offset(), Rinterface);
+  __ ld_ptr(Rinterface, ConstMethod::constants_offset(), Rinterface);
+  __ ld_ptr(Rinterface, ConstantPool::pool_holder_offset_in_bytes(), Rinterface);
 
-  __ ld(O2_Klass, InstanceKlass::vtable_length_offset() * wordSize, Rtemp);
-  if (align_object_offset(1) > 1) {
-    __ round_to(Rtemp, align_object_offset(1));
-  }
-  __ sll(Rtemp, LogBytesPerWord, Rtemp);   // Rscratch *= 4;
-  if (Assembler::is_simm13(base)) {
-    __ add(Rtemp, base, Rtemp);
-  } else {
-    __ set(base, Rscratch);
-    __ add(Rscratch, Rtemp, Rtemp);
-  }
-  __ add(O2_Klass, Rtemp, Rscratch);
+  // Get itable index from method
+  const Register Rindex = G5_method;
+  __ ld(Rmethod, Method::itable_index_offset(), Rindex);
+  __ sub(Rindex, Method::itable_index_max, Rindex);
+  __ neg(Rindex);
 
-  __ bind(search);
-
-  __ ld_ptr(Rscratch, itableOffsetEntry::interface_offset_in_bytes(), Rtemp);
-  {
-    Label ok;
-
-    // Check that entry is non-null.  Null entries are probably a bytecode
-    // problem.  If the interface isn't implemented by the receiver class,
-    // the VM should throw IncompatibleClassChangeError.  linkResolver checks
-    // this too but that's only if the entry isn't already resolved, so we
-    // need to check again.
-    __ br_notnull_short( Rtemp, Assembler::pt, ok);
-    call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_IncompatibleClassChangeError));
-    __ should_not_reach_here();
-    __ bind(ok);
-  }
-
-  __ cmp(Rinterface, Rtemp);
-  __ brx(Assembler::notEqual, true, Assembler::pn, search);
-  __ delayed()->add(Rscratch, itableOffsetEntry::size() * wordSize, Rscratch);
-
-  // entry found and Rscratch points to it
-  __ ld(Rscratch, itableOffsetEntry::offset_offset_in_bytes(), Rscratch);
-
-  assert(itableMethodEntry::method_offset_in_bytes() == 0, "adjust instruction below");
-  __ sll(Rindex, exact_log2(itableMethodEntry::size() * wordSize), Rindex);       // Rindex *= 8;
-  __ add(Rscratch, Rindex, Rscratch);
-  __ ld_ptr(O2_Klass, Rscratch, G5_method);
+  __ lookup_interface_method(// inputs: rec. class, interface, itable index
+                             O2_Klass, Rinterface, Rindex,
+                             // outputs: method, scan temp reg, temp reg
+                             G5_method, Rscratch, Rtemp,
+                             L_no_such_interface);
 
   // Check for abstract method error.
   {
@@ -3260,6 +3242,10 @@
 
   __ profile_arguments_type(G5_method, Rcall, Gargs, true);
   __ call_from_interpreter(Rcall, Gargs, Rret);
+
+  __ bind(L_no_such_interface);
+  call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_IncompatibleClassChangeError));
+  __ should_not_reach_here();
 }
 
 void TemplateTable::invokehandle(int byte_no) {
diff --git a/src/cpu/sparc/vm/vm_version_sparc.cpp b/src/cpu/sparc/vm/vm_version_sparc.cpp
index 15e6f33..c0cd16a 100644
--- a/src/cpu/sparc/vm/vm_version_sparc.cpp
+++ b/src/cpu/sparc/vm/vm_version_sparc.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -140,10 +140,17 @@
     if (is_niagara_plus()) {
       if (has_blk_init() && (cache_line_size > 0) && UseTLAB &&
           FLAG_IS_DEFAULT(AllocatePrefetchInstr)) {
-        // Use BIS instruction for TLAB allocation prefetch.
-        FLAG_SET_ERGO(intx, AllocatePrefetchInstr, 1);
-        if (FLAG_IS_DEFAULT(AllocatePrefetchStyle)) {
-          FLAG_SET_ERGO(intx, AllocatePrefetchStyle, 3);
+        if (!has_sparc5_instr()) {
+          // Use BIS instruction for TLAB allocation prefetch
+          // on Niagara plus processors other than those based on CoreS4.
+          FLAG_SET_DEFAULT(AllocatePrefetchInstr, 1);
+        } else {
+          // On CoreS4 processors use prefetch instruction
+          // to avoid partial RAW issue, also use prefetch style 3.
+          FLAG_SET_DEFAULT(AllocatePrefetchInstr, 0);
+          if (FLAG_IS_DEFAULT(AllocatePrefetchStyle)) {
+            FLAG_SET_DEFAULT(AllocatePrefetchStyle, 3);
+          }
         }
         if (FLAG_IS_DEFAULT(AllocatePrefetchDistance)) {
           // Use smaller prefetch distance with BIS
@@ -165,6 +172,11 @@
         FLAG_SET_DEFAULT(AllocatePrefetchDistance, 256);
       }
       if (AllocatePrefetchInstr == 1) {
+
+        // Use allocation prefetch style 3 because BIS instructions
+        // require aligned memory addresses.
+        FLAG_SET_DEFAULT(AllocatePrefetchStyle, 3);
+
         // Need a space at the end of TLAB for BIS since it
         // will fault when accessing memory outside of heap.
 
diff --git a/src/cpu/sparc/vm/vtableStubs_sparc.cpp b/src/cpu/sparc/vm/vtableStubs_sparc.cpp
index cdbb57f..e090ee3 100644
--- a/src/cpu/sparc/vm/vtableStubs_sparc.cpp
+++ b/src/cpu/sparc/vm/vtableStubs_sparc.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,7 @@
 #include "code/vtableStubs.hpp"
 #include "interp_masm_sparc.hpp"
 #include "memory/resourceArea.hpp"
+#include "oops/compiledICHolder.hpp"
 #include "oops/instanceKlass.hpp"
 #include "oops/klassVtable.hpp"
 #include "runtime/sharedRuntime.hpp"
@@ -110,7 +111,7 @@
   masm->flush();
 
   if (PrintMiscellaneous && (WizardMode || Verbose)) {
-    tty->print_cr("vtable #%d at "PTR_FORMAT"[%d] left over: %d",
+    tty->print_cr("vtable #%d at " PTR_FORMAT "[%d] left over: %d",
                   vtable_index, s->entry_point(),
                   (int)(s->code_end() - s->entry_point()),
                   (int)(s->code_end() - __ pc()));
@@ -140,7 +141,8 @@
   MacroAssembler* masm = new MacroAssembler(&cb);
 
   Register G3_Klass = G3_scratch;
-  Register G5_interface = G5;  // Passed in as an argument
+  Register G5_icholder = G5;  // Passed in as an argument
+  Register G4_interface = G4_scratch;
   Label search;
 
   // Entry arguments:
@@ -164,14 +166,26 @@
   }
 #endif /* PRODUCT */
 
-  Label throw_icce;
+  Label L_no_such_interface;
 
   Register L5_method = L5;
+
+  // Receiver subtype check against REFC.
+  __ ld_ptr(G5_icholder, CompiledICHolder::holder_klass_offset(), G4_interface);
   __ lookup_interface_method(// inputs: rec. class, interface, itable index
-                             G3_Klass, G5_interface, itable_index,
+                             G3_Klass, G4_interface, itable_index,
+                             // outputs: scan temp. reg1, scan temp. reg2
+                             L5_method, L2, L3,
+                             L_no_such_interface,
+                             /*return_method=*/ false);
+
+  // Get Method* and entrypoint for compiler
+  __ ld_ptr(G5_icholder, CompiledICHolder::holder_metadata_offset(), G4_interface);
+  __ lookup_interface_method(// inputs: rec. class, interface, itable index
+                             G3_Klass, G4_interface, itable_index,
                              // outputs: method, scan temp. reg
                              L5_method, L2, L3,
-                             throw_icce);
+                             L_no_such_interface);
 
 #ifndef PRODUCT
   if (DebugVtables) {
@@ -197,7 +211,7 @@
   __ JMP(G3_scratch, 0);
   __ delayed()->nop();
 
-  __ bind(throw_icce);
+  __ bind(L_no_such_interface);
   AddressLiteral icce(StubRoutines::throw_IncompatibleClassChangeError_entry());
   __ jump_to(icce, G3_scratch);
   __ delayed()->restore();
@@ -205,7 +219,7 @@
   masm->flush();
 
   if (PrintMiscellaneous && (WizardMode || Verbose)) {
-    tty->print_cr("itable #%d at "PTR_FORMAT"[%d] left over: %d",
+    tty->print_cr("itable #%d at " PTR_FORMAT "[%d] left over: %d",
                   itable_index, s->entry_point(),
                   (int)(s->code_end() - s->entry_point()),
                   (int)(s->code_end() - __ pc()));
@@ -232,7 +246,7 @@
                           MacroAssembler::instr_size_for_decode_klass_not_null() : 0);
       return basic + slop;
     } else {
-      const int basic = (28 LP64_ONLY(+ 6)) * BytesPerInstWord +
+      const int basic = (48 LP64_ONLY(+ 6)) * BytesPerInstWord +
                         // shift;add for load_klass (only shift with zero heap based)
                         (UseCompressedClassPointers ?
                           MacroAssembler::instr_size_for_decode_klass_not_null() : 0);
diff --git a/src/cpu/x86/vm/c1_Runtime1_x86.cpp b/src/cpu/x86/vm/c1_Runtime1_x86.cpp
index aaa7964..d0948c1 100644
--- a/src/cpu/x86/vm/c1_Runtime1_x86.cpp
+++ b/src/cpu/x86/vm/c1_Runtime1_x86.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1667,31 +1667,15 @@
         __ jmp(done);
 
         __ bind(runtime);
-        __ push(rcx);
-#ifdef _LP64
-        __ push(r8);
-        __ push(r9);
-        __ push(r10);
-        __ push(r11);
-#  ifndef _WIN64
-        __ push(rdi);
-        __ push(rsi);
-#  endif
-#endif
+
+        save_live_registers(sasm, 3);
+
         // load the pre-value
         f.load_argument(0, rcx);
         __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), rcx, thread);
-#ifdef _LP64
-#  ifndef _WIN64
-        __ pop(rsi);
-        __ pop(rdi);
-#  endif
-        __ pop(r11);
-        __ pop(r10);
-        __ pop(r9);
-        __ pop(r8);
-#endif
-        __ pop(rcx);
+
+        restore_live_registers(sasm);
+
         __ bind(done);
 
         __ pop(rdx);
@@ -1773,27 +1757,13 @@
 
         __ bind(runtime);
         __ push(rdx);
-#ifdef _LP64
-        __ push(r8);
-        __ push(r9);
-        __ push(r10);
-        __ push(r11);
-#  ifndef _WIN64
-        __ push(rdi);
-        __ push(rsi);
-#  endif
-#endif
+
+        save_live_registers(sasm, 3);
+
         __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, thread);
-#ifdef _LP64
-#  ifndef _WIN64
-        __ pop(rsi);
-        __ pop(rdi);
-#  endif
-        __ pop(r11);
-        __ pop(r10);
-        __ pop(r9);
-        __ pop(r8);
-#endif
+
+        restore_live_registers(sasm);
+
         __ pop(rdx);
         __ bind(done);
 
diff --git a/src/cpu/x86/vm/interp_masm_x86_32.cpp b/src/cpu/x86/vm/interp_masm_x86_32.cpp
index 8a132c1..84cdc94 100644
--- a/src/cpu/x86/vm/interp_masm_x86_32.cpp
+++ b/src/cpu/x86/vm/interp_masm_x86_32.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1445,5 +1445,7 @@
   incrementl(scratch, increment);
   movl(counter_addr, scratch);
   andl(scratch, mask);
-  jcc(cond, *where);
+  if (where != NULL) {
+    jcc(cond, *where);
+  }
 }
diff --git a/src/cpu/x86/vm/interp_masm_x86_64.cpp b/src/cpu/x86/vm/interp_masm_x86_64.cpp
index 693ac79..727207e 100644
--- a/src/cpu/x86/vm/interp_masm_x86_64.cpp
+++ b/src/cpu/x86/vm/interp_masm_x86_64.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1505,5 +1505,7 @@
   incrementl(scratch, increment);
   movl(counter_addr, scratch);
   andl(scratch, mask);
-  jcc(cond, *where);
+  if (where != NULL) {
+    jcc(cond, *where);
+  }
 }
diff --git a/src/cpu/x86/vm/interpreterRT_x86_64.cpp b/src/cpu/x86/vm/interpreterRT_x86_64.cpp
index 959ed6e..60aaf4e 100644
--- a/src/cpu/x86/vm/interpreterRT_x86_64.cpp
+++ b/src/cpu/x86/vm/interpreterRT_x86_64.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -346,8 +346,9 @@
     _from -= Interpreter::stackElementSize;
 
     if (_num_args < Argument::n_float_register_parameters_c-1) {
+      assert((_num_args*2) < BitsPerWord, "_num_args*2 is out of range");
       *_reg_args++ = from_obj;
-      *_fp_identifiers |= (intptr_t)(0x01 << (_num_args*2)); // mark as float
+      *_fp_identifiers |= ((intptr_t)0x01 << (_num_args*2)); // mark as float
       _num_args++;
     } else {
       *_to++ = from_obj;
@@ -360,8 +361,9 @@
     _from -= 2*Interpreter::stackElementSize;
 
     if (_num_args < Argument::n_float_register_parameters_c-1) {
+      assert((_num_args*2) < BitsPerWord, "_num_args*2 is out of range");
       *_reg_args++ = from_obj;
-      *_fp_identifiers |= (intptr_t)(0x3 << (_num_args*2)); // mark as double
+      *_fp_identifiers |= ((intptr_t)0x3 << (_num_args*2)); // mark as double
       _num_args++;
     } else {
       *_to++ = from_obj;
diff --git a/src/cpu/x86/vm/macroAssembler_x86.cpp b/src/cpu/x86/vm/macroAssembler_x86.cpp
index 9711089..0e757f2 100644
--- a/src/cpu/x86/vm/macroAssembler_x86.cpp
+++ b/src/cpu/x86/vm/macroAssembler_x86.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -4853,8 +4853,13 @@
                                              RegisterOrConstant itable_index,
                                              Register method_result,
                                              Register scan_temp,
-                                             Label& L_no_such_interface) {
-  assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
+                                             Label& L_no_such_interface,
+                                             bool return_method) {
+  assert_different_registers(recv_klass, intf_klass, scan_temp);
+  assert_different_registers(method_result, intf_klass, scan_temp);
+  assert(recv_klass != method_result || !return_method,
+         "recv_klass can be destroyed when method isn't needed");
+
   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
          "caller must use same register for non-constant itable index as for method");
 
@@ -4876,9 +4881,11 @@
     round_to(scan_temp, BytesPerLong);
   }
 
-  // Adjust recv_klass by scaled itable_index, so we can free itable_index.
-  assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
-  lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
+  if (return_method) {
+    // Adjust recv_klass by scaled itable_index, so we can free itable_index.
+    assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
+    lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
+  }
 
   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
   //   if (scan->interface() == intf) {
@@ -4912,9 +4919,11 @@
 
   bind(found_method);
 
-  // Got a hit.
-  movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
-  movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
+  if (return_method) {
+    // Got a hit.
+    movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
+    movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
+  }
 }
 
 
@@ -5208,7 +5217,7 @@
       {
         ResourceMark rm;
         stringStream ss;
-        ss.print("DelayedValue="INTPTR_FORMAT, delayed_value_addr[1]);
+        ss.print("DelayedValue=" INTPTR_FORMAT, delayed_value_addr[1]);
         buf = code_string(ss.as_string());
       }
       jcc(Assembler::notZero, L);
diff --git a/src/cpu/x86/vm/macroAssembler_x86.hpp b/src/cpu/x86/vm/macroAssembler_x86.hpp
index b827056..c3c0a79 100644
--- a/src/cpu/x86/vm/macroAssembler_x86.hpp
+++ b/src/cpu/x86/vm/macroAssembler_x86.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -525,7 +525,8 @@
                                RegisterOrConstant itable_index,
                                Register method_result,
                                Register scan_temp,
-                               Label& no_such_interface);
+                               Label& no_such_interface,
+                               bool return_method = true);
 
   // virtual method calling
   void lookup_virtual_method(Register recv_klass,
diff --git a/src/cpu/x86/vm/methodHandles_x86.cpp b/src/cpu/x86/vm/methodHandles_x86.cpp
index 2f1326a..b1fa65c 100644
--- a/src/cpu/x86/vm/methodHandles_x86.cpp
+++ b/src/cpu/x86/vm/methodHandles_x86.cpp
@@ -483,7 +483,7 @@
   bool has_mh = (strstr(adaptername, "/static") == NULL &&
                  strstr(adaptername, "linkTo") == NULL);    // static linkers don't have MH
   const char* mh_reg_name = has_mh ? "rcx_mh" : "rcx";
-  tty->print_cr("MH %s %s="PTR_FORMAT" sp="PTR_FORMAT,
+  tty->print_cr("MH %s %s=" PTR_FORMAT " sp=" PTR_FORMAT,
                 adaptername, mh_reg_name,
                 (void *)mh, entry_sp);
 
diff --git a/src/cpu/x86/vm/sharedRuntime_x86_32.cpp b/src/cpu/x86/vm/sharedRuntime_x86_32.cpp
index 3441868..9debbc1 100644
--- a/src/cpu/x86/vm/sharedRuntime_x86_32.cpp
+++ b/src/cpu/x86/vm/sharedRuntime_x86_32.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -955,7 +955,7 @@
     Label missed;
     __ movptr(temp, Address(receiver, oopDesc::klass_offset_in_bytes()));
     __ cmpptr(temp, Address(holder, CompiledICHolder::holder_klass_offset()));
-    __ movptr(rbx, Address(holder, CompiledICHolder::holder_method_offset()));
+    __ movptr(rbx, Address(holder, CompiledICHolder::holder_metadata_offset()));
     __ jcc(Assembler::notEqual, missed);
     // Method might have been compiled since the call site was patched to
     // interpreted if that is the case treat it as a miss so we can get
diff --git a/src/cpu/x86/vm/sharedRuntime_x86_64.cpp b/src/cpu/x86/vm/sharedRuntime_x86_64.cpp
index 39a880b..e50c722 100644
--- a/src/cpu/x86/vm/sharedRuntime_x86_64.cpp
+++ b/src/cpu/x86/vm/sharedRuntime_x86_64.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -869,7 +869,7 @@
   {
     __ load_klass(temp, receiver);
     __ cmpptr(temp, Address(holder, CompiledICHolder::holder_klass_offset()));
-    __ movptr(rbx, Address(holder, CompiledICHolder::holder_method_offset()));
+    __ movptr(rbx, Address(holder, CompiledICHolder::holder_metadata_offset()));
     __ jcc(Assembler::equal, ok);
     __ jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
 
diff --git a/src/cpu/x86/vm/templateTable_x86_32.cpp b/src/cpu/x86/vm/templateTable_x86_32.cpp
index 9d18e8c..5d33add 100644
--- a/src/cpu/x86/vm/templateTable_x86_32.cpp
+++ b/src/cpu/x86/vm/templateTable_x86_32.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1640,15 +1640,16 @@
         // Increment the MDO backedge counter
         const Address mdo_backedge_counter(rbx, in_bytes(MethodData::backedge_counter_offset()) +
                                                 in_bytes(InvocationCounter::counter_offset()));
-        __ increment_mask_and_jump(mdo_backedge_counter, increment, mask,
-                                   rax, false, Assembler::zero, &backedge_counter_overflow);
+        __ increment_mask_and_jump(mdo_backedge_counter, increment, mask, rax, false, Assembler::zero,
+                                   UseOnStackReplacement ? &backedge_counter_overflow : NULL);
         __ jmp(dispatch);
       }
       __ bind(no_mdo);
       // Increment backedge counter in MethodCounters*
       __ movptr(rcx, Address(rcx, Method::method_counters_offset()));
       __ increment_mask_and_jump(Address(rcx, be_offset), increment, mask,
-                                 rax, false, Assembler::zero, &backedge_counter_overflow);
+                                 rax, false, Assembler::zero,
+                                 UseOnStackReplacement ? &backedge_counter_overflow : NULL);
     } else {
       // increment counter
       __ movptr(rcx, Address(rcx, Method::method_counters_offset()));
@@ -3099,11 +3100,11 @@
 void TemplateTable::invokeinterface(int byte_no) {
   transition(vtos, vtos);
   assert(byte_no == f1_byte, "use this argument");
-  prepare_invoke(byte_no, rax, rbx,  // get f1 Klass*, f2 itable index
+  prepare_invoke(byte_no, rax, rbx,  // get f1 Klass*, f2 Method*
                  rcx, rdx); // recv, flags
 
-  // rax: interface klass (from f1)
-  // rbx: itable index (from f2)
+  // rax: reference klass (from f1)
+  // rbx: method (from f2)
   // rcx: receiver
   // rdx: flags
 
@@ -3124,10 +3125,29 @@
   __ null_check(rcx, oopDesc::klass_offset_in_bytes());
   __ load_klass(rdx, rcx);
 
+  Label no_such_interface, no_such_method;
+
+  // Receiver subtype check against REFC.
+  // Superklass in rax. Subklass in rdx. Blows rcx, rdi.
+  __ lookup_interface_method(// inputs: rec. class, interface, itable index
+                             rdx, rax, noreg,
+                             // outputs: scan temp. reg, scan temp. reg
+                             rsi, rdi,
+                             no_such_interface,
+                             /*return_method=*/false);
+
+
   // profile this call
+  __ restore_bcp(); // rbcp was destroyed by receiver type check
   __ profile_virtual_call(rdx, rsi, rdi);
 
-  Label no_such_interface, no_such_method;
+  // Get declaring interface class from method, and itable index
+  __ movptr(rax, Address(rbx, Method::const_offset()));
+  __ movptr(rax, Address(rax, ConstMethod::constants_offset()));
+  __ movptr(rax, Address(rax, ConstantPool::pool_holder_offset_in_bytes()));
+  __ movl(rbx, Address(rbx, Method::itable_index_offset()));
+  __ subl(rbx, Method::itable_index_max);
+  __ negl(rbx);
 
   __ lookup_interface_method(// inputs: rec. class, interface, itable index
                              rdx, rax, rbx,
diff --git a/src/cpu/x86/vm/templateTable_x86_64.cpp b/src/cpu/x86/vm/templateTable_x86_64.cpp
index 9a8c34c..a619f44 100644
--- a/src/cpu/x86/vm/templateTable_x86_64.cpp
+++ b/src/cpu/x86/vm/templateTable_x86_64.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1665,15 +1665,16 @@
         // Increment the MDO backedge counter
         const Address mdo_backedge_counter(rbx, in_bytes(MethodData::backedge_counter_offset()) +
                                            in_bytes(InvocationCounter::counter_offset()));
-        __ increment_mask_and_jump(mdo_backedge_counter, increment, mask,
-                                   rax, false, Assembler::zero, &backedge_counter_overflow);
+        __ increment_mask_and_jump(mdo_backedge_counter, increment, mask, rax, false, Assembler::zero,
+                                   UseOnStackReplacement ? &backedge_counter_overflow : NULL);
         __ jmp(dispatch);
       }
       __ bind(no_mdo);
       // Increment backedge counter in MethodCounters*
       __ movptr(rcx, Address(rcx, Method::method_counters_offset()));
       __ increment_mask_and_jump(Address(rcx, be_offset), increment, mask,
-                                 rax, false, Assembler::zero, &backedge_counter_overflow);
+                                 rax, false, Assembler::zero,
+                                 UseOnStackReplacement ? &backedge_counter_overflow : NULL);
     } else {
       // increment counter
       __ movptr(rcx, Address(rcx, Method::method_counters_offset()));
@@ -3150,11 +3151,11 @@
 void TemplateTable::invokeinterface(int byte_no) {
   transition(vtos, vtos);
   assert(byte_no == f1_byte, "use this argument");
-  prepare_invoke(byte_no, rax, rbx,  // get f1 Klass*, f2 itable index
+  prepare_invoke(byte_no, rax, rbx,  // get f1 Klass*, f2 Method*
                  rcx, rdx); // recv, flags
 
-  // rax: interface klass (from f1)
-  // rbx: itable index (from f2)
+  // rax: reference klass (from f1)
+  // rbx: method (from f2)
   // rcx: receiver
   // rdx: flags
 
@@ -3175,10 +3176,28 @@
   __ null_check(rcx, oopDesc::klass_offset_in_bytes());
   __ load_klass(rdx, rcx);
 
+  Label no_such_interface, no_such_method;
+
+  // Receiver subtype check against REFC.
+  // Superklass in rax. Subklass in rdx. Blows rcx, rdi.
+  __ lookup_interface_method(// inputs: rec. class, interface, itable index
+                             rdx, rax, noreg,
+                             // outputs: scan temp. reg, scan temp. reg
+                             r13, r14,
+                             no_such_interface,
+                             /*return_method=*/false);
+
   // profile this call
+  __ restore_bcp(); // rbcp was destroyed by receiver type check
   __ profile_virtual_call(rdx, r13, r14);
 
-  Label no_such_interface, no_such_method;
+  // Get declaring interface class from method, and itable index
+  __ movptr(rax, Address(rbx, Method::const_offset()));
+  __ movptr(rax, Address(rax, ConstMethod::constants_offset()));
+  __ movptr(rax, Address(rax, ConstantPool::pool_holder_offset_in_bytes()));
+  __ movl(rbx, Address(rbx, Method::itable_index_offset()));
+  __ subl(rbx, Method::itable_index_max);
+  __ negl(rbx);
 
   __ lookup_interface_method(// inputs: rec. class, interface, itable index
                              rdx, rax, rbx,
diff --git a/src/cpu/x86/vm/vtableStubs_x86_32.cpp b/src/cpu/x86/vm/vtableStubs_x86_32.cpp
index 8d0353e..7d7e24e 100644
--- a/src/cpu/x86/vm/vtableStubs_x86_32.cpp
+++ b/src/cpu/x86/vm/vtableStubs_x86_32.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,7 @@
 #include "code/vtableStubs.hpp"
 #include "interp_masm_x86.hpp"
 #include "memory/resourceArea.hpp"
+#include "oops/compiledICHolder.hpp"
 #include "oops/instanceKlass.hpp"
 #include "oops/klassVtable.hpp"
 #include "runtime/sharedRuntime.hpp"
@@ -117,7 +118,7 @@
   masm->flush();
 
   if (PrintMiscellaneous && (WizardMode || Verbose)) {
-    tty->print_cr("vtable #%d at "PTR_FORMAT"[%d] left over: %d",
+    tty->print_cr("vtable #%d at " PTR_FORMAT "[%d] left over: %d",
                   vtable_index, p2i(s->entry_point()),
                   (int)(s->code_end() - s->entry_point()),
                   (int)(s->code_end() - __ pc()));
@@ -147,7 +148,7 @@
   MacroAssembler* masm = new MacroAssembler(&cb);
 
   // Entry arguments:
-  //  rax,: Interface
+  //  rax: CompiledICHolder
   //  rcx: Receiver
 
 #ifndef PRODUCT
@@ -155,25 +156,42 @@
     __ incrementl(ExternalAddress((address) SharedRuntime::nof_megamorphic_calls_addr()));
   }
 #endif /* PRODUCT */
-  // get receiver (need to skip return address on top of stack)
-
-  assert(VtableStub::receiver_location() == rcx->as_VMReg(), "receiver expected in rcx");
-
-  // get receiver klass (also an implicit null-check)
-  address npe_addr = __ pc();
-  __ movptr(rsi, Address(rcx, oopDesc::klass_offset_in_bytes()));
 
   // Most registers are in use; we'll use rax, rbx, rsi, rdi
   // (If we need to make rsi, rdi callee-save, do a push/pop here.)
-  const Register method = rbx;
-  Label throw_icce;
+  const Register recv_klass_reg     = rsi;
+  const Register holder_klass_reg   = rax; // declaring interface klass (DECC)
+  const Register resolved_klass_reg = rbx; // resolved interface klass (REFC)
+  const Register temp_reg           = rdi;
 
-  // Get Method* and entrypoint for compiler
+  const Register icholder_reg = rax;
+  __ movptr(resolved_klass_reg, Address(icholder_reg, CompiledICHolder::holder_klass_offset()));
+  __ movptr(holder_klass_reg,   Address(icholder_reg, CompiledICHolder::holder_metadata_offset()));
+
+  Label L_no_such_interface;
+
+  // get receiver klass (also an implicit null-check)
+  address npe_addr = __ pc();
+  assert(VtableStub::receiver_location() ==  rcx->as_VMReg(), "receiver expected in  rcx");
+  __ load_klass(recv_klass_reg, rcx);
+
+  // Receiver subtype check against REFC.
+  // Destroys recv_klass_reg value.
+  __ lookup_interface_method(// inputs: rec. class, interface
+                             recv_klass_reg, resolved_klass_reg, noreg,
+                             // outputs:  scan temp. reg1, scan temp. reg2
+                             recv_klass_reg, temp_reg,
+                             L_no_such_interface,
+                             /*return_method=*/false);
+
+  // Get selected method from declaring class and itable index
+  const Register method = rbx;
+  __ load_klass(recv_klass_reg, rcx); // restore recv_klass_reg
   __ lookup_interface_method(// inputs: rec. class, interface, itable index
-                             rsi, rax, itable_index,
+                             recv_klass_reg, holder_klass_reg, itable_index,
                              // outputs: method, scan temp. reg
-                             method, rdi,
-                             throw_icce);
+                             method, temp_reg,
+                             L_no_such_interface);
 
   // method (rbx): Method*
   // rcx: receiver
@@ -193,12 +211,13 @@
   address ame_addr = __ pc();
   __ jmp(Address(method, Method::from_compiled_offset()));
 
-  __ bind(throw_icce);
+  __ bind(L_no_such_interface);
   __ jump(RuntimeAddress(StubRoutines::throw_IncompatibleClassChangeError_entry()));
-  masm->flush();
+
+  __ flush();
 
   if (PrintMiscellaneous && (WizardMode || Verbose)) {
-    tty->print_cr("itable #%d at "PTR_FORMAT"[%d] left over: %d",
+    tty->print_cr("itable #%d at " PTR_FORMAT "[%d] left over: %d",
                   itable_index, p2i(s->entry_point()),
                   (int)(s->code_end() - s->entry_point()),
                   (int)(s->code_end() - __ pc()));
@@ -220,7 +239,7 @@
     return (DebugVtables ? 210 : 16) + (CountCompiledCalls ? 6 : 0);
   } else {
     // Itable stub size
-    return (DebugVtables ? 256 : 66) + (CountCompiledCalls ? 6 : 0);
+    return (DebugVtables ? 256 : 116) + (CountCompiledCalls ? 6 : 0);
   }
   // In order to tune these parameters, run the JVM with VM options
   // +PrintMiscellaneous and +WizardMode to see information about
diff --git a/src/cpu/x86/vm/vtableStubs_x86_64.cpp b/src/cpu/x86/vm/vtableStubs_x86_64.cpp
index b6dd1b3..a30883c 100644
--- a/src/cpu/x86/vm/vtableStubs_x86_64.cpp
+++ b/src/cpu/x86/vm/vtableStubs_x86_64.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,7 @@
 #include "code/vtableStubs.hpp"
 #include "interp_masm_x86.hpp"
 #include "memory/resourceArea.hpp"
+#include "oops/compiledICHolder.hpp"
 #include "oops/instanceKlass.hpp"
 #include "oops/klassVtable.hpp"
 #include "runtime/sharedRuntime.hpp"
@@ -112,7 +113,7 @@
   __ flush();
 
   if (PrintMiscellaneous && (WizardMode || Verbose)) {
-    tty->print_cr("vtable #%d at "PTR_FORMAT"[%d] left over: %d",
+    tty->print_cr("vtable #%d at " PTR_FORMAT "[%d] left over: %d",
                   vtable_index, s->entry_point(),
                   (int)(s->code_end() - s->entry_point()),
                   (int)(s->code_end() - __ pc()));
@@ -149,36 +150,50 @@
 #endif
 
   // Entry arguments:
-  //  rax: Interface
+  //  rax: CompiledICHolder
   //  j_rarg0: Receiver
 
-  // Free registers (non-args) are rax (interface), rbx
-
-  // get receiver (need to skip return address on top of stack)
-
-  assert(VtableStub::receiver_location() == j_rarg0->as_VMReg(), "receiver expected in j_rarg0");
-  // get receiver klass (also an implicit null-check)
-  address npe_addr = __ pc();
-
   // Most registers are in use; we'll use rax, rbx, r10, r11
   // (various calling sequences use r[cd]x, r[sd]i, r[89]; stay away from them)
-  __ load_klass(r10, j_rarg0);
+  const Register recv_klass_reg     = r10;
+  const Register holder_klass_reg   = rax; // declaring interface klass (DECC)
+  const Register resolved_klass_reg = rbx; // resolved interface klass (REFC)
+  const Register temp_reg           = r11;
+
+  Label L_no_such_interface;
+
+  const Register icholder_reg = rax;
+  __ movptr(resolved_klass_reg, Address(icholder_reg, CompiledICHolder::holder_klass_offset()));
+  __ movptr(holder_klass_reg,   Address(icholder_reg, CompiledICHolder::holder_metadata_offset()));
+
+  // get receiver klass (also an implicit null-check)
+  assert(VtableStub::receiver_location() == j_rarg0->as_VMReg(), "receiver expected in j_rarg0");
+  address npe_addr = __ pc();
+  __ load_klass(recv_klass_reg, j_rarg0);
+
+  // Receiver subtype check against REFC.
+  // Destroys recv_klass_reg value.
+  __ lookup_interface_method(// inputs: rec. class, interface
+                             recv_klass_reg, resolved_klass_reg, noreg,
+                             // outputs:  scan temp. reg1, scan temp. reg2
+                             recv_klass_reg, temp_reg,
+                             L_no_such_interface,
+                             /*return_method=*/false);
+
+  // Get selected method from declaring class and itable index
+  const Register method = rbx;
+  __ load_klass(recv_klass_reg, j_rarg0);   // restore recv_klass_reg
+  __ lookup_interface_method(// inputs: rec. class, interface, itable index
+                       recv_klass_reg, holder_klass_reg, itable_index,
+                       // outputs: method, scan temp. reg
+                       method, temp_reg,
+                       L_no_such_interface);
 
   // If we take a trap while this arg is on the stack we will not
   // be able to walk the stack properly. This is not an issue except
   // when there are mistakes in this assembly code that could generate
   // a spurious fault. Ask me how I know...
 
-  const Register method = rbx;
-  Label throw_icce;
-
-  // Get Method* and entrypoint for compiler
-  __ lookup_interface_method(// inputs: rec. class, interface, itable index
-                             r10, rax, itable_index,
-                             // outputs: method, scan temp. reg
-                             method, r11,
-                             throw_icce);
-
   // method (rbx): Method*
   // j_rarg0: receiver
 
@@ -199,13 +214,13 @@
   address ame_addr = __ pc();
   __ jmp(Address(method, Method::from_compiled_offset()));
 
-  __ bind(throw_icce);
+  __ bind(L_no_such_interface);
   __ jump(RuntimeAddress(StubRoutines::throw_IncompatibleClassChangeError_entry()));
 
   __ flush();
 
   if (PrintMiscellaneous && (WizardMode || Verbose)) {
-    tty->print_cr("itable #%d at "PTR_FORMAT"[%d] left over: %d",
+    tty->print_cr("itable #%d at " PTR_FORMAT "[%d] left over: %d",
                   itable_index, s->entry_point(),
                   (int)(s->code_end() - s->entry_point()),
                   (int)(s->code_end() - __ pc()));
@@ -226,8 +241,8 @@
            (UseCompressedClassPointers ?  MacroAssembler::instr_size_for_decode_klass_not_null() : 0);
   } else {
     // Itable stub size
-    return (DebugVtables ? 512 : 74) + (CountCompiledCalls ? 13 : 0) +
-           (UseCompressedClassPointers ?  MacroAssembler::instr_size_for_decode_klass_not_null() : 0);
+    return (DebugVtables ? 512 : 140) + (CountCompiledCalls ? 13 : 0) +
+           (UseCompressedClassPointers ? 2 * MacroAssembler::instr_size_for_decode_klass_not_null() : 0);
   }
   // In order to tune these parameters, run the JVM with VM options
   // +PrintMiscellaneous and +WizardMode to see information about
diff --git a/src/cpu/x86/vm/x86.ad b/src/cpu/x86/vm/x86.ad
index 4e2499a..36d6d96 100644
--- a/src/cpu/x86/vm/x86.ad
+++ b/src/cpu/x86/vm/x86.ad
@@ -1,5 +1,5 @@
 //
-// Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+// Copyright (c) 2011, 2018, Oracle and/or its affiliates. All rights reserved.
 // DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 //
 // This code is free software; you can redistribute it and/or modify it
@@ -683,7 +683,7 @@
 }
 
 // Vector ideal reg corresponding to specidied size in bytes
-const int Matcher::vector_ideal_reg(int size) {
+const uint Matcher::vector_ideal_reg(int size) {
   assert(MaxVectorSize >= size, "");
   switch(size) {
     case  4: return Op_VecS;
@@ -696,7 +696,7 @@
 }
 
 // Only lowest bits of xmm reg are used for vector shift count.
-const int Matcher::vector_shift_count_ideal_reg(int size) {
+const uint Matcher::vector_shift_count_ideal_reg(int size) {
   return Op_VecS;
 }
 
diff --git a/src/cpu/zero/vm/entry_zero.hpp b/src/cpu/zero/vm/entry_zero.hpp
index 20f5d33..73987f0 100644
--- a/src/cpu/zero/vm/entry_zero.hpp
+++ b/src/cpu/zero/vm/entry_zero.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
  * Copyright 2008, 2009, 2010 Red Hat, Inc.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -26,6 +26,8 @@
 #ifndef CPU_ZERO_VM_ENTRY_ZERO_HPP
 #define CPU_ZERO_VM_ENTRY_ZERO_HPP
 
+#include "interpreter/cppInterpreter.hpp"
+
 class ZeroEntry {
  public:
   ZeroEntry() {
diff --git a/src/cpu/zero/vm/methodHandles_zero.cpp b/src/cpu/zero/vm/methodHandles_zero.cpp
index ea1bc0e..2b0b39d 100644
--- a/src/cpu/zero/vm/methodHandles_zero.cpp
+++ b/src/cpu/zero/vm/methodHandles_zero.cpp
@@ -180,3 +180,9 @@
     return NULL;
   }
 }
+
+#ifndef PRODUCT
+void MethodHandles::trace_method_handle(MacroAssembler* _masm, const char* adaptername) {
+  // This is just a stub.
+}
+#endif //PRODUCT
diff --git a/src/cpu/zero/vm/nativeInst_zero.cpp b/src/cpu/zero/vm/nativeInst_zero.cpp
index 98a2121..bd9a703 100644
--- a/src/cpu/zero/vm/nativeInst_zero.cpp
+++ b/src/cpu/zero/vm/nativeInst_zero.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
  * Copyright 2008 Red Hat, Inc.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -25,6 +25,8 @@
 
 #include "precompiled.hpp"
 #include "assembler_zero.inline.hpp"
+#include "entry_zero.hpp"
+#include "interpreter/cppInterpreter.hpp"
 #include "memory/resourceArea.hpp"
 #include "nativeInst_zero.hpp"
 #include "oops/oop.inline.hpp"
diff --git a/src/os/aix/vm/os_aix.cpp b/src/os/aix/vm/os_aix.cpp
index 4cd28b8..8cd1f4e 100644
--- a/src/os/aix/vm/os_aix.cpp
+++ b/src/os/aix/vm/os_aix.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
  * Copyright 2012, 2014 SAP AG. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -410,7 +410,7 @@
   // thread (because primordial thread's stack may have different page size than
   // pthread thread stacks). Running a VM on the primordial thread won't work for a
   // number of reasons so we may just as well guarantee it here
-  guarantee(!os::Aix::is_primordial_thread(), "Must not be called for primordial thread");
+  guarantee(!os::is_primordial_thread(), "Must not be called for primordial thread");
 
   // query stack page size
   {
@@ -3835,7 +3835,7 @@
 
   ThreadCritical::initialize();
 
-  // Main_thread points to the aboriginal thread.
+  // _main_thread points to the thread that created/loaded the JVM.
   Aix::_main_thread = pthread_self();
 
   initial_time_count = os::elapsed_counter();
@@ -4008,6 +4008,16 @@
 };
 
 int os::active_processor_count() {
+  // User has overridden the number of active processors
+  if (ActiveProcessorCount > 0) {
+    if (PrintActiveCpus) {
+      tty->print_cr("active_processor_count: "
+                    "active processor count set by user : %d",
+                     ActiveProcessorCount);
+    }
+    return ActiveProcessorCount;
+  }
+
   int online_cpus = ::sysconf(_SC_NPROCESSORS_ONLN);
   assert(online_cpus > 0 && online_cpus <= processor_count(), "sanity check");
   return online_cpus;
@@ -4511,7 +4521,7 @@
   }
 }
 
-bool os::Aix::is_primordial_thread() {
+bool os::is_primordial_thread(void) {
   if (pthread_self() == (pthread_t)1) {
     return true;
   } else {
@@ -4646,7 +4656,7 @@
 
   // This only works when invoked on a pthread. As we agreed not to use
   // primordial threads anyway, I assert here
-  guarantee(!os::Aix::is_primordial_thread(), "not allowed on the primordial thread");
+  guarantee(!os::is_primordial_thread(), "not allowed on the primordial thread");
 
   // information about this api can be found (a) in the pthread.h header and
   // (b) in http://publib.boulder.ibm.com/infocenter/pseries/v5r3/index.jsp?topic=/com.ibm.aix.basetechref/doc/basetrf1/pthread_getthrds_np.htm
diff --git a/src/os/aix/vm/os_aix.hpp b/src/os/aix/vm/os_aix.hpp
index 01831fb..1fa350d 100644
--- a/src/os/aix/vm/os_aix.hpp
+++ b/src/os/aix/vm/os_aix.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
  * Copyright 2013 SAP AG. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -170,12 +170,6 @@
   // Given an address, returns the size of the page backing that address
   static size_t query_pagesize(void* p);
 
-  // Return `true' if the calling thread is the primordial thread. The
-  // primordial thread is the thread which contains the main function,
-  // *not* necessarily the thread which initialized the VM by calling
-  // JNI_CreateJavaVM.
-  static bool is_primordial_thread(void);
-
   static int page_size(void) {
     assert(_page_size != -1, "not initialized");
     return _page_size;
diff --git a/src/os/aix/vm/perfMemory_aix.cpp b/src/os/aix/vm/perfMemory_aix.cpp
index be6e855..96f8451 100644
--- a/src/os/aix/vm/perfMemory_aix.cpp
+++ b/src/os/aix/vm/perfMemory_aix.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved.
  * Copyright 2012, 2013 SAP AG. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -706,7 +706,7 @@
 // return the name of the user that owns the JVM indicated by the given vmid.
 //
 static char* get_user_name(int vmid, TRAPS) {
-  return get_user_name_slow(vmid, CHECK_NULL);
+  return get_user_name_slow(vmid, THREAD);
 }
 
 // return the file name of the backing store file for the named
diff --git a/src/os/bsd/vm/os_bsd.cpp b/src/os/bsd/vm/os_bsd.cpp
index 58b5896..c377c7d 100644
--- a/src/os/bsd/vm/os_bsd.cpp
+++ b/src/os/bsd/vm/os_bsd.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1681,14 +1681,9 @@
 
   dlclose(handle);
 #elif defined(__APPLE__)
-  uint32_t count;
-  uint32_t i;
-
-  count = _dyld_image_count();
-  for (i = 1; i < count; i++) {
-    const char *name = _dyld_get_image_name(i);
-    intptr_t slide = _dyld_get_image_vmaddr_slide(i);
-    st->print_cr(PTR_FORMAT " \t%s", slide, name);
+  for (uint32_t i = 1; i < _dyld_image_count(); i++) {
+    st->print_cr(PTR_FORMAT " \t%s", _dyld_get_image_header(i),
+        _dyld_get_image_name(i));
   }
 #else
   st->print_cr("Error: Cannot print dynamic libraries.");
@@ -3616,7 +3611,7 @@
 
   Bsd::initialize_system_info();
 
-  // main_thread points to the aboriginal thread
+  // _main_thread points to the thread that created/loaded the JVM.
   Bsd::_main_thread = pthread_self();
 
   Bsd::clock_init();
@@ -3770,6 +3765,16 @@
 };
 
 int os::active_processor_count() {
+  // User has overridden the number of active processors
+  if (ActiveProcessorCount > 0) {
+    if (PrintActiveCpus) {
+      tty->print_cr("active_processor_count: "
+                    "active processor count set by user : %d",
+                     ActiveProcessorCount);
+    }
+    return ActiveProcessorCount;
+  }
+
   return _processor_count;
 }
 
diff --git a/src/os/bsd/vm/os_bsd.hpp b/src/os/bsd/vm/os_bsd.hpp
index f9803c0..f67d192 100644
--- a/src/os/bsd/vm/os_bsd.hpp
+++ b/src/os/bsd/vm/os_bsd.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -92,7 +92,6 @@
 
   static void hotspot_sigmask(Thread* thread);
 
-  static bool is_initial_thread(void);
   static pid_t gettid();
 
   static int page_size(void)                                        { return _page_size; }
diff --git a/src/os/bsd/vm/perfMemory_bsd.cpp b/src/os/bsd/vm/perfMemory_bsd.cpp
index f25c39d..df4fca6 100644
--- a/src/os/bsd/vm/perfMemory_bsd.cpp
+++ b/src/os/bsd/vm/perfMemory_bsd.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -615,7 +615,7 @@
 // return the name of the user that owns the JVM indicated by the given vmid.
 //
 static char* get_user_name(int vmid, TRAPS) {
-  return get_user_name_slow(vmid, CHECK_NULL);
+  return get_user_name_slow(vmid, THREAD);
 }
 
 // return the file name of the backing store file for the named
diff --git a/src/os/linux/vm/globals_linux.hpp b/src/os/linux/vm/globals_linux.hpp
index 32d4619..f98bde4 100644
--- a/src/os/linux/vm/globals_linux.hpp
+++ b/src/os/linux/vm/globals_linux.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -49,8 +49,13 @@
   product(bool, UseSHM, false,                                          \
           "Use SYSV shared memory for large pages")                     \
                                                                         \
-  diagnostic(bool, PrintActiveCpus, false,                              \
-          "Print the number of CPUs detected in os::active_processor_count")
+  product(bool, UseContainerSupport, true,                              \
+          "Enable detection and runtime container configuration support") \
+                                                                        \
+  product(bool, PreferContainerQuotaForCPUCount, true,                  \
+          "Calculate the container CPU availability based on the value" \
+          " of quotas (if set), when true. Otherwise, use the CPU"      \
+          " shares value, provided it is less than quota.")
 
 //
 // Defines Linux-specific default values. The flags are available on all
diff --git a/src/os/linux/vm/osContainer_linux.cpp b/src/os/linux/vm/osContainer_linux.cpp
new file mode 100644
index 0000000..55a2981
--- /dev/null
+++ b/src/os/linux/vm/osContainer_linux.cpp
@@ -0,0 +1,680 @@
+/*
+ * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+#include <string.h>
+#include <math.h>
+#include <errno.h>
+#include "utilities/globalDefinitions.hpp"
+#include "memory/allocation.hpp"
+#include "runtime/os.hpp"
+#include "osContainer_linux.hpp"
+
+#define PER_CPU_SHARES 1024
+
+bool  OSContainer::_is_initialized   = false;
+bool  OSContainer::_is_containerized = false;
+julong _unlimited_memory;
+
+class CgroupSubsystem: CHeapObj<mtInternal> {
+ friend class OSContainer;
+
+ private:
+    /* mountinfo contents */
+    char *_root;
+    char *_mount_point;
+
+    /* Constructed subsystem directory */
+    char *_path;
+
+ public:
+    CgroupSubsystem(char *root, char *mountpoint) {
+      _root = os::strdup(root);
+      _mount_point = os::strdup(mountpoint);
+      _path = NULL;
+    }
+
+    /*
+     * Set directory to subsystem specific files based
+     * on the contents of the mountinfo and cgroup files.
+     */
+    void set_subsystem_path(char *cgroup_path) {
+      char buf[MAXPATHLEN+1];
+      if (_root != NULL && cgroup_path != NULL) {
+        if (strcmp(_root, "/") == 0) {
+          int buflen;
+          strncpy(buf, _mount_point, MAXPATHLEN);
+          buf[MAXPATHLEN-1] = '\0';
+          if (strcmp(cgroup_path,"/") != 0) {
+            buflen = strlen(buf);
+            if ((buflen + strlen(cgroup_path)) > (MAXPATHLEN-1)) {
+              return;
+            }
+            strncat(buf, cgroup_path, MAXPATHLEN-buflen);
+            buf[MAXPATHLEN-1] = '\0';
+          }
+          _path = os::strdup(buf);
+        } else {
+          if (strcmp(_root, cgroup_path) == 0) {
+            strncpy(buf, _mount_point, MAXPATHLEN);
+            buf[MAXPATHLEN-1] = '\0';
+            _path = os::strdup(buf);
+          } else {
+            char *p = strstr(_root, cgroup_path);
+            if (p != NULL && p == _root) {
+              if (strlen(cgroup_path) > strlen(_root)) {
+                int buflen;
+                strncpy(buf, _mount_point, MAXPATHLEN);
+                buf[MAXPATHLEN-1] = '\0';
+                buflen = strlen(buf);
+                if ((buflen + strlen(cgroup_path)) > (MAXPATHLEN-1)) {
+                  return;
+                }
+                strncat(buf, cgroup_path + strlen(_root), MAXPATHLEN-buflen);
+                buf[MAXPATHLEN-1] = '\0';
+                _path = os::strdup(buf);
+              }
+            }
+          }
+        }
+      }
+    }
+
+    char *subsystem_path() { return _path; }
+};
+
+CgroupSubsystem* memory = NULL;
+CgroupSubsystem* cpuset = NULL;
+CgroupSubsystem* cpu = NULL;
+CgroupSubsystem* cpuacct = NULL;
+
+typedef char * cptr;
+
+PRAGMA_DIAG_PUSH
+PRAGMA_FORMAT_NONLITERAL_IGNORED
+template <typename T> int subsystem_file_contents(CgroupSubsystem* c,
+                                              const char *filename,
+                                              const char *scan_fmt,
+                                              T returnval) {
+  FILE *fp = NULL;
+  char *p;
+  char file[MAXPATHLEN+1];
+  char buf[MAXPATHLEN+1];
+
+  if (c == NULL) {
+    if (PrintContainerInfo) {
+      tty->print_cr("subsystem_file_contents: CgroupSubsytem* is NULL");
+    }
+    return OSCONTAINER_ERROR;
+  }
+  if (c->subsystem_path() == NULL) {
+    if (PrintContainerInfo) {
+      tty->print_cr("subsystem_file_contents: subsystem path is NULL");
+    }
+    return OSCONTAINER_ERROR;
+  }
+
+  strncpy(file, c->subsystem_path(), MAXPATHLEN);
+  file[MAXPATHLEN-1] = '\0';
+  int filelen = strlen(file);
+  if ((filelen + strlen(filename)) > (MAXPATHLEN-1)) {
+    if (PrintContainerInfo) {
+      tty->print_cr("File path too long %s, %s", file, filename);
+    }
+    return OSCONTAINER_ERROR;
+  }
+  strncat(file, filename, MAXPATHLEN-filelen);
+  if (PrintContainerInfo) {
+    tty->print_cr("Path to %s is %s", filename, file);
+  }
+  fp = fopen(file, "r");
+  if (fp != NULL) {
+    p = fgets(buf, MAXPATHLEN, fp);
+    if (p != NULL) {
+      int matched = sscanf(p, scan_fmt, returnval);
+      if (matched == 1) {
+        fclose(fp);
+        return 0;
+      } else {
+        if (PrintContainerInfo) {
+          tty->print_cr("Type %s not found in file %s", scan_fmt, file);
+        }
+      }
+    } else {
+      if (PrintContainerInfo) {
+        tty->print_cr("Empty file %s", file);
+      }
+    }
+  } else {
+    if (PrintContainerInfo) {
+      tty->print_cr("Open of file %s failed, %s", file, strerror(errno));
+    }
+  }
+  if (fp != NULL)
+    fclose(fp);
+  return OSCONTAINER_ERROR;
+}
+PRAGMA_DIAG_POP
+
+#define GET_CONTAINER_INFO(return_type, subsystem, filename,              \
+                           logstring, scan_fmt, variable)                 \
+  return_type variable;                                                   \
+{                                                                         \
+  int err;                                                                \
+  err = subsystem_file_contents(subsystem,                                \
+                                filename,                                 \
+                                scan_fmt,                                 \
+                                &variable);                               \
+  if (err != 0)                                                           \
+    return (return_type) OSCONTAINER_ERROR;                               \
+                                                                          \
+  if (PrintContainerInfo)                                                 \
+    tty->print_cr(logstring, variable);                                   \
+}
+
+#define GET_CONTAINER_INFO_CPTR(return_type, subsystem, filename,         \
+                               logstring, scan_fmt, variable, bufsize)    \
+  char variable[bufsize];                                                 \
+{                                                                         \
+  int err;                                                                \
+  err = subsystem_file_contents(subsystem,                                \
+                                filename,                                 \
+                                scan_fmt,                                 \
+                                variable);                                \
+  if (err != 0)                                                           \
+    return (return_type) NULL;                                            \
+                                                                          \
+  if (PrintContainerInfo)                                                 \
+    tty->print_cr(logstring, variable);                                   \
+}
+
+/* init
+ *
+ * Initialize the container support and determine if
+ * we are running under cgroup control.
+ */
+void OSContainer::init() {
+  int mountid;
+  int parentid;
+  int major;
+  int minor;
+  FILE *mntinfo = NULL;
+  FILE *cgroup = NULL;
+  char buf[MAXPATHLEN+1];
+  char tmproot[MAXPATHLEN+1];
+  char tmpmount[MAXPATHLEN+1];
+  char tmpbase[MAXPATHLEN+1];
+  char *p;
+  jlong mem_limit;
+
+  assert(!_is_initialized, "Initializing OSContainer more than once");
+
+  _is_initialized = true;
+  _is_containerized = false;
+
+  _unlimited_memory = (LONG_MAX / os::vm_page_size()) * os::vm_page_size();
+
+  if (PrintContainerInfo) {
+    tty->print_cr("OSContainer::init: Initializing Container Support");
+  }
+  if (!UseContainerSupport) {
+    if (PrintContainerInfo) {
+      tty->print_cr("Container Support not enabled");
+    }
+    return;
+  }
+
+  /*
+   * Find the cgroup mount point for memory and cpuset
+   * by reading /proc/self/mountinfo
+   *
+   * Example for docker:
+   * 219 214 0:29 /docker/7208cebd00fa5f2e342b1094f7bed87fa25661471a4637118e65f1c995be8a34 /sys/fs/cgroup/memory ro,nosuid,nodev,noexec,relatime - cgroup cgroup rw,memory
+   *
+   * Example for host:
+   * 34 28 0:29 / /sys/fs/cgroup/memory rw,nosuid,nodev,noexec,relatime shared:16 - cgroup cgroup rw,memory
+   */
+  mntinfo = fopen("/proc/self/mountinfo", "r");
+  if (mntinfo == NULL) {
+      if (PrintContainerInfo) {
+        tty->print_cr("Can't open /proc/self/mountinfo, %s",
+                       strerror(errno));
+      }
+      return;
+  }
+
+  while ( (p = fgets(buf, MAXPATHLEN, mntinfo)) != NULL) {
+    // Look for the filesystem type and see if it's cgroup
+    char fstype[MAXPATHLEN+1];
+    fstype[0] = '\0';
+    char *s =  strstr(p, " - ");
+    if (s != NULL &&
+        sscanf(s, " - %s", fstype) == 1 &&
+        strcmp(fstype, "cgroup") == 0) {
+
+      if (strstr(p, "memory") != NULL) {
+        int matched = sscanf(p, "%d %d %d:%d %s %s",
+                             &mountid,
+                             &parentid,
+                             &major,
+                             &minor,
+                             tmproot,
+                             tmpmount);
+        if (matched == 6) {
+          memory = new CgroupSubsystem(tmproot, tmpmount);
+        }
+        else
+          if (PrintContainerInfo) {
+            tty->print_cr("Incompatible str containing cgroup and memory: %s", p);
+          }
+      } else if (strstr(p, "cpuset") != NULL) {
+        int matched = sscanf(p, "%d %d %d:%d %s %s",
+                             &mountid,
+                             &parentid,
+                             &major,
+                             &minor,
+                             tmproot,
+                             tmpmount);
+        if (matched == 6) {
+          cpuset = new CgroupSubsystem(tmproot, tmpmount);
+        }
+        else {
+          if (PrintContainerInfo) {
+            tty->print_cr("Incompatible str containing cgroup and cpuset: %s", p);
+          }
+        }
+      } else if (strstr(p, "cpu,cpuacct") != NULL || strstr(p, "cpuacct,cpu") != NULL) {
+        int matched = sscanf(p, "%d %d %d:%d %s %s",
+                             &mountid,
+                             &parentid,
+                             &major,
+                             &minor,
+                             tmproot,
+                             tmpmount);
+        if (matched == 6) {
+          cpu = new CgroupSubsystem(tmproot, tmpmount);
+          cpuacct = new CgroupSubsystem(tmproot, tmpmount);
+        }
+        else {
+          if (PrintContainerInfo) {
+            tty->print_cr("Incompatible str containing cgroup and cpu,cpuacct: %s", p);
+          }
+        }
+      } else if (strstr(p, "cpuacct") != NULL) {
+        int matched = sscanf(p, "%d %d %d:%d %s %s",
+                             &mountid,
+                             &parentid,
+                             &major,
+                             &minor,
+                             tmproot,
+                             tmpmount);
+        if (matched == 6) {
+          cpuacct = new CgroupSubsystem(tmproot, tmpmount);
+        }
+        else {
+          if (PrintContainerInfo) {
+            tty->print_cr("Incompatible str containing cgroup and cpuacct: %s", p);
+          }
+        }
+      } else if (strstr(p, "cpu") != NULL) {
+        int matched = sscanf(p, "%d %d %d:%d %s %s",
+                             &mountid,
+                             &parentid,
+                             &major,
+                             &minor,
+                             tmproot,
+                             tmpmount);
+        if (matched == 6) {
+          cpu = new CgroupSubsystem(tmproot, tmpmount);
+        }
+        else {
+          if (PrintContainerInfo) {
+            tty->print_cr("Incompatible str containing cgroup and cpu: %s", p);
+          }
+        }
+      }
+    }
+  }
+
+  fclose(mntinfo);
+
+  if (memory == NULL) {
+    if (PrintContainerInfo) {
+      tty->print_cr("Required cgroup memory subsystem not found");
+    }
+    return;
+  }
+  if (cpuset == NULL) {
+    if (PrintContainerInfo) {
+      tty->print_cr("Required cgroup cpuset subsystem not found");
+    }
+    return;
+  }
+  if (cpu == NULL) {
+    if (PrintContainerInfo) {
+      tty->print_cr("Required cgroup cpu subsystem not found");
+    }
+    return;
+  }
+  if (cpuacct == NULL) {
+    if (PrintContainerInfo) {
+      tty->print_cr("Required cgroup cpuacct subsystem not found");
+    }
+    return;
+  }
+
+  /*
+   * Read /proc/self/cgroup and map host mount point to
+   * local one via /proc/self/mountinfo content above
+   *
+   * Docker example:
+   * 5:memory:/docker/6558aed8fc662b194323ceab5b964f69cf36b3e8af877a14b80256e93aecb044
+   *
+   * Host example:
+   * 5:memory:/user.slice
+   *
+   * Construct a path to the process specific memory and cpuset
+   * cgroup directory.
+   *
+   * For a container running under Docker from memory example above
+   * the paths would be:
+   *
+   * /sys/fs/cgroup/memory
+   *
+   * For a Host from memory example above the path would be:
+   *
+   * /sys/fs/cgroup/memory/user.slice
+   *
+   */
+  cgroup = fopen("/proc/self/cgroup", "r");
+  if (cgroup == NULL) {
+    if (PrintContainerInfo) {
+      tty->print_cr("Can't open /proc/self/cgroup, %s",
+                     strerror(errno));
+      }
+    return;
+  }
+
+  while ( (p = fgets(buf, MAXPATHLEN, cgroup)) != NULL) {
+    int cgno;
+    int matched;
+    char *controller;
+    char *base;
+
+    /* Skip cgroup number */
+    strsep(&p, ":");
+    /* Get controller and base */
+    controller = strsep(&p, ":");
+    base = strsep(&p, "\n");
+
+    if (controller != NULL) {
+      if (strstr(controller, "memory") != NULL) {
+        memory->set_subsystem_path(base);
+      } else if (strstr(controller, "cpuset") != NULL) {
+        cpuset->set_subsystem_path(base);
+      } else if (strstr(controller, "cpu,cpuacct") != NULL || strstr(controller, "cpuacct,cpu") != NULL) {
+        cpu->set_subsystem_path(base);
+        cpuacct->set_subsystem_path(base);
+      } else if (strstr(controller, "cpuacct") != NULL) {
+        cpuacct->set_subsystem_path(base);
+      } else if (strstr(controller, "cpu") != NULL) {
+        cpu->set_subsystem_path(base);
+      }
+    }
+  }
+
+  fclose(cgroup);
+
+  // We need to update the amount of physical memory now that
+  // command line arguments have been processed.
+  if ((mem_limit = memory_limit_in_bytes()) > 0) {
+    os::Linux::set_physical_memory(mem_limit);
+  }
+
+  _is_containerized = true;
+
+}
+
+const char * OSContainer::container_type() {
+  if (is_containerized()) {
+    return "cgroupv1";
+  } else {
+    return NULL;
+  }
+}
+
+
+/* memory_limit_in_bytes
+ *
+ * Return the limit of available memory for this process.
+ *
+ * return:
+ *    memory limit in bytes or
+ *    -1 for unlimited
+ *    OSCONTAINER_ERROR for not supported
+ */
+jlong OSContainer::memory_limit_in_bytes() {
+  GET_CONTAINER_INFO(julong, memory, "/memory.limit_in_bytes",
+                     "Memory Limit is: " JULONG_FORMAT, JULONG_FORMAT, memlimit);
+
+  if (memlimit >= _unlimited_memory) {
+    if (PrintContainerInfo) {
+      tty->print_cr("Memory Limit is: Unlimited");
+    }
+    return (jlong)-1;
+  }
+  else {
+    return (jlong)memlimit;
+  }
+}
+
+jlong OSContainer::memory_and_swap_limit_in_bytes() {
+  GET_CONTAINER_INFO(julong, memory, "/memory.memsw.limit_in_bytes",
+                     "Memory and Swap Limit is: " JULONG_FORMAT, JULONG_FORMAT, memswlimit);
+  if (memswlimit >= _unlimited_memory) {
+    if (PrintContainerInfo) {
+      tty->print_cr("Memory and Swap Limit is: Unlimited");
+    }
+    return (jlong)-1;
+  } else {
+    return (jlong)memswlimit;
+  }
+}
+
+jlong OSContainer::memory_soft_limit_in_bytes() {
+  GET_CONTAINER_INFO(julong, memory, "/memory.soft_limit_in_bytes",
+                     "Memory Soft Limit is: " JULONG_FORMAT, JULONG_FORMAT, memsoftlimit);
+  if (memsoftlimit >= _unlimited_memory) {
+    if (PrintContainerInfo) {
+      tty->print_cr("Memory Soft Limit is: Unlimited");
+    }
+    return (jlong)-1;
+  } else {
+    return (jlong)memsoftlimit;
+  }
+}
+
+/* memory_usage_in_bytes
+ *
+ * Return the amount of used memory for this process.
+ *
+ * return:
+ *    memory usage in bytes or
+ *    -1 for unlimited
+ *    OSCONTAINER_ERROR for not supported
+ */
+jlong OSContainer::memory_usage_in_bytes() {
+  GET_CONTAINER_INFO(jlong, memory, "/memory.usage_in_bytes",
+                     "Memory Usage is: " JLONG_FORMAT, JLONG_FORMAT, memusage);
+  return memusage;
+}
+
+/* memory_max_usage_in_bytes
+ *
+ * Return the maximum amount of used memory for this process.
+ *
+ * return:
+ *    max memory usage in bytes or
+ *    OSCONTAINER_ERROR for not supported
+ */
+jlong OSContainer::memory_max_usage_in_bytes() {
+  GET_CONTAINER_INFO(jlong, memory, "/memory.max_usage_in_bytes",
+                     "Maximum Memory Usage is: " JLONG_FORMAT, JLONG_FORMAT, memmaxusage);
+  return memmaxusage;
+}
+
+/* active_processor_count
+ *
+ * Calculate an appropriate number of active processors for the
+ * VM to use based on these three inputs.
+ *
+ * cpu affinity
+ * cgroup cpu quota & cpu period
+ * cgroup cpu shares
+ *
+ * Algorithm:
+ *
+ * Determine the number of available CPUs from sched_getaffinity
+ *
+ * If user specified a quota (quota != -1), calculate the number of
+ * required CPUs by dividing quota by period.
+ *
+ * If shares are in effect (shares != -1), calculate the number
+ * of CPUs required for the shares by dividing the share value
+ * by PER_CPU_SHARES.
+ *
+ * All results of division are rounded up to the next whole number.
+ *
+ * If neither shares or quotas have been specified, return the
+ * number of active processors in the system.
+ *
+ * If both shares and quotas have been specified, the results are
+ * based on the flag PreferContainerQuotaForCPUCount.  If true,
+ * return the quota value.  If false return the smallest value
+ * between shares or quotas.
+ *
+ * If shares and/or quotas have been specified, the resulting number
+ * returned will never exceed the number of active processors.
+ *
+ * return:
+ *    number of CPUs
+ */
+int OSContainer::active_processor_count() {
+  int quota_count = 0, share_count = 0;
+  int cpu_count, limit_count;
+  int result;
+
+  cpu_count = limit_count = os::Linux::active_processor_count();
+  int quota  = cpu_quota();
+  int period = cpu_period();
+  int share  = cpu_shares();
+
+  if (quota > -1 && period > 0) {
+    quota_count = ceilf((float)quota / (float)period);
+    if (PrintContainerInfo) {
+      tty->print_cr("CPU Quota count based on quota/period: %d", quota_count);
+    }
+  }
+  if (share > -1) {
+    share_count = ceilf((float)share / (float)PER_CPU_SHARES);
+    if (PrintContainerInfo) {
+      tty->print_cr("CPU Share count based on shares: %d", share_count);
+    }
+  }
+
+  // If both shares and quotas are setup results depend
+  // on flag PreferContainerQuotaForCPUCount.
+  // If true, limit CPU count to quota
+  // If false, use minimum of shares and quotas
+  if (quota_count !=0 && share_count != 0) {
+    if (PreferContainerQuotaForCPUCount) {
+      limit_count = quota_count;
+    } else {
+      limit_count = MIN2(quota_count, share_count);
+    }
+  } else if (quota_count != 0) {
+    limit_count = quota_count;
+  } else if (share_count != 0) {
+    limit_count = share_count;
+  }
+
+  result = MIN2(cpu_count, limit_count);
+  if (PrintContainerInfo) {
+    tty->print_cr("OSContainer::active_processor_count: %d", result);
+  }
+  return result;
+}
+
+char * OSContainer::cpu_cpuset_cpus() {
+  GET_CONTAINER_INFO_CPTR(cptr, cpuset, "/cpuset.cpus",
+                     "cpuset.cpus is: %s", "%1023s", cpus, 1024);
+  return os::strdup(cpus);
+}
+
+char * OSContainer::cpu_cpuset_memory_nodes() {
+  GET_CONTAINER_INFO_CPTR(cptr, cpuset, "/cpuset.mems",
+                     "cpuset.mems is: %s", "%1023s", mems, 1024);
+  return os::strdup(mems);
+}
+
+/* cpu_quota
+ *
+ * Return the number of milliseconds per period
+ * process is guaranteed to run.
+ *
+ * return:
+ *    quota time in milliseconds
+ *    -1 for no quota
+ *    OSCONTAINER_ERROR for not supported
+ */
+int OSContainer::cpu_quota() {
+  GET_CONTAINER_INFO(int, cpu, "/cpu.cfs_quota_us",
+                     "CPU Quota is: %d", "%d", quota);
+  return quota;
+}
+
+int OSContainer::cpu_period() {
+  GET_CONTAINER_INFO(int, cpu, "/cpu.cfs_period_us",
+                     "CPU Period is: %d", "%d", period);
+  return period;
+}
+
+/* cpu_shares
+ *
+ * Return the amount of cpu shares available to the process
+ *
+ * return:
+ *    Share number (typically a number relative to 1024)
+ *                 (2048 typically expresses 2 CPUs worth of processing)
+ *    -1 for no share setup
+ *    OSCONTAINER_ERROR for not supported
+ */
+int OSContainer::cpu_shares() {
+  GET_CONTAINER_INFO(int, cpu, "/cpu.shares",
+                     "CPU Shares is: %d", "%d", shares);
+  // Convert 1024 to no shares setup
+  if (shares == 1024) return -1;
+
+  return shares;
+}
+
diff --git a/src/os/linux/vm/osContainer_linux.hpp b/src/os/linux/vm/osContainer_linux.hpp
new file mode 100644
index 0000000..3edeab7
--- /dev/null
+++ b/src/os/linux/vm/osContainer_linux.hpp
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+#ifndef OS_LINUX_VM_OSCONTAINER_LINUX_HPP
+#define OS_LINUX_VM_OSCONTAINER_LINUX_HPP
+
+#include "utilities/globalDefinitions.hpp"
+#include "utilities/macros.hpp"
+#include "memory/allocation.hpp"
+
+#define OSCONTAINER_ERROR (-2)
+
+class OSContainer: AllStatic {
+
+ private:
+  static bool   _is_initialized;
+  static bool   _is_containerized;
+
+ public:
+  static void init();
+  static inline bool is_containerized();
+  static const char * container_type();
+
+  static jlong memory_limit_in_bytes();
+  static jlong memory_and_swap_limit_in_bytes();
+  static jlong memory_soft_limit_in_bytes();
+  static jlong memory_usage_in_bytes();
+  static jlong memory_max_usage_in_bytes();
+
+  static int active_processor_count();
+
+  static char * cpu_cpuset_cpus();
+  static char * cpu_cpuset_memory_nodes();
+
+  static int cpu_quota();
+  static int cpu_period();
+
+  static int cpu_shares();
+
+};
+
+inline bool OSContainer::is_containerized() {
+  assert(_is_initialized, "OSContainer not initialized");
+  return _is_containerized;
+}
+
+#endif // OS_LINUX_VM_OSCONTAINER_LINUX_HPP
diff --git a/src/os/linux/vm/os_linux.cpp b/src/os/linux/vm/os_linux.cpp
index 044a70a..4d4dad0 100644
--- a/src/os/linux/vm/os_linux.cpp
+++ b/src/os/linux/vm/os_linux.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -37,6 +37,7 @@
 #include "mutex_linux.inline.hpp"
 #include "oops/oop.inline.hpp"
 #include "os_share_linux.hpp"
+#include "osContainer_linux.hpp"
 #include "prims/jniFastGetField.hpp"
 #include "prims/jvm.h"
 #include "prims/jvm_misc.hpp"
@@ -179,13 +180,62 @@
 julong os::Linux::available_memory() {
   // values in struct sysinfo are "unsigned long"
   struct sysinfo si;
-  sysinfo(&si);
+  julong avail_mem;
 
-  return (julong)si.freeram * si.mem_unit;
+  if (OSContainer::is_containerized()) {
+    jlong mem_limit, mem_usage;
+    if ((mem_limit = OSContainer::memory_limit_in_bytes()) < 1) {
+      if (PrintContainerInfo) {
+        tty->print_cr("container memory limit %s: " JLONG_FORMAT ", using host value",
+                       mem_limit == OSCONTAINER_ERROR ? "failed" : "unlimited", mem_limit);
+      }
+    }
+
+    if (mem_limit > 0 && (mem_usage = OSContainer::memory_usage_in_bytes()) < 1) {
+      if (PrintContainerInfo) {
+        tty->print_cr("container memory usage failed: " JLONG_FORMAT ", using host value", mem_usage);
+      }
+    }
+
+    if (mem_limit > 0 && mem_usage > 0 ) {
+      avail_mem = mem_limit > mem_usage ? (julong)mem_limit - (julong)mem_usage : 0;
+      if (PrintContainerInfo) {
+        tty->print_cr("available container memory: " JULONG_FORMAT, avail_mem);
+      }
+      return avail_mem;
+    }
+  }
+
+  sysinfo(&si);
+  avail_mem = (julong)si.freeram * si.mem_unit;
+  if (Verbose) {
+    tty->print_cr("available memory: " JULONG_FORMAT, avail_mem);
+  }
+  return avail_mem;
 }
 
 julong os::physical_memory() {
-  return Linux::physical_memory();
+  jlong phys_mem = 0;
+  if (OSContainer::is_containerized()) {
+    jlong mem_limit;
+    if ((mem_limit = OSContainer::memory_limit_in_bytes()) > 0) {
+      if (PrintContainerInfo) {
+        tty->print_cr("total container memory: " JLONG_FORMAT, mem_limit);
+      }
+      return mem_limit;
+    }
+
+    if (PrintContainerInfo) {
+      tty->print_cr("container memory limit %s: " JLONG_FORMAT ", using host value",
+                     mem_limit == OSCONTAINER_ERROR ? "failed" : "unlimited", mem_limit);
+    }
+  }
+
+  phys_mem = Linux::physical_memory();
+  if (Verbose) {
+    tty->print_cr("total system memory: " JLONG_FORMAT, phys_mem);
+  }
+  return phys_mem;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
@@ -674,6 +724,10 @@
   }
 }
 
+void os::Linux::expand_stack_to(address bottom) {
+  _expand_stack_to(bottom);
+}
+
 bool os::Linux::manually_expand_stack(JavaThread * t, address addr) {
   assert(t!=NULL, "just checking");
   assert(t->osthread()->expanding_stack(), "expand should be set");
@@ -946,8 +1000,8 @@
     }
   }
 
-  if (os::Linux::is_initial_thread()) {
-    // If current thread is initial thread, its stack is mapped on demand,
+  if (os::is_primordial_thread()) {
+    // If current thread is primordial thread, its stack is mapped on demand,
     // see notes about MAP_GROWSDOWN. Here we try to force kernel to map
     // the entire stack region to avoid SEGV in stack banging.
     // It is also useful to get around the heap-stack-gap problem on SuSE
@@ -1032,21 +1086,24 @@
 }
 
 //////////////////////////////////////////////////////////////////////////////
-// initial thread
+// primordial thread
 
-// Check if current thread is the initial thread, similar to Solaris thr_main.
-bool os::Linux::is_initial_thread(void) {
+// Check if current thread is the primordial thread, similar to Solaris thr_main.
+bool os::is_primordial_thread(void) {
   char dummy;
   // If called before init complete, thread stack bottom will be null.
   // Can be called if fatal error occurs before initialization.
-  if (initial_thread_stack_bottom() == NULL) return false;
-  assert(initial_thread_stack_bottom() != NULL &&
-         initial_thread_stack_size()   != 0,
-         "os::init did not locate initial thread's stack region");
-  if ((address)&dummy >= initial_thread_stack_bottom() &&
-      (address)&dummy < initial_thread_stack_bottom() + initial_thread_stack_size())
+  if (os::Linux::initial_thread_stack_bottom() == NULL) return false;
+  assert(os::Linux::initial_thread_stack_bottom() != NULL &&
+         os::Linux::initial_thread_stack_size()   != 0,
+         "os::init did not locate primordial thread's stack region");
+  if ((address)&dummy >= os::Linux::initial_thread_stack_bottom() &&
+      (address)&dummy < os::Linux::initial_thread_stack_bottom() +
+                        os::Linux::initial_thread_stack_size()) {
        return true;
-  else return false;
+  } else {
+       return false;
+  }
 }
 
 // Find the virtual memory area that contains addr
@@ -1073,7 +1130,7 @@
   return false;
 }
 
-// Locate initial thread stack. This special handling of initial thread stack
+// Locate primordial thread stack. This special handling of primordial thread stack
 // is needed because pthread_getattr_np() on most (all?) Linux distros returns
 // bogus value for the primordial process thread. While the launcher has created
 // the VM in a new thread since JDK 6, we still have to allow for the use of the
@@ -1097,7 +1154,10 @@
   // 6308388: a bug in ld.so will relocate its own .data section to the
   //   lower end of primordial stack; reduce ulimit -s value a little bit
   //   so we won't install guard page on ld.so's data section.
-  stack_size -= 2 * page_size();
+  //   But ensure we don't underflow the stack size - allow 1 page spare
+  if (stack_size >= (size_t)(3 * page_size())) {
+    stack_size -= 2 * page_size();
+  }
 
   // Try to figure out where the stack base (top) is. This is harder.
   //
@@ -1218,16 +1278,16 @@
 
       if (i != 28 - 2) {
          assert(false, "Bad conversion from /proc/self/stat");
-         // product mode - assume we are the initial thread, good luck in the
+         // product mode - assume we are the primordial thread, good luck in the
          // embedded case.
-         warning("Can't detect initial thread stack location - bad conversion");
+         warning("Can't detect primordial thread stack location - bad conversion");
          stack_start = (uintptr_t) &rlim;
       }
     } else {
       // For some reason we can't open /proc/self/stat (for example, running on
       // FreeBSD with a Linux emulator, or inside chroot), this should work for
       // most cases, so don't abort:
-      warning("Can't detect initial thread stack location - no /proc/self/stat");
+      warning("Can't detect primordial thread stack location - no /proc/self/stat");
       stack_start = (uintptr_t) &rlim;
     }
   }
@@ -1247,7 +1307,7 @@
     stack_top = (uintptr_t)high;
   } else {
     // failed, likely because /proc/self/maps does not exist
-    warning("Can't detect initial thread stack location - find_vma failed");
+    warning("Can't detect primordial thread stack location - find_vma failed");
     // best effort: stack_start is normally within a few pages below the real
     // stack top, use it as stack top, and reduce stack size so we won't put
     // guard page outside stack.
@@ -1900,7 +1960,7 @@
     {EM_SPARCV9,     EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"},
     {EM_PPC,         EM_PPC,     ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"},
 #if defined(VM_LITTLE_ENDIAN)
-    {EM_PPC64,       EM_PPC64,   ELFCLASS64, ELFDATA2LSB, (char*)"Power PC 64"},
+    {EM_PPC64,       EM_PPC64,   ELFCLASS64, ELFDATA2LSB, (char*)"Power PC 64 LE"},
 #else
     {EM_PPC64,       EM_PPC64,   ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"},
 #endif
@@ -2114,6 +2174,8 @@
   os::Posix::print_load_average(st);
 
   os::Linux::print_full_memory_info(st);
+
+  os::Linux::print_container_info(st);
 }
 
 // Try to identify popular distros.
@@ -2179,6 +2241,57 @@
    st->cr();
 }
 
+void os::Linux::print_container_info(outputStream* st) {
+if (!OSContainer::is_containerized()) {
+    return;
+  }
+
+  st->print("container (cgroup) information:\n");
+
+  const char *p_ct = OSContainer::container_type();
+  st->print("container_type: %s\n", p_ct != NULL ? p_ct : "failed");
+
+  char *p = OSContainer::cpu_cpuset_cpus();
+  st->print("cpu_cpuset_cpus: %s\n", p != NULL ? p : "failed");
+  free(p);
+
+  p = OSContainer::cpu_cpuset_memory_nodes();
+  st->print("cpu_memory_nodes: %s\n", p != NULL ? p : "failed");
+  free(p);
+
+  int i = OSContainer::active_processor_count();
+  if (i > 0) {
+    st->print("active_processor_count: %d\n", i);
+  } else {
+    st->print("active_processor_count: failed\n");
+  }
+
+  i = OSContainer::cpu_quota();
+  st->print("cpu_quota: %d\n", i);
+
+  i = OSContainer::cpu_period();
+  st->print("cpu_period: %d\n", i);
+
+  i = OSContainer::cpu_shares();
+  st->print("cpu_shares: %d\n", i);
+
+  jlong j = OSContainer::memory_limit_in_bytes();
+  st->print("memory_limit_in_bytes: " JLONG_FORMAT "\n", j);
+
+  j = OSContainer::memory_and_swap_limit_in_bytes();
+  st->print("memory_and_swap_limit_in_bytes: " JLONG_FORMAT "\n", j);
+
+  j = OSContainer::memory_soft_limit_in_bytes();
+  st->print("memory_soft_limit_in_bytes: " JLONG_FORMAT "\n", j);
+
+  j = OSContainer::OSContainer::memory_usage_in_bytes();
+  st->print("memory_usage_in_bytes: " JLONG_FORMAT "\n", j);
+
+  j = OSContainer::OSContainer::memory_max_usage_in_bytes();
+  st->print("memory_max_usage_in_bytes: " JLONG_FORMAT "\n", j);
+  st->cr();
+}
+
 void os::print_memory_info(outputStream* st) {
 
   st->print("Memory:");
@@ -3066,11 +3179,11 @@
 // where we're going to put our guard pages, truncate the mapping at
 // that point by munmap()ping it.  This ensures that when we later
 // munmap() the guard pages we don't leave a hole in the stack
-// mapping. This only affects the main/initial thread
+// mapping. This only affects the main/primordial thread
 
 bool os::pd_create_stack_guard_pages(char* addr, size_t size) {
 
-  if (os::Linux::is_initial_thread()) {
+  if (os::is_primordial_thread()) {
     // As we manually grow stack up to bottom inside create_attached_thread(),
     // it's likely that os::Linux::initial_thread_stack_bottom is mapped and
     // we don't need to do anything special.
@@ -3095,14 +3208,14 @@
 
 // If this is a growable mapping, remove the guard pages entirely by
 // munmap()ping them.  If not, just call uncommit_memory(). This only
-// affects the main/initial thread, but guard against future OS changes
-// It's safe to always unmap guard pages for initial thread because we
-// always place it right after end of the mapped region
+// affects the main/primordial thread, but guard against future OS changes.
+// It's safe to always unmap guard pages for primordial thread because we
+// always place it right after end of the mapped region.
 
 bool os::remove_stack_guard_pages(char* addr, size_t size) {
   uintptr_t stack_extent, stack_base;
 
-  if (os::Linux::is_initial_thread()) {
+  if (os::is_primordial_thread()) {
     return ::munmap(addr, size) == 0;
   }
 
@@ -4877,10 +4990,9 @@
   }
 }
 
-// this is called _before_ the most of global arguments have been parsed
+// this is called _before_ most of the global arguments have been parsed
 void os::init(void) {
   char dummy;   /* used to get a guess on initial stack address */
-//  first_hrtime = gethrtime();
 
   // With LinuxThreads the JavaMain thread pid (primordial thread)
   // is different than the pid of the java launcher thread.
@@ -4907,7 +5019,7 @@
 
   Linux::initialize_system_info();
 
-  // main_thread points to the aboriginal thread
+  // _main_thread points to the thread that created/loaded the JVM.
   Linux::_main_thread = pthread_self();
 
   Linux::clock_init();
@@ -4951,6 +5063,10 @@
   }
 }
 
+void os::pd_init_container_support() {
+  OSContainer::init();
+}
+
 // this is called _after_ the global arguments have been parsed
 jint os::init_2(void)
 {
@@ -5131,7 +5247,7 @@
 // sched_getaffinity gives an accurate answer as it accounts for cpusets.
 // If anything goes wrong we fallback to returning the number of online
 // processors - which can be greater than the number available to the process.
-int os::active_processor_count() {
+int os::Linux::active_processor_count() {
   cpu_set_t cpus;  // can represent at most 1024 (CPU_SETSIZE) processors
   int cpus_size = sizeof(cpu_set_t);
   int cpu_count = 0;
@@ -5149,10 +5265,48 @@
             "which may exceed available processors", strerror(errno), cpu_count);
   }
 
-  assert(cpu_count > 0 && cpu_count <= processor_count(), "sanity check");
+  assert(cpu_count > 0 && cpu_count <= os::processor_count(), "sanity check");
   return cpu_count;
 }
 
+// Determine the active processor count from one of
+// three different sources:
+//
+// 1. User option -XX:ActiveProcessorCount
+// 2. kernel os calls (sched_getaffinity or sysconf(_SC_NPROCESSORS_ONLN)
+// 3. extracted from cgroup cpu subsystem (shares and quotas)
+//
+// Option 1, if specified, will always override.
+// If the cgroup subsystem is active and configured, we
+// will return the min of the cgroup and option 2 results.
+// This is required since tools, such as numactl, that
+// alter cpu affinity do not update cgroup subsystem
+// cpuset configuration files.
+int os::active_processor_count() {
+  // User has overridden the number of active processors
+  if (ActiveProcessorCount > 0) {
+    if (PrintActiveCpus) {
+      tty->print_cr("active_processor_count: "
+                    "active processor count set by user : %d",
+                    ActiveProcessorCount);
+    }
+    return ActiveProcessorCount;
+  }
+
+  int active_cpus;
+  if (OSContainer::is_containerized()) {
+    active_cpus = OSContainer::active_processor_count();
+    if (PrintActiveCpus) {
+      tty->print_cr("active_processor_count: determined by OSContainer: %d",
+                     active_cpus);
+    }
+  } else {
+    active_cpus = os::Linux::active_processor_count();
+  }
+
+  return active_cpus;
+}
+
 void os::set_native_thread_name(const char *name) {
   // Not yet implemented.
   return;
diff --git a/src/os/linux/vm/os_linux.hpp b/src/os/linux/vm/os_linux.hpp
index c56983c..e207dcc 100644
--- a/src/os/linux/vm/os_linux.hpp
+++ b/src/os/linux/vm/os_linux.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -35,6 +35,7 @@
 
 class Linux {
   friend class os;
+  friend class OSContainer;
   friend class TestReserveMemorySpecial;
 
   // For signal-chaining
@@ -79,6 +80,9 @@
 
   static julong available_memory();
   static julong physical_memory() { return _physical_memory; }
+  static void set_physical_memory(julong phys_mem) { _physical_memory = phys_mem; }
+  static int active_processor_count();
+
   static void initialize_system_info();
 
   static int commit_memory_impl(char* addr, size_t bytes, bool exec);
@@ -116,6 +120,7 @@
   static bool release_memory_special_huge_tlbfs(char* base, size_t bytes);
 
   static void print_full_memory_info(outputStream* st);
+  static void print_container_info(outputStream* st);
   static void print_distro_info(outputStream* st);
   static void print_libversion_info(outputStream* st);
 
@@ -137,7 +142,6 @@
 
   static address   initial_thread_stack_bottom(void)                { return _initial_thread_stack_bottom; }
   static uintptr_t initial_thread_stack_size(void)                  { return _initial_thread_stack_size; }
-  static bool is_initial_thread(void);
 
   static int page_size(void)                                        { return _page_size; }
   static void set_page_size(int val)                                { _page_size = val; }
@@ -245,6 +249,8 @@
   static int safe_cond_timedwait(pthread_cond_t *_cond, pthread_mutex_t *_mutex, const struct timespec *_abstime);
 
 private:
+  static void expand_stack_to(address bottom);
+
   typedef int (*sched_getcpu_func_t)(void);
   typedef int (*numa_node_to_cpus_func_t)(int node, unsigned long *buffer, int bufferlen);
   typedef int (*numa_max_node_func_t)(void);
@@ -285,8 +291,8 @@
   static void set_numa_bitmask_isbitset(numa_bitmask_isbitset_func_t func) { _numa_bitmask_isbitset = func; }
   static void set_numa_distance(numa_distance_func_t func) { _numa_distance = func; }
   static void set_numa_all_nodes(unsigned long* ptr) { _numa_all_nodes = ptr; }
-  static void set_numa_all_nodes_ptr(struct bitmask **ptr) { _numa_all_nodes_ptr = *ptr; }
-  static void set_numa_nodes_ptr(struct bitmask **ptr) { _numa_nodes_ptr = *ptr; }
+  static void set_numa_all_nodes_ptr(struct bitmask **ptr) { _numa_all_nodes_ptr = (ptr == NULL ? NULL : *ptr); }
+  static void set_numa_nodes_ptr(struct bitmask **ptr) { _numa_nodes_ptr = (ptr == NULL ? NULL : *ptr); }
   static int sched_getcpu_syscall(void);
 public:
   static int sched_getcpu()  { return _sched_getcpu != NULL ? _sched_getcpu() : -1; }
@@ -330,6 +336,18 @@
   static bool isnode_in_existing_nodes(unsigned int n) {
     if (_numa_bitmask_isbitset != NULL && _numa_nodes_ptr != NULL) {
       return _numa_bitmask_isbitset(_numa_nodes_ptr, n);
+    } else if (_numa_bitmask_isbitset != NULL && _numa_all_nodes_ptr != NULL) {
+      // Not all libnuma API v2 implement numa_nodes_ptr, so it's not possible
+      // to trust the API version for checking its absence. On the other hand,
+      // numa_nodes_ptr found in libnuma 2.0.9 and above is the only way to get
+      // a complete view of all numa nodes in the system, hence numa_nodes_ptr
+      // is used to handle CPU and nodes on architectures (like PowerPC) where
+      // there can exist nodes with CPUs but no memory or vice-versa and the
+      // nodes may be non-contiguous. For most of the architectures, like
+      // x86_64, numa_node_ptr presents the same node set as found in
+      // numa_all_nodes_ptr so it's possible to use numa_all_nodes_ptr as a
+      // substitute.
+      return _numa_bitmask_isbitset(_numa_all_nodes_ptr, n);
     } else
       return 0;
   }
diff --git a/src/os/linux/vm/os_linux.inline.hpp b/src/os/linux/vm/os_linux.inline.hpp
index 10d56d8..fea10fa 100644
--- a/src/os/linux/vm/os_linux.inline.hpp
+++ b/src/os/linux/vm/os_linux.inline.hpp
@@ -114,8 +114,12 @@
   return ::ftruncate64(fd, length);
 }
 
+// readdir_r has been deprecated since glibc 2.24.
+// See https://sourceware.org/bugzilla/show_bug.cgi?id=19056 for more details.
+#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
 inline struct dirent* os::readdir(DIR* dirp, dirent *dbuf)
 {
+
   dirent* p;
   int status;
   assert(dirp != NULL, "just checking");
@@ -129,6 +133,7 @@
     return NULL;
   } else
     return p;
+
 }
 
 inline int os::closedir(DIR *dirp) {
diff --git a/src/os/linux/vm/perfMemory_linux.cpp b/src/os/linux/vm/perfMemory_linux.cpp
index 8510abb..4143f65 100644
--- a/src/os/linux/vm/perfMemory_linux.cpp
+++ b/src/os/linux/vm/perfMemory_linux.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -627,7 +627,7 @@
 // return the name of the user that owns the JVM indicated by the given vmid.
 //
 static char* get_user_name(int vmid, TRAPS) {
-  return get_user_name_slow(vmid, CHECK_NULL);
+  return get_user_name_slow(vmid, THREAD);
 }
 
 // return the file name of the backing store file for the named
diff --git a/src/os/posix/vm/os_posix.cpp b/src/os/posix/vm/os_posix.cpp
index d1bf84f..c301898 100644
--- a/src/os/posix/vm/os_posix.cpp
+++ b/src/os/posix/vm/os_posix.cpp
@@ -1,5 +1,5 @@
 /*
-* Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved.
+* Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -166,6 +166,16 @@
   return aligned_base;
 }
 
+int os::vsnprintf(char* buf, size_t len, const char* fmt, va_list args) {
+  int result = ::vsnprintf(buf, len, fmt, args);
+  // If an encoding error occurred (result < 0) then it's not clear
+  // whether the buffer is NUL terminated, so ensure it is.
+  if ((result < 0) && (len > 0)) {
+    buf[len - 1] = '\0';
+  }
+  return result;
+}
+
 void os::Posix::print_load_average(outputStream* st) {
   st->print("load average:");
   double loadavg[3];
diff --git a/src/os/solaris/vm/os_solaris.cpp b/src/os/solaris/vm/os_solaris.cpp
index 2b4e33c..4a786cf 100644
--- a/src/os/solaris/vm/os_solaris.cpp
+++ b/src/os/solaris/vm/os_solaris.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -200,17 +200,21 @@
   return st;
 }
 
-address os::current_stack_base() {
+bool os::is_primordial_thread(void) {
   int r = thr_main() ;
   guarantee (r == 0 || r == 1, "CR6501650 or CR6493689") ;
-  bool is_primordial_thread = r;
+  return r == 1;
+}
+
+address os::current_stack_base() {
+  bool _is_primordial_thread = is_primordial_thread();
 
   // Workaround 4352906, avoid calls to thr_stksegment by
   // thr_main after the first one (it looks like we trash
   // some data, causing the value for ss_sp to be incorrect).
-  if (!is_primordial_thread || os::Solaris::_main_stack_base == NULL) {
+  if (!_is_primordial_thread || os::Solaris::_main_stack_base == NULL) {
     stack_t st = get_stack_info();
-    if (is_primordial_thread) {
+    if (_is_primordial_thread) {
       // cache initial value of stack base
       os::Solaris::_main_stack_base = (address)st.ss_sp;
     }
@@ -224,9 +228,7 @@
 size_t os::current_stack_size() {
   size_t size;
 
-  int r = thr_main() ;
-  guarantee (r == 0 || r == 1, "CR6501650 or CR6493689") ;
-  if(!r) {
+  if (!is_primordial_thread()) {
     size = get_stack_info().ss_size;
   } else {
     struct rlimit limits;
@@ -357,6 +359,16 @@
 }
 
 int os::active_processor_count() {
+  // User has overridden the number of active processors
+  if (ActiveProcessorCount > 0) {
+    if (Verbose) {
+      tty->print_cr("active_processor_count: "
+                    "active processor count set by user : %d",
+                     ActiveProcessorCount);
+    }
+    return ActiveProcessorCount;
+  }
+
   int online_cpus = sysconf(_SC_NPROCESSORS_ONLN);
   pid_t pid = getpid();
   psetid_t pset = PS_NONE;
@@ -1277,9 +1289,7 @@
 
 // First crack at OS-specific initialization, from inside the new thread.
 void os::initialize_thread(Thread* thr) {
-  int r = thr_main() ;
-  guarantee (r == 0 || r == 1, "CR6501650 or CR6493689") ;
-  if (r) {
+  if (is_primordial_thread()) {
     JavaThread* jt = (JavaThread *)thr;
     assert(jt != NULL,"Sanity check");
     size_t stack_size;
@@ -4904,6 +4914,7 @@
   // (Solaris only) this switches to calls that actually do locking.
   ThreadCritical::initialize();
 
+  // main_thread points to the thread that created/loaded the JVM.
   main_thread = thr_self();
 
   // Constant minimum stack size allowed. It must be at least
diff --git a/src/os/solaris/vm/perfMemory_solaris.cpp b/src/os/solaris/vm/perfMemory_solaris.cpp
index a90623e..7c6f616 100644
--- a/src/os/solaris/vm/perfMemory_solaris.cpp
+++ b/src/os/solaris/vm/perfMemory_solaris.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -666,7 +666,7 @@
   // since the structured procfs and old procfs interfaces can't be
   // mixed, we attempt to find the file through a directory search.
 
-  return get_user_name_slow(vmid, CHECK_NULL);
+  return get_user_name_slow(vmid, THREAD);
 }
 
 // return the file name of the backing store file for the named
diff --git a/src/os/windows/vm/os_windows.cpp b/src/os/windows/vm/os_windows.cpp
index 44d89a2..4f550c9 100644
--- a/src/os/windows/vm/os_windows.cpp
+++ b/src/os/windows/vm/os_windows.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -716,6 +716,16 @@
 #endif
 
 int os::active_processor_count() {
+  // User has overridden the number of active processors
+  if (ActiveProcessorCount > 0) {
+    if (PrintActiveCpus) {
+      tty->print_cr("active_processor_count: "
+                    "active processor count set by user : %d",
+                     ActiveProcessorCount);
+    }
+    return ActiveProcessorCount;
+  }
+
   DWORD_PTR lpProcessAffinityMask = 0;
   DWORD_PTR lpSystemAffinityMask = 0;
   int proc_count = processor_count();
@@ -1827,6 +1837,42 @@
   st->cr();
 }
 
+
+int os::vsnprintf(char* buf, size_t len, const char* fmt, va_list args) {
+#if _MSC_VER >= 1900
+  // Starting with Visual Studio 2015, vsnprint is C99 compliant.
+  int result = ::vsnprintf(buf, len, fmt, args);
+  // If an encoding error occurred (result < 0) then it's not clear
+  // whether the buffer is NUL terminated, so ensure it is.
+  if ((result < 0) && (len > 0)) {
+    buf[len - 1] = '\0';
+  }
+  return result;
+#else
+  // Before Visual Studio 2015, vsnprintf is not C99 compliant, so use
+  // _vsnprintf, whose behavior seems to be *mostly* consistent across
+  // versions.  However, when len == 0, avoid _vsnprintf too, and just
+  // go straight to _vscprintf.  The output is going to be truncated in
+  // that case, except in the unusual case of empty output.  More
+  // importantly, the documentation for various versions of Visual Studio
+  // are inconsistent about the behavior of _vsnprintf when len == 0,
+  // including it possibly being an error.
+  int result = -1;
+  if (len > 0) {
+    result = _vsnprintf(buf, len, fmt, args);
+    // If output (including NUL terminator) is truncated, the buffer
+    // won't be NUL terminated.  Add the trailing NUL specified by C99.
+    if ((result < 0) || (result >= (int) len)) {
+      buf[len - 1] = '\0';
+    }
+  }
+  if (result < 0) {
+    result = _vscprintf(fmt, args);
+  }
+  return result;
+#endif // _MSC_VER dispatch
+}
+
 void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) {
   // do nothing
 }
@@ -2187,13 +2233,6 @@
 // Windows Vista/2008 heap corruption check
 #define EXCEPTION_HEAP_CORRUPTION        0xC0000374
 
-#define def_excpt(val) #val, val
-
-struct siglabel {
-  char *name;
-  int   number;
-};
-
 // All Visual C++ exceptions thrown from code generated by the Microsoft Visual
 // C++ compiler contain this error code. Because this is a compiler-generated
 // error, the code is not listed in the Win32 API header files.
@@ -2203,8 +2242,9 @@
 
 #define EXCEPTION_UNCAUGHT_CXX_EXCEPTION    0xE06D7363
 
+#define def_excpt(val) { #val, (val) }
 
-struct siglabel exceptlabels[] = {
+static const struct { char* name; uint number; } exceptlabels[] = {
     def_excpt(EXCEPTION_ACCESS_VIOLATION),
     def_excpt(EXCEPTION_DATATYPE_MISALIGNMENT),
     def_excpt(EXCEPTION_BREAKPOINT),
@@ -2229,16 +2269,16 @@
     def_excpt(EXCEPTION_GUARD_PAGE),
     def_excpt(EXCEPTION_INVALID_HANDLE),
     def_excpt(EXCEPTION_UNCAUGHT_CXX_EXCEPTION),
-    def_excpt(EXCEPTION_HEAP_CORRUPTION),
+    def_excpt(EXCEPTION_HEAP_CORRUPTION)
 #ifdef _M_IA64
-    def_excpt(EXCEPTION_REG_NAT_CONSUMPTION),
+    , def_excpt(EXCEPTION_REG_NAT_CONSUMPTION)
 #endif
-    NULL, 0
 };
 
 const char* os::exception_name(int exception_code, char *buf, size_t size) {
-  for (int i = 0; exceptlabels[i].name != NULL; i++) {
-    if (exceptlabels[i].number == exception_code) {
+  uint code = static_cast<uint>(exception_code);
+  for (uint i = 0; i < ARRAY_SIZE(exceptlabels); ++i) {
+    if (exceptlabels[i].number == code) {
        jio_snprintf(buf, size, "%s", exceptlabels[i].name);
        return buf;
     }
@@ -2261,9 +2301,9 @@
   assert((pc[1] & ~0x7) == 0xF8, "cannot handle non-register operands");
   assert(ctx->Rax == min_jint, "unexpected idiv exception");
   // set correct result values and continue after idiv instruction
-  ctx->Rip = (DWORD)pc + 2;        // idiv reg, reg  is 2 bytes
-  ctx->Rax = (DWORD)min_jint;      // result
-  ctx->Rdx = (DWORD)0;             // remainder
+  ctx->Rip = (DWORD64)pc + 2;        // idiv reg, reg  is 2 bytes
+  ctx->Rax = (DWORD64)min_jint;      // result
+  ctx->Rdx = (DWORD64)0;             // remainder
   // Continue the execution
   #else
   PCONTEXT ctx = exceptionInfo->ContextRecord;
@@ -5782,7 +5822,7 @@
   char* result = os::reserve_memory_special(large_allocation_size, os::large_page_size(), NULL, false);
   if (result == NULL) {
     if (VerboseInternalVMTests) {
-      gclog_or_tty->print("Failed to allocate control block with size "SIZE_FORMAT". Skipping remainder of test.",
+      gclog_or_tty->print("Failed to allocate control block with size " SIZE_FORMAT ". Skipping remainder of test.",
         large_allocation_size);
     }
   } else {
@@ -5795,7 +5835,7 @@
     char* actual_location = os::reserve_memory_special(expected_allocation_size, os::large_page_size(), expected_location, false);
     if (actual_location == NULL) {
       if (VerboseInternalVMTests) {
-        gclog_or_tty->print("Failed to allocate any memory at "PTR_FORMAT" size "SIZE_FORMAT". Skipping remainder of test.",
+        gclog_or_tty->print("Failed to allocate any memory at " PTR_FORMAT " size " SIZE_FORMAT ". Skipping remainder of test.",
           expected_location, large_allocation_size);
       }
     } else {
@@ -5803,7 +5843,7 @@
       os::release_memory_special(actual_location, expected_allocation_size);
       // only now check, after releasing any memory to avoid any leaks.
       assert(actual_location == expected_location,
-        err_msg("Failed to allocate memory at requested location "PTR_FORMAT" of size "SIZE_FORMAT", is "PTR_FORMAT" instead",
+        err_msg("Failed to allocate memory at requested location " PTR_FORMAT " of size " SIZE_FORMAT ", is " PTR_FORMAT " instead",
           expected_location, expected_allocation_size, actual_location));
     }
   }
diff --git a/src/os_cpu/linux_ppc/vm/os_linux_ppc.cpp b/src/os_cpu/linux_ppc/vm/os_linux_ppc.cpp
index 1192f55..0816696 100644
--- a/src/os_cpu/linux_ppc/vm/os_linux_ppc.cpp
+++ b/src/os_cpu/linux_ppc/vm/os_linux_ppc.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * Copyright 2012, 2015 SAP AG. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -510,8 +510,8 @@
 //    pthread_attr_getstack()
 
 static void current_stack_region(address * bottom, size_t * size) {
-  if (os::Linux::is_initial_thread()) {
-     // initial thread needs special handling because pthread_getattr_np()
+  if (os::is_primordial_thread()) {
+     // primordial thread needs special handling because pthread_getattr_np()
      // may return bogus value.
     *bottom = os::Linux::initial_thread_stack_bottom();
     *size   = os::Linux::initial_thread_stack_size();
diff --git a/src/os_cpu/linux_sparc/vm/os_linux_sparc.cpp b/src/os_cpu/linux_sparc/vm/os_linux_sparc.cpp
index f8165a1..2a07de4 100644
--- a/src/os_cpu/linux_sparc/vm/os_linux_sparc.cpp
+++ b/src/os_cpu/linux_sparc/vm/os_linux_sparc.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -162,8 +162,8 @@
 }
 
 static void current_stack_region(address* bottom, size_t* size) {
-  if (os::Linux::is_initial_thread()) {
-    // initial thread needs special handling because pthread_getattr_np()
+  if (os::is_primordial_thread()) {
+    // primordial thread needs special handling because pthread_getattr_np()
     // may return bogus value.
     *bottom = os::Linux::initial_thread_stack_bottom();
     *size = os::Linux::initial_thread_stack_size();
diff --git a/src/os_cpu/linux_x86/vm/os_linux_x86.cpp b/src/os_cpu/linux_x86/vm/os_linux_x86.cpp
index fb96738..e963daa 100644
--- a/src/os_cpu/linux_x86/vm/os_linux_x86.cpp
+++ b/src/os_cpu/linux_x86/vm/os_linux_x86.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -541,6 +541,7 @@
   err.report_and_die();
 
   ShouldNotReachHere();
+  return false;
 }
 
 void os::Linux::init_thread_fpu_state(void) {
@@ -712,8 +713,8 @@
 //    pthread_attr_getstack()
 
 static void current_stack_region(address * bottom, size_t * size) {
-  if (os::Linux::is_initial_thread()) {
-     // initial thread needs special handling because pthread_getattr_np()
+  if (os::is_primordial_thread()) {
+     // primordial thread needs special handling because pthread_getattr_np()
      // may return bogus value.
      *bottom = os::Linux::initial_thread_stack_bottom();
      *size   = os::Linux::initial_thread_stack_size();
@@ -892,6 +893,27 @@
 void os::workaround_expand_exec_shield_cs_limit() {
 #if defined(IA32)
   size_t page_size = os::vm_page_size();
+
+  /*
+   * JDK-8197429
+   *
+   * Expand the stack mapping to the end of the initial stack before
+   * attempting to install the codebuf.  This is needed because newer
+   * Linux kernels impose a distance of a megabyte between stack
+   * memory and other memory regions.  If we try to install the
+   * codebuf before expanding the stack the installation will appear
+   * to succeed but we'll get a segfault later if we expand the stack
+   * in Java code.
+   *
+   */
+  if (os::is_primordial_thread()) {
+    address limit = Linux::initial_thread_stack_bottom();
+    if (! DisablePrimordialThreadGuardPages) {
+      limit += (StackYellowPages + StackRedPages) * page_size;
+    }
+    os::Linux::expand_stack_to(limit);
+  }
+
   /*
    * Take the highest VA the OS will give us and exec
    *
@@ -910,6 +932,16 @@
   char* hint = (char*) (Linux::initial_thread_stack_bottom() -
                         ((StackYellowPages + StackRedPages + 1) * page_size));
   char* codebuf = os::attempt_reserve_memory_at(page_size, hint);
+
+  if (codebuf == NULL) {
+    // JDK-8197429: There may be a stack gap of one megabyte between
+    // the limit of the stack and the nearest memory region: this is a
+    // Linux kernel workaround for CVE-2017-1000364.  If we failed to
+    // map our codebuf, try again at an address one megabyte lower.
+    hint -= 1 * M;
+    codebuf = os::attempt_reserve_memory_at(page_size, hint);
+  }
+
   if ( (codebuf == NULL) || (!os::commit_memory(codebuf, page_size, true)) ) {
     return; // No matter, we tried, best effort.
   }
diff --git a/src/os_cpu/linux_zero/vm/os_linux_zero.cpp b/src/os_cpu/linux_zero/vm/os_linux_zero.cpp
index 1d069c6..d22ea11 100644
--- a/src/os_cpu/linux_zero/vm/os_linux_zero.cpp
+++ b/src/os_cpu/linux_zero/vm/os_linux_zero.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
  * Copyright 2007, 2008, 2009, 2010 Red Hat, Inc.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -360,7 +360,7 @@
   // The initial thread has a growable stack, and the size reported
   // by pthread_attr_getstack is the maximum size it could possibly
   // be given what currently mapped.  This can be huge, so we cap it.
-  if (os::Linux::is_initial_thread()) {
+  if (os::is_primordial_thread()) {
     stack_bytes = stack_top - stack_bottom;
 
     if (stack_bytes > JavaThread::stack_size_at_create())
@@ -408,6 +408,7 @@
 
 extern "C" {
   int SpinPause() {
+    return 0; // Shouldn't matter.
   }
 
 
diff --git a/src/os_cpu/linux_zero/vm/os_linux_zero.hpp b/src/os_cpu/linux_zero/vm/os_linux_zero.hpp
index 7b7e367..e1a80d7 100644
--- a/src/os_cpu/linux_zero/vm/os_linux_zero.hpp
+++ b/src/os_cpu/linux_zero/vm/os_linux_zero.hpp
@@ -36,18 +36,34 @@
 
   // Atomically copy 64 bits of data
   static void atomic_copy64(volatile void *src, volatile void *dst) {
-#if defined(PPC32)
+#if defined(PPC32) && !defined(__SPE__)
     double tmp;
-    asm volatile ("lfd  %0, 0(%1)\n"
-                  "stfd %0, 0(%2)\n"
-                  : "=f"(tmp)
-                  : "b"(src), "b"(dst));
+    asm volatile ("lfd  %0, %2\n"
+                  "stfd %0, %1\n"
+                  : "=&f"(tmp), "=Q"(*(volatile double*)dst)
+                  : "Q"(*(volatile double*)src));
+#elif defined(PPC32) && defined(__SPE__)
+    long tmp;
+    asm volatile ("evldd  %0, %2\n"
+                  "evstdd %0, %1\n"
+                  : "=&r"(tmp), "=Q"(*(volatile long*)dst)
+                  : "Q"(*(volatile long*)src));
 #elif defined(S390) && !defined(_LP64)
     double tmp;
-    asm volatile ("ld  %0, 0(%1)\n"
-                  "std %0, 0(%2)\n"
+    asm volatile ("ld  %0, %2\n"
+                  "std %0, %1\n"
+                  : "=&f"(tmp), "=Q"(*(volatile double*)dst)
+                  : "Q"(*(volatile double*)src));
+#elif defined(__ARM_ARCH_7A__)
+    // Note that a ldrexd + clrex combination is only needed for
+    // correctness on the OS level (context-switches). In this
+    // case, clrex *may* be beneficial for performance. For now
+    // don't bother with clrex as this is Zero.
+    jlong tmp;
+    asm volatile ("ldrexd  %0, [%1]\n"
                   : "=r"(tmp)
-                  : "a"(src), "a"(dst));
+                  : "r"(src), "m"(src));
+    *(jlong *) dst = tmp;
 #else
     *(jlong *) dst = *(jlong *) src;
 #endif
diff --git a/src/os_cpu/windows_x86/vm/os_windows_x86.cpp b/src/os_cpu/windows_x86/vm/os_windows_x86.cpp
index 1c3cd19..c5b84b5 100644
--- a/src/os_cpu/windows_x86/vm/os_windows_x86.cpp
+++ b/src/os_cpu/windows_x86/vm/os_windows_x86.cpp
@@ -454,11 +454,18 @@
 // Returns an estimate of the current stack pointer. Result must be guaranteed
 // to point into the calling threads stack, and be no lower than the current
 // stack pointer.
+#if defined(_MSC_VER) && _MSC_VER >= 1900
+// warning C4172: returning address of local variable or temporary: dummy
+#pragma warning(disable: 4172)
+#endif
 address os::current_stack_pointer() {
   int dummy;
   address sp = (address)&dummy;
   return sp;
 }
+#if defined(_MSC_VER) && _MSC_VER >= 1900
+#pragma warning(default: 4172)
+#endif
 #else
 // Returns the current stack pointer. Accurate value needed for
 // os::verify_stack_alignment().
diff --git a/src/share/tools/hsdis/Makefile b/src/share/tools/hsdis/Makefile
index 2fb0821..0d1b608 100644
--- a/src/share/tools/hsdis/Makefile
+++ b/src/share/tools/hsdis/Makefile
@@ -2,19 +2,41 @@
 # Copyright (c) 2008, 2013, 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.
+# The Universal Permissive License (UPL), Version 1.0
 #
-# 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).
+# Subject to the condition set forth below, permission is hereby granted to
+# any person obtaining a copy of this software, associated documentation
+# and/or data (collectively the "Software"), free of charge and under any
+# and all copyright rights in the Software, and any and all patent rights
+# owned or freely licensable by each licensor hereunder covering either (i)
+# the unmodified Software as contributed to or provided by such licensor,
+# or (ii) the Larger Works (as defined below), to deal in both
 #
-# 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.
+# (a) the Software, and
+#
+# (b) any piece of software and/or hardware listed in the lrgrwrks.txt file
+# if one is included with the Software (each a "Larger Work" to which the
+# Software is contributed by such licensors),
+#
+# without restriction, including without limitation the rights to copy,
+# create derivative works of, display, perform, and distribute the Software
+# and make, use, sell, offer for sale, import, export, have made, and have
+# sold the Software and the Larger Work(s), and to sublicense the foregoing
+# rights on either these or other terms.
+#
+# This license is subject to the following condition:
+#
+# The above copyright notice and either this complete permission notice or
+# at a minimum a reference to the UPL must be included in all copies or
+# substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+# USE OR OTHER DEALINGS IN THE SOFTWARE.
 #
 # Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 # or visit www.oracle.com if you need additional information or have any
@@ -75,6 +97,7 @@
 CFLAGS/sparcv9	+= -m64
 CFLAGS/amd64	+= -m64
 CFLAGS/ppc64	+= -m64
+CFLAGS/ppc64le  += -m64 -DABI_ELFv2
 else
 ARCH=$(ARCH1:amd64=i386)
 CFLAGS/i386	+= -m32
diff --git a/src/share/tools/hsdis/README b/src/share/tools/hsdis/README
index dbebc54..2addff6 100644
--- a/src/share/tools/hsdis/README
+++ b/src/share/tools/hsdis/README
@@ -1,20 +1,42 @@
-Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
+Copyright (c) 2008, 2018, Oracle and/or its affiliates. All rights reserved.
 DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   
-This code is free software; you can redistribute it and/or modify it
-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.
-  
+The Universal Permissive License (UPL), Version 1.0
+
+Subject to the condition set forth below, permission is hereby granted to
+any person obtaining a copy of this software, associated documentation
+and/or data (collectively the "Software"), free of charge and under any
+and all copyright rights in the Software, and any and all patent rights
+owned or freely licensable by each licensor hereunder covering either (i)
+the unmodified Software as contributed to or provided by such licensor,
+or (ii) the Larger Works (as defined below), to deal in both
+
+(a) the Software, and
+
+(b) any piece of software and/or hardware listed in the lrgrwrks.txt file
+if one is included with the Software (each a "Larger Work" to which the
+Software is contributed by such licensors),
+
+without restriction, including without limitation the rights to copy,
+create derivative works of, display, perform, and distribute the Software
+and make, use, sell, offer for sale, import, export, have made, and have
+sold the Software and the Larger Work(s), and to sublicense the foregoing
+rights on either these or other terms.
+
+This license is subject to the following condition:
+
+The above copyright notice and either this complete permission notice or
+at a minimum a reference to the UPL must be included in all copies or
+substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+USE OR OTHER DEALINGS IN THE SOFTWARE.
+
 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.
@@ -32,11 +54,12 @@
 
 * Building
 
-To build this project you a copy of GNU binutils to build against.  It
-is known to work with binutils 2.17 and binutils 2.19.1.  Download a
+To build this project you need a copy of GNU binutils to build against.
+It is known to work with binutils 2.29.1, 2.30, and 2.31.1. Building
+against versions older than 2.29 is no longer supported. Download a
 copy of the software from http://directory.fsf.org/project/binutils or
-one of it's mirrors.  Builds targetting windows should use at least
-2.19 and currently requires the use of a cross compiler.
+one of its mirrors.  Builds targetting windows currently require the
+use of a cross compiler.
 
 Binutils should be configured with the '--disable-nls' flag to disable
 Native Language Support, otherwise you might get an "undefined
@@ -85,9 +108,9 @@
 the makefile what prefix to use to find the mingw tools by using
 MINGW=.  For example:
 
-make MINGW=i586-mingw32msvc BINTUILS=build/binutils-2.19.1
+make MINGW=i586-mingw32msvc BINUTILS=build/binutils-2.31.1
 
-will build the Win32 cross compiled version of hsdis based on 2.19.1.
+will build the Win32 cross compiled version of hsdis based on 2.31.1.
 
 * Installing
 
diff --git a/src/share/tools/hsdis/hsdis-demo.c b/src/share/tools/hsdis/hsdis-demo.c
index b9586ee..0ab3018 100644
--- a/src/share/tools/hsdis/hsdis-demo.c
+++ b/src/share/tools/hsdis/hsdis-demo.c
@@ -2,19 +2,41 @@
  * Copyright (c) 2008, 2012, 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.
+ * The Universal Permissive License (UPL), Version 1.0
  *
- * 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).
+ * Subject to the condition set forth below, permission is hereby granted to
+ * any person obtaining a copy of this software, associated documentation
+ * and/or data (collectively the "Software"), free of charge and under any
+ * and all copyright rights in the Software, and any and all patent rights
+ * owned or freely licensable by each licensor hereunder covering either (i)
+ * the unmodified Software as contributed to or provided by such licensor,
+ * or (ii) the Larger Works (as defined below), to deal in both
  *
- * 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.
+ * (a) the Software, and
+ *
+ * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file
+ * if one is included with the Software (each a "Larger Work" to which the
+ * Software is contributed by such licensors),
+ *
+ * without restriction, including without limitation the rights to copy,
+ * create derivative works of, display, perform, and distribute the Software
+ * and make, use, sell, offer for sale, import, export, have made, and have
+ * sold the Software and the Larger Work(s), and to sublicense the foregoing
+ * rights on either these or other terms.
+ *
+ * This license is subject to the following condition:
+ *
+ * The above copyright notice and either this complete permission notice or
+ * at a minimum a reference to the UPL must be included in all copies or
+ * substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+ * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+ * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+ * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+ * USE OR OTHER DEALINGS IN THE SOFTWARE.
  *
  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  * or visit www.oracle.com if you need additional information or have any
@@ -66,7 +88,7 @@
   printf("...And now for something completely different:\n");
   void *start = (void*) &main;
   void *end = (void*) &end_of_file;
-#if defined(__ia64) || defined(__powerpc__)
+#if defined(__ia64) || (defined(__powerpc__) && !defined(ABI_ELFv2))
   /* On IA64 and PPC function pointers are pointers to function descriptors */
   start = *((void**)start);
   end = *((void**)end);
diff --git a/src/share/tools/hsdis/hsdis.c b/src/share/tools/hsdis/hsdis.c
index 268084d..7bef104 100644
--- a/src/share/tools/hsdis/hsdis.c
+++ b/src/share/tools/hsdis/hsdis.c
@@ -1,20 +1,42 @@
 /*
- * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
+ * The Universal Permissive License (UPL), Version 1.0
  *
- * 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).
+ * Subject to the condition set forth below, permission is hereby granted to
+ * any person obtaining a copy of this software, associated documentation
+ * and/or data (collectively the "Software"), free of charge and under any
+ * and all copyright rights in the Software, and any and all patent rights
+ * owned or freely licensable by each licensor hereunder covering either (i)
+ * the unmodified Software as contributed to or provided by such licensor,
+ * or (ii) the Larger Works (as defined below), to deal in both
  *
- * 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.
+ * (a) the Software, and
+ *
+ * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file
+ * if one is included with the Software (each a "Larger Work" to which the
+ * Software is contributed by such licensors),
+ *
+ * without restriction, including without limitation the rights to copy,
+ * create derivative works of, display, perform, and distribute the Software
+ * and make, use, sell, offer for sale, import, export, have made, and have
+ * sold the Software and the Larger Work(s), and to sublicense the foregoing
+ * rights on either these or other terms.
+ *
+ * This license is subject to the following condition:
+ *
+ * The above copyright notice and either this complete permission notice or
+ * at a minimum a reference to the UPL must be included in all copies or
+ * substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+ * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+ * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+ * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+ * USE OR OTHER DEALINGS IN THE SOFTWARE.
  *
  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  * or visit www.oracle.com if you need additional information or have any
@@ -28,12 +50,15 @@
 */
 
 #include <config.h> /* required by bfd.h */
-#include <libiberty.h>
-#include <bfd.h>
-#include <dis-asm.h>
+#include <errno.h>
 #include <inttypes.h>
 #include <string.h>
-#include <errno.h>
+
+#include <libiberty.h>
+#include <bfd.h>
+#include <bfdver.h>
+#include <dis-asm.h>
+
 #include "hsdis.h"
 
 #ifndef bool
@@ -312,7 +337,10 @@
 
   /* Finish linking together the various callback blocks. */
   app_data->dinfo.application_data = (void*) app_data;
-  app_data->dfn = disassembler(native_bfd);
+  app_data->dfn = disassembler(bfd_get_arch(native_bfd),
+                               bfd_big_endian(native_bfd),
+                               bfd_get_mach(native_bfd),
+                               native_bfd);
   app_data->dinfo.print_address_func = hsdis_print_address_func;
   app_data->dinfo.read_memory_func = hsdis_read_memory_func;
 
@@ -460,7 +488,7 @@
 #ifdef LIBARCH_sparcv9
   res = "sparc:v9b";
 #endif
-#ifdef LIBARCH_ppc64
+#if defined(LIBARCH_ppc64) || defined(LIBARCH_ppc64le)
   res = "powerpc:common64";
 #endif
   if (res == NULL)
diff --git a/src/share/tools/hsdis/hsdis.h b/src/share/tools/hsdis/hsdis.h
index ca712e6..a6b45a5 100644
--- a/src/share/tools/hsdis/hsdis.h
+++ b/src/share/tools/hsdis/hsdis.h
@@ -2,19 +2,41 @@
  * Copyright (c) 2008, 2012, 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.
+ * The Universal Permissive License (UPL), Version 1.0
  *
- * 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).
+ * Subject to the condition set forth below, permission is hereby granted to
+ * any person obtaining a copy of this software, associated documentation
+ * and/or data (collectively the "Software"), free of charge and under any
+ * and all copyright rights in the Software, and any and all patent rights
+ * owned or freely licensable by each licensor hereunder covering either (i)
+ * the unmodified Software as contributed to or provided by such licensor,
+ * or (ii) the Larger Works (as defined below), to deal in both
  *
- * 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.
+ * (a) the Software, and
+ *
+ * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file
+ * if one is included with the Software (each a "Larger Work" to which the
+ * Software is contributed by such licensors),
+ *
+ * without restriction, including without limitation the rights to copy,
+ * create derivative works of, display, perform, and distribute the Software
+ * and make, use, sell, offer for sale, import, export, have made, and have
+ * sold the Software and the Larger Work(s), and to sublicense the foregoing
+ * rights on either these or other terms.
+ *
+ * This license is subject to the following condition:
+ *
+ * The above copyright notice and either this complete permission notice or
+ * at a minimum a reference to the UPL must be included in all copies or
+ * substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+ * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+ * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+ * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+ * USE OR OTHER DEALINGS IN THE SOFTWARE.
  *
  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  * or visit www.oracle.com if you need additional information or have any
diff --git a/src/share/vm/adlc/arena.hpp b/src/share/vm/adlc/arena.hpp
index 7f09511..b98bf2a 100644
--- a/src/share/vm/adlc/arena.hpp
+++ b/src/share/vm/adlc/arena.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -69,6 +69,11 @@
 //------------------------------Chunk------------------------------------------
 // Linked list of raw memory chunks
 class Chunk: public CHeapObj {
+ private:
+  // This ordinary operator delete is needed even though not used, so the
+  // below two-argument operator delete will be treated as a placement
+  // delete rather than an ordinary sized delete; see C++14 3.7.4.2/p2.
+  void operator delete(void* p);
  public:
   void* operator new(size_t size, size_t length) throw();
   void  operator delete(void* p, size_t length);
diff --git a/src/share/vm/adlc/output_c.cpp b/src/share/vm/adlc/output_c.cpp
index f53dbd5..b376663 100644
--- a/src/share/vm/adlc/output_c.cpp
+++ b/src/share/vm/adlc/output_c.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -4177,11 +4177,11 @@
   fprintf(fp_cpp,"%s\n", _frame->_c_calling_convention);
   fprintf(fp_cpp,"}\n\n");
   // Java Return Value Location
-  fprintf(fp_cpp,"OptoRegPair Matcher::return_value(int ideal_reg, bool is_outgoing) {\n");
+  fprintf(fp_cpp,"OptoRegPair Matcher::return_value(uint ideal_reg, bool is_outgoing) {\n");
   fprintf(fp_cpp,"%s\n", _frame->_return_value);
   fprintf(fp_cpp,"}\n\n");
   // Native Return Value Location
-  fprintf(fp_cpp,"OptoRegPair Matcher::c_return_value(int ideal_reg, bool is_outgoing) {\n");
+  fprintf(fp_cpp,"OptoRegPair Matcher::c_return_value(uint ideal_reg, bool is_outgoing) {\n");
   fprintf(fp_cpp,"%s\n", _frame->_c_return_value);
   fprintf(fp_cpp,"}\n\n");
 
diff --git a/src/share/vm/asm/assembler.hpp b/src/share/vm/asm/assembler.hpp
index ec8ec5e..ac39e6a 100644
--- a/src/share/vm/asm/assembler.hpp
+++ b/src/share/vm/asm/assembler.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -169,6 +169,14 @@
   Label() {
     init();
   }
+
+  ~Label() {
+    assert(is_bound() || is_unused(), "Label was never bound to a location, but it was used as a jmp target");
+  }
+
+  void reset() {
+    init(); //leave _patch_overflow because it points to CodeBuffer.
+  }
 };
 
 // A union type for code which has to assemble both constant and
diff --git a/src/share/vm/c1/c1_CFGPrinter.cpp b/src/share/vm/c1/c1_CFGPrinter.cpp
index b0cb946..c5b35d0 100644
--- a/src/share/vm/c1/c1_CFGPrinter.cpp
+++ b/src/share/vm/c1/c1_CFGPrinter.cpp
@@ -161,7 +161,7 @@
 
   print("name \"%s\"", method_name(_compilation->method(), true));
   print("method \"%s\"", method_name(_compilation->method()));
-  print("date "INT64_FORMAT, (int64_t) os::javaTimeMillis());
+  print("date " INT64_FORMAT, (int64_t) os::javaTimeMillis());
 
   print_end("compilation");
 }
diff --git a/src/share/vm/c1/c1_LIRAssembler.cpp b/src/share/vm/c1/c1_LIRAssembler.cpp
index 3447e07..a2cf5f2 100644
--- a/src/share/vm/c1/c1_LIRAssembler.cpp
+++ b/src/share/vm/c1/c1_LIRAssembler.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -128,6 +128,9 @@
 
 
 LIR_Assembler::~LIR_Assembler() {
+  // The unwind handler label may be unbound if this destructor is invoked because of a bail-out.
+  // Reset it here to avoid an assertion.
+  _unwind_handler_entry.reset();
 }
 
 
diff --git a/src/share/vm/c1/c1_Runtime1.cpp b/src/share/vm/c1/c1_Runtime1.cpp
index f64c60e..5a614b6 100644
--- a/src/share/vm/c1/c1_Runtime1.cpp
+++ b/src/share/vm/c1/c1_Runtime1.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -547,9 +547,8 @@
     // normal bytecode execution.
     thread->clear_exception_oop_and_pc();
 
-    Handle original_exception(thread, exception());
-
-    continuation = SharedRuntime::compute_compiled_exc_handler(nm, pc, exception, false, false);
+    bool recursive_exception = false;
+    continuation = SharedRuntime::compute_compiled_exc_handler(nm, pc, exception, false, false, recursive_exception);
     // If an exception was thrown during exception dispatch, the exception oop may have changed
     thread->set_exception_oop(exception());
     thread->set_exception_pc(pc);
@@ -557,8 +556,9 @@
     // the exception cache is used only by non-implicit exceptions
     // Update the exception cache only when there didn't happen
     // another exception during the computation of the compiled
-    // exception handler.
-    if (continuation != NULL && original_exception() == exception()) {
+    // exception handler. Checking for exception oop equality is not
+    // sufficient because some exceptions are pre-allocated and reused.
+    if (continuation != NULL && !recursive_exception) {
       nm->add_handler_for_exception_and_pc(exception, pc, continuation);
     }
   }
diff --git a/src/share/vm/ci/ciReplay.cpp b/src/share/vm/ci/ciReplay.cpp
index 6acde21..58b5019 100644
--- a/src/share/vm/ci/ciReplay.cpp
+++ b/src/share/vm/ci/ciReplay.cpp
@@ -1,4 +1,5 @@
-/* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+/*
+ * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -329,7 +330,7 @@
   // Lookup a klass
   Klass* resolve_klass(const char* klass, TRAPS) {
     Symbol* klass_name = SymbolTable::lookup(klass, (int)strlen(klass), CHECK_NULL);
-    return SystemDictionary::resolve_or_fail(klass_name, _loader, _protection_domain, true, CHECK_NULL);
+    return SystemDictionary::resolve_or_fail(klass_name, _loader, _protection_domain, true, THREAD);
   }
 
   // Parse the standard tuple of <klass> <name> <signature>
diff --git a/src/share/vm/classfile/altHashing.cpp b/src/share/vm/classfile/altHashing.cpp
index 91eb5be..ca1ed02 100644
--- a/src/share/vm/classfile/altHashing.cpp
+++ b/src/share/vm/classfile/altHashing.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -224,7 +224,7 @@
 static const jbyte THREE_BYTE[] = { (jbyte) 0x80, (jbyte) 0x81, (jbyte) 0x82};
 static const jbyte FOUR_BYTE[] = { (jbyte) 0x80, (jbyte) 0x81, (jbyte) 0x82, (jbyte) 0x83};
 static const jchar TWO_CHAR[] = { (jchar) 0x8180, (jchar) 0x8382};
-static const jint ONE_INT[] = { 0x83828180};
+static const jint ONE_INT[] = { (jint) 0x83828180};
 static const jbyte SIX_BYTE[] = { (jbyte) 0x80, (jbyte) 0x81, (jbyte) 0x82, (jbyte) 0x83, (jbyte) 0x84, (jbyte) 0x85};
 static const jchar THREE_CHAR[] = { (jchar) 0x8180, (jchar) 0x8382, (jchar) 0x8584};
 static const jbyte EIGHT_BYTE[] = {
@@ -235,7 +235,7 @@
   (jchar) 0x8180, (jchar) 0x8382,
   (jchar) 0x8584, (jchar) 0x8786};
 
-static const jint TWO_INT[] = { 0x83828180, 0x87868584};
+static const jint TWO_INT[] = { (jint) 0x83828180, (jint) 0x87868584};
 
 static const juint MURMUR3_32_X86_CHECK_VALUE = 0xB0F57EE3;
 
diff --git a/src/share/vm/classfile/classFileParser.cpp b/src/share/vm/classfile/classFileParser.cpp
index 59a68f8..a5bfb9d 100644
--- a/src/share/vm/classfile/classFileParser.cpp
+++ b/src/share/vm/classfile/classFileParser.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -275,7 +275,7 @@
             char* str = java_lang_String::as_utf8_string(patch());
             // (could use java_lang_String::as_symbol instead, but might as well batch them)
             utf8_buffer = (u1*) str;
-            utf8_length = (int) strlen(str);
+            utf8_length = (u2) strlen(str);
           }
 
           unsigned int hash;
diff --git a/src/share/vm/classfile/classLoaderData.cpp b/src/share/vm/classfile/classLoaderData.cpp
index d6d1312..b4eb8f5 100644
--- a/src/share/vm/classfile/classLoaderData.cpp
+++ b/src/share/vm/classfile/classLoaderData.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -488,7 +488,7 @@
 // These anonymous class loaders are to contain classes used for JSR292
 ClassLoaderData* ClassLoaderData::anonymous_class_loader_data(oop loader, TRAPS) {
   // Add a new class loader data to the graph.
-  return ClassLoaderDataGraph::add(loader, true, CHECK_NULL);
+  return ClassLoaderDataGraph::add(loader, true, THREAD);
 }
 
 const char* ClassLoaderData::loader_name() {
@@ -502,7 +502,7 @@
 
 void ClassLoaderData::dump(outputStream * const out) {
   ResourceMark rm;
-  out->print("ClassLoaderData CLD: "PTR_FORMAT", loader: "PTR_FORMAT", loader_klass: "PTR_FORMAT" %s {",
+  out->print("ClassLoaderData CLD: " PTR_FORMAT ", loader: " PTR_FORMAT ", loader_klass: " PTR_FORMAT " %s {",
       p2i(this), p2i((void *)class_loader()),
       p2i(class_loader() != NULL ? class_loader()->klass() : NULL), loader_name());
   if (claimed()) out->print(" claimed ");
@@ -520,7 +520,7 @@
     ResourceMark rm;
     Klass* k = _klasses;
     while (k != NULL) {
-      out->print_cr("klass "PTR_FORMAT", %s, CT: %d, MUT: %d", k, k->name()->as_C_string(),
+      out->print_cr("klass " PTR_FORMAT ", %s, CT: %d, MUT: %d", k, k->name()->as_C_string(),
           k->has_modified_oops(), k->has_accumulated_modified_oops());
       assert(k != k->next_link(), "no loops!");
       k = k->next_link();
diff --git a/src/share/vm/classfile/classLoaderStats.cpp b/src/share/vm/classfile/classLoaderStats.cpp
new file mode 100644
index 0000000..7132c22
--- /dev/null
+++ b/src/share/vm/classfile/classLoaderStats.cpp
@@ -0,0 +1,167 @@
+/*
+ * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+#include "precompiled.hpp"
+#include "classfile/classLoaderStats.hpp"
+#include "utilities/globalDefinitions.hpp"
+
+
+class ClassStatsClosure : public KlassClosure {
+public:
+  int _num_classes;
+
+  ClassStatsClosure() :
+    _num_classes(0) {
+  }
+
+  virtual void do_klass(Klass* k) {
+    _num_classes++;
+  }
+};
+
+
+void ClassLoaderStatsClosure::do_cld(ClassLoaderData* cld) {
+  oop cl = cld->class_loader();
+  ClassLoaderStats* cls;
+
+  // The hashtable key is the ClassLoader oop since we want to account
+  // for "real" classes and anonymous classes together
+  ClassLoaderStats** cls_ptr = _stats->get(cl);
+  if (cls_ptr == NULL) {
+    cls = new ClassLoaderStats();
+    _stats->put(cl, cls);
+    _total_loaders++;
+  } else {
+    cls = *cls_ptr;
+  }
+
+  if (!cld->is_anonymous()) {
+    cls->_cld = cld;
+  }
+
+  cls->_class_loader = cl;
+  if (cl != NULL) {
+    cls->_parent = java_lang_ClassLoader::parent(cl);
+    addEmptyParents(cls->_parent);
+  }
+
+  ClassStatsClosure csc;
+  cld->classes_do(&csc);
+  if(cld->is_anonymous()) {
+    cls->_anon_classes_count += csc._num_classes;
+  } else {
+    cls->_classes_count = csc._num_classes;
+  }
+  _total_classes += csc._num_classes;
+
+  Metaspace* ms = cld->metaspace_or_null();
+  if (ms != NULL) {
+    if(cld->is_anonymous()) {
+      cls->_anon_chunk_sz += ms->allocated_chunks_bytes();
+      cls->_anon_block_sz += ms->allocated_blocks_bytes();
+    } else {
+      cls->_chunk_sz = ms->allocated_chunks_bytes();
+      cls->_block_sz = ms->allocated_blocks_bytes();
+    }
+    _total_chunk_sz += ms->allocated_chunks_bytes();
+    _total_block_sz += ms->allocated_blocks_bytes();
+  }
+}
+
+
+// Handles the difference in pointer width on 32 and 64 bit platforms
+#ifdef _LP64
+  #define SPACE "%8s"
+#else
+  #define SPACE "%s"
+#endif
+
+
+bool ClassLoaderStatsClosure::do_entry(oop const& key, ClassLoaderStats* const& cls) {
+  Klass* class_loader_klass = (cls->_class_loader == NULL ? NULL : cls->_class_loader->klass());
+  Klass* parent_klass = (cls->_parent == NULL ? NULL : cls->_parent->klass());
+
+  _out->print(INTPTR_FORMAT "  " INTPTR_FORMAT "  " INTPTR_FORMAT "  " UINTX_FORMAT_W(6) "  " SIZE_FORMAT_W(8) "  " SIZE_FORMAT_W(8) "  ",
+      p2i(class_loader_klass), p2i(parent_klass), p2i(cls->_cld),
+      cls->_classes_count,
+      cls->_chunk_sz, cls->_block_sz);
+  if (class_loader_klass != NULL) {
+    _out->print("%s", class_loader_klass->external_name());
+  } else {
+    _out->print("<boot class loader>");
+  }
+  _out->cr();
+  if (cls->_anon_classes_count > 0) {
+    _out->print_cr(SPACE SPACE SPACE "                                    " UINTX_FORMAT_W(6) "  " SIZE_FORMAT_W(8) "  " SIZE_FORMAT_W(8) "   + unsafe anonymous classes",
+        "", "", "",
+        cls->_anon_classes_count,
+        cls->_anon_chunk_sz, cls->_anon_block_sz);
+  }
+  return true;
+}
+
+
+void ClassLoaderStatsClosure::print() {
+  _out->print_cr("ClassLoader" SPACE " Parent" SPACE "      CLD*" SPACE "       Classes   ChunkSz   BlockSz  Type", "", "", "");
+  _stats->iterate(this);
+  _out->print("Total = " UINTX_FORMAT_W(-6), _total_loaders);
+  _out->print(SPACE SPACE SPACE "                      ", "", "", "");
+  _out->print_cr(UINTX_FORMAT_W(6) "  " SIZE_FORMAT_W(8) "  " SIZE_FORMAT_W(8) "  ",
+      _total_classes,
+      _total_chunk_sz,
+      _total_block_sz);
+  _out->print_cr("ChunkSz: Total size of all allocated metaspace chunks");
+  _out->print_cr("BlockSz: Total size of all allocated metaspace blocks (each chunk has several blocks)");
+}
+
+
+void ClassLoaderStatsClosure::addEmptyParents(oop cl) {
+  while (cl != NULL && java_lang_ClassLoader::loader_data(cl) == NULL) {
+    // This classloader has not loaded any classes
+    ClassLoaderStats** cls_ptr = _stats->get(cl);
+    if (cls_ptr == NULL) {
+      // It does not exist in our table - add it
+      ClassLoaderStats* cls = new ClassLoaderStats();
+      cls->_class_loader = cl;
+      cls->_parent = java_lang_ClassLoader::parent(cl);
+      _stats->put(cl, cls);
+      _total_loaders++;
+    }
+
+    cl = java_lang_ClassLoader::parent(cl);
+  }
+}
+
+
+void ClassLoaderStatsVMOperation::doit() {
+  ClassLoaderStatsClosure clsc (_out);
+  ClassLoaderDataGraph::cld_do(&clsc);
+  clsc.print();
+}
+
+
+void ClassLoaderStatsDCmd::execute(DCmdSource source, TRAPS) {
+  ClassLoaderStatsVMOperation op(output());
+  VMThread::execute(&op);
+}
diff --git a/src/share/vm/classfile/classLoaderStats.hpp b/src/share/vm/classfile/classLoaderStats.hpp
new file mode 100644
index 0000000..72904c1
--- /dev/null
+++ b/src/share/vm/classfile/classLoaderStats.hpp
@@ -0,0 +1,152 @@
+/*
+ * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+#ifndef SHARE_VM_CLASSFILE_CLASSLOADERSTATS_HPP
+#define SHARE_VM_CLASSFILE_CLASSLOADERSTATS_HPP
+
+
+#include "classfile/classLoaderData.hpp"
+#include "oops/klass.hpp"
+#include "oops/oopsHierarchy.hpp"
+#include "runtime/vm_operations.hpp"
+#include "services/diagnosticCommand.hpp"
+#include "utilities/resourceHash.hpp"
+
+
+class ClassLoaderStatsDCmd : public DCmd {
+public:
+  ClassLoaderStatsDCmd(outputStream* output, bool heap) :
+    DCmd(output, heap) {
+  }
+
+  static const char* name() {
+    return "VM.classloader_stats";
+  }
+
+  static const char* description() {
+    return "Print statistics about all ClassLoaders.";
+  }
+
+  static const char* impact() {
+    return "Low";
+  }
+
+  virtual void execute(DCmdSource source, TRAPS);
+
+  static int num_arguments() {
+    return 0;
+  }
+
+  static const JavaPermission permission() {
+    JavaPermission p = {"java.lang.management.ManagementPermission",
+                        "monitor", NULL};
+    return p;
+  }
+};
+
+
+class ClassLoaderStats : public ResourceObj {
+public:
+  ClassLoaderData*  _cld;
+  oop               _class_loader;
+  oop               _parent;
+
+  size_t            _chunk_sz;
+  size_t            _block_sz;
+  uintx             _classes_count;
+
+  size_t            _anon_chunk_sz;
+  size_t            _anon_block_sz;
+  uintx             _anon_classes_count;
+
+  ClassLoaderStats() :
+    _cld(0),
+    _class_loader(0),
+    _parent(0),
+    _chunk_sz(0),
+    _block_sz(0),
+    _classes_count(0),
+    _anon_block_sz(0),
+    _anon_chunk_sz(0),
+    _anon_classes_count(0) {
+  }
+};
+
+
+class ClassLoaderStatsClosure : public CLDClosure {
+protected:
+  static bool oop_equals(oop const& s1, oop const& s2) {
+    return s1 == s2;
+  }
+
+  static unsigned oop_hash(oop const& s1) {
+    unsigned hash = (unsigned)((uintptr_t)&s1);
+    return hash ^ (hash >> LogMinObjAlignment);
+  }
+
+  typedef ResourceHashtable<oop, ClassLoaderStats*,
+      ClassLoaderStatsClosure::oop_hash, ClassLoaderStatsClosure::oop_equals> StatsTable;
+
+  outputStream* _out;
+  StatsTable* _stats;
+  uintx   _total_loaders;
+  uintx   _total_classes;
+  size_t  _total_chunk_sz;
+  size_t  _total_block_sz;
+
+public:
+  ClassLoaderStatsClosure(outputStream* out) :
+    _out(out),
+    _total_loaders(0),
+    _total_block_sz(0),
+    _total_chunk_sz(0),
+    _total_classes(0),
+    _stats(new StatsTable()) {
+  }
+
+  virtual void do_cld(ClassLoaderData* cld);
+  virtual bool do_entry(oop const& key, ClassLoaderStats* const& cls);
+  void print();
+
+private:
+  void addEmptyParents(oop cl);
+};
+
+
+class ClassLoaderStatsVMOperation : public VM_Operation {
+  outputStream* _out;
+
+public:
+  ClassLoaderStatsVMOperation(outputStream* out) :
+    _out(out) {
+  }
+
+  VMOp_Type type() const {
+    return VMOp_ClassLoaderStatsOperation;
+  }
+
+  void doit();
+};
+
+#endif // SHARE_VM_CLASSFILE_CLASSLOADERSTATS_HPP
diff --git a/src/share/vm/classfile/defaultMethods.cpp b/src/share/vm/classfile/defaultMethods.cpp
index 0e3d5d7..4b4b4e2 100644
--- a/src/share/vm/classfile/defaultMethods.cpp
+++ b/src/share/vm/classfile/defaultMethods.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -493,7 +493,7 @@
 };
 
 Symbol* MethodFamily::generate_no_defaults_message(TRAPS) const {
-  return SymbolTable::new_symbol("No qualifying defaults found", CHECK_NULL);
+  return SymbolTable::new_symbol("No qualifying defaults found", THREAD);
 }
 
 Symbol* MethodFamily::generate_method_message(Symbol *klass_name, Method* method, TRAPS) const {
diff --git a/src/share/vm/classfile/dictionary.cpp b/src/share/vm/classfile/dictionary.cpp
index c9a43de..f4e3501 100644
--- a/src/share/vm/classfile/dictionary.cpp
+++ b/src/share/vm/classfile/dictionary.cpp
@@ -568,7 +568,7 @@
 }
 
 void ProtectionDomainCacheEntry::print() {
-  tty->print_cr("entry "PTR_FORMAT" value "PTR_FORMAT" strongly_reachable %d next "PTR_FORMAT,
+  tty->print_cr("entry " PTR_FORMAT " value " PTR_FORMAT " strongly_reachable %d next " PTR_FORMAT,
                 this, (void*)literal(), _strongly_reachable, next());
 }
 #endif
diff --git a/src/share/vm/classfile/dictionary.hpp b/src/share/vm/classfile/dictionary.hpp
index 504e735..9ed0def 100644
--- a/src/share/vm/classfile/dictionary.hpp
+++ b/src/share/vm/classfile/dictionary.hpp
@@ -373,7 +373,7 @@
 
   void print_on(outputStream* st) const {
     symbol()->print_value_on(st);
-    st->print("/mode="INTX_FORMAT, symbol_mode());
+    st->print("/mode=" INTX_FORMAT, symbol_mode());
     st->print(" -> ");
     bool printed = false;
     if (method() != NULL) {
diff --git a/src/share/vm/classfile/javaClasses.cpp b/src/share/vm/classfile/javaClasses.cpp
index fbd7cc5..2345d74 100644
--- a/src/share/vm/classfile/javaClasses.cpp
+++ b/src/share/vm/classfile/javaClasses.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1961,7 +1961,7 @@
   // This class is eagerly initialized during VM initialization, since we keep a refence
   // to one of the methods
   assert(InstanceKlass::cast(klass)->is_initialized(), "must be initialized");
-  return InstanceKlass::cast(klass)->allocate_instance_handle(CHECK_NH);
+  return InstanceKlass::cast(klass)->allocate_instance_handle(THREAD);
 }
 
 oop java_lang_reflect_Method::clazz(oop reflect) {
@@ -2679,6 +2679,32 @@
   *offset = value;
 }
 
+// Support for java_lang_ref_ReferenceQueue
+
+oop java_lang_ref_ReferenceQueue::NULL_queue() {
+  InstanceKlass* ik = InstanceKlass::cast(SystemDictionary::ReferenceQueue_klass());
+  oop mirror = ik->java_mirror();
+  return mirror->obj_field(static_NULL_queue_offset);
+}
+
+oop java_lang_ref_ReferenceQueue::ENQUEUED_queue() {
+  InstanceKlass* ik = InstanceKlass::cast(SystemDictionary::ReferenceQueue_klass());
+  oop mirror = ik->java_mirror();
+  return mirror->obj_field(static_ENQUEUED_queue_offset);
+}
+
+void java_lang_ref_ReferenceQueue::compute_offsets() {
+  Klass* k = SystemDictionary::ReferenceQueue_klass();
+  compute_offset(static_NULL_queue_offset,
+                 k,
+                 vmSymbols::referencequeue_null_name(),
+                 vmSymbols::referencequeue_signature());
+  compute_offset(static_ENQUEUED_queue_offset,
+                 k,
+                 vmSymbols::referencequeue_enqueued_name(),
+                 vmSymbols::referencequeue_signature());
+}
+
 // Support for java_lang_invoke_DirectMethodHandle
 
 int java_lang_invoke_DirectMethodHandle::_member_offset;
@@ -3197,6 +3223,8 @@
 int java_lang_ref_Reference::static_lock_offset;
 int java_lang_ref_Reference::static_pending_offset;
 int java_lang_ref_Reference::number_of_fake_oop_fields;
+int java_lang_ref_ReferenceQueue::static_NULL_queue_offset;
+int java_lang_ref_ReferenceQueue::static_ENQUEUED_queue_offset;
 int java_lang_ref_SoftReference::timestamp_offset;
 int java_lang_ref_SoftReference::static_clock_offset;
 int java_lang_ClassLoader::parent_offset;
@@ -3378,6 +3406,8 @@
   if (JDK_Version::is_jdk18x_version())
     java_lang_reflect_Parameter::compute_offsets();
 
+  java_lang_ref_ReferenceQueue::compute_offsets();
+
   // generated interpreter code wants to know about the offsets we just computed:
   AbstractAssembler::update_delayed_values();
 }
diff --git a/src/share/vm/classfile/javaClasses.hpp b/src/share/vm/classfile/javaClasses.hpp
index db61183..c041bb1 100644
--- a/src/share/vm/classfile/javaClasses.hpp
+++ b/src/share/vm/classfile/javaClasses.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -929,6 +929,12 @@
   static HeapWord* discovered_addr(oop ref) {
     return ref->obj_field_addr<HeapWord>(discovered_offset);
   }
+  static inline oop queue(oop ref) {
+    return ref->obj_field(queue_offset);
+  }
+  static inline void set_queue(oop ref, oop value) {
+    return ref->obj_field_put(queue_offset, value);
+  }
   // Accessors for statics
   static oop  pending_list_lock();
   static oop  pending_list();
@@ -962,6 +968,20 @@
 };
 
 
+// Interface to java.lang.ref.ReferenceQueue objects
+
+class java_lang_ref_ReferenceQueue: public AllStatic {
+public:
+  static int static_NULL_queue_offset;
+  static int static_ENQUEUED_queue_offset;
+
+  // Accessors
+  static oop NULL_queue();
+  static oop ENQUEUED_queue();
+
+  static void compute_offsets();
+};
+
 // Interface to java.lang.invoke.MethodHandle objects
 
 class MethodHandleEntry;
@@ -1189,7 +1209,7 @@
   static oop              target(         oop site)             { return site->obj_field(             _target_offset);         }
   static void         set_target(         oop site, oop target) {        site->obj_field_put(         _target_offset, target); }
 
-  static volatile oop     target_volatile(oop site)             { return site->obj_field_volatile(    _target_offset);         }
+  static volatile oop     target_volatile(oop site)             { return oop((oopDesc *)(site->obj_field_volatile(_target_offset))); }
   static void         set_target_volatile(oop site, oop target) {        site->obj_field_put_volatile(_target_offset, target); }
 
   // Testers
diff --git a/src/share/vm/classfile/metadataOnStackMark.cpp b/src/share/vm/classfile/metadataOnStackMark.cpp
index 4c9b4ef..ade3a86 100644
--- a/src/share/vm/classfile/metadataOnStackMark.cpp
+++ b/src/share/vm/classfile/metadataOnStackMark.cpp
@@ -41,13 +41,13 @@
 // Walk metadata on the stack and mark it so that redefinition doesn't delete
 // it.  Class unloading also walks the previous versions and might try to
 // delete it, so this class is used by class unloading also.
-MetadataOnStackMark::MetadataOnStackMark(bool visit_code_cache) {
+MetadataOnStackMark::MetadataOnStackMark(bool has_redefined_a_class) {
   assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
   assert(_used_buffers == NULL, "sanity check");
   NOT_PRODUCT(_is_active = true;)
 
   Threads::metadata_do(Metadata::mark_on_stack);
-  if (visit_code_cache) {
+  if (has_redefined_a_class) {
     CodeCache::alive_nmethods_do(nmethod::mark_on_stack);
   }
   CompileBroker::mark_on_stack();
diff --git a/src/share/vm/classfile/metadataOnStackMark.hpp b/src/share/vm/classfile/metadataOnStackMark.hpp
index 9233c26..e0d5c76 100644
--- a/src/share/vm/classfile/metadataOnStackMark.hpp
+++ b/src/share/vm/classfile/metadataOnStackMark.hpp
@@ -47,7 +47,7 @@
   static void retire_buffer(MetadataOnStackBuffer* buffer);
 
  public:
-  MetadataOnStackMark(bool visit_code_cache);
+  MetadataOnStackMark(bool has_redefined_a_class);
    ~MetadataOnStackMark();
 
   static void record(Metadata* m, Thread* thread);
diff --git a/src/share/vm/classfile/systemDictionary.cpp b/src/share/vm/classfile/systemDictionary.cpp
index 1dfe3b6..40e6644 100644
--- a/src/share/vm/classfile/systemDictionary.cpp
+++ b/src/share/vm/classfile/systemDictionary.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -121,7 +121,7 @@
 
 ClassLoaderData* SystemDictionary::register_loader(Handle class_loader, TRAPS) {
   if (class_loader() == NULL) return ClassLoaderData::the_null_class_loader_data();
-  return ClassLoaderDataGraph::find_or_create(class_loader, CHECK_NULL);
+  return ClassLoaderDataGraph::find_or_create(class_loader, THREAD);
 }
 
 // ----------------------------------------------------------------------------
@@ -1927,6 +1927,8 @@
   InstanceKlass::cast(WK_KLASS(PhantomReference_klass))->set_reference_type(REF_PHANTOM);
   InstanceKlass::cast(WK_KLASS(Cleaner_klass))->set_reference_type(REF_CLEANER);
 
+  initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(ReferenceQueue_klass), scan, CHECK);
+
   // JSR 292 classes
   WKID jsr292_group_start = WK_KLASS_ENUM_NAME(MethodHandle_klass);
   WKID jsr292_group_end   = WK_KLASS_ENUM_NAME(VolatileCallSite_klass);
diff --git a/src/share/vm/classfile/systemDictionary.hpp b/src/share/vm/classfile/systemDictionary.hpp
index 887fab0..57a9d66 100644
--- a/src/share/vm/classfile/systemDictionary.hpp
+++ b/src/share/vm/classfile/systemDictionary.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -130,6 +130,7 @@
   do_klass(PhantomReference_klass,                      java_lang_ref_PhantomReference,            Pre                 ) \
   do_klass(Cleaner_klass,                               sun_misc_Cleaner,                          Pre                 ) \
   do_klass(Finalizer_klass,                             java_lang_ref_Finalizer,                   Pre                 ) \
+  do_klass(ReferenceQueue_klass,                        java_lang_ref_ReferenceQueue,              Pre                 ) \
                                                                                                                          \
   do_klass(Thread_klass,                                java_lang_Thread,                          Pre                 ) \
   do_klass(ThreadGroup_klass,                           java_lang_ThreadGroup,                     Pre                 ) \
diff --git a/src/share/vm/classfile/verificationType.cpp b/src/share/vm/classfile/verificationType.cpp
index 716a72d..bdba76f 100644
--- a/src/share/vm/classfile/verificationType.cpp
+++ b/src/share/vm/classfile/verificationType.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -63,6 +63,7 @@
         name(), Handle(THREAD, klass->class_loader()),
         Handle(THREAD, klass->protection_domain()), true, CHECK_false);
     KlassHandle this_class(THREAD, obj);
+    klass->class_loader_data()->record_dependency(obj, CHECK_false);
 
     if (this_class->is_interface() && (!from_field_is_protected ||
         from.name() != vmSymbols::java_lang_Object())) {
@@ -74,6 +75,7 @@
       Klass* from_class = SystemDictionary::resolve_or_fail(
           from.name(), Handle(THREAD, klass->class_loader()),
           Handle(THREAD, klass->protection_domain()), true, CHECK_false);
+      klass->class_loader_data()->record_dependency(from_class, CHECK_false);
       bool result = InstanceKlass::cast(from_class)->is_subclass_of(this_class());
       if (result && DumpSharedSpaces) {
         if (klass()->is_subclass_of(from_class) && klass()->is_subclass_of(this_class())) {
@@ -97,7 +99,7 @@
     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,
-                                          from_field_is_protected, CHECK_false);
+                                          from_field_is_protected, THREAD);
     }
   }
   return false;
diff --git a/src/share/vm/classfile/verificationType.hpp b/src/share/vm/classfile/verificationType.hpp
index 43bd79e..3ccc3a6 100644
--- a/src/share/vm/classfile/verificationType.hpp
+++ b/src/share/vm/classfile/verificationType.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -289,7 +289,7 @@
           if (is_reference() && from.is_reference()) {
             return is_reference_assignable_from(from, context,
                                                 from_field_is_protected,
-                                                CHECK_false);
+                                                THREAD);
           } else {
             return false;
           }
diff --git a/src/share/vm/classfile/verifier.cpp b/src/share/vm/classfile/verifier.cpp
index b53b4ae..82509ff 100644
--- a/src/share/vm/classfile/verifier.cpp
+++ b/src/share/vm/classfile/verifier.cpp
@@ -1949,9 +1949,11 @@
   oop loader = current_class()->class_loader();
   oop protection_domain = current_class()->protection_domain();
 
-  return SystemDictionary::resolve_or_fail(
+  Klass* kls = SystemDictionary::resolve_or_fail(
     name, Handle(THREAD, loader), Handle(THREAD, protection_domain),
     true, CHECK_NULL);
+  current_class()->class_loader_data()->record_dependency(kls, CHECK_NULL);
+  return kls;
 }
 
 bool ClassVerifier::is_protected_access(instanceKlassHandle this_class,
diff --git a/src/share/vm/classfile/vmSymbols.hpp b/src/share/vm/classfile/vmSymbols.hpp
index e6a3899..1de2213 100644
--- a/src/share/vm/classfile/vmSymbols.hpp
+++ b/src/share/vm/classfile/vmSymbols.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -81,6 +81,7 @@
   template(java_lang_ref_PhantomReference,            "java/lang/ref/PhantomReference")           \
   template(sun_misc_Cleaner,                          "sun/misc/Cleaner")                         \
   template(java_lang_ref_Finalizer,                   "java/lang/ref/Finalizer")                  \
+  template(java_lang_ref_ReferenceQueue,              "java/lang/ref/ReferenceQueue")             \
   template(java_lang_reflect_AccessibleObject,        "java/lang/reflect/AccessibleObject")       \
   template(java_lang_reflect_Method,                  "java/lang/reflect/Method")                 \
   template(java_lang_reflect_Constructor,             "java/lang/reflect/Constructor")            \
@@ -417,6 +418,9 @@
   template(getProtectionDomain_name,                  "getProtectionDomain")                      \
   template(getProtectionDomain_signature,             "(Ljava/security/CodeSource;)Ljava/security/ProtectionDomain;") \
   template(url_code_signer_array_void_signature,      "(Ljava/net/URL;[Ljava/security/CodeSigner;)V") \
+  template(resolved_references_name,                  "<resolved_references>")                    \
+  template(referencequeue_null_name,                  "NULL")                                     \
+  template(referencequeue_enqueued_name,              "ENQUEUED")                                 \
                                                                                                   \
   /* non-intrinsic name/signature pairs: */                                                       \
   template(register_method_name,                      "register")                                 \
@@ -505,9 +509,11 @@
   template(class_array_signature,                     "[Ljava/lang/Class;")                                       \
   template(classloader_signature,                     "Ljava/lang/ClassLoader;")                                  \
   template(object_signature,                          "Ljava/lang/Object;")                                       \
+  template(object_array_signature,                    "[Ljava/lang/Object;")                                       \
   template(class_signature,                           "Ljava/lang/Class;")                                        \
   template(string_signature,                          "Ljava/lang/String;")                                       \
   template(reference_signature,                       "Ljava/lang/ref/Reference;")                                \
+  template(referencequeue_signature,                  "Ljava/lang/ref/ReferenceQueue;")                           \
   template(executable_signature,                      "Ljava/lang/reflect/Executable;")                           \
   template(concurrenthashmap_signature,               "Ljava/util/concurrent/ConcurrentHashMap;")                 \
   template(String_StringBuilder_signature,            "(Ljava/lang/String;)Ljava/lang/StringBuilder;")            \
@@ -569,6 +575,11 @@
   template(java_lang_management_ThreadInfo_constructor_signature, "(Ljava/lang/Thread;ILjava/lang/Object;Ljava/lang/Thread;JJJJ[Ljava/lang/StackTraceElement;)V") \
   template(java_lang_management_ThreadInfo_with_locks_constructor_signature, "(Ljava/lang/Thread;ILjava/lang/Object;Ljava/lang/Thread;JJJJ[Ljava/lang/StackTraceElement;[Ljava/lang/Object;[I[Ljava/lang/Object;)V") \
   template(long_long_long_long_void_signature,         "(JJJJ)V")                                                 \
+  template(finalizer_histogram_klass,                  "java/lang/ref/FinalizerHistogram")                        \
+  template(void_finalizer_histogram_entry_array_signature,  "()[Ljava/lang/ref/FinalizerHistogram$Entry;")                        \
+  template(get_finalizer_histogram_name,               "getFinalizerHistogram")                                   \
+  template(finalizer_histogram_entry_name_field,       "className")                                               \
+  template(finalizer_histogram_entry_count_field,      "instanceCount")                                           \
                                                                                                                   \
   template(java_lang_management_MemoryPoolMXBean,      "java/lang/management/MemoryPoolMXBean")                   \
   template(java_lang_management_MemoryManagerMXBean,   "java/lang/management/MemoryManagerMXBean")                \
diff --git a/src/share/vm/code/codeBlob.cpp b/src/share/vm/code/codeBlob.cpp
index ee0d17d..87ae60f 100644
--- a/src/share/vm/code/codeBlob.cpp
+++ b/src/share/vm/code/codeBlob.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -289,6 +289,28 @@
   return blob;
 }
 
+VtableBlob::VtableBlob(const char* name, int size) :
+  BufferBlob(name, size) {
+}
+
+VtableBlob* VtableBlob::create(const char* name, int buffer_size) {
+  ThreadInVMfromUnknown __tiv;  // get to VM state in case we block on CodeCache_lock
+
+  VtableBlob* blob = NULL;
+  unsigned int size = sizeof(VtableBlob);
+  // align the size to CodeEntryAlignment
+  size = align_code_offset(size);
+  size += round_to(buffer_size, oopSize);
+  assert(name != NULL, "must provide a name");
+  {
+    MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
+    blob = new (size) VtableBlob(name, size);
+  }
+  // Track memory usage statistic after releasing CodeCache_lock
+  MemoryService::track_code_cache_memory_usage();
+
+  return blob;
+}
 
 //----------------------------------------------------------------------------------------------------
 // Implementation of MethodHandlesAdapterBlob
diff --git a/src/share/vm/code/codeBlob.hpp b/src/share/vm/code/codeBlob.hpp
index db270f1..4f83fac 100644
--- a/src/share/vm/code/codeBlob.hpp
+++ b/src/share/vm/code/codeBlob.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -101,6 +101,7 @@
   virtual bool is_exception_stub() const         { return false; }
   virtual bool is_safepoint_stub() const              { return false; }
   virtual bool is_adapter_blob() const                { return false; }
+  virtual bool is_vtable_blob() const                 { return false; }
   virtual bool is_method_handles_adapter_blob() const { return false; }
 
   virtual bool is_compiled_by_c2() const         { return false; }
@@ -202,6 +203,7 @@
 class BufferBlob: public CodeBlob {
   friend class VMStructs;
   friend class AdapterBlob;
+  friend class VtableBlob;
   friend class MethodHandlesAdapterBlob;
 
  private:
@@ -246,6 +248,18 @@
   virtual bool is_adapter_blob() const { return true; }
 };
 
+//---------------------------------------------------------------------------------------------------
+class VtableBlob: public BufferBlob {
+private:
+  VtableBlob(const char*, int);
+
+public:
+  // Creation
+  static VtableBlob* create(const char* name, int buffer_size);
+
+  // Typing
+  virtual bool is_vtable_blob() const { return true; }
+};
 
 //----------------------------------------------------------------------------------------------------
 // MethodHandlesAdapterBlob: used to hold MethodHandles adapters
diff --git a/src/share/vm/code/codeCache.cpp b/src/share/vm/code/codeCache.cpp
index c9059d7..9e5b7e9 100644
--- a/src/share/vm/code/codeCache.cpp
+++ b/src/share/vm/code/codeCache.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -41,6 +41,7 @@
 #include "oops/oop.inline.hpp"
 #include "runtime/handles.inline.hpp"
 #include "runtime/arguments.hpp"
+#include "runtime/deoptimization.hpp"
 #include "runtime/icache.hpp"
 #include "runtime/java.hpp"
 #include "runtime/mutexLocker.hpp"
diff --git a/src/share/vm/code/compiledIC.cpp b/src/share/vm/code/compiledIC.cpp
index 09e4728..0679421 100644
--- a/src/share/vm/code/compiledIC.cpp
+++ b/src/share/vm/code/compiledIC.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -228,10 +228,13 @@
 #ifdef ASSERT
     int index = call_info->resolved_method()->itable_index();
     assert(index == itable_index, "CallInfo pre-computes this");
-#endif //ASSERT
     InstanceKlass* k = call_info->resolved_method()->method_holder();
     assert(k->verify_itable_index(itable_index), "sanity check");
-    InlineCacheBuffer::create_transition_stub(this, k, entry);
+#endif //ASSERT
+    CompiledICHolder* holder = new CompiledICHolder(call_info->resolved_method()->method_holder(),
+                                                    call_info->resolved_klass()(), false);
+    holder->claim();
+    InlineCacheBuffer::create_transition_stub(this, holder, entry);
   } else {
     assert(call_info->call_kind() == CallInfo::vtable_call, "either itable or vtable");
     // Can be different than selected_method->vtable_index(), due to package-private etc.
@@ -267,7 +270,7 @@
   assert(!is_optimized(), "an optimized call cannot be megamorphic");
 
   // Cannot rely on cached_value. It is either an interface or a method.
-  return VtableStubs::is_entry_point(ic_destination());
+  return VtableStubs::entry_point(ic_destination()) != NULL;
 }
 
 bool CompiledIC::is_call_to_compiled() const {
@@ -527,7 +530,16 @@
 
 bool CompiledIC::is_icholder_entry(address entry) {
   CodeBlob* cb = CodeCache::find_blob_unsafe(entry);
-  return (cb != NULL && cb->is_adapter_blob());
+  if (cb != NULL && cb->is_adapter_blob()) {
+    return true;
+  }
+  // itable stubs also use CompiledICHolder
+  if (cb != NULL && cb->is_vtable_blob()) {
+    VtableStub* s = VtableStubs::entry_point(entry);
+    return (s != NULL) && s->is_itable_stub();
+  }
+
+  return false;
 }
 
 // ----------------------------------------------------------------------------
diff --git a/src/share/vm/code/compiledIC.hpp b/src/share/vm/code/compiledIC.hpp
index de72423..16472d3 100644
--- a/src/share/vm/code/compiledIC.hpp
+++ b/src/share/vm/code/compiledIC.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -59,11 +59,11 @@
 //          \                        /   \     /
 //       [4] \                      / [4] \->-/
 //            \->-  Megamorphic -<-/
-//                  (Method*)
+//              (CompiledICHolder*)
 //
-// The text in paranteses () refere to the value of the inline cache receiver (mov instruction)
+// The text in parentheses () refers to the value of the inline cache receiver (mov instruction)
 //
-// The numbers in square brackets refere to the kind of transition:
+// The numbers in square brackets refer to the kind of transition:
 // [1]: Initial fixup. Receiver it found from debug information
 // [2]: Compilation of a method
 // [3]: Recompilation of a method (note: only entry is changed. The Klass* must stay the same)
diff --git a/src/share/vm/code/dependencies.cpp b/src/share/vm/code/dependencies.cpp
index c71d921..c4c8e9b 100644
--- a/src/share/vm/code/dependencies.cpp
+++ b/src/share/vm/code/dependencies.cpp
@@ -793,6 +793,14 @@
     _signature = NULL;
     initialize(participant);
   }
+  ClassHierarchyWalker(Klass* participants[], int num_participants) {
+    _name      = NULL;
+    _signature = NULL;
+    initialize(NULL);
+    for (int i = 0; i < num_participants; ++i) {
+      add_participant(participants[i]);
+    }
+  }
 
   // This is common code for two searches:  One for concrete subtypes,
   // the other for concrete method implementations and overrides.
@@ -891,6 +899,24 @@
       // Search class hierarchy first.
       Method* m = InstanceKlass::cast(k)->find_instance_method(_name, _signature);
       if (!Dependencies::is_concrete_method(m, k)) {
+        // Check for re-abstraction of method
+        if (!k->is_interface() && m != NULL && m->is_abstract()) {
+          // Found a matching abstract method 'm' in the class hierarchy.
+          // This is fine iff 'k' is an abstract class and all concrete subtypes
+          // of 'k' override 'm' and are participates of the current search.
+          ClassHierarchyWalker wf(_participants, _num_participants);
+          Klass* w = wf.find_witness_subtype(k);
+          if (w != NULL) {
+            Method* wm = InstanceKlass::cast(w)->find_instance_method(_name, _signature);
+            if (!Dependencies::is_concrete_method(wm, w)) {
+              // Found a concrete subtype 'w' which does not override abstract method 'm'.
+              // Bail out because 'm' could be called with 'w' as receiver (leading to an
+              // AbstractMethodError) and thus the method we are looking for is not unique.
+              _found_methods[_num_participants] = m;
+              return true;
+            }
+          }
+        }
         // Check interface defaults also, if any exist.
         Array<Method*>* default_methods = InstanceKlass::cast(k)->default_methods();
         if (default_methods == NULL)
diff --git a/src/share/vm/code/exceptionHandlerTable.cpp b/src/share/vm/code/exceptionHandlerTable.cpp
index 511b84d..224e164 100644
--- a/src/share/vm/code/exceptionHandlerTable.cpp
+++ b/src/share/vm/code/exceptionHandlerTable.cpp
@@ -186,7 +186,7 @@
 void ImplicitExceptionTable::print(address base) const {
   tty->print("{");
   for( uint i=0; i<len(); i++ )
-    tty->print("< "INTPTR_FORMAT", "INTPTR_FORMAT" > ",base + *adr(i), base + *(adr(i)+1));
+    tty->print("< " INTPTR_FORMAT ", " INTPTR_FORMAT " > ",base + *adr(i), base + *(adr(i)+1));
   tty->print_cr("}");
 }
 
diff --git a/src/share/vm/code/nmethod.cpp b/src/share/vm/code/nmethod.cpp
index b897b6a..2b8ed36 100644
--- a/src/share/vm/code/nmethod.cpp
+++ b/src/share/vm/code/nmethod.cpp
@@ -1748,12 +1748,11 @@
     CompiledICHolder* cichk_oop = ic->cached_icholder();
 
     if (mark_on_stack) {
-      Metadata::mark_on_stack(cichk_oop->holder_method());
+      Metadata::mark_on_stack(cichk_oop->holder_metadata());
       Metadata::mark_on_stack(cichk_oop->holder_klass());
     }
 
-    if (cichk_oop->holder_method()->method_holder()->is_loader_alive(is_alive) &&
-        cichk_oop->holder_klass()->is_loader_alive(is_alive)) {
+    if (cichk_oop->is_loader_alive(is_alive)) {
       return;
     }
   } else {
@@ -2173,14 +2172,14 @@
                "metadata must be found in exactly one place");
         if (r->metadata_is_immediate() && r->metadata_value() != NULL) {
           Metadata* md = r->metadata_value();
-          f(md);
+          if (md != _method) f(md);
         }
       } else if (iter.type() == relocInfo::virtual_call_type) {
         // Check compiledIC holders associated with this nmethod
         CompiledIC *ic = CompiledIC_at(&iter);
         if (ic->is_icholder_call()) {
           CompiledICHolder* cichk = ic->cached_icholder();
-          f(cichk->holder_method());
+          f(cichk->holder_metadata());
           f(cichk->holder_klass());
         } else {
           Metadata* ic_oop = ic->cached_metadata();
@@ -2199,7 +2198,7 @@
     f(md);
   }
 
-  // Visit metadata not embedded in the other places.
+  // Call function Method*, not embedded in these other places.
   if (_method != NULL) f(_method);
 }
 
@@ -2324,7 +2323,7 @@
   void maybe_print(oop* p) {
     if (_print_nm == NULL)  return;
     if (!_detected_scavenge_root)  _print_nm->print_on(tty, "new scavenge root");
-    tty->print_cr(""PTR_FORMAT"[offset=%d] detected scavengable oop "PTR_FORMAT" (found at "PTR_FORMAT")",
+    tty->print_cr("" PTR_FORMAT "[offset=%d] detected scavengable oop " PTR_FORMAT " (found at " PTR_FORMAT ")",
                   _print_nm, (int)((intptr_t)p - (intptr_t)_print_nm),
                   (void *)(*p), (intptr_t)p);
     (*p)->print();
@@ -2705,7 +2704,7 @@
       _nm->print_nmethod(true);
       _ok = false;
     }
-    tty->print_cr("*** non-oop "PTR_FORMAT" found at "PTR_FORMAT" (offset %d)",
+    tty->print_cr("*** non-oop " PTR_FORMAT " found at " PTR_FORMAT " (offset %d)",
                   (void *)(*p), (intptr_t)p, (int)((intptr_t)p - (intptr_t)_nm));
   }
   virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }
@@ -2829,7 +2828,7 @@
       _nm->print_nmethod(true);
       _ok = false;
     }
-    tty->print_cr("*** scavengable oop "PTR_FORMAT" found at "PTR_FORMAT" (offset %d)",
+    tty->print_cr("*** scavengable oop " PTR_FORMAT " found at " PTR_FORMAT " (offset %d)",
                   (void *)(*p), (intptr_t)p, (int)((intptr_t)p - (intptr_t)_nm));
     (*p)->print();
   }
@@ -2874,7 +2873,7 @@
   print_on(tty, NULL);
 
   if (WizardMode) {
-    tty->print("((nmethod*) "INTPTR_FORMAT ") ", this);
+    tty->print("((nmethod*) " INTPTR_FORMAT ") ", this);
     tty->print(" for method " INTPTR_FORMAT , (address)method());
     tty->print(" { ");
     if (is_in_use())      tty->print("in_use ");
diff --git a/src/share/vm/code/vtableStubs.cpp b/src/share/vm/code/vtableStubs.cpp
index ac99da4..8424378 100644
--- a/src/share/vm/code/vtableStubs.cpp
+++ b/src/share/vm/code/vtableStubs.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -60,7 +60,7 @@
 
    // There is a dependency on the name of the blob in src/share/vm/prims/jvmtiCodeBlobEvents.cpp
    // If changing the name, update the other file accordingly.
-    BufferBlob* blob = BufferBlob::create("vtable chunks", bytes);
+    VtableBlob* blob = VtableBlob::create("vtable chunks", bytes);
     if (blob == NULL) {
       return NULL;
     }
@@ -167,17 +167,18 @@
   _number_of_vtable_stubs++;
 }
 
-
-bool VtableStubs::is_entry_point(address pc) {
+VtableStub* VtableStubs::entry_point(address pc) {
   MutexLocker ml(VtableStubs_lock);
   VtableStub* stub = (VtableStub*)(pc - VtableStub::entry_offset());
   uint hash = VtableStubs::hash(stub->is_vtable_stub(), stub->index());
   VtableStub* s;
   for (s = _table[hash]; s != NULL && s != stub; s = s->next()) {}
-  return s == stub;
+  if (s == stub) {
+    return s;
+  }
+  return NULL;
 }
 
-
 bool VtableStubs::contains(address pc) {
   // simple solution for now - we may want to use
   // a faster way if this function is called often
diff --git a/src/share/vm/code/vtableStubs.hpp b/src/share/vm/code/vtableStubs.hpp
index b3d4f2d..04f3e7e 100644
--- a/src/share/vm/code/vtableStubs.hpp
+++ b/src/share/vm/code/vtableStubs.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -126,7 +126,7 @@
  public:
   static address     find_vtable_stub(int vtable_index) { return find_stub(true,  vtable_index); }
   static address     find_itable_stub(int itable_index) { return find_stub(false, itable_index); }
-  static bool        is_entry_point(address pc);                     // is pc a vtable stub entry point?
+  static VtableStub* entry_point(address pc);                        // vtable stub entry point for a pc
   static bool        contains(address pc);                           // is pc within any stub?
   static VtableStub* stub_containing(address pc);                    // stub containing pc or NULL
   static int         number_of_vtable_stubs() { return _number_of_vtable_stubs; }
diff --git a/src/share/vm/compiler/compileBroker.cpp b/src/share/vm/compiler/compileBroker.cpp
index 32a753c..104aaae 100644
--- a/src/share/vm/compiler/compileBroker.cpp
+++ b/src/share/vm/compiler/compileBroker.cpp
@@ -203,7 +203,7 @@
   }
 
   void log_nmethod(JavaThread* thread, nmethod* nm) {
-    log(thread, "nmethod %d%s " INTPTR_FORMAT " code ["INTPTR_FORMAT ", " INTPTR_FORMAT "]",
+    log(thread, "nmethod %d%s " INTPTR_FORMAT " code [" INTPTR_FORMAT ", " INTPTR_FORMAT "]",
         nm->compile_id(), nm->is_osr_method() ? "%" : "",
         p2i(nm), p2i(nm->code_begin()), p2i(nm->code_end()));
   }
diff --git a/src/share/vm/compiler/disassembler.cpp b/src/share/vm/compiler/disassembler.cpp
index 3291360..93cd9e8 100644
--- a/src/share/vm/compiler/disassembler.cpp
+++ b/src/share/vm/compiler/disassembler.cpp
@@ -60,7 +60,7 @@
 Disassembler::decode_func_virtual Disassembler::_decode_instructions_virtual = NULL;
 Disassembler::decode_func Disassembler::_decode_instructions = NULL;
 
-static const char hsdis_library_name[] = "hsdis-"HOTSPOT_LIB_ARCH;
+static const char hsdis_library_name[] = "hsdis-" HOTSPOT_LIB_ARCH;
 static const char decode_instructions_virtual_name[] = "decode_instructions_virtual";
 static const char decode_instructions_name[] = "decode_instructions";
 static bool use_new_version = true;
diff --git a/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp b/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp
index 14f09d1..f42f1c9 100644
--- a/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp
+++ b/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -838,18 +838,18 @@
   GenCollectedHeap* gch = GenCollectedHeap::heap();
   if (PrintGCDetails) {
     if (Verbose) {
-      gclog_or_tty->print("[%d %s-%s: "SIZE_FORMAT"("SIZE_FORMAT")]",
+      gclog_or_tty->print("[%d %s-%s: " SIZE_FORMAT "(" SIZE_FORMAT ")]",
         level(), short_name(), s, used(), capacity());
     } else {
-      gclog_or_tty->print("[%d %s-%s: "SIZE_FORMAT"K("SIZE_FORMAT"K)]",
+      gclog_or_tty->print("[%d %s-%s: " SIZE_FORMAT "K(" SIZE_FORMAT "K)]",
         level(), short_name(), s, used() / K, capacity() / K);
     }
   }
   if (Verbose) {
-    gclog_or_tty->print(" "SIZE_FORMAT"("SIZE_FORMAT")",
+    gclog_or_tty->print(" " SIZE_FORMAT "(" SIZE_FORMAT ")",
               gch->used(), gch->capacity());
   } else {
-    gclog_or_tty->print(" "SIZE_FORMAT"K("SIZE_FORMAT"K)",
+    gclog_or_tty->print(" " SIZE_FORMAT "K(" SIZE_FORMAT "K)",
               gch->used() / K, gch->capacity() / K);
   }
 }
@@ -879,8 +879,8 @@
   bool   res = (available >= av_promo) || (available >= max_promotion_in_bytes);
   if (Verbose && PrintGCDetails) {
     gclog_or_tty->print_cr(
-      "CMS: promo attempt is%s safe: available("SIZE_FORMAT") %s av_promo("SIZE_FORMAT"),"
-      "max_promo("SIZE_FORMAT")",
+      "CMS: promo attempt is%s safe: available(" SIZE_FORMAT ") %s av_promo(" SIZE_FORMAT "),"
+      "max_promo(" SIZE_FORMAT ")",
       res? "":" not", available, res? ">=":"<",
       av_promo, max_promotion_in_bytes);
   }
@@ -966,8 +966,8 @@
         desired_free_percentage);
       gclog_or_tty->print_cr("  Maximum free fraction %f",
         maximum_free_percentage);
-      gclog_or_tty->print_cr("  Capactiy "SIZE_FORMAT, capacity()/1000);
-      gclog_or_tty->print_cr("  Desired capacity "SIZE_FORMAT,
+      gclog_or_tty->print_cr("  Capactiy " SIZE_FORMAT, capacity()/1000);
+      gclog_or_tty->print_cr("  Desired capacity " SIZE_FORMAT,
         desired_capacity/1000);
       int prev_level = level() - 1;
       if (prev_level >= 0) {
@@ -975,14 +975,14 @@
         GenCollectedHeap* gch = GenCollectedHeap::heap();
         Generation* prev_gen = gch->_gens[prev_level];
         prev_size = prev_gen->capacity();
-          gclog_or_tty->print_cr("  Younger gen size "SIZE_FORMAT,
+          gclog_or_tty->print_cr("  Younger gen size " SIZE_FORMAT,
                                  prev_size/1000);
       }
-      gclog_or_tty->print_cr("  unsafe_max_alloc_nogc "SIZE_FORMAT,
+      gclog_or_tty->print_cr("  unsafe_max_alloc_nogc " SIZE_FORMAT,
         unsafe_max_alloc_nogc()/1000);
-      gclog_or_tty->print_cr("  contiguous available "SIZE_FORMAT,
+      gclog_or_tty->print_cr("  contiguous available " SIZE_FORMAT,
         contiguous_available()/1000);
-      gclog_or_tty->print_cr("  Expand by "SIZE_FORMAT" (bytes)",
+      gclog_or_tty->print_cr("  Expand by " SIZE_FORMAT " (bytes)",
         expand_bytes);
     }
     // safe if expansion fails
@@ -1513,8 +1513,8 @@
     stats().print_on(gclog_or_tty);
     gclog_or_tty->print_cr("time_until_cms_gen_full %3.7f",
       stats().time_until_cms_gen_full());
-    gclog_or_tty->print_cr("free="SIZE_FORMAT, _cmsGen->free());
-    gclog_or_tty->print_cr("contiguous_available="SIZE_FORMAT,
+    gclog_or_tty->print_cr("free=" SIZE_FORMAT, _cmsGen->free());
+    gclog_or_tty->print_cr("contiguous_available=" SIZE_FORMAT,
                            _cmsGen->contiguous_available());
     gclog_or_tty->print_cr("promotion_rate=%g", stats().promotion_rate());
     gclog_or_tty->print_cr("cms_allocation_rate=%g", stats().cms_allocation_rate());
@@ -2792,8 +2792,8 @@
     assert(_numObjectsPromoted == 0, "check");
     assert(_numWordsPromoted   == 0, "check");
     if (Verbose && PrintGC) {
-      gclog_or_tty->print("Allocated "SIZE_FORMAT" objects, "
-                          SIZE_FORMAT" bytes concurrently",
+      gclog_or_tty->print("Allocated " SIZE_FORMAT " objects, "
+                          SIZE_FORMAT " bytes concurrently",
       _numObjectsAllocated, _numWordsAllocated*sizeof(HeapWord));
     }
     _numObjectsAllocated = 0;
@@ -2879,8 +2879,8 @@
     assert(_numObjectsAllocated == 0, "check");
     assert(_numWordsAllocated == 0, "check");
     if (Verbose && PrintGC) {
-      gclog_or_tty->print("Promoted "SIZE_FORMAT" objects, "
-                          SIZE_FORMAT" bytes",
+      gclog_or_tty->print("Promoted " SIZE_FORMAT " objects, "
+                          SIZE_FORMAT " bytes",
                  _numObjectsPromoted, _numWordsPromoted*sizeof(HeapWord));
     }
     _numObjectsPromoted = 0;
@@ -2890,7 +2890,7 @@
   if (PrintGC && Verbose) {
     // Call down the chain in contiguous_available needs the freelistLock
     // so print this out before releasing the freeListLock.
-    gclog_or_tty->print(" Contiguous available "SIZE_FORMAT" bytes ",
+    gclog_or_tty->print(" Contiguous available " SIZE_FORMAT " bytes ",
                         contiguous_available());
   }
 }
@@ -2978,7 +2978,7 @@
     HeapWord* addr = _marks->offsetToHeapWord(offset);
     if (!_marks->isMarked(addr)) {
       oop(addr)->print_on(gclog_or_tty);
-      gclog_or_tty->print_cr(" ("INTPTR_FORMAT" should have been marked)", addr);
+      gclog_or_tty->print_cr(" (" INTPTR_FORMAT " should have been marked)", addr);
       _failed = true;
     }
     return true;
@@ -5039,7 +5039,7 @@
 
   SpecializationStats::clear();
   if (PrintGCDetails) {
-    gclog_or_tty->print("[YG occupancy: "SIZE_FORMAT" K ("SIZE_FORMAT" K)]",
+    gclog_or_tty->print("[YG occupancy: " SIZE_FORMAT " K (" SIZE_FORMAT " K)]",
                         _young_gen->used() / K,
                         _young_gen->capacity() / K);
   }
@@ -5172,8 +5172,8 @@
   if (ser_ovflw > 0) {
     if (PrintCMSStatistics != 0) {
       gclog_or_tty->print_cr("Marking stack overflow (benign) "
-        "(pmc_pc="SIZE_FORMAT", pmc_rm="SIZE_FORMAT", kac="SIZE_FORMAT
-        ", kac_preclean="SIZE_FORMAT")",
+        "(pmc_pc=" SIZE_FORMAT ", pmc_rm=" SIZE_FORMAT ", kac=" SIZE_FORMAT
+        ", kac_preclean=" SIZE_FORMAT ")",
         _ser_pmc_preclean_ovflw, _ser_pmc_remark_ovflw,
         _ser_kac_ovflw, _ser_kac_preclean_ovflw);
     }
@@ -5186,7 +5186,7 @@
   if (_par_pmc_remark_ovflw > 0 || _par_kac_ovflw > 0) {
     if (PrintCMSStatistics != 0) {
       gclog_or_tty->print_cr("Work queue overflow (benign) "
-        "(pmc_rm="SIZE_FORMAT", kac="SIZE_FORMAT")",
+        "(pmc_rm=" SIZE_FORMAT ", kac=" SIZE_FORMAT ")",
         _par_pmc_remark_ovflw, _par_kac_ovflw);
     }
     _par_pmc_remark_ovflw = 0;
@@ -5194,12 +5194,12 @@
   }
   if (PrintCMSStatistics != 0) {
      if (_markStack._hit_limit > 0) {
-       gclog_or_tty->print_cr(" (benign) Hit max stack size limit ("SIZE_FORMAT")",
+       gclog_or_tty->print_cr(" (benign) Hit max stack size limit (" SIZE_FORMAT ")",
                               _markStack._hit_limit);
      }
      if (_markStack._failed_double > 0) {
-       gclog_or_tty->print_cr(" (benign) Failed stack doubling ("SIZE_FORMAT"),"
-                              " current capacity "SIZE_FORMAT,
+       gclog_or_tty->print_cr(" (benign) Failed stack doubling (" SIZE_FORMAT "),"
+                              " current capacity " SIZE_FORMAT,
                               _markStack._failed_double,
                               _markStack.capacity());
      }
@@ -5963,7 +5963,7 @@
                                                &markFromDirtyCardsClosure);
       verify_work_stacks_empty();
       if (PrintCMSStatistics != 0) {
-        gclog_or_tty->print(" (re-scanned "SIZE_FORMAT" dirty cards in cms gen) ",
+        gclog_or_tty->print(" (re-scanned " SIZE_FORMAT " dirty cards in cms gen) ",
           markFromDirtyCardsClosure.num_dirty_cards());
       }
     }
@@ -6829,7 +6829,7 @@
   size_t start_ofs = heapWordToOffset(mr.start());
   // Make sure that end() is appropriately aligned
   assert(mr.end() == (HeapWord*)round_to((intptr_t)mr.end(),
-                        (1 << (_shifter+LogHeapWordSize))),
+                        ((intptr_t) 1 << (_shifter+LogHeapWordSize))),
          "Misaligned mr.end()");
   size_t end_ofs   = heapWordToOffset(mr.end());
   assert(end_ofs > start_ofs, "Should mark at least one bit");
@@ -6893,8 +6893,8 @@
   } else if (_failed_double++ == 0 && !CMSConcurrentMTEnabled && PrintGCDetails) {
     // Failed to double capacity, continue;
     // we print a detail message only once per CMS cycle.
-    gclog_or_tty->print(" (benign) Failed to expand marking stack from "SIZE_FORMAT"K to "
-            SIZE_FORMAT"K",
+    gclog_or_tty->print(" (benign) Failed to expand marking stack from " SIZE_FORMAT "K to "
+            SIZE_FORMAT "K",
             _capacity / K, new_capacity / K);
   }
 }
@@ -8216,25 +8216,25 @@
     ShouldNotReachHere();
   }
   if (Verbose && PrintGC) {
-    gclog_or_tty->print("Collected "SIZE_FORMAT" objects, " SIZE_FORMAT " bytes",
+    gclog_or_tty->print("Collected " SIZE_FORMAT " objects, " SIZE_FORMAT " bytes",
                         _numObjectsFreed, _numWordsFreed*sizeof(HeapWord));
-    gclog_or_tty->print_cr("\nLive "SIZE_FORMAT" objects,  "
-                           SIZE_FORMAT" bytes  "
-      "Already free "SIZE_FORMAT" objects, "SIZE_FORMAT" bytes",
+    gclog_or_tty->print_cr("\nLive " SIZE_FORMAT " objects,  "
+                           SIZE_FORMAT " bytes  "
+      "Already free " SIZE_FORMAT " objects, " SIZE_FORMAT " bytes",
       _numObjectsLive, _numWordsLive*sizeof(HeapWord),
       _numObjectsAlreadyFree, _numWordsAlreadyFree*sizeof(HeapWord));
     size_t totalBytes = (_numWordsFreed + _numWordsLive + _numWordsAlreadyFree)
                         * sizeof(HeapWord);
-    gclog_or_tty->print_cr("Total sweep: "SIZE_FORMAT" bytes", totalBytes);
+    gclog_or_tty->print_cr("Total sweep: " SIZE_FORMAT " bytes", totalBytes);
 
     if (PrintCMSStatistics && CMSVerifyReturnedBytes) {
       size_t indexListReturnedBytes = _sp->sumIndexedFreeListArrayReturnedBytes();
       size_t dict_returned_bytes = _sp->dictionary()->sum_dict_returned_bytes();
       size_t returned_bytes = indexListReturnedBytes + dict_returned_bytes;
-      gclog_or_tty->print("Returned "SIZE_FORMAT" bytes", returned_bytes);
-      gclog_or_tty->print("   Indexed List Returned "SIZE_FORMAT" bytes",
+      gclog_or_tty->print("Returned " SIZE_FORMAT " bytes", returned_bytes);
+      gclog_or_tty->print("   Indexed List Returned " SIZE_FORMAT " bytes",
         indexListReturnedBytes);
-      gclog_or_tty->print_cr("        Dictionary Returned "SIZE_FORMAT" bytes",
+      gclog_or_tty->print_cr("        Dictionary Returned " SIZE_FORMAT " bytes",
         dict_returned_bytes);
     }
   }
@@ -8313,13 +8313,13 @@
     // coalesced chunk to the appropriate free list.
     if (inFreeRange()) {
       assert(freeFinger() >= _sp->bottom() && freeFinger() < _limit,
-             err_msg("freeFinger() " PTR_FORMAT" is out-of-bounds", freeFinger()));
+             err_msg("freeFinger() " PTR_FORMAT " is out-of-bounds", freeFinger()));
       flush_cur_free_chunk(freeFinger(),
                            pointer_delta(addr, freeFinger()));
       if (CMSTraceSweeper) {
         gclog_or_tty->print("Sweep: last chunk: ");
-        gclog_or_tty->print("put_free_blk 0x%x ("SIZE_FORMAT") "
-                   "[coalesced:"SIZE_FORMAT"]\n",
+        gclog_or_tty->print("put_free_blk 0x%x (" SIZE_FORMAT ") "
+                   "[coalesced:" SIZE_FORMAT "]\n",
                    freeFinger(), pointer_delta(addr, freeFinger()),
                    lastFreeRangeCoalesced());
       }
diff --git a/src/share/vm/gc_implementation/g1/collectionSetChooser.cpp b/src/share/vm/gc_implementation/g1/collectionSetChooser.cpp
index 07b92d0..ff1b6f0 100644
--- a/src/share/vm/gc_implementation/g1/collectionSetChooser.cpp
+++ b/src/share/vm/gc_implementation/g1/collectionSetChooser.cpp
@@ -117,7 +117,7 @@
   }
   guarantee(sum_of_reclaimable_bytes == _remaining_reclaimable_bytes,
             err_msg("reclaimable bytes inconsistent, "
-                    "remaining: "SIZE_FORMAT" sum: "SIZE_FORMAT,
+                    "remaining: " SIZE_FORMAT " sum: " SIZE_FORMAT,
                     _remaining_reclaimable_bytes, sum_of_reclaimable_bytes));
 }
 #endif // !PRODUCT
diff --git a/src/share/vm/gc_implementation/g1/collectionSetChooser.hpp b/src/share/vm/gc_implementation/g1/collectionSetChooser.hpp
index e177fd1..c36852e 100644
--- a/src/share/vm/gc_implementation/g1/collectionSetChooser.hpp
+++ b/src/share/vm/gc_implementation/g1/collectionSetChooser.hpp
@@ -92,7 +92,7 @@
     regions_at_put(_curr_index, NULL);
     assert(hr->reclaimable_bytes() <= _remaining_reclaimable_bytes,
            err_msg("remaining reclaimable bytes inconsistent "
-                   "from region: "SIZE_FORMAT" remaining: "SIZE_FORMAT,
+                   "from region: " SIZE_FORMAT " remaining: " SIZE_FORMAT,
                    hr->reclaimable_bytes(), _remaining_reclaimable_bytes));
     _remaining_reclaimable_bytes -= hr->reclaimable_bytes();
     _curr_index += 1;
diff --git a/src/share/vm/gc_implementation/g1/concurrentMark.cpp b/src/share/vm/gc_implementation/g1/concurrentMark.cpp
index a5c4261..ea0e564 100644
--- a/src/share/vm/gc_implementation/g1/concurrentMark.cpp
+++ b/src/share/vm/gc_implementation/g1/concurrentMark.cpp
@@ -284,7 +284,7 @@
     if (PrintGCDetails && Verbose) {
       // Failed to double capacity, continue;
       gclog_or_tty->print(" (benign) Failed to expand marking stack capacity from "
-                          SIZE_FORMAT"K to " SIZE_FORMAT"K",
+                          SIZE_FORMAT "K to " SIZE_FORMAT "K",
                           _capacity / K, new_capacity / K);
     }
   }
@@ -581,7 +581,7 @@
   _verbose_level = verbose_level;
 
   if (verbose_low()) {
-    gclog_or_tty->print_cr("[global] init, heap start = "PTR_FORMAT", "
+    gclog_or_tty->print_cr("[global] init, heap start = " PTR_FORMAT", "
                            "heap end = " INTPTR_FORMAT, p2i(_heap_start), p2i(_heap_end));
   }
 
@@ -837,7 +837,7 @@
     // in a STW phase.
     assert(!concurrent_marking_in_progress(), "invariant");
     assert(out_of_regions(),
-           err_msg("only way to get here: _finger: "PTR_FORMAT", _heap_end: "PTR_FORMAT,
+           err_msg("only way to get here: _finger: " PTR_FORMAT ", _heap_end: " PTR_FORMAT,
                    p2i(_finger), p2i(_heap_end)));
   }
 }
@@ -1452,7 +1452,7 @@
 
     assert(start <= hr->end() && start <= ntams && ntams <= hr->end(),
            err_msg("Preconditions not met - "
-                   "start: "PTR_FORMAT", ntams: "PTR_FORMAT", end: "PTR_FORMAT,
+                   "start: " PTR_FORMAT ", ntams: " PTR_FORMAT ", end: " PTR_FORMAT,
                    p2i(start), p2i(ntams), p2i(hr->end())));
 
     // Find the first marked object at or after "start".
@@ -1769,10 +1769,10 @@
       }
 
       assert(end_idx <= _card_bm->size(),
-             err_msg("oob: end_idx=  "SIZE_FORMAT", bitmap size= "SIZE_FORMAT,
+             err_msg("oob: end_idx=  " SIZE_FORMAT ", bitmap size= " SIZE_FORMAT,
                      end_idx, _card_bm->size()));
       assert(start_idx < _card_bm->size(),
-             err_msg("oob: start_idx=  "SIZE_FORMAT", bitmap size= "SIZE_FORMAT,
+             err_msg("oob: start_idx=  " SIZE_FORMAT ", bitmap size= " SIZE_FORMAT,
                      start_idx, _card_bm->size()));
 
       _cm->set_card_bitmap_range(_card_bm, start_idx, end_idx, true /* is_par */);
@@ -2277,7 +2277,7 @@
       oop obj = oopDesc::load_decode_heap_oop(p);
       if (_cm->verbose_high()) {
         gclog_or_tty->print_cr("\t[%u] we're looking at location "
-                               "*"PTR_FORMAT" = "PTR_FORMAT,
+                               "*" PTR_FORMAT " = " PTR_FORMAT,
                                _task->worker_id(), p2i(p), p2i((void*) obj));
       }
 
@@ -2846,7 +2846,7 @@
       }
     }
 
-    _out->print_cr("  "PTR_FORMAT": "PTR_FORMAT"%s%s",
+    _out->print_cr("  " PTR_FORMAT ": " PTR_FORMAT "%s%s",
                    p2i(p), p2i((void*) obj), str, str2);
   }
 };
@@ -2873,7 +2873,7 @@
     bool print_it = _all || over_tams || marked;
 
     if (print_it) {
-      _out->print_cr(" "PTR_FORMAT"%s",
+      _out->print_cr(" " PTR_FORMAT "%s",
                      p2i((void *)o), (over_tams) ? " >" : (marked) ? " M" : "");
       PrintReachableOopClosure oopCl(_out, _vo, _all);
       o->oop_iterate_no_header(&oopCl);
@@ -2894,7 +2894,7 @@
     HeapWord* e = hr->end();
     HeapWord* t = hr->top();
     HeapWord* p = _g1h->top_at_mark_start(hr, _vo);
-    _out->print_cr("** ["PTR_FORMAT", "PTR_FORMAT"] top: "PTR_FORMAT" "
+    _out->print_cr("** [" PTR_FORMAT ", " PTR_FORMAT "] top: " PTR_FORMAT " "
                    "TAMS: " PTR_FORMAT, p2i(b), p2i(e), p2i(t), p2i(p));
     _out->cr();
 
@@ -3018,9 +3018,9 @@
       HeapWord*   limit         = curr_region->next_top_at_mark_start();
 
       if (verbose_low()) {
-        gclog_or_tty->print_cr("[%u] curr_region = "PTR_FORMAT" "
-                               "["PTR_FORMAT", "PTR_FORMAT"), "
-                               "limit = "PTR_FORMAT,
+        gclog_or_tty->print_cr("[%u] curr_region = " PTR_FORMAT " "
+                               "[" PTR_FORMAT ", " PTR_FORMAT "), "
+                               "limit = " PTR_FORMAT,
                                worker_id, p2i(curr_region), p2i(bottom), p2i(end), p2i(limit));
       }
 
@@ -3035,7 +3035,7 @@
 
       if (limit > bottom) {
         if (verbose_low()) {
-          gclog_or_tty->print_cr("[%u] region "PTR_FORMAT" is not empty, "
+          gclog_or_tty->print_cr("[%u] region " PTR_FORMAT " is not empty, "
                                  "returning it ", worker_id, p2i(curr_region));
         }
         return curr_region;
@@ -3043,7 +3043,7 @@
         assert(limit == bottom,
                "the region limit should be at bottom");
         if (verbose_low()) {
-          gclog_or_tty->print_cr("[%u] region "PTR_FORMAT" is empty, "
+          gclog_or_tty->print_cr("[%u] region " PTR_FORMAT " is empty, "
                                  "returning NULL", worker_id, p2i(curr_region));
         }
         // we return NULL and the caller should try calling
@@ -3055,13 +3055,13 @@
       if (verbose_low()) {
         if (curr_region == NULL) {
           gclog_or_tty->print_cr("[%u] found uncommitted region, moving finger, "
-                                 "global finger = "PTR_FORMAT", "
-                                 "our finger = "PTR_FORMAT,
+                                 "global finger = " PTR_FORMAT ", "
+                                 "our finger = " PTR_FORMAT,
                                  worker_id, p2i(_finger), p2i(finger));
         } else {
           gclog_or_tty->print_cr("[%u] somebody else moved the finger, "
-                                 "global finger = "PTR_FORMAT", "
-                                 "our finger = "PTR_FORMAT,
+                                 "global finger = " PTR_FORMAT ", "
+                                 "our finger = " PTR_FORMAT,
                                  worker_id, p2i(_finger), p2i(finger));
         }
       }
@@ -3097,7 +3097,7 @@
 
   void do_object_work(oop obj) {
     guarantee(!_g1h->obj_in_cs(obj),
-              err_msg("obj: "PTR_FORMAT" in CSet, phase: %s, info: %d",
+              err_msg("obj: " PTR_FORMAT " in CSet, phase: %s, info: %d",
                       p2i((void*) obj), phase_str(), _info));
   }
 
@@ -3158,7 +3158,7 @@
     // here.
     HeapRegion* global_hr = _g1h->heap_region_containing_raw(global_finger);
     guarantee(global_hr == NULL || global_finger == global_hr->bottom(),
-              err_msg("global finger: "PTR_FORMAT" region: "HR_FORMAT,
+              err_msg("global finger: " PTR_FORMAT " region: " HR_FORMAT,
                       p2i(global_finger), HR_FORMAT_PARAMS(global_hr)));
   }
 
@@ -3172,7 +3172,7 @@
       HeapRegion* task_hr = _g1h->heap_region_containing_raw(task_finger);
       guarantee(task_hr == NULL || task_finger == task_hr->bottom() ||
                 !task_hr->in_collection_set(),
-                err_msg("task finger: "PTR_FORMAT" region: "HR_FORMAT,
+                err_msg("task finger: " PTR_FORMAT " region: " HR_FORMAT,
                         p2i(task_finger), HR_FORMAT_PARAMS(task_hr)));
     }
   }
@@ -3214,8 +3214,8 @@
 
     assert(start <= limit && limit <= hr->top() && hr->top() <= hr->end(),
            err_msg("Preconditions not met - "
-                   "start: "PTR_FORMAT", limit: "PTR_FORMAT", "
-                   "top: "PTR_FORMAT", end: "PTR_FORMAT,
+                   "start: " PTR_FORMAT ", limit: " PTR_FORMAT ", "
+                   "top: " PTR_FORMAT ", end: " PTR_FORMAT,
                    p2i(start), p2i(limit), p2i(hr->top()), p2i(hr->end())));
 
     assert(hr->next_marked_bytes() == 0, "Precondition");
@@ -3494,7 +3494,7 @@
 #ifndef PRODUCT
 // for debugging purposes
 void ConcurrentMark::print_finger() {
-  gclog_or_tty->print_cr("heap ["PTR_FORMAT", "PTR_FORMAT"), global finger = "PTR_FORMAT,
+  gclog_or_tty->print_cr("heap [" PTR_FORMAT ", " PTR_FORMAT "), global finger = " PTR_FORMAT,
                          p2i(_heap_start), p2i(_heap_end), p2i(_finger));
   for (uint i = 0; i < _max_worker_id; ++i) {
     gclog_or_tty->print("   %u: " PTR_FORMAT, i, p2i(_tasks[i]->finger()));
@@ -3579,7 +3579,7 @@
         "claim_region() should have filtered out continues humongous regions");
 
   if (_cm->verbose_low()) {
-    gclog_or_tty->print_cr("[%u] setting up for region "PTR_FORMAT,
+    gclog_or_tty->print_cr("[%u] setting up for region " PTR_FORMAT,
                            _worker_id, p2i(hr));
   }
 
@@ -3596,7 +3596,7 @@
   if (limit == bottom) {
     if (_cm->verbose_low()) {
       gclog_or_tty->print_cr("[%u] found an empty region "
-                             "["PTR_FORMAT", "PTR_FORMAT")",
+                             "[" PTR_FORMAT ", " PTR_FORMAT ")",
                              _worker_id, p2i(bottom), p2i(limit));
     }
     // The region was collected underneath our feet.
@@ -3628,7 +3628,7 @@
 void CMTask::giveup_current_region() {
   assert(_curr_region != NULL, "invariant");
   if (_cm->verbose_low()) {
-    gclog_or_tty->print_cr("[%u] giving up region "PTR_FORMAT,
+    gclog_or_tty->print_cr("[%u] giving up region " PTR_FORMAT,
                            _worker_id, p2i(_curr_region));
   }
   clear_region_fields();
@@ -3750,7 +3750,7 @@
 
   if (_cm->verbose_medium()) {
       gclog_or_tty->print_cr("[%u] regular clock, interval = %1.2lfms, "
-                        "scanned = "SIZE_FORMAT"%s, refs reached = "SIZE_FORMAT"%s",
+                        "scanned = " SIZE_FORMAT "%s, refs reached = " SIZE_FORMAT "%s",
                         _worker_id, last_interval_ms,
                         _words_scanned,
                         (_words_scanned >= _words_scanned_limit) ? " (*)" : "",
@@ -3919,7 +3919,7 @@
       statsOnly( ++_local_pops );
 
       if (_cm->verbose_high()) {
-        gclog_or_tty->print_cr("[%u] popped "PTR_FORMAT, _worker_id,
+        gclog_or_tty->print_cr("[%u] popped " PTR_FORMAT, _worker_id,
                                p2i((void*) obj));
       }
 
@@ -4272,8 +4272,8 @@
 
       if (_cm->verbose_low()) {
         gclog_or_tty->print_cr("[%u] we're scanning part "
-                               "["PTR_FORMAT", "PTR_FORMAT") "
-                               "of region "HR_FORMAT,
+                               "[" PTR_FORMAT ", " PTR_FORMAT ") "
+                               "of region " HR_FORMAT,
                                _worker_id, p2i(_finger), p2i(_region_limit),
                                HR_FORMAT_PARAMS(_curr_region));
       }
@@ -4360,7 +4360,7 @@
 
         if (_cm->verbose_low()) {
           gclog_or_tty->print_cr("[%u] we successfully claimed "
-                                 "region "PTR_FORMAT,
+                                 "region " PTR_FORMAT,
                                  _worker_id, p2i(claimed_region));
         }
 
@@ -4421,7 +4421,7 @@
 
       if (_cm->try_stealing(_worker_id, &_hash_seed, obj)) {
         if (_cm->verbose_medium()) {
-          gclog_or_tty->print_cr("[%u] stolen "PTR_FORMAT" successfully",
+          gclog_or_tty->print_cr("[%u] stolen " PTR_FORMAT " successfully",
                                  _worker_id, p2i((void*) obj));
         }
 
@@ -4629,7 +4629,7 @@
 // identify them easily in a large log file.
 #define G1PPRL_LINE_PREFIX            "###"
 
-#define G1PPRL_ADDR_BASE_FORMAT    " "PTR_FORMAT"-"PTR_FORMAT
+#define G1PPRL_ADDR_BASE_FORMAT    " " PTR_FORMAT "-" PTR_FORMAT
 #ifdef _LP64
 #define G1PPRL_ADDR_BASE_H_FORMAT  " %37s"
 #else // _LP64
@@ -4639,16 +4639,16 @@
 // For per-region info
 #define G1PPRL_TYPE_FORMAT            "   %-4s"
 #define G1PPRL_TYPE_H_FORMAT          "   %4s"
-#define G1PPRL_BYTE_FORMAT            "  "SIZE_FORMAT_W(9)
+#define G1PPRL_BYTE_FORMAT            "  " SIZE_FORMAT_W(9)
 #define G1PPRL_BYTE_H_FORMAT          "  %9s"
 #define G1PPRL_DOUBLE_FORMAT          "  %14.1f"
 #define G1PPRL_DOUBLE_H_FORMAT        "  %14s"
 
 // For summary info
-#define G1PPRL_SUM_ADDR_FORMAT(tag)    "  "tag":"G1PPRL_ADDR_BASE_FORMAT
-#define G1PPRL_SUM_BYTE_FORMAT(tag)    "  "tag": "SIZE_FORMAT
-#define G1PPRL_SUM_MB_FORMAT(tag)      "  "tag": %1.2f MB"
-#define G1PPRL_SUM_MB_PERC_FORMAT(tag) G1PPRL_SUM_MB_FORMAT(tag)" / %1.2f %%"
+#define G1PPRL_SUM_ADDR_FORMAT(tag)    "  " tag ":" G1PPRL_ADDR_BASE_FORMAT
+#define G1PPRL_SUM_BYTE_FORMAT(tag)    "  " tag ": " SIZE_FORMAT
+#define G1PPRL_SUM_MB_FORMAT(tag)      "  " tag ": %1.2f MB"
+#define G1PPRL_SUM_MB_PERC_FORMAT(tag) G1PPRL_SUM_MB_FORMAT(tag) " / %1.2f %%"
 
 G1PrintRegionLivenessInfoClosure::
 G1PrintRegionLivenessInfoClosure(outputStream* out, const char* phase_name)
diff --git a/src/share/vm/gc_implementation/g1/concurrentMark.inline.hpp b/src/share/vm/gc_implementation/g1/concurrentMark.inline.hpp
index 4e84d49..46ab546 100644
--- a/src/share/vm/gc_implementation/g1/concurrentMark.inline.hpp
+++ b/src/share/vm/gc_implementation/g1/concurrentMark.inline.hpp
@@ -196,8 +196,8 @@
   assert(_bmStartWord <= (addr) && (addr) < (_bmStartWord + _bmWordSize),      \
          "outside underlying space?");                                         \
   assert(G1CollectedHeap::heap()->is_in_exact(addr),                           \
-         err_msg("Trying to access not available bitmap "PTR_FORMAT            \
-                 " corresponding to "PTR_FORMAT" (%u)",                        \
+         err_msg("Trying to access not available bitmap " PTR_FORMAT           \
+                 " corresponding to " PTR_FORMAT " (%u)",                      \
                  p2i(this), p2i(addr), G1CollectedHeap::heap()->addr_to_region(addr)));
 
 inline void CMBitMap::mark(HeapWord* addr) {
@@ -343,7 +343,7 @@
 
 inline void CMTask::deal_with_reference(oop obj) {
   if (_cm->verbose_high()) {
-    gclog_or_tty->print_cr("[%u] we're dealing with reference = "PTR_FORMAT,
+    gclog_or_tty->print_cr("[%u] we're dealing with reference = " PTR_FORMAT,
                            _worker_id, p2i((void*) obj));
   }
 
@@ -392,7 +392,7 @@
   // assert that word_size is under an upper bound which is its
   // containing region's capacity.
   assert(word_size * HeapWordSize <= hr->capacity(),
-         err_msg("size: "SIZE_FORMAT" capacity: "SIZE_FORMAT" "HR_FORMAT,
+         err_msg("size: " SIZE_FORMAT " capacity: " SIZE_FORMAT " " HR_FORMAT,
                  word_size * HeapWordSize, hr->capacity(),
                  HR_FORMAT_PARAMS(hr)));
 
diff --git a/src/share/vm/gc_implementation/g1/g1AllocRegion.cpp b/src/share/vm/gc_implementation/g1/g1AllocRegion.cpp
index 697a402..f92ae11 100644
--- a/src/share/vm/gc_implementation/g1/g1AllocRegion.cpp
+++ b/src/share/vm/gc_implementation/g1/g1AllocRegion.cpp
@@ -140,7 +140,7 @@
 }
 
 void G1AllocRegion::fill_in_ext_msg(ar_ext_msg* msg, const char* message) {
-  msg->append("[%s] %s c: %u b: %s r: "PTR_FORMAT" u: "SIZE_FORMAT,
+  msg->append("[%s] %s c: %u b: %s r: " PTR_FORMAT " u: " SIZE_FORMAT,
               _name, message, _count, BOOL_TO_STR(_bot_updates),
               p2i(_alloc_region), _used_bytes_before);
 }
@@ -217,7 +217,7 @@
 
     if (G1_ALLOC_REGION_TRACING > 1) {
       if (result != NULL) {
-        jio_snprintf(rest_buffer, buffer_length, SIZE_FORMAT" "PTR_FORMAT,
+        jio_snprintf(rest_buffer, buffer_length, SIZE_FORMAT " " PTR_FORMAT,
                      word_size, result);
       } else if (word_size != 0) {
         jio_snprintf(rest_buffer, buffer_length, SIZE_FORMAT, word_size);
diff --git a/src/share/vm/gc_implementation/g1/g1Allocator.hpp b/src/share/vm/gc_implementation/g1/g1Allocator.hpp
index cf94856..d07446d 100644
--- a/src/share/vm/gc_implementation/g1/g1Allocator.hpp
+++ b/src/share/vm/gc_implementation/g1/g1Allocator.hpp
@@ -74,7 +74,7 @@
 
    void decrease_used(size_t bytes) {
      assert(_summary_bytes_used >= bytes,
-            err_msg("invariant: _summary_bytes_used: "SIZE_FORMAT" should be >= bytes: "SIZE_FORMAT,
+            err_msg("invariant: _summary_bytes_used: " SIZE_FORMAT " should be >= bytes: " SIZE_FORMAT,
                 _summary_bytes_used, bytes));
      _summary_bytes_used -= bytes;
    }
diff --git a/src/share/vm/gc_implementation/g1/g1BiasedArray.cpp b/src/share/vm/gc_implementation/g1/g1BiasedArray.cpp
index 8c5bef7..f0b51ac 100644
--- a/src/share/vm/gc_implementation/g1/g1BiasedArray.cpp
+++ b/src/share/vm/gc_implementation/g1/g1BiasedArray.cpp
@@ -36,19 +36,19 @@
 #ifndef PRODUCT
 void G1BiasedMappedArrayBase::verify_index(idx_t index) const {
   guarantee(_base != NULL, "Array not initialized");
-  guarantee(index < length(), err_msg("Index out of bounds index: "SIZE_FORMAT" length: "SIZE_FORMAT, index, length()));
+  guarantee(index < length(), err_msg("Index out of bounds index: " SIZE_FORMAT " length: " SIZE_FORMAT, index, length()));
 }
 
 void G1BiasedMappedArrayBase::verify_biased_index(idx_t biased_index) const {
   guarantee(_biased_base != NULL, "Array not initialized");
   guarantee(biased_index >= bias() && biased_index < (bias() + length()),
-    err_msg("Biased index out of bounds, index: "SIZE_FORMAT" bias: "SIZE_FORMAT" length: "SIZE_FORMAT, biased_index, bias(), length()));
+    err_msg("Biased index out of bounds, index: " SIZE_FORMAT " bias: " SIZE_FORMAT " length: " SIZE_FORMAT, biased_index, bias(), length()));
 }
 
 void G1BiasedMappedArrayBase::verify_biased_index_inclusive_end(idx_t biased_index) const {
   guarantee(_biased_base != NULL, "Array not initialized");
   guarantee(biased_index >= bias() && biased_index <= (bias() + length()),
-    err_msg("Biased index out of inclusive bounds, index: "SIZE_FORMAT" bias: "SIZE_FORMAT" length: "SIZE_FORMAT, biased_index, bias(), length()));
+    err_msg("Biased index out of inclusive bounds, index: " SIZE_FORMAT " bias: " SIZE_FORMAT " length: " SIZE_FORMAT, biased_index, bias(), length()));
 }
 
 class TestMappedArray : public G1BiasedMappedArray<int> {
diff --git a/src/share/vm/gc_implementation/g1/g1BlockOffsetTable.cpp b/src/share/vm/gc_implementation/g1/g1BlockOffsetTable.cpp
index 44f0d58..f6ef670 100644
--- a/src/share/vm/gc_implementation/g1/g1BlockOffsetTable.cpp
+++ b/src/share/vm/gc_implementation/g1/g1BlockOffsetTable.cpp
@@ -385,11 +385,11 @@
     HeapWord* card_addr = _array->address_for_index(card);
     HeapWord* block_start = block_start_const(card_addr);
     if (block_start != obj_start) {
-      gclog_or_tty->print_cr("block start: "PTR_FORMAT" is incorrect - "
-                             "card index: "SIZE_FORMAT" "
-                             "card addr: "PTR_FORMAT" BOT entry: %u "
-                             "obj: "PTR_FORMAT" word size: "SIZE_FORMAT" "
-                             "cards: ["SIZE_FORMAT","SIZE_FORMAT"]",
+      gclog_or_tty->print_cr("block start: " PTR_FORMAT " is incorrect - "
+                             "card index: " SIZE_FORMAT " "
+                             "card addr: " PTR_FORMAT " BOT entry: %u "
+                             "obj: " PTR_FORMAT " word size: " SIZE_FORMAT " "
+                             "cards: [" SIZE_FORMAT "," SIZE_FORMAT "]",
                              block_start, card, card_addr,
                              _array->offset_array(card),
                              obj_start, word_size, first_card, last_card);
@@ -404,11 +404,11 @@
 G1BlockOffsetArray::print_on(outputStream* out) {
   size_t from_index = _array->index_for(_bottom);
   size_t to_index = _array->index_for(_end);
-  out->print_cr(">> BOT for area ["PTR_FORMAT","PTR_FORMAT") "
-                "cards ["SIZE_FORMAT","SIZE_FORMAT")",
+  out->print_cr(">> BOT for area [" PTR_FORMAT "," PTR_FORMAT ") "
+                "cards [" SIZE_FORMAT "," SIZE_FORMAT ")",
                 _bottom, _end, from_index, to_index);
   for (size_t i = from_index; i < to_index; ++i) {
-    out->print_cr("  entry "SIZE_FORMAT_W(8)" | "PTR_FORMAT" : %3u",
+    out->print_cr("  entry " SIZE_FORMAT_W(8) " | " PTR_FORMAT " : %3u",
                   i, _array->address_for_index(i),
                   (uint) _array->offset_array(i));
   }
@@ -488,7 +488,7 @@
 void
 G1BlockOffsetArrayContigSpace::print_on(outputStream* out) {
   G1BlockOffsetArray::print_on(out);
-  out->print_cr("  next offset threshold: "PTR_FORMAT, _next_offset_threshold);
-  out->print_cr("  next offset index:     "SIZE_FORMAT, _next_offset_index);
+  out->print_cr("  next offset threshold: " PTR_FORMAT, _next_offset_threshold);
+  out->print_cr("  next offset index:     " SIZE_FORMAT, _next_offset_index);
 }
 #endif // !PRODUCT
diff --git a/src/share/vm/gc_implementation/g1/g1CardCounts.cpp b/src/share/vm/gc_implementation/g1/g1CardCounts.cpp
index 76bf850..0023998 100644
--- a/src/share/vm/gc_implementation/g1/g1CardCounts.cpp
+++ b/src/share/vm/gc_implementation/g1/g1CardCounts.cpp
@@ -44,7 +44,7 @@
 void G1CardCounts::clear_range(size_t from_card_num, size_t to_card_num) {
   if (has_count_table()) {
     assert(from_card_num < to_card_num,
-           err_msg("Wrong order? from: " SIZE_FORMAT ", to: "SIZE_FORMAT,
+           err_msg("Wrong order? from: " SIZE_FORMAT ", to: " SIZE_FORMAT,
                    from_card_num, to_card_num));
     Copy::fill_to_bytes(&_card_counts[from_card_num], (to_card_num - from_card_num));
   }
@@ -87,7 +87,7 @@
   if (has_count_table()) {
     size_t card_num = ptr_2_card_num(card_ptr);
     assert(card_num < _reserved_max_card_num,
-           err_msg("Card "SIZE_FORMAT" outside of card counts table (max size "SIZE_FORMAT")",
+           err_msg("Card " SIZE_FORMAT " outside of card counts table (max size " SIZE_FORMAT ")",
                    card_num, _reserved_max_card_num));
     count = (uint) _card_counts[card_num];
     if (count < G1ConcRSHotCardLimit) {
diff --git a/src/share/vm/gc_implementation/g1/g1CardCounts.hpp b/src/share/vm/gc_implementation/g1/g1CardCounts.hpp
index 7dcad45..b2ab012 100644
--- a/src/share/vm/gc_implementation/g1/g1CardCounts.hpp
+++ b/src/share/vm/gc_implementation/g1/g1CardCounts.hpp
@@ -91,7 +91,7 @@
 
   jbyte* card_num_2_ptr(size_t card_num) {
     assert(card_num >= 0 && card_num < _reserved_max_card_num,
-           err_msg("card num out of range: "SIZE_FORMAT, card_num));
+           err_msg("card num out of range: " SIZE_FORMAT, card_num));
     return (jbyte*) (_ct_bot + card_num);
   }
 
diff --git a/src/share/vm/gc_implementation/g1/g1CodeCacheRemSet.cpp b/src/share/vm/gc_implementation/g1/g1CodeCacheRemSet.cpp
index c7cad45..fb13379 100644
--- a/src/share/vm/gc_implementation/g1/g1CodeCacheRemSet.cpp
+++ b/src/share/vm/gc_implementation/g1/g1CodeCacheRemSet.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -76,10 +76,16 @@
   static size_t static_mem_size() {
     return sizeof(_purge_list);
   }
+
+  size_t mem_size();
 };
 
 CodeRootSetTable* volatile CodeRootSetTable::_purge_list = NULL;
 
+size_t CodeRootSetTable::mem_size() {
+  return sizeof(CodeRootSetTable) + (entry_size() * number_of_entries()) + (sizeof(HashtableBucket<mtGC>) * table_size());
+}
+
 CodeRootSetTable::Entry* CodeRootSetTable::new_entry(nmethod* nm) {
   unsigned int hash = compute_hash(nm);
   Entry* entry = (Entry*) new_entry_free_list();
@@ -232,7 +238,6 @@
   OrderAccess::release_store_ptr(&_table, temp);
 }
 
-
 void G1CodeRootSet::purge() {
   CodeRootSetTable::purge();
 }
@@ -247,12 +252,13 @@
     allocate_small_table();
   }
   added = _table->add(method);
-  if (_length == Threshold) {
-    move_to_large();
-  }
   if (added) {
+    if (_length == Threshold) {
+      move_to_large();
+    }
     ++_length;
   }
+  assert(_length == (size_t)_table->number_of_entries(), "sizes should match");
 }
 
 bool G1CodeRootSet::remove(nmethod* method) {
@@ -266,11 +272,13 @@
       clear();
     }
   }
+  assert((_length == 0 && _table == NULL) ||
+         (_length == (size_t)_table->number_of_entries()), "sizes should match");
   return removed;
 }
 
 bool G1CodeRootSet::contains(nmethod* method) {
-  CodeRootSetTable* table = load_acquire_table();
+  CodeRootSetTable* table = load_acquire_table(); // contains() may be called outside of lock, so ensure mem sync.
   if (table != NULL) {
     return table->contains(method);
   }
@@ -284,8 +292,7 @@
 }
 
 size_t G1CodeRootSet::mem_size() {
-  return sizeof(*this) +
-      (_table != NULL ? sizeof(CodeRootSetTable) + _table->entry_size() * _length : 0);
+  return sizeof(*this) + (_table != NULL ? _table->mem_size() : 0);
 }
 
 void G1CodeRootSet::nmethods_do(CodeBlobClosure* blk) const {
@@ -352,11 +359,11 @@
       assert(set1.is_empty(), "Code root set must be initially empty but is not.");
 
       assert(G1CodeRootSet::static_mem_size() == sizeof(void*),
-          err_msg("The code root set's static memory usage is incorrect, "SIZE_FORMAT" bytes", G1CodeRootSet::static_mem_size()));
+          err_msg("The code root set's static memory usage is incorrect, " SIZE_FORMAT " bytes", G1CodeRootSet::static_mem_size()));
 
       set1.add((nmethod*)1);
       assert(set1.length() == 1, err_msg("Added exactly one element, but set contains "
-          SIZE_FORMAT" elements", set1.length()));
+          SIZE_FORMAT " elements", set1.length()));
 
       const size_t num_to_add = (size_t)G1CodeRootSet::Threshold + 1;
 
@@ -365,14 +372,14 @@
       }
       assert(set1.length() == 1,
           err_msg("Duplicate detection should not have increased the set size but "
-              "is "SIZE_FORMAT, set1.length()));
+              "is " SIZE_FORMAT, set1.length()));
 
       for (size_t i = 2; i <= num_to_add; i++) {
         set1.add((nmethod*)(uintptr_t)(i));
       }
       assert(set1.length() == num_to_add,
-          err_msg("After adding in total "SIZE_FORMAT" distinct code roots, they "
-              "need to be in the set, but there are only "SIZE_FORMAT,
+          err_msg("After adding in total " SIZE_FORMAT " distinct code roots, they "
+              "need to be in the set, but there are only " SIZE_FORMAT,
               num_to_add, set1.length()));
 
       assert(CodeRootSetTable::_purge_list != NULL, "should have grown to large hashtable");
@@ -387,7 +394,7 @@
         }
       }
       assert(num_popped == num_to_add,
-          err_msg("Managed to pop "SIZE_FORMAT" code roots, but only "SIZE_FORMAT" "
+          err_msg("Managed to pop " SIZE_FORMAT " code roots, but only " SIZE_FORMAT " "
               "were added", num_popped, num_to_add));
       assert(CodeRootSetTable::_purge_list != NULL, "should have grown to large hashtable");
 
diff --git a/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp b/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp
index 76bfcd6..d1ca35e 100644
--- a/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp
+++ b/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp
@@ -230,7 +230,7 @@
   HeapRegion* last = NULL;
   while (curr != NULL) {
     if (!curr->is_young()) {
-      gclog_or_tty->print_cr("### YOUNG REGION "PTR_FORMAT"-"PTR_FORMAT" "
+      gclog_or_tty->print_cr("### YOUNG REGION " PTR_FORMAT "-" PTR_FORMAT " "
                              "incorrectly tagged (y: %d, surv: %d)",
                              curr->bottom(), curr->end(),
                              curr->is_young(), curr->is_survivor());
@@ -359,7 +359,7 @@
     if (curr == NULL)
       gclog_or_tty->print_cr("  empty");
     while (curr != NULL) {
-      gclog_or_tty->print_cr("  "HR_FORMAT", P: "PTR_FORMAT ", N: "PTR_FORMAT", age: %4d",
+      gclog_or_tty->print_cr("  " HR_FORMAT ", P: " PTR_FORMAT ", N: " PTR_FORMAT ", age: %4d",
                              HR_FORMAT_PARAMS(curr),
                              curr->prev_top_at_mark_start(),
                              curr->next_top_at_mark_start(),
@@ -490,7 +490,7 @@
   gclog_or_tty->print_cr("Log entries = %d, dirty cards = %d.",
                          clear.num_processed(), orig_count);
   guarantee(redirty.num_processed() == clear.num_processed(),
-            err_msg("Redirtied "SIZE_FORMAT" cards, bug cleared "SIZE_FORMAT,
+            err_msg("Redirtied " SIZE_FORMAT " cards, bug cleared " SIZE_FORMAT,
                     redirty.num_processed(), clear.num_processed()));
 
   CountNonCleanMemRegionClosure count3(this);
@@ -528,7 +528,7 @@
       HeapRegion* res = _hrm.allocate_free_region(is_old);
       if (G1ConcRegionFreeingVerbose) {
         gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "
-                               "allocated "HR_FORMAT" from secondary_free_list",
+                               "allocated " HR_FORMAT " from secondary_free_list",
                                HR_FORMAT_PARAMS(res));
       }
       return res;
@@ -1464,6 +1464,9 @@
       // Rebuild the strong code root lists for each region
       rebuild_strong_code_roots();
 
+      // Purge code root memory
+      purge_code_root_memory();
+
       if (true) { // FIXME
         MetaspaceGC::compute_new_size();
       }
@@ -1597,8 +1600,8 @@
   // This assert only makes sense here, before we adjust them
   // with respect to the min and max heap size.
   assert(minimum_desired_capacity <= maximum_desired_capacity,
-         err_msg("minimum_desired_capacity = "SIZE_FORMAT", "
-                 "maximum_desired_capacity = "SIZE_FORMAT,
+         err_msg("minimum_desired_capacity = " SIZE_FORMAT ", "
+                 "maximum_desired_capacity = " SIZE_FORMAT,
                  minimum_desired_capacity, maximum_desired_capacity));
 
   // Should not be greater than the heap max size. No need to adjust
@@ -2256,7 +2259,7 @@
   virtual bool doHeapRegion(HeapRegion* hr) {
     unsigned region_gc_time_stamp = hr->get_gc_time_stamp();
     if (_gc_time_stamp != region_gc_time_stamp) {
-      gclog_or_tty->print_cr("Region "HR_FORMAT" has GC time stamp = %d, "
+      gclog_or_tty->print_cr("Region " HR_FORMAT " has GC time stamp = %d, "
                              "expected %d", HR_FORMAT_PARAMS(hr),
                              region_gc_time_stamp, _gc_time_stamp);
       _failures = true;
@@ -2679,7 +2682,7 @@
     } else if (r->continuesHumongous()) {
       if (r->humongous_start_region() != _sh_region) {
         gclog_or_tty->print_cr("Region " HR_FORMAT ", "
-                               "HS = "PTR_FORMAT", should be "PTR_FORMAT,
+                               "HS = " PTR_FORMAT ", should be " PTR_FORMAT,
                                HR_FORMAT_PARAMS(r),
                                r->humongous_start_region(),
                                _sh_region);
@@ -2991,10 +2994,10 @@
     if (!oopDesc::is_null(heap_oop)) {
       oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
       if (_g1h->is_obj_dead_cond(obj, _vo)) {
-        gclog_or_tty->print_cr("Root location "PTR_FORMAT" "
-                              "points to dead obj "PTR_FORMAT, p, (void*) obj);
+        gclog_or_tty->print_cr("Root location " PTR_FORMAT " "
+                              "points to dead obj " PTR_FORMAT, p, (void*) obj);
         if (_vo == VerifyOption_G1UseMarkWord) {
-          gclog_or_tty->print_cr("  Mark word: "PTR_FORMAT, (void*)(obj->mark()));
+          gclog_or_tty->print_cr("  Mark word: " PTR_FORMAT, (void*)(obj->mark()));
         }
         obj->print_on(gclog_or_tty);
         _failures = true;
@@ -3041,9 +3044,9 @@
       // Verify that the strong code root list for this region
       // contains the nmethod
       if (!hrrs->strong_code_roots_list_contains(_nm)) {
-        gclog_or_tty->print_cr("Code root location "PTR_FORMAT" "
-                              "from nmethod "PTR_FORMAT" not in strong "
-                              "code roots for region ["PTR_FORMAT","PTR_FORMAT")",
+        gclog_or_tty->print_cr("Code root location " PTR_FORMAT " "
+                              "from nmethod " PTR_FORMAT " not in strong "
+                              "code roots for region [" PTR_FORMAT "," PTR_FORMAT ")",
                               p, _nm, hr->bottom(), hr->end());
         _failures = true;
       }
@@ -3173,7 +3176,7 @@
     if (o != NULL) {
       HeapWord *start = (HeapWord *) o;
       size_t word_sz = o->size();
-      gclog_or_tty->print("\nPrinting obj "PTR_FORMAT" of size " SIZE_FORMAT
+      gclog_or_tty->print("\nPrinting obj " PTR_FORMAT " of size " SIZE_FORMAT
                           " isMarkedPrev %d isMarkedNext %d isAllocSince %d\n",
                           (void*) o, word_sz,
                           _g1->isMarkedPrev(o),
@@ -3184,7 +3187,7 @@
       int *val;
       for (cur = start; cur < end; cur++) {
         val = (int *) cur;
-        gclog_or_tty->print("\t "PTR_FORMAT":"PTR_FORMAT"\n", val, *val);
+        gclog_or_tty->print("\t " PTR_FORMAT ":" PTR_FORMAT "\n", val, *val);
       }
     }
   }
@@ -3219,9 +3222,9 @@
         r->object_iterate(&not_dead_yet_cl);
         if (_vo != VerifyOption_G1UseNextMarking) {
           if (r->max_live_bytes() < not_dead_yet_cl.live_bytes()) {
-            gclog_or_tty->print_cr("["PTR_FORMAT","PTR_FORMAT"] "
-                                   "max_live_bytes "SIZE_FORMAT" "
-                                   "< calculated "SIZE_FORMAT,
+            gclog_or_tty->print_cr("[" PTR_FORMAT "," PTR_FORMAT "] "
+                                   "max_live_bytes " SIZE_FORMAT " "
+                                   "< calculated " SIZE_FORMAT,
                                    r->bottom(), r->end(),
                                    r->max_live_bytes(),
                                  not_dead_yet_cl.live_bytes());
@@ -3533,7 +3536,7 @@
     size_t occupied = hrrs->occupied();
     _occupied_sum += occupied;
 
-    gclog_or_tty->print_cr("Printing RSet for region "HR_FORMAT,
+    gclog_or_tty->print_cr("Printing RSet for region " HR_FORMAT,
                            HR_FORMAT_PARAMS(r));
     if (occupied == 0) {
       gclog_or_tty->print_cr("  RSet is empty");
@@ -3552,7 +3555,7 @@
   }
 
   ~PrintRSetsClosure() {
-    gclog_or_tty->print_cr("Occupied Sum: "SIZE_FORMAT, _occupied_sum);
+    gclog_or_tty->print_cr("Occupied Sum: " SIZE_FORMAT, _occupied_sum);
     gclog_or_tty->print_cr("========================================");
     gclog_or_tty->cr();
   }
@@ -4416,7 +4419,7 @@
 G1CollectedHeap::handle_evacuation_failure_par(G1ParScanThreadState* _par_scan_state,
                                                oop old) {
   assert(obj_in_cs(old),
-         err_msg("obj: "PTR_FORMAT" should still be in the CSet",
+         err_msg("obj: " PTR_FORMAT " should still be in the CSet",
                  (HeapWord*) old));
   markOop m = old->mark();
   oop forward_ptr = old->forward_to_atomic(old);
@@ -4450,7 +4453,7 @@
     // space for this object (old != forward_ptr) or they beat us in
     // self-forwarding it (old == forward_ptr).
     assert(old == forward_ptr || !obj_in_cs(forward_ptr),
-           err_msg("obj: "PTR_FORMAT" forwarded to: "PTR_FORMAT" "
+           err_msg("obj: " PTR_FORMAT " forwarded to: " PTR_FORMAT " "
                    "should not be in the CSet",
                    (HeapWord*) old, (HeapWord*) forward_ptr));
     return forward_ptr;
@@ -4837,16 +4840,16 @@
 
   ~G1StringSymbolTableUnlinkTask() {
     guarantee(!_process_strings || !_do_in_parallel || StringTable::parallel_claimed_index() >= _initial_string_table_size,
-              err_msg("claim value "INT32_FORMAT" after unlink less than initial string table size "INT32_FORMAT,
+              err_msg("claim value " INT32_FORMAT " after unlink less than initial string table size " INT32_FORMAT,
                       StringTable::parallel_claimed_index(), _initial_string_table_size));
     guarantee(!_process_symbols || !_do_in_parallel || SymbolTable::parallel_claimed_index() >= _initial_symbol_table_size,
-              err_msg("claim value "INT32_FORMAT" after unlink less than initial symbol table size "INT32_FORMAT,
+              err_msg("claim value " INT32_FORMAT " after unlink less than initial symbol table size " INT32_FORMAT,
                       SymbolTable::parallel_claimed_index(), _initial_symbol_table_size));
 
     if (G1TraceStringSymbolTableScrubbing) {
       gclog_or_tty->print_cr("Cleaned string and symbol table, "
-                             "strings: "SIZE_FORMAT" processed, "SIZE_FORMAT" removed, "
-                             "symbols: "SIZE_FORMAT" processed, "SIZE_FORMAT" removed",
+                             "strings: " SIZE_FORMAT " processed, " SIZE_FORMAT " removed, "
+                             "symbols: " SIZE_FORMAT " processed, " SIZE_FORMAT " removed",
                              strings_processed(), strings_removed(),
                              symbols_processed(), symbols_removed());
     }
@@ -6029,13 +6032,13 @@
 bool G1CollectedHeap::verify_no_bits_over_tams(const char* bitmap_name, CMBitMapRO* bitmap,
                                                HeapWord* tams, HeapWord* end) {
   guarantee(tams <= end,
-            err_msg("tams: "PTR_FORMAT" end: "PTR_FORMAT, tams, end));
+            err_msg("tams: " PTR_FORMAT " end: " PTR_FORMAT, tams, end));
   HeapWord* result = bitmap->getNextMarkedWordAddress(tams, end);
   if (result < end) {
     gclog_or_tty->cr();
-    gclog_or_tty->print_cr("## wrong marked address on %s bitmap: "PTR_FORMAT,
+    gclog_or_tty->print_cr("## wrong marked address on %s bitmap: " PTR_FORMAT,
                            bitmap_name, result);
-    gclog_or_tty->print_cr("## %s tams: "PTR_FORMAT" end: "PTR_FORMAT,
+    gclog_or_tty->print_cr("## %s tams: " PTR_FORMAT " end: " PTR_FORMAT,
                            bitmap_name, tams, end);
     return false;
   }
@@ -6061,7 +6064,7 @@
     res_n = verify_no_bits_over_tams("next", next_bitmap, ntams, end);
   }
   if (!res_p || !res_n) {
-    gclog_or_tty->print_cr("#### Bitmap verification failed for "HR_FORMAT,
+    gclog_or_tty->print_cr("#### Bitmap verification failed for " HR_FORMAT,
                            HR_FORMAT_PARAMS(hr));
     gclog_or_tty->print_cr("#### Caller: %s", caller);
     return false;
@@ -6373,7 +6376,7 @@
         !r->rem_set()->is_empty()) {
 
       if (G1TraceEagerReclaimHumongousObjects) {
-        gclog_or_tty->print_cr("Live humongous region %u size "SIZE_FORMAT" start "PTR_FORMAT" length "UINT32_FORMAT" with remset "SIZE_FORMAT" code roots "SIZE_FORMAT" is marked %d reclaim candidate %d type array %d",
+        gclog_or_tty->print_cr("Live humongous region %u size " SIZE_FORMAT " start " PTR_FORMAT " length " UINT32_FORMAT " with remset " SIZE_FORMAT " code roots " SIZE_FORMAT " is marked %d reclaim candidate %d type array %d",
                                region_idx,
                                obj->size()*HeapWordSize,
                                r->bottom(),
@@ -6395,7 +6398,7 @@
                       r->bottom()));
 
     if (G1TraceEagerReclaimHumongousObjects) {
-      gclog_or_tty->print_cr("Dead humongous region %u size "SIZE_FORMAT" start "PTR_FORMAT" length "UINT32_FORMAT" with remset "SIZE_FORMAT" code roots "SIZE_FORMAT" is marked %d reclaim candidate %d type array %d",
+      gclog_or_tty->print_cr("Dead humongous region %u size " SIZE_FORMAT " start " PTR_FORMAT " length " UINT32_FORMAT " with remset " SIZE_FORMAT " code roots " SIZE_FORMAT " is marked %d reclaim candidate %d type array %d",
                              region_idx,
                              obj->size()*HeapWordSize,
                              r->bottom(),
@@ -6551,7 +6554,7 @@
   NoYoungRegionsClosure() : _success(true) { }
   bool doHeapRegion(HeapRegion* r) {
     if (r->is_young()) {
-      gclog_or_tty->print_cr("Region ["PTR_FORMAT", "PTR_FORMAT") tagged as young",
+      gclog_or_tty->print_cr("Region [" PTR_FORMAT ", " PTR_FORMAT ") tagged as young",
                              r->bottom(), r->end());
       _success = false;
     }
@@ -6680,7 +6683,7 @@
   }
   assert(_allocator->used_unlocked() == recalculate_used(),
          err_msg("inconsistent _allocator->used_unlocked(), "
-                 "value: "SIZE_FORMAT" recalculated: "SIZE_FORMAT,
+                 "value: " SIZE_FORMAT " recalculated: " SIZE_FORMAT,
                  _allocator->used_unlocked(), recalculate_used()));
 }
 
@@ -6901,8 +6904,8 @@
       oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
       HeapRegion* hr = _g1h->heap_region_containing(obj);
       assert(!hr->continuesHumongous(),
-             err_msg("trying to add code root "PTR_FORMAT" in continuation of humongous region "HR_FORMAT
-                     " starting at "HR_FORMAT,
+             err_msg("trying to add code root " PTR_FORMAT " in continuation of humongous region " HR_FORMAT
+                     " starting at " HR_FORMAT,
                      _nm, HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region())));
 
       // HeapRegion::add_strong_code_root_locked() avoids adding duplicate entries.
@@ -6928,8 +6931,8 @@
       oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
       HeapRegion* hr = _g1h->heap_region_containing(obj);
       assert(!hr->continuesHumongous(),
-             err_msg("trying to remove code root "PTR_FORMAT" in continuation of humongous region "HR_FORMAT
-                     " starting at "HR_FORMAT,
+             err_msg("trying to remove code root " PTR_FORMAT " in continuation of humongous region " HR_FORMAT
+                     " starting at " HR_FORMAT,
                      _nm, HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region())));
 
       hr->remove_strong_code_root(_nm);
diff --git a/src/share/vm/gc_implementation/g1/g1CollectedHeap.inline.hpp b/src/share/vm/gc_implementation/g1/g1CollectedHeap.inline.hpp
index 0fd2786..7b26fdb 100644
--- a/src/share/vm/gc_implementation/g1/g1CollectedHeap.inline.hpp
+++ b/src/share/vm/gc_implementation/g1/g1CollectedHeap.inline.hpp
@@ -81,7 +81,7 @@
 
 inline uint G1CollectedHeap::addr_to_region(HeapWord* addr) const {
   assert(is_in_reserved(addr),
-         err_msg("Cannot calculate region index for address "PTR_FORMAT" that is outside of the heap ["PTR_FORMAT", "PTR_FORMAT")",
+         err_msg("Cannot calculate region index for address " PTR_FORMAT " that is outside of the heap [" PTR_FORMAT ", " PTR_FORMAT ")",
                  p2i(addr), p2i(_reserved.start()), p2i(_reserved.end())));
   return (uint)(pointer_delta(addr, _reserved.start(), sizeof(uint8_t)) >> HeapRegion::LogOfHRGrainBytes);
 }
@@ -94,7 +94,7 @@
 inline HeapRegion* G1CollectedHeap::heap_region_containing_raw(const T addr) const {
   assert(addr != NULL, "invariant");
   assert(is_in_g1_reserved((const void*) addr),
-      err_msg("Address "PTR_FORMAT" is outside of the heap ranging from ["PTR_FORMAT" to "PTR_FORMAT")",
+      err_msg("Address " PTR_FORMAT " is outside of the heap ranging from [" PTR_FORMAT " to " PTR_FORMAT ")",
           p2i((void*)addr), p2i(g1_reserved().start()), p2i(g1_reserved().end())));
   return _hrm.addr_to_region((HeapWord*) addr);
 }
diff --git a/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp b/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp
index ea80c44..c4463f5 100644
--- a/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp
+++ b/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp
@@ -199,7 +199,7 @@
   const size_t region_size = HeapRegion::GrainWords;
   if (YoungPLABSize > region_size || OldPLABSize > region_size) {
     char buffer[128];
-    jio_snprintf(buffer, sizeof(buffer), "%sPLABSize should be at most "SIZE_FORMAT,
+    jio_snprintf(buffer, sizeof(buffer), "%sPLABSize should be at most " SIZE_FORMAT,
                  OldPLABSize > region_size ? "Old" : "Young", region_size);
     vm_exit_during_initialization(buffer);
   }
@@ -846,7 +846,7 @@
   update_survivors_policy();
 
   assert(_g1->used() == _g1->recalculate_used(),
-         err_msg("sanity, used: "SIZE_FORMAT" recalculate_used: "SIZE_FORMAT,
+         err_msg("sanity, used: " SIZE_FORMAT " recalculate_used: " SIZE_FORMAT,
                  _g1->used(), _g1->recalculate_used()));
 
   double s_w_t_ms = (start_time_sec - _stop_world_start) * 1000.0;
@@ -1231,10 +1231,10 @@
     (_young_list_target_length * HeapRegion::GrainBytes) - survivor_used_bytes_after_gc;
 
   gclog_or_tty->print(
-    "   [Eden: "EXT_SIZE_FORMAT"("EXT_SIZE_FORMAT")->"EXT_SIZE_FORMAT"("EXT_SIZE_FORMAT") "
-    "Survivors: "EXT_SIZE_FORMAT"->"EXT_SIZE_FORMAT" "
-    "Heap: "EXT_SIZE_FORMAT"("EXT_SIZE_FORMAT")->"
-    EXT_SIZE_FORMAT"("EXT_SIZE_FORMAT")]",
+    "   [Eden: " EXT_SIZE_FORMAT "(" EXT_SIZE_FORMAT ")->" EXT_SIZE_FORMAT "(" EXT_SIZE_FORMAT ") "
+    "Survivors: " EXT_SIZE_FORMAT "->" EXT_SIZE_FORMAT " "
+    "Heap: " EXT_SIZE_FORMAT "(" EXT_SIZE_FORMAT ")->"
+    EXT_SIZE_FORMAT "(" EXT_SIZE_FORMAT ")]",
     EXT_SIZE_PARAMS(_eden_used_bytes_before_gc),
     EXT_SIZE_PARAMS(_eden_capacity_bytes_before_gc),
     EXT_SIZE_PARAMS(eden_used_bytes_after_gc),
@@ -1851,7 +1851,7 @@
   while (csr != NULL) {
     HeapRegion* next = csr->next_in_collection_set();
     assert(csr->in_collection_set(), "bad CS");
-    st->print_cr("  "HR_FORMAT", P: "PTR_FORMAT "N: "PTR_FORMAT", age: %4d",
+    st->print_cr("  " HR_FORMAT ", P: " PTR_FORMAT "N: " PTR_FORMAT ", age: %4d",
                  HR_FORMAT_PARAMS(csr),
                  csr->prev_top_at_mark_start(), csr->next_top_at_mark_start(),
                  csr->age_in_surv_rate_group_cond());
diff --git a/src/share/vm/gc_implementation/g1/g1ErgoVerbose.hpp b/src/share/vm/gc_implementation/g1/g1ErgoVerbose.hpp
index eff1196..fff1663 100644
--- a/src/share/vm/gc_implementation/g1/g1ErgoVerbose.hpp
+++ b/src/share/vm/gc_implementation/g1/g1ErgoVerbose.hpp
@@ -121,15 +121,15 @@
 // Single parameter format strings
 #define ergo_format_str(_name_)      ", " _name_ ": %s"
 #define ergo_format_region(_name_)   ", " _name_ ": %u regions"
-#define ergo_format_byte(_name_)     ", " _name_ ": "SIZE_FORMAT" bytes"
+#define ergo_format_byte(_name_)     ", " _name_ ": " SIZE_FORMAT " bytes"
 #define ergo_format_double(_name_)   ", " _name_ ": %1.2f"
 #define ergo_format_perc(_name_)     ", " _name_ ": %1.2f %%"
 #define ergo_format_ms(_name_)       ", " _name_ ": %1.2f ms"
-#define ergo_format_size(_name_)     ", " _name_ ": "SIZE_FORMAT
+#define ergo_format_size(_name_)     ", " _name_ ": " SIZE_FORMAT
 
 // Double parameter format strings
 #define ergo_format_byte_perc(_name_)                                   \
-                             ", " _name_ ": "SIZE_FORMAT" bytes (%1.2f %%)"
+                             ", " _name_ ": " SIZE_FORMAT " bytes (%1.2f %%)"
 
 // Generates the format string
 #define ergo_format(_extra_format_)                           \
diff --git a/src/share/vm/gc_implementation/g1/g1GCPhaseTimes.cpp b/src/share/vm/gc_implementation/g1/g1GCPhaseTimes.cpp
index c037110..d43976d 100644
--- a/src/share/vm/gc_implementation/g1/g1GCPhaseTimes.cpp
+++ b/src/share/vm/gc_implementation/g1/g1GCPhaseTimes.cpp
@@ -41,13 +41,13 @@
   int _cur;
 
   void vappend(const char* format, va_list ap)  ATTRIBUTE_PRINTF(2, 0) {
-    int res = vsnprintf(&_buffer[_cur], BUFFER_LEN - _cur, format, ap);
-    if (res != -1) {
-      _cur += res;
-    } else {
+    int res = os::vsnprintf(&_buffer[_cur], BUFFER_LEN - _cur, format, ap);
+    if (res > BUFFER_LEN) {
       DEBUG_ONLY(warning("buffer too small in LineBuffer");)
       _buffer[BUFFER_LEN -1] = 0;
       _cur = BUFFER_LEN; // vsnprintf above should not add to _buffer if we are called again
+    } else if (res != -1) {
+      _cur += res;
     }
   }
 
@@ -332,7 +332,7 @@
 }
 
 void G1GCPhaseTimes::print_stats(int level, const char* str, size_t value) {
-  LineBuffer(level).append_and_print_cr("[%s: "SIZE_FORMAT"]", str, value);
+  LineBuffer(level).append_and_print_cr("[%s: " SIZE_FORMAT "]", str, value);
 }
 
 void G1GCPhaseTimes::print_stats(int level, const char* str, double value, uint workers) {
@@ -452,7 +452,7 @@
 
     if (phase->_thread_work_items != NULL) {
       LineBuffer buf2(phase->_thread_work_items->_indent_level);
-      buf2.append_and_print_cr("[%s:  "SIZE_FORMAT"]", phase->_thread_work_items->_title, _phase_times->sum_thread_work_items(phase_id));
+      buf2.append_and_print_cr("[%s:  " SIZE_FORMAT "]", phase->_thread_work_items->_title, _phase_times->sum_thread_work_items(phase_id));
     }
   }
 
diff --git a/src/share/vm/gc_implementation/g1/g1HRPrinter.cpp b/src/share/vm/gc_implementation/g1/g1HRPrinter.cpp
index 8139048..ac56309 100644
--- a/src/share/vm/gc_implementation/g1/g1HRPrinter.cpp
+++ b/src/share/vm/gc_implementation/g1/g1HRPrinter.cpp
@@ -84,18 +84,18 @@
 
   if (type_str != NULL) {
     if (top != NULL) {
-      gclog_or_tty->print_cr(G1HR_PREFIX" %s(%s) "PTR_FORMAT" "PTR_FORMAT,
+      gclog_or_tty->print_cr(G1HR_PREFIX " %s(%s) " PTR_FORMAT " " PTR_FORMAT,
                              action_str, type_str, bottom, top);
     } else {
-      gclog_or_tty->print_cr(G1HR_PREFIX" %s(%s) "PTR_FORMAT,
+      gclog_or_tty->print_cr(G1HR_PREFIX " %s(%s) " PTR_FORMAT,
                              action_str, type_str, bottom);
     }
   } else {
     if (top != NULL) {
-      gclog_or_tty->print_cr(G1HR_PREFIX" %s "PTR_FORMAT" "PTR_FORMAT,
+      gclog_or_tty->print_cr(G1HR_PREFIX " %s " PTR_FORMAT " " PTR_FORMAT,
                              action_str, bottom, top);
     } else {
-      gclog_or_tty->print_cr(G1HR_PREFIX" %s "PTR_FORMAT,
+      gclog_or_tty->print_cr(G1HR_PREFIX " %s " PTR_FORMAT,
                              action_str, bottom);
     }
   }
@@ -104,11 +104,11 @@
 void G1HRPrinter::print(ActionType action, HeapWord* bottom, HeapWord* end) {
   const char* action_str = action_name(action);
 
-  gclog_or_tty->print_cr(G1HR_PREFIX" %s ["PTR_FORMAT","PTR_FORMAT"]",
+  gclog_or_tty->print_cr(G1HR_PREFIX " %s [" PTR_FORMAT "," PTR_FORMAT "]",
                          action_str, bottom, end);
 }
 
 void G1HRPrinter::print(PhaseType phase, size_t phase_num) {
   const char* phase_str = phase_name(phase);
-  gclog_or_tty->print_cr(G1HR_PREFIX" #%s "SIZE_FORMAT, phase_str, phase_num);
+  gclog_or_tty->print_cr(G1HR_PREFIX " #%s " SIZE_FORMAT, phase_str, phase_num);
 }
diff --git a/src/share/vm/gc_implementation/g1/g1InCSetState.hpp b/src/share/vm/gc_implementation/g1/g1InCSetState.hpp
index f13eaa0..50639c3 100644
--- a/src/share/vm/gc_implementation/g1/g1InCSetState.hpp
+++ b/src/share/vm/gc_implementation/g1/g1InCSetState.hpp
@@ -103,7 +103,7 @@
  public:
   void set_humongous(uintptr_t index) {
     assert(get_by_index(index).is_default(),
-           err_msg("State at index " INTPTR_FORMAT" should be default but is " CSETSTATE_FORMAT, index, get_by_index(index).value()));
+           err_msg("State at index " INTPTR_FORMAT " should be default but is " CSETSTATE_FORMAT, index, get_by_index(index).value()));
     set_by_index(index, InCSetState::Humongous);
   }
 
@@ -113,13 +113,13 @@
 
   void set_in_young(uintptr_t index) {
     assert(get_by_index(index).is_default(),
-           err_msg("State at index " INTPTR_FORMAT" should be default but is " CSETSTATE_FORMAT, index, get_by_index(index).value()));
+           err_msg("State at index " INTPTR_FORMAT " should be default but is " CSETSTATE_FORMAT, index, get_by_index(index).value()));
     set_by_index(index, InCSetState::Young);
   }
 
   void set_in_old(uintptr_t index) {
     assert(get_by_index(index).is_default(),
-           err_msg("State at index " INTPTR_FORMAT" should be default but is " CSETSTATE_FORMAT, index, get_by_index(index).value()));
+           err_msg("State at index " INTPTR_FORMAT " should be default but is " CSETSTATE_FORMAT, index, get_by_index(index).value()));
     set_by_index(index, InCSetState::Old);
   }
 
diff --git a/src/share/vm/gc_implementation/g1/g1MarkSweep.cpp b/src/share/vm/gc_implementation/g1/g1MarkSweep.cpp
index b1bc682..6908477 100644
--- a/src/share/vm/gc_implementation/g1/g1MarkSweep.cpp
+++ b/src/share/vm/gc_implementation/g1/g1MarkSweep.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -135,9 +135,16 @@
   MarkingCodeBlobClosure follow_code_closure(&GenMarkSweep::follow_root_closure, !CodeBlobToOopClosure::FixRelocations);
   {
     G1RootProcessor root_processor(g1h);
-    root_processor.process_strong_roots(&GenMarkSweep::follow_root_closure,
-                                        &GenMarkSweep::follow_cld_closure,
-                                        &follow_code_closure);
+    if (ClassUnloading) {
+      root_processor.process_strong_roots(&GenMarkSweep::follow_root_closure,
+                                          &GenMarkSweep::follow_cld_closure,
+                                          &follow_code_closure);
+    } else {
+      root_processor.process_all_roots_no_string_table(
+                                          &GenMarkSweep::follow_root_closure,
+                                          &GenMarkSweep::follow_cld_closure,
+                                          &follow_code_closure);
+    }
   }
 
   // Process reference objects found during marking
@@ -158,15 +165,17 @@
   // This is the point where the entire marking should have completed.
   assert(GenMarkSweep::_marking_stack.is_empty(), "Marking should have completed");
 
-  // Unload classes and purge the SystemDictionary.
-  bool purged_class = SystemDictionary::do_unloading(&GenMarkSweep::is_alive);
+  if (ClassUnloading) {
 
-  // Unload nmethods.
-  CodeCache::do_unloading(&GenMarkSweep::is_alive, purged_class);
+     // Unload classes and purge the SystemDictionary.
+     bool purged_class = SystemDictionary::do_unloading(&GenMarkSweep::is_alive);
 
-  // Prune dead klasses from subklass/sibling/implementor lists.
-  Klass::clean_weak_klass_links(&GenMarkSweep::is_alive);
+     // Unload nmethods.
+     CodeCache::do_unloading(&GenMarkSweep::is_alive, purged_class);
 
+     // Prune dead klasses from subklass/sibling/implementor lists.
+     Klass::clean_weak_klass_links(&GenMarkSweep::is_alive);
+  }
   // Delete entries for dead interned string and clean up unreferenced symbols in symbol table.
   G1CollectedHeap::heap()->unlink_string_and_symbol_table(&GenMarkSweep::is_alive);
 
diff --git a/src/share/vm/gc_implementation/g1/g1OopClosures.inline.hpp b/src/share/vm/gc_implementation/g1/g1OopClosures.inline.hpp
index a00cd7a..0385f66 100644
--- a/src/share/vm/gc_implementation/g1/g1OopClosures.inline.hpp
+++ b/src/share/vm/gc_implementation/g1/g1OopClosures.inline.hpp
@@ -118,7 +118,7 @@
   oop obj = oopDesc::load_decode_heap_oop(p);
   if (_cm->verbose_high()) {
     gclog_or_tty->print_cr("[%u] we're looking at location "
-                           "*"PTR_FORMAT" = "PTR_FORMAT,
+                           "*" PTR_FORMAT " = " PTR_FORMAT,
                            _task->worker_id(), p2i(p), p2i((void*) obj));
   }
   _task->deal_with_reference(obj);
diff --git a/src/share/vm/gc_implementation/g1/g1RemSet.cpp b/src/share/vm/gc_implementation/g1/g1RemSet.cpp
index ca714dc..da4d632 100644
--- a/src/share/vm/gc_implementation/g1/g1RemSet.cpp
+++ b/src/share/vm/gc_implementation/g1/g1RemSet.cpp
@@ -442,7 +442,7 @@
 bool G1RemSet::refine_card(jbyte* card_ptr, uint worker_i,
                            bool check_for_refs_into_cset) {
   assert(_g1->is_in_exact(_ct_bs->addr_for(card_ptr)),
-         err_msg("Card at "PTR_FORMAT" index "SIZE_FORMAT" representing heap at "PTR_FORMAT" (%u) must be in committed heap",
+         err_msg("Card at " PTR_FORMAT " index " SIZE_FORMAT " representing heap at " PTR_FORMAT " (%u) must be in committed heap",
                  p2i(card_ptr),
                  _ct_bs->index_for(_ct_bs->addr_for(card_ptr)),
                  _ct_bs->addr_for(card_ptr),
diff --git a/src/share/vm/gc_implementation/g1/g1RemSetSummary.cpp b/src/share/vm/gc_implementation/g1/g1RemSetSummary.cpp
index 45bc364..b276264 100644
--- a/src/share/vm/gc_implementation/g1/g1RemSetSummary.cpp
+++ b/src/share/vm/gc_implementation/g1/g1RemSetSummary.cpp
@@ -183,26 +183,26 @@
   size_t code_root_elems() const { return _code_root_elems; }
 
   void print_rs_mem_info_on(outputStream * out, size_t total) {
-    out->print_cr("    "SIZE_FORMAT_W(8) "%s (%5.1f%%) by "SIZE_FORMAT" %s regions",
+    out->print_cr("    " SIZE_FORMAT_W(8) "%s (%5.1f%%) by " SIZE_FORMAT " %s regions",
         byte_size_in_proper_unit(rs_mem_size()),
         proper_unit_for_byte_size(rs_mem_size()),
         rs_mem_size_percent_of(total), amount(), _name);
   }
 
   void print_cards_occupied_info_on(outputStream * out, size_t total) {
-    out->print_cr("     "SIZE_FORMAT_W(8)" (%5.1f%%) entries by "SIZE_FORMAT" %s regions",
+    out->print_cr("     " SIZE_FORMAT_W(8) " (%5.1f%%) entries by " SIZE_FORMAT " %s regions",
         cards_occupied(), cards_occupied_percent_of(total), amount(), _name);
   }
 
   void print_code_root_mem_info_on(outputStream * out, size_t total) {
-    out->print_cr("    "SIZE_FORMAT_W(8) "%s (%5.1f%%) by "SIZE_FORMAT" %s regions",
+    out->print_cr("    " SIZE_FORMAT_W(8) "%s (%5.1f%%) by " SIZE_FORMAT " %s regions",
         byte_size_in_proper_unit(code_root_mem_size()),
         proper_unit_for_byte_size(code_root_mem_size()),
         code_root_mem_size_percent_of(total), amount(), _name);
   }
 
   void print_code_root_elems_info_on(outputStream * out, size_t total) {
-    out->print_cr("     "SIZE_FORMAT_W(8)" (%5.1f%%) elements by "SIZE_FORMAT" %s regions",
+    out->print_cr("     " SIZE_FORMAT_W(8) " (%5.1f%%) elements by " SIZE_FORMAT " %s regions",
         code_root_elems(), code_root_elems_percent_of(total), amount(), _name);
   }
 };
@@ -298,7 +298,7 @@
                   byte_size_in_proper_unit(HeapRegionRemSet::fl_mem_size()),
                   proper_unit_for_byte_size(HeapRegionRemSet::fl_mem_size()));
 
-    out->print_cr("    "SIZE_FORMAT" occupied cards represented.",
+    out->print_cr("    " SIZE_FORMAT " occupied cards represented.",
                   total_cards_occupied());
     for (RegionTypeCounter** current = &counters[0]; *current != NULL; current++) {
       (*current)->print_cards_occupied_info_on(out, total_cards_occupied());
@@ -306,8 +306,8 @@
 
     // Largest sized rem set region statistics
     HeapRegionRemSet* rem_set = max_rs_mem_sz_region()->rem_set();
-    out->print_cr("    Region with largest rem set = "HR_FORMAT", "
-                  "size = "SIZE_FORMAT "%s, occupied = "SIZE_FORMAT "%s.",
+    out->print_cr("    Region with largest rem set = " HR_FORMAT ", "
+                  "size = " SIZE_FORMAT "%s, occupied = " SIZE_FORMAT "%s.",
                   HR_FORMAT_PARAMS(max_rs_mem_sz_region()),
                   byte_size_in_proper_unit(rem_set->mem_size()),
                   proper_unit_for_byte_size(rem_set->mem_size()),
@@ -326,14 +326,14 @@
       (*current)->print_code_root_mem_info_on(out, total_code_root_mem_sz());
     }
 
-    out->print_cr("    "SIZE_FORMAT" code roots represented.",
+    out->print_cr("    " SIZE_FORMAT " code roots represented.",
                   total_code_root_elems());
     for (RegionTypeCounter** current = &counters[0]; *current != NULL; current++) {
       (*current)->print_code_root_elems_info_on(out, total_code_root_elems());
     }
 
-    out->print_cr("    Region with largest amount of code roots = "HR_FORMAT", "
-                  "size = "SIZE_FORMAT "%s, num_elems = "SIZE_FORMAT".",
+    out->print_cr("    Region with largest amount of code roots = " HR_FORMAT ", "
+                  "size = " SIZE_FORMAT "%s, num_elems = " SIZE_FORMAT ".",
                   HR_FORMAT_PARAMS(max_code_root_mem_sz_region()),
                   byte_size_in_proper_unit(max_code_root_rem_set->strong_code_roots_mem_size()),
                   proper_unit_for_byte_size(max_code_root_rem_set->strong_code_roots_mem_size()),
@@ -344,16 +344,16 @@
 
 void G1RemSetSummary::print_on(outputStream* out) {
   out->print_cr("\n Recent concurrent refinement statistics");
-  out->print_cr("  Processed "SIZE_FORMAT" cards",
+  out->print_cr("  Processed " SIZE_FORMAT " cards",
                 num_concurrent_refined_cards());
-  out->print_cr("  Of "SIZE_FORMAT" completed buffers:", num_processed_buf_total());
-  out->print_cr("     "SIZE_FORMAT_W(8)" (%5.1f%%) by concurrent RS threads.",
+  out->print_cr("  Of " SIZE_FORMAT " completed buffers:", num_processed_buf_total());
+  out->print_cr("     " SIZE_FORMAT_W(8) " (%5.1f%%) by concurrent RS threads.",
                 num_processed_buf_total(),
                 percent_of(num_processed_buf_rs_threads(), num_processed_buf_total()));
-  out->print_cr("     "SIZE_FORMAT_W(8)" (%5.1f%%) by mutator threads.",
+  out->print_cr("     " SIZE_FORMAT_W(8) " (%5.1f%%) by mutator threads.",
                 num_processed_buf_mutator(),
                 percent_of(num_processed_buf_mutator(), num_processed_buf_total()));
-  out->print_cr("  Did "SIZE_FORMAT" coarsenings.", num_coarsenings());
+  out->print_cr("  Did " SIZE_FORMAT " coarsenings.", num_coarsenings());
   out->print_cr("  Concurrent RS threads times (s)");
   out->print("     ");
   for (uint i = 0; i < _num_vtimes; i++) {
diff --git a/src/share/vm/gc_implementation/g1/g1RootProcessor.cpp b/src/share/vm/gc_implementation/g1/g1RootProcessor.cpp
index b27696d..5b27a01 100644
--- a/src/share/vm/gc_implementation/g1/g1RootProcessor.cpp
+++ b/src/share/vm/gc_implementation/g1/g1RootProcessor.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -156,7 +156,7 @@
   }
 
   process_vm_roots(strong_roots, weak_roots, phase_times, worker_i);
-
+  process_string_table_roots(weak_roots, phase_times, worker_i);
   {
     // Now the CM ref_processor roots.
     G1GCParPhaseTimesTracker x(phase_times, G1GCPhaseTimes::CMRefRoots, worker_i);
@@ -223,18 +223,34 @@
 
 void G1RootProcessor::process_all_roots(OopClosure* oops,
                                         CLDClosure* clds,
-                                        CodeBlobClosure* blobs) {
+                                        CodeBlobClosure* blobs,
+                                        bool process_string_table) {
 
   process_java_roots(oops, NULL, clds, clds, NULL, NULL, 0);
   process_vm_roots(oops, oops, NULL, 0);
 
-  if (!_process_strong_tasks.is_task_claimed(G1RP_PS_CodeCache_oops_do)) {
-    CodeCache::blobs_do(blobs);
-  }
+  if (process_string_table) {
+    process_string_table_roots(oops, NULL, 0);
+   }
+  process_code_cache_roots(blobs, NULL, 0);
 
   _process_strong_tasks.all_tasks_completed();
 }
 
+void G1RootProcessor::process_all_roots(OopClosure* oops,
+                                        CLDClosure* clds,
+                                        CodeBlobClosure* blobs) {
+  process_all_roots(oops, clds, blobs, true);
+}
+
+void G1RootProcessor::process_all_roots_no_string_table(OopClosure* oops,
+                                                        CLDClosure* clds,
+                                                        CodeBlobClosure* blobs) {
+  assert(!ClassUnloading, "Should only be used when class unloading is disabled");
+  process_all_roots(oops, clds, blobs, false);
+}
+
+
 void G1RootProcessor::process_java_roots(OopClosure* strong_roots,
                                          CLDClosure* thread_stack_clds,
                                          CLDClosure* strong_clds,
@@ -311,14 +327,23 @@
       SystemDictionary::roots_oops_do(strong_roots, weak_roots);
     }
   }
+}
 
-  {
-    G1GCParPhaseTimesTracker x(phase_times, G1GCPhaseTimes::StringTableRoots, worker_i);
-    // All threads execute the following. A specific chunk of buckets
-    // from the StringTable are the individual tasks.
-    if (weak_roots != NULL) {
-      StringTable::possibly_parallel_oops_do(weak_roots);
-    }
+void G1RootProcessor::process_string_table_roots(OopClosure* weak_roots, G1GCPhaseTimes* phase_times,
+                                                 uint worker_i) {
+  assert(weak_roots != NULL, "Should only be called when all roots are processed");
+
+  G1GCParPhaseTimesTracker x(phase_times, G1GCPhaseTimes::StringTableRoots, worker_i);
+  // All threads execute the following. A specific chunk of buckets
+  // from the StringTable are the individual tasks.
+  StringTable::possibly_parallel_oops_do(weak_roots);
+}
+
+void G1RootProcessor::process_code_cache_roots(CodeBlobClosure* code_closure,
+                                               G1GCPhaseTimes* phase_times,
+                                               uint worker_i) {
+  if (!_process_strong_tasks.is_task_claimed(G1RP_PS_CodeCache_oops_do)) {
+    CodeCache::blobs_do(code_closure);
   }
 }
 
diff --git a/src/share/vm/gc_implementation/g1/g1RootProcessor.hpp b/src/share/vm/gc_implementation/g1/g1RootProcessor.hpp
index 1cce9f3..ad4e75b 100644
--- a/src/share/vm/gc_implementation/g1/g1RootProcessor.hpp
+++ b/src/share/vm/gc_implementation/g1/g1RootProcessor.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -34,6 +34,7 @@
 class G1CollectedHeap;
 class G1GCPhaseTimes;
 class G1ParPushHeapRSClosure;
+class G1RootClosures;
 class Monitor;
 class OopClosure;
 class SubTasksDone;
@@ -71,6 +72,11 @@
   void worker_has_discovered_all_strong_classes();
   void wait_until_all_strong_classes_discovered();
 
+  void process_all_roots(OopClosure* oops,
+                         CLDClosure* clds,
+                         CodeBlobClosure* blobs,
+                         bool process_string_table);
+
   void process_java_roots(OopClosure* scan_non_heap_roots,
                           CLDClosure* thread_stack_clds,
                           CLDClosure* scan_strong_clds,
@@ -84,6 +90,14 @@
                         G1GCPhaseTimes* phase_times,
                         uint worker_i);
 
+  void process_string_table_roots(OopClosure* scan_non_heap_weak_roots,
+                                  G1GCPhaseTimes* phase_times,
+                                  uint worker_i);
+
+  void process_code_cache_roots(CodeBlobClosure* code_closure,
+                                G1GCPhaseTimes* phase_times,
+                                uint worker_i);
+
 public:
   G1RootProcessor(G1CollectedHeap* g1h);
 
@@ -114,6 +128,13 @@
                             OopClosure* scan_non_heap_weak_roots,
                             uint worker_i);
 
+  // Apply oops, clds and blobs to strongly and weakly reachable roots in the system,
+  // the only thing different from process_all_roots is that we skip the string table
+  // to avoid keeping every string live when doing class unloading.
+  void process_all_roots_no_string_table(OopClosure* oops,
+                                         CLDClosure* clds,
+                                         CodeBlobClosure* blobs);
+
   // Inform the root processor about the number of worker threads
   void set_num_workers(int active_workers);
 };
diff --git a/src/share/vm/gc_implementation/g1/g1StringDedupQueue.cpp b/src/share/vm/gc_implementation/g1/g1StringDedupQueue.cpp
index 8ae53e3..747f61b 100644
--- a/src/share/vm/gc_implementation/g1/g1StringDedupQueue.cpp
+++ b/src/share/vm/gc_implementation/g1/g1StringDedupQueue.cpp
@@ -151,7 +151,7 @@
 void G1StringDedupQueue::print_statistics(outputStream* st) {
   st->print_cr(
     "   [Queue]\n"
-    "      [Dropped: "UINTX_FORMAT"]", _queue->_dropped);
+    "      [Dropped: " UINTX_FORMAT "]", _queue->_dropped);
 }
 
 void G1StringDedupQueue::verify() {
diff --git a/src/share/vm/gc_implementation/g1/g1StringDedupStat.cpp b/src/share/vm/gc_implementation/g1/g1StringDedupStat.cpp
index 2d5523c..f9700e1 100644
--- a/src/share/vm/gc_implementation/g1/g1StringDedupStat.cpp
+++ b/src/share/vm/gc_implementation/g1/g1StringDedupStat.cpp
@@ -80,8 +80,8 @@
   st->stamp(PrintGCTimeStamps);
   st->print_cr(
     "[GC concurrent-string-deduplication, "
-    G1_STRDEDUP_BYTES_FORMAT_NS"->"G1_STRDEDUP_BYTES_FORMAT_NS"("G1_STRDEDUP_BYTES_FORMAT_NS"), avg "
-    G1_STRDEDUP_PERCENT_FORMAT_NS", "G1_STRDEDUP_TIME_FORMAT"]",
+    G1_STRDEDUP_BYTES_FORMAT_NS "->" G1_STRDEDUP_BYTES_FORMAT_NS "(" G1_STRDEDUP_BYTES_FORMAT_NS "), avg "
+    G1_STRDEDUP_PERCENT_FORMAT_NS ", " G1_STRDEDUP_TIME_FORMAT "]",
     G1_STRDEDUP_BYTES_PARAM(last_stat._new_bytes),
     G1_STRDEDUP_BYTES_PARAM(last_stat._new_bytes - last_stat._deduped_bytes),
     G1_STRDEDUP_BYTES_PARAM(last_stat._deduped_bytes),
@@ -135,22 +135,22 @@
 
   if (total) {
     st->print_cr(
-      "   [Total Exec: "UINTX_FORMAT"/"G1_STRDEDUP_TIME_FORMAT", Idle: "UINTX_FORMAT"/"G1_STRDEDUP_TIME_FORMAT", Blocked: "UINTX_FORMAT"/"G1_STRDEDUP_TIME_FORMAT"]",
+      "   [Total Exec: " UINTX_FORMAT "/" G1_STRDEDUP_TIME_FORMAT ", Idle: " UINTX_FORMAT "/" G1_STRDEDUP_TIME_FORMAT ", Blocked: " UINTX_FORMAT "/" G1_STRDEDUP_TIME_FORMAT "]",
       stat._exec, stat._exec_elapsed, stat._idle, stat._idle_elapsed, stat._block, stat._block_elapsed);
   } else {
     st->print_cr(
-      "   [Last Exec: "G1_STRDEDUP_TIME_FORMAT", Idle: "G1_STRDEDUP_TIME_FORMAT", Blocked: "UINTX_FORMAT"/"G1_STRDEDUP_TIME_FORMAT"]",
+      "   [Last Exec: " G1_STRDEDUP_TIME_FORMAT ", Idle: " G1_STRDEDUP_TIME_FORMAT ", Blocked: " UINTX_FORMAT "/" G1_STRDEDUP_TIME_FORMAT "]",
       stat._exec_elapsed, stat._idle_elapsed, stat._block, stat._block_elapsed);
   }
   st->print_cr(
-    "      [Inspected:    "G1_STRDEDUP_OBJECTS_FORMAT"]\n"
-    "         [Skipped:   "G1_STRDEDUP_OBJECTS_FORMAT"("G1_STRDEDUP_PERCENT_FORMAT")]\n"
-    "         [Hashed:    "G1_STRDEDUP_OBJECTS_FORMAT"("G1_STRDEDUP_PERCENT_FORMAT")]\n"
-    "         [Known:     "G1_STRDEDUP_OBJECTS_FORMAT"("G1_STRDEDUP_PERCENT_FORMAT")]\n"
-    "         [New:       "G1_STRDEDUP_OBJECTS_FORMAT"("G1_STRDEDUP_PERCENT_FORMAT") "G1_STRDEDUP_BYTES_FORMAT"]\n"
-    "      [Deduplicated: "G1_STRDEDUP_OBJECTS_FORMAT"("G1_STRDEDUP_PERCENT_FORMAT") "G1_STRDEDUP_BYTES_FORMAT"("G1_STRDEDUP_PERCENT_FORMAT")]\n"
-    "         [Young:     "G1_STRDEDUP_OBJECTS_FORMAT"("G1_STRDEDUP_PERCENT_FORMAT") "G1_STRDEDUP_BYTES_FORMAT"("G1_STRDEDUP_PERCENT_FORMAT")]\n"
-    "         [Old:       "G1_STRDEDUP_OBJECTS_FORMAT"("G1_STRDEDUP_PERCENT_FORMAT") "G1_STRDEDUP_BYTES_FORMAT"("G1_STRDEDUP_PERCENT_FORMAT")]",
+    "      [Inspected:    " G1_STRDEDUP_OBJECTS_FORMAT "]\n"
+    "         [Skipped:   " G1_STRDEDUP_OBJECTS_FORMAT "(" G1_STRDEDUP_PERCENT_FORMAT ")]\n"
+    "         [Hashed:    " G1_STRDEDUP_OBJECTS_FORMAT "(" G1_STRDEDUP_PERCENT_FORMAT ")]\n"
+    "         [Known:     " G1_STRDEDUP_OBJECTS_FORMAT "(" G1_STRDEDUP_PERCENT_FORMAT ")]\n"
+    "         [New:       " G1_STRDEDUP_OBJECTS_FORMAT "(" G1_STRDEDUP_PERCENT_FORMAT ") " G1_STRDEDUP_BYTES_FORMAT "]\n"
+    "      [Deduplicated: " G1_STRDEDUP_OBJECTS_FORMAT "(" G1_STRDEDUP_PERCENT_FORMAT ") " G1_STRDEDUP_BYTES_FORMAT "(" G1_STRDEDUP_PERCENT_FORMAT ")]\n"
+    "         [Young:     " G1_STRDEDUP_OBJECTS_FORMAT "(" G1_STRDEDUP_PERCENT_FORMAT ") " G1_STRDEDUP_BYTES_FORMAT "(" G1_STRDEDUP_PERCENT_FORMAT ")]\n"
+    "         [Old:       " G1_STRDEDUP_OBJECTS_FORMAT "(" G1_STRDEDUP_PERCENT_FORMAT ") " G1_STRDEDUP_BYTES_FORMAT "(" G1_STRDEDUP_PERCENT_FORMAT ")]",
     stat._inspected,
     stat._skipped, skipped_percent,
     stat._hashed, hashed_percent,
diff --git a/src/share/vm/gc_implementation/g1/g1StringDedupTable.cpp b/src/share/vm/gc_implementation/g1/g1StringDedupTable.cpp
index 71e7e53..c8d128b 100644
--- a/src/share/vm/gc_implementation/g1/g1StringDedupTable.cpp
+++ b/src/share/vm/gc_implementation/g1/g1StringDedupTable.cpp
@@ -596,12 +596,12 @@
 void G1StringDedupTable::print_statistics(outputStream* st) {
   st->print_cr(
     "   [Table]\n"
-    "      [Memory Usage: "G1_STRDEDUP_BYTES_FORMAT_NS"]\n"
-    "      [Size: "SIZE_FORMAT", Min: "SIZE_FORMAT", Max: "SIZE_FORMAT"]\n"
-    "      [Entries: "UINTX_FORMAT", Load: "G1_STRDEDUP_PERCENT_FORMAT_NS", Cached: " UINTX_FORMAT ", Added: "UINTX_FORMAT", Removed: "UINTX_FORMAT"]\n"
-    "      [Resize Count: "UINTX_FORMAT", Shrink Threshold: "UINTX_FORMAT"("G1_STRDEDUP_PERCENT_FORMAT_NS"), Grow Threshold: "UINTX_FORMAT"("G1_STRDEDUP_PERCENT_FORMAT_NS")]\n"
-    "      [Rehash Count: "UINTX_FORMAT", Rehash Threshold: "UINTX_FORMAT", Hash Seed: 0x%x]\n"
-    "      [Age Threshold: "UINTX_FORMAT"]",
+    "      [Memory Usage: " G1_STRDEDUP_BYTES_FORMAT_NS "]\n"
+    "      [Size: " SIZE_FORMAT ", Min: " SIZE_FORMAT ", Max: " SIZE_FORMAT "]\n"
+    "      [Entries: " UINTX_FORMAT ", Load: " G1_STRDEDUP_PERCENT_FORMAT_NS ", Cached: " UINTX_FORMAT ", Added: " UINTX_FORMAT ", Removed: " UINTX_FORMAT "]\n"
+    "      [Resize Count: " UINTX_FORMAT ", Shrink Threshold: " UINTX_FORMAT "(" G1_STRDEDUP_PERCENT_FORMAT_NS "), Grow Threshold: " UINTX_FORMAT "(" G1_STRDEDUP_PERCENT_FORMAT_NS ")]\n"
+    "      [Rehash Count: " UINTX_FORMAT ", Rehash Threshold: " UINTX_FORMAT ", Hash Seed: 0x%x]\n"
+    "      [Age Threshold: " UINTX_FORMAT "]",
     G1_STRDEDUP_BYTES_PARAM(_table->_size * sizeof(G1StringDedupEntry*) + (_table->_entries + _entry_cache->size()) * sizeof(G1StringDedupEntry)),
     _table->_size, _min_size, _max_size,
     _table->_entries, (double)_table->_entries / (double)_table->_size * 100.0, _entry_cache->size(), _entries_added, _entries_removed,
diff --git a/src/share/vm/gc_implementation/g1/heapRegion.cpp b/src/share/vm/gc_implementation/g1/heapRegion.cpp
index ef5b437..eefa1c9 100644
--- a/src/share/vm/gc_implementation/g1/heapRegion.cpp
+++ b/src/share/vm/gc_implementation/g1/heapRegion.cpp
@@ -333,7 +333,7 @@
                                                   bool during_conc_mark,
                                                   size_t marked_bytes) {
   assert(0 <= marked_bytes && marked_bytes <= used(),
-         err_msg("marked: "SIZE_FORMAT" used: "SIZE_FORMAT,
+         err_msg("marked: " SIZE_FORMAT " used: " SIZE_FORMAT,
                  marked_bytes, used()));
   _prev_top_at_mark_start = top();
   _prev_marked_bytes = marked_bytes;
@@ -514,9 +514,9 @@
         // Object is in the region. Check that its less than top
         if (_hr->top() <= (HeapWord*)obj) {
           // Object is above top
-          gclog_or_tty->print_cr("Object "PTR_FORMAT" in region "
-                                 "["PTR_FORMAT", "PTR_FORMAT") is above "
-                                 "top "PTR_FORMAT,
+          gclog_or_tty->print_cr("Object " PTR_FORMAT " in region "
+                                 "[" PTR_FORMAT ", " PTR_FORMAT ") is above "
+                                 "top " PTR_FORMAT,
                                  (void *)obj, _hr->bottom(), _hr->end(), _hr->top());
           _failures = true;
           return;
@@ -550,22 +550,22 @@
     if (nm != NULL) {
       // Verify that the nemthod is live
       if (!nm->is_alive()) {
-        gclog_or_tty->print_cr("region ["PTR_FORMAT","PTR_FORMAT"] has dead nmethod "
-                               PTR_FORMAT" in its strong code roots",
+        gclog_or_tty->print_cr("region [" PTR_FORMAT "," PTR_FORMAT "] has dead nmethod "
+                               PTR_FORMAT " in its strong code roots",
                                _hr->bottom(), _hr->end(), nm);
         _failures = true;
       } else {
         VerifyStrongCodeRootOopClosure oop_cl(_hr, nm);
         nm->oops_do(&oop_cl);
         if (!oop_cl.has_oops_in_region()) {
-          gclog_or_tty->print_cr("region ["PTR_FORMAT","PTR_FORMAT"] has nmethod "
-                                 PTR_FORMAT" in its strong code roots "
+          gclog_or_tty->print_cr("region [" PTR_FORMAT "," PTR_FORMAT "] has nmethod "
+                                 PTR_FORMAT " in its strong code roots "
                                  "with no pointers into region",
                                  _hr->bottom(), _hr->end(), nm);
           _failures = true;
         } else if (oop_cl.failures()) {
-          gclog_or_tty->print_cr("region ["PTR_FORMAT","PTR_FORMAT"] has other "
-                                 "failures for nmethod "PTR_FORMAT,
+          gclog_or_tty->print_cr("region [" PTR_FORMAT "," PTR_FORMAT "] has other "
+                                 "failures for nmethod " PTR_FORMAT,
                                  _hr->bottom(), _hr->end(), nm);
           _failures = true;
         }
@@ -599,8 +599,8 @@
   // on its strong code root list
   if (is_empty()) {
     if (strong_code_roots_length > 0) {
-      gclog_or_tty->print_cr("region ["PTR_FORMAT","PTR_FORMAT"] is empty "
-                             "but has "SIZE_FORMAT" code root entries",
+      gclog_or_tty->print_cr("region [" PTR_FORMAT "," PTR_FORMAT "] is empty "
+                             "but has " SIZE_FORMAT " code root entries",
                              bottom(), end(), strong_code_roots_length);
       *failures = true;
     }
@@ -609,8 +609,8 @@
 
   if (continuesHumongous()) {
     if (strong_code_roots_length > 0) {
-      gclog_or_tty->print_cr("region "HR_FORMAT" is a continuation of a humongous "
-                             "region but has "SIZE_FORMAT" code root entries",
+      gclog_or_tty->print_cr("region " HR_FORMAT " is a continuation of a humongous "
+                             "region but has " SIZE_FORMAT " code root entries",
                              HR_FORMAT_PARAMS(this), strong_code_roots_length);
       *failures = true;
     }
@@ -634,7 +634,7 @@
   else
     st->print("   ");
   st->print(" TS %5d", _gc_time_stamp);
-  st->print(" PTAMS "PTR_FORMAT" NTAMS "PTR_FORMAT,
+  st->print(" PTAMS " PTR_FORMAT " NTAMS " PTR_FORMAT,
             prev_top_at_mark_start(), next_top_at_mark_start());
   G1OffsetTableContigSpace::print_on(st);
 }
@@ -708,25 +708,25 @@
         }
         if (!_g1h->is_in_closed_subset(obj)) {
           HeapRegion* from = _g1h->heap_region_containing((HeapWord*)p);
-          gclog_or_tty->print_cr("Field "PTR_FORMAT
-                                 " of live obj "PTR_FORMAT" in region "
-                                 "["PTR_FORMAT", "PTR_FORMAT")",
+          gclog_or_tty->print_cr("Field " PTR_FORMAT
+                                 " of live obj " PTR_FORMAT " in region "
+                                 "[" PTR_FORMAT ", " PTR_FORMAT ")",
                                  p, (void*) _containing_obj,
                                  from->bottom(), from->end());
           print_object(gclog_or_tty, _containing_obj);
-          gclog_or_tty->print_cr("points to obj "PTR_FORMAT" not in the heap",
+          gclog_or_tty->print_cr("points to obj " PTR_FORMAT " not in the heap",
                                  (void*) obj);
         } else {
           HeapRegion* from = _g1h->heap_region_containing((HeapWord*)p);
           HeapRegion* to   = _g1h->heap_region_containing((HeapWord*)obj);
-          gclog_or_tty->print_cr("Field "PTR_FORMAT
-                                 " of live obj "PTR_FORMAT" in region "
-                                 "["PTR_FORMAT", "PTR_FORMAT")",
+          gclog_or_tty->print_cr("Field " PTR_FORMAT
+                                 " of live obj " PTR_FORMAT " in region "
+                                 "[" PTR_FORMAT ", " PTR_FORMAT ")",
                                  p, (void*) _containing_obj,
                                  from->bottom(), from->end());
           print_object(gclog_or_tty, _containing_obj);
-          gclog_or_tty->print_cr("points to dead obj "PTR_FORMAT" in region "
-                                 "["PTR_FORMAT", "PTR_FORMAT")",
+          gclog_or_tty->print_cr("points to dead obj " PTR_FORMAT " in region "
+                                 "[" PTR_FORMAT ", " PTR_FORMAT ")",
                                  (void*) obj, to->bottom(), to->end());
           print_object(gclog_or_tty, obj);
         }
@@ -784,14 +784,14 @@
             gclog_or_tty->print_cr("----------");
           }
           gclog_or_tty->print_cr("Missing rem set entry:");
-          gclog_or_tty->print_cr("Field "PTR_FORMAT" "
-                                 "of obj "PTR_FORMAT", "
-                                 "in region "HR_FORMAT,
+          gclog_or_tty->print_cr("Field " PTR_FORMAT " "
+                                 "of obj " PTR_FORMAT ", "
+                                 "in region " HR_FORMAT,
                                  p, (void*) _containing_obj,
                                  HR_FORMAT_PARAMS(from));
           _containing_obj->print_on(gclog_or_tty);
-          gclog_or_tty->print_cr("points to obj "PTR_FORMAT" "
-                                 "in region "HR_FORMAT,
+          gclog_or_tty->print_cr("points to obj " PTR_FORMAT " "
+                                 "in region " HR_FORMAT,
                                  (void*) obj,
                                  HR_FORMAT_PARAMS(to));
           if (obj->is_oop()) {
@@ -830,8 +830,8 @@
 
     if (is_humongous != g1->isHumongous(obj_size) &&
         !g1->is_obj_dead(obj, this)) { // Dead objects may have bigger block_size since they span several objects.
-      gclog_or_tty->print_cr("obj "PTR_FORMAT" is of %shumongous size ("
-                             SIZE_FORMAT" words) in a %shumongous region",
+      gclog_or_tty->print_cr("obj " PTR_FORMAT " is of %shumongous size ("
+                             SIZE_FORMAT " words) in a %shumongous region",
                              p, g1->isHumongous(obj_size) ? "" : "non-",
                              obj_size, is_humongous ? "" : "non-");
        *failures = true;
@@ -854,12 +854,12 @@
                                    (vo == VerifyOption_G1UsePrevMarking &&
                                    ClassLoaderDataGraph::unload_list_contains(klass));
         if (!is_metaspace_object) {
-          gclog_or_tty->print_cr("klass "PTR_FORMAT" of object "PTR_FORMAT" "
+          gclog_or_tty->print_cr("klass " PTR_FORMAT " of object " PTR_FORMAT " "
                                  "not metadata", klass, (void *)obj);
           *failures = true;
           return;
         } else if (!klass->is_klass()) {
-          gclog_or_tty->print_cr("klass "PTR_FORMAT" of object "PTR_FORMAT" "
+          gclog_or_tty->print_cr("klass " PTR_FORMAT " of object " PTR_FORMAT " "
                                  "not a klass", klass, (void *)obj);
           *failures = true;
           return;
@@ -891,7 +891,7 @@
           }
         }
       } else {
-        gclog_or_tty->print_cr(PTR_FORMAT" not an oop", (void *)obj);
+        gclog_or_tty->print_cr(PTR_FORMAT " not an oop", (void *)obj);
         *failures = true;
         return;
       }
@@ -901,8 +901,8 @@
   }
 
   if (p != top()) {
-    gclog_or_tty->print_cr("end of last object "PTR_FORMAT" "
-                           "does not match top "PTR_FORMAT, p, top());
+    gclog_or_tty->print_cr("end of last object " PTR_FORMAT " "
+                           "does not match top " PTR_FORMAT, p, top());
     *failures = true;
     return;
   }
@@ -917,8 +917,8 @@
     HeapWord* addr_1 = p;
     HeapWord* b_start_1 = _offsets.block_start_const(addr_1);
     if (b_start_1 != p) {
-      gclog_or_tty->print_cr("BOT look up for top: "PTR_FORMAT" "
-                             " yielded "PTR_FORMAT", expecting "PTR_FORMAT,
+      gclog_or_tty->print_cr("BOT look up for top: " PTR_FORMAT " "
+                             " yielded " PTR_FORMAT ", expecting " PTR_FORMAT,
                              addr_1, b_start_1, p);
       *failures = true;
       return;
@@ -929,8 +929,8 @@
     if (addr_2 < the_end) {
       HeapWord* b_start_2 = _offsets.block_start_const(addr_2);
       if (b_start_2 != p) {
-        gclog_or_tty->print_cr("BOT look up for top + 1: "PTR_FORMAT" "
-                               " yielded "PTR_FORMAT", expecting "PTR_FORMAT,
+        gclog_or_tty->print_cr("BOT look up for top + 1: " PTR_FORMAT " "
+                               " yielded " PTR_FORMAT ", expecting " PTR_FORMAT,
                                addr_2, b_start_2, p);
         *failures = true;
         return;
@@ -943,8 +943,8 @@
     if (addr_3 < the_end) {
       HeapWord* b_start_3 = _offsets.block_start_const(addr_3);
       if (b_start_3 != p) {
-        gclog_or_tty->print_cr("BOT look up for top + diff: "PTR_FORMAT" "
-                               " yielded "PTR_FORMAT", expecting "PTR_FORMAT,
+        gclog_or_tty->print_cr("BOT look up for top + diff: " PTR_FORMAT " "
+                               " yielded " PTR_FORMAT ", expecting " PTR_FORMAT,
                                addr_3, b_start_3, p);
         *failures = true;
         return;
@@ -955,8 +955,8 @@
     HeapWord* addr_4 = the_end - 1;
     HeapWord* b_start_4 = _offsets.block_start_const(addr_4);
     if (b_start_4 != p) {
-      gclog_or_tty->print_cr("BOT look up for end - 1: "PTR_FORMAT" "
-                             " yielded "PTR_FORMAT", expecting "PTR_FORMAT,
+      gclog_or_tty->print_cr("BOT look up for end - 1: " PTR_FORMAT " "
+                             " yielded " PTR_FORMAT ", expecting " PTR_FORMAT,
                              addr_4, b_start_4, p);
       *failures = true;
       return;
@@ -964,8 +964,8 @@
   }
 
   if (is_humongous && object_num > 1) {
-    gclog_or_tty->print_cr("region ["PTR_FORMAT","PTR_FORMAT"] is humongous "
-                           "but has "SIZE_FORMAT", objects",
+    gclog_or_tty->print_cr("region [" PTR_FORMAT "," PTR_FORMAT "] is humongous "
+                           "but has " SIZE_FORMAT ", objects",
                            bottom(), end(), object_num);
     *failures = true;
     return;
diff --git a/src/share/vm/gc_implementation/g1/heapRegion.hpp b/src/share/vm/gc_implementation/g1/heapRegion.hpp
index e62a2ab..76627e7 100644
--- a/src/share/vm/gc_implementation/g1/heapRegion.hpp
+++ b/src/share/vm/gc_implementation/g1/heapRegion.hpp
@@ -52,7 +52,7 @@
 class HeapRegionSetBase;
 class nmethod;
 
-#define HR_FORMAT "%u:(%s)["PTR_FORMAT","PTR_FORMAT","PTR_FORMAT"]"
+#define HR_FORMAT "%u:(%s)[" PTR_FORMAT "," PTR_FORMAT "," PTR_FORMAT "]"
 #define HR_FORMAT_PARAMS(_hr_) \
                 (_hr_)->hrm_index(), \
                 (_hr_)->get_short_type_str(), \
@@ -534,8 +534,8 @@
   void set_containing_set(HeapRegionSetBase* containing_set) {
     assert((containing_set == NULL && _containing_set != NULL) ||
            (containing_set != NULL && _containing_set == NULL),
-           err_msg("containing_set: "PTR_FORMAT" "
-                   "_containing_set: "PTR_FORMAT,
+           err_msg("containing_set: " PTR_FORMAT " "
+                   "_containing_set: " PTR_FORMAT,
                    p2i(containing_set), p2i(_containing_set)));
 
     _containing_set = containing_set;
diff --git a/src/share/vm/gc_implementation/g1/heapRegion.inline.hpp b/src/share/vm/gc_implementation/g1/heapRegion.inline.hpp
index 62ae230..46e8b00 100644
--- a/src/share/vm/gc_implementation/g1/heapRegion.inline.hpp
+++ b/src/share/vm/gc_implementation/g1/heapRegion.inline.hpp
@@ -112,7 +112,7 @@
 
   assert(ClassUnloadingWithConcurrentMark,
       err_msg("All blocks should be objects if G1 Class Unloading isn't used. "
-              "HR: ["PTR_FORMAT", "PTR_FORMAT", "PTR_FORMAT") "
+              "HR: [" PTR_FORMAT ", " PTR_FORMAT ", " PTR_FORMAT ") "
               "addr: " PTR_FORMAT,
               p2i(bottom()), p2i(top()), p2i(end()), p2i(addr)));
 
diff --git a/src/share/vm/gc_implementation/g1/heapRegionManager.cpp b/src/share/vm/gc_implementation/g1/heapRegionManager.cpp
index 020eb08..14673df 100644
--- a/src/share/vm/gc_implementation/g1/heapRegionManager.cpp
+++ b/src/share/vm/gc_implementation/g1/heapRegionManager.cpp
@@ -432,7 +432,7 @@
     HeapRegion* hr = _regions.get_by_index(i);
     guarantee(hr != NULL, err_msg("invariant: i: %u", i));
     guarantee(!prev_committed || hr->bottom() == prev_end,
-              err_msg("invariant i: %u "HR_FORMAT" prev_end: "PTR_FORMAT,
+              err_msg("invariant i: %u " HR_FORMAT " prev_end: " PTR_FORMAT,
                       i, HR_FORMAT_PARAMS(hr), p2i(prev_end)));
     guarantee(hr->hrm_index() == i,
               err_msg("invariant: i: %u hrm_index(): %u", i, hr->hrm_index()));
diff --git a/src/share/vm/gc_implementation/g1/heapRegionManager.inline.hpp b/src/share/vm/gc_implementation/g1/heapRegionManager.inline.hpp
index 96bc92f..68840d6 100644
--- a/src/share/vm/gc_implementation/g1/heapRegionManager.inline.hpp
+++ b/src/share/vm/gc_implementation/g1/heapRegionManager.inline.hpp
@@ -31,9 +31,9 @@
 
 inline HeapRegion* HeapRegionManager::addr_to_region(HeapWord* addr) const {
   assert(addr < heap_end(),
-        err_msg("addr: "PTR_FORMAT" end: "PTR_FORMAT, p2i(addr), p2i(heap_end())));
+        err_msg("addr: " PTR_FORMAT " end: " PTR_FORMAT, p2i(addr), p2i(heap_end())));
   assert(addr >= heap_bottom(),
-        err_msg("addr: "PTR_FORMAT" bottom: "PTR_FORMAT, p2i(addr), p2i(heap_bottom())));
+        err_msg("addr: " PTR_FORMAT " bottom: " PTR_FORMAT, p2i(addr), p2i(heap_bottom())));
 
   HeapRegion* hr = _regions.get_by_address(addr);
   return hr;
diff --git a/src/share/vm/gc_implementation/g1/heapRegionRemSet.cpp b/src/share/vm/gc_implementation/g1/heapRegionRemSet.cpp
index 662f4f1..4376362 100644
--- a/src/share/vm/gc_implementation/g1/heapRegionRemSet.cpp
+++ b/src/share/vm/gc_implementation/g1/heapRegionRemSet.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -381,7 +381,7 @@
 
 void FromCardCache::invalidate(uint start_idx, size_t new_num_regions) {
   guarantee((size_t)start_idx + new_num_regions <= max_uintx,
-            err_msg("Trying to invalidate beyond maximum region, from %u size "SIZE_FORMAT,
+            err_msg("Trying to invalidate beyond maximum region, from %u size " SIZE_FORMAT,
                     start_idx, new_num_regions));
   for (uint i = 0; i < HeapRegionRemSet::num_par_rem_sets(); i++) {
     uint end_idx = (start_idx + (uint)new_num_regions);
@@ -396,7 +396,7 @@
 void FromCardCache::print(outputStream* out) {
   for (uint i = 0; i < HeapRegionRemSet::num_par_rem_sets(); i++) {
     for (uint j = 0; j < _max_regions; j++) {
-      out->print_cr("_from_card_cache["UINT32_FORMAT"]["UINT32_FORMAT"] = "INT32_FORMAT".",
+      out->print_cr("_from_card_cache[" UINT32_FORMAT "][" UINT32_FORMAT "] = " INT32_FORMAT ".",
                     i, j, at(i, j));
     }
   }
@@ -436,7 +436,7 @@
   int from_card = (int)(uintptr_t(from) >> CardTableModRefBS::card_shift);
 
   if (G1TraceHeapRegionRememberedSet) {
-    gclog_or_tty->print_cr("Table for [" PTR_FORMAT "...): card %d (cache = "INT32_FORMAT")",
+    gclog_or_tty->print_cr("Table for [" PTR_FORMAT "...): card %d (cache = " INT32_FORMAT ")",
                   hr()->bottom(), from_card,
                   FromCardCache::at((uint)tid, cur_hrm_ind));
   }
@@ -514,7 +514,15 @@
 
       PerRegionTable* first_prt = _fine_grain_regions[ind];
       prt->set_collision_list_next(first_prt);
-      _fine_grain_regions[ind] = prt;
+      // The assignment into _fine_grain_regions allows the prt to
+      // start being used concurrently. In addition to
+      // collision_list_next which must be visible (else concurrent
+      // parsing of the list, if any, may fail to see other entries),
+      // the content of the prt must be visible (else for instance
+      // some mark bits may not yet seem cleared or a 'later' update
+      // performed by a concurrent thread could be undone when the
+      // zeroing becomes visible). This requires store ordering.
+      OrderAccess::release_store_ptr((volatile PerRegionTable*)&_fine_grain_regions[ind], prt);
       _n_fine_entries++;
 
       if (G1HRRSUseSparseTable) {
@@ -642,13 +650,13 @@
 
   assert(_coarse_map.size() == region_bm->size(), "Precondition");
   if (G1RSScrubVerbose) {
-    gclog_or_tty->print("   Coarse map: before = "SIZE_FORMAT"...",
+    gclog_or_tty->print("   Coarse map: before = " SIZE_FORMAT "...",
                         _n_coarse_entries);
   }
   _coarse_map.set_intersection(*region_bm);
   _n_coarse_entries = _coarse_map.count_one_bits();
   if (G1RSScrubVerbose) {
-    gclog_or_tty->print_cr("   after = "SIZE_FORMAT".", _n_coarse_entries);
+    gclog_or_tty->print_cr("   after = " SIZE_FORMAT ".", _n_coarse_entries);
   }
 
   // Now do the fine-grained maps.
@@ -950,6 +958,9 @@
 
 void HeapRegionRemSet::add_strong_code_root(nmethod* nm) {
   assert(nm != NULL, "sanity");
+  assert((!CodeCache_lock->owned_by_self() || SafepointSynchronize::is_at_safepoint()),
+          err_msg("should call add_strong_code_root_locked instead. CodeCache_lock->owned_by_self(): %s, is_at_safepoint(): %s",
+                  BOOL_TO_STR(CodeCache_lock->owned_by_self()), BOOL_TO_STR(SafepointSynchronize::is_at_safepoint())));
   // Optimistic unlocked contains-check
   if (!_code_roots.contains(nm)) {
     MutexLockerEx ml(&_m, Mutex::_no_safepoint_check_flag);
@@ -959,6 +970,12 @@
 
 void HeapRegionRemSet::add_strong_code_root_locked(nmethod* nm) {
   assert(nm != NULL, "sanity");
+  assert((CodeCache_lock->owned_by_self() ||
+         (SafepointSynchronize::is_at_safepoint() &&
+          (_m.owned_by_self() || Thread::current()->is_VM_thread()))),
+          err_msg("not safely locked. CodeCache_lock->owned_by_self(): %s, is_at_safepoint(): %s, _m.owned_by_self(): %s, Thread::current()->is_VM_thread(): %s",
+                  BOOL_TO_STR(CodeCache_lock->owned_by_self()), BOOL_TO_STR(SafepointSynchronize::is_at_safepoint()),
+                  BOOL_TO_STR(_m.owned_by_self()), BOOL_TO_STR(Thread::current()->is_VM_thread())));
   _code_roots.add(nm);
 }
 
@@ -1044,7 +1061,7 @@
 
   card_index = _cur_region_card_offset + _cur_card_in_prt;
   guarantee(_cur_card_in_prt < HeapRegion::CardsPerRegion,
-            err_msg("Card index "SIZE_FORMAT" must be within the region", _cur_card_in_prt));
+            err_msg("Card index " SIZE_FORMAT " must be within the region", _cur_card_in_prt));
   return true;
 }
 
@@ -1213,8 +1230,8 @@
 
   size_t min_prt_size = sizeof(void*) + dummy->bm()->size_in_words() * HeapWordSize;
   assert(dummy->mem_size() > min_prt_size,
-         err_msg("PerRegionTable memory usage is suspiciously small, only has "SIZE_FORMAT" bytes. "
-                 "Should be at least "SIZE_FORMAT" bytes.", dummy->mem_size(), min_prt_size));
+         err_msg("PerRegionTable memory usage is suspiciously small, only has " SIZE_FORMAT " bytes. "
+                 "Should be at least " SIZE_FORMAT " bytes.", dummy->mem_size(), min_prt_size));
   free(dummy);
   guarantee(dummy->mem_size() == fl_mem_size(), "fl_mem_size() does not return the correct element size");
   // try to reset the state
diff --git a/src/share/vm/gc_implementation/g1/heapRegionSet.cpp b/src/share/vm/gc_implementation/g1/heapRegionSet.cpp
index b654430..9ffb46f 100644
--- a/src/share/vm/gc_implementation/g1/heapRegionSet.cpp
+++ b/src/share/vm/gc_implementation/g1/heapRegionSet.cpp
@@ -32,7 +32,7 @@
 uint FreeRegionList::_unrealistically_long_length = 0;
 
 void HeapRegionSetBase::fill_in_ext_msg(hrs_ext_msg* msg, const char* message) {
-  msg->append("[%s] %s ln: %u cy: "SIZE_FORMAT,
+  msg->append("[%s] %s ln: %u cy: " SIZE_FORMAT,
               name(), message, length(), total_capacity_bytes());
   fill_in_ext_msg_extra(msg);
 }
@@ -84,13 +84,13 @@
 
 void HeapRegionSetBase::print_on(outputStream* out, bool print_contents) {
   out->cr();
-  out->print_cr("Set: %s ("PTR_FORMAT")", name(), this);
+  out->print_cr("Set: %s (" PTR_FORMAT ")", name(), this);
   out->print_cr("  Region Assumptions");
   out->print_cr("    humongous         : %s", BOOL_TO_STR(regions_humongous()));
   out->print_cr("    free              : %s", BOOL_TO_STR(regions_free()));
   out->print_cr("  Attributes");
   out->print_cr("    length            : %14u", length());
-  out->print_cr("    total capacity    : "SIZE_FORMAT_W(14)" bytes",
+  out->print_cr("    total capacity    : " SIZE_FORMAT_W(14) " bytes",
                 total_capacity_bytes());
 }
 
@@ -106,7 +106,7 @@
 }
 
 void FreeRegionList::fill_in_ext_msg_extra(hrs_ext_msg* msg) {
-  msg->append(" hd: "PTR_FORMAT" tl: "PTR_FORMAT, _head, _tail);
+  msg->append(" hd: " PTR_FORMAT " tl: " PTR_FORMAT, _head, _tail);
 }
 
 void FreeRegionList::remove_all() {
@@ -277,8 +277,8 @@
 void FreeRegionList::print_on(outputStream* out, bool print_contents) {
   HeapRegionSetBase::print_on(out, print_contents);
   out->print_cr("  Linking");
-  out->print_cr("    head              : "PTR_FORMAT, _head);
-  out->print_cr("    tail              : "PTR_FORMAT, _tail);
+  out->print_cr("    head              : " PTR_FORMAT, _head);
+  out->print_cr("    tail              : " PTR_FORMAT, _tail);
 
   if (print_contents) {
     out->print_cr("  Contents");
@@ -306,7 +306,7 @@
 
     count++;
     guarantee(count < _unrealistically_long_length,
-        hrs_err_msg("[%s] the calculated length: %u seems very long, is there maybe a cycle? curr: "PTR_FORMAT" prev0: "PTR_FORMAT" " "prev1: "PTR_FORMAT" length: %u", name(), count, curr, prev0, prev1, length()));
+        hrs_err_msg("[%s] the calculated length: %u seems very long, is there maybe a cycle? curr: " PTR_FORMAT " prev0: " PTR_FORMAT " " "prev1: " PTR_FORMAT " length: %u", name(), count, curr, prev0, prev1, length()));
 
     if (curr->next() != NULL) {
       guarantee(curr->next()->prev() == curr, "Next or prev pointers messed up");
diff --git a/src/share/vm/gc_implementation/g1/satbQueue.cpp b/src/share/vm/gc_implementation/g1/satbQueue.cpp
index 3544db5..d423c69 100644
--- a/src/share/vm/gc_implementation/g1/satbQueue.cpp
+++ b/src/share/vm/gc_implementation/g1/satbQueue.cpp
@@ -202,8 +202,8 @@
 
 void ObjPtrQueue::print(const char* name,
                         void** buf, size_t index, size_t sz) {
-  gclog_or_tty->print_cr("  SATB BUFFER [%s] buf: "PTR_FORMAT" "
-                         "index: "SIZE_FORMAT" sz: "SIZE_FORMAT,
+  gclog_or_tty->print_cr("  SATB BUFFER [%s] buf: " PTR_FORMAT " "
+                         "index: " SIZE_FORMAT " sz: " SIZE_FORMAT,
                          name, buf, index, sz);
 }
 #endif // PRODUCT
diff --git a/src/share/vm/gc_implementation/parallelScavenge/gcTaskManager.cpp b/src/share/vm/gc_implementation/parallelScavenge/gcTaskManager.cpp
index 4dda503..153e5bd 100644
--- a/src/share/vm/gc_implementation/parallelScavenge/gcTaskManager.cpp
+++ b/src/share/vm/gc_implementation/parallelScavenge/gcTaskManager.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1035,7 +1035,7 @@
    if (monitor() != NULL) {
      MonitorSupply::release(monitor());
   }
-  _monitor = (Monitor*) 0xDEAD000F;
+  _monitor = (Monitor*) (uintptr_t) 0xDEAD000F;
 }
 
 void WaitForBarrierGCTask::do_it(GCTaskManager* manager, uint which) {
diff --git a/src/share/vm/gc_implementation/shared/mutableNUMASpace.cpp b/src/share/vm/gc_implementation/shared/mutableNUMASpace.cpp
index 9a9ed05..39a370c 100644
--- a/src/share/vm/gc_implementation/shared/mutableNUMASpace.cpp
+++ b/src/share/vm/gc_implementation/shared/mutableNUMASpace.cpp
@@ -86,7 +86,7 @@
         while (words_left_to_fill > 0) {
           size_t words_to_fill = MIN2(words_left_to_fill, CollectedHeap::filler_array_max_size());
           assert(words_to_fill >= CollectedHeap::min_fill_size(),
-            err_msg("Remaining size ("SIZE_FORMAT ") is too small to fill (based on " SIZE_FORMAT " and " SIZE_FORMAT ")",
+            err_msg("Remaining size (" SIZE_FORMAT ") is too small to fill (based on " SIZE_FORMAT " and " SIZE_FORMAT ")",
             words_to_fill, words_left_to_fill, CollectedHeap::filler_array_max_size()));
           CollectedHeap::fill_with_object((HeapWord*)cur_top, words_to_fill);
           if (!os::numa_has_static_binding()) {
diff --git a/src/share/vm/interpreter/bytecodeInterpreter.cpp b/src/share/vm/interpreter/bytecodeInterpreter.cpp
index 59e1fb9..3a5f31a 100644
--- a/src/share/vm/interpreter/bytecodeInterpreter.cpp
+++ b/src/share/vm/interpreter/bytecodeInterpreter.cpp
@@ -2569,13 +2569,35 @@
 
         // this could definitely be cleaned up QQQ
         Method* callee;
-        Klass* iclass = cache->f1_as_klass();
-        // InstanceKlass* interface = (InstanceKlass*) iclass;
+        Method *interface_method = cache->f2_as_interface_method();
+        InstanceKlass* iclass = interface_method->method_holder();
+
         // get receiver
         int parms = cache->parameter_size();
         oop rcvr = STACK_OBJECT(-parms);
         CHECK_NULL(rcvr);
         InstanceKlass* int2 = (InstanceKlass*) rcvr->klass();
+
+        // Receiver subtype check against resolved interface klass (REFC).
+        {
+          Klass* refc = cache->f1_as_klass();
+          itableOffsetEntry* scan;
+          for (scan = (itableOffsetEntry*) int2->start_of_itable();
+               scan->interface_klass() != NULL;
+               scan++) {
+            if (scan->interface_klass() == refc) {
+              break;
+            }
+          }
+          // Check that the entry is non-null.  A null entry means
+          // that the receiver class doesn't implement the
+          // interface, and wasn't the same as when the caller was
+          // compiled.
+          if (scan->interface_klass() == NULL) {
+            VM_JAVA_ERROR(vmSymbols::java_lang_IncompatibleClassChangeError(), "", note_no_trap);
+          }
+        }
+
         itableOffsetEntry* ki = (itableOffsetEntry*) int2->start_of_itable();
         int i;
         for ( i = 0 ; i < int2->itable_length() ; i++, ki++ ) {
@@ -2587,7 +2609,8 @@
         if (i == int2->itable_length()) {
           VM_JAVA_ERROR(vmSymbols::java_lang_IncompatibleClassChangeError(), "", note_no_trap);
         }
-        int mindex = cache->f2_as_index();
+        int mindex = interface_method->itable_index();
+
         itableMethodEntry* im = ki->first_method_entry(rcvr->klass());
         callee = im[mindex].method();
         if (callee == NULL) {
diff --git a/src/share/vm/interpreter/cppInterpreterGenerator.hpp b/src/share/vm/interpreter/cppInterpreterGenerator.hpp
index c27805e..b753027 100644
--- a/src/share/vm/interpreter/cppInterpreterGenerator.hpp
+++ b/src/share/vm/interpreter/cppInterpreterGenerator.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -29,6 +29,9 @@
 // of the template interpreter generator.
 
 #ifdef CC_INTERP
+#ifdef TARGET_ARCH_zero
+# include "entry_zero.hpp"
+#endif
 
 class CppInterpreterGenerator: public AbstractInterpreterGenerator {
   protected:
diff --git a/src/share/vm/interpreter/interpreter.hpp b/src/share/vm/interpreter/interpreter.hpp
index d3792f8..1f18ce1 100644
--- a/src/share/vm/interpreter/interpreter.hpp
+++ b/src/share/vm/interpreter/interpreter.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -28,11 +28,9 @@
 #include "code/stubs.hpp"
 #include "interpreter/cppInterpreter.hpp"
 #include "interpreter/templateInterpreter.hpp"
-#ifdef ZERO
 #ifdef TARGET_ARCH_zero
 # include "entry_zero.hpp"
 #endif
-#endif
 
 // This file contains the platform-independent parts
 // of the interpreter and the interpreter generator.
diff --git a/src/share/vm/interpreter/interpreterRuntime.cpp b/src/share/vm/interpreter/interpreterRuntime.cpp
index de928e9..b5a7229 100644
--- a/src/share/vm/interpreter/interpreterRuntime.cpp
+++ b/src/share/vm/interpreter/interpreterRuntime.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -320,6 +320,8 @@
   Handle exception = get_preinitialized_exception(
                                  SystemDictionary::StackOverflowError_klass(),
                                  CHECK);
+  // Increment counter for hs_err file reporting
+  Atomic::inc(&Exceptions::_stack_overflow_errors);
   THROW_HANDLE(exception);
 IRT_END
 
@@ -768,7 +770,7 @@
   // it is not an interface.  The receiver for invokespecial calls within interface
   // methods must be checked for every call.
   InstanceKlass* sender = pool->pool_holder();
-  sender = sender->is_anonymous() ? InstanceKlass::cast(sender->host_klass()) : sender;
+  sender = sender->has_host_klass() ? InstanceKlass::cast(sender->host_klass()) : sender;
 
   switch (info.call_kind()) {
   case CallInfo::direct_call:
@@ -786,6 +788,7 @@
   case CallInfo::itable_call:
     cache_entry(thread)->set_itable_call(
       bytecode,
+      info.resolved_klass(),
       info.resolved_method(),
       info.itable_index());
     break;
diff --git a/src/share/vm/interpreter/linkResolver.cpp b/src/share/vm/interpreter/linkResolver.cpp
index aae38fa..3a27bec 100644
--- a/src/share/vm/interpreter/linkResolver.cpp
+++ b/src/share/vm/interpreter/linkResolver.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -540,6 +540,42 @@
   }
 }
 
+void LinkResolver::check_method_loader_constraints(methodHandle& resolved_method,
+                                                   KlassHandle resolved_klass,
+                                                   Symbol* method_name,
+                                                   Symbol* method_signature,
+                                                   KlassHandle current_klass,
+                                                   const char* method_type, TRAPS) {
+  Handle loader (THREAD, InstanceKlass::cast(current_klass())->class_loader());
+  Handle class_loader (THREAD, resolved_method->method_holder()->class_loader());
+  {
+    ResourceMark rm(THREAD);
+    Symbol* failed_type_symbol =
+      SystemDictionary::check_signature_loaders(method_signature, loader,
+                                                class_loader, true, CHECK);
+    if (failed_type_symbol != NULL) {
+      const char* msg = "loader constraint violation: when resolving %s"
+        " \"%s\" the class loader (instance of %s) of the current class, %s,"
+        " and the class loader (instance of %s) for the method's defining class, %s, have"
+        " different Class objects for the type %s used in the signature";
+      char* sig = Method::name_and_sig_as_C_string(resolved_klass(), method_name, method_signature);
+      const char* loader1 = SystemDictionary::loader_name(loader());
+      char* current = InstanceKlass::cast(current_klass())->name()->as_C_string();
+      const char* loader2 = SystemDictionary::loader_name(class_loader());
+      char* target = InstanceKlass::cast(resolved_method->method_holder())
+                     ->name()->as_C_string();
+      char* failed_type_name = failed_type_symbol->as_C_string();
+      size_t buflen = strlen(msg) + strlen(sig) + strlen(loader1) +
+        strlen(current) + strlen(loader2) + strlen(target) +
+        strlen(failed_type_name) + strlen(method_type) + 1;
+      char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen);
+      jio_snprintf(buf, buflen, msg, method_type, sig, loader1, current, loader2,
+                   target, failed_type_name);
+      THROW_MSG(vmSymbols::java_lang_LinkageError(), buf);
+    }
+  }
+}
+
 void LinkResolver::resolve_method(methodHandle& resolved_method, KlassHandle resolved_klass,
                                   Symbol* method_name, Symbol* method_signature,
                                   KlassHandle current_klass, bool check_access,
@@ -596,34 +632,8 @@
                                CHECK);
 
     // check loader constraints
-    Handle loader (THREAD, InstanceKlass::cast(current_klass())->class_loader());
-    Handle class_loader (THREAD, resolved_method->method_holder()->class_loader());
-    {
-      ResourceMark rm(THREAD);
-      Symbol* failed_type_symbol =
-        SystemDictionary::check_signature_loaders(method_signature, loader,
-                                                  class_loader, true, CHECK);
-      if (failed_type_symbol != NULL) {
-        const char* msg = "loader constraint violation: when resolving method"
-          " \"%s\" the class loader (instance of %s) of the current class, %s,"
-          " and the class loader (instance of %s) for the method's defining class, %s, have"
-          " different Class objects for the type %s used in the signature";
-        char* sig = Method::name_and_sig_as_C_string(resolved_klass(),method_name,method_signature);
-        const char* loader1 = SystemDictionary::loader_name(loader());
-        char* current = InstanceKlass::cast(current_klass())->name()->as_C_string();
-        const char* loader2 = SystemDictionary::loader_name(class_loader());
-        char* target = InstanceKlass::cast(resolved_method->method_holder())
-                       ->name()->as_C_string();
-        char* failed_type_name = failed_type_symbol->as_C_string();
-        size_t buflen = strlen(msg) + strlen(sig) + strlen(loader1) +
-          strlen(current) + strlen(loader2) + strlen(target) +
-          strlen(failed_type_name) + 1;
-        char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen);
-        jio_snprintf(buf, buflen, msg, sig, loader1, current, loader2,
-                     target, failed_type_name);
-        THROW_MSG(vmSymbols::java_lang_LinkageError(), buf);
-      }
-    }
+    check_method_loader_constraints(resolved_method, resolved_klass, method_name,
+                                    method_signature, current_klass, "method", CHECK);
   }
 }
 
@@ -672,36 +682,8 @@
                                resolved_method,
                                CHECK);
 
-    HandleMark hm(THREAD);
-    Handle loader (THREAD, InstanceKlass::cast(current_klass())->class_loader());
-    Handle class_loader (THREAD, resolved_method->method_holder()->class_loader());
-    {
-      ResourceMark rm(THREAD);
-      Symbol* failed_type_symbol =
-        SystemDictionary::check_signature_loaders(method_signature, loader,
-                                                  class_loader, true, CHECK);
-      if (failed_type_symbol != NULL) {
-        const char* msg = "loader constraint violation: when resolving "
-          "interface method \"%s\" the class loader (instance of %s) of the "
-          "current class, %s, and the class loader (instance of %s) for "
-          "the method's defining class, %s, have different Class objects for the type %s "
-          "used in the signature";
-        char* sig = Method::name_and_sig_as_C_string(resolved_klass(),method_name,method_signature);
-        const char* loader1 = SystemDictionary::loader_name(loader());
-        char* current = InstanceKlass::cast(current_klass())->name()->as_C_string();
-        const char* loader2 = SystemDictionary::loader_name(class_loader());
-        char* target = InstanceKlass::cast(resolved_method->method_holder())
-                       ->name()->as_C_string();
-        char* failed_type_name = failed_type_symbol->as_C_string();
-        size_t buflen = strlen(msg) + strlen(sig) + strlen(loader1) +
-          strlen(current) + strlen(loader2) + strlen(target) +
-          strlen(failed_type_name) + 1;
-        char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen);
-        jio_snprintf(buf, buflen, msg, sig, loader1, current, loader2,
-                     target, failed_type_name);
-        THROW_MSG(vmSymbols::java_lang_LinkageError(), buf);
-      }
-    }
+    check_method_loader_constraints(resolved_method, resolved_klass, method_name,
+                                    method_signature, current_klass, "interface method", CHECK);
   }
 
   if (nostatics && resolved_method->is_static()) {
@@ -797,37 +779,37 @@
     THROW_MSG(vmSymbols::java_lang_NoSuchFieldError(), field->as_C_string());
   }
 
-  if (!check_access)
-    // Access checking may be turned off when calling from within the VM.
-    return;
+  // Access checking may be turned off when calling from within the VM.
+  if (check_access) {
 
-  // check access
-  check_field_accessability(current_klass, resolved_klass, sel_klass, fd, CHECK);
+    // check access
+    check_field_accessability(current_klass, resolved_klass, sel_klass, fd, CHECK);
 
-  // check for errors
-  if (is_static != fd.is_static()) {
-    ResourceMark rm(THREAD);
-    char msg[200];
-    jio_snprintf(msg, sizeof(msg), "Expected %s field %s.%s", is_static ? "static" : "non-static", resolved_klass()->external_name(), fd.name()->as_C_string());
-    THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(), msg);
+    // check for errors
+    if (is_static != fd.is_static()) {
+      ResourceMark rm(THREAD);
+      char msg[200];
+      jio_snprintf(msg, sizeof(msg), "Expected %s field %s.%s", is_static ? "static" : "non-static", resolved_klass()->external_name(), fd.name()->as_C_string());
+      THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(), msg);
+    }
+
+    // Final fields can only be accessed from its own class.
+    if (is_put && fd.access_flags().is_final() && sel_klass() != current_klass()) {
+      THROW(vmSymbols::java_lang_IllegalAccessError());
+    }
+
+    // initialize resolved_klass if necessary
+    // note 1: the klass which declared the field must be initialized (i.e, sel_klass)
+    //         according to the newest JVM spec (5.5, p.170) - was bug (gri 7/28/99)
+    //
+    // note 2: we don't want to force initialization if we are just checking
+    //         if the field access is legal; e.g., during compilation
+    if (is_static && initialize_class) {
+      sel_klass->initialize(CHECK);
+    }
   }
 
-  // Final fields can only be accessed from its own class.
-  if (is_put && fd.access_flags().is_final() && sel_klass() != current_klass()) {
-    THROW(vmSymbols::java_lang_IllegalAccessError());
-  }
-
-  // initialize resolved_klass if necessary
-  // note 1: the klass which declared the field must be initialized (i.e, sel_klass)
-  //         according to the newest JVM spec (5.5, p.170) - was bug (gri 7/28/99)
-  //
-  // note 2: we don't want to force initialization if we are just checking
-  //         if the field access is legal; e.g., during compilation
-  if (is_static && initialize_class) {
-    sel_klass->initialize(CHECK);
-  }
-
-  if (sel_klass() != current_klass()) {
+  if (sel_klass() != current_klass() && !current_klass.is_null()) {
     HandleMark hm(THREAD);
     Handle ref_loader (THREAD, InstanceKlass::cast(current_klass())->class_loader());
     Handle sel_loader (THREAD, InstanceKlass::cast(sel_klass())->class_loader());
@@ -1051,6 +1033,10 @@
                   Method::name_and_sig_as_C_string(resolved_klass(),
                                             resolved_method->name(),
                                             resolved_method->signature()));
+      } else if (sel_method() != resolved_method()) {
+        check_method_loader_constraints(sel_method, resolved_klass,
+                                        sel_method->name(), sel_method->signature(),
+                                        current_klass, "method", CHECK);
       }
     }
 
diff --git a/src/share/vm/interpreter/linkResolver.hpp b/src/share/vm/interpreter/linkResolver.hpp
index 0fc1712..203b653 100644
--- a/src/share/vm/interpreter/linkResolver.hpp
+++ b/src/share/vm/interpreter/linkResolver.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -135,6 +135,9 @@
   static void resolve_pool  (KlassHandle& resolved_klass, Symbol*& method_name, Symbol*& method_signature, KlassHandle& current_klass, constantPoolHandle pool, int index, TRAPS);
 
   static void resolve_interface_method(methodHandle& resolved_method, KlassHandle resolved_klass, Symbol* method_name, Symbol* method_signature, KlassHandle current_klass, bool check_access, bool nostatics, TRAPS);
+  static void check_method_loader_constraints(methodHandle& resolved_method, KlassHandle resolved_klass,
+                                              Symbol* method_name, Symbol* method_signature,
+                                              KlassHandle current_klass, const char* method_type, TRAPS);
   static void resolve_method          (methodHandle& resolved_method, KlassHandle resolved_klass, Symbol* method_name, Symbol* method_signature, KlassHandle current_klass, bool check_access, bool require_methodref, TRAPS);
 
   static void linktime_resolve_static_method    (methodHandle& resolved_method, KlassHandle resolved_klass, Symbol* method_name, Symbol* method_signature, KlassHandle current_klass, bool check_access, TRAPS);
diff --git a/src/share/vm/interpreter/oopMapCache.cpp b/src/share/vm/interpreter/oopMapCache.cpp
index d3f1888..f696bcb 100644
--- a/src/share/vm/interpreter/oopMapCache.cpp
+++ b/src/share/vm/interpreter/oopMapCache.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -426,9 +426,9 @@
 
 #ifndef PRODUCT
 
-static long _total_memory_usage = 0;
+static size_t _total_memory_usage = 0;
 
-long OopMapCache::memory_usage() {
+size_t OopMapCache::memory_usage() {
   return _total_memory_usage;
 }
 
diff --git a/src/share/vm/interpreter/oopMapCache.hpp b/src/share/vm/interpreter/oopMapCache.hpp
index dbdd4cb..99fbe81 100644
--- a/src/share/vm/interpreter/oopMapCache.hpp
+++ b/src/share/vm/interpreter/oopMapCache.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -176,7 +176,7 @@
   static void compute_one_oop_map(methodHandle method, int bci, InterpreterOopMap* entry);
 
   // Returns total no. of bytes allocated as part of OopMapCache's
-  static long memory_usage()                     PRODUCT_RETURN0;
+  static size_t memory_usage()                     PRODUCT_RETURN0;
 };
 
 #endif // SHARE_VM_INTERPRETER_OOPMAPCACHE_HPP
diff --git a/src/share/vm/memory/allocation.cpp b/src/share/vm/memory/allocation.cpp
index 1fe4b36..96d83ac 100644
--- a/src/share/vm/memory/allocation.cpp
+++ b/src/share/vm/memory/allocation.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -66,8 +66,7 @@
                                  size_t word_size, bool read_only,
                                  MetaspaceObj::Type type, TRAPS) throw() {
   // Klass has it's own operator new
-  return Metaspace::allocate(loader_data, word_size, read_only,
-                             type, CHECK_NULL);
+  return Metaspace::allocate(loader_data, word_size, read_only, type, THREAD);
 }
 
 bool MetaspaceObj::is_shared() const {
@@ -749,7 +748,7 @@
 julong  AllocStats::resource_bytes() { return Arena::_bytes_allocated - start_res_bytes; }
 void    AllocStats::print() {
   tty->print_cr(UINT64_FORMAT " mallocs (" UINT64_FORMAT "MB), "
-                UINT64_FORMAT" frees (" UINT64_FORMAT "MB), " UINT64_FORMAT "MB resrc",
+                UINT64_FORMAT " frees (" UINT64_FORMAT "MB), " UINT64_FORMAT "MB resrc",
                 num_mallocs(), alloc_bytes()/M, num_frees(), free_bytes()/M, resource_bytes()/M);
 }
 
diff --git a/src/share/vm/memory/barrierSet.inline.hpp b/src/share/vm/memory/barrierSet.inline.hpp
index 274614b..1188ea8 100644
--- a/src/share/vm/memory/barrierSet.inline.hpp
+++ b/src/share/vm/memory/barrierSet.inline.hpp
@@ -69,7 +69,7 @@
   assert(UseCompressedOops || (aligned_start == start && aligned_end == end),
          "Expected heap word alignment of start and end");
 #if 0
-  warning("Post:\t" INTPTR_FORMAT "[" SIZE_FORMAT "] : [" INTPTR_FORMAT","INTPTR_FORMAT")\t",
+  warning("Post:\t" INTPTR_FORMAT "[" SIZE_FORMAT "] : [" INTPTR_FORMAT "," INTPTR_FORMAT ")\t",
                    start,            count,              aligned_start,   aligned_end);
 #endif
   write_ref_array_work(MemRegion(aligned_start, aligned_end));
diff --git a/src/share/vm/memory/blockOffsetTable.cpp b/src/share/vm/memory/blockOffsetTable.cpp
index 1275b17..815f872 100644
--- a/src/share/vm/memory/blockOffsetTable.cpp
+++ b/src/share/vm/memory/blockOffsetTable.cpp
@@ -560,7 +560,7 @@
     q = n;
     n += _sp->block_size(n);
     assert(n > q,
-           err_msg("Looping at n = " PTR_FORMAT " with last = " PTR_FORMAT","
+           err_msg("Looping at n = " PTR_FORMAT " with last = " PTR_FORMAT ","
                    " while querying blk_start(" PTR_FORMAT ")"
                    " on _sp = [" PTR_FORMAT "," PTR_FORMAT ")",
                    p2i(n), p2i(last), p2i(addr), p2i(_sp->bottom()), p2i(_sp->end())));
diff --git a/src/share/vm/memory/cardTableModRefBS.cpp b/src/share/vm/memory/cardTableModRefBS.cpp
index eebd63e..be8e4c7 100644
--- a/src/share/vm/memory/cardTableModRefBS.cpp
+++ b/src/share/vm/memory/cardTableModRefBS.cpp
@@ -678,7 +678,7 @@
                       (val_equals) ? "" : "not ", val);
         failures = true;
       }
-      tty->print_cr("==   card "PTR_FORMAT" ["PTR_FORMAT","PTR_FORMAT"], "
+      tty->print_cr("==   card " PTR_FORMAT " [" PTR_FORMAT "," PTR_FORMAT "], "
                     "val: %d", p2i(curr), p2i(addr_for(curr)),
                     p2i((HeapWord*) (((size_t) addr_for(curr)) + card_size)),
                     (int) curr_val);
diff --git a/src/share/vm/memory/cardTableModRefBS.hpp b/src/share/vm/memory/cardTableModRefBS.hpp
index ae15ba7..01e4688 100644
--- a/src/share/vm/memory/cardTableModRefBS.hpp
+++ b/src/share/vm/memory/cardTableModRefBS.hpp
@@ -158,8 +158,8 @@
   // Mapping from address to card marking array entry
   jbyte* byte_for(const void* p) const {
     assert(_whole_heap.contains(p),
-           err_msg("Attempt to access p = "PTR_FORMAT" out of bounds of "
-                   " card marking array's _whole_heap = ["PTR_FORMAT","PTR_FORMAT")",
+           err_msg("Attempt to access p = " PTR_FORMAT " out of bounds of "
+                   " card marking array's _whole_heap = [" PTR_FORMAT "," PTR_FORMAT ")",
                    p2i(p), p2i(_whole_heap.start()), p2i(_whole_heap.end())));
     jbyte* result = &byte_map_base[uintptr_t(p) >> card_shift];
     assert(result >= _byte_map && result < _byte_map + _byte_map_size,
@@ -436,8 +436,8 @@
     size_t delta = pointer_delta(p, byte_map_base, sizeof(jbyte));
     HeapWord* result = (HeapWord*) (delta << card_shift);
     assert(_whole_heap.contains(result),
-           err_msg("Returning result = "PTR_FORMAT" out of bounds of "
-                   " card marking array's _whole_heap = ["PTR_FORMAT","PTR_FORMAT")",
+           err_msg("Returning result = " PTR_FORMAT " out of bounds of "
+                   " card marking array's _whole_heap = [" PTR_FORMAT "," PTR_FORMAT ")",
                    p2i(result), p2i(_whole_heap.start()), p2i(_whole_heap.end())));
     return result;
   }
@@ -445,8 +445,8 @@
   // Mapping from address to card marking array index.
   size_t index_for(void* p) {
     assert(_whole_heap.contains(p),
-           err_msg("Attempt to access p = "PTR_FORMAT" out of bounds of "
-                   " card marking array's _whole_heap = ["PTR_FORMAT","PTR_FORMAT")",
+           err_msg("Attempt to access p = " PTR_FORMAT " out of bounds of "
+                   " card marking array's _whole_heap = [" PTR_FORMAT "," PTR_FORMAT ")",
                    p2i(p), p2i(_whole_heap.start()), p2i(_whole_heap.end())));
     return byte_for(p) - _byte_map;
   }
diff --git a/src/share/vm/memory/generation.cpp b/src/share/vm/memory/generation.cpp
index d52f325..3c45a91 100644
--- a/src/share/vm/memory/generation.cpp
+++ b/src/share/vm/memory/generation.cpp
@@ -187,7 +187,7 @@
   bool   res = (available >= max_promotion_in_bytes);
   if (PrintGC && Verbose) {
     gclog_or_tty->print_cr(
-      "Generation: promo attempt is%s safe: available("SIZE_FORMAT") %s max_promo("SIZE_FORMAT")",
+      "Generation: promo attempt is%s safe: available(" SIZE_FORMAT ") %s max_promo(" SIZE_FORMAT ")",
       res? "":" not", available, res? ">=":"<",
       max_promotion_in_bytes);
   }
diff --git a/src/share/vm/memory/guardedMemory.cpp b/src/share/vm/memory/guardedMemory.cpp
index 763548f..f92c27f 100644
--- a/src/share/vm/memory/guardedMemory.cpp
+++ b/src/share/vm/memory/guardedMemory.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -84,6 +84,8 @@
 
 #ifndef PRODUCT
 
+#define GEN_PURPOSE_TAG ((void *) ((uintptr_t)0xf000f000))
+
 static void guarded_memory_test_check(void* p, size_t sz, void* tag) {
   assert(p != NULL, "NULL pointer given to check");
   u_char* c = (u_char*) p;
@@ -100,12 +102,12 @@
   assert(total_sz > 1 && total_sz >= (sizeof(GuardHeader) + 1 + sizeof(Guard)), "Unexpected size");
   u_char* basep = (u_char*) os::malloc(total_sz, mtInternal);
 
-  GuardedMemory guarded(basep, 1, (void*)0xf000f000);
+  GuardedMemory guarded(basep, 1, GEN_PURPOSE_TAG);
 
   assert(*basep == badResourceValue, "Expected guard in the form of badResourceValue");
   u_char* userp = guarded.get_user_ptr();
   assert(*userp == uninitBlockPad, "Expected uninitialized data in the form of uninitBlockPad");
-  guarded_memory_test_check(userp, 1, (void*)0xf000f000);
+  guarded_memory_test_check(userp, 1, GEN_PURPOSE_TAG);
 
   void* freep = guarded.release_for_freeing();
   assert((u_char*)freep == basep, "Expected the same pointer guard was ");
diff --git a/src/share/vm/memory/metaspace.cpp b/src/share/vm/memory/metaspace.cpp
index be68021..64f1abd 100644
--- a/src/share/vm/memory/metaspace.cpp
+++ b/src/share/vm/memory/metaspace.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -154,7 +154,7 @@
 
   // Map a size to a list index assuming that there are lists
   // for special, small, medium, and humongous chunks.
-  static ChunkIndex list_index(size_t size);
+  ChunkIndex list_index(size_t size);
 
   // Remove the chunk from its freelist.  It is
   // expected to be on one of the _free_chunks[] lists.
@@ -531,9 +531,8 @@
 
   size_t free_bytes();
 
-  Metachunk* get_new_chunk(size_t word_size,
-                           size_t grow_chunks_by_words,
-                           size_t medium_chunk_bunch);
+  Metachunk* get_new_chunk(size_t chunk_word_size,
+                           size_t suggested_commit_granularity);
 
   bool expand_node_by(VirtualSpaceNode* node,
                       size_t min_words,
@@ -687,19 +686,27 @@
     MediumChunkMultiple = 4
   };
 
-  bool is_class() { return _mdtype == Metaspace::ClassType; }
+  static size_t specialized_chunk_size(bool is_class) { return is_class ? ClassSpecializedChunk : SpecializedChunk; }
+  static size_t small_chunk_size(bool is_class)       { return is_class ? ClassSmallChunk : SmallChunk; }
+  static size_t medium_chunk_size(bool is_class)      { return is_class ? ClassMediumChunk : MediumChunk; }
+
+  static size_t smallest_chunk_size(bool is_class)    { return specialized_chunk_size(is_class); }
 
   // Accessors
-  size_t specialized_chunk_size() { return (size_t) is_class() ? ClassSpecializedChunk : SpecializedChunk; }
-  size_t small_chunk_size()       { return (size_t) is_class() ? ClassSmallChunk : SmallChunk; }
-  size_t medium_chunk_size()      { return (size_t) is_class() ? ClassMediumChunk : MediumChunk; }
-  size_t medium_chunk_bunch()     { return medium_chunk_size() * MediumChunkMultiple; }
+  bool is_class() const { return _mdtype == Metaspace::ClassType; }
 
-  size_t smallest_chunk_size()  { return specialized_chunk_size(); }
+  size_t specialized_chunk_size() const { return specialized_chunk_size(is_class()); }
+  size_t small_chunk_size()       const { return small_chunk_size(is_class()); }
+  size_t medium_chunk_size()      const { return medium_chunk_size(is_class()); }
+
+  size_t smallest_chunk_size()    const { return smallest_chunk_size(is_class()); }
+
+  size_t medium_chunk_bunch()     const { return medium_chunk_size() * MediumChunkMultiple; }
 
   size_t allocated_blocks_words() const { return _allocated_blocks_words; }
   size_t allocated_blocks_bytes() const { return _allocated_blocks_words * BytesPerWord; }
   size_t allocated_chunks_words() const { return _allocated_chunks_words; }
+  size_t allocated_chunks_bytes() const { return _allocated_chunks_words * BytesPerWord; }
   size_t allocated_chunks_count() const { return _allocated_chunks_count; }
 
   bool is_humongous(size_t word_size) { return word_size > medium_chunk_size(); }
@@ -718,10 +725,13 @@
   // decremented for all the Metachunks in-use by this SpaceManager.
   void dec_total_from_size_metrics();
 
-  // Set the sizes for the initial chunks.
-  void get_initial_chunk_sizes(Metaspace::MetaspaceType type,
-                               size_t* chunk_word_size,
-                               size_t* class_chunk_word_size);
+  // Adjust the initial chunk size to match one of the fixed chunk list sizes,
+  // or return the unadjusted size if the requested size is humongous.
+  static size_t adjust_initial_chunk_size(size_t requested, bool is_class_space);
+  size_t adjust_initial_chunk_size(size_t requested) const;
+
+  // Get the initial chunks size for this metaspace type.
+  size_t get_initial_chunk_size(Metaspace::MetaspaceType type) const;
 
   size_t sum_capacity_in_chunks_in_use() const;
   size_t sum_used_in_chunks_in_use() const;
@@ -732,7 +742,7 @@
   size_t sum_count_in_chunks_in_use();
   size_t sum_count_in_chunks_in_use(ChunkIndex i);
 
-  Metachunk* get_new_chunk(size_t word_size, size_t grow_chunks_by_words);
+  Metachunk* get_new_chunk(size_t chunk_word_size);
 
   // Block allocation and deallocation.
   // Allocates a block from the current chunk
@@ -1200,7 +1210,7 @@
 }
 
 size_t VirtualSpaceList::free_bytes() {
-  return virtual_space_list()->free_words_in_vs() * BytesPerWord;
+  return current_virtual_space()->free_words_in_vs() * BytesPerWord;
 }
 
 // Allocate another meta virtual space and add it to the list.
@@ -1319,12 +1329,10 @@
   return false;
 }
 
-Metachunk* VirtualSpaceList::get_new_chunk(size_t word_size,
-                                           size_t grow_chunks_by_words,
-                                           size_t medium_chunk_bunch) {
+Metachunk* VirtualSpaceList::get_new_chunk(size_t chunk_word_size, size_t suggested_commit_granularity) {
 
   // Allocate a chunk out of the current virtual space.
-  Metachunk* next = current_virtual_space()->get_chunk_vs(grow_chunks_by_words);
+  Metachunk* next = current_virtual_space()->get_chunk_vs(chunk_word_size);
 
   if (next != NULL) {
     return next;
@@ -1333,8 +1341,8 @@
   // The expand amount is currently only determined by the requested sizes
   // and not how much committed memory is left in the current virtual space.
 
-  size_t min_word_size       = align_size_up(grow_chunks_by_words, Metaspace::commit_alignment_words());
-  size_t preferred_word_size = align_size_up(medium_chunk_bunch,   Metaspace::commit_alignment_words());
+  size_t min_word_size       = align_size_up(chunk_word_size,              Metaspace::commit_alignment_words());
+  size_t preferred_word_size = align_size_up(suggested_commit_granularity, Metaspace::commit_alignment_words());
   if (min_word_size >= preferred_word_size) {
     // Can happen when humongous chunks are allocated.
     preferred_word_size = min_word_size;
@@ -1342,7 +1350,7 @@
 
   bool expanded = expand_by(min_word_size, preferred_word_size);
   if (expanded) {
-    next = current_virtual_space()->get_chunk_vs(grow_chunks_by_words);
+    next = current_virtual_space()->get_chunk_vs(chunk_word_size);
     assert(next != NULL, "The allocation was expected to succeed after the expansion");
   }
 
@@ -1744,7 +1752,11 @@
   st->print_cr("Sum free chunk total " SIZE_FORMAT "  count " SIZE_FORMAT,
                 sum_free_chunks(), sum_free_chunks_count());
 }
+
 ChunkList* ChunkManager::free_chunks(ChunkIndex index) {
+  assert(index == SpecializedIndex || index == SmallIndex || index == MediumIndex,
+         err_msg("Bad index: %d", (int)index));
+
   return &_free_chunks[index];
 }
 
@@ -1856,7 +1868,7 @@
   }
 
   assert((word_size <= chunk->word_size()) ||
-         list_index(chunk->word_size() == HumongousIndex),
+         (list_index(chunk->word_size()) == HumongousIndex),
          "Non-humongous variable sized chunk");
   if (TraceMetadataChunkAllocation) {
     size_t list_count;
@@ -1883,36 +1895,58 @@
 
 // SpaceManager methods
 
-void SpaceManager::get_initial_chunk_sizes(Metaspace::MetaspaceType type,
-                                           size_t* chunk_word_size,
-                                           size_t* class_chunk_word_size) {
-  switch (type) {
-  case Metaspace::BootMetaspaceType:
-    *chunk_word_size = Metaspace::first_chunk_word_size();
-    *class_chunk_word_size = Metaspace::first_class_chunk_word_size();
-    break;
-  case Metaspace::ROMetaspaceType:
-    *chunk_word_size = SharedReadOnlySize / wordSize;
-    *class_chunk_word_size = ClassSpecializedChunk;
-    break;
-  case Metaspace::ReadWriteMetaspaceType:
-    *chunk_word_size = SharedReadWriteSize / wordSize;
-    *class_chunk_word_size = ClassSpecializedChunk;
-    break;
-  case Metaspace::AnonymousMetaspaceType:
-  case Metaspace::ReflectionMetaspaceType:
-    *chunk_word_size = SpecializedChunk;
-    *class_chunk_word_size = ClassSpecializedChunk;
-    break;
-  default:
-    *chunk_word_size = SmallChunk;
-    *class_chunk_word_size = ClassSmallChunk;
-    break;
+size_t SpaceManager::adjust_initial_chunk_size(size_t requested, bool is_class_space) {
+  size_t chunk_sizes[] = {
+      specialized_chunk_size(is_class_space),
+      small_chunk_size(is_class_space),
+      medium_chunk_size(is_class_space)
+  };
+
+  // Adjust up to one of the fixed chunk sizes ...
+  for (size_t i = 0; i < ARRAY_SIZE(chunk_sizes); i++) {
+    if (requested <= chunk_sizes[i]) {
+      return chunk_sizes[i];
+    }
   }
-  assert(*chunk_word_size != 0 && *class_chunk_word_size != 0,
-    err_msg("Initial chunks sizes bad: data  " SIZE_FORMAT
-            " class " SIZE_FORMAT,
-            *chunk_word_size, *class_chunk_word_size));
+
+  // ... or return the size as a humongous chunk.
+  return requested;
+}
+
+size_t SpaceManager::adjust_initial_chunk_size(size_t requested) const {
+  return adjust_initial_chunk_size(requested, is_class());
+}
+
+size_t SpaceManager::get_initial_chunk_size(Metaspace::MetaspaceType type) const {
+  size_t requested;
+
+  if (is_class()) {
+    switch (type) {
+    case Metaspace::BootMetaspaceType:       requested = Metaspace::first_class_chunk_word_size(); break;
+    case Metaspace::ROMetaspaceType:         requested = ClassSpecializedChunk; break;
+    case Metaspace::ReadWriteMetaspaceType:  requested = ClassSpecializedChunk; break;
+    case Metaspace::AnonymousMetaspaceType:  requested = ClassSpecializedChunk; break;
+    case Metaspace::ReflectionMetaspaceType: requested = ClassSpecializedChunk; break;
+    default:                                 requested = ClassSmallChunk; break;
+    }
+  } else {
+    switch (type) {
+    case Metaspace::BootMetaspaceType:       requested = Metaspace::first_chunk_word_size(); break;
+    case Metaspace::ROMetaspaceType:         requested = SharedReadOnlySize / wordSize; break;
+    case Metaspace::ReadWriteMetaspaceType:  requested = SharedReadWriteSize / wordSize; break;
+    case Metaspace::AnonymousMetaspaceType:  requested = SpecializedChunk; break;
+    case Metaspace::ReflectionMetaspaceType: requested = SpecializedChunk; break;
+    default:                                 requested = SmallChunk; break;
+    }
+  }
+
+  // Adjust to one of the fixed chunk sizes (unless humongous)
+  const size_t adjusted = adjust_initial_chunk_size(requested);
+
+  assert(adjusted != 0, err_msg("Incorrect initial chunk size. Requested: "
+         SIZE_FORMAT " adjusted: " SIZE_FORMAT, requested, adjusted));
+
+  return adjusted;
 }
 
 size_t SpaceManager::sum_free_in_chunks_in_use() const {
@@ -2102,8 +2136,8 @@
   }
 
   // Get another chunk out of the virtual space
-  size_t grow_chunks_by_words = calc_chunk_size(word_size);
-  Metachunk* next = get_new_chunk(word_size, grow_chunks_by_words);
+  size_t chunk_word_size = calc_chunk_size(word_size);
+  Metachunk* next = get_new_chunk(chunk_word_size);
 
   MetaWord* mem = NULL;
 
@@ -2328,22 +2362,18 @@
 }
 
 ChunkIndex ChunkManager::list_index(size_t size) {
-  switch (size) {
-    case SpecializedChunk:
-      assert(SpecializedChunk == ClassSpecializedChunk,
-             "Need branch for ClassSpecializedChunk");
-      return SpecializedIndex;
-    case SmallChunk:
-    case ClassSmallChunk:
-      return SmallIndex;
-    case MediumChunk:
-    case ClassMediumChunk:
-      return MediumIndex;
-    default:
-      assert(size > MediumChunk || size > ClassMediumChunk,
-             "Not a humongous chunk");
-      return HumongousIndex;
+  if (free_chunks(SpecializedIndex)->size() == size) {
+    return SpecializedIndex;
   }
+  if (free_chunks(SmallIndex)->size() == size) {
+    return SmallIndex;
+  }
+  if (free_chunks(MediumIndex)->size() == size) {
+    return MediumIndex;
+  }
+
+  assert(size > free_chunks(MediumIndex)->size(), "Not a humongous chunk");
+  return HumongousIndex;
 }
 
 void SpaceManager::deallocate(MetaWord* p, size_t word_size) {
@@ -2365,7 +2395,7 @@
 
   // Find the correct list and and set the current
   // chunk for that list.
-  ChunkIndex index = ChunkManager::list_index(new_chunk->word_size());
+  ChunkIndex index = chunk_manager()->list_index(new_chunk->word_size());
 
   if (index != HumongousIndex) {
     retire_current_chunk();
@@ -2412,14 +2442,12 @@
   }
 }
 
-Metachunk* SpaceManager::get_new_chunk(size_t word_size,
-                                       size_t grow_chunks_by_words) {
+Metachunk* SpaceManager::get_new_chunk(size_t chunk_word_size) {
   // Get a chunk from the chunk freelist
-  Metachunk* next = chunk_manager()->chunk_freelist_allocate(grow_chunks_by_words);
+  Metachunk* next = chunk_manager()->chunk_freelist_allocate(chunk_word_size);
 
   if (next == NULL) {
-    next = vs_list()->get_new_chunk(word_size,
-                                    grow_chunks_by_words,
+    next = vs_list()->get_new_chunk(chunk_word_size,
                                     medium_chunk_bunch());
   }
 
@@ -3070,13 +3098,24 @@
   initialize_class_space(metaspace_rs);
 
   if (PrintCompressedOopsMode || (PrintMiscellaneous && Verbose)) {
-    gclog_or_tty->print_cr("Narrow klass base: " PTR_FORMAT ", Narrow klass shift: " SIZE_FORMAT,
-                            Universe::narrow_klass_base(), Universe::narrow_klass_shift());
-    gclog_or_tty->print_cr("Compressed class space size: " SIZE_FORMAT " Address: " PTR_FORMAT " Req Addr: " PTR_FORMAT,
-                           compressed_class_space_size(), metaspace_rs.base(), requested_addr);
+      print_compressed_class_space(gclog_or_tty, requested_addr);
   }
 }
 
+void Metaspace::print_compressed_class_space(outputStream* st, const char* requested_addr) {
+  st->print_cr("Narrow klass base: " PTR_FORMAT ", Narrow klass shift: %d",
+               p2i(Universe::narrow_klass_base()), Universe::narrow_klass_shift());
+  if (_class_space_list != NULL) {
+    address base = (address)_class_space_list->current_virtual_space()->bottom();
+    st->print("Compressed class space size: " SIZE_FORMAT " Address: " PTR_FORMAT,
+                 compressed_class_space_size(), p2i(base));
+    if (requested_addr != 0) {
+      st->print(" Req Addr: " PTR_FORMAT, p2i(requested_addr));
+    }
+    st->cr();
+   }
+ }
+
 // For UseCompressedClassPointers the class space is reserved above the top of
 // the Java heap.  The argument passed in is at the base of the compressed space.
 void Metaspace::initialize_class_space(ReservedSpace rs) {
@@ -3085,7 +3124,7 @@
          err_msg(SIZE_FORMAT " != " UINTX_FORMAT, rs.size(), CompressedClassSpaceSize));
   assert(using_class_space(), "Must be using class space");
   _class_space_list = new VirtualSpaceList(rs);
-  _chunk_manager_class = new ChunkManager(SpecializedChunk, ClassSmallChunk, ClassMediumChunk);
+  _chunk_manager_class = new ChunkManager(ClassSpecializedChunk, ClassSmallChunk, ClassMediumChunk);
 
   if (!_class_space_list->initialization_succeeded()) {
     vm_exit_during_initialization("Failed to setup compressed class space virtual space list.");
@@ -3135,6 +3174,24 @@
 
   CompressedClassSpaceSize = align_size_down_bounded(CompressedClassSpaceSize, _reserve_alignment);
   set_compressed_class_space_size(CompressedClassSpaceSize);
+
+  // Initial virtual space size will be calculated at global_initialize()
+  uintx min_metaspace_sz =
+      VIRTUALSPACEMULTIPLIER * InitialBootClassLoaderMetaspaceSize;
+  if (UseCompressedClassPointers) {
+    if ((min_metaspace_sz + CompressedClassSpaceSize) >  MaxMetaspaceSize) {
+      if (min_metaspace_sz >= MaxMetaspaceSize) {
+        vm_exit_during_initialization("MaxMetaspaceSize is too small.");
+      } else {
+        FLAG_SET_ERGO(uintx, CompressedClassSpaceSize,
+                      MaxMetaspaceSize - min_metaspace_sz);
+      }
+    }
+  } else if (min_metaspace_sz >= MaxMetaspaceSize) {
+    FLAG_SET_ERGO(uintx, InitialBootClassLoaderMetaspaceSize,
+                  min_metaspace_sz);
+  }
+
 }
 
 void Metaspace::global_initialize() {
@@ -3268,66 +3325,62 @@
   MetaspaceGC::post_initialize();
 }
 
-Metachunk* Metaspace::get_initialization_chunk(MetadataType mdtype,
-                                               size_t chunk_word_size,
-                                               size_t chunk_bunch) {
+void Metaspace::initialize_first_chunk(MetaspaceType type, MetadataType mdtype) {
+  Metachunk* chunk = get_initialization_chunk(type, mdtype);
+  if (chunk != NULL) {
+    // Add to this manager's list of chunks in use and current_chunk().
+    get_space_manager(mdtype)->add_chunk(chunk, true);
+  }
+}
+
+Metachunk* Metaspace::get_initialization_chunk(MetaspaceType type, MetadataType mdtype) {
+  size_t chunk_word_size = get_space_manager(mdtype)->get_initial_chunk_size(type);
+
   // Get a chunk from the chunk freelist
   Metachunk* chunk = get_chunk_manager(mdtype)->chunk_freelist_allocate(chunk_word_size);
-  if (chunk != NULL) {
-    return chunk;
+
+  if (chunk == NULL) {
+    chunk = get_space_list(mdtype)->get_new_chunk(chunk_word_size,
+                                                  get_space_manager(mdtype)->medium_chunk_bunch());
   }
 
-  return get_space_list(mdtype)->get_new_chunk(chunk_word_size, chunk_word_size, chunk_bunch);
+  // For dumping shared archive, report error if allocation has failed.
+  if (DumpSharedSpaces && chunk == NULL) {
+    report_insufficient_metaspace(MetaspaceAux::committed_bytes() + chunk_word_size * BytesPerWord);
+  }
+
+  return chunk;
+}
+
+void Metaspace::verify_global_initialization() {
+  assert(space_list() != NULL, "Metadata VirtualSpaceList has not been initialized");
+  assert(chunk_manager_metadata() != NULL, "Metadata ChunkManager has not been initialized");
+
+  if (using_class_space()) {
+    assert(class_space_list() != NULL, "Class VirtualSpaceList has not been initialized");
+    assert(chunk_manager_class() != NULL, "Class ChunkManager has not been initialized");
+  }
 }
 
 void Metaspace::initialize(Mutex* lock, MetaspaceType type) {
+  verify_global_initialization();
 
-  assert(space_list() != NULL,
-    "Metadata VirtualSpaceList has not been initialized");
-  assert(chunk_manager_metadata() != NULL,
-    "Metadata ChunkManager has not been initialized");
-
+  // Allocate SpaceManager for metadata objects.
   _vsm = new SpaceManager(NonClassType, lock);
-  if (_vsm == NULL) {
-    return;
-  }
-  size_t word_size;
-  size_t class_word_size;
-  vsm()->get_initial_chunk_sizes(type, &word_size, &class_word_size);
 
   if (using_class_space()) {
-  assert(class_space_list() != NULL,
-    "Class VirtualSpaceList has not been initialized");
-  assert(chunk_manager_class() != NULL,
-    "Class ChunkManager has not been initialized");
-
     // Allocate SpaceManager for classes.
     _class_vsm = new SpaceManager(ClassType, lock);
-    if (_class_vsm == NULL) {
-      return;
-    }
   }
 
   MutexLockerEx cl(SpaceManager::expand_lock(), Mutex::_no_safepoint_check_flag);
 
   // Allocate chunk for metadata objects
-  Metachunk* new_chunk = get_initialization_chunk(NonClassType,
-                                                  word_size,
-                                                  vsm()->medium_chunk_bunch());
-  assert(!DumpSharedSpaces || new_chunk != NULL, "should have enough space for both chunks");
-  if (new_chunk != NULL) {
-    // Add to this manager's list of chunks in use and current_chunk().
-    vsm()->add_chunk(new_chunk, true);
-  }
+  initialize_first_chunk(type, NonClassType);
 
   // Allocate chunk for class metadata objects
   if (using_class_space()) {
-    Metachunk* class_chunk = get_initialization_chunk(ClassType,
-                                                      class_word_size,
-                                                      class_vsm()->medium_chunk_bunch());
-    if (class_chunk != NULL) {
-      class_vsm()->add_chunk(class_chunk, true);
-    }
+    initialize_first_chunk(type, ClassType);
   }
 
   _alloc_record_head = NULL;
@@ -3422,6 +3475,16 @@
   return capacity_words_slow(mdtype) * BytesPerWord;
 }
 
+size_t Metaspace::allocated_blocks_bytes() const {
+  return vsm()->allocated_blocks_bytes() +
+      (using_class_space() ? class_vsm()->allocated_blocks_bytes() : 0);
+}
+
+size_t Metaspace::allocated_chunks_bytes() const {
+  return vsm()->allocated_chunks_bytes() +
+      (using_class_space() ? class_vsm()->allocated_chunks_bytes() : 0);
+}
+
 void Metaspace::deallocate(MetaWord* ptr, size_t word_size, bool is_class) {
   if (SafepointSynchronize::is_at_safepoint()) {
     if (DumpSharedSpaces && PrintSharedSpaces) {
@@ -3754,7 +3817,7 @@
     // vm_allocation_granularity aligned on Windows.
     size_t large_size = (size_t)(2*256*K + (os::vm_page_size()/BytesPerWord));
     large_size += (os::vm_page_size()/BytesPerWord);
-    vs_list->get_new_chunk(large_size, large_size, 0);
+    vs_list->get_new_chunk(large_size, 0);
   }
 
   static void test() {
@@ -3929,4 +3992,90 @@
   TestVirtualSpaceNodeTest::test();
   TestVirtualSpaceNodeTest::test_is_available();
 }
+
+// The following test is placed here instead of a gtest / unittest file
+// because the ChunkManager class is only available in this file.
+class SpaceManagerTest : AllStatic {
+  friend void SpaceManager_test_adjust_initial_chunk_size();
+
+  static void test_adjust_initial_chunk_size(bool is_class) {
+    const size_t smallest = SpaceManager::smallest_chunk_size(is_class);
+    const size_t normal   = SpaceManager::small_chunk_size(is_class);
+    const size_t medium   = SpaceManager::medium_chunk_size(is_class);
+
+#define test_adjust_initial_chunk_size(value, expected, is_class_value)          \
+    do {                                                                         \
+      size_t v = value;                                                          \
+      size_t e = expected;                                                       \
+      assert(SpaceManager::adjust_initial_chunk_size(v, (is_class_value)) == e,  \
+             err_msg("Expected: " SIZE_FORMAT " got: " SIZE_FORMAT, e, v));      \
+    } while (0)
+
+    // Smallest (specialized)
+    test_adjust_initial_chunk_size(1,            smallest, is_class);
+    test_adjust_initial_chunk_size(smallest - 1, smallest, is_class);
+    test_adjust_initial_chunk_size(smallest,     smallest, is_class);
+
+    // Small
+    test_adjust_initial_chunk_size(smallest + 1, normal, is_class);
+    test_adjust_initial_chunk_size(normal - 1,   normal, is_class);
+    test_adjust_initial_chunk_size(normal,       normal, is_class);
+
+    // Medium
+    test_adjust_initial_chunk_size(normal + 1, medium, is_class);
+    test_adjust_initial_chunk_size(medium - 1, medium, is_class);
+    test_adjust_initial_chunk_size(medium,     medium, is_class);
+
+    // Humongous
+    test_adjust_initial_chunk_size(medium + 1, medium + 1, is_class);
+
+#undef test_adjust_initial_chunk_size
+  }
+
+  static void test_adjust_initial_chunk_size() {
+    test_adjust_initial_chunk_size(false);
+    test_adjust_initial_chunk_size(true);
+  }
+};
+
+void SpaceManager_test_adjust_initial_chunk_size() {
+  SpaceManagerTest::test_adjust_initial_chunk_size();
+}
+
+// The following test is placed here instead of a gtest / unittest file
+// because the ChunkManager class is only available in this file.
+void ChunkManager_test_list_index() {
+  ChunkManager manager(ClassSpecializedChunk, ClassSmallChunk, ClassMediumChunk);
+
+  // Test previous bug where a query for a humongous class metachunk,
+  // incorrectly matched the non-class medium metachunk size.
+  {
+    assert(MediumChunk > ClassMediumChunk, "Precondition for test");
+
+    ChunkIndex index = manager.list_index(MediumChunk);
+
+    assert(index == HumongousIndex,
+           err_msg("Requested size is larger than ClassMediumChunk,"
+           " so should return HumongousIndex. Got index: %d", (int)index));
+  }
+
+  // Check the specified sizes as well.
+  {
+    ChunkIndex index = manager.list_index(ClassSpecializedChunk);
+    assert(index == SpecializedIndex, err_msg("Wrong index returned. Got index: %d", (int)index));
+  }
+  {
+    ChunkIndex index = manager.list_index(ClassSmallChunk);
+    assert(index == SmallIndex, err_msg("Wrong index returned. Got index: %d", (int)index));
+  }
+  {
+    ChunkIndex index = manager.list_index(ClassMediumChunk);
+    assert(index == MediumIndex, err_msg("Wrong index returned. Got index: %d", (int)index));
+  }
+  {
+    ChunkIndex index = manager.list_index(ClassMediumChunk + 1);
+    assert(index == HumongousIndex, err_msg("Wrong index returned. Got index: %d", (int)index));
+  }
+}
+
 #endif
diff --git a/src/share/vm/memory/metaspace.hpp b/src/share/vm/memory/metaspace.hpp
index 2026420..e1979ff 100644
--- a/src/share/vm/memory/metaspace.hpp
+++ b/src/share/vm/memory/metaspace.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -104,14 +104,15 @@
   };
 
  private:
+  static void verify_global_initialization();
+
   void initialize(Mutex* lock, MetaspaceType type);
 
-  // Get the first chunk for a Metaspace.  Used for
+  // Initialize the first chunk for a Metaspace.  Used for
   // special cases such as the boot class loader, reflection
   // class loader and anonymous class loader.
-  Metachunk* get_initialization_chunk(MetadataType mdtype,
-                                      size_t chunk_word_size,
-                                      size_t chunk_bunch);
+  void initialize_first_chunk(MetaspaceType type, MetadataType mdtype);
+  Metachunk* get_initialization_chunk(MetaspaceType type, MetadataType mdtype);
 
   // Align up the word size to the allocation word size
   static size_t align_word_size_up(size_t);
@@ -138,6 +139,10 @@
 
   SpaceManager* _class_vsm;
   SpaceManager* class_vsm() const { return _class_vsm; }
+  SpaceManager* get_space_manager(MetadataType mdtype) {
+    assert(mdtype != MetadataTypeCount, "MetadaTypeCount can't be used as mdtype");
+    return mdtype == ClassType ? class_vsm() : vsm();
+  }
 
   // Allocate space for metadata of type mdtype. This is space
   // within a Metachunk and is used by
@@ -227,6 +232,9 @@
   size_t used_bytes_slow(MetadataType mdtype) const;
   size_t capacity_bytes_slow(MetadataType mdtype) const;
 
+  size_t allocated_blocks_bytes() const;
+  size_t allocated_chunks_bytes() const;
+
   static MetaWord* allocate(ClassLoaderData* loader_data, size_t word_size,
                             bool read_only, MetaspaceObj::Type type, TRAPS);
   void deallocate(MetaWord* ptr, size_t byte_size, bool is_class);
@@ -251,6 +259,8 @@
   // Debugging support
   void verify();
 
+  static void print_compressed_class_space(outputStream* st, const char* requested_addr = 0) NOT_LP64({});
+
   class AllocRecordClosure :  public StackObj {
   public:
     virtual void doit(address ptr, MetaspaceObj::Type type, int byte_size) = 0;
diff --git a/src/share/vm/memory/oopFactory.hpp b/src/share/vm/memory/oopFactory.hpp
index 1d14010..0eb590e 100644
--- a/src/share/vm/memory/oopFactory.hpp
+++ b/src/share/vm/memory/oopFactory.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -41,20 +41,20 @@
 class oopFactory: AllStatic {
  public:
   // Basic type leaf array allocation
-  static typeArrayOop    new_boolArray  (int length, TRAPS) { return TypeArrayKlass::cast(Universe::boolArrayKlassObj  ())->allocate(length, CHECK_NULL); }
-  static typeArrayOop    new_charArray  (int length, TRAPS) { return TypeArrayKlass::cast(Universe::charArrayKlassObj  ())->allocate(length, CHECK_NULL); }
-  static typeArrayOop    new_singleArray(int length, TRAPS) { return TypeArrayKlass::cast(Universe::singleArrayKlassObj())->allocate(length, CHECK_NULL); }
-  static typeArrayOop    new_doubleArray(int length, TRAPS) { return TypeArrayKlass::cast(Universe::doubleArrayKlassObj())->allocate(length, CHECK_NULL); }
-  static typeArrayOop    new_byteArray  (int length, TRAPS) { return TypeArrayKlass::cast(Universe::byteArrayKlassObj  ())->allocate(length, CHECK_NULL); }
-  static typeArrayOop    new_shortArray (int length, TRAPS) { return TypeArrayKlass::cast(Universe::shortArrayKlassObj ())->allocate(length, CHECK_NULL); }
-  static typeArrayOop    new_intArray   (int length, TRAPS) { return TypeArrayKlass::cast(Universe::intArrayKlassObj   ())->allocate(length, CHECK_NULL); }
-  static typeArrayOop    new_longArray  (int length, TRAPS) { return TypeArrayKlass::cast(Universe::longArrayKlassObj  ())->allocate(length, CHECK_NULL); }
+  static typeArrayOop    new_boolArray  (int length, TRAPS) { return TypeArrayKlass::cast(Universe::boolArrayKlassObj  ())->allocate(length, THREAD); }
+  static typeArrayOop    new_charArray  (int length, TRAPS) { return TypeArrayKlass::cast(Universe::charArrayKlassObj  ())->allocate(length, THREAD); }
+  static typeArrayOop    new_singleArray(int length, TRAPS) { return TypeArrayKlass::cast(Universe::singleArrayKlassObj())->allocate(length, THREAD); }
+  static typeArrayOop    new_doubleArray(int length, TRAPS) { return TypeArrayKlass::cast(Universe::doubleArrayKlassObj())->allocate(length, THREAD); }
+  static typeArrayOop    new_byteArray  (int length, TRAPS) { return TypeArrayKlass::cast(Universe::byteArrayKlassObj  ())->allocate(length, THREAD); }
+  static typeArrayOop    new_shortArray (int length, TRAPS) { return TypeArrayKlass::cast(Universe::shortArrayKlassObj ())->allocate(length, THREAD); }
+  static typeArrayOop    new_intArray   (int length, TRAPS) { return TypeArrayKlass::cast(Universe::intArrayKlassObj   ())->allocate(length, THREAD); }
+  static typeArrayOop    new_longArray  (int length, TRAPS) { return TypeArrayKlass::cast(Universe::longArrayKlassObj  ())->allocate(length, THREAD); }
 
   // create java.lang.Object[]
   static objArrayOop     new_objectArray(int length, TRAPS)  {
     assert(Universe::objectArrayKlassObj() != NULL, "Too early?");
     return ObjArrayKlass::
-      cast(Universe::objectArrayKlassObj())->allocate(length, CHECK_NULL);
+      cast(Universe::objectArrayKlassObj())->allocate(length, THREAD);
   }
 
   static typeArrayOop    new_charArray           (const char* utf8_str,  TRAPS);
diff --git a/src/share/vm/memory/resourceArea.cpp b/src/share/vm/memory/resourceArea.cpp
index 767e45e..3995e63 100644
--- a/src/share/vm/memory/resourceArea.cpp
+++ b/src/share/vm/memory/resourceArea.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,15 @@
 #include "memory/resourceArea.hpp"
 #include "runtime/mutexLocker.hpp"
 #include "runtime/thread.inline.hpp"
+#include "services/memTracker.hpp"
+
+void ResourceArea::bias_to(MEMFLAGS new_flags) {
+  if (new_flags != _flags) {
+    MemTracker::record_arena_free(_flags);
+    MemTracker::record_new_arena(new_flags);
+    _flags = new_flags;
+  }
+}
 
 //------------------------------ResourceMark-----------------------------------
 debug_only(int ResourceArea::_warned;)      // to suppress multiple warnings
diff --git a/src/share/vm/memory/resourceArea.hpp b/src/share/vm/memory/resourceArea.hpp
index 567b5fc..7ffe641 100644
--- a/src/share/vm/memory/resourceArea.hpp
+++ b/src/share/vm/memory/resourceArea.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -49,11 +49,11 @@
   debug_only(static int _warned;)       // to suppress multiple warnings
 
 public:
-  ResourceArea() : Arena(mtThread) {
+  ResourceArea(MEMFLAGS flags = mtThread) : Arena(flags) {
     debug_only(_nesting = 0;)
   }
 
-  ResourceArea(size_t init_size) : Arena(mtThread, init_size) {
+  ResourceArea(size_t init_size, MEMFLAGS flags = mtThread) : Arena(flags, init_size) {
     debug_only(_nesting = 0;);
   }
 
@@ -70,7 +70,11 @@
     return (char*)Amalloc(size, alloc_failmode);
   }
 
-  debug_only(int nesting() const { return _nesting; });
+  // Bias this resource area to specific memory type
+  // (by default, ResourceArea is tagged as mtThread, per-thread general purpose storage)
+  void bias_to(MEMFLAGS flags);
+
+  debug_only(int nesting() const { return _nesting; })
 };
 
 
diff --git a/src/share/vm/memory/tenuredGeneration.cpp b/src/share/vm/memory/tenuredGeneration.cpp
index d7432ba..cdc51ee 100644
--- a/src/share/vm/memory/tenuredGeneration.cpp
+++ b/src/share/vm/memory/tenuredGeneration.cpp
@@ -294,8 +294,8 @@
   bool   res = (available >= av_promo) || (available >= max_promotion_in_bytes);
   if (PrintGC && Verbose) {
     gclog_or_tty->print_cr(
-      "Tenured: promo attempt is%s safe: available("SIZE_FORMAT") %s av_promo("SIZE_FORMAT"),"
-      "max_promo("SIZE_FORMAT")",
+      "Tenured: promo attempt is%s safe: available(" SIZE_FORMAT ") %s av_promo(" SIZE_FORMAT "),"
+      "max_promo(" SIZE_FORMAT ")",
       res? "":" not", available, res? ">=":"<",
       av_promo, max_promotion_in_bytes);
   }
diff --git a/src/share/vm/memory/threadLocalAllocBuffer.cpp b/src/share/vm/memory/threadLocalAllocBuffer.cpp
index 0603343..ecb2ab7 100644
--- a/src/share/vm/memory/threadLocalAllocBuffer.cpp
+++ b/src/share/vm/memory/threadLocalAllocBuffer.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -200,7 +200,7 @@
 
   set_desired_size(initial_desired_size());
 
-  // Following check is needed because at startup the main (primordial)
+  // Following check is needed because at startup the main
   // thread is initialized before the heap is.  The initialization for
   // this thread is redone in startup_initialization below.
   if (Universe::heap() != NULL) {
@@ -223,7 +223,7 @@
 
   _global_stats = new GlobalTLABStats();
 
-  // During jvm startup, the main (primordial) thread is initialized
+  // During jvm startup, the main thread is initialized
   // before the heap is initialized.  So reinitialize it now.
   guarantee(Thread::current()->is_Java_thread(), "tlab initialization thread not Java thread");
   Thread::current()->tlab().initialize();
diff --git a/src/share/vm/memory/threadLocalAllocBuffer.inline.hpp b/src/share/vm/memory/threadLocalAllocBuffer.inline.hpp
index cf3fefb..b19bd93 100644
--- a/src/share/vm/memory/threadLocalAllocBuffer.inline.hpp
+++ b/src/share/vm/memory/threadLocalAllocBuffer.inline.hpp
@@ -94,10 +94,10 @@
 
   if (PrintTLAB && Verbose) {
     Thread* thrd = myThread();
-    gclog_or_tty->print("TLAB: %s thread: "INTPTR_FORMAT" [id: %2d]"
-                        " obj: "SIZE_FORMAT
-                        " free: "SIZE_FORMAT
-                        " waste: "SIZE_FORMAT"\n",
+    gclog_or_tty->print("TLAB: %s thread: " INTPTR_FORMAT " [id: %2d]"
+                        " obj: " SIZE_FORMAT
+                        " free: " SIZE_FORMAT
+                        " waste: " SIZE_FORMAT "\n",
                         "slow", p2i(thrd), thrd->osthread()->thread_id(),
                         obj_size, free(), refill_waste_limit());
   }
diff --git a/src/share/vm/memory/universe.cpp b/src/share/vm/memory/universe.cpp
index 2e1e90f..63a862d 100644
--- a/src/share/vm/memory/universe.cpp
+++ b/src/share/vm/memory/universe.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -882,7 +882,7 @@
     Universe::set_narrow_ptrs_base(Universe::narrow_oop_base());
 
     if (PrintCompressedOopsMode || (PrintMiscellaneous && Verbose)) {
-      Universe::print_compressed_oops_mode();
+      Universe::print_compressed_oops_mode(tty);
     }
   }
   // Universe::narrow_oop_base() is one page below the heap.
@@ -904,29 +904,27 @@
   return JNI_OK;
 }
 
-void Universe::print_compressed_oops_mode() {
-  tty->cr();
-  tty->print("heap address: " PTR_FORMAT ", size: " SIZE_FORMAT " MB",
+void Universe::print_compressed_oops_mode(outputStream* st) {
+  st->print("heap address: " PTR_FORMAT ", size: " SIZE_FORMAT " MB",
               Universe::heap()->base(), Universe::heap()->reserved_region().byte_size()/M);
 
-  tty->print(", Compressed Oops mode: %s", narrow_oop_mode_to_string(narrow_oop_mode()));
+  st->print(", Compressed Oops mode: %s", narrow_oop_mode_to_string(narrow_oop_mode()));
 
   if (Universe::narrow_oop_base() != 0) {
-    tty->print(":" PTR_FORMAT, Universe::narrow_oop_base());
+    st->print(":" PTR_FORMAT, Universe::narrow_oop_base());
   }
 
   if (Universe::narrow_oop_shift() != 0) {
-    tty->print(", Oop shift amount: %d", Universe::narrow_oop_shift());
+    st->print(", Oop shift amount: %d", Universe::narrow_oop_shift());
   }
 
-  tty->cr();
-  tty->cr();
+  st->cr();
 }
 
 // Reserve the Java heap, which is now the same for all GCs.
 ReservedSpace Universe::reserve_heap(size_t heap_size, size_t alignment) {
   assert(alignment <= Arguments::conservative_max_heap_alignment(),
-      err_msg("actual alignment "SIZE_FORMAT" must be within maximum heap alignment "SIZE_FORMAT,
+      err_msg("actual alignment " SIZE_FORMAT " must be within maximum heap alignment " SIZE_FORMAT,
           alignment, Arguments::conservative_max_heap_alignment()));
   size_t total_reserved = align_size_up(heap_size, alignment);
   assert(!UseCompressedOops || (total_reserved <= (OopEncodingHeapMax - os::vm_page_size())),
diff --git a/src/share/vm/memory/universe.hpp b/src/share/vm/memory/universe.hpp
index 3c6a89d..8909c6d 100644
--- a/src/share/vm/memory/universe.hpp
+++ b/src/share/vm/memory/universe.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -375,7 +375,7 @@
   static void     set_narrow_ptrs_base(address a)         { _narrow_ptrs_base = a; }
   static address  narrow_ptrs_base()                      { return _narrow_ptrs_base; }
 
-  static void     print_compressed_oops_mode();
+  static void     print_compressed_oops_mode(outputStream* st);
 
   // this is set in vm_version on sparc (and then reset in universe afaict)
   static void     set_narrow_oop_shift(int shift)         {
diff --git a/src/share/vm/oops/compiledICHolder.cpp b/src/share/vm/oops/compiledICHolder.cpp
index 7226807..568f2fe 100644
--- a/src/share/vm/oops/compiledICHolder.cpp
+++ b/src/share/vm/oops/compiledICHolder.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -24,8 +24,6 @@
 
 #include "precompiled.hpp"
 #include "oops/compiledICHolder.hpp"
-#include "oops/klass.hpp"
-#include "oops/method.hpp"
 #include "oops/oop.inline2.hpp"
 
 volatile int CompiledICHolder::_live_count;
@@ -36,8 +34,8 @@
 
 void CompiledICHolder::print_on(outputStream* st) const {
   st->print("%s", internal_name());
-  st->print(" - method: "); holder_method()->print_value_on(st); st->cr();
-  st->print(" - klass:  "); holder_klass()->print_value_on(st); st->cr();
+  st->print(" - metadata: "); holder_metadata()->print_value_on(st); st->cr();
+  st->print(" - klass:    "); holder_klass()->print_value_on(st); st->cr();
 }
 
 void CompiledICHolder::print_value_on(outputStream* st) const {
@@ -48,6 +46,6 @@
 // Verification
 
 void CompiledICHolder::verify_on(outputStream* st) {
-  guarantee(holder_method()->is_method(), "should be method");
+  guarantee(holder_metadata()->is_method() || holder_metadata()->is_klass(), "should be method or klass");
   guarantee(holder_klass()->is_klass(),   "should be klass");
 }
diff --git a/src/share/vm/oops/compiledICHolder.hpp b/src/share/vm/oops/compiledICHolder.hpp
index d3ca41f..63d3a87 100644
--- a/src/share/vm/oops/compiledICHolder.hpp
+++ b/src/share/vm/oops/compiledICHolder.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,10 +26,13 @@
 #define SHARE_VM_OOPS_COMPILEDICHOLDEROOP_HPP
 
 #include "oops/oop.hpp"
+#include "oops/klass.hpp"
+#include "oops/method.hpp"
 
 // A CompiledICHolder* is a helper object for the inline cache implementation.
-// It holds an intermediate value (method+klass pair) used when converting from
-// compiled to an interpreted call.
+// It holds:
+//   (1) (method+klass pair) when converting from compiled to an interpreted call
+//   (2) (klass+klass pair) when calling itable stub from megamorphic compiled call
 //
 // These are always allocated in the C heap and are freed during a
 // safepoint by the ICBuffer logic.  It's unsafe to free them earlier
@@ -44,14 +47,15 @@
   static volatile int _live_not_claimed_count; // allocated but not yet in use so not
                                                // reachable by iterating over nmethods
 
-  Method* _holder_method;
+  Metadata* _holder_metadata;
   Klass*    _holder_klass;    // to avoid name conflict with oopDesc::_klass
   CompiledICHolder* _next;
+  bool _is_metadata_method;
 
  public:
   // Constructor
-  CompiledICHolder(Method* method, Klass* klass)
-      : _holder_method(method), _holder_klass(klass) {
+  CompiledICHolder(Metadata* metadata, Klass* klass, bool is_method = true)
+      : _holder_metadata(metadata), _holder_klass(klass), _is_metadata_method(is_method) {
 #ifdef ASSERT
     Atomic::inc(&_live_count);
     Atomic::inc(&_live_not_claimed_count);
@@ -69,19 +73,29 @@
   static int live_not_claimed_count() { return _live_not_claimed_count; }
 
   // accessors
-  Method* holder_method() const     { return _holder_method; }
   Klass*    holder_klass()  const     { return _holder_klass; }
+  Metadata* holder_metadata() const   { return _holder_metadata; }
 
-  void set_holder_method(Method* m) { _holder_method = m; }
-  void set_holder_klass(Klass* k)   { _holder_klass = k; }
+  void set_holder_metadata(Metadata* m) { _holder_metadata = m; }
+  void set_holder_klass(Klass* k)     { _holder_klass = k; }
 
-  // interpreter support (offsets in bytes)
-  static int holder_method_offset()   { return offset_of(CompiledICHolder, _holder_method); }
+  static int holder_metadata_offset() { return offset_of(CompiledICHolder, _holder_metadata); }
   static int holder_klass_offset()    { return offset_of(CompiledICHolder, _holder_klass); }
 
   CompiledICHolder* next()     { return _next; }
   void set_next(CompiledICHolder* n) { _next = n; }
 
+  inline bool is_loader_alive(BoolObjectClosure* is_alive) {
+    Klass* k = _is_metadata_method ? ((Method*)_holder_metadata)->method_holder() : (Klass*)_holder_metadata;
+    if (!k->is_loader_alive(is_alive)) {
+      return false;
+    }
+    if (!_holder_klass->is_loader_alive(is_alive)) {
+      return false;
+    }
+    return true;
+  }
+
   // Verify
   void verify_on(outputStream* st);
 
diff --git a/src/share/vm/oops/constantPool.cpp b/src/share/vm/oops/constantPool.cpp
index a9685b2..9ab9e9d 100644
--- a/src/share/vm/oops/constantPool.cpp
+++ b/src/share/vm/oops/constantPool.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -109,6 +109,16 @@
   return (objArrayOop)JNIHandles::resolve(_resolved_references);
 }
 
+// Called from outside constant pool resolution where a resolved_reference array
+// may not be present.
+objArrayOop ConstantPool::resolved_references_or_null() const {
+  if (_cache == NULL) {
+    return NULL;
+  } else {
+    return (objArrayOop)JNIHandles::resolve(_resolved_references);
+  }
+}
+
 // Create resolved_references array and mapping array for original cp indexes
 // The ldc bytecode was rewritten to have the resolved reference array index so need a way
 // to map it back for resolving and some unlikely miscellaneous uses.
@@ -520,7 +530,7 @@
 
 
 Klass* ConstantPool::klass_ref_at(int which, TRAPS) {
-  return klass_at(klass_ref_index_at(which), CHECK_NULL);
+  return klass_at(klass_ref_index_at(which), THREAD);
 }
 
 
@@ -1494,7 +1504,7 @@
       }
       case JVM_CONSTANT_Long: {
         u8 val = Bytes::get_Java_u8(bytes);
-        printf("long         "INT64_FORMAT, (int64_t) *(jlong *) &val);
+        printf("long         " INT64_FORMAT, (int64_t) *(jlong *) &val);
         ent_size = 8;
         idx++; // Long takes two cpool slots
         break;
diff --git a/src/share/vm/oops/constantPool.hpp b/src/share/vm/oops/constantPool.hpp
index 497df53..0698eb4 100644
--- a/src/share/vm/oops/constantPool.hpp
+++ b/src/share/vm/oops/constantPool.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -200,6 +200,7 @@
 
   // resolved strings, methodHandles and callsite objects from the constant pool
   objArrayOop resolved_references()  const;
+  objArrayOop resolved_references_or_null()  const;
   // mapping resolved object array indexes to cp indexes and back.
   int object_to_cp_index(int index)         { return _reference_map->at(index); }
   int cp_to_object_index(int index);
@@ -983,7 +984,7 @@
         delete(cur);
       }
     }
-    delete _buckets;
+    FREE_C_HEAP_ARRAY(SymbolHashMapBucket, _buckets, mtSymbol);
   }
 }; // End SymbolHashMap class
 
diff --git a/src/share/vm/oops/cpCache.cpp b/src/share/vm/oops/cpCache.cpp
index 3bbb400..cea52ef 100644
--- a/src/share/vm/oops/cpCache.cpp
+++ b/src/share/vm/oops/cpCache.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -226,14 +226,13 @@
       // virtual method in java.lang.Object. This is a corner case in the spec
       // but is presumably legal. javac does not generate this code.
       //
-      // We set bytecode_1() to _invokeinterface, because that is the
-      // bytecode # used by the interpreter to see if it is resolved.
+      // We do not set bytecode_1() to _invokeinterface, because that is the
+      // bytecode # used by the interpreter to see if it is resolved.  In this
+      // case, the method gets reresolved with caller for each interface call
+      // because the actual selected method may not be public.
+      //
       // We set bytecode_2() to _invokevirtual.
       // See also interpreterRuntime.cpp. (8/25/2000)
-      // Only set resolved for the invokeinterface case if method is public.
-      // Otherwise, the method needs to be reresolved with caller for each
-      // interface call.
-      if (method->is_public()) set_bytecode_1(invoke_code);
     } else {
       assert(invoke_code == Bytecodes::_invokevirtual, "");
     }
@@ -259,14 +258,16 @@
   set_direct_or_vtable_call(invoke_code, method, index, false);
 }
 
-void ConstantPoolCacheEntry::set_itable_call(Bytecodes::Code invoke_code, methodHandle method, int index) {
+void ConstantPoolCacheEntry::set_itable_call(Bytecodes::Code invoke_code,
+                                                        KlassHandle referenced_klass,
+                                                        methodHandle method, int index) {
   assert(method->method_holder()->verify_itable_index(index), "");
   assert(invoke_code == Bytecodes::_invokeinterface, "");
   InstanceKlass* interf = method->method_holder();
   assert(interf->is_interface(), "must be an interface");
   assert(!method->is_final_method(), "interfaces do not have final methods; cannot link to one here");
-  set_f1(interf);
-  set_f2(index);
+  set_f1(referenced_klass());
+  set_f2((intx)method());
   set_method_flags(as_TosState(method->result_type()),
                    0,  // no option bits
                    method()->size_of_parameters());
@@ -313,7 +314,7 @@
                    adapter->size_of_parameters());
 
   if (TraceInvokeDynamic) {
-    tty->print_cr("set_method_handle bc=%d appendix="PTR_FORMAT"%s method_type="PTR_FORMAT"%s method="PTR_FORMAT" ",
+    tty->print_cr("set_method_handle bc=%d appendix=" PTR_FORMAT "%s method_type=" PTR_FORMAT "%s method=" PTR_FORMAT " ",
                   invoke_code,
                   (void *)appendix(),    (has_appendix    ? "" : " (unused)"),
                   (void *)method_type(), (has_method_type ? "" : " (unused)"),
@@ -433,10 +434,27 @@
 
 
 #if INCLUDE_JVMTI
+
+void log_adjust(const char* entry_type, Method* old_method, Method* new_method, bool* trace_name_printed) {
+  if (RC_TRACE_IN_RANGE(0x00100000, 0x00400000)) {
+    if (!(*trace_name_printed)) {
+      // RC_TRACE_MESG macro has an embedded ResourceMark
+      RC_TRACE_MESG(("adjust: name=%s",
+        old_method->method_holder()->external_name()));
+      *trace_name_printed = true;
+    }
+    // RC_TRACE macro has an embedded ResourceMark
+    RC_TRACE(0x00400000, ("cpc %s entry update: %s(%s)",
+      entry_type,
+      new_method->name()->as_C_string(),
+      new_method->signature()->as_C_string()));
+  }
+}
+
 // RedefineClasses() API support:
 // If this ConstantPoolCacheEntry refers to old_method then update it
 // to refer to new_method.
-bool ConstantPoolCacheEntry::adjust_method_entry(Method* old_method,
+void ConstantPoolCacheEntry::adjust_method_entry(Method* old_method,
        Method* new_method, bool * trace_name_printed) {
 
   if (is_vfinal()) {
@@ -445,69 +463,34 @@
       // match old_method so need an update
       // NOTE: can't use set_f2_as_vfinal_method as it asserts on different values
       _f2 = (intptr_t)new_method;
-      if (RC_TRACE_IN_RANGE(0x00100000, 0x00400000)) {
-        if (!(*trace_name_printed)) {
-          // RC_TRACE_MESG macro has an embedded ResourceMark
-          RC_TRACE_MESG(("adjust: name=%s",
-            old_method->method_holder()->external_name()));
-          *trace_name_printed = true;
-        }
-        // RC_TRACE macro has an embedded ResourceMark
-        RC_TRACE(0x00400000, ("cpc vf-entry update: %s(%s)",
-          new_method->name()->as_C_string(),
-          new_method->signature()->as_C_string()));
-      }
-      return true;
     }
-
-    // f1() is not used with virtual entries so bail out
-    return false;
+    return;
   }
 
-  if (_f1 == NULL) {
-    // NULL f1() means this is a virtual entry so bail out
-    // We are assuming that the vtable index does not need change.
-    return false;
-  }
+  assert (_f1 != NULL, "should not call with uninteresting entry");
 
-  if (_f1 == old_method) {
+  if (!(_f1->is_method())) {
+    // _f1 is a Klass* for an interface, _f2 is the method
+    if (f2_as_interface_method() == old_method) {
+      _f2 = (intptr_t)new_method;
+      log_adjust("interface", old_method, new_method, trace_name_printed);
+    }
+  } else if (_f1 == old_method) {
     _f1 = new_method;
-    if (RC_TRACE_IN_RANGE(0x00100000, 0x00400000)) {
-      if (!(*trace_name_printed)) {
-        // RC_TRACE_MESG macro has an embedded ResourceMark
-        RC_TRACE_MESG(("adjust: name=%s",
-          old_method->method_holder()->external_name()));
-        *trace_name_printed = true;
-      }
-      // RC_TRACE macro has an embedded ResourceMark
-      RC_TRACE(0x00400000, ("cpc entry update: %s(%s)",
-        new_method->name()->as_C_string(),
-        new_method->signature()->as_C_string()));
-    }
-    return true;
+    log_adjust("special, static or dynamic", old_method, new_method, trace_name_printed);
   }
-
-  return false;
 }
 
 // a constant pool cache entry should never contain old or obsolete methods
 bool ConstantPoolCacheEntry::check_no_old_or_obsolete_entries() {
-  if (is_vfinal()) {
-    // virtual and final so _f2 contains method ptr instead of vtable index
-    Metadata* f2 = (Metadata*)_f2;
-    // Return false if _f2 refers to an old or an obsolete method.
-    // _f2 == NULL || !_f2->is_method() are just as unexpected here.
-    return (f2 != NULL NOT_PRODUCT(&& f2->is_valid()) && f2->is_method() &&
-            !((Method*)f2)->is_old() && !((Method*)f2)->is_obsolete());
-  } else if (_f1 == NULL ||
-             (NOT_PRODUCT(_f1->is_valid() &&) !_f1->is_method())) {
-    // _f1 == NULL || !_f1->is_method() are OK here
+  Method* m = get_interesting_method_entry(NULL);
+  // return false if m refers to a non-deleted old or obsolete method
+  if (m != NULL) {
+    assert(m->is_valid() && m->is_method(), "m is a valid method");
+    return !m->is_old() && !m->is_obsolete(); // old is always set for old and obsolete
+  } else {
     return true;
   }
-  // return false if _f1 refers to a non-deleted old or obsolete method
-  return (NOT_PRODUCT(_f1->is_valid() &&) _f1->is_method() &&
-          (f1_as_method()->is_deleted() ||
-          (!f1_as_method()->is_old() && !f1_as_method()->is_obsolete())));
 }
 
 Method* ConstantPoolCacheEntry::get_interesting_method_entry(Klass* k) {
@@ -524,10 +507,11 @@
     return NULL;
   } else {
     if (!(_f1->is_method())) {
-      // _f1 can also contain a Klass* for an interface
-      return NULL;
+      // _f1 is a Klass* for an interface
+      m = f2_as_interface_method();
+    } else {
+      m = f1_as_method();
     }
-    m = f1_as_method();
   }
   assert(m != NULL && m->is_method(), "sanity check");
   if (m == NULL || !m->is_method() || (k != NULL && m->method_holder() != k)) {
@@ -544,12 +528,12 @@
   // print separator
   if (index == 0) st->print_cr("                 -------------");
   // print entry
-  st->print("%3d  ("PTR_FORMAT")  ", index, (intptr_t)this);
+  st->print("%3d  (" PTR_FORMAT ")  ", index, (intptr_t)this);
   st->print_cr("[%02x|%02x|%5d]", bytecode_2(), bytecode_1(),
                constant_pool_index());
-  st->print_cr("                 [   "PTR_FORMAT"]", (intptr_t)_f1);
-  st->print_cr("                 [   "PTR_FORMAT"]", (intptr_t)_f2);
-  st->print_cr("                 [   "PTR_FORMAT"]", (intptr_t)_flags);
+  st->print_cr("                 [   " PTR_FORMAT "]", (intptr_t)_f1);
+  st->print_cr("                 [   " PTR_FORMAT "]", (intptr_t)_f2);
+  st->print_cr("                 [   " PTR_FORMAT "]", (intptr_t)_flags);
   st->print_cr("                 -------------");
 }
 
diff --git a/src/share/vm/oops/cpCache.hpp b/src/share/vm/oops/cpCache.hpp
index 17860b4..a4a6c3f 100644
--- a/src/share/vm/oops/cpCache.hpp
+++ b/src/share/vm/oops/cpCache.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -248,6 +248,7 @@
 
   void set_itable_call(
     Bytecodes::Code invoke_code,                 // the bytecode used; must be invokeinterface
+    KlassHandle referenced_klass,                // the referenced klass in the InterfaceMethodref
     methodHandle method,                         // the resolved interface method
     int itable_index                             // index into itable for the method
   );
@@ -344,6 +345,7 @@
   bool      is_f1_null() const                   { Metadata* f1 = f1_ord(); return f1 == NULL; }  // classifies a CPC entry as unbound
   int       f2_as_index() const                  { assert(!is_vfinal(), ""); return (int) _f2; }
   Method*   f2_as_vfinal_method() const          { assert(is_vfinal(), ""); return (Method*)_f2; }
+  Method*   f2_as_interface_method() const       { assert(bytecode_1() == Bytecodes::_invokeinterface, ""); return (Method*)_f2; }
   int  field_index() const                       { assert(is_field_entry(),  ""); return (_flags & field_index_mask); }
   int  parameter_size() const                    { assert(is_method_entry(), ""); return (_flags & parameter_size_mask); }
   bool is_volatile() const                       { return (_flags & (1 << is_volatile_shift))       != 0; }
@@ -374,7 +376,7 @@
   // trace_name_printed is set to true if the current call has
   // printed the klass name so that other routines in the adjust_*
   // group don't print the klass name.
-  bool adjust_method_entry(Method* old_method, Method* new_method,
+  void adjust_method_entry(Method* old_method, Method* new_method,
          bool* trace_name_printed);
   bool check_no_old_or_obsolete_entries();
   Method* get_interesting_method_entry(Klass* k);
diff --git a/src/share/vm/oops/generateOopMap.cpp b/src/share/vm/oops/generateOopMap.cpp
index 2207e8c..bb951f8 100644
--- a/src/share/vm/oops/generateOopMap.cpp
+++ b/src/share/vm/oops/generateOopMap.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -29,6 +29,7 @@
 #include "oops/symbol.hpp"
 #include "runtime/handles.inline.hpp"
 #include "runtime/java.hpp"
+#include "runtime/os.hpp"
 #include "runtime/relocator.hpp"
 #include "utilities/bitMap.inline.hpp"
 #include "prims/methodHandles.hpp"
@@ -2133,10 +2134,10 @@
 void GenerateOopMap::error_work(const char *format, va_list ap) {
   _got_error = true;
   char msg_buffer[512];
-  vsnprintf(msg_buffer, sizeof(msg_buffer), format, ap);
+  os::vsnprintf(msg_buffer, sizeof(msg_buffer), format, ap);
   // Append method name
   char msg_buffer2[512];
-  jio_snprintf(msg_buffer2, sizeof(msg_buffer2), "%s in method %s", msg_buffer, method()->name()->as_C_string());
+  os::snprintf(msg_buffer2, sizeof(msg_buffer2), "%s in method %s", msg_buffer, method()->name()->as_C_string());
   _exception = Exceptions::new_exception(Thread::current(),
                 vmSymbols::java_lang_LinkageError(), msg_buffer2);
 }
@@ -2154,7 +2155,7 @@
   _got_error = true;
   // Append method name
   char msg_buffer2[512];
-  jio_snprintf(msg_buffer2, sizeof(msg_buffer2), "%s in method %s", msg,
+  os::snprintf(msg_buffer2, sizeof(msg_buffer2), "%s in method %s", msg,
                method()->name()->as_C_string());
   _exception = Exceptions::new_exception(Thread::current(),
                 vmSymbols::java_lang_LinkageError(), msg_buffer2);
diff --git a/src/share/vm/oops/instanceKlass.cpp b/src/share/vm/oops/instanceKlass.cpp
index b1c09f6..2cff42c 100644
--- a/src/share/vm/oops/instanceKlass.cpp
+++ b/src/share/vm/oops/instanceKlass.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -581,7 +581,7 @@
   // 1) Verify the bytecodes
   Verifier::Mode mode =
     throw_verifyerror ? Verifier::ThrowException : Verifier::NoException;
-  return Verifier::verify(this_oop, mode, this_oop->should_verify_class(), CHECK_false);
+  return Verifier::verify(this_oop, mode, this_oop->should_verify_class(), THREAD);
 }
 
 
@@ -1195,7 +1195,7 @@
   if (or_null) {
     return oak->array_klass_or_null(n);
   }
-  return oak->array_klass(n, CHECK_NULL);
+  return oak->array_klass(n, THREAD);
 }
 
 Klass* InstanceKlass::array_klass_impl(bool or_null, TRAPS) {
@@ -2582,16 +2582,6 @@
     assert(breakpoints() == 0x0, "should have cleared breakpoints");
   }
 
-  // deallocate information about previous versions
-  if (_previous_versions != NULL) {
-    for (int i = _previous_versions->length() - 1; i >= 0; i--) {
-      PreviousVersionNode * pv_node = _previous_versions->at(i);
-      delete pv_node;
-    }
-    delete _previous_versions;
-    _previous_versions = NULL;
-  }
-
   // deallocate the cached class file
   if (_cached_class_file != NULL) {
     os::free(_cached_class_file, mtClass);
@@ -3187,16 +3177,17 @@
   st->print(BULLET"field type annotations:  "); fields_type_annotations()->print_value_on(st); st->cr();
   {
     bool have_pv = false;
-    PreviousVersionWalker pvw(Thread::current(), (InstanceKlass*)this);
-    for (PreviousVersionNode * pv_node = pvw.next_previous_version();
-         pv_node != NULL; pv_node = pvw.next_previous_version()) {
+    // previous versions are linked together through the InstanceKlass
+    for (InstanceKlass* pv_node = _previous_versions;
+         pv_node != NULL;
+         pv_node = pv_node->previous_versions()) {
       if (!have_pv)
         st->print(BULLET"previous version:  ");
       have_pv = true;
-      pv_node->prev_constant_pool()->print_value_on(st);
+      pv_node->constants()->print_value_on(st);
     }
     if (have_pv) st->cr();
-  } // pvw is cleaned up
+  }
 
   if (generic_signature() != NULL) {
     st->print(BULLET"generic signature: ");
@@ -3610,205 +3601,126 @@
 // RedefineClasses() support for previous versions:
 
 // Purge previous versions
-static void purge_previous_versions_internal(InstanceKlass* ik, int emcp_method_count) {
+void InstanceKlass::purge_previous_versions(InstanceKlass* ik) {
   if (ik->previous_versions() != NULL) {
     // This klass has previous versions so see what we can cleanup
     // while it is safe to do so.
 
     int deleted_count = 0;    // leave debugging breadcrumbs
     int live_count = 0;
-    ClassLoaderData* loader_data = ik->class_loader_data() == NULL ?
-                       ClassLoaderData::the_null_class_loader_data() :
-                       ik->class_loader_data();
+    ClassLoaderData* loader_data = ik->class_loader_data();
+    assert(loader_data != NULL, "should never be null");
 
     // RC_TRACE macro has an embedded ResourceMark
-    RC_TRACE(0x00000200, ("purge: %s: previous version length=%d",
-      ik->external_name(), ik->previous_versions()->length()));
+    RC_TRACE(0x00000200, ("purge: %s: previous versions", ik->external_name()));
 
-    for (int i = ik->previous_versions()->length() - 1; i >= 0; i--) {
-      // check the previous versions array
-      PreviousVersionNode * pv_node = ik->previous_versions()->at(i);
-      ConstantPool* cp_ref = pv_node->prev_constant_pool();
-      assert(cp_ref != NULL, "cp ref was unexpectedly cleared");
+    // previous versions are linked together through the InstanceKlass
+    InstanceKlass* pv_node = ik->previous_versions();
+    InstanceKlass* last = ik;
+    int version = 0;
 
-      ConstantPool* pvcp = cp_ref;
+    // check the previous versions list
+    for (; pv_node != NULL; ) {
+
+      ConstantPool* pvcp = pv_node->constants();
+      assert(pvcp != NULL, "cp ref was unexpectedly cleared");
+
+
       if (!pvcp->on_stack()) {
         // If the constant pool isn't on stack, none of the methods
-        // are executing.  Delete all the methods, the constant pool and
-        // and this previous version node.
-        GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
-        if (method_refs != NULL) {
-          for (int j = method_refs->length() - 1; j >= 0; j--) {
-            Method* method = method_refs->at(j);
-            assert(method != NULL, "method ref was unexpectedly cleared");
-            method_refs->remove_at(j);
-            // method will be freed with associated class.
-          }
-        }
-        // Remove the constant pool
-        delete pv_node;
-        // Since we are traversing the array backwards, we don't have to
-        // do anything special with the index.
-        ik->previous_versions()->remove_at(i);
+        // are executing.  Unlink this previous_version.
+        // The previous version InstanceKlass is on the ClassLoaderData deallocate list
+        // so will be deallocated during the next phase of class unloading.
+        pv_node = pv_node->previous_versions();
+        last->link_previous_versions(pv_node);
         deleted_count++;
+        version++;
         continue;
       } else {
-        RC_TRACE(0x00000200, ("purge: previous version @%d is alive", i));
+        RC_TRACE(0x00000200, ("purge: previous version " INTPTR_FORMAT " is alive",
+                              pv_node));
         assert(pvcp->pool_holder() != NULL, "Constant pool with no holder");
         guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack");
         live_count++;
       }
 
-      // At least one method is live in this previous version, clean out
-      // the others or mark them as obsolete.
-      GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
+      // At least one method is live in this previous version so clean its MethodData.
+      // Reset dead EMCP methods not to get breakpoints.
+      // All methods are deallocated when all of the methods for this class are no
+      // longer running.
+      Array<Method*>* method_refs = pv_node->methods();
       if (method_refs != NULL) {
         RC_TRACE(0x00000200, ("purge: previous methods length=%d",
           method_refs->length()));
-        for (int j = method_refs->length() - 1; j >= 0; j--) {
+        for (int j = 0; j < method_refs->length(); j++) {
           Method* method = method_refs->at(j);
-          assert(method != NULL, "method ref was unexpectedly cleared");
 
-          // Remove the emcp method if it's not executing
-          // If it's been made obsolete by a redefinition of a non-emcp
-          // method, mark it as obsolete but leave it to clean up later.
           if (!method->on_stack()) {
-            method_refs->remove_at(j);
-          } else if (emcp_method_count == 0) {
-            method->set_is_obsolete();
+            // no breakpoints for non-running methods
+            if (method->is_running_emcp()) {
+              method->set_running_emcp(false);
+            }
           } else {
+            assert (method->is_obsolete() || method->is_running_emcp(),
+                    "emcp method cannot run after emcp bit is cleared");
             // RC_TRACE macro has an embedded ResourceMark
             RC_TRACE(0x00000200,
               ("purge: %s(%s): prev method @%d in version @%d is alive",
               method->name()->as_C_string(),
-              method->signature()->as_C_string(), j, i));
+              method->signature()->as_C_string(), j, version));
+            if (method->method_data() != NULL) {
+              // Clean out any weak method links for running methods
+              // (also should include not EMCP methods)
+              method->method_data()->clean_weak_method_links();
+            }
           }
         }
       }
+      // next previous version
+      last = pv_node;
+      pv_node = pv_node->previous_versions();
+      version++;
     }
-    assert(ik->previous_versions()->length() == live_count, "sanity check");
     RC_TRACE(0x00000200,
       ("purge: previous version stats: live=%d, deleted=%d", live_count,
       deleted_count));
   }
-}
 
-// External interface for use during class unloading.
-void InstanceKlass::purge_previous_versions(InstanceKlass* ik) {
-  // Call with >0 emcp methods since they are not currently being redefined.
-  purge_previous_versions_internal(ik, 1);
-}
-
-
-// Potentially add an information node that contains pointers to the
-// interesting parts of the previous version of the_class.
-// This is also where we clean out any unused references.
-// Note that while we delete nodes from the _previous_versions
-// array, we never delete the array itself until the klass is
-// unloaded. The has_been_redefined() query depends on that fact.
-//
-void InstanceKlass::add_previous_version(instanceKlassHandle ikh,
-       BitMap* emcp_methods, int emcp_method_count) {
-  assert(Thread::current()->is_VM_thread(),
-         "only VMThread can add previous versions");
-
-  if (_previous_versions == NULL) {
-    // This is the first previous version so make some space.
-    // Start with 2 elements under the assumption that the class
-    // won't be redefined much.
-    _previous_versions =  new (ResourceObj::C_HEAP, mtClass)
-                            GrowableArray<PreviousVersionNode *>(2, true);
-  }
-
-  ConstantPool* cp_ref = ikh->constants();
-
-  // RC_TRACE macro has an embedded ResourceMark
-  RC_TRACE(0x00000400, ("adding previous version ref for %s @%d, EMCP_cnt=%d "
-                        "on_stack=%d",
-    ikh->external_name(), _previous_versions->length(), emcp_method_count,
-    cp_ref->on_stack()));
-
-  // If the constant pool for this previous version of the class
-  // is not marked as being on the stack, then none of the methods
-  // in this previous version of the class are on the stack so
-  // we don't need to create a new PreviousVersionNode. However,
-  // we still need to examine older previous versions below.
-  Array<Method*>* old_methods = ikh->methods();
-
-  if (cp_ref->on_stack()) {
-    PreviousVersionNode * pv_node = NULL;
-    if (emcp_method_count == 0) {
-      // non-shared ConstantPool gets a reference
-      pv_node = new PreviousVersionNode(cp_ref, NULL);
-      RC_TRACE(0x00000400,
-          ("add: all methods are obsolete; flushing any EMCP refs"));
-    } else {
-      int local_count = 0;
-      GrowableArray<Method*>* method_refs = new (ResourceObj::C_HEAP, mtClass)
-          GrowableArray<Method*>(emcp_method_count, true);
-      for (int i = 0; i < old_methods->length(); i++) {
-        if (emcp_methods->at(i)) {
-            // this old method is EMCP. Save it only if it's on the stack
-            Method* old_method = old_methods->at(i);
-            if (old_method->on_stack()) {
-              method_refs->append(old_method);
-            }
-          if (++local_count >= emcp_method_count) {
-            // no more EMCP methods so bail out now
-            break;
-          }
-        }
-      }
-      // non-shared ConstantPool gets a reference
-      pv_node = new PreviousVersionNode(cp_ref, method_refs);
+  // Clean MethodData of this class's methods so they don't refer to
+  // old methods that are no longer running.
+  Array<Method*>* methods = ik->methods();
+  int num_methods = methods->length();
+  for (int index2 = 0; index2 < num_methods; ++index2) {
+    if (methods->at(index2)->method_data() != NULL) {
+      methods->at(index2)->method_data()->clean_weak_method_links();
     }
-    // append new previous version.
-    _previous_versions->append(pv_node);
   }
+}
 
-  // Since the caller is the VMThread and we are at a safepoint, this
-  // is a good time to clear out unused references.
-
-  RC_TRACE(0x00000400, ("add: previous version length=%d",
-    _previous_versions->length()));
-
-  // Purge previous versions not executing on the stack
-  purge_previous_versions_internal(this, emcp_method_count);
-
+void InstanceKlass::mark_newly_obsolete_methods(Array<Method*>* old_methods,
+                                                int emcp_method_count) {
   int obsolete_method_count = old_methods->length() - emcp_method_count;
 
   if (emcp_method_count != 0 && obsolete_method_count != 0 &&
-      _previous_versions->length() > 0) {
+      _previous_versions != NULL) {
     // We have a mix of obsolete and EMCP methods so we have to
     // clear out any matching EMCP method entries the hard way.
     int local_count = 0;
     for (int i = 0; i < old_methods->length(); i++) {
-      if (!emcp_methods->at(i)) {
+      Method* old_method = old_methods->at(i);
+      if (old_method->is_obsolete()) {
         // only obsolete methods are interesting
-        Method* old_method = old_methods->at(i);
         Symbol* m_name = old_method->name();
         Symbol* m_signature = old_method->signature();
 
-        // we might not have added the last entry
-        for (int j = _previous_versions->length() - 1; j >= 0; j--) {
-          // check the previous versions array for non executing obsolete methods
-          PreviousVersionNode * pv_node = _previous_versions->at(j);
+        // previous versions are linked together through the InstanceKlass
+        int j = 0;
+        for (InstanceKlass* prev_version = _previous_versions;
+             prev_version != NULL;
+             prev_version = prev_version->previous_versions(), j++) {
 
-          GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
-          if (method_refs == NULL) {
-            // We have run into a PreviousVersion generation where
-            // all methods were made obsolete during that generation's
-            // RedefineClasses() operation. At the time of that
-            // operation, all EMCP methods were flushed so we don't
-            // have to go back any further.
-            //
-            // A NULL method_refs is different than an empty method_refs.
-            // We cannot infer any optimizations about older generations
-            // from an empty method_refs for the current generation.
-            break;
-          }
-
-          for (int k = method_refs->length() - 1; k >= 0; k--) {
+          Array<Method*>* method_refs = prev_version->methods();
+          for (int k = 0; k < method_refs->length(); k++) {
             Method* method = method_refs->at(k);
 
             if (!method->is_obsolete() &&
@@ -3816,14 +3728,11 @@
                 method->signature() == m_signature) {
               // The current RedefineClasses() call has made all EMCP
               // versions of this method obsolete so mark it as obsolete
-              // and remove the reference.
               RC_TRACE(0x00000400,
                 ("add: %s(%s): flush obsolete method @%d in version @%d",
                 m_name->as_C_string(), m_signature->as_C_string(), k, j));
 
               method->set_is_obsolete();
-              // Leave obsolete methods on the previous version list to
-              // clean up later.
               break;
             }
           }
@@ -3831,9 +3740,9 @@
           // The previous loop may not find a matching EMCP method, but
           // that doesn't mean that we can optimize and not go any
           // further back in the PreviousVersion generations. The EMCP
-          // method for this generation could have already been deleted,
+          // method for this generation could have already been made obsolete,
           // but there still may be an older EMCP method that has not
-          // been deleted.
+          // been made obsolete.
         }
 
         if (++local_count >= obsolete_method_count) {
@@ -3843,30 +3752,67 @@
       }
     }
   }
-} // end add_previous_version()
-
-
-// Determine if InstanceKlass has a previous version.
-bool InstanceKlass::has_previous_version() const {
-  return (_previous_versions != NULL && _previous_versions->length() > 0);
-} // end has_previous_version()
-
-
-InstanceKlass* InstanceKlass::get_klass_version(int version) {
-  if (constants()->version() == version) {
-    return this;
-  }
-  PreviousVersionWalker pvw(Thread::current(), (InstanceKlass*)this);
-  for (PreviousVersionNode * pv_node = pvw.next_previous_version();
-       pv_node != NULL; pv_node = pvw.next_previous_version()) {
-    ConstantPool* prev_cp = pv_node->prev_constant_pool();
-    if (prev_cp->version() == version) {
-      return prev_cp->pool_holder();
-    }
-  }
-  return NULL; // None found
 }
 
+// Save the scratch_class as the previous version if any of the methods are running.
+// The previous_versions are used to set breakpoints in EMCP methods and they are
+// also used to clean MethodData links to redefined methods that are no longer running.
+void InstanceKlass::add_previous_version(instanceKlassHandle scratch_class,
+                                         int emcp_method_count) {
+  assert(Thread::current()->is_VM_thread(),
+         "only VMThread can add previous versions");
+
+  // RC_TRACE macro has an embedded ResourceMark
+  RC_TRACE(0x00000400, ("adding previous version ref for %s, EMCP_cnt=%d",
+    scratch_class->external_name(), emcp_method_count));
+
+  // Clean out old previous versions
+  purge_previous_versions(this);
+
+  // Mark newly obsolete methods in remaining previous versions.  An EMCP method from
+  // a previous redefinition may be made obsolete by this redefinition.
+  Array<Method*>* old_methods = scratch_class->methods();
+  mark_newly_obsolete_methods(old_methods, emcp_method_count);
+
+  // If the constant pool for this previous version of the class
+  // is not marked as being on the stack, then none of the methods
+  // in this previous version of the class are on the stack so
+  // we don't need to add this as a previous version.
+  ConstantPool* cp_ref = scratch_class->constants();
+  if (!cp_ref->on_stack()) {
+    RC_TRACE(0x00000400, ("add: scratch class not added; no methods are running"));
+    return;
+  }
+
+  if (emcp_method_count != 0) {
+    // At least one method is still running, check for EMCP methods
+    for (int i = 0; i < old_methods->length(); i++) {
+      Method* old_method = old_methods->at(i);
+      if (!old_method->is_obsolete() && old_method->on_stack()) {
+        // if EMCP method (not obsolete) is on the stack, mark as EMCP so that
+        // we can add breakpoints for it.
+
+        // We set the method->on_stack bit during safepoints for class redefinition and
+        // class unloading and use this bit to set the is_running_emcp bit.
+        // After the safepoint, the on_stack bit is cleared and the running emcp
+        // method may exit.   If so, we would set a breakpoint in a method that
+        // is never reached, but this won't be noticeable to the programmer.
+        old_method->set_running_emcp(true);
+        RC_TRACE(0x00000400, ("add: EMCP method %s is on_stack " INTPTR_FORMAT,
+                              old_method->name_and_sig_as_C_string(), old_method));
+      } else if (!old_method->is_obsolete()) {
+        RC_TRACE(0x00000400, ("add: EMCP method %s is NOT on_stack " INTPTR_FORMAT,
+                              old_method->name_and_sig_as_C_string(), old_method));
+      }
+    }
+  }
+
+  // Add previous version if any methods are still running.
+  RC_TRACE(0x00000400, ("add: scratch class added; one of its methods is on_stack"));
+  assert(scratch_class->previous_versions() == NULL, "shouldn't have a previous version");
+  scratch_class->link_previous_versions(previous_versions());
+  link_previous_versions(scratch_class());
+} // end add_previous_version()
 
 Method* InstanceKlass::method_with_idnum(int idnum) {
   Method* m = NULL;
@@ -3924,61 +3870,3 @@
 unsigned char * InstanceKlass::get_cached_class_file_bytes() {
   return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file);
 }
-
-
-// Construct a PreviousVersionNode entry for the array hung off
-// the InstanceKlass.
-PreviousVersionNode::PreviousVersionNode(ConstantPool* prev_constant_pool,
-  GrowableArray<Method*>* prev_EMCP_methods) {
-
-  _prev_constant_pool = prev_constant_pool;
-  _prev_EMCP_methods = prev_EMCP_methods;
-}
-
-
-// Destroy a PreviousVersionNode
-PreviousVersionNode::~PreviousVersionNode() {
-  if (_prev_constant_pool != NULL) {
-    _prev_constant_pool = NULL;
-  }
-
-  if (_prev_EMCP_methods != NULL) {
-    delete _prev_EMCP_methods;
-  }
-}
-
-// Construct a helper for walking the previous versions array
-PreviousVersionWalker::PreviousVersionWalker(Thread* thread, InstanceKlass *ik) {
-  _thread = thread;
-  _previous_versions = ik->previous_versions();
-  _current_index = 0;
-  _current_p = NULL;
-  _current_constant_pool_handle = constantPoolHandle(thread, ik->constants());
-}
-
-
-// Return the interesting information for the next previous version
-// of the klass. Returns NULL if there are no more previous versions.
-PreviousVersionNode* PreviousVersionWalker::next_previous_version() {
-  if (_previous_versions == NULL) {
-    // no previous versions so nothing to return
-    return NULL;
-  }
-
-  _current_p = NULL;  // reset to NULL
-  _current_constant_pool_handle = NULL;
-
-  int length = _previous_versions->length();
-
-  while (_current_index < length) {
-    PreviousVersionNode * pv_node = _previous_versions->at(_current_index++);
-
-    // Save a handle to the constant pool for this previous version,
-    // which keeps all the methods from being deallocated.
-    _current_constant_pool_handle = constantPoolHandle(_thread, pv_node->prev_constant_pool());
-    _current_p = pv_node;
-    return pv_node;
-  }
-
-  return NULL;
-} // end next_previous_version()
diff --git a/src/share/vm/oops/instanceKlass.hpp b/src/share/vm/oops/instanceKlass.hpp
index e1fba31..a5f2eb3 100644
--- a/src/share/vm/oops/instanceKlass.hpp
+++ b/src/share/vm/oops/instanceKlass.hpp
@@ -88,7 +88,6 @@
 class fieldDescriptor;
 class DepChange;
 class nmethodBucket;
-class PreviousVersionNode;
 class JvmtiCachedClassFieldMap;
 class MemberNameTable;
 
@@ -235,7 +234,8 @@
     _misc_is_anonymous             = 1 << 3, // has embedded _host_klass field
     _misc_is_contended             = 1 << 4, // marked with contended annotation
     _misc_has_default_methods      = 1 << 5, // class/superclass/implemented interfaces has default methods
-    _misc_declares_default_methods = 1 << 6  // directly declares default methods (any access)
+    _misc_declares_default_methods = 1 << 6, // directly declares default methods (any access)
+    _misc_has_been_redefined       = 1 << 7  // class has been redefined
   };
   u2              _misc_flags;
   u2              _minor_version;        // minor version number of class file
@@ -250,9 +250,8 @@
   nmethodBucket*  _dependencies;         // list of dependent nmethods
   nmethod*        _osr_nmethods_head;    // Head of list of on-stack replacement nmethods for this class
   BreakpointInfo* _breakpoints;          // bpt lists, managed by Method*
-  // Array of interesting part(s) of the previous version(s) of this
-  // InstanceKlass. See PreviousVersionWalker below.
-  GrowableArray<PreviousVersionNode *>* _previous_versions;
+  // Linked instanceKlasses of previous versions
+  InstanceKlass* _previous_versions;
   // JVMTI fields can be moved to their own structure - see 6315920
   // JVMTI: cached class file, before retransformable agent modified it in CFLH
   JvmtiCachedClassFileData* _cached_class_file;
@@ -583,9 +582,11 @@
   Klass* host_klass() const              {
     Klass** hk = (Klass**)adr_host_klass();
     if (hk == NULL) {
+      assert(!is_anonymous(), "Anonymous classes have host klasses");
       return NULL;
     } else {
       assert(*hk != NULL, "host klass should always be set if the address is not null");
+      assert(is_anonymous(), "Only anonymous classes have host klasses");
       return *hk;
     }
   }
@@ -597,6 +598,9 @@
       *addr = host;
     }
   }
+  bool has_host_klass() const              {
+    return adr_host_klass() != NULL;
+  }
   bool is_anonymous() const                {
     return (_misc_flags & _misc_is_anonymous) != 0;
   }
@@ -664,21 +668,31 @@
   }
 
   // RedefineClasses() support for previous versions:
-  void add_previous_version(instanceKlassHandle ikh, BitMap *emcp_methods,
-         int emcp_method_count);
-  // If the _previous_versions array is non-NULL, then this klass
-  // has been redefined at least once even if we aren't currently
-  // tracking a previous version.
-  bool has_been_redefined() const { return _previous_versions != NULL; }
-  bool has_previous_version() const;
+  void add_previous_version(instanceKlassHandle ikh, int emcp_method_count);
+
+  InstanceKlass* previous_versions() const { return _previous_versions; }
+
+  bool has_been_redefined() const {
+    return (_misc_flags & _misc_has_been_redefined) != 0;
+  }
+  void set_has_been_redefined() {
+    _misc_flags |= _misc_has_been_redefined;
+  }
+
   void init_previous_versions() {
     _previous_versions = NULL;
   }
-  GrowableArray<PreviousVersionNode *>* previous_versions() const {
-    return _previous_versions;
+
+
+  InstanceKlass* get_klass_version(int version) {
+    for (InstanceKlass* ik = this; ik != NULL; ik = ik->previous_versions()) {
+      if (ik->constants()->version() == version) {
+        return ik;
+      }
+    }
+    return NULL;
   }
 
-  InstanceKlass* get_klass_version(int version);
   static void purge_previous_versions(InstanceKlass* ik);
 
   // JVMTI: Support for caching a class file before it is modified by an agent that can do retransformation
@@ -1119,6 +1133,10 @@
 
   // Free CHeap allocated fields.
   void release_C_heap_structures();
+
+  // RedefineClasses support
+  void link_previous_versions(InstanceKlass* pv) { _previous_versions = pv; }
+  void mark_newly_obsolete_methods(Array<Method*>* old_methods, int emcp_method_count);
 public:
   // CDS support - remove and restore oops from metadata. Oops are not shared.
   virtual void remove_unshareable_info();
@@ -1217,62 +1235,6 @@
 };
 
 
-// If breakpoints are more numerous than just JVMTI breakpoints,
-// consider compressing this data structure.
-// It is currently a simple linked list defined in method.hpp.
-
-class BreakpointInfo;
-
-
-// A collection point for interesting information about the previous
-// version(s) of an InstanceKlass.  A GrowableArray of PreviousVersionNodes
-// is attached to the InstanceKlass as needed. See PreviousVersionWalker below.
-class PreviousVersionNode : public CHeapObj<mtClass> {
- private:
-  ConstantPool*    _prev_constant_pool;
-
-  // If the previous version of the InstanceKlass doesn't have any
-  // EMCP methods, then _prev_EMCP_methods will be NULL. If all the
-  // EMCP methods have been collected, then _prev_EMCP_methods can
-  // have a length of zero.
-  GrowableArray<Method*>* _prev_EMCP_methods;
-
-public:
-  PreviousVersionNode(ConstantPool* prev_constant_pool,
-                      GrowableArray<Method*>* prev_EMCP_methods);
-  ~PreviousVersionNode();
-  ConstantPool* prev_constant_pool() const {
-    return _prev_constant_pool;
-  }
-  GrowableArray<Method*>* prev_EMCP_methods() const {
-    return _prev_EMCP_methods;
-  }
-};
-
-
-// Helper object for walking previous versions.
-class PreviousVersionWalker : public StackObj {
- private:
-  Thread*                               _thread;
-  GrowableArray<PreviousVersionNode *>* _previous_versions;
-  int                                   _current_index;
-
-  // A pointer to the current node object so we can handle the deletes.
-  PreviousVersionNode*                  _current_p;
-
-  // The constant pool handle keeps all the methods in this class from being
-  // deallocated from the metaspace during class unloading.
-  constantPoolHandle                    _current_constant_pool_handle;
-
- public:
-  PreviousVersionWalker(Thread* thread, InstanceKlass *ik);
-
-  // Return the interesting information for the next previous version
-  // of the klass. Returns NULL if there are no more previous versions.
-  PreviousVersionNode* next_previous_version();
-};
-
-
 //
 // nmethodBucket is used to record dependent nmethods for
 // deoptimization.  nmethod dependencies are actually <klass, method>
diff --git a/src/share/vm/oops/klass.cpp b/src/share/vm/oops/klass.cpp
index e24a43d..0604903 100644
--- a/src/share/vm/oops/klass.cpp
+++ b/src/share/vm/oops/klass.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -48,6 +48,19 @@
 #include "gc_implementation/parallelScavenge/psScavenge.hpp"
 #endif // INCLUDE_ALL_GCS
 
+bool Klass::is_cloneable() const {
+  return _access_flags.is_cloneable() ||
+         is_subtype_of(SystemDictionary::Cloneable_klass());
+}
+
+void Klass::set_is_cloneable() {
+  if (oop_is_instance() && InstanceKlass::cast(this)->reference_type() != REF_NONE) {
+    // Reference cloning should not be intrinsified and always happen in JVM_Clone.
+  } else {
+    _access_flags.set_is_cloneable();
+  }
+}
+
 void Klass::set_name(Symbol* n) {
   _name = n;
   if (_name != NULL) _name->increment_refcount();
@@ -152,7 +165,7 @@
 
 void* Klass::operator new(size_t size, ClassLoaderData* loader_data, size_t word_size, TRAPS) throw() {
   return Metaspace::allocate(loader_data, word_size, /*read_only*/false,
-                             MetaspaceObj::ClassType, CHECK_NULL);
+                             MetaspaceObj::ClassType, THREAD);
 }
 
 Klass::Klass() {
@@ -455,6 +468,12 @@
     if (clean_alive_klasses && current->oop_is_instance()) {
       InstanceKlass* ik = InstanceKlass::cast(current);
       ik->clean_weak_instanceklass_links(is_alive);
+
+      // JVMTI RedefineClasses creates previous versions that are not in
+      // the class hierarchy, so process them here.
+      while ((ik = ik->previous_versions()) != NULL) {
+        ik->clean_weak_instanceklass_links(is_alive);
+      }
     }
   }
 }
diff --git a/src/share/vm/oops/klass.hpp b/src/share/vm/oops/klass.hpp
index 297932f..9f612c3 100644
--- a/src/share/vm/oops/klass.hpp
+++ b/src/share/vm/oops/klass.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -582,8 +582,8 @@
   bool has_final_method() const         { return _access_flags.has_final_method(); }
   void set_has_finalizer()              { _access_flags.set_has_finalizer(); }
   void set_has_final_method()           { _access_flags.set_has_final_method(); }
-  bool is_cloneable() const             { return _access_flags.is_cloneable(); }
-  void set_is_cloneable()               { _access_flags.set_is_cloneable(); }
+  bool is_cloneable() const;
+  void set_is_cloneable();
   bool has_vanilla_constructor() const  { return _access_flags.has_vanilla_constructor(); }
   void set_has_vanilla_constructor()    { _access_flags.set_has_vanilla_constructor(); }
   bool has_miranda_methods () const     { return access_flags().has_miranda_methods(); }
diff --git a/src/share/vm/oops/klassVtable.cpp b/src/share/vm/oops/klassVtable.cpp
index b6220ef..315d97f 100644
--- a/src/share/vm/oops/klassVtable.cpp
+++ b/src/share/vm/oops/klassVtable.cpp
@@ -1204,7 +1204,6 @@
   Array<Method*>* methods = InstanceKlass::cast(interf_h())->methods();
   int nof_methods = methods->length();
   HandleMark hm;
-  assert(nof_methods > 0, "at least one method must exist for interface to be in vtable");
   Handle interface_loader (THREAD, InstanceKlass::cast(interf_h())->class_loader());
 
   int ime_count = method_count_for_interface(interf_h());
@@ -1386,8 +1385,10 @@
       }
     }
 
-    // Only count interfaces with at least one method
-    if (method_count > 0) {
+    // Visit all interfaces which either have any methods or can participate in receiver type check.
+    // We do not bother to count methods in transitive interfaces, although that would allow us to skip
+    // this step in the rare case of a zero-method interface extending another zero-method interface.
+    if (method_count > 0 || InstanceKlass::cast(intf)->transitive_interfaces()->length() > 0) {
       blk->doit(intf, method_count);
     }
   }
diff --git a/src/share/vm/oops/markOop.cpp b/src/share/vm/oops/markOop.cpp
index 1cc8a19..9bca601 100644
--- a/src/share/vm/oops/markOop.cpp
+++ b/src/share/vm/oops/markOop.cpp
@@ -49,7 +49,7 @@
         st->print("monitor=NULL");
       else {
         BasicLock * bl = (BasicLock *) mon->owner();
-        st->print("monitor={count="INTPTR_FORMAT",waiters="INTPTR_FORMAT",recursions="INTPTR_FORMAT",owner="INTPTR_FORMAT"}",
+        st->print("monitor={count=" INTPTR_FORMAT ",waiters=" INTPTR_FORMAT ",recursions=" INTPTR_FORMAT ",owner=" INTPTR_FORMAT "}",
                 mon->count(), mon->waiters(), mon->recursions(), p2i(bl));
       }
     } else {
diff --git a/src/share/vm/oops/method.cpp b/src/share/vm/oops/method.cpp
index 35d5508..9e58c01 100644
--- a/src/share/vm/oops/method.cpp
+++ b/src/share/vm/oops/method.cpp
@@ -91,6 +91,7 @@
   set_hidden(false);
   set_dont_inline(false);
   set_has_injected_profile(false);
+  set_running_emcp(false);
   set_method_data(NULL);
   clear_method_counters();
   set_vtable_index(Method::garbage_vtable_index);
@@ -1968,9 +1969,9 @@
   assert(is_method(), "must be method");
   st->print_cr("%s", internal_name());
   // get the effect of PrintOopAddress, always, for methods:
-  st->print_cr(" - this oop:          "INTPTR_FORMAT, (intptr_t)this);
+  st->print_cr(" - this oop:          " INTPTR_FORMAT, (intptr_t)this);
   st->print   (" - method holder:     "); method_holder()->print_value_on(st); st->cr();
-  st->print   (" - constants:         "INTPTR_FORMAT" ", (address)constants());
+  st->print   (" - constants:         " INTPTR_FORMAT " ", (address)constants());
   constants()->print_value_on(st); st->cr();
   st->print   (" - access:            0x%x  ", access_flags().as_int()); access_flags().print_on(st); st->cr();
   st->print   (" - name:              ");    name()->print_value_on(st); st->cr();
diff --git a/src/share/vm/oops/method.hpp b/src/share/vm/oops/method.hpp
index 90b7029..fc6f433 100644
--- a/src/share/vm/oops/method.hpp
+++ b/src/share/vm/oops/method.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -111,6 +111,7 @@
                     _caller_sensitive     : 1,
                     _force_inline         : 1,
                     _hidden               : 1,
+                    _running_emcp         : 1,
                     _dont_inline          : 1,
                     _has_injected_profile : 1,
                                           : 2;
@@ -661,6 +662,7 @@
   static ByteSize from_interpreted_offset()      { return byte_offset_of(Method, _from_interpreted_entry ); }
   static ByteSize interpreter_entry_offset()     { return byte_offset_of(Method, _i2i_entry ); }
   static ByteSize signature_handler_offset()     { return in_ByteSize(sizeof(Method) + wordSize);      }
+  static ByteSize itable_index_offset()          { return byte_offset_of(Method, _vtable_index ); }
 
   // for code generation
   static int method_data_offset_in_bytes()       { return offset_of(Method, _method_data); }
@@ -711,6 +713,21 @@
   void set_is_obsolete()                            { _access_flags.set_is_obsolete(); }
   bool is_deleted() const                           { return access_flags().is_deleted(); }
   void set_is_deleted()                             { _access_flags.set_is_deleted(); }
+
+  bool is_running_emcp() const {
+    // EMCP methods are old but not obsolete or deleted. Equivalent
+    // Modulo Constant Pool means the method is equivalent except
+    // the constant pool and instructions that access the constant
+    // pool might be different.
+    // If a breakpoint is set in a redefined method, its EMCP methods that are
+    // still running must have a breakpoint also.
+    return _running_emcp;
+  }
+
+  void set_running_emcp(bool x) {
+    _running_emcp = x;
+  }
+
   bool on_stack() const                             { return access_flags().on_stack(); }
   void set_on_stack(const bool value);
 
diff --git a/src/share/vm/oops/methodData.cpp b/src/share/vm/oops/methodData.cpp
index f8ec09b..eb48188 100644
--- a/src/share/vm/oops/methodData.cpp
+++ b/src/share/vm/oops/methodData.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -681,7 +681,7 @@
   int size = MethodData::compute_allocation_size_in_words(method);
 
   return new (loader_data, size, false, MetaspaceObj::MethodDataType, THREAD)
-    MethodData(method(), size, CHECK_NULL);
+    MethodData(method(), size, THREAD);
 }
 
 int MethodData::bytecode_cell_count(Bytecodes::Code code) {
@@ -1559,9 +1559,35 @@
   }
 }
 
-// Remove SpeculativeTrapData entries that reference an unloaded
-// method
-void MethodData::clean_extra_data(BoolObjectClosure* is_alive) {
+class CleanExtraDataClosure : public StackObj {
+public:
+  virtual bool is_live(Method* m) = 0;
+};
+
+// Check for entries that reference an unloaded method
+class CleanExtraDataKlassClosure : public CleanExtraDataClosure {
+private:
+  BoolObjectClosure* _is_alive;
+public:
+  CleanExtraDataKlassClosure(BoolObjectClosure* is_alive) : _is_alive(is_alive) {}
+  bool is_live(Method* m) {
+    return m->method_holder()->is_loader_alive(_is_alive);
+  }
+};
+
+// Check for entries that reference a redefined method
+class CleanExtraDataMethodClosure : public CleanExtraDataClosure {
+public:
+  CleanExtraDataMethodClosure() {}
+  bool is_live(Method* m) {
+    return m->on_stack();
+  }
+};
+
+
+// Remove SpeculativeTrapData entries that reference an unloaded or
+// redefined method
+void MethodData::clean_extra_data(CleanExtraDataClosure* cl) {
   DataLayout* dp  = extra_data_base();
   DataLayout* end = extra_data_limit();
 
@@ -1572,7 +1598,7 @@
       SpeculativeTrapData* data = new SpeculativeTrapData(dp);
       Method* m = data->method();
       assert(m != NULL, "should have a method");
-      if (!m->method_holder()->is_loader_alive(is_alive)) {
+      if (!cl->is_live(m)) {
         // "shift" accumulates the number of cells for dead
         // SpeculativeTrapData entries that have been seen so
         // far. Following entries must be shifted left by that many
@@ -1603,9 +1629,9 @@
   }
 }
 
-// Verify there's no unloaded method referenced by a
+// Verify there's no unloaded or redefined method referenced by a
 // SpeculativeTrapData entry
-void MethodData::verify_extra_data_clean(BoolObjectClosure* is_alive) {
+void MethodData::verify_extra_data_clean(CleanExtraDataClosure* cl) {
 #ifdef ASSERT
   DataLayout* dp  = extra_data_base();
   DataLayout* end = extra_data_limit();
@@ -1615,7 +1641,7 @@
     case DataLayout::speculative_trap_data_tag: {
       SpeculativeTrapData* data = new SpeculativeTrapData(dp);
       Method* m = data->method();
-      assert(m != NULL && m->method_holder()->is_loader_alive(is_alive), "Method should exist");
+      assert(m != NULL && cl->is_live(m), "Method should exist");
       break;
     }
     case DataLayout::bit_data_tag:
@@ -1641,6 +1667,19 @@
     parameters->clean_weak_klass_links(is_alive);
   }
 
-  clean_extra_data(is_alive);
-  verify_extra_data_clean(is_alive);
+  CleanExtraDataKlassClosure cl(is_alive);
+  clean_extra_data(&cl);
+  verify_extra_data_clean(&cl);
+}
+
+void MethodData::clean_weak_method_links() {
+  for (ProfileData* data = first_data();
+       is_valid(data);
+       data = next_data(data)) {
+    data->clean_weak_method_links();
+  }
+
+  CleanExtraDataMethodClosure cl;
+  clean_extra_data(&cl);
+  verify_extra_data_clean(&cl);
 }
diff --git a/src/share/vm/oops/methodData.hpp b/src/share/vm/oops/methodData.hpp
index dd4ca1f..3cd7cd6 100644
--- a/src/share/vm/oops/methodData.hpp
+++ b/src/share/vm/oops/methodData.hpp
@@ -251,6 +251,9 @@
 
   // GC support
   void clean_weak_klass_links(BoolObjectClosure* cl);
+
+  // Redefinition support
+  void clean_weak_method_links();
 };
 
 
@@ -508,6 +511,9 @@
   // GC support
   virtual void clean_weak_klass_links(BoolObjectClosure* is_alive_closure) {}
 
+  // Redefinition support
+  virtual void clean_weak_method_links() {}
+
   // CI translation: ProfileData can represent both MethodDataOop data
   // as well as CIMethodData data. This function is provided for translating
   // an oop in a ProfileData to the ci equivalent. Generally speaking,
@@ -2030,6 +2036,7 @@
 //
 
 CC_INTERP_ONLY(class BytecodeInterpreter;)
+class CleanExtraDataClosure;
 
 class MethodData : public Metadata {
   friend class VMStructs;
@@ -2183,9 +2190,9 @@
   static bool profile_parameters_jsr292_only();
   static bool profile_all_parameters();
 
-  void clean_extra_data(BoolObjectClosure* is_alive);
+  void clean_extra_data(CleanExtraDataClosure* cl);
   void clean_extra_data_helper(DataLayout* dp, int shift, bool reset = false);
-  void verify_extra_data_clean(BoolObjectClosure* is_alive);
+  void verify_extra_data_clean(CleanExtraDataClosure* cl);
 
 public:
   static int header_size() {
@@ -2477,6 +2484,8 @@
   static bool profile_return_jsr292_only();
 
   void clean_method_data(BoolObjectClosure* is_alive);
+
+  void clean_weak_method_links();
 };
 
 #endif // SHARE_VM_OOPS_METHODDATAOOP_HPP
diff --git a/src/share/vm/oops/objArrayKlass.cpp b/src/share/vm/oops/objArrayKlass.cpp
index a4c51d0..8049209 100644
--- a/src/share/vm/oops/objArrayKlass.cpp
+++ b/src/share/vm/oops/objArrayKlass.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -189,7 +189,7 @@
     if (length <= arrayOopDesc::max_array_length(T_OBJECT)) {
       int size = objArrayOopDesc::object_size(length);
       KlassHandle h_k(THREAD, this);
-      return (objArrayOop)CollectedHeap::array_allocate(h_k, size, length, CHECK_NULL);
+      return (objArrayOop)CollectedHeap::array_allocate(h_k, size, length, THREAD);
     } else {
       report_java_out_of_memory("Requested array size exceeds VM limit");
       JvmtiExport::post_array_size_exhausted();
@@ -362,11 +362,11 @@
   if (or_null) {
     return ak->array_klass_or_null(n);
   }
-  return ak->array_klass(n, CHECK_NULL);
+  return ak->array_klass(n, THREAD);
 }
 
 Klass* ObjArrayKlass::array_klass_impl(bool or_null, TRAPS) {
-  return array_klass_impl(or_null, dimension() +  1, CHECK_NULL);
+  return array_klass_impl(or_null, dimension() +  1, THREAD);
 }
 
 bool ObjArrayKlass::can_be_primary_super_slow() const {
@@ -657,7 +657,7 @@
       if (i > max_objArray_print_length) {
         st->print("..."); break;
       }
-      st->print(" "INTPTR_FORMAT, (intptr_t)(void*)objArrayOop(obj)->obj_at(i));
+      st->print(" " INTPTR_FORMAT, (intptr_t)(void*)objArrayOop(obj)->obj_at(i));
     }
     st->print(" }");
   }
diff --git a/src/share/vm/oops/oop.cpp b/src/share/vm/oops/oop.cpp
index 1be5781..3df79d4 100644
--- a/src/share/vm/oops/oop.cpp
+++ b/src/share/vm/oops/oop.cpp
@@ -46,7 +46,7 @@
 
 void oopDesc::print_address_on(outputStream* st) const {
   if (PrintOopAddress) {
-    st->print("{"INTPTR_FORMAT"}", this);
+    st->print("{" INTPTR_FORMAT "}", this);
   }
 }
 
diff --git a/src/share/vm/oops/oopsHierarchy.hpp b/src/share/vm/oops/oopsHierarchy.hpp
index ef0d2ed..b6c12fa 100644
--- a/src/share/vm/oops/oopsHierarchy.hpp
+++ b/src/share/vm/oops/oopsHierarchy.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 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
@@ -112,9 +112,7 @@
 
   // Assignment
   oop& operator=(const oop& o)                            { _o = o.obj(); return *this; }
-#ifndef SOLARIS
   volatile oop& operator=(const oop& o) volatile          { _o = o.obj(); return *this; }
-#endif
   volatile oop& operator=(const volatile oop& o) volatile { _o = o.obj(); return *this; }
 
   // Explict user conversions
@@ -123,11 +121,10 @@
   operator void* () const volatile    { return (void *)obj(); }
 #endif
   operator HeapWord* () const         { return (HeapWord*)obj(); }
-  operator oopDesc* () const          { return obj(); }
+  operator oopDesc* () const volatile { return obj(); }
   operator intptr_t* () const         { return (intptr_t*)obj(); }
   operator PromotedObject* () const   { return (PromotedObject*)obj(); }
-  operator markOop () const           { return markOop(obj()); }
-
+  operator markOop () const volatile  { return markOop(obj()); }
   operator address   () const         { return (address)obj(); }
 
   // from javaCalls.cpp
@@ -161,11 +158,10 @@
             oop::operator=(o);                                             \
             return *this;                                                  \
        }                                                                   \
-       NOT_SOLARIS(                                                        \
        volatile type##Oop& operator=(const type##Oop& o) volatile {        \
             (void)const_cast<oop&>(oop::operator=(o));                     \
             return *this;                                                  \
-       })                                                                  \
+       }                                                                   \
        volatile type##Oop& operator=(const volatile type##Oop& o) volatile {\
             (void)const_cast<oop&>(oop::operator=(o));                     \
             return *this;                                                  \
diff --git a/src/share/vm/oops/typeArrayKlass.cpp b/src/share/vm/oops/typeArrayKlass.cpp
index 7cc9475..d69267d 100644
--- a/src/share/vm/oops/typeArrayKlass.cpp
+++ b/src/share/vm/oops/typeArrayKlass.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -191,7 +191,7 @@
   if (or_null) {
     return h_ak->array_klass_or_null(n);
   }
-  return h_ak->array_klass(n, CHECK_NULL);
+  return h_ak->array_klass(n, THREAD);
 }
 
 Klass* TypeArrayKlass::array_klass_impl(bool or_null, TRAPS) {
diff --git a/src/share/vm/oops/typeArrayOop.hpp b/src/share/vm/oops/typeArrayOop.hpp
index 57c305d..71c0350 100644
--- a/src/share/vm/oops/typeArrayOop.hpp
+++ b/src/share/vm/oops/typeArrayOop.hpp
@@ -129,7 +129,7 @@
   Metadata* metadata_at(int which) const {
     return (Metadata*)*long_at_addr(which); }
   void metadata_at_put(int which, Metadata* contents) {
-    *long_at_addr(which) = (long)contents;
+    *long_at_addr(which) = (jlong)contents;
   }
 #else
   Metadata* metadata_at(int which) const {
diff --git a/src/share/vm/opto/buildOopMap.cpp b/src/share/vm/opto/buildOopMap.cpp
index 9f2dd67..4f7c42e 100644
--- a/src/share/vm/opto/buildOopMap.cpp
+++ b/src/share/vm/opto/buildOopMap.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -629,7 +629,7 @@
     // last block as his only undone child, we can move the OopFlow from the
     // pred to this block.  Otherwise we have to grab a new OopFlow.
     OopFlow *flow = NULL;       // Flag for finding optimized flow
-    Block *pred = (Block*)0xdeadbeef;
+    Block *pred = (Block*)((intptr_t)0xdeadbeef);
     // Scan this block's preds to find a done predecessor
     for (uint j = 1; j < b->num_preds(); j++) {
       Block* p = _cfg->get_block_for_node(b->pred(j));
diff --git a/src/share/vm/opto/callnode.cpp b/src/share/vm/opto/callnode.cpp
index 0320e31..a3de53e 100644
--- a/src/share/vm/opto/callnode.cpp
+++ b/src/share/vm/opto/callnode.cpp
@@ -340,7 +340,7 @@
     const Type *t = n->bottom_type();
     switch (t->base()) {
     case Type::Int:
-      st->print(" %s%d]=#"INT32_FORMAT,msg,i,t->is_int()->get_con());
+      st->print(" %s%d]=#" INT32_FORMAT,msg,i,t->is_int()->get_con());
       break;
     case Type::AnyPtr:
       assert( t == TypePtr::NULL_PTR || n->in_dump(), "" );
@@ -369,7 +369,7 @@
       st->print(" %s%d]=#%fF",msg,i,t->is_float_constant()->_f);
       break;
     case Type::Long:
-      st->print(" %s%d]=#"INT64_FORMAT,msg,i,(int64_t)(t->is_long()->get_con()));
+      st->print(" %s%d]=#" INT64_FORMAT,msg,i,(int64_t)(t->is_long()->get_con()));
       break;
     case Type::Half:
     case Type::Top:
diff --git a/src/share/vm/opto/cfgnode.cpp b/src/share/vm/opto/cfgnode.cpp
index de5eec8..bd79eee 100644
--- a/src/share/vm/opto/cfgnode.cpp
+++ b/src/share/vm/opto/cfgnode.cpp
@@ -2016,6 +2016,7 @@
   uint ideal_reg = _type->ideal_reg();
   assert( ideal_reg != Node::NotAMachineReg, "invalid type at Phi" );
   if( ideal_reg == 0 ) return RegMask::Empty;
+  assert(ideal_reg != Op_RegFlags, "flags register is not spillable");
   return *(Compile::current()->matcher()->idealreg2spillmask[ideal_reg]);
 }
 
diff --git a/src/share/vm/opto/chaitin.cpp b/src/share/vm/opto/chaitin.cpp
index 5930650..ec318c5 100644
--- a/src/share/vm/opto/chaitin.cpp
+++ b/src/share/vm/opto/chaitin.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -338,8 +338,8 @@
   _alternate = 0;
   _matcher._allocation_started = true;
 
-  ResourceArea split_arena;     // Arena for Split local resources
-  ResourceArea live_arena;      // Arena for liveness & IFG info
+  ResourceArea split_arena(mtCompiler);     // Arena for Split local resources
+  ResourceArea live_arena(mtCompiler);      // Arena for liveness & IFG info
   ResourceMark rm(&live_arena);
 
   // Need live-ness for the IFG; need the IFG for coalescing.  If the
@@ -755,7 +755,7 @@
         const RegMask &rm = n->out_RegMask();
         lrg.AND( rm );
 
-        int ireg = n->ideal_reg();
+        uint ireg = n->ideal_reg();
         assert( !n->bottom_type()->isa_oop_ptr() || ireg == Op_RegP,
                 "oops must be in Op_RegP's" );
 
@@ -961,7 +961,7 @@
 
         // Check for bound register masks
         const RegMask &lrgmask = lrg.mask();
-        int kreg = n->in(k)->ideal_reg();
+        uint kreg = n->in(k)->ideal_reg();
         bool is_vect = RegMask::is_vector(kreg);
         assert(n->in(k)->bottom_type()->isa_vect() == NULL ||
                is_vect || kreg == Op_RegD || kreg == Op_RegL,
diff --git a/src/share/vm/opto/coalesce.cpp b/src/share/vm/opto/coalesce.cpp
index c7f9527..c675445 100644
--- a/src/share/vm/opto/coalesce.cpp
+++ b/src/share/vm/opto/coalesce.cpp
@@ -25,6 +25,7 @@
 #include "precompiled.hpp"
 #include "memory/allocation.inline.hpp"
 #include "opto/block.hpp"
+#include "opto/c2compiler.hpp"
 #include "opto/cfgnode.hpp"
 #include "opto/chaitin.hpp"
 #include "opto/coalesce.hpp"
@@ -292,7 +293,18 @@
               // Copy any flags as well
               _phc.clone_projs(pred, pred->end_idx(), m, copy, _phc._lrg_map);
             } else {
-              const RegMask *rm = C->matcher()->idealreg2spillmask[m->ideal_reg()];
+              int ireg = m->ideal_reg();
+              if (ireg == 0 || ireg == Op_RegFlags) {
+                if (C->subsume_loads()) {
+                  C->record_failure(C2Compiler::retry_no_subsuming_loads());
+                } else {
+                  assert(false, err_msg("attempted to spill a non-spillable item: %d: %s, ireg = %d",
+                                        m->_idx, m->Name(), ireg));
+                  C->record_method_not_compilable("attempted to spill a non-spillable item");
+                }
+                return;
+              }
+              const RegMask *rm = C->matcher()->idealreg2spillmask[ireg];
               copy = new (C) MachSpillCopyNode(m, *rm, *rm);
               // Find a good place to insert.  Kinda tricky, use a subroutine
               insert_copy_with_overlap(pred,copy,phi_name,src_name);
@@ -326,7 +338,14 @@
               b->insert_node(copy, l++);
               l += _phc.clone_projs(b, l, m, copy, _phc._lrg_map);
             } else {
-              const RegMask *rm = C->matcher()->idealreg2spillmask[m->ideal_reg()];
+              int ireg = m->ideal_reg();
+              if (ireg == 0 || ireg == Op_RegFlags) {
+                assert(false, err_msg("attempted to spill a non-spillable item: %d: %s, ireg = %d",
+                                      m->_idx, m->Name(), ireg));
+                C->record_method_not_compilable("attempted to spill a non-spillable item");
+                return;
+              }
+              const RegMask *rm = C->matcher()->idealreg2spillmask[ireg];
               copy = new (C) MachSpillCopyNode(m, *rm, *rm);
               // Insert the copy in the basic block, just before us
               b->insert_node(copy, l++);
@@ -373,7 +392,14 @@
               if( k < b->_num_succs )
                 continue;     // Live out; do not pre-split
               // Split the lrg at this use
-              const RegMask *rm = C->matcher()->idealreg2spillmask[inp->ideal_reg()];
+              int ireg = inp->ideal_reg();
+              if (ireg == 0 || ireg == Op_RegFlags) {
+                assert(false, err_msg("attempted to spill a non-spillable item: %d: %s, ireg = %d",
+                                      inp->_idx, inp->Name(), ireg));
+                C->record_method_not_compilable("attempted to spill a non-spillable item");
+                return;
+              }
+              const RegMask *rm = C->matcher()->idealreg2spillmask[ireg];
               Node *copy = new (C) MachSpillCopyNode( inp, *rm, *rm );
               // Insert the copy in the use-def chain
               n->set_req(inpidx, copy );
diff --git a/src/share/vm/opto/compile.cpp b/src/share/vm/opto/compile.cpp
index 439e55e..130a059 100644
--- a/src/share/vm/opto/compile.cpp
+++ b/src/share/vm/opto/compile.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -2392,8 +2392,8 @@
   print_method(PHASE_FINAL_CODE);
 
   // He's dead, Jim.
-  _cfg     = (PhaseCFG*)0xdeadbeef;
-  _regalloc = (PhaseChaitin*)0xdeadbeef;
+  _cfg     = (PhaseCFG*)((intptr_t)0xdeadbeef);
+  _regalloc = (PhaseChaitin*)((intptr_t)0xdeadbeef);
 }
 
 
@@ -3480,7 +3480,7 @@
     _root->verify_edges(visited);
     if (no_dead_code) {
       // Now make sure that no visited node is used by an unvisited node.
-      bool dead_nodes = 0;
+      bool dead_nodes = false;
       Unique_Node_List checked(area);
       while (visited.size() > 0) {
         Node* n = visited.pop();
@@ -3491,14 +3491,16 @@
           if (visited.member(use))  continue;  // already in the graph
           if (use->is_Con())        continue;  // a dead ConNode is OK
           // At this point, we have found a dead node which is DU-reachable.
-          if (dead_nodes++ == 0)
+          if (!dead_nodes) {
             tty->print_cr("*** Dead nodes reachable via DU edges:");
+            dead_nodes = true;
+          }
           use->dump(2);
           tty->print_cr("---");
           checked.push(use);  // No repeats; pretend it is now checked.
         }
       }
-      assert(dead_nodes == 0, "using nodes must be reachable from root");
+      assert(!dead_nodes, "using nodes must be reachable from root");
     }
   }
 }
diff --git a/src/share/vm/opto/escape.cpp b/src/share/vm/opto/escape.cpp
index bcd2e78..77c49ba 100644
--- a/src/share/vm/opto/escape.cpp
+++ b/src/share/vm/opto/escape.cpp
@@ -2016,8 +2016,10 @@
         // Check for unsafe oop field access
         for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
           int opcode = n->fast_out(i)->Opcode();
-          if (opcode == Op_StoreP || opcode == Op_LoadP ||
-              opcode == Op_StoreN || opcode == Op_LoadN) {
+          if (opcode == Op_StoreP          || opcode == Op_StoreN ||
+              opcode == Op_LoadP           || opcode == Op_LoadN  ||
+              opcode == Op_GetAndSetP      || opcode == Op_GetAndSetN ||
+              opcode == Op_CompareAndSwapP || opcode == Op_CompareAndSwapN) {
             bt = T_OBJECT;
             (*unsafe) = true;
             break;
@@ -2037,8 +2039,10 @@
       // Allocation initialization, ThreadLocal field access, unsafe access
       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
         int opcode = n->fast_out(i)->Opcode();
-        if (opcode == Op_StoreP || opcode == Op_LoadP ||
-            opcode == Op_StoreN || opcode == Op_LoadN) {
+        if (opcode == Op_StoreP          || opcode == Op_StoreN ||
+            opcode == Op_LoadP           || opcode == Op_LoadN  ||
+            opcode == Op_GetAndSetP      || opcode == Op_GetAndSetN ||
+            opcode == Op_CompareAndSwapP || opcode == Op_CompareAndSwapN) {
           bt = T_OBJECT;
           break;
         }
diff --git a/src/share/vm/opto/gcm.cpp b/src/share/vm/opto/gcm.cpp
index c574998..a3e6b1a 100644
--- a/src/share/vm/opto/gcm.cpp
+++ b/src/share/vm/opto/gcm.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1375,7 +1375,7 @@
   }
 #endif
   // Dead.
-  _node_latency = (GrowableArray<uint> *)0xdeadbeef;
+  _node_latency = (GrowableArray<uint> *)((intptr_t)0xdeadbeef);
 }
 
 bool PhaseCFG::do_global_code_motion() {
diff --git a/src/share/vm/opto/idealGraphPrinter.cpp b/src/share/vm/opto/idealGraphPrinter.cpp
index b222526..65c1ac9 100644
--- a/src/share/vm/opto/idealGraphPrinter.cpp
+++ b/src/share/vm/opto/idealGraphPrinter.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -612,7 +612,7 @@
     }
 #endif
 
-    if (_chaitin && _chaitin != (PhaseChaitin *)0xdeadbeef) {
+    if (_chaitin && _chaitin != (PhaseChaitin *)((intptr_t)0xdeadbeef)) {
       buffer[0] = 0;
       _chaitin->dump_register(node, buffer);
       print_prop("reg", buffer);
diff --git a/src/share/vm/opto/ifnode.cpp b/src/share/vm/opto/ifnode.cpp
index c1ee196..3101455 100644
--- a/src/share/vm/opto/ifnode.cpp
+++ b/src/share/vm/opto/ifnode.cpp
@@ -234,6 +234,13 @@
       predicate_proj = proj;
     }
   }
+
+  // If all the defs of the phi are the same constant, we already have the desired end state.
+  // Skip the split that would create empty phi and region nodes.
+  if((r->req() - req_c) == 1) {
+    return NULL;
+  }
+
   Node* predicate_c = NULL;
   Node* predicate_x = NULL;
   bool counted_loop = r->is_CountedLoop();
@@ -446,6 +453,9 @@
 // offset.  Return 2 if we had to negate the test.  Index is NULL if the check
 // is versus a constant.
 int IfNode::is_range_check(Node* &range, Node* &index, jint &offset) {
+  if (outcnt() != 2) {
+    return 0;
+  }
   Node* b = in(1);
   if (b == NULL || !b->is_Bool())  return 0;
   BoolNode* bn = b->as_Bool();
diff --git a/src/share/vm/opto/library_call.cpp b/src/share/vm/opto/library_call.cpp
index d708499..105f8c0 100644
--- a/src/share/vm/opto/library_call.cpp
+++ b/src/share/vm/opto/library_call.cpp
@@ -6026,7 +6026,7 @@
   }
 
   assert(UseMontgomeryMultiplyIntrinsic, "not implemented on this platform");
-  const char* stubName = "montgomery_square";
+  const char* stubName = "montgomery_multiply";
 
   assert(callee()->signature()->size() == 7, "montgomeryMultiply has 7 parameters");
 
@@ -6068,11 +6068,21 @@
     Node* n_start = array_element_address(n, intcon(0), n_elem);
     Node* m_start = array_element_address(m, intcon(0), m_elem);
 
-    Node* call = make_runtime_call(RC_LEAF,
-                                   OptoRuntime::montgomeryMultiply_Type(),
-                                   stubAddr, stubName, TypePtr::BOTTOM,
-                                   a_start, b_start, n_start, len, inv, top(),
-                                   m_start);
+    Node* call = NULL;
+    if (CCallingConventionRequiresIntsAsLongs) {
+      Node* len_I2L = ConvI2L(len);
+      call = make_runtime_call(RC_LEAF,
+                               OptoRuntime::montgomeryMultiply_Type(),
+                               stubAddr, stubName, TypePtr::BOTTOM,
+                               a_start, b_start, n_start, len_I2L XTOP, inv,
+                               top(), m_start);
+    } else {
+      call = make_runtime_call(RC_LEAF,
+                               OptoRuntime::montgomeryMultiply_Type(),
+                               stubAddr, stubName, TypePtr::BOTTOM,
+                               a_start, b_start, n_start, len, inv, top(),
+                               m_start);
+    }
     set_result(m);
   }
 
@@ -6122,11 +6132,22 @@
     Node* n_start = array_element_address(n, intcon(0), n_elem);
     Node* m_start = array_element_address(m, intcon(0), m_elem);
 
-    Node* call = make_runtime_call(RC_LEAF,
-                                   OptoRuntime::montgomerySquare_Type(),
-                                   stubAddr, stubName, TypePtr::BOTTOM,
-                                   a_start, n_start, len, inv, top(),
-                                   m_start);
+    Node* call = NULL;
+    if (CCallingConventionRequiresIntsAsLongs) {
+      Node* len_I2L = ConvI2L(len);
+      call = make_runtime_call(RC_LEAF,
+                               OptoRuntime::montgomerySquare_Type(),
+                               stubAddr, stubName, TypePtr::BOTTOM,
+                               a_start, n_start, len_I2L XTOP, inv, top(),
+                               m_start);
+    } else {
+      call = make_runtime_call(RC_LEAF,
+                               OptoRuntime::montgomerySquare_Type(),
+                               stubAddr, stubName, TypePtr::BOTTOM,
+                               a_start, n_start, len, inv, top(),
+                               m_start);
+    }
+
     set_result(m);
   }
 
@@ -6204,10 +6225,16 @@
   // Call the stub.
   address stubAddr = StubRoutines::updateBytesCRC32();
   const char *stubName = "updateBytesCRC32";
-
-  Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
-                                 stubAddr, stubName, TypePtr::BOTTOM,
-                                 crc, src_start, length);
+  Node* call;
+  if (CCallingConventionRequiresIntsAsLongs) {
+   call =  make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
+                             stubAddr, stubName, TypePtr::BOTTOM,
+                             crc XTOP, src_start, length XTOP);
+  } else {
+    call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
+                             stubAddr, stubName, TypePtr::BOTTOM,
+                             crc, src_start, length);
+  }
   Node* result = _gvn.transform(new (C) ProjNode(call, TypeFunc::Parms));
   set_result(result);
   return true;
@@ -6236,10 +6263,16 @@
   // Call the stub.
   address stubAddr = StubRoutines::updateBytesCRC32();
   const char *stubName = "updateBytesCRC32";
-
-  Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
-                                 stubAddr, stubName, TypePtr::BOTTOM,
-                                 crc, src_start, length);
+  Node* call;
+  if (CCallingConventionRequiresIntsAsLongs) {
+    call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
+                      stubAddr, stubName, TypePtr::BOTTOM,
+                      crc XTOP, src_start, length XTOP);
+  } else {
+    call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
+                             stubAddr, stubName, TypePtr::BOTTOM,
+                             crc, src_start, length);
+  }
   Node* result = _gvn.transform(new (C) ProjNode(call, TypeFunc::Parms));
   set_result(result);
   return true;
diff --git a/src/share/vm/opto/loopPredicate.cpp b/src/share/vm/opto/loopPredicate.cpp
index ae3437a..5d2b469 100644
--- a/src/share/vm/opto/loopPredicate.cpp
+++ b/src/share/vm/opto/loopPredicate.cpp
@@ -869,7 +869,7 @@
       Node*          idx    = cmp->in(1);
       assert(!invar.is_invariant(idx), "index is variant");
       Node* rng = cmp->in(2);
-      assert(rng->Opcode() == Op_LoadRange || _igvn.type(rng)->is_int() >= 0, "must be");
+      assert(rng->Opcode() == Op_LoadRange || _igvn.type(rng)->is_int()->_lo >= 0, "must be");
       assert(invar.is_invariant(rng), "range must be invariant");
       int scale    = 1;
       Node* offset = zero;
diff --git a/src/share/vm/opto/loopopts.cpp b/src/share/vm/opto/loopopts.cpp
index e19f35a..0452a23 100644
--- a/src/share/vm/opto/loopopts.cpp
+++ b/src/share/vm/opto/loopopts.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -309,6 +309,7 @@
       }
       return NULL;
     }
+    assert(m->is_Phi() || is_dominator(get_ctrl(m), n_ctrl), "m has strange control");
   }
 
   return n_ctrl;
@@ -609,6 +610,7 @@
   // Now replace all Phis with CMOV's
   Node *cmov_ctrl = iff->in(0);
   uint flip = (lp->Opcode() == Op_IfTrue);
+  Node_List wq;
   while (1) {
     PhiNode* phi = NULL;
     for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
@@ -623,17 +625,21 @@
     if (PrintOpto && VerifyLoopOptimizations) tty->print_cr("CMOV");
 #endif
     // Move speculative ops
-    for (uint j = 1; j < region->req(); j++) {
-      Node *proj = region->in(j);
-      Node *inp = phi->in(j);
-      if (get_ctrl(inp) == proj) { // Found local op
+    wq.push(phi);
+    while (wq.size() > 0) {
+      Node *n = wq.pop();
+      for (uint j = 1; j < n->req(); j++) {
+        Node* m = n->in(j);
+        if (m != NULL && !is_dominator(get_ctrl(m), cmov_ctrl)) {
 #ifndef PRODUCT
-        if (PrintOpto && VerifyLoopOptimizations) {
-          tty->print("  speculate: ");
-          inp->dump();
-        }
+          if (PrintOpto && VerifyLoopOptimizations) {
+            tty->print("  speculate: ");
+            m->dump();
+          }
 #endif
-        set_ctrl(inp, cmov_ctrl);
+          set_ctrl(m, cmov_ctrl);
+          wq.push(m);
+        }
       }
     }
     Node *cmov = CMoveNode::make( C, cmov_ctrl, iff->in(1), phi->in(1+flip), phi->in(2-flip), _igvn.type(phi) );
diff --git a/src/share/vm/opto/machnode.cpp b/src/share/vm/opto/machnode.cpp
index 69139e1..f93e178 100644
--- a/src/share/vm/opto/machnode.cpp
+++ b/src/share/vm/opto/machnode.cpp
@@ -619,6 +619,7 @@
   }
 
   // Values outside the domain represent debug info
+  assert(in(idx)->ideal_reg() != Op_RegFlags, "flags register is not spillable");
   return *Compile::current()->matcher()->idealreg2spillmask[in(idx)->ideal_reg()];
 }
 
diff --git a/src/share/vm/opto/macro.cpp b/src/share/vm/opto/macro.cpp
index d1e1f32..cf2ba77 100644
--- a/src/share/vm/opto/macro.cpp
+++ b/src/share/vm/opto/macro.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1775,7 +1775,7 @@
       i_o = pf_phi_abio;
    } else if( UseTLAB && AllocatePrefetchStyle == 3 ) {
       // Insert a prefetch for each allocation.
-      // This code is used for Sparc with BIS.
+      // This code is used to generate 1 prefetch instruction per cache line.
       Node *pf_region = new (C) RegionNode(3);
       Node *pf_phi_rawmem = new (C) PhiNode( pf_region, Type::MEMORY,
                                              TypeRawPtr::BOTTOM );
@@ -1791,6 +1791,8 @@
       transform_later(cache_adr);
       cache_adr = new (C) CastP2XNode(needgc_false, cache_adr);
       transform_later(cache_adr);
+      // Address is aligned to execute prefetch to the beginning of cache line size
+      // (it is important when BIS instruction is used on SPARC as prefetch).
       Node* mask = _igvn.MakeConX(~(intptr_t)(step_size-1));
       cache_adr = new (C) AndXNode(cache_adr, mask);
       transform_later(cache_adr);
diff --git a/src/share/vm/opto/matcher.cpp b/src/share/vm/opto/matcher.cpp
index d6ee92f..b4dda48 100644
--- a/src/share/vm/opto/matcher.cpp
+++ b/src/share/vm/opto/matcher.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -79,7 +79,7 @@
   _register_save_type(register_save_type),
   _ruleName(ruleName),
   _allocation_started(false),
-  _states_arena(Chunk::medium_size),
+  _states_arena(Chunk::medium_size, mtCompiler),
   _visited(&_states_arena),
   _shared(&_states_arena),
   _dontcare(&_states_arena) {
@@ -95,6 +95,7 @@
   idealreg2spillmask  [Op_VecD] = NULL;
   idealreg2spillmask  [Op_VecX] = NULL;
   idealreg2spillmask  [Op_VecY] = NULL;
+  idealreg2spillmask  [Op_RegFlags] = NULL;
 
   idealreg2debugmask  [Op_RegI] = NULL;
   idealreg2debugmask  [Op_RegN] = NULL;
@@ -106,6 +107,7 @@
   idealreg2debugmask  [Op_VecD] = NULL;
   idealreg2debugmask  [Op_VecX] = NULL;
   idealreg2debugmask  [Op_VecY] = NULL;
+  idealreg2debugmask  [Op_RegFlags] = NULL;
 
   idealreg2mhdebugmask[Op_RegI] = NULL;
   idealreg2mhdebugmask[Op_RegN] = NULL;
@@ -117,6 +119,7 @@
   idealreg2mhdebugmask[Op_VecD] = NULL;
   idealreg2mhdebugmask[Op_VecX] = NULL;
   idealreg2mhdebugmask[Op_VecY] = NULL;
+  idealreg2mhdebugmask[Op_RegFlags] = NULL;
 
   debug_only(_mem_node = NULL;)   // Ideal memory node consumed by mach node
 }
@@ -193,7 +196,7 @@
   const TypeTuple *range = C->tf()->range();
   if( range->cnt() > TypeFunc::Parms ) { // If not a void function
     // Get ideal-register return type
-    int ireg = range->field_at(TypeFunc::Parms)->ideal_reg();
+    uint ireg = range->field_at(TypeFunc::Parms)->ideal_reg();
     // Get machine return register
     uint sop = C->start()->Opcode();
     OptoRegPair regs = return_value(ireg, false);
diff --git a/src/share/vm/opto/matcher.hpp b/src/share/vm/opto/matcher.hpp
index 66d4a0a..2f2dc5b 100644
--- a/src/share/vm/opto/matcher.hpp
+++ b/src/share/vm/opto/matcher.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -283,8 +283,8 @@
   }
 
   // Vector ideal reg
-  static const int vector_ideal_reg(int len);
-  static const int vector_shift_count_ideal_reg(int len);
+  static const uint vector_ideal_reg(int len);
+  static const uint vector_shift_count_ideal_reg(int len);
 
   // CPU supports misaligned vectors store/load.
   static const bool misaligned_vectors_ok();
@@ -326,8 +326,8 @@
   virtual OptoReg::Name return_addr() const;
   RegMask              _return_addr_mask;
   // Return value register.  On Intel it is EAX.  On Sparc i0/o0.
-  static OptoRegPair   return_value(int ideal_reg, bool is_outgoing);
-  static OptoRegPair c_return_value(int ideal_reg, bool is_outgoing);
+  static OptoRegPair   return_value(uint ideal_reg, bool is_outgoing);
+  static OptoRegPair c_return_value(uint ideal_reg, bool is_outgoing);
   RegMask                     _return_value_mask;
   // Inline Cache Register
   static OptoReg::Name  inline_cache_reg();
diff --git a/src/share/vm/opto/output.cpp b/src/share/vm/opto/output.cpp
index 287d8d1..ebd68de 100644
--- a/src/share/vm/opto/output.cpp
+++ b/src/share/vm/opto/output.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -2687,7 +2687,7 @@
   }
 
   Node *kill = def;             // Rename 'def' to more descriptive 'kill'
-  debug_only( def = (Node*)0xdeadbeef; )
+  debug_only( def = (Node*)((intptr_t)0xdeadbeef); )
 
   // After some number of kills there _may_ be a later def
   Node *later_def = NULL;
diff --git a/src/share/vm/opto/reg_split.cpp b/src/share/vm/opto/reg_split.cpp
index cfcecad..af79891 100644
--- a/src/share/vm/opto/reg_split.cpp
+++ b/src/share/vm/opto/reg_split.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -59,7 +59,7 @@
   // If ideal reg doesn't exist we've got a bad schedule happening
   // that is forcing us to spill something that isn't spillable.
   // Bail rather than abort
-  int ireg = def->ideal_reg();
+  uint ireg = def->ideal_reg();
   if( ireg == 0 || ireg == Op_RegFlags ) {
     assert(false, "attempted to spill a non-spillable item");
     C->record_method_not_compilable("attempted to spill a non-spillable item");
@@ -1163,7 +1163,7 @@
         // Grab UP info for DEF
         const RegMask &dmask = n->out_RegMask();
         bool defup = dmask.is_UP();
-        int ireg = n->ideal_reg();
+        uint ireg = n->ideal_reg();
         bool is_vect = RegMask::is_vector(ireg);
         // Only split at Def if this is a HRP block or bound (and spilled once)
         if( !n->rematerialize() &&
diff --git a/src/share/vm/opto/runtime.cpp b/src/share/vm/opto/runtime.cpp
index 597580b..364152c 100644
--- a/src/share/vm/opto/runtime.cpp
+++ b/src/share/vm/opto/runtime.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -846,13 +846,24 @@
  */
 const TypeFunc* OptoRuntime::updateBytesCRC32_Type() {
   // create input type (domain)
-  int num_args      = 3;
+  int num_args = 3;
   int argcnt = num_args;
+  if (CCallingConventionRequiresIntsAsLongs) {
+    argcnt += 2;
+  }
   const Type** fields = TypeTuple::fields(argcnt);
   int argp = TypeFunc::Parms;
-  fields[argp++] = TypeInt::INT;        // crc
-  fields[argp++] = TypePtr::NOTNULL;    // src
-  fields[argp++] = TypeInt::INT;        // len
+  if (CCallingConventionRequiresIntsAsLongs) {
+    fields[argp++] = TypeLong::LONG;   // crc
+    fields[argp++] = Type::HALF;
+    fields[argp++] = TypePtr::NOTNULL; // src
+    fields[argp++] = TypeLong::LONG;   // len
+    fields[argp++] = Type::HALF;
+  } else {
+    fields[argp++] = TypeInt::INT;     // crc
+    fields[argp++] = TypePtr::NOTNULL; // src
+    fields[argp++] = TypeInt::INT;     // len
+  }
   assert(argp == TypeFunc::Parms+argcnt, "correct decoding");
   const TypeTuple* domain = TypeTuple::make(TypeFunc::Parms+argcnt, fields);
 
@@ -1003,12 +1014,20 @@
   // create input type (domain)
   int num_args      = 7;
   int argcnt = num_args;
+  if (CCallingConventionRequiresIntsAsLongs) {
+    argcnt++;                           // additional placeholder
+  }
   const Type** fields = TypeTuple::fields(argcnt);
   int argp = TypeFunc::Parms;
   fields[argp++] = TypePtr::NOTNULL;    // a
   fields[argp++] = TypePtr::NOTNULL;    // b
   fields[argp++] = TypePtr::NOTNULL;    // n
-  fields[argp++] = TypeInt::INT;        // len
+  if (CCallingConventionRequiresIntsAsLongs) {
+    fields[argp++] = TypeLong::LONG;    // len
+    fields[argp++] = TypeLong::HALF;    // placeholder
+  } else {
+    fields[argp++] = TypeInt::INT;      // len
+  }
   fields[argp++] = TypeLong::LONG;      // inv
   fields[argp++] = Type::HALF;
   fields[argp++] = TypePtr::NOTNULL;    // result
@@ -1027,11 +1046,19 @@
   // create input type (domain)
   int num_args      = 6;
   int argcnt = num_args;
+  if (CCallingConventionRequiresIntsAsLongs) {
+    argcnt++;                           // additional placeholder
+  }
   const Type** fields = TypeTuple::fields(argcnt);
   int argp = TypeFunc::Parms;
   fields[argp++] = TypePtr::NOTNULL;    // a
   fields[argp++] = TypePtr::NOTNULL;    // n
-  fields[argp++] = TypeInt::INT;        // len
+  if (CCallingConventionRequiresIntsAsLongs) {
+    fields[argp++] = TypeLong::LONG;    // len
+    fields[argp++] = TypeLong::HALF;    // placeholder
+  } else {
+    fields[argp++] = TypeInt::INT;      // len
+  }
   fields[argp++] = TypeLong::LONG;      // inv
   fields[argp++] = Type::HALF;
   fields[argp++] = TypePtr::NOTNULL;    // result
@@ -1218,17 +1245,23 @@
         force_unwind ? NULL : nm->handler_for_exception_and_pc(exception, pc);
 
       if (handler_address == NULL) {
-        Handle original_exception(thread, exception());
-        handler_address = SharedRuntime::compute_compiled_exc_handler(nm, pc, exception, force_unwind, true);
+        bool recursive_exception = false;
+        handler_address = SharedRuntime::compute_compiled_exc_handler(nm, pc, exception, force_unwind, true, recursive_exception);
         assert (handler_address != NULL, "must have compiled handler");
         // Update the exception cache only when the unwind was not forced
         // and there didn't happen another exception during the computation of the
-        // compiled exception handler.
-        if (!force_unwind && original_exception() == exception()) {
+        // compiled exception handler. Checking for exception oop equality is not
+        // sufficient because some exceptions are pre-allocated and reused.
+        if (!force_unwind && !recursive_exception) {
           nm->add_handler_for_exception_and_pc(exception,pc,handler_address);
         }
       } else {
-        assert(handler_address == SharedRuntime::compute_compiled_exc_handler(nm, pc, exception, force_unwind, true), "Must be the same");
+#ifdef ASSERT
+        bool recursive_exception = false;
+        address computed_address = SharedRuntime::compute_compiled_exc_handler(nm, pc, exception, force_unwind, true, recursive_exception);
+        assert(recursive_exception || (handler_address == computed_address), err_msg("Handler address inconsistency: " PTR_FORMAT " != " PTR_FORMAT,
+                 p2i(handler_address), p2i(computed_address)));
+#endif
       }
     }
 
diff --git a/src/share/vm/opto/split_if.cpp b/src/share/vm/opto/split_if.cpp
index f7f5529..94d680c 100644
--- a/src/share/vm/opto/split_if.cpp
+++ b/src/share/vm/opto/split_if.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -255,7 +255,7 @@
 Node *PhaseIdealLoop::spinup( Node *iff_dom, Node *new_false, Node *new_true, Node *use_blk, Node *def, small_cache *cache ) {
   if (use_blk->is_top())        // Handle dead uses
     return use_blk;
-  Node *prior_n = (Node*)0xdeadbeef;
+  Node *prior_n = (Node*)((intptr_t)0xdeadbeef);
   Node *n = use_blk;            // Get path input
   assert( use_blk != iff_dom, "" );
   // Here's the "spinup" the dominator tree loop.  Do a cache-check
@@ -302,7 +302,7 @@
   }
 
   // Update cache everywhere
-  prior_n = (Node*)0xdeadbeef;  // Reset IDOM walk
+  prior_n = (Node*)((intptr_t)0xdeadbeef);  // Reset IDOM walk
   n = use_blk;                  // Get path input
   // Spin-up the idom tree again, basically doing path-compression.
   // Insert cache entries along the way, so that if we ever hit this
diff --git a/src/share/vm/opto/type.cpp b/src/share/vm/opto/type.cpp
index 6076a56..7cf794a 100644
--- a/src/share/vm/opto/type.cpp
+++ b/src/share/vm/opto/type.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -51,7 +51,7 @@
 Dict* Type::_shared_type_dict = NULL;
 
 // Array which maps compiler types to Basic Types
-Type::TypeInfo Type::_type_info[Type::lastype] = {
+const Type::TypeInfo Type::_type_info[Type::lastype] = {
   { Bad,             T_ILLEGAL,    "bad",           false, Node::NotAMachineReg, relocInfo::none          },  // Bad
   { Control,         T_ILLEGAL,    "control",       false, 0,                    relocInfo::none          },  // Control
   { Bottom,          T_VOID,       "top",           false, 0,                    relocInfo::none          },  // Top
diff --git a/src/share/vm/opto/type.hpp b/src/share/vm/opto/type.hpp
index cf7857a..c0d5529 100644
--- a/src/share/vm/opto/type.hpp
+++ b/src/share/vm/opto/type.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -130,17 +130,17 @@
 
 private:
   typedef struct {
-    const TYPES                dual_type;
-    const BasicType            basic_type;
-    const char*                msg;
-    const bool                 isa_oop;
-    const int                  ideal_reg;
-    const relocInfo::relocType reloc;
+    TYPES                dual_type;
+    BasicType            basic_type;
+    const char*          msg;
+    bool                 isa_oop;
+    uint                 ideal_reg;
+    relocInfo::relocType reloc;
   } TypeInfo;
 
   // Dictionary of types shared among compilations.
   static Dict* _shared_type_dict;
-  static TypeInfo _type_info[];
+  static const TypeInfo _type_info[];
 
   static int uhash( const Type *const t );
   // Structural equality check.  Assumes that cmp() has already compared
@@ -407,7 +407,7 @@
 
   // Mapping from compiler type to VM BasicType
   BasicType basic_type() const       { return _type_info[_base].basic_type; }
-  int ideal_reg() const              { return _type_info[_base].ideal_reg; }
+  uint ideal_reg() const             { return _type_info[_base].ideal_reg; }
   const char* msg() const            { return _type_info[_base].msg; }
   bool isa_oop_ptr() const           { return _type_info[_base].isa_oop; }
   relocInfo::relocType reloc() const { return _type_info[_base].reloc; }
diff --git a/src/share/vm/prims/jni.cpp b/src/share/vm/prims/jni.cpp
index 95fd4d2..51b453e 100644
--- a/src/share/vm/prims/jni.cpp
+++ b/src/share/vm/prims/jni.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * Copyright (c) 2012 Red Hat, Inc.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -33,6 +33,7 @@
 #include "classfile/vmSymbols.hpp"
 #include "interpreter/linkResolver.hpp"
 #include "utilities/macros.hpp"
+#include "utilities/ostream.hpp"
 #if INCLUDE_ALL_GCS
 #include "gc_implementation/g1/g1SATBCardTableModRefBS.hpp"
 #endif // INCLUDE_ALL_GCS
@@ -3832,7 +3833,7 @@
   EntryProbe; \
   DT_VOID_RETURN_MARK(Get##Result##ArrayRegion); \
   typeArrayOop src = typeArrayOop(JNIHandles::resolve_non_null(array)); \
-  if (start < 0 || len < 0 || ((unsigned int)start + (unsigned int)len > (unsigned int)src->length())) { \
+  if (start < 0 || len < 0 || (start > src->length() - len)) { \
     THROW(vmSymbols::java_lang_ArrayIndexOutOfBoundsException()); \
   } else { \
     if (len > 0) { \
@@ -3916,7 +3917,7 @@
   EntryProbe; \
   DT_VOID_RETURN_MARK(Set##Result##ArrayRegion); \
   typeArrayOop dst = typeArrayOop(JNIHandles::resolve_non_null(array)); \
-  if (start < 0 || len < 0 || ((unsigned int)start + (unsigned int)len > (unsigned int)dst->length())) { \
+  if (start < 0 || len < 0 || (start > dst->length() - len)) { \
     THROW(vmSymbols::java_lang_ArrayIndexOutOfBoundsException()); \
   } else { \
     if (len > 0) { \
@@ -4200,7 +4201,7 @@
   DT_VOID_RETURN_MARK(GetStringRegion);
   oop s = JNIHandles::resolve_non_null(string);
   int s_len = java_lang_String::length(s);
-  if (start < 0 || len < 0 || start + len > s_len) {
+  if (start < 0 || len < 0 || start > s_len - len) {
     THROW(vmSymbols::java_lang_StringIndexOutOfBoundsException());
   } else {
     if (len > 0) {
@@ -4229,7 +4230,7 @@
   DT_VOID_RETURN_MARK(GetStringUTFRegion);
   oop s = JNIHandles::resolve_non_null(string);
   int s_len = java_lang_String::length(s);
-  if (start < 0 || len < 0 || start + len > s_len) {
+  if (start < 0 || len < 0 || start > s_len - len) {
     THROW(vmSymbols::java_lang_StringIndexOutOfBoundsException());
   } else {
     //%note jni_7
@@ -5093,6 +5094,7 @@
 void TestReserveMemorySpecial_test();
 void TestVirtualSpace_test();
 void TestMetaspaceAux_test();
+void SpaceManager_test_adjust_initial_chunk_size();
 void TestMetachunk_test();
 void TestVirtualSpaceNode_test();
 void TestNewSize_test();
@@ -5105,6 +5107,7 @@
 void TestBufferingOopClosure_test();
 void TestCodeCacheRemSet_test();
 void FreeRegionList_test();
+void ChunkManager_test_list_index();
 #endif
 
 void execute_internal_vm_tests() {
@@ -5125,6 +5128,7 @@
     run_unit_test(GuardedMemory::test_guarded_memory());
     run_unit_test(AltHashing::test_alt_hash());
     run_unit_test(test_loggc_filename());
+    run_unit_test(test_snprintf());
     run_unit_test(TestNewSize_test());
     run_unit_test(TestKlass_test());
     run_unit_test(Test_linked_list());
@@ -5137,6 +5141,8 @@
     run_unit_test(TestOldFreeSpaceCalculation_test());
     run_unit_test(TestG1BiasedArray_test());
     run_unit_test(HeapRegionRemSet::test_prt());
+    run_unit_test(SpaceManager_test_adjust_initial_chunk_size());
+    run_unit_test(ChunkManager_test_list_index());
     run_unit_test(TestBufferingOopClosure_test());
     run_unit_test(TestCodeCacheRemSet_test());
     if (UseG1GC) {
diff --git a/src/share/vm/prims/jvm.cpp b/src/share/vm/prims/jvm.cpp
index 36aa9cb..c9d8cc8 100644
--- a/src/share/vm/prims/jvm.cpp
+++ b/src/share/vm/prims/jvm.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -24,6 +24,7 @@
 
 #include "precompiled.hpp"
 #include "classfile/classLoader.hpp"
+#include "classfile/classLoaderData.inline.hpp"
 #include "classfile/classLoaderExt.hpp"
 #include "classfile/javaAssertions.hpp"
 #include "classfile/javaClasses.hpp"
@@ -37,6 +38,7 @@
 #include "gc_interface/collectedHeap.inline.hpp"
 #include "interpreter/bytecode.hpp"
 #include "memory/oopFactory.hpp"
+#include "memory/referenceType.hpp"
 #include "memory/universe.inline.hpp"
 #include "oops/fieldStreams.hpp"
 #include "oops/instanceKlass.hpp"
@@ -89,6 +91,10 @@
 # include "jvm_bsd.h"
 #endif
 
+#if INCLUDE_ALL_GCS
+#include "gc_implementation/g1/g1SATBCardTableModRefBS.hpp"
+#endif // INCLUDE_ALL_GCS
+
 #include <errno.h>
 
 #ifndef USDT2
@@ -577,6 +583,28 @@
 JVM_END
 
 
+static void fixup_cloned_reference(ReferenceType ref_type, oop src, oop clone) {
+  // If G1 is enabled then we need to register a non-null referent
+  // with the SATB barrier.
+#if INCLUDE_ALL_GCS
+  if (UseG1GC) {
+    oop referent = java_lang_ref_Reference::referent(clone);
+    if (referent != NULL) {
+      G1SATBCardTableModRefBS::enqueue(referent);
+    }
+  }
+#endif // INCLUDE_ALL_GCS
+  if ((java_lang_ref_Reference::next(clone) != NULL) ||
+      (java_lang_ref_Reference::queue(clone) == java_lang_ref_ReferenceQueue::ENQUEUED_queue())) {
+    // If the source has been enqueued or is being enqueued, don't
+    // register the clone with a queue.
+    java_lang_ref_Reference::set_queue(clone, java_lang_ref_ReferenceQueue::NULL_queue());
+  }
+  // discovered and next are list links; the clone is not in those lists.
+  java_lang_ref_Reference::set_discovered(clone, NULL);
+  java_lang_ref_Reference::set_next(clone, NULL);
+}
+
 JVM_ENTRY(jobject, JVM_Clone(JNIEnv* env, jobject handle))
   JVMWrapper("JVM_Clone");
   Handle obj(THREAD, JNIHandles::resolve_non_null(handle));
@@ -602,12 +630,17 @@
   }
 
   // Make shallow object copy
+  ReferenceType ref_type = REF_NONE;
   const int size = obj->size();
   oop new_obj_oop = NULL;
   if (obj->is_array()) {
     const int length = ((arrayOop)obj())->length();
     new_obj_oop = CollectedHeap::array_allocate(klass, size, length, CHECK_NULL);
   } else {
+    ref_type = InstanceKlass::cast(klass())->reference_type();
+    assert((ref_type == REF_NONE) ==
+           !klass->is_subclass_of(SystemDictionary::Reference_klass()),
+           "invariant");
     new_obj_oop = CollectedHeap::obj_allocate(klass, size, CHECK_NULL);
   }
 
@@ -631,6 +664,12 @@
   assert(bs->has_write_region_opt(), "Barrier set does not have write_region");
   bs->write_region(MemRegion((HeapWord*)new_obj_oop, size));
 
+  // If cloning a Reference, set Reference fields to a safe state.
+  // Fixup must be completed before any safepoint.
+  if (ref_type != REF_NONE) {
+    fixup_cloned_reference(ref_type, obj(), new_obj_oop);
+  }
+
   Handle new_obj(THREAD, new_obj_oop);
   // Special handling for MemberNames.  Since they contain Method* metadata, they
   // must be registered so that RedefineClasses can fix metadata contained in them.
@@ -720,6 +759,79 @@
 JVM_END
 
 
+// java.nio.Bits ///////////////////////////////////////////////////////////////
+
+#define MAX_OBJECT_SIZE \
+  ( arrayOopDesc::header_size(T_DOUBLE) * HeapWordSize \
+    + ((julong)max_jint * sizeof(double)) )
+
+static inline jlong field_offset_to_byte_offset(jlong field_offset) {
+  return field_offset;
+}
+
+static inline void assert_field_offset_sane(oop p, jlong field_offset) {
+#ifdef ASSERT
+  jlong byte_offset = field_offset_to_byte_offset(field_offset);
+
+  if (p != NULL) {
+    assert(byte_offset >= 0 && byte_offset <= (jlong)MAX_OBJECT_SIZE, "sane offset");
+    if (byte_offset == (jint)byte_offset) {
+      void* ptr_plus_disp = (address)p + byte_offset;
+      assert((void*)p->obj_field_addr<oop>((jint)byte_offset) == ptr_plus_disp,
+             "raw [ptr+disp] must be consistent with oop::field_base");
+    }
+    jlong p_size = HeapWordSize * (jlong)(p->size());
+    assert(byte_offset < p_size, err_msg("Unsafe access: offset " INT64_FORMAT
+                                         " > object's size " INT64_FORMAT,
+                                         (int64_t)byte_offset, (int64_t)p_size));
+  }
+#endif
+}
+
+static inline void* index_oop_from_field_offset_long(oop p, jlong field_offset) {
+  assert_field_offset_sane(p, field_offset);
+  jlong byte_offset = field_offset_to_byte_offset(field_offset);
+
+  if (sizeof(char*) == sizeof(jint)) {   // (this constant folds!)
+    return (address)p + (jint) byte_offset;
+  } else {
+    return (address)p +        byte_offset;
+  }
+}
+
+// This function is a leaf since if the source and destination are both in native memory
+// the copy may potentially be very large, and we don't want to disable GC if we can avoid it.
+// If either source or destination (or both) are on the heap, the function will enter VM using
+// JVM_ENTRY_FROM_LEAF
+JVM_LEAF(void, JVM_CopySwapMemory(JNIEnv *env, jobject srcObj, jlong srcOffset,
+                                  jobject dstObj, jlong dstOffset, jlong size,
+                                  jlong elemSize)) {
+
+  size_t sz = (size_t)size;
+  size_t esz = (size_t)elemSize;
+
+  if (srcObj == NULL && dstObj == NULL) {
+    // Both src & dst are in native memory
+    address src = (address)srcOffset;
+    address dst = (address)dstOffset;
+
+    Copy::conjoint_swap(src, dst, sz, esz);
+  } else {
+    // At least one of src/dst are on heap, transition to VM to access raw pointers
+
+    JVM_ENTRY_FROM_LEAF(env, void, JVM_CopySwapMemory) {
+      oop srcp = JNIHandles::resolve(srcObj);
+      oop dstp = JNIHandles::resolve(dstObj);
+
+      address src = (address)index_oop_from_field_offset_long(srcp, srcOffset);
+      address dst = (address)index_oop_from_field_offset_long(dstp, dstOffset);
+
+      Copy::conjoint_swap(src, dst, sz, esz);
+    } JVM_END
+  }
+} JVM_END
+
+
 // Misc. class handling ///////////////////////////////////////////////////////////
 
 
@@ -952,6 +1064,12 @@
   Handle h_prot  (THREAD, protection_domain);
   jclass result = find_class_from_class_loader(env, h_name, init, h_loader,
                                                h_prot, true, thread);
+  if (result != NULL) {
+    oop mirror = JNIHandles::resolve_non_null(result);
+    Klass* to_class = java_lang_Class::as_Klass(mirror);
+    ClassLoaderData* cld = ClassLoaderData::class_loader_data(h_loader());
+    cld->record_dependency(to_class, CHECK_NULL);
+  }
 
   if (TraceClassResolution && result != NULL) {
     // this function is generally only used for class loading during verification.
@@ -2870,16 +2988,12 @@
 
 ATTRIBUTE_PRINTF(3, 0)
 int jio_vsnprintf(char *str, size_t count, const char *fmt, va_list args) {
-  // see bug 4399518, 4417214
+  // Reject count values that are negative signed values converted to
+  // unsigned; see bug 4399518, 4417214
   if ((intptr_t)count <= 0) return -1;
 
-  int result = vsnprintf(str, count, fmt, args);
-  // Note: on truncation vsnprintf(3) on Unix returns number of
-  // characters which would have been written had the buffer been large
-  // enough; on Windows, it returns -1. We handle both cases here and
-  // always return -1, and perform null termination.
-  if ((result > 0 && (size_t)result >= count) || result == -1) {
-    str[count - 1] = '\0';
+  int result = os::vsnprintf(str, count, fmt, args);
+  if (result > 0 && (size_t)result >= count) {
     result = -1;
   }
 
@@ -3654,15 +3768,16 @@
 JVM_END
 
 
-// Return the first non-null class loader up the execution stack, or null
-// if only code from the null class loader is on the stack.
+// Returns first non-privileged class loader on the stack (excluding reflection
+// generated frames) or null if only classes loaded by the boot class loader
+// and extension class loader are found on the stack.
 
 JVM_ENTRY(jobject, JVM_LatestUserDefinedLoader(JNIEnv *env))
   for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
     // UseNewReflection
     vfst.skip_reflection_related_frames(); // Only needed for 1.4 reflection
     oop loader = vfst.method()->method_holder()->class_loader();
-    if (loader != NULL) {
+    if (loader != NULL && !SystemDictionary::is_ext_class_loader(loader)) {
       return JNIHandles::make_local(env, loader);
     }
   }
diff --git a/src/share/vm/prims/jvm.h b/src/share/vm/prims/jvm.h
index 3b36b73..2c64341 100644
--- a/src/share/vm/prims/jvm.h
+++ b/src/share/vm/prims/jvm.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -145,6 +145,14 @@
 JVM_OnExit(void (*func)(void));
 
 /*
+ * java.nio.Bits
+ */
+JNIEXPORT void JNICALL
+JVM_CopySwapMemory(JNIEnv *env, jobject srcObj, jlong srcOffset,
+                   jobject dstObj, jlong dstOffset, jlong size,
+                   jlong elemSize);
+
+/*
  * java.lang.Runtime
  */
 JNIEXPORT void JNICALL
diff --git a/src/share/vm/prims/jvmtiEnv.cpp b/src/share/vm/prims/jvmtiEnv.cpp
index 98624be..d88e396 100644
--- a/src/share/vm/prims/jvmtiEnv.cpp
+++ b/src/share/vm/prims/jvmtiEnv.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -727,7 +727,7 @@
   thread_objs = NEW_RESOURCE_ARRAY(Handle, nthreads);
   NULL_CHECK(thread_objs, JVMTI_ERROR_OUT_OF_MEMORY);
 
-  for (int i=0; i < nthreads; i++) {
+  for (int i = 0; i < nthreads; i++) {
     thread_objs[i] = Handle(tle.get_threadObj(i));
   }
 
@@ -952,16 +952,14 @@
   Handle context_class_loader;
   bool          is_daemon;
 
-  { MutexLocker mu(Threads_lock);
+  name = Handle(current_thread, java_lang_Thread::name(thread_obj()));
+  priority = java_lang_Thread::priority(thread_obj());
+  thread_group = Handle(current_thread, java_lang_Thread::threadGroup(thread_obj()));
+  is_daemon = java_lang_Thread::is_daemon(thread_obj());
 
-    name = Handle(current_thread, java_lang_Thread::name(thread_obj()));
-    priority = java_lang_Thread::priority(thread_obj());
-    thread_group = Handle(current_thread, java_lang_Thread::threadGroup(thread_obj()));
-    is_daemon = java_lang_Thread::is_daemon(thread_obj());
+  oop loader = java_lang_Thread::context_class_loader(thread_obj());
+  context_class_loader = Handle(current_thread, loader);
 
-    oop loader = java_lang_Thread::context_class_loader(thread_obj());
-    context_class_loader = Handle(current_thread, loader);
-  }
   { const char *n;
 
     if (name() != NULL) {
@@ -1193,14 +1191,11 @@
   bool is_daemon;
   ThreadPriority max_priority;
 
-  { MutexLocker mu(Threads_lock);
-
-    name         = typeArrayHandle(current_thread,
-                                   java_lang_ThreadGroup::name(group_obj()));
-    parent_group = Handle(current_thread, java_lang_ThreadGroup::parent(group_obj()));
-    is_daemon    = java_lang_ThreadGroup::is_daemon(group_obj());
-    max_priority = java_lang_ThreadGroup::maxPriority(group_obj());
-  }
+  name         = typeArrayHandle(current_thread,
+                                 java_lang_ThreadGroup::name(group_obj()));
+  parent_group = Handle(current_thread, java_lang_ThreadGroup::parent(group_obj()));
+  is_daemon    = java_lang_ThreadGroup::is_daemon(group_obj());
+  max_priority = java_lang_ThreadGroup::maxPriority(group_obj());
 
   info_ptr->is_daemon    = is_daemon;
   info_ptr->max_priority = max_priority;
@@ -1240,8 +1235,8 @@
 
   Handle group_hdl(current_thread, group_obj);
 
-  { MutexLocker mu(Threads_lock);
-
+  {
+    ObjectLocker ol(group_hdl, current_thread);
     nthreads = java_lang_ThreadGroup::nthreads(group_hdl());
     ngroups  = java_lang_ThreadGroup::ngroups(group_hdl());
 
@@ -1249,7 +1244,7 @@
       objArrayOop threads = java_lang_ThreadGroup::threads(group_hdl());
       assert(nthreads <= threads->length(), "too many threads");
       thread_objs = NEW_RESOURCE_ARRAY(Handle,nthreads);
-      for (int i=0, j=0; i<nthreads; i++) {
+      for (int i = 0, j = 0; i < nthreads; i++) {
         oop thread_obj = threads->obj_at(i);
         assert(thread_obj != NULL, "thread_obj is NULL");
         JavaThread *javathread = java_lang_Thread::thread(thread_obj);
@@ -1266,15 +1261,14 @@
       objArrayOop groups = java_lang_ThreadGroup::groups(group_hdl());
       assert(ngroups <= groups->length(), "too many threads");
       group_objs = NEW_RESOURCE_ARRAY(Handle,ngroups);
-      for (int i=0; i<ngroups; i++) {
+      for (int i = 0; i < ngroups; i++) {
         oop group_obj = groups->obj_at(i);
         assert(group_obj != NULL, "group_obj != NULL");
         group_objs[i] = Handle(current_thread, group_obj);
       }
     }
-  }
+  } // ThreadGroup unlocked here
 
-  // have to make global handles outside of Threads_lock
   *group_count_ptr  = ngroups;
   *thread_count_ptr = nthreads;
   *threads_ptr     = new_jthreadArray(nthreads, thread_objs);
@@ -2979,7 +2973,7 @@
       // objects that are locked.
       int r;
       intptr_t recursion = rmonitor->recursions();
-      for (intptr_t i=0; i <= recursion; i++) {
+      for (intptr_t i = 0; i <= recursion; i++) {
         r = rmonitor->raw_exit(thread);
         assert(r == ObjectMonitor::OM_OK, "raw_exit should have worked");
         if (r != ObjectMonitor::OM_OK) {  // robustness
@@ -3395,7 +3389,7 @@
       strcpy(*tmp_value, key);
     } else {
       // clean up previously allocated memory.
-      for (int j=0; j<i; j++) {
+      for (int j = 0; j < i; j++) {
         Deallocate((unsigned char*)*property_ptr+j);
       }
       Deallocate((unsigned char*)property_ptr);
diff --git a/src/share/vm/prims/jvmtiGetLoadedClasses.cpp b/src/share/vm/prims/jvmtiGetLoadedClasses.cpp
index 70aede5..a292f89 100644
--- a/src/share/vm/prims/jvmtiGetLoadedClasses.cpp
+++ b/src/share/vm/prims/jvmtiGetLoadedClasses.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,9 @@
 #include "memory/universe.inline.hpp"
 #include "prims/jvmtiGetLoadedClasses.hpp"
 #include "runtime/thread.hpp"
+#if INCLUDE_ALL_GCS
+#include "gc_implementation/g1/g1SATBCardTableModRefBS.hpp"
+#endif
 
 
 // The closure for GetLoadedClasses
@@ -35,6 +38,20 @@
   Stack<jclass, mtInternal> _classStack;
   JvmtiEnv* _env;
 
+// Tell the GC to keep this klass alive
+static void ensure_klass_alive(oop o) {
+  // A klass that was previously considered dead can be looked up in the
+  // CLD/SD, and its _java_mirror or _class_loader can be stored in a root
+  // or a reachable object making it alive again. The SATB part of G1 needs
+  // to get notified about this potential resurrection, otherwise the marking
+  // might not find the object.
+#if INCLUDE_ALL_GCS
+  if (UseG1GC && o != NULL) {
+    G1SATBCardTableModRefBS::enqueue(o);
+  }
+#endif
+}
+
 public:
   LoadedClassesClosure(JvmtiEnv* env) {
     _env = env;
@@ -43,6 +60,7 @@
   void do_klass(Klass* k) {
     // Collect all jclasses
     _classStack.push((jclass) _env->jni_reference(k->java_mirror()));
+    ensure_klass_alive(k->java_mirror());
   }
 
   int extract(jclass* result_list) {
diff --git a/src/share/vm/prims/jvmtiImpl.cpp b/src/share/vm/prims/jvmtiImpl.cpp
index 9b308d4..3c66b16 100644
--- a/src/share/vm/prims/jvmtiImpl.cpp
+++ b/src/share/vm/prims/jvmtiImpl.cpp
@@ -282,39 +282,22 @@
 void JvmtiBreakpoint::each_method_version_do(method_action meth_act) {
   ((Method*)_method->*meth_act)(_bci);
 
-  // add/remove breakpoint to/from versions of the method that
-  // are EMCP. Directly or transitively obsolete methods are
-  // not saved in the PreviousVersionNodes.
+  // add/remove breakpoint to/from versions of the method that are EMCP.
   Thread *thread = Thread::current();
   instanceKlassHandle ikh = instanceKlassHandle(thread, _method->method_holder());
   Symbol* m_name = _method->name();
   Symbol* m_signature = _method->signature();
 
   // search previous versions if they exist
-  PreviousVersionWalker pvw(thread, (InstanceKlass *)ikh());
-  for (PreviousVersionNode * pv_node = pvw.next_previous_version();
-       pv_node != NULL; pv_node = pvw.next_previous_version()) {
-    GrowableArray<Method*>* methods = pv_node->prev_EMCP_methods();
-
-    if (methods == NULL) {
-      // We have run into a PreviousVersion generation where
-      // all methods were made obsolete during that generation's
-      // RedefineClasses() operation. At the time of that
-      // operation, all EMCP methods were flushed so we don't
-      // have to go back any further.
-      //
-      // A NULL methods array is different than an empty methods
-      // array. We cannot infer any optimizations about older
-      // generations from an empty methods array for the current
-      // generation.
-      break;
-    }
+  for (InstanceKlass* pv_node = ikh->previous_versions();
+       pv_node != NULL;
+       pv_node = pv_node->previous_versions()) {
+    Array<Method*>* methods = pv_node->methods();
 
     for (int i = methods->length() - 1; i >= 0; i--) {
       Method* method = methods->at(i);
-      // obsolete methods that are running are not deleted from
-      // previous version array, but they are skipped here.
-      if (!method->is_obsolete() &&
+      // Only set breakpoints in running EMCP methods.
+      if (method->is_running_emcp() &&
           method->name() == m_name &&
           method->signature() == m_signature) {
         RC_TRACE(0x00000800, ("%sing breakpoint in %s(%s)",
diff --git a/src/share/vm/prims/jvmtiRedefineClasses.cpp b/src/share/vm/prims/jvmtiRedefineClasses.cpp
index f610db2..0e194b6 100644
--- a/src/share/vm/prims/jvmtiRedefineClasses.cpp
+++ b/src/share/vm/prims/jvmtiRedefineClasses.cpp
@@ -3435,13 +3435,12 @@
     }
 
     // the previous versions' constant pool caches may need adjustment
-    PreviousVersionWalker pvw(_thread, ik);
-    for (PreviousVersionNode * pv_node = pvw.next_previous_version();
-         pv_node != NULL; pv_node = pvw.next_previous_version()) {
-      other_cp = pv_node->prev_constant_pool();
-      cp_cache = other_cp->cache();
+    for (InstanceKlass* pv_node = ik->previous_versions();
+         pv_node != NULL;
+         pv_node = pv_node->previous_versions()) {
+      cp_cache = pv_node->constants()->cache();
       if (cp_cache != NULL) {
-        cp_cache->adjust_method_entries(other_cp->pool_holder(), &trace_name_printed);
+        cp_cache->adjust_method_entries(pv_node, &trace_name_printed);
       }
     }
   }
@@ -3461,9 +3460,8 @@
   }
 }
 
-void VM_RedefineClasses::check_methods_and_mark_as_obsolete(
-       BitMap *emcp_methods, int * emcp_method_count_p) {
-  *emcp_method_count_p = 0;
+int VM_RedefineClasses::check_methods_and_mark_as_obsolete() {
+  int emcp_method_count = 0;
   int obsolete_count = 0;
   int old_index = 0;
   for (int j = 0; j < _matching_methods_length; ++j, ++old_index) {
@@ -3537,9 +3535,9 @@
       // that we get from effectively overwriting the old methods
       // when the new methods are attached to the_class.
 
-      // track which methods are EMCP for add_previous_version() call
-      emcp_methods->set_bit(old_index);
-      (*emcp_method_count_p)++;
+      // Count number of methods that are EMCP.  The method will be marked
+      // old but not obsolete if it is EMCP.
+      emcp_method_count++;
 
       // An EMCP method is _not_ obsolete. An obsolete method has a
       // different jmethodID than the current method. An EMCP method
@@ -3589,10 +3587,11 @@
                           old_method->name()->as_C_string(),
                           old_method->signature()->as_C_string()));
   }
-  assert((*emcp_method_count_p + obsolete_count) == _old_methods->length(),
+  assert((emcp_method_count + obsolete_count) == _old_methods->length(),
     "sanity check");
-  RC_TRACE(0x00000100, ("EMCP_cnt=%d, obsolete_cnt=%d", *emcp_method_count_p,
+  RC_TRACE(0x00000100, ("EMCP_cnt=%d, obsolete_cnt=%d", emcp_method_count,
     obsolete_count));
+  return emcp_method_count;
 }
 
 // This internal class transfers the native function registration from old methods
@@ -3973,11 +3972,8 @@
   old_constants->set_pool_holder(scratch_class());
 #endif
 
-  // track which methods are EMCP for add_previous_version() call below
-  BitMap emcp_methods(_old_methods->length());
-  int emcp_method_count = 0;
-  emcp_methods.clear();  // clears 0..(length() - 1)
-  check_methods_and_mark_as_obsolete(&emcp_methods, &emcp_method_count);
+  // track number of methods that are EMCP for add_previous_version() call below
+  int emcp_method_count = check_methods_and_mark_as_obsolete();
   transfer_old_native_function_registrations(the_class);
 
   // The class file bytes from before any retransformable agents mucked
@@ -4064,9 +4060,10 @@
     scratch_class->enclosing_method_method_index());
   scratch_class->set_enclosing_method_indices(old_class_idx, old_method_idx);
 
+  the_class->set_has_been_redefined();
+
   // keep track of previous versions of this class
-  the_class->add_previous_version(scratch_class, &emcp_methods,
-    emcp_method_count);
+  the_class->add_previous_version(scratch_class, emcp_method_count);
 
   RC_TIMER_STOP(_timer_rsc_phase1);
   RC_TIMER_START(_timer_rsc_phase2);
diff --git a/src/share/vm/prims/jvmtiRedefineClasses.hpp b/src/share/vm/prims/jvmtiRedefineClasses.hpp
index d2611f2..aab9d45 100644
--- a/src/share/vm/prims/jvmtiRedefineClasses.hpp
+++ b/src/share/vm/prims/jvmtiRedefineClasses.hpp
@@ -403,14 +403,9 @@
   // Change jmethodIDs to point to the new methods
   void update_jmethod_ids();
 
-  // In addition to marking methods as obsolete, this routine
-  // records which methods are EMCP (Equivalent Module Constant
-  // Pool) in the emcp_methods BitMap and returns the number of
-  // EMCP methods via emcp_method_count_p. This information is
-  // used when information about the previous version of the_class
-  // is squirreled away.
-  void check_methods_and_mark_as_obsolete(BitMap *emcp_methods,
-         int * emcp_method_count_p);
+  // In addition to marking methods as old and/or obsolete, this routine
+  // counts the number of methods that are EMCP (Equivalent Module Constant Pool).
+  int check_methods_and_mark_as_obsolete();
   void transfer_old_native_function_registrations(instanceKlassHandle the_class);
 
   // Install the redefinition of a class
diff --git a/src/share/vm/prims/jvmtiTagMap.cpp b/src/share/vm/prims/jvmtiTagMap.cpp
index 1ae7ce6..c45181d 100644
--- a/src/share/vm/prims/jvmtiTagMap.cpp
+++ b/src/share/vm/prims/jvmtiTagMap.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -47,6 +47,7 @@
 #include "services/serviceUtil.hpp"
 #include "utilities/macros.hpp"
 #if INCLUDE_ALL_GCS
+#include "gc_implementation/g1/g1SATBCardTableModRefBS.hpp"
 #include "gc_implementation/parallelScavenge/parallelScavengeHeap.hpp"
 #endif // INCLUDE_ALL_GCS
 
@@ -1519,6 +1520,14 @@
       if (_tags[i] == entry->tag()) {
         oop o = entry->object();
         assert(o != NULL && Universe::heap()->is_in_reserved(o), "sanity check");
+#if INCLUDE_ALL_GCS
+        if (UseG1GC) {
+          // The reference in this tag map could be the only (implicitly weak)
+          // reference to that object. If we hand it out, we need to keep it live wrt
+          // SATB marking similar to other j.l.ref.Reference referents.
+          G1SATBCardTableModRefBS::enqueue(o);
+        }
+#endif
         jobject ref = JNIHandles::make_local(JavaThread::current(), o);
         _object_results->append(ref);
         _tag_results->append((uint64_t)entry->tag());
diff --git a/src/share/vm/prims/methodHandles.cpp b/src/share/vm/prims/methodHandles.cpp
index 6c7cdb5..8645340 100644
--- a/src/share/vm/prims/methodHandles.cpp
+++ b/src/share/vm/prims/methodHandles.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -391,12 +391,12 @@
 // convert the external string or reflective type to an internal signature
 Symbol* MethodHandles::lookup_signature(oop type_str, bool intern_if_not_found, TRAPS) {
   if (java_lang_invoke_MethodType::is_instance(type_str)) {
-    return java_lang_invoke_MethodType::as_signature(type_str, intern_if_not_found, CHECK_NULL);
+    return java_lang_invoke_MethodType::as_signature(type_str, intern_if_not_found, THREAD);
   } else if (java_lang_Class::is_instance(type_str)) {
-    return java_lang_Class::as_signature(type_str, false, CHECK_NULL);
+    return java_lang_Class::as_signature(type_str, false, THREAD);
   } else if (java_lang_String::is_instance(type_str)) {
     if (intern_if_not_found) {
-      return java_lang_String::as_symbol(type_str, CHECK_NULL);
+      return java_lang_String::as_symbol(type_str, THREAD);
     } else {
       return java_lang_String::as_symbol_or_null(type_str);
     }
@@ -1329,40 +1329,40 @@
 #define LANG "Ljava/lang/"
 #define JLINV "Ljava/lang/invoke/"
 
-#define OBJ   LANG"Object;"
-#define CLS   LANG"Class;"
-#define STRG  LANG"String;"
-#define CS    JLINV"CallSite;"
-#define MT    JLINV"MethodType;"
-#define MH    JLINV"MethodHandle;"
-#define MEM   JLINV"MemberName;"
+#define OBJ   LANG "Object;"
+#define CLS   LANG "Class;"
+#define STRG  LANG "String;"
+#define CS    JLINV "CallSite;"
+#define MT    JLINV "MethodType;"
+#define MH    JLINV "MethodHandle;"
+#define MEM   JLINV "MemberName;"
 
 #define CC (char*)  /*cast a literal from (const char*)*/
 #define FN_PTR(f) CAST_FROM_FN_PTR(void*, &f)
 
 // These are the native methods on java.lang.invoke.MethodHandleNatives.
 static JNINativeMethod MHN_methods[] = {
-  {CC"init",                      CC"("MEM""OBJ")V",                     FN_PTR(MHN_init_Mem)},
-  {CC"expand",                    CC"("MEM")V",                          FN_PTR(MHN_expand_Mem)},
-  {CC"resolve",                   CC"("MEM""CLS")"MEM,                   FN_PTR(MHN_resolve_Mem)},
-  {CC"getConstant",               CC"(I)I",                              FN_PTR(MHN_getConstant)},
+  {CC "init",                      CC "(" MEM "" OBJ ")V",                     FN_PTR(MHN_init_Mem)},
+  {CC"expand",                     CC "(" MEM ")V",                          FN_PTR(MHN_expand_Mem)},
+  {CC "resolve",                   CC "(" MEM "" CLS ")" MEM,                   FN_PTR(MHN_resolve_Mem)},
+  {CC "getConstant",               CC "(I)I",                              FN_PTR(MHN_getConstant)},
   //  static native int getNamedCon(int which, Object[] name)
-  {CC"getNamedCon",               CC"(I["OBJ")I",                        FN_PTR(MHN_getNamedCon)},
+  {CC "getNamedCon",               CC "(I[" OBJ ")I",                        FN_PTR(MHN_getNamedCon)},
   //  static native int getMembers(Class<?> defc, String matchName, String matchSig,
   //          int matchFlags, Class<?> caller, int skip, MemberName[] results);
-  {CC"getMembers",                CC"("CLS""STRG""STRG"I"CLS"I["MEM")I", FN_PTR(MHN_getMembers)},
-  {CC"objectFieldOffset",         CC"("MEM")J",                          FN_PTR(MHN_objectFieldOffset)},
-  {CC"setCallSiteTargetNormal",   CC"("CS""MH")V",                       FN_PTR(MHN_setCallSiteTargetNormal)},
-  {CC"setCallSiteTargetVolatile", CC"("CS""MH")V",                       FN_PTR(MHN_setCallSiteTargetVolatile)},
-  {CC"staticFieldOffset",         CC"("MEM")J",                          FN_PTR(MHN_staticFieldOffset)},
-  {CC"staticFieldBase",           CC"("MEM")"OBJ,                        FN_PTR(MHN_staticFieldBase)},
-  {CC"getMemberVMInfo",           CC"("MEM")"OBJ,                        FN_PTR(MHN_getMemberVMInfo)}
+  {CC "getMembers",                CC "(" CLS "" STRG "" STRG "I" CLS "I[" MEM ")I", FN_PTR(MHN_getMembers)},
+  {CC "objectFieldOffset",         CC "(" MEM ")J",                          FN_PTR(MHN_objectFieldOffset)},
+  {CC "setCallSiteTargetNormal",   CC "(" CS "" MH ")V",                       FN_PTR(MHN_setCallSiteTargetNormal)},
+  {CC "setCallSiteTargetVolatile", CC "(" CS "" MH ")V",                       FN_PTR(MHN_setCallSiteTargetVolatile)},
+  {CC "staticFieldOffset",         CC "(" MEM ")J",                          FN_PTR(MHN_staticFieldOffset)},
+  {CC "staticFieldBase",           CC "(" MEM ")" OBJ,                        FN_PTR(MHN_staticFieldBase)},
+  {CC "getMemberVMInfo",           CC "(" MEM ")" OBJ,                        FN_PTR(MHN_getMemberVMInfo)}
 };
 
 static JNINativeMethod MH_methods[] = {
   // UnsupportedOperationException throwers
-  {CC"invoke",                    CC"(["OBJ")"OBJ,                       FN_PTR(MH_invoke_UOE)},
-  {CC"invokeExact",               CC"(["OBJ")"OBJ,                       FN_PTR(MH_invokeExact_UOE)}
+  {CC "invoke",                    CC "([" OBJ ")" OBJ,                       FN_PTR(MH_invoke_UOE)},
+  {CC "invokeExact",               CC "([" OBJ ")" OBJ,                       FN_PTR(MH_invokeExact_UOE)}
 };
 
 /**
diff --git a/src/share/vm/prims/perf.cpp b/src/share/vm/prims/perf.cpp
index 9ad0f4c..74a1287 100644
--- a/src/share/vm/prims/perf.cpp
+++ b/src/share/vm/prims/perf.cpp
@@ -290,17 +290,17 @@
 #define FN_PTR(f) CAST_FROM_FN_PTR(void*, &f)
 #define BB "Ljava/nio/ByteBuffer;"
 #define JLS "Ljava/lang/String;"
-#define CL_ARGS     CC"("JLS"IIJ)"BB
-#define CBA_ARGS    CC"("JLS"II[BI)"BB
+#define CL_ARGS     CC "(" JLS "IIJ)" BB
+#define CBA_ARGS    CC "(" JLS "II[BI)" BB
 
 static JNINativeMethod perfmethods[] = {
 
-  {CC"attach",              CC"("JLS"II)"BB,  FN_PTR(Perf_Attach)},
-  {CC"detach",              CC"("BB")V",      FN_PTR(Perf_Detach)},
-  {CC"createLong",          CL_ARGS,          FN_PTR(Perf_CreateLong)},
-  {CC"createByteArray",     CBA_ARGS,         FN_PTR(Perf_CreateByteArray)},
-  {CC"highResCounter",      CC"()J",          FN_PTR(Perf_HighResCounter)},
-  {CC"highResFrequency",    CC"()J",          FN_PTR(Perf_HighResFrequency)}
+  {CC "attach",              CC "(" JLS "II)" BB, FN_PTR(Perf_Attach)},
+  {CC "detach",              CC "(" BB ")V",      FN_PTR(Perf_Detach)},
+  {CC "createLong",          CL_ARGS,             FN_PTR(Perf_CreateLong)},
+  {CC "createByteArray",     CBA_ARGS,            FN_PTR(Perf_CreateByteArray)},
+  {CC "highResCounter",      CC "()J",            FN_PTR(Perf_HighResCounter)},
+  {CC "highResFrequency",    CC "()J",            FN_PTR(Perf_HighResFrequency)}
 };
 
 #undef CBA_ARGS
diff --git a/src/share/vm/prims/unsafe.cpp b/src/share/vm/prims/unsafe.cpp
index 5e39b38..3b25eb7 100644
--- a/src/share/vm/prims/unsafe.cpp
+++ b/src/share/vm/prims/unsafe.cpp
@@ -199,37 +199,40 @@
 
 // Get/SetObject must be special-cased, since it works with handles.
 
+// We could be accessing the referent field in a reference
+// object. If G1 is enabled then we need to register non-null
+// referent with the SATB barrier.
+
+#if INCLUDE_ALL_GCS
+static bool is_java_lang_ref_Reference_access(oop o, jlong offset) {
+  if (offset == java_lang_ref_Reference::referent_offset && o != NULL) {
+    Klass* k = o->klass();
+    if (InstanceKlass::cast(k)->reference_type() != REF_NONE) {
+      assert(InstanceKlass::cast(k)->is_subclass_of(SystemDictionary::Reference_klass()), "sanity");
+      return true;
+    }
+  }
+ return false;
+}
+#endif
+
+static void ensure_satb_referent_alive(oop o, jlong offset, oop v) {
+#if INCLUDE_ALL_GCS
+  if (UseG1GC && v != NULL && is_java_lang_ref_Reference_access(o, offset)) {
+    G1SATBCardTableModRefBS::enqueue(v);
+  }
+#endif
+}
+
 // The xxx140 variants for backward compatibility do not allow a full-width offset.
 UNSAFE_ENTRY(jobject, Unsafe_GetObject140(JNIEnv *env, jobject unsafe, jobject obj, jint offset))
   UnsafeWrapper("Unsafe_GetObject");
   if (obj == NULL)  THROW_0(vmSymbols::java_lang_NullPointerException());
   GET_OOP_FIELD(obj, offset, v)
-  jobject ret = JNIHandles::make_local(env, v);
-#if INCLUDE_ALL_GCS
-  // We could be accessing the referent field in a reference
-  // object. If G1 is enabled then we need to register a non-null
-  // referent with the SATB barrier.
-  if (UseG1GC) {
-    bool needs_barrier = false;
 
-    if (ret != NULL) {
-      if (offset == java_lang_ref_Reference::referent_offset) {
-        oop o = JNIHandles::resolve_non_null(obj);
-        Klass* k = o->klass();
-        if (InstanceKlass::cast(k)->reference_type() != REF_NONE) {
-          assert(InstanceKlass::cast(k)->is_subclass_of(SystemDictionary::Reference_klass()), "sanity");
-          needs_barrier = true;
-        }
-      }
-    }
+  ensure_satb_referent_alive(p, offset, v);
 
-    if (needs_barrier) {
-      oop referent = JNIHandles::resolve(ret);
-      G1SATBCardTableModRefBS::enqueue(referent);
-    }
-  }
-#endif // INCLUDE_ALL_GCS
-  return ret;
+  return JNIHandles::make_local(env, v);
 UNSAFE_END
 
 UNSAFE_ENTRY(void, Unsafe_SetObject140(JNIEnv *env, jobject unsafe, jobject obj, jint offset, jobject x_h))
@@ -262,32 +265,10 @@
 UNSAFE_ENTRY(jobject, Unsafe_GetObject(JNIEnv *env, jobject unsafe, jobject obj, jlong offset))
   UnsafeWrapper("Unsafe_GetObject");
   GET_OOP_FIELD(obj, offset, v)
-  jobject ret = JNIHandles::make_local(env, v);
-#if INCLUDE_ALL_GCS
-  // We could be accessing the referent field in a reference
-  // object. If G1 is enabled then we need to register non-null
-  // referent with the SATB barrier.
-  if (UseG1GC) {
-    bool needs_barrier = false;
 
-    if (ret != NULL) {
-      if (offset == java_lang_ref_Reference::referent_offset && obj != NULL) {
-        oop o = JNIHandles::resolve(obj);
-        Klass* k = o->klass();
-        if (InstanceKlass::cast(k)->reference_type() != REF_NONE) {
-          assert(InstanceKlass::cast(k)->is_subclass_of(SystemDictionary::Reference_klass()), "sanity");
-          needs_barrier = true;
-        }
-      }
-    }
+  ensure_satb_referent_alive(p, offset, v);
 
-    if (needs_barrier) {
-      oop referent = JNIHandles::resolve(ret);
-      G1SATBCardTableModRefBS::enqueue(referent);
-    }
-  }
-#endif // INCLUDE_ALL_GCS
-  return ret;
+  return JNIHandles::make_local(env, v);
 UNSAFE_END
 
 UNSAFE_ENTRY(void, Unsafe_SetObject(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject x_h))
@@ -312,6 +293,9 @@
   } else {
     (void)const_cast<oop&>(v = *(volatile oop*) addr);
   }
+
+  ensure_satb_referent_alive(p, offset, v);
+
   OrderAccess::acquire();
   return JNIHandles::make_local(env, v);
 UNSAFE_END
@@ -1366,47 +1350,47 @@
 
 #define LANG "Ljava/lang/"
 
-#define OBJ LANG"Object;"
-#define CLS LANG"Class;"
-#define CTR LANG"reflect/Constructor;"
-#define FLD LANG"reflect/Field;"
-#define MTH LANG"reflect/Method;"
-#define THR LANG"Throwable;"
+#define OBJ LANG "Object;"
+#define CLS LANG "Class;"
+#define CTR LANG "reflect/Constructor;"
+#define FLD LANG "reflect/Field;"
+#define MTH LANG "reflect/Method;"
+#define THR LANG "Throwable;"
 
-#define DC0_Args LANG"String;[BII"
-#define DC_Args  DC0_Args LANG"ClassLoader;" "Ljava/security/ProtectionDomain;"
+#define DC0_Args LANG "String;[BII"
+#define DC_Args  DC0_Args LANG "ClassLoader;" "Ljava/security/ProtectionDomain;"
 
 #define CC (char*)  /*cast a literal from (const char*)*/
 #define FN_PTR(f) CAST_FROM_FN_PTR(void*, &f)
 
 // define deprecated accessors for compabitility with 1.4.0
 #define DECLARE_GETSETOOP_140(Boolean, Z) \
-    {CC"get"#Boolean,      CC"("OBJ"I)"#Z,      FN_PTR(Unsafe_Get##Boolean##140)}, \
-    {CC"put"#Boolean,      CC"("OBJ"I"#Z")V",   FN_PTR(Unsafe_Set##Boolean##140)}
+    {CC "get" #Boolean,      CC "(" OBJ "I)" #Z,      FN_PTR(Unsafe_Get##Boolean##140)}, \
+    {CC "put" #Boolean,      CC "(" OBJ "I" #Z ")V",   FN_PTR(Unsafe_Set##Boolean##140)}
 
 // Note:  In 1.4.1, getObject and kin take both int and long offsets.
 #define DECLARE_GETSETOOP_141(Boolean, Z) \
-    {CC"get"#Boolean,      CC"("OBJ"J)"#Z,      FN_PTR(Unsafe_Get##Boolean)}, \
-    {CC"put"#Boolean,      CC"("OBJ"J"#Z")V",   FN_PTR(Unsafe_Set##Boolean)}
+    {CC "get" #Boolean,      CC "(" OBJ "J)" #Z,      FN_PTR(Unsafe_Get##Boolean)}, \
+    {CC "put" #Boolean,      CC "(" OBJ "J" #Z ")V",   FN_PTR(Unsafe_Set##Boolean)}
 
 // Note:  In 1.5.0, there are volatile versions too
 #define DECLARE_GETSETOOP(Boolean, Z) \
-    {CC"get"#Boolean,      CC"("OBJ"J)"#Z,      FN_PTR(Unsafe_Get##Boolean)}, \
-    {CC"put"#Boolean,      CC"("OBJ"J"#Z")V",   FN_PTR(Unsafe_Set##Boolean)}, \
-    {CC"get"#Boolean"Volatile",      CC"("OBJ"J)"#Z,      FN_PTR(Unsafe_Get##Boolean##Volatile)}, \
-    {CC"put"#Boolean"Volatile",      CC"("OBJ"J"#Z")V",   FN_PTR(Unsafe_Set##Boolean##Volatile)}
+    {CC "get" #Boolean,      CC "(" OBJ "J)" #Z,      FN_PTR(Unsafe_Get##Boolean)}, \
+    {CC "put" #Boolean,      CC "(" OBJ "J" #Z ")V",   FN_PTR(Unsafe_Set##Boolean)}, \
+    {CC "get" #Boolean "Volatile",      CC "(" OBJ "J)" #Z,      FN_PTR(Unsafe_Get##Boolean##Volatile)}, \
+    {CC "put" #Boolean "Volatile",      CC "(" OBJ "J" #Z ")V",   FN_PTR(Unsafe_Set##Boolean##Volatile)}
 
 
 #define DECLARE_GETSETNATIVE(Byte, B) \
-    {CC"get"#Byte,         CC"("ADR")"#B,       FN_PTR(Unsafe_GetNative##Byte)}, \
-    {CC"put"#Byte,         CC"("ADR#B")V",      FN_PTR(Unsafe_SetNative##Byte)}
+    {CC "get" #Byte,         CC "(" ADR ")" #B,       FN_PTR(Unsafe_GetNative##Byte)}, \
+    {CC "put" #Byte,         CC "(" ADR#B ")V",      FN_PTR(Unsafe_SetNative##Byte)}
 
 
 
 // These are the methods for 1.4.0
 static JNINativeMethod methods_140[] = {
-    {CC"getObject",        CC"("OBJ"I)"OBJ"",   FN_PTR(Unsafe_GetObject140)},
-    {CC"putObject",        CC"("OBJ"I"OBJ")V",  FN_PTR(Unsafe_SetObject140)},
+    {CC "getObject",        CC "(" OBJ "I)" OBJ "",   FN_PTR(Unsafe_GetObject140)},
+    {CC "putObject",        CC "(" OBJ "I" OBJ ")V",  FN_PTR(Unsafe_SetObject140)},
 
     DECLARE_GETSETOOP_140(Boolean, Z),
     DECLARE_GETSETOOP_140(Byte, B),
@@ -1425,33 +1409,33 @@
     DECLARE_GETSETNATIVE(Float, F),
     DECLARE_GETSETNATIVE(Double, D),
 
-    {CC"getAddress",         CC"("ADR")"ADR,             FN_PTR(Unsafe_GetNativeAddress)},
-    {CC"putAddress",         CC"("ADR""ADR")V",          FN_PTR(Unsafe_SetNativeAddress)},
+    {CC "getAddress",         CC "(" ADR ")" ADR,             FN_PTR(Unsafe_GetNativeAddress)},
+    {CC "putAddress",         CC "(" ADR "" ADR ")V",          FN_PTR(Unsafe_SetNativeAddress)},
 
-    {CC"allocateMemory",     CC"(J)"ADR,                 FN_PTR(Unsafe_AllocateMemory)},
-    {CC"reallocateMemory",   CC"("ADR"J)"ADR,            FN_PTR(Unsafe_ReallocateMemory)},
-    {CC"freeMemory",         CC"("ADR")V",               FN_PTR(Unsafe_FreeMemory)},
+    {CC "allocateMemory",     CC "(J)" ADR,                 FN_PTR(Unsafe_AllocateMemory)},
+    {CC "reallocateMemory",   CC "(" ADR "J)" ADR,            FN_PTR(Unsafe_ReallocateMemory)},
+    {CC "freeMemory",         CC "(" ADR ")V",               FN_PTR(Unsafe_FreeMemory)},
 
-    {CC"fieldOffset",        CC"("FLD")I",               FN_PTR(Unsafe_FieldOffset)},
-    {CC"staticFieldBase",    CC"("CLS")"OBJ,             FN_PTR(Unsafe_StaticFieldBaseFromClass)},
-    {CC"ensureClassInitialized",CC"("CLS")V",            FN_PTR(Unsafe_EnsureClassInitialized)},
-    {CC"arrayBaseOffset",    CC"("CLS")I",               FN_PTR(Unsafe_ArrayBaseOffset)},
-    {CC"arrayIndexScale",    CC"("CLS")I",               FN_PTR(Unsafe_ArrayIndexScale)},
-    {CC"addressSize",        CC"()I",                    FN_PTR(Unsafe_AddressSize)},
-    {CC"pageSize",           CC"()I",                    FN_PTR(Unsafe_PageSize)},
+    {CC "fieldOffset",        CC "(" FLD ")I",               FN_PTR(Unsafe_FieldOffset)},
+    {CC "staticFieldBase",    CC "(" CLS ")" OBJ,             FN_PTR(Unsafe_StaticFieldBaseFromClass)},
+    {CC "ensureClassInitialized",CC "(" CLS ")V",            FN_PTR(Unsafe_EnsureClassInitialized)},
+    {CC "arrayBaseOffset",    CC "(" CLS ")I",               FN_PTR(Unsafe_ArrayBaseOffset)},
+    {CC "arrayIndexScale",    CC "(" CLS ")I",               FN_PTR(Unsafe_ArrayIndexScale)},
+    {CC "addressSize",        CC "()I",                    FN_PTR(Unsafe_AddressSize)},
+    {CC "pageSize",           CC "()I",                    FN_PTR(Unsafe_PageSize)},
 
-    {CC"defineClass",        CC"("DC0_Args")"CLS,        FN_PTR(Unsafe_DefineClass0)},
-    {CC"defineClass",        CC"("DC_Args")"CLS,         FN_PTR(Unsafe_DefineClass)},
-    {CC"allocateInstance",   CC"("CLS")"OBJ,             FN_PTR(Unsafe_AllocateInstance)},
-    {CC"monitorEnter",       CC"("OBJ")V",               FN_PTR(Unsafe_MonitorEnter)},
-    {CC"monitorExit",        CC"("OBJ")V",               FN_PTR(Unsafe_MonitorExit)},
-    {CC"throwException",     CC"("THR")V",               FN_PTR(Unsafe_ThrowException)}
+    {CC "defineClass",        CC "(" DC0_Args ")" CLS,        FN_PTR(Unsafe_DefineClass0)},
+    {CC "defineClass",        CC "(" DC_Args ")" CLS,         FN_PTR(Unsafe_DefineClass)},
+    {CC "allocateInstance",   CC "(" CLS ")" OBJ,             FN_PTR(Unsafe_AllocateInstance)},
+    {CC "monitorEnter",       CC "(" OBJ ")V",               FN_PTR(Unsafe_MonitorEnter)},
+    {CC "monitorExit",        CC "(" OBJ ")V",               FN_PTR(Unsafe_MonitorExit)},
+    {CC "throwException",     CC "(" THR ")V",               FN_PTR(Unsafe_ThrowException)}
 };
 
 // These are the methods prior to the JSR 166 changes in 1.5.0
 static JNINativeMethod methods_141[] = {
-    {CC"getObject",        CC"("OBJ"J)"OBJ"",   FN_PTR(Unsafe_GetObject)},
-    {CC"putObject",        CC"("OBJ"J"OBJ")V",  FN_PTR(Unsafe_SetObject)},
+    {CC "getObject",        CC "(" OBJ "J)" OBJ "",   FN_PTR(Unsafe_GetObject)},
+    {CC "putObject",        CC "(" OBJ "J" OBJ ")V",  FN_PTR(Unsafe_SetObject)},
 
     DECLARE_GETSETOOP_141(Boolean, Z),
     DECLARE_GETSETOOP_141(Byte, B),
@@ -1470,37 +1454,37 @@
     DECLARE_GETSETNATIVE(Float, F),
     DECLARE_GETSETNATIVE(Double, D),
 
-    {CC"getAddress",         CC"("ADR")"ADR,             FN_PTR(Unsafe_GetNativeAddress)},
-    {CC"putAddress",         CC"("ADR""ADR")V",          FN_PTR(Unsafe_SetNativeAddress)},
+    {CC "getAddress",         CC "(" ADR ")" ADR,             FN_PTR(Unsafe_GetNativeAddress)},
+    {CC "putAddress",         CC "(" ADR "" ADR ")V",          FN_PTR(Unsafe_SetNativeAddress)},
 
-    {CC"allocateMemory",     CC"(J)"ADR,                 FN_PTR(Unsafe_AllocateMemory)},
-    {CC"reallocateMemory",   CC"("ADR"J)"ADR,            FN_PTR(Unsafe_ReallocateMemory)},
-    {CC"freeMemory",         CC"("ADR")V",               FN_PTR(Unsafe_FreeMemory)},
+    {CC "allocateMemory",     CC "(J)" ADR,                 FN_PTR(Unsafe_AllocateMemory)},
+    {CC "reallocateMemory",   CC "(" ADR "J)" ADR,            FN_PTR(Unsafe_ReallocateMemory)},
+    {CC "freeMemory",         CC "(" ADR ")V",               FN_PTR(Unsafe_FreeMemory)},
 
-    {CC"objectFieldOffset",  CC"("FLD")J",               FN_PTR(Unsafe_ObjectFieldOffset)},
-    {CC"staticFieldOffset",  CC"("FLD")J",               FN_PTR(Unsafe_StaticFieldOffset)},
-    {CC"staticFieldBase",    CC"("FLD")"OBJ,             FN_PTR(Unsafe_StaticFieldBaseFromField)},
-    {CC"ensureClassInitialized",CC"("CLS")V",            FN_PTR(Unsafe_EnsureClassInitialized)},
-    {CC"arrayBaseOffset",    CC"("CLS")I",               FN_PTR(Unsafe_ArrayBaseOffset)},
-    {CC"arrayIndexScale",    CC"("CLS")I",               FN_PTR(Unsafe_ArrayIndexScale)},
-    {CC"addressSize",        CC"()I",                    FN_PTR(Unsafe_AddressSize)},
-    {CC"pageSize",           CC"()I",                    FN_PTR(Unsafe_PageSize)},
+    {CC "objectFieldOffset",  CC "(" FLD ")J",               FN_PTR(Unsafe_ObjectFieldOffset)},
+    {CC "staticFieldOffset",  CC "(" FLD ")J",               FN_PTR(Unsafe_StaticFieldOffset)},
+    {CC "staticFieldBase",    CC "(" FLD ")" OBJ,             FN_PTR(Unsafe_StaticFieldBaseFromField)},
+    {CC "ensureClassInitialized",CC "(" CLS ")V",            FN_PTR(Unsafe_EnsureClassInitialized)},
+    {CC "arrayBaseOffset",    CC "(" CLS ")I",               FN_PTR(Unsafe_ArrayBaseOffset)},
+    {CC "arrayIndexScale",    CC "(" CLS ")I",               FN_PTR(Unsafe_ArrayIndexScale)},
+    {CC "addressSize",        CC "()I",                    FN_PTR(Unsafe_AddressSize)},
+    {CC "pageSize",           CC "()I",                    FN_PTR(Unsafe_PageSize)},
 
-    {CC"defineClass",        CC"("DC0_Args")"CLS,        FN_PTR(Unsafe_DefineClass0)},
-    {CC"defineClass",        CC"("DC_Args")"CLS,         FN_PTR(Unsafe_DefineClass)},
-    {CC"allocateInstance",   CC"("CLS")"OBJ,             FN_PTR(Unsafe_AllocateInstance)},
-    {CC"monitorEnter",       CC"("OBJ")V",               FN_PTR(Unsafe_MonitorEnter)},
-    {CC"monitorExit",        CC"("OBJ")V",               FN_PTR(Unsafe_MonitorExit)},
-    {CC"throwException",     CC"("THR")V",               FN_PTR(Unsafe_ThrowException)}
+    {CC "defineClass",        CC "(" DC0_Args ")" CLS,        FN_PTR(Unsafe_DefineClass0)},
+    {CC "defineClass",        CC "(" DC_Args ")" CLS,         FN_PTR(Unsafe_DefineClass)},
+    {CC "allocateInstance",   CC "(" CLS ")" OBJ,             FN_PTR(Unsafe_AllocateInstance)},
+    {CC "monitorEnter",       CC "(" OBJ ")V",               FN_PTR(Unsafe_MonitorEnter)},
+    {CC "monitorExit",        CC "(" OBJ ")V",               FN_PTR(Unsafe_MonitorExit)},
+    {CC "throwException",     CC "(" THR ")V",               FN_PTR(Unsafe_ThrowException)}
 
 };
 
 // These are the methods prior to the JSR 166 changes in 1.6.0
 static JNINativeMethod methods_15[] = {
-    {CC"getObject",        CC"("OBJ"J)"OBJ"",   FN_PTR(Unsafe_GetObject)},
-    {CC"putObject",        CC"("OBJ"J"OBJ")V",  FN_PTR(Unsafe_SetObject)},
-    {CC"getObjectVolatile",CC"("OBJ"J)"OBJ"",   FN_PTR(Unsafe_GetObjectVolatile)},
-    {CC"putObjectVolatile",CC"("OBJ"J"OBJ")V",  FN_PTR(Unsafe_SetObjectVolatile)},
+    {CC "getObject",        CC "(" OBJ "J)" OBJ "",   FN_PTR(Unsafe_GetObject)},
+    {CC "putObject",        CC "(" OBJ "J" OBJ ")V",  FN_PTR(Unsafe_SetObject)},
+    {CC "getObjectVolatile",CC "(" OBJ "J)" OBJ "",   FN_PTR(Unsafe_GetObjectVolatile)},
+    {CC "putObjectVolatile",CC "(" OBJ "J" OBJ ")V",  FN_PTR(Unsafe_SetObjectVolatile)},
 
 
     DECLARE_GETSETOOP(Boolean, Z),
@@ -1520,42 +1504,42 @@
     DECLARE_GETSETNATIVE(Float, F),
     DECLARE_GETSETNATIVE(Double, D),
 
-    {CC"getAddress",         CC"("ADR")"ADR,             FN_PTR(Unsafe_GetNativeAddress)},
-    {CC"putAddress",         CC"("ADR""ADR")V",          FN_PTR(Unsafe_SetNativeAddress)},
+    {CC "getAddress",         CC "(" ADR ")" ADR,             FN_PTR(Unsafe_GetNativeAddress)},
+    {CC "putAddress",         CC "(" ADR "" ADR ")V",          FN_PTR(Unsafe_SetNativeAddress)},
 
-    {CC"allocateMemory",     CC"(J)"ADR,                 FN_PTR(Unsafe_AllocateMemory)},
-    {CC"reallocateMemory",   CC"("ADR"J)"ADR,            FN_PTR(Unsafe_ReallocateMemory)},
-    {CC"freeMemory",         CC"("ADR")V",               FN_PTR(Unsafe_FreeMemory)},
+    {CC "allocateMemory",     CC "(J)" ADR,                 FN_PTR(Unsafe_AllocateMemory)},
+    {CC "reallocateMemory",   CC "(" ADR "J)" ADR,            FN_PTR(Unsafe_ReallocateMemory)},
+    {CC "freeMemory",         CC "(" ADR ")V",               FN_PTR(Unsafe_FreeMemory)},
 
-    {CC"objectFieldOffset",  CC"("FLD")J",               FN_PTR(Unsafe_ObjectFieldOffset)},
-    {CC"staticFieldOffset",  CC"("FLD")J",               FN_PTR(Unsafe_StaticFieldOffset)},
-    {CC"staticFieldBase",    CC"("FLD")"OBJ,             FN_PTR(Unsafe_StaticFieldBaseFromField)},
-    {CC"ensureClassInitialized",CC"("CLS")V",            FN_PTR(Unsafe_EnsureClassInitialized)},
-    {CC"arrayBaseOffset",    CC"("CLS")I",               FN_PTR(Unsafe_ArrayBaseOffset)},
-    {CC"arrayIndexScale",    CC"("CLS")I",               FN_PTR(Unsafe_ArrayIndexScale)},
-    {CC"addressSize",        CC"()I",                    FN_PTR(Unsafe_AddressSize)},
-    {CC"pageSize",           CC"()I",                    FN_PTR(Unsafe_PageSize)},
+    {CC "objectFieldOffset",  CC "(" FLD ")J",               FN_PTR(Unsafe_ObjectFieldOffset)},
+    {CC "staticFieldOffset",  CC "(" FLD ")J",               FN_PTR(Unsafe_StaticFieldOffset)},
+    {CC "staticFieldBase",    CC "(" FLD ")" OBJ,             FN_PTR(Unsafe_StaticFieldBaseFromField)},
+    {CC "ensureClassInitialized",CC "(" CLS ")V",            FN_PTR(Unsafe_EnsureClassInitialized)},
+    {CC "arrayBaseOffset",    CC "(" CLS ")I",               FN_PTR(Unsafe_ArrayBaseOffset)},
+    {CC "arrayIndexScale",    CC "(" CLS ")I",               FN_PTR(Unsafe_ArrayIndexScale)},
+    {CC "addressSize",        CC "()I",                    FN_PTR(Unsafe_AddressSize)},
+    {CC "pageSize",           CC "()I",                    FN_PTR(Unsafe_PageSize)},
 
-    {CC"defineClass",        CC"("DC0_Args")"CLS,        FN_PTR(Unsafe_DefineClass0)},
-    {CC"defineClass",        CC"("DC_Args")"CLS,         FN_PTR(Unsafe_DefineClass)},
-    {CC"allocateInstance",   CC"("CLS")"OBJ,             FN_PTR(Unsafe_AllocateInstance)},
-    {CC"monitorEnter",       CC"("OBJ")V",               FN_PTR(Unsafe_MonitorEnter)},
-    {CC"monitorExit",        CC"("OBJ")V",               FN_PTR(Unsafe_MonitorExit)},
-    {CC"throwException",     CC"("THR")V",               FN_PTR(Unsafe_ThrowException)},
-    {CC"compareAndSwapObject", CC"("OBJ"J"OBJ""OBJ")Z",  FN_PTR(Unsafe_CompareAndSwapObject)},
-    {CC"compareAndSwapInt",  CC"("OBJ"J""I""I"")Z",      FN_PTR(Unsafe_CompareAndSwapInt)},
-    {CC"compareAndSwapLong", CC"("OBJ"J""J""J"")Z",      FN_PTR(Unsafe_CompareAndSwapLong)},
-    {CC"park",               CC"(ZJ)V",                  FN_PTR(Unsafe_Park)},
-    {CC"unpark",             CC"("OBJ")V",               FN_PTR(Unsafe_Unpark)}
+    {CC "defineClass",        CC "(" DC0_Args ")" CLS,        FN_PTR(Unsafe_DefineClass0)},
+    {CC "defineClass",        CC "(" DC_Args ")" CLS,         FN_PTR(Unsafe_DefineClass)},
+    {CC "allocateInstance",   CC "(" CLS ")" OBJ,             FN_PTR(Unsafe_AllocateInstance)},
+    {CC "monitorEnter",       CC "(" OBJ ")V",               FN_PTR(Unsafe_MonitorEnter)},
+    {CC "monitorExit",        CC "(" OBJ ")V",               FN_PTR(Unsafe_MonitorExit)},
+    {CC "throwException",     CC "(" THR ")V",               FN_PTR(Unsafe_ThrowException)},
+    {CC "compareAndSwapObject", CC "(" OBJ "J" OBJ "" OBJ ")Z",  FN_PTR(Unsafe_CompareAndSwapObject)},
+    {CC "compareAndSwapInt",  CC "(" OBJ "J""I""I"")Z",      FN_PTR(Unsafe_CompareAndSwapInt)},
+    {CC "compareAndSwapLong", CC "(" OBJ "J""J""J"")Z",      FN_PTR(Unsafe_CompareAndSwapLong)},
+    {CC "park",               CC "(ZJ)V",                  FN_PTR(Unsafe_Park)},
+    {CC "unpark",             CC "(" OBJ ")V",               FN_PTR(Unsafe_Unpark)}
 
 };
 
 // These are the methods for 1.6.0 and 1.7.0
 static JNINativeMethod methods_16[] = {
-    {CC"getObject",        CC"("OBJ"J)"OBJ"",   FN_PTR(Unsafe_GetObject)},
-    {CC"putObject",        CC"("OBJ"J"OBJ")V",  FN_PTR(Unsafe_SetObject)},
-    {CC"getObjectVolatile",CC"("OBJ"J)"OBJ"",   FN_PTR(Unsafe_GetObjectVolatile)},
-    {CC"putObjectVolatile",CC"("OBJ"J"OBJ")V",  FN_PTR(Unsafe_SetObjectVolatile)},
+    {CC "getObject",        CC "(" OBJ "J)" OBJ "",   FN_PTR(Unsafe_GetObject)},
+    {CC "putObject",        CC "(" OBJ "J" OBJ ")V",  FN_PTR(Unsafe_SetObject)},
+    {CC "getObjectVolatile",CC "(" OBJ "J)" OBJ "",   FN_PTR(Unsafe_GetObjectVolatile)},
+    {CC "putObjectVolatile",CC "(" OBJ "J" OBJ ")V",  FN_PTR(Unsafe_SetObjectVolatile)},
 
     DECLARE_GETSETOOP(Boolean, Z),
     DECLARE_GETSETOOP(Byte, B),
@@ -1574,45 +1558,45 @@
     DECLARE_GETSETNATIVE(Float, F),
     DECLARE_GETSETNATIVE(Double, D),
 
-    {CC"getAddress",         CC"("ADR")"ADR,             FN_PTR(Unsafe_GetNativeAddress)},
-    {CC"putAddress",         CC"("ADR""ADR")V",          FN_PTR(Unsafe_SetNativeAddress)},
+    {CC "getAddress",         CC "(" ADR ")" ADR,             FN_PTR(Unsafe_GetNativeAddress)},
+    {CC "putAddress",         CC "(" ADR "" ADR ")V",          FN_PTR(Unsafe_SetNativeAddress)},
 
-    {CC"allocateMemory",     CC"(J)"ADR,                 FN_PTR(Unsafe_AllocateMemory)},
-    {CC"reallocateMemory",   CC"("ADR"J)"ADR,            FN_PTR(Unsafe_ReallocateMemory)},
-    {CC"freeMemory",         CC"("ADR")V",               FN_PTR(Unsafe_FreeMemory)},
+    {CC "allocateMemory",     CC "(J)" ADR,                 FN_PTR(Unsafe_AllocateMemory)},
+    {CC "reallocateMemory",   CC "(" ADR "J)" ADR,            FN_PTR(Unsafe_ReallocateMemory)},
+    {CC "freeMemory",         CC "(" ADR ")V",               FN_PTR(Unsafe_FreeMemory)},
 
-    {CC"objectFieldOffset",  CC"("FLD")J",               FN_PTR(Unsafe_ObjectFieldOffset)},
-    {CC"staticFieldOffset",  CC"("FLD")J",               FN_PTR(Unsafe_StaticFieldOffset)},
-    {CC"staticFieldBase",    CC"("FLD")"OBJ,             FN_PTR(Unsafe_StaticFieldBaseFromField)},
-    {CC"ensureClassInitialized",CC"("CLS")V",            FN_PTR(Unsafe_EnsureClassInitialized)},
-    {CC"arrayBaseOffset",    CC"("CLS")I",               FN_PTR(Unsafe_ArrayBaseOffset)},
-    {CC"arrayIndexScale",    CC"("CLS")I",               FN_PTR(Unsafe_ArrayIndexScale)},
-    {CC"addressSize",        CC"()I",                    FN_PTR(Unsafe_AddressSize)},
-    {CC"pageSize",           CC"()I",                    FN_PTR(Unsafe_PageSize)},
+    {CC "objectFieldOffset",  CC "(" FLD ")J",               FN_PTR(Unsafe_ObjectFieldOffset)},
+    {CC "staticFieldOffset",  CC "(" FLD ")J",               FN_PTR(Unsafe_StaticFieldOffset)},
+    {CC "staticFieldBase",    CC "(" FLD ")" OBJ,             FN_PTR(Unsafe_StaticFieldBaseFromField)},
+    {CC "ensureClassInitialized",CC "(" CLS ")V",            FN_PTR(Unsafe_EnsureClassInitialized)},
+    {CC "arrayBaseOffset",    CC "(" CLS ")I",               FN_PTR(Unsafe_ArrayBaseOffset)},
+    {CC "arrayIndexScale",    CC "(" CLS ")I",               FN_PTR(Unsafe_ArrayIndexScale)},
+    {CC "addressSize",        CC "()I",                    FN_PTR(Unsafe_AddressSize)},
+    {CC "pageSize",           CC "()I",                    FN_PTR(Unsafe_PageSize)},
 
-    {CC"defineClass",        CC"("DC0_Args")"CLS,        FN_PTR(Unsafe_DefineClass0)},
-    {CC"defineClass",        CC"("DC_Args")"CLS,         FN_PTR(Unsafe_DefineClass)},
-    {CC"allocateInstance",   CC"("CLS")"OBJ,             FN_PTR(Unsafe_AllocateInstance)},
-    {CC"monitorEnter",       CC"("OBJ")V",               FN_PTR(Unsafe_MonitorEnter)},
-    {CC"monitorExit",        CC"("OBJ")V",               FN_PTR(Unsafe_MonitorExit)},
-    {CC"tryMonitorEnter",    CC"("OBJ")Z",               FN_PTR(Unsafe_TryMonitorEnter)},
-    {CC"throwException",     CC"("THR")V",               FN_PTR(Unsafe_ThrowException)},
-    {CC"compareAndSwapObject", CC"("OBJ"J"OBJ""OBJ")Z",  FN_PTR(Unsafe_CompareAndSwapObject)},
-    {CC"compareAndSwapInt",  CC"("OBJ"J""I""I"")Z",      FN_PTR(Unsafe_CompareAndSwapInt)},
-    {CC"compareAndSwapLong", CC"("OBJ"J""J""J"")Z",      FN_PTR(Unsafe_CompareAndSwapLong)},
-    {CC"putOrderedObject",   CC"("OBJ"J"OBJ")V",         FN_PTR(Unsafe_SetOrderedObject)},
-    {CC"putOrderedInt",      CC"("OBJ"JI)V",             FN_PTR(Unsafe_SetOrderedInt)},
-    {CC"putOrderedLong",     CC"("OBJ"JJ)V",             FN_PTR(Unsafe_SetOrderedLong)},
-    {CC"park",               CC"(ZJ)V",                  FN_PTR(Unsafe_Park)},
-    {CC"unpark",             CC"("OBJ")V",               FN_PTR(Unsafe_Unpark)}
+    {CC "defineClass",        CC "(" DC0_Args ")" CLS,        FN_PTR(Unsafe_DefineClass0)},
+    {CC "defineClass",        CC "(" DC_Args ")" CLS,         FN_PTR(Unsafe_DefineClass)},
+    {CC "allocateInstance",   CC "(" CLS ")" OBJ,             FN_PTR(Unsafe_AllocateInstance)},
+    {CC "monitorEnter",       CC "(" OBJ ")V",               FN_PTR(Unsafe_MonitorEnter)},
+    {CC "monitorExit",        CC "(" OBJ ")V",               FN_PTR(Unsafe_MonitorExit)},
+    {CC "tryMonitorEnter",    CC "(" OBJ ")Z",               FN_PTR(Unsafe_TryMonitorEnter)},
+    {CC "throwException",     CC "(" THR ")V",               FN_PTR(Unsafe_ThrowException)},
+    {CC "compareAndSwapObject", CC "(" OBJ "J" OBJ "" OBJ ")Z",  FN_PTR(Unsafe_CompareAndSwapObject)},
+    {CC "compareAndSwapInt",  CC "(" OBJ "J""I""I"")Z",      FN_PTR(Unsafe_CompareAndSwapInt)},
+    {CC "compareAndSwapLong", CC "(" OBJ "J""J""J"")Z",      FN_PTR(Unsafe_CompareAndSwapLong)},
+    {CC "putOrderedObject",   CC "(" OBJ "J" OBJ ")V",         FN_PTR(Unsafe_SetOrderedObject)},
+    {CC "putOrderedInt",      CC "(" OBJ "JI)V",             FN_PTR(Unsafe_SetOrderedInt)},
+    {CC "putOrderedLong",     CC "(" OBJ "JJ)V",             FN_PTR(Unsafe_SetOrderedLong)},
+    {CC "park",               CC "(ZJ)V",                  FN_PTR(Unsafe_Park)},
+    {CC "unpark",             CC "(" OBJ ")V",               FN_PTR(Unsafe_Unpark)}
 };
 
 // These are the methods for 1.8.0
 static JNINativeMethod methods_18[] = {
-    {CC"getObject",        CC"("OBJ"J)"OBJ"",   FN_PTR(Unsafe_GetObject)},
-    {CC"putObject",        CC"("OBJ"J"OBJ")V",  FN_PTR(Unsafe_SetObject)},
-    {CC"getObjectVolatile",CC"("OBJ"J)"OBJ"",   FN_PTR(Unsafe_GetObjectVolatile)},
-    {CC"putObjectVolatile",CC"("OBJ"J"OBJ")V",  FN_PTR(Unsafe_SetObjectVolatile)},
+    {CC "getObject",        CC "(" OBJ "J)" OBJ "",   FN_PTR(Unsafe_GetObject)},
+    {CC "putObject",        CC "(" OBJ "J" OBJ ")V",  FN_PTR(Unsafe_SetObject)},
+    {CC "getObjectVolatile",CC "(" OBJ "J)" OBJ "",   FN_PTR(Unsafe_GetObjectVolatile)},
+    {CC "putObjectVolatile",CC "(" OBJ "J" OBJ ")V",  FN_PTR(Unsafe_SetObjectVolatile)},
 
     DECLARE_GETSETOOP(Boolean, Z),
     DECLARE_GETSETOOP(Byte, B),
@@ -1631,71 +1615,71 @@
     DECLARE_GETSETNATIVE(Float, F),
     DECLARE_GETSETNATIVE(Double, D),
 
-    {CC"getAddress",         CC"("ADR")"ADR,             FN_PTR(Unsafe_GetNativeAddress)},
-    {CC"putAddress",         CC"("ADR""ADR")V",          FN_PTR(Unsafe_SetNativeAddress)},
+    {CC "getAddress",         CC "(" ADR ")" ADR,             FN_PTR(Unsafe_GetNativeAddress)},
+    {CC "putAddress",         CC "(" ADR "" ADR ")V",          FN_PTR(Unsafe_SetNativeAddress)},
 
-    {CC"allocateMemory",     CC"(J)"ADR,                 FN_PTR(Unsafe_AllocateMemory)},
-    {CC"reallocateMemory",   CC"("ADR"J)"ADR,            FN_PTR(Unsafe_ReallocateMemory)},
-    {CC"freeMemory",         CC"("ADR")V",               FN_PTR(Unsafe_FreeMemory)},
+    {CC "allocateMemory",     CC "(J)" ADR,                 FN_PTR(Unsafe_AllocateMemory)},
+    {CC "reallocateMemory",   CC "(" ADR "J)" ADR,            FN_PTR(Unsafe_ReallocateMemory)},
+    {CC "freeMemory",         CC "(" ADR ")V",               FN_PTR(Unsafe_FreeMemory)},
 
-    {CC"objectFieldOffset",  CC"("FLD")J",               FN_PTR(Unsafe_ObjectFieldOffset)},
-    {CC"staticFieldOffset",  CC"("FLD")J",               FN_PTR(Unsafe_StaticFieldOffset)},
-    {CC"staticFieldBase",    CC"("FLD")"OBJ,             FN_PTR(Unsafe_StaticFieldBaseFromField)},
-    {CC"ensureClassInitialized",CC"("CLS")V",            FN_PTR(Unsafe_EnsureClassInitialized)},
-    {CC"arrayBaseOffset",    CC"("CLS")I",               FN_PTR(Unsafe_ArrayBaseOffset)},
-    {CC"arrayIndexScale",    CC"("CLS")I",               FN_PTR(Unsafe_ArrayIndexScale)},
-    {CC"addressSize",        CC"()I",                    FN_PTR(Unsafe_AddressSize)},
-    {CC"pageSize",           CC"()I",                    FN_PTR(Unsafe_PageSize)},
+    {CC "objectFieldOffset",  CC "(" FLD ")J",               FN_PTR(Unsafe_ObjectFieldOffset)},
+    {CC "staticFieldOffset",  CC "(" FLD ")J",               FN_PTR(Unsafe_StaticFieldOffset)},
+    {CC "staticFieldBase",    CC "(" FLD ")" OBJ,             FN_PTR(Unsafe_StaticFieldBaseFromField)},
+    {CC "ensureClassInitialized",CC "(" CLS ")V",            FN_PTR(Unsafe_EnsureClassInitialized)},
+    {CC "arrayBaseOffset",    CC "(" CLS ")I",               FN_PTR(Unsafe_ArrayBaseOffset)},
+    {CC "arrayIndexScale",    CC "(" CLS ")I",               FN_PTR(Unsafe_ArrayIndexScale)},
+    {CC "addressSize",        CC "()I",                    FN_PTR(Unsafe_AddressSize)},
+    {CC "pageSize",           CC "()I",                    FN_PTR(Unsafe_PageSize)},
 
-    {CC"defineClass",        CC"("DC_Args")"CLS,         FN_PTR(Unsafe_DefineClass)},
-    {CC"allocateInstance",   CC"("CLS")"OBJ,             FN_PTR(Unsafe_AllocateInstance)},
-    {CC"monitorEnter",       CC"("OBJ")V",               FN_PTR(Unsafe_MonitorEnter)},
-    {CC"monitorExit",        CC"("OBJ")V",               FN_PTR(Unsafe_MonitorExit)},
-    {CC"tryMonitorEnter",    CC"("OBJ")Z",               FN_PTR(Unsafe_TryMonitorEnter)},
-    {CC"throwException",     CC"("THR")V",               FN_PTR(Unsafe_ThrowException)},
-    {CC"compareAndSwapObject", CC"("OBJ"J"OBJ""OBJ")Z",  FN_PTR(Unsafe_CompareAndSwapObject)},
-    {CC"compareAndSwapInt",  CC"("OBJ"J""I""I"")Z",      FN_PTR(Unsafe_CompareAndSwapInt)},
-    {CC"compareAndSwapLong", CC"("OBJ"J""J""J"")Z",      FN_PTR(Unsafe_CompareAndSwapLong)},
-    {CC"putOrderedObject",   CC"("OBJ"J"OBJ")V",         FN_PTR(Unsafe_SetOrderedObject)},
-    {CC"putOrderedInt",      CC"("OBJ"JI)V",             FN_PTR(Unsafe_SetOrderedInt)},
-    {CC"putOrderedLong",     CC"("OBJ"JJ)V",             FN_PTR(Unsafe_SetOrderedLong)},
-    {CC"park",               CC"(ZJ)V",                  FN_PTR(Unsafe_Park)},
-    {CC"unpark",             CC"("OBJ")V",               FN_PTR(Unsafe_Unpark)}
+    {CC "defineClass",        CC "(" DC_Args ")" CLS,         FN_PTR(Unsafe_DefineClass)},
+    {CC "allocateInstance",   CC "(" CLS ")" OBJ,             FN_PTR(Unsafe_AllocateInstance)},
+    {CC "monitorEnter",       CC "(" OBJ ")V",               FN_PTR(Unsafe_MonitorEnter)},
+    {CC "monitorExit",        CC "(" OBJ ")V",               FN_PTR(Unsafe_MonitorExit)},
+    {CC "tryMonitorEnter",    CC "(" OBJ ")Z",               FN_PTR(Unsafe_TryMonitorEnter)},
+    {CC "throwException",     CC "(" THR ")V",               FN_PTR(Unsafe_ThrowException)},
+    {CC "compareAndSwapObject", CC "(" OBJ "J" OBJ "" OBJ ")Z",  FN_PTR(Unsafe_CompareAndSwapObject)},
+    {CC "compareAndSwapInt",  CC "(" OBJ "J""I""I"")Z",      FN_PTR(Unsafe_CompareAndSwapInt)},
+    {CC "compareAndSwapLong", CC "(" OBJ "J""J""J"")Z",      FN_PTR(Unsafe_CompareAndSwapLong)},
+    {CC "putOrderedObject",   CC "(" OBJ "J" OBJ ")V",         FN_PTR(Unsafe_SetOrderedObject)},
+    {CC "putOrderedInt",      CC "(" OBJ "JI)V",             FN_PTR(Unsafe_SetOrderedInt)},
+    {CC "putOrderedLong",     CC "(" OBJ "JJ)V",             FN_PTR(Unsafe_SetOrderedLong)},
+    {CC "park",               CC "(ZJ)V",                  FN_PTR(Unsafe_Park)},
+    {CC "unpark",             CC "(" OBJ ")V",               FN_PTR(Unsafe_Unpark)}
 };
 
 JNINativeMethod loadavg_method[] = {
-    {CC"getLoadAverage",     CC"([DI)I",                 FN_PTR(Unsafe_Loadavg)}
+    {CC "getLoadAverage",     CC "([DI)I",                 FN_PTR(Unsafe_Loadavg)}
 };
 
 JNINativeMethod prefetch_methods[] = {
-    {CC"prefetchRead",       CC"("OBJ"J)V",              FN_PTR(Unsafe_PrefetchRead)},
-    {CC"prefetchWrite",      CC"("OBJ"J)V",              FN_PTR(Unsafe_PrefetchWrite)},
-    {CC"prefetchReadStatic", CC"("OBJ"J)V",              FN_PTR(Unsafe_PrefetchRead)},
-    {CC"prefetchWriteStatic",CC"("OBJ"J)V",              FN_PTR(Unsafe_PrefetchWrite)}
+    {CC "prefetchRead",       CC "(" OBJ "J)V",              FN_PTR(Unsafe_PrefetchRead)},
+    {CC "prefetchWrite",      CC "(" OBJ "J)V",              FN_PTR(Unsafe_PrefetchWrite)},
+    {CC "prefetchReadStatic", CC "(" OBJ "J)V",              FN_PTR(Unsafe_PrefetchRead)},
+    {CC "prefetchWriteStatic",CC "(" OBJ "J)V",              FN_PTR(Unsafe_PrefetchWrite)}
 };
 
 JNINativeMethod memcopy_methods_17[] = {
-    {CC"copyMemory",         CC"("OBJ"J"OBJ"JJ)V",       FN_PTR(Unsafe_CopyMemory2)},
-    {CC"setMemory",          CC"("OBJ"JJB)V",            FN_PTR(Unsafe_SetMemory2)}
+    {CC "copyMemory",         CC "(" OBJ "J" OBJ "JJ)V",       FN_PTR(Unsafe_CopyMemory2)},
+    {CC "setMemory",          CC "(" OBJ "JJB)V",            FN_PTR(Unsafe_SetMemory2)}
 };
 
 JNINativeMethod memcopy_methods_15[] = {
-    {CC"setMemory",          CC"("ADR"JB)V",             FN_PTR(Unsafe_SetMemory)},
-    {CC"copyMemory",         CC"("ADR ADR"J)V",          FN_PTR(Unsafe_CopyMemory)}
+    {CC "setMemory",          CC "(" ADR "JB)V",             FN_PTR(Unsafe_SetMemory)},
+    {CC "copyMemory",         CC "(" ADR ADR "J)V",          FN_PTR(Unsafe_CopyMemory)}
 };
 
 JNINativeMethod anonk_methods[] = {
-    {CC"defineAnonymousClass", CC"("DAC_Args")"CLS,      FN_PTR(Unsafe_DefineAnonymousClass)},
+    {CC "defineAnonymousClass", CC "(" DAC_Args ")" CLS,      FN_PTR(Unsafe_DefineAnonymousClass)},
 };
 
 JNINativeMethod lform_methods[] = {
-    {CC"shouldBeInitialized",CC"("CLS")Z",               FN_PTR(Unsafe_ShouldBeInitialized)},
+    {CC "shouldBeInitialized",CC "(" CLS ")Z",               FN_PTR(Unsafe_ShouldBeInitialized)},
 };
 
 JNINativeMethod fence_methods[] = {
-    {CC"loadFence",          CC"()V",                    FN_PTR(Unsafe_LoadFence)},
-    {CC"storeFence",         CC"()V",                    FN_PTR(Unsafe_StoreFence)},
-    {CC"fullFence",          CC"()V",                    FN_PTR(Unsafe_FullFence)},
+    {CC "loadFence",          CC "()V",                    FN_PTR(Unsafe_LoadFence)},
+    {CC "storeFence",         CC "()V",                    FN_PTR(Unsafe_StoreFence)},
+    {CC "fullFence",          CC "()V",                    FN_PTR(Unsafe_FullFence)},
 };
 
 #undef CC
diff --git a/src/share/vm/prims/whitebox.cpp b/src/share/vm/prims/whitebox.cpp
index c3e0688..a778daf 100644
--- a/src/share/vm/prims/whitebox.cpp
+++ b/src/share/vm/prims/whitebox.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -158,6 +158,10 @@
 }
 WB_END
 
+#ifdef LINUX
+#include "utilities/elfFile.hpp"
+#include "osContainer_linux.hpp"
+#endif
 
 WB_ENTRY(jlong, WB_GetCompressedOopsMaxHeapSize(JNIEnv* env, jobject o)) {
   return (jlong)Arguments::max_heap_for_compressed_oops();
@@ -166,8 +170,8 @@
 
 WB_ENTRY(void, WB_PrintHeapSizes(JNIEnv* env, jobject o)) {
   CollectorPolicy * p = Universe::heap()->collector_policy();
-  gclog_or_tty->print_cr("Minimum heap "SIZE_FORMAT" Initial heap "
-    SIZE_FORMAT" Maximum heap "SIZE_FORMAT" Min alignment "SIZE_FORMAT" Max alignment "SIZE_FORMAT,
+  gclog_or_tty->print_cr("Minimum heap " SIZE_FORMAT " Initial heap "
+    SIZE_FORMAT" Maximum heap " SIZE_FORMAT " Min alignment " SIZE_FORMAT " Max alignment " SIZE_FORMAT,
     p->min_heap_byte_size(), p->initial_heap_byte_size(), p->max_heap_byte_size(),
     p->space_alignment(), p->heap_alignment());
 }
@@ -202,8 +206,8 @@
          Universe::narrow_oop_use_implicit_null_checks() )) {
     tty->print_cr("WB_ReadFromNoaccessArea method is useless:\n "
                   "\tUseCompressedOops is %d\n"
-                  "\trhs.base() is "PTR_FORMAT"\n"
-                  "\tUniverse::narrow_oop_base() is "PTR_FORMAT"\n"
+                  "\trhs.base() is " PTR_FORMAT "\n"
+                  "\tUniverse::narrow_oop_base() is " PTR_FORMAT "\n"
                   "\tUniverse::narrow_oop_use_implicit_null_checks() is %d",
                   UseCompressedOops,
                   rhs.base(),
@@ -256,8 +260,8 @@
 
 WB_ENTRY(jint, WB_StressVirtualSpaceResize(JNIEnv* env, jobject o,
         jlong reserved_space_size, jlong magnitude, jlong iterations))
-  tty->print_cr("reservedSpaceSize="JLONG_FORMAT", magnitude="JLONG_FORMAT", "
-                "iterations="JLONG_FORMAT"\n", reserved_space_size, magnitude,
+  tty->print_cr("reservedSpaceSize=" JLONG_FORMAT ", magnitude=" JLONG_FORMAT ", "
+                "iterations=" JLONG_FORMAT "\n", reserved_space_size, magnitude,
                 iterations);
   if (reserved_space_size < 0 || magnitude < 0 || iterations < 0) {
     tty->print_cr("One of variables printed above is negative. Can't proceed.\n");
@@ -1010,6 +1014,30 @@
   }
 }
 
+// Checks that the library libfile has the noexecstack bit set.
+WB_ENTRY(jboolean, WB_CheckLibSpecifiesNoexecstack(JNIEnv* env, jobject o, jstring libfile))
+  jboolean ret = false;
+#ifdef LINUX
+  // Can't be in VM when we call JNI.
+  ThreadToNativeFromVM ttnfv(thread);
+  const char* lf = env->GetStringUTFChars(libfile, NULL);
+  CHECK_JNI_EXCEPTION_(env, 0);
+  ElfFile ef(lf);
+  ret = (jboolean) ef.specifies_noexecstack();
+  env->ReleaseStringUTFChars(libfile, lf);
+#endif
+  return ret;
+WB_END
+
+WB_ENTRY(jboolean, WB_IsContainerized(JNIEnv* env, jobject o))
+  LINUX_ONLY(return OSContainer::is_containerized();)
+  return false;
+WB_END
+
+WB_ENTRY(void, WB_PrintOsInfo(JNIEnv* env, jobject o))
+  os::print_os_info(tty);
+WB_END
+
 #define CC (char*)
 
 static JNINativeMethod methods[] = {
@@ -1121,6 +1149,10 @@
                                                       (void*)&WB_GetNMethod         },
   {CC"isMonitorInflated",  CC"(Ljava/lang/Object;)Z", (void*)&WB_IsMonitorInflated  },
   {CC"forceSafepoint",     CC"()V",                   (void*)&WB_ForceSafepoint     },
+  {CC"checkLibSpecifiesNoexecstack", CC"(Ljava/lang/String;)Z",
+                                                      (void*)&WB_CheckLibSpecifiesNoexecstack},
+  {CC"isContainerized",           CC"()Z",            (void*)&WB_IsContainerized },
+  {CC"printOsInfo",               CC"()V",            (void*)&WB_PrintOsInfo },
 };
 
 #undef CC
diff --git a/src/share/vm/runtime/arguments.cpp b/src/share/vm/runtime/arguments.cpp
index 204a991..d914c73 100644
--- a/src/share/vm/runtime/arguments.cpp
+++ b/src/share/vm/runtime/arguments.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1377,11 +1377,6 @@
     CFLS_LAB::modify_initialization(OldPLABSize, OldPLABWeight);
   }
 
-  if (!ClassUnloading) {
-    FLAG_SET_CMDLINE(bool, CMSClassUnloadingEnabled, false);
-    FLAG_SET_CMDLINE(bool, ExplicitGCInvokesConcurrentAndUnloadsClasses, false);
-  }
-
   if (PrintGCDetails && Verbose) {
     tty->print_cr("MarkStackSize: %uk  MarkStackSizeMax: %uk",
       (unsigned int) (MarkStackSize / K), (uint) (MarkStackSizeMax / K));
@@ -1748,6 +1743,13 @@
     // Keeping the heap 100% free is hard ;-) so limit it to 99%.
     FLAG_SET_ERGO(uintx, MinHeapFreeRatio, 99);
   }
+
+  // If class unloading is disabled, also disable concurrent class unloading.
+  if (!ClassUnloading) {
+    FLAG_SET_CMDLINE(bool, CMSClassUnloadingEnabled, false);
+    FLAG_SET_CMDLINE(bool, ClassUnloadingWithConcurrentMark, false);
+    FLAG_SET_CMDLINE(bool, ExplicitGCInvokesConcurrentAndUnloadsClasses, false);
+  }
 #else // INCLUDE_ALL_GCS
   assert(verify_serial_gc_flags(), "SerialGC unset");
 #endif // INCLUDE_ALL_GCS
@@ -1801,20 +1803,34 @@
     }
   }
 
+  // Convert Fraction to Precentage values
+  if (FLAG_IS_DEFAULT(MaxRAMPercentage) &&
+      !FLAG_IS_DEFAULT(MaxRAMFraction))
+    MaxRAMPercentage = 100.0 / MaxRAMFraction;
+
+   if (FLAG_IS_DEFAULT(MinRAMPercentage) &&
+       !FLAG_IS_DEFAULT(MinRAMFraction))
+     MinRAMPercentage = 100.0 / MinRAMFraction;
+
+   if (FLAG_IS_DEFAULT(InitialRAMPercentage) &&
+       !FLAG_IS_DEFAULT(InitialRAMFraction))
+     InitialRAMPercentage = 100.0 / InitialRAMFraction;
+
   // If the maximum heap size has not been set with -Xmx,
   // then set it as fraction of the size of physical memory,
   // respecting the maximum and minimum sizes of the heap.
   if (FLAG_IS_DEFAULT(MaxHeapSize)) {
-    julong reasonable_max = phys_mem / MaxRAMFraction;
-
-    if (phys_mem <= MaxHeapSize * MinRAMFraction) {
+    julong reasonable_max = (julong)((phys_mem * MaxRAMPercentage) / 100);
+    const julong reasonable_min = (julong)((phys_mem * MinRAMPercentage) / 100);
+    if (reasonable_min < MaxHeapSize) {
       // Small physical memory, so use a minimum fraction of it for the heap
-      reasonable_max = phys_mem / MinRAMFraction;
+      reasonable_max = reasonable_min;
     } else {
       // Not-small physical memory, so require a heap at least
       // as large as MaxHeapSize
       reasonable_max = MAX2(reasonable_max, (julong)MaxHeapSize);
     }
+
     if (!FLAG_IS_DEFAULT(ErgoHeapSizeLimit) && ErgoHeapSizeLimit != 0) {
       // Limit the heap size to ErgoHeapSizeLimit
       reasonable_max = MIN2(reasonable_max, (julong)ErgoHeapSizeLimit);
@@ -1856,7 +1872,7 @@
     reasonable_minimum = limit_by_allocatable_memory(reasonable_minimum);
 
     if (InitialHeapSize == 0) {
-      julong reasonable_initial = phys_mem / InitialRAMFraction;
+      julong reasonable_initial = (julong)((phys_mem * InitialRAMPercentage) / 100);
 
       reasonable_initial = MAX3(reasonable_initial, reasonable_minimum, (julong)min_heap_size());
       reasonable_initial = MIN2(reasonable_initial, (julong)MaxHeapSize);
@@ -1881,6 +1897,94 @@
   }
 }
 
+// This option inspects the machine and attempts to set various
+// parameters to be optimal for long-running, memory allocation
+// intensive jobs.  It is intended for machines with large
+// amounts of cpu and memory.
+jint Arguments::set_aggressive_heap_flags() {
+  // initHeapSize is needed since _initial_heap_size is 4 bytes on a 32 bit
+  // VM, but we may not be able to represent the total physical memory
+  // available (like having 8gb of memory on a box but using a 32bit VM).
+  // Thus, we need to make sure we're using a julong for intermediate
+  // calculations.
+  julong initHeapSize;
+  julong total_memory = os::physical_memory();
+
+  if (total_memory < (julong) 256 * M) {
+    jio_fprintf(defaultStream::error_stream(),
+            "You need at least 256mb of memory to use -XX:+AggressiveHeap\n");
+    vm_exit(1);
+  }
+
+  // The heap size is half of available memory, or (at most)
+  // all of possible memory less 160mb (leaving room for the OS
+  // when using ISM).  This is the maximum; because adaptive sizing
+  // is turned on below, the actual space used may be smaller.
+
+  initHeapSize = MIN2(total_memory / (julong) 2,
+                      total_memory - (julong) 160 * M);
+
+  initHeapSize = limit_by_allocatable_memory(initHeapSize);
+
+  if (FLAG_IS_DEFAULT(MaxHeapSize)) {
+    FLAG_SET_CMDLINE(uintx, MaxHeapSize, initHeapSize);
+    FLAG_SET_CMDLINE(uintx, InitialHeapSize, initHeapSize);
+    // Currently the minimum size and the initial heap sizes are the same.
+    set_min_heap_size(initHeapSize);
+  }
+  if (FLAG_IS_DEFAULT(NewSize)) {
+    // Make the young generation 3/8ths of the total heap.
+    FLAG_SET_CMDLINE(uintx, NewSize,
+            ((julong) MaxHeapSize / (julong) 8) * (julong) 3);
+    FLAG_SET_CMDLINE(uintx, MaxNewSize, NewSize);
+  }
+
+#ifndef _ALLBSD_SOURCE  // UseLargePages is not yet supported on BSD.
+  FLAG_SET_DEFAULT(UseLargePages, true);
+#endif
+
+  // Increase some data structure sizes for efficiency
+  FLAG_SET_CMDLINE(uintx, BaseFootPrintEstimate, MaxHeapSize);
+  FLAG_SET_CMDLINE(bool, ResizeTLAB, false);
+  FLAG_SET_CMDLINE(uintx, TLABSize, 256 * K);
+
+  // See the OldPLABSize comment below, but replace 'after promotion'
+  // with 'after copying'.  YoungPLABSize is the size of the survivor
+  // space per-gc-thread buffers.  The default is 4kw.
+  FLAG_SET_CMDLINE(uintx, YoungPLABSize, 256 * K);     // Note: this is in words
+
+  // OldPLABSize is the size of the buffers in the old gen that
+  // UseParallelGC uses to promote live data that doesn't fit in the
+  // survivor spaces.  At any given time, there's one for each gc thread.
+  // The default size is 1kw. These buffers are rarely used, since the
+  // survivor spaces are usually big enough.  For specjbb, however, there
+  // are occasions when there's lots of live data in the young gen
+  // and we end up promoting some of it.  We don't have a definite
+  // explanation for why bumping OldPLABSize helps, but the theory
+  // is that a bigger PLAB results in retaining something like the
+  // original allocation order after promotion, which improves mutator
+  // locality.  A minor effect may be that larger PLABs reduce the
+  // number of PLAB allocation events during gc.  The value of 8kw
+  // was arrived at by experimenting with specjbb.
+  FLAG_SET_CMDLINE(uintx, OldPLABSize, 8 * K);      // Note: this is in words
+
+  // Enable parallel GC and adaptive generation sizing
+  FLAG_SET_CMDLINE(bool, UseParallelGC, true);
+
+  // Encourage steady state memory management
+  FLAG_SET_CMDLINE(uintx, ThresholdTolerance, 100);
+
+  // This appears to improve mutator locality
+  FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false);
+
+  // Get around early Solaris scheduling bug
+  // (affinity vs other jobs on system)
+  // but disallow DR and offlining (5008695).
+  FLAG_SET_CMDLINE(bool, BindGCTaskThreadsToCPUs, true);
+
+  return JNI_OK;
+}
+
 // This must be called after ergonomics because we want bytecode rewriting
 // if the server compiler is used, or if UseSharedSpaces is disabled.
 void Arguments::set_bytecode_flags() {
@@ -2644,6 +2748,14 @@
     return result;
   }
 
+  // We need to ensure processor and memory resources have been properly
+  // configured - which may rely on arguments we just processed - before
+  // doing the final argument processing. Any argument processing that
+  // needs to know about processor and memory resources must occur after
+  // this point.
+
+  os::init_container_support();
+
   // Do final processing now that all arguments have been parsed
   result = finalize_vm_init_args(&scp, scp_assembly_required);
   if (result != JNI_OK) {
@@ -3117,94 +3229,6 @@
       _exit_hook = CAST_TO_FN_PTR(exit_hook_t, option->extraInfo);
     } else if (match_option(option, "abort", &tail)) {
       _abort_hook = CAST_TO_FN_PTR(abort_hook_t, option->extraInfo);
-    // -XX:+AggressiveHeap
-    } else if (match_option(option, "-XX:+AggressiveHeap", &tail)) {
-
-      // This option inspects the machine and attempts to set various
-      // parameters to be optimal for long-running, memory allocation
-      // intensive jobs.  It is intended for machines with large
-      // amounts of cpu and memory.
-
-      // initHeapSize is needed since _initial_heap_size is 4 bytes on a 32 bit
-      // VM, but we may not be able to represent the total physical memory
-      // available (like having 8gb of memory on a box but using a 32bit VM).
-      // Thus, we need to make sure we're using a julong for intermediate
-      // calculations.
-      julong initHeapSize;
-      julong total_memory = os::physical_memory();
-
-      if (total_memory < (julong)256*M) {
-        jio_fprintf(defaultStream::error_stream(),
-                    "You need at least 256mb of memory to use -XX:+AggressiveHeap\n");
-        vm_exit(1);
-      }
-
-      // The heap size is half of available memory, or (at most)
-      // all of possible memory less 160mb (leaving room for the OS
-      // when using ISM).  This is the maximum; because adaptive sizing
-      // is turned on below, the actual space used may be smaller.
-
-      initHeapSize = MIN2(total_memory / (julong)2,
-                          total_memory - (julong)160*M);
-
-      initHeapSize = limit_by_allocatable_memory(initHeapSize);
-
-      if (FLAG_IS_DEFAULT(MaxHeapSize)) {
-         FLAG_SET_CMDLINE(uintx, MaxHeapSize, initHeapSize);
-         FLAG_SET_CMDLINE(uintx, InitialHeapSize, initHeapSize);
-         // Currently the minimum size and the initial heap sizes are the same.
-         set_min_heap_size(initHeapSize);
-      }
-      if (FLAG_IS_DEFAULT(NewSize)) {
-         // Make the young generation 3/8ths of the total heap.
-         FLAG_SET_CMDLINE(uintx, NewSize,
-                                ((julong)MaxHeapSize / (julong)8) * (julong)3);
-         FLAG_SET_CMDLINE(uintx, MaxNewSize, NewSize);
-      }
-
-#ifndef _ALLBSD_SOURCE  // UseLargePages is not yet supported on BSD.
-      FLAG_SET_DEFAULT(UseLargePages, true);
-#endif
-
-      // Increase some data structure sizes for efficiency
-      FLAG_SET_CMDLINE(uintx, BaseFootPrintEstimate, MaxHeapSize);
-      FLAG_SET_CMDLINE(bool, ResizeTLAB, false);
-      FLAG_SET_CMDLINE(uintx, TLABSize, 256*K);
-
-      // See the OldPLABSize comment below, but replace 'after promotion'
-      // with 'after copying'.  YoungPLABSize is the size of the survivor
-      // space per-gc-thread buffers.  The default is 4kw.
-      FLAG_SET_CMDLINE(uintx, YoungPLABSize, 256*K);      // Note: this is in words
-
-      // OldPLABSize is the size of the buffers in the old gen that
-      // UseParallelGC uses to promote live data that doesn't fit in the
-      // survivor spaces.  At any given time, there's one for each gc thread.
-      // The default size is 1kw. These buffers are rarely used, since the
-      // survivor spaces are usually big enough.  For specjbb, however, there
-      // are occasions when there's lots of live data in the young gen
-      // and we end up promoting some of it.  We don't have a definite
-      // explanation for why bumping OldPLABSize helps, but the theory
-      // is that a bigger PLAB results in retaining something like the
-      // original allocation order after promotion, which improves mutator
-      // locality.  A minor effect may be that larger PLABs reduce the
-      // number of PLAB allocation events during gc.  The value of 8kw
-      // was arrived at by experimenting with specjbb.
-      FLAG_SET_CMDLINE(uintx, OldPLABSize, 8*K);  // Note: this is in words
-
-      // Enable parallel GC and adaptive generation sizing
-      FLAG_SET_CMDLINE(bool, UseParallelGC, true);
-
-      // Encourage steady state memory management
-      FLAG_SET_CMDLINE(uintx, ThresholdTolerance, 100);
-
-      // This appears to improve mutator locality
-      FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false);
-
-      // Get around early Solaris scheduling bug
-      // (affinity vs other jobs on system)
-      // but disallow DR and offlining (5008695).
-      FLAG_SET_CMDLINE(bool, BindGCTaskThreadsToCPUs, true);
-
     } else if (match_option(option, "-XX:+NeverTenure", &tail)) {
       // The last option must always win.
       FLAG_SET_CMDLINE(bool, AlwaysTenure, false);
@@ -3605,6 +3629,15 @@
     return JNI_ERR;
   }
 
+  // This must be done after all arguments have been processed
+  // and the container support has been initialized since AggressiveHeap
+  // relies on the amount of total memory available.
+  if (AggressiveHeap) {
+    jint result = set_aggressive_heap_flags();
+    if (result != JNI_OK) {
+      return result;
+    }
+  }
   // This must be done after all arguments have been processed.
   // java_compiler() true means set to "NONE" or empty.
   if (java_compiler() && !xdebug_mode()) {
diff --git a/src/share/vm/runtime/arguments.hpp b/src/share/vm/runtime/arguments.hpp
index 8fd3e3f..133ac33 100644
--- a/src/share/vm/runtime/arguments.hpp
+++ b/src/share/vm/runtime/arguments.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -365,6 +365,8 @@
   // Aggressive optimization flags.
   static void set_aggressive_opts_flags();
 
+  static jint set_aggressive_heap_flags();
+
   // Argument parsing
   static void do_pd_flag_adjustments();
   static bool parse_argument(const char* arg, Flag::Flags origin);
diff --git a/src/share/vm/runtime/deoptimization.cpp b/src/share/vm/runtime/deoptimization.cpp
index 387a31c..7690d9f 100644
--- a/src/share/vm/runtime/deoptimization.cpp
+++ b/src/share/vm/runtime/deoptimization.cpp
@@ -1373,7 +1373,7 @@
       ttyLocker ttyl;
       char buf[100];
       if (xtty != NULL) {
-        xtty->begin_head("uncommon_trap thread='" UINTX_FORMAT"' %s",
+        xtty->begin_head("uncommon_trap thread='" UINTX_FORMAT "' %s",
                          os::current_thread_id(),
                          format_trap_request(buf, sizeof(buf), trap_request));
         nm->log_identity(xtty);
diff --git a/src/share/vm/runtime/fieldDescriptor.cpp b/src/share/vm/runtime/fieldDescriptor.cpp
index 79e3ddc..f3f7130 100644
--- a/src/share/vm/runtime/fieldDescriptor.cpp
+++ b/src/share/vm/runtime/fieldDescriptor.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -94,7 +94,7 @@
 }
 
 oop fieldDescriptor::string_initial_value(TRAPS) const {
-  return constants()->uncached_string_at(initial_value_index(), CHECK_0);
+  return constants()->uncached_string_at(initial_value_index(), THREAD);
 }
 
 void fieldDescriptor::reinitialize(InstanceKlass* ik, int index) {
diff --git a/src/share/vm/runtime/fprofiler.cpp b/src/share/vm/runtime/fprofiler.cpp
index a4d01b8..4290a5d 100644
--- a/src/share/vm/runtime/fprofiler.cpp
+++ b/src/share/vm/runtime/fprofiler.cpp
@@ -775,7 +775,7 @@
 }
 
 void ThreadProfiler::vm_update(TickPosition where) {
-  vm_update(NULL, where);
+  vm_update("", where);
 }
 
 void ThreadProfiler::vm_update(const char* name, TickPosition where) {
diff --git a/src/share/vm/runtime/frame.hpp b/src/share/vm/runtime/frame.hpp
index c83808b..255596e 100644
--- a/src/share/vm/runtime/frame.hpp
+++ b/src/share/vm/runtime/frame.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -45,11 +45,9 @@
 # include "adfiles/adGlobals_ppc_64.hpp"
 #endif
 #endif // COMPILER2
-#ifdef ZERO
 #ifdef TARGET_ARCH_zero
 # include "stack_zero.hpp"
 #endif
-#endif
 
 typedef class BytecodeInterpreter* interpreterState;
 
diff --git a/src/share/vm/runtime/frame.inline.hpp b/src/share/vm/runtime/frame.inline.hpp
index ce72595..37d13f8 100644
--- a/src/share/vm/runtime/frame.inline.hpp
+++ b/src/share/vm/runtime/frame.inline.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -46,14 +46,12 @@
 #ifdef TARGET_ARCH_ppc
 # include "jniTypes_ppc.hpp"
 #endif
-#ifdef ZERO
 #ifdef TARGET_ARCH_zero
 # include "entryFrame_zero.hpp"
 # include "fakeStubFrame_zero.hpp"
 # include "interpreterFrame_zero.hpp"
 # include "sharkFrame_zero.hpp"
 #endif
-#endif
 
 // This file holds platform-independent bodies of inline functions for frames.
 
diff --git a/src/share/vm/runtime/globals.hpp b/src/share/vm/runtime/globals.hpp
index 6c9bd3b..421a3ba 100644
--- a/src/share/vm/runtime/globals.hpp
+++ b/src/share/vm/runtime/globals.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -768,8 +768,8 @@
           "Time out and warn or fail after SafepointTimeoutDelay "          \
           "milliseconds if failed to reach safepoint")                      \
                                                                             \
-  develop(bool, DieOnSafepointTimeout, false,                               \
-          "Die upon failure to reach safepoint (see SafepointTimeout)")     \
+  diagnostic(bool, AbortVMOnSafepointTimeout, false,                        \
+          "Abort upon failure to reach safepoint (see SafepointTimeout)")   \
                                                                             \
   /* 50 retries * (5 * current_retry_count) millis = ~6.375 seconds */      \
   /* typically, at most a few retries are needed */                         \
@@ -1124,6 +1124,10 @@
           "Use detached threads that are recycled upon termination "        \
           "(for Solaris only)")                                             \
                                                                             \
+  experimental(bool, DisablePrimordialThreadGuardPages, false,              \
+               "Disable the use of stack guard pages if the JVM is loaded " \
+               "on the primordial process thread")                          \
+                                                                            \
   product(bool, UseLWPSynchronization, true,                                \
           "Use LWP-based instead of libthread-based synchronization "       \
           "(SPARC only)")                                                   \
@@ -2064,13 +2068,23 @@
   product_pd(uint64_t, MaxRAM,                                              \
           "Real memory size (in bytes) used to set maximum heap size")      \
                                                                             \
+  product(bool, AggressiveHeap, false,                                      \
+          "Optimize heap options for long-running memory intensive apps")   \
+                                                                            \
   product(uintx, ErgoHeapSizeLimit, 0,                                      \
           "Maximum ergonomically set heap size (in bytes); zero means use " \
-          "MaxRAM / MaxRAMFraction")                                        \
+          "MaxRAM * MaxRAMPercentage / 100")                                \
                                                                             \
   experimental(bool, UseCGroupMemoryLimitForHeap, false,                    \
           "Use CGroup memory limit as physical memory limit for heap "      \
-          "sizing")                                                         \
+          "sizing"                                                          \
+          "Deprecated, replaced by container support")                      \
+                                                                            \
+  diagnostic(bool, PrintContainerInfo, false,                               \
+          "Print container related information")                            \
+                                                                            \
+  diagnostic(bool, PrintActiveCpus, false,                                  \
+           "Print the number of CPUs detected in os::active_processor_count") \
                                                                             \
   product(uintx, MaxRAMFraction, 4,                                         \
           "Maximum fraction (1/n) of real memory used for maximum heap "    \
@@ -2087,6 +2101,19 @@
   product(uintx, InitialRAMFraction, 64,                                    \
           "Fraction (1/n) of real memory used for initial heap size")       \
                                                                             \
+  product(double, MaxRAMPercentage, 25.0,                                   \
+          "Maximum percentage of real memory used for maximum heap size")   \
+                                                                            \
+  product(double, MinRAMPercentage, 50.0,                                   \
+          "Minimum percentage of real memory used for maximum heap"         \
+          "size on systems with small physical memory size")                \
+                                                                            \
+  product(double, InitialRAMPercentage, 1.5625,                             \
+          "Percentage of real memory used for initial heap size")           \
+                                                                            \
+  product(intx, ActiveProcessorCount, -1,                                   \
+          "Specify the CPU count the VM should use and report as active")   \
+                                                                            \
   develop(uintx, MaxVirtMemFraction, 2,                                     \
           "Maximum fraction (1/n) of virtual memory used for ergonomically "\
           "determining maximum heap size")                                  \
diff --git a/src/share/vm/runtime/interfaceSupport.hpp b/src/share/vm/runtime/interfaceSupport.hpp
index fa9ad5e..7a20fba 100644
--- a/src/share/vm/runtime/interfaceSupport.hpp
+++ b/src/share/vm/runtime/interfaceSupport.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -431,6 +431,14 @@
   os::verify_stack_alignment();                                      \
   /* begin of body */
 
+#define VM_ENTRY_BASE_FROM_LEAF(result_type, header, thread)         \
+  TRACE_CALL(result_type, header)                                    \
+  debug_only(ResetNoHandleMark __rnhm;)                              \
+  HandleMarkCleaner __hm(thread);                                    \
+  Thread* THREAD = thread;                                           \
+  os::verify_stack_alignment();                                      \
+  /* begin of body */
+
 
 // ENTRY routines may lock, GC and throw exceptions
 
@@ -592,6 +600,14 @@
     VM_LEAF_BASE(result_type, header)
 
 
+#define JVM_ENTRY_FROM_LEAF(env, result_type, header)                \
+  { {                                                                \
+    JavaThread* thread=JavaThread::thread_from_jni_environment(env); \
+    ThreadInVMfromNative __tiv(thread);                              \
+    debug_only(VMNativeEntryWrapper __vew;)                          \
+    VM_ENTRY_BASE_FROM_LEAF(result_type, header, thread)
+
+
 #define JVM_END } }
 
 #endif // SHARE_VM_RUNTIME_INTERFACESUPPORT_HPP
diff --git a/src/share/vm/runtime/memprofiler.cpp b/src/share/vm/runtime/memprofiler.cpp
index 279277e..c1cfb60 100644
--- a/src/share/vm/runtime/memprofiler.cpp
+++ b/src/share/vm/runtime/memprofiler.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -126,7 +126,7 @@
 
   fprintf(_log_fp, UINTX_FORMAT_W(6) ",", CodeCache::capacity() / K);
 
-  fprintf(_log_fp, UINTX_FORMAT_W(6) "," UINTX_FORMAT_W(6) ",%6ld\n",
+  fprintf(_log_fp, UINTX_FORMAT_W(6) "," UINTX_FORMAT_W(6) "," UINTX_FORMAT_W(6) "\n",
           handles_memory_usage / K,
           resource_memory_usage / K,
           OopMapCache::memory_usage() / K);
diff --git a/src/share/vm/runtime/objectMonitor.cpp b/src/share/vm/runtime/objectMonitor.cpp
index 3e57333..40c9dbd 100644
--- a/src/share/vm/runtime/objectMonitor.cpp
+++ b/src/share/vm/runtime/objectMonitor.cpp
@@ -471,9 +471,7 @@
     event.commit();
   }
 
-  if (ObjectMonitor::_sync_ContendedLockAttempts != NULL) {
-     ObjectMonitor::_sync_ContendedLockAttempts->inc() ;
-  }
+  OM_PERFDATA_OP(ContendedLockAttempts, inc());
 }
 
 
@@ -634,16 +632,16 @@
 
         if (TryLock(Self) > 0) break ;
 
-        // The lock is still contested.
-        // Keep a tally of the # of futile wakeups.
-        // Note that the counter is not protected by a lock or updated by atomics.
-        // That is by design - we trade "lossy" counters which are exposed to
-        // races during updates for a lower probe effect.
-        TEVENT (Inflated enter - Futile wakeup) ;
-        if (ObjectMonitor::_sync_FutileWakeups != NULL) {
-           ObjectMonitor::_sync_FutileWakeups->inc() ;
-        }
-        ++ nWakeups ;
+    // The lock is still contested.
+    // Keep a tally of the # of futile wakeups.
+    // Note that the counter is not protected by a lock or updated by atomics.
+    // That is by design - we trade "lossy" counters which are exposed to
+    // races during updates for a lower probe effect.
+    TEVENT(Inflated enter - Futile wakeup);
+    // This PerfData object can be used in parallel with a safepoint.
+    // See the work around in PerfDataManager::destroy().
+    OM_PERFDATA_OP(FutileWakeups, inc());
+    ++nWakeups;
 
         // Assuming this is not a spurious wakeup we'll normally find _succ == Self.
         // We can defer clearing _succ until after the spin completes
@@ -814,9 +812,9 @@
         // *must* retry  _owner before parking.
         OrderAccess::fence() ;
 
-        if (ObjectMonitor::_sync_FutileWakeups != NULL) {
-          ObjectMonitor::_sync_FutileWakeups->inc() ;
-        }
+        // This PerfData object can be used in parallel with a safepoint.
+        // See the work around in PerfDataManager::destroy().
+        OM_PERFDATA_OP(FutileWakeups, inc());
     }
 
     // Self has acquired the lock -- Unlink Self from the cxq or EntryList .
@@ -1352,10 +1350,8 @@
    DTRACE_MONITOR_PROBE(contended__exit, this, object(), Self);
    Trigger->unpark() ;
 
-   // Maintain stats and report events to JVMTI
-   if (ObjectMonitor::_sync_Parks != NULL) {
-      ObjectMonitor::_sync_Parks->inc() ;
-   }
+  // Maintain stats and report events to JVMTI
+  OM_PERFDATA_OP(Parks, inc());
 }
 
 
@@ -1808,8 +1804,8 @@
 
   Thread::SpinRelease (&_WaitSetLock) ;
 
-  if (iterator != NULL && ObjectMonitor::_sync_Notifications != NULL) {
-     ObjectMonitor::_sync_Notifications->inc() ;
+  if (iterator != NULL) {
+      OM_PERFDATA_OP(Notifications, inc(1));
   }
 }
 
@@ -1920,21 +1916,10 @@
      if (Policy < 4) {
        iterator->wait_reenter_begin(this);
      }
-
-     // _WaitSetLock protects the wait queue, not the EntryList.  We could
-     // move the add-to-EntryList operation, above, outside the critical section
-     // protected by _WaitSetLock.  In practice that's not useful.  With the
-     // exception of  wait() timeouts and interrupts the monitor owner
-     // is the only thread that grabs _WaitSetLock.  There's almost no contention
-     // on _WaitSetLock so it's not profitable to reduce the length of the
-     // critical section.
   }
+  Thread::SpinRelease (&_WaitSetLock);
 
-  Thread::SpinRelease (&_WaitSetLock) ;
-
-  if (Tally != 0 && ObjectMonitor::_sync_Notifications != NULL) {
-     ObjectMonitor::_sync_Notifications->inc(Tally) ;
-  }
+  OM_PERFDATA_OP(Notifications, inc(Tally));
 }
 
 // -----------------------------------------------------------------------------
diff --git a/src/share/vm/runtime/objectMonitor.hpp b/src/share/vm/runtime/objectMonitor.hpp
index 09180cf..ac2cd4e 100644
--- a/src/share/vm/runtime/objectMonitor.hpp
+++ b/src/share/vm/runtime/objectMonitor.hpp
@@ -85,6 +85,10 @@
   };
 
  public:
+  static int Knob_ExitRelease;
+  static int Knob_VerifyInUse;
+  static int Knob_VerifyMatch;
+
   // TODO-FIXME: the "offset" routines should return a type of off_t instead of int ...
   // ByteSize would also be an appropriate type.
   static int header_offset_in_bytes()      { return offset_of(ObjectMonitor, _header);     }
@@ -290,6 +294,19 @@
 
  public:
   static void Initialize () ;
+
+    // Only perform a PerfData operation if the PerfData object has been
+    // allocated and if the PerfDataManager has not freed the PerfData
+    // objects which can happen at normal VM shutdown.
+    //
+  #define OM_PERFDATA_OP(f, op_str)              \
+    do {                                         \
+      if (ObjectMonitor::_sync_ ## f != NULL &&  \
+          PerfDataManager::has_PerfData()) {     \
+        ObjectMonitor::_sync_ ## f->op_str;      \
+      }                                          \
+    } while (0)
+
   static PerfCounter * _sync_ContendedLockAttempts ;
   static PerfCounter * _sync_FutileWakeups ;
   static PerfCounter * _sync_Parks ;
diff --git a/src/share/vm/runtime/os.cpp b/src/share/vm/runtime/os.cpp
index 06e81a5..8cf2ed9 100644
--- a/src/share/vm/runtime/os.cpp
+++ b/src/share/vm/runtime/os.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -96,6 +96,26 @@
   os::init_globals();
 }
 
+static time_t get_timezone(const struct tm* time_struct) {
+#if defined(_ALLBSD_SOURCE)
+  return time_struct->tm_gmtoff;
+#elif defined(_WINDOWS)
+  long zone;
+  _get_timezone(&zone);
+  return static_cast<time_t>(zone);
+#else
+  return timezone;
+#endif
+}
+
+int os::snprintf(char* buf, size_t len, const char* fmt, ...) {
+  va_list args;
+  va_start(args, fmt);
+  int result = os::vsnprintf(buf, len, fmt, args);
+  va_end(args);
+  return result;
+}
+
 // Fill in buffer with current local time as an ISO-8601 string.
 // E.g., yyyy-mm-ddThh:mm:ss-zzzz.
 // Returns buffer, or NULL if it failed.
@@ -134,11 +154,7 @@
     assert(false, "Failed localtime_pd");
     return NULL;
   }
-#if defined(_ALLBSD_SOURCE)
-  const time_t zone = (time_t) time_struct.tm_gmtoff;
-#else
-  const time_t zone = timezone;
-#endif
+  const time_t zone = get_timezone(&time_struct);
 
   // If daylight savings time is in effect,
   // we are 1 hour East of our time zone
@@ -847,7 +863,7 @@
   pd_print_cpu_info(st);
 }
 
-void os::print_date_and_time(outputStream *st) {
+void os::print_date_and_time(outputStream *st, char* buf, size_t buflen) {
   const int secs_per_day  = 86400;
   const int secs_per_hour = 3600;
   const int secs_per_min  = 60;
@@ -856,6 +872,12 @@
   (void)time(&tloc);
   st->print("time: %s", ctime(&tloc));  // ctime adds newline.
 
+  struct tm tz;
+  if (localtime_pd(&tloc, &tz) != NULL) {
+    ::strftime(buf, buflen, "%Z", &tz);
+    st->print_cr("timezone: %s", buf);
+  }
+
   double t = os::elapsedTime();
   // NOTE: It tends to crash after a SEGV if we want to printf("%f",...) in
   //       Linux. Must be a bug in glibc ? Workaround is to round "t" to int
diff --git a/src/share/vm/runtime/os.hpp b/src/share/vm/runtime/os.hpp
index e008b9c..92553ab 100644
--- a/src/share/vm/runtime/os.hpp
+++ b/src/share/vm/runtime/os.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -152,8 +152,16 @@
   static size_t page_size_for_region(size_t region_size, size_t min_pages, bool must_be_aligned);
 
   static void initialize_initial_active_processor_count();
+
+  LINUX_ONLY(static void pd_init_container_support();)
+
  public:
   static void init(void);                      // Called before command line parsing
+
+  static void init_container_support() {       // Called during command line parsing.
+     LINUX_ONLY(pd_init_container_support();)
+  }
+
   static void init_before_ergo(void);          // Called after command line parsing
                                                // before VM ergonomics processing.
   static jint init_2(void);                    // Called after command line parsing
@@ -449,7 +457,24 @@
   static bool create_thread(Thread* thread,
                             ThreadType thr_type,
                             size_t stack_size = 0);
+
+  // The "main thread", also known as "starting thread", is the thread
+  // that loads/creates the JVM via JNI_CreateJavaVM.
   static bool create_main_thread(JavaThread* thread);
+
+  // The primordial thread is the initial process thread. The java
+  // launcher never uses the primordial thread as the main thread, but
+  // applications that host the JVM directly may do so. Some platforms
+  // need special-case handling of the primordial thread if it attaches
+  // to the VM.
+  static bool is_primordial_thread(void)
+#if defined(_WINDOWS) || defined(BSD)
+    // No way to identify the primordial thread.
+    { return false; }
+#else
+  ;
+#endif
+
   static bool create_attached_thread(JavaThread* thread);
   static void pd_start_thread(Thread* thread);
   static void start_thread(Thread* thread);
@@ -591,6 +616,9 @@
   static void *find_agent_function(AgentLibrary *agent_lib, bool check_lib,
                                    const char *syms[], size_t syms_len);
 
+  static int vsnprintf(char* buf, size_t len, const char* fmt, va_list args) ATTRIBUTE_PRINTF(3, 0);
+  static int snprintf(char* buf, size_t len, const char* fmt, ...) ATTRIBUTE_PRINTF(3, 4);
+
   // Print out system information; they are called by fatal error handler.
   // Output format may be different on different platforms.
   static void print_os_info(outputStream* st);
@@ -604,7 +632,7 @@
   static void print_register_info(outputStream* st, void* context);
   static void print_siginfo(outputStream* st, void* siginfo);
   static void print_signal_handlers(outputStream* st, char* buf, size_t buflen);
-  static void print_date_and_time(outputStream* st);
+  static void print_date_and_time(outputStream* st, char* buf, size_t buflen);
 
   static void print_location(outputStream* st, intptr_t x, bool verbose = false);
   static size_t lasterror(char *buf, size_t len);
diff --git a/src/share/vm/runtime/perfData.cpp b/src/share/vm/runtime/perfData.cpp
index 8dee999..3c79281 100644
--- a/src/share/vm/runtime/perfData.cpp
+++ b/src/share/vm/runtime/perfData.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2015, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -39,6 +39,7 @@
 PerfDataList*   PerfDataManager::_all = NULL;
 PerfDataList*   PerfDataManager::_sampled = NULL;
 PerfDataList*   PerfDataManager::_constants = NULL;
+volatile bool   PerfDataManager::_has_PerfData = 0;
 
 /*
  * The jvmstat global and subsysem jvmstat counter name spaces. The top
@@ -272,16 +273,22 @@
 }
 
 
-
-
-
-
 void PerfDataManager::destroy() {
 
   if (_all == NULL)
     // destroy already called, or initialization never happened
     return;
 
+  // Clear the flag before we free the PerfData counters. Thus begins
+  // the race between this thread and another thread that has just
+  // queried PerfDataManager::has_PerfData() and gotten back 'true'.
+  // The hope is that the other thread will finish its PerfData
+  // manipulation before we free the memory. The two alternatives are
+  // 1) leak the PerfData memory or 2) do some form of synchronized
+  // access or check before every PerfData operation.
+  _has_PerfData = false;
+  os::naked_short_sleep(1);  // 1ms sleep to let other thread(s) run
+
   for (int index = 0; index < _all->length(); index++) {
     PerfData* p = _all->at(index);
     delete p;
@@ -302,6 +309,7 @@
 
   if (_all == NULL) {
     _all = new PerfDataList(100);
+    _has_PerfData = true;
   }
 
   assert(!_all->contains(p->name()), "duplicate name added");
diff --git a/src/share/vm/runtime/perfData.hpp b/src/share/vm/runtime/perfData.hpp
index 0ed4a3c..0943455 100644
--- a/src/share/vm/runtime/perfData.hpp
+++ b/src/share/vm/runtime/perfData.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2015, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -668,6 +668,7 @@
     static PerfDataList* _sampled;
     static PerfDataList* _constants;
     static const char* _name_spaces[];
+    static volatile bool _has_PerfData;
 
     // add a PerfData item to the list(s) of know PerfData objects
     static void add_item(PerfData* p, bool sampled);
@@ -869,6 +870,7 @@
     }
 
     static void destroy();
+    static bool has_PerfData() { return _has_PerfData; }
 };
 
 // Useful macros to create the performance counters
diff --git a/src/share/vm/runtime/perfMemory.cpp b/src/share/vm/runtime/perfMemory.cpp
index 4eddf2a..8ac6276 100644
--- a/src/share/vm/runtime/perfMemory.cpp
+++ b/src/share/vm/runtime/perfMemory.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2015, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -32,6 +32,7 @@
 #include "runtime/os.hpp"
 #include "runtime/perfData.hpp"
 #include "runtime/perfMemory.hpp"
+#include "runtime/safepoint.hpp"
 #include "runtime/statSampler.hpp"
 #include "utilities/globalDefinitions.hpp"
 
@@ -64,16 +65,20 @@
   if (!UsePerfData) return;
   if (!PerfMemory::is_initialized()) return;
 
-  // if the StatSampler is active, then we don't want to remove
-  // resources it may be dependent on. Typically, the StatSampler
-  // is disengaged from the watcher thread when this method is called,
-  // but it is not disengaged if this method is invoked during a
-  // VM abort.
+  // Only destroy PerfData objects if we're at a safepoint and the
+  // StatSampler is not active. Otherwise, we risk removing PerfData
+  // objects that are currently being used by running JavaThreads
+  // or the StatSampler. This method is invoked while we are not at
+  // a safepoint during a VM abort so leaving the PerfData objects
+  // around may also help diagnose the failure. In rare cases,
+  // PerfData objects are used in parallel with a safepoint. See
+  // the work around in PerfDataManager::destroy().
   //
-  if (!StatSampler::is_active())
+  if (SafepointSynchronize::is_at_safepoint() && !StatSampler::is_active()) {
     PerfDataManager::destroy();
+  }
 
-  // remove the persistent external resources, if any. this method
+  // Remove the persistent external resources, if any. This method
   // does not unmap or invalidate any virtual memory allocated during
   // initialization.
   //
diff --git a/src/share/vm/runtime/reflection.cpp b/src/share/vm/runtime/reflection.cpp
index e2f282e..4b39d8c 100644
--- a/src/share/vm/runtime/reflection.cpp
+++ b/src/share/vm/runtime/reflection.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -682,7 +682,7 @@
 }
 
 objArrayHandle Reflection::get_exception_types(methodHandle method, TRAPS) {
-  return method->resolved_checked_exceptions(CHECK_(objArrayHandle()));
+  return method->resolved_checked_exceptions(THREAD);
 }
 
 
diff --git a/src/share/vm/runtime/safepoint.cpp b/src/share/vm/runtime/safepoint.cpp
index 2f46a84..be4bb45 100644
--- a/src/share/vm/runtime/safepoint.cpp
+++ b/src/share/vm/runtime/safepoint.cpp
@@ -790,9 +790,9 @@
     tty->print_cr("# SafepointSynchronize::begin: (End of list)");
   }
 
-  // To debug the long safepoint, specify both DieOnSafepointTimeout &
+  // To debug the long safepoint, specify both AbortVMOnSafepointTimeout &
   // ShowMessageBoxOnError.
-  if (DieOnSafepointTimeout) {
+  if (AbortVMOnSafepointTimeout) {
     char msg[1024];
     VM_Operation *op = VMThread::vm_operation();
     sprintf(msg, "Safepoint sync time longer than " INTX_FORMAT "ms detected when executing %s.",
@@ -914,7 +914,7 @@
 
     case _running:
     default:
-       tty->print_cr("restart thread "INTPTR_FORMAT" with state %d",
+       tty->print_cr("restart thread " INTPTR_FORMAT " with state %d",
                       _thread, _type);
        _thread->print();
       ShouldNotReachHere();
@@ -1213,7 +1213,7 @@
     sstats = &_safepoint_stats[index];
     tty->print("%.3f: ", sstats->_time_stamp);
     tty->print("%-26s       ["
-               INT32_FORMAT_W(8)INT32_FORMAT_W(11)INT32_FORMAT_W(15)
+               INT32_FORMAT_W(8) INT32_FORMAT_W(11) INT32_FORMAT_W(15)
                "    ]    ",
                sstats->_vmop_type == -1 ? "no vm operation" :
                VM_Operation::name(sstats->_vmop_type),
@@ -1222,9 +1222,9 @@
                sstats->_nof_threads_wait_to_block);
     // "/ MICROUNITS " is to convert the unit from nanos to millis.
     tty->print("  ["
-               INT64_FORMAT_W(6)INT64_FORMAT_W(6)
-               INT64_FORMAT_W(6)INT64_FORMAT_W(6)
-               INT64_FORMAT_W(6)"    ]  ",
+               INT64_FORMAT_W(6) INT64_FORMAT_W(6)
+               INT64_FORMAT_W(6) INT64_FORMAT_W(6)
+               INT64_FORMAT_W(6) "    ]  ",
                sstats->_time_to_spin / MICROUNITS,
                sstats->_time_to_wait_to_block / MICROUNITS,
                sstats->_time_to_sync / MICROUNITS,
@@ -1232,9 +1232,9 @@
                sstats->_time_to_exec_vmop / MICROUNITS);
 
     if (need_to_track_page_armed_status) {
-      tty->print(INT32_FORMAT"         ", sstats->_page_armed);
+      tty->print(INT32_FORMAT "         ", sstats->_page_armed);
     }
-    tty->print_cr(INT32_FORMAT"   ", sstats->_nof_threads_hit_page_trap);
+    tty->print_cr(INT32_FORMAT "   ", sstats->_nof_threads_hit_page_trap);
   }
 }
 
@@ -1271,17 +1271,17 @@
 
   for (int index = 0; index < VM_Operation::VMOp_Terminating; index++) {
     if (_safepoint_reasons[index] != 0) {
-      tty->print_cr("%-26s"UINT64_FORMAT_W(10), VM_Operation::name(index),
+      tty->print_cr("%-26s" UINT64_FORMAT_W(10), VM_Operation::name(index),
                     _safepoint_reasons[index]);
     }
   }
 
-  tty->print_cr(UINT64_FORMAT_W(5)" VM operations coalesced during safepoint",
+  tty->print_cr(UINT64_FORMAT_W(5) " VM operations coalesced during safepoint",
                 _coalesced_vmop_count);
-  tty->print_cr("Maximum sync time  "INT64_FORMAT_W(5)" ms",
+  tty->print_cr("Maximum sync time  " INT64_FORMAT_W(5) " ms",
                 _max_sync_time / MICROUNITS);
   tty->print_cr("Maximum vm operation time (except for Exit VM operation)  "
-                INT64_FORMAT_W(5)" ms",
+                INT64_FORMAT_W(5) " ms",
                 _max_vmop_time / MICROUNITS);
 }
 
diff --git a/src/share/vm/runtime/sharedRuntime.cpp b/src/share/vm/runtime/sharedRuntime.cpp
index 8ffa8ab..d14f173 100644
--- a/src/share/vm/runtime/sharedRuntime.cpp
+++ b/src/share/vm/runtime/sharedRuntime.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -639,7 +639,7 @@
 // ret_pc points into caller; we are returning caller's exception handler
 // for given exception
 address SharedRuntime::compute_compiled_exc_handler(nmethod* nm, address ret_pc, Handle& exception,
-                                                    bool force_unwind, bool top_frame_only) {
+                                                    bool force_unwind, bool top_frame_only, bool& recursive_exception_occurred) {
   assert(nm != NULL, "must exist");
   ResourceMark rm;
 
@@ -667,6 +667,7 @@
         // BCI of the exception handler which caused the exception to be
         // thrown (bugs 4307310 and 4546590). Set "exception" reference
         // argument to ensure that the correct exception is thrown (4870175).
+        recursive_exception_occurred = true;
         exception = Handle(THREAD, PENDING_EXCEPTION);
         CLEAR_PENDING_EXCEPTION;
         if (handler_bci >= 0) {
@@ -758,6 +759,8 @@
   if (StackTraceInThrowable) {
     java_lang_Throwable::fill_in_stack_trace(exception);
   }
+  // Increment counter for hs_err file reporting
+  Atomic::inc(&Exceptions::_stack_overflow_errors);
   throw_and_post_jvmti_exception(thread, exception);
 JRT_END
 
diff --git a/src/share/vm/runtime/sharedRuntime.hpp b/src/share/vm/runtime/sharedRuntime.hpp
index 2167eb8..c6a96a8 100644
--- a/src/share/vm/runtime/sharedRuntime.hpp
+++ b/src/share/vm/runtime/sharedRuntime.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -184,7 +184,7 @@
 
   // exception handling and implicit exceptions
   static address compute_compiled_exc_handler(nmethod* nm, address ret_pc, Handle& exception,
-                                              bool force_unwind, bool top_frame_only);
+                                              bool force_unwind, bool top_frame_only, bool& recursive_exception_occurred);
   enum ImplicitExceptionKind {
     IMPLICIT_NULL,
     IMPLICIT_DIVIDE_BY_ZERO,
diff --git a/src/share/vm/runtime/stubCodeGenerator.cpp b/src/share/vm/runtime/stubCodeGenerator.cpp
index 5ecbe02..7b592d9 100644
--- a/src/share/vm/runtime/stubCodeGenerator.cpp
+++ b/src/share/vm/runtime/stubCodeGenerator.cpp
@@ -34,12 +34,12 @@
 
 // Implementation of StubCodeDesc
 
-StubCodeDesc* StubCodeDesc::_list = NULL;
-int           StubCodeDesc::_count = 0;
+StubCodeDesc* volatile StubCodeDesc::_list = NULL;
+int                    StubCodeDesc::_count = 0;
 
 
 StubCodeDesc* StubCodeDesc::desc_for(address pc) {
-  StubCodeDesc* p = _list;
+  StubCodeDesc* p = (StubCodeDesc*)OrderAccess::load_ptr_acquire(&_list);
   while (p != NULL && !p->contains(pc)) p = p->_next;
   // p == NULL || p->contains(pc)
   return p;
@@ -47,7 +47,7 @@
 
 
 StubCodeDesc* StubCodeDesc::desc_for_index(int index) {
-  StubCodeDesc* p = _list;
+  StubCodeDesc* p = (StubCodeDesc*)OrderAccess::load_ptr_acquire(&_list);
   while (p != NULL && p->index() != index) p = p->_next;
   return p;
 }
diff --git a/src/share/vm/runtime/stubCodeGenerator.hpp b/src/share/vm/runtime/stubCodeGenerator.hpp
index d9f81b1..dc2b516 100644
--- a/src/share/vm/runtime/stubCodeGenerator.hpp
+++ b/src/share/vm/runtime/stubCodeGenerator.hpp
@@ -38,7 +38,7 @@
 
 class StubCodeDesc: public CHeapObj<mtCode> {
  protected:
-  static StubCodeDesc* _list;                  // the list of all descriptors
+  static StubCodeDesc* volatile _list;         // the list of all descriptors
   static int           _count;                 // length of list
 
   StubCodeDesc*        _next;                  // the next element in the linked list
@@ -69,13 +69,13 @@
 
   StubCodeDesc(const char* group, const char* name, address begin) {
     assert(name != NULL, "no name specified");
-    _next           = _list;
+    _next           = (StubCodeDesc*)OrderAccess::load_ptr_acquire(&_list);
     _group          = group;
     _name           = name;
     _index          = ++_count; // (never zero)
     _begin          = begin;
     _end            = NULL;
-    _list           = this;
+    OrderAccess::release_store_ptr(&_list, this);
   };
 
   const char* group() const                      { return _group; }
diff --git a/src/share/vm/runtime/synchronizer.cpp b/src/share/vm/runtime/synchronizer.cpp
index 6bd9233..86579c4 100644
--- a/src/share/vm/runtime/synchronizer.cpp
+++ b/src/share/vm/runtime/synchronizer.cpp
@@ -1318,20 +1318,20 @@
           guarantee (object->mark() == markOopDesc::INFLATING(), "invariant") ;
           object->release_set_mark(markOopDesc::encode(m));
 
-          // Hopefully the performance counters are allocated on distinct cache lines
-          // to avoid false sharing on MP systems ...
-          if (ObjectMonitor::_sync_Inflations != NULL) ObjectMonitor::_sync_Inflations->inc() ;
-          TEVENT(Inflate: overwrite stacklock) ;
-          if (TraceMonitorInflation) {
-            if (object->is_instance()) {
-              ResourceMark rm;
-              tty->print_cr("Inflating object " INTPTR_FORMAT " , mark " INTPTR_FORMAT " , type %s",
-                (void *) object, (intptr_t) object->mark(),
-                object->klass()->external_name());
-            }
-          }
-          return m ;
+      // Hopefully the performance counters are allocated on distinct cache lines
+      // to avoid false sharing on MP systems ...
+      OM_PERFDATA_OP(Inflations, inc());
+      TEVENT(Inflate: overwrite stacklock);
+      if (TraceMonitorInflation) {
+        if (object->is_instance()) {
+          ResourceMark rm;
+          tty->print_cr("Inflating object " INTPTR_FORMAT " , mark " INTPTR_FORMAT " , type %s",
+                        (void *) object, (intptr_t) object->mark(),
+                        object->klass()->external_name());
+        }
       }
+      return m;
+    }
 
       // CASE: neutral
       // TODO-FIXME: for entry we currently inflate and then try to CAS _owner.
@@ -1368,19 +1368,19 @@
           // live-lock -- "Inflated" is an absorbing state.
       }
 
-      // Hopefully the performance counters are allocated on distinct
-      // cache lines to avoid false sharing on MP systems ...
-      if (ObjectMonitor::_sync_Inflations != NULL) ObjectMonitor::_sync_Inflations->inc() ;
-      TEVENT(Inflate: overwrite neutral) ;
-      if (TraceMonitorInflation) {
-        if (object->is_instance()) {
-          ResourceMark rm;
-          tty->print_cr("Inflating object " INTPTR_FORMAT " , mark " INTPTR_FORMAT " , type %s",
-            (void *) object, (intptr_t) object->mark(),
-            object->klass()->external_name());
-        }
+    // Hopefully the performance counters are allocated on distinct
+    // cache lines to avoid false sharing on MP systems ...
+    OM_PERFDATA_OP(Inflations, inc());
+    TEVENT(Inflate: overwrite neutral);
+    if (TraceMonitorInflation) {
+      if (object->is_instance()) {
+        ResourceMark rm;
+        tty->print_cr("Inflating object " INTPTR_FORMAT " , mark " INTPTR_FORMAT " , type %s",
+                      (void *) object, (intptr_t) object->mark(),
+                      object->klass()->external_name());
       }
-      return m ;
+    }
+    return m;
   }
 }
 
@@ -1586,8 +1586,8 @@
   }
   Thread::muxRelease (&ListLock) ;
 
-  if (ObjectMonitor::_sync_Deflations != NULL) ObjectMonitor::_sync_Deflations->inc(nScavenged) ;
-  if (ObjectMonitor::_sync_MonExtant  != NULL) ObjectMonitor::_sync_MonExtant ->set_value(nInCirculation);
+  OM_PERFDATA_OP(Deflations, inc(nScavenged));
+  OM_PERFDATA_OP(MonExtant, set_value(nInCirculation));
 
   // TODO: Add objectMonitor leak detection.
   // Audit/inventory the objectMonitors -- make sure they're all accounted for.
diff --git a/src/share/vm/runtime/synchronizer.hpp b/src/share/vm/runtime/synchronizer.hpp
index 3b2597d..1bd635a 100644
--- a/src/share/vm/runtime/synchronizer.hpp
+++ b/src/share/vm/runtime/synchronizer.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -161,7 +161,7 @@
   void waitUninterruptibly (TRAPS) { ObjectSynchronizer::waitUninterruptibly (_obj, 0, CHECK);}
   // complete_exit gives up lock completely, returning recursion count
   // reenter reclaims lock with original recursion count
-  intptr_t complete_exit(TRAPS) { return  ObjectSynchronizer::complete_exit(_obj, CHECK_0); }
+  intptr_t complete_exit(TRAPS) { return  ObjectSynchronizer::complete_exit(_obj, THREAD); }
   void reenter(intptr_t recursion, TRAPS) { ObjectSynchronizer::reenter(_obj, recursion, CHECK); }
 };
 
diff --git a/src/share/vm/runtime/thread.cpp b/src/share/vm/runtime/thread.cpp
index 0dc86d9..48bba78 100644
--- a/src/share/vm/runtime/thread.cpp
+++ b/src/share/vm/runtime/thread.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1451,7 +1451,7 @@
   _in_deopt_handler = 0;
   _doing_unsafe_access = false;
   _stack_guard_state = stack_guard_unused;
-  (void)const_cast<oop&>(_exception_oop = NULL);
+  (void)const_cast<oop&>(_exception_oop = oop(NULL));
   _exception_pc  = 0;
   _exception_handler_pc = 0;
   _is_method_handle_return = 0;
@@ -2485,7 +2485,15 @@
 }
 
 void JavaThread::create_stack_guard_pages() {
-  if (! os::uses_stack_guard_pages() || _stack_guard_state != stack_guard_unused) return;
+  if (!os::uses_stack_guard_pages() ||
+      _stack_guard_state != stack_guard_unused ||
+      (DisablePrimordialThreadGuardPages && os::is_primordial_thread())) {
+      if (TraceThreadEvents) {
+        tty->print_cr("Stack guard page creation for thread "
+                      UINTX_FORMAT " disabled", os::current_thread_id());
+      }
+    return;
+  }
   address low_addr = stack_base() - stack_size();
   size_t len = (StackYellowPages + StackRedPages) * os::vm_page_size();
 
@@ -3242,6 +3250,9 @@
   _scanned_nmethod = NULL;
   _compiler = NULL;
 
+  // Compiler uses resource area for compilation, let's bias it to mtCompiler
+  resource_area()->bias_to(mtCompiler);
+
 #ifndef PRODUCT
   _ideal_graph_printer = NULL;
 #endif
@@ -3332,6 +3343,7 @@
   Arguments::init_version_specific_system_properties();
 
   // Parse arguments
+  // Note: this internally calls os::init_container_support()
   jint parse_result = Arguments::parse(args);
   if (parse_result != JNI_OK) return parse_result;
 
diff --git a/src/share/vm/runtime/thread.hpp b/src/share/vm/runtime/thread.hpp
index 1117c87..68169b7 100644
--- a/src/share/vm/runtime/thread.hpp
+++ b/src/share/vm/runtime/thread.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -51,11 +51,9 @@
 #include "gc_implementation/g1/dirtyCardQueue.hpp"
 #include "gc_implementation/g1/satbQueue.hpp"
 #endif // INCLUDE_ALL_GCS
-#ifdef ZERO
 #ifdef TARGET_ARCH_zero
 # include "stack_zero.hpp"
 #endif
-#endif
 
 class ThreadSafepointState;
 class ThreadProfiler;
@@ -1801,7 +1799,8 @@
 
 inline bool JavaThread::stack_yellow_zone_enabled() {
 #ifdef ASSERT
-  if (os::uses_stack_guard_pages()) {
+  if (os::uses_stack_guard_pages() &&
+      !(DisablePrimordialThreadGuardPages && os::is_primordial_thread())) {
     assert(_stack_guard_state != stack_guard_unused, "guard pages must be in use");
   }
 #endif
diff --git a/src/share/vm/runtime/unhandledOops.cpp b/src/share/vm/runtime/unhandledOops.cpp
index d27b1fb..3e7b6c1 100644
--- a/src/share/vm/runtime/unhandledOops.cpp
+++ b/src/share/vm/runtime/unhandledOops.cpp
@@ -105,7 +105,7 @@
   _level --;
   if (unhandled_oop_print) {
     for (int i=0; i<_level; i++) tty->print(" ");
-    tty->print_cr("u "INTPTR_FORMAT, op);
+    tty->print_cr("u " INTPTR_FORMAT, op);
   }
 
   int i = _oop_list->find_from_end(op, match_oop_entry);
diff --git a/src/share/vm/runtime/vmStructs.cpp b/src/share/vm/runtime/vmStructs.cpp
index 3447b7c..161a4c4 100644
--- a/src/share/vm/runtime/vmStructs.cpp
+++ b/src/share/vm/runtime/vmStructs.cpp
@@ -278,7 +278,7 @@
   volatile_nonstatic_field(ArrayKlass,         _lower_dimension,                              Klass*)                                \
   nonstatic_field(ArrayKlass,                  _vtable_len,                                   int)                                   \
   nonstatic_field(ArrayKlass,                  _component_mirror,                             oop)                                   \
-  nonstatic_field(CompiledICHolder,     _holder_method,                                Method*)                               \
+  nonstatic_field(CompiledICHolder,     _holder_metadata,                              Metadata*)                             \
   nonstatic_field(CompiledICHolder,     _holder_klass,                                 Klass*)                                \
   nonstatic_field(ConstantPool,         _tags,                                         Array<u1>*)                            \
   nonstatic_field(ConstantPool,         _cache,                                        ConstantPoolCache*)                    \
diff --git a/src/share/vm/runtime/vm_operations.hpp b/src/share/vm/runtime/vm_operations.hpp
index fb99be9..cc32b97 100644
--- a/src/share/vm/runtime/vm_operations.hpp
+++ b/src/share/vm/runtime/vm_operations.hpp
@@ -97,6 +97,7 @@
   template(LinuxDllLoad)                          \
   template(RotateGCLog)                           \
   template(WhiteBoxOperation)                     \
+  template(ClassLoaderStatsOperation)             \
 
 class VM_Operation: public CHeapObj<mtInternal> {
  public:
diff --git a/src/share/vm/runtime/vm_version.cpp b/src/share/vm/runtime/vm_version.cpp
index 95628fe..6ad28d5 100644
--- a/src/share/vm/runtime/vm_version.cpp
+++ b/src/share/vm/runtime/vm_version.cpp
@@ -183,11 +183,16 @@
 #ifndef CPU
 #ifdef ZERO
 #define CPU      ZERO_LIBARCH
+#elif defined(PPC64)
+#if defined(VM_LITTLE_ENDIAN)
+#define CPU      "ppc64le"
+#else
+#define CPU      "ppc64"
+#endif
 #else
 #define CPU      IA32_ONLY("x86")                \
                  IA64_ONLY("ia64")               \
                  AMD64_ONLY("amd64")             \
-                 PPC64_ONLY("ppc64")             \
                  SPARC_ONLY("sparc")
 #endif // ZERO
 #endif
@@ -217,6 +222,14 @@
         #define HOTSPOT_BUILD_COMPILER "MS VC++ 10.0 (VS2010)"
       #elif _MSC_VER == 1700
         #define HOTSPOT_BUILD_COMPILER "MS VC++ 11.0 (VS2012)"
+      #elif _MSC_VER == 1800
+        #define HOTSPOT_BUILD_COMPILER "MS VC++ 12.0 (VS2013)"
+      #elif _MSC_VER == 1900
+        #define HOTSPOT_BUILD_COMPILER "MS VC++ 14.0 (VS2015)"
+      #elif _MSC_VER == 1912
+        #define HOTSPOT_BUILD_COMPILER "MS VC++ 15.5 (VS2017)"
+      #elif _MSC_VER == 1913
+        #define HOTSPOT_BUILD_COMPILER "MS VC++ 15.6 (VS2017)"
       #else
         #define HOTSPOT_BUILD_COMPILER "unknown MS VC++:" XSTR(_MSC_VER)
       #endif
diff --git a/src/share/vm/services/attachListener.cpp b/src/share/vm/services/attachListener.cpp
index 45d930d..59b2f54 100644
--- a/src/share/vm/services/attachListener.cpp
+++ b/src/share/vm/services/attachListener.cpp
@@ -466,15 +466,39 @@
   }
 }
 
+bool AttachListener::has_init_error(TRAPS) {
+  if (HAS_PENDING_EXCEPTION) {
+    tty->print_cr("Exception in VM (AttachListener::init) : ");
+    java_lang_Throwable::print(PENDING_EXCEPTION, tty);
+    tty->cr();
+
+    CLEAR_PENDING_EXCEPTION;
+
+    return true;
+  } else {
+    return false;
+  }
+}
+
 // Starts the Attach Listener thread
 void AttachListener::init() {
   EXCEPTION_MARK;
-  Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, CHECK);
+  Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, THREAD);
+  if (has_init_error(THREAD)) {
+    return;
+  }
+
   instanceKlassHandle klass (THREAD, k);
-  instanceHandle thread_oop = klass->allocate_instance_handle(CHECK);
+  instanceHandle thread_oop = klass->allocate_instance_handle(THREAD);
+  if (has_init_error(THREAD)) {
+    return;
+  }
 
   const char thread_name[] = "Attach Listener";
-  Handle string = java_lang_String::create_from_str(thread_name, CHECK);
+  Handle string = java_lang_String::create_from_str(thread_name, THREAD);
+  if (has_init_error(THREAD)) {
+    return;
+  }
 
   // Initialize thread_oop to put it into the system threadGroup
   Handle thread_group (THREAD, Universe::system_thread_group());
@@ -487,13 +511,7 @@
                        string,
                        THREAD);
 
-  if (HAS_PENDING_EXCEPTION) {
-    tty->print_cr("Exception in VM (AttachListener::init) : ");
-    java_lang_Throwable::print(PENDING_EXCEPTION, tty);
-    tty->cr();
-
-    CLEAR_PENDING_EXCEPTION;
-
+  if (has_init_error(THREAD)) {
     return;
   }
 
@@ -505,14 +523,7 @@
                         vmSymbols::thread_void_signature(),
                         thread_oop,             // ARG 1
                         THREAD);
-
-  if (HAS_PENDING_EXCEPTION) {
-    tty->print_cr("Exception in VM (AttachListener::init) : ");
-    java_lang_Throwable::print(PENDING_EXCEPTION, tty);
-    tty->cr();
-
-    CLEAR_PENDING_EXCEPTION;
-
+  if (has_init_error(THREAD)) {
     return;
   }
 
diff --git a/src/share/vm/services/attachListener.hpp b/src/share/vm/services/attachListener.hpp
index 6995a0f..5204c4c 100644
--- a/src/share/vm/services/attachListener.hpp
+++ b/src/share/vm/services/attachListener.hpp
@@ -94,6 +94,9 @@
   // dequeue the next operation
   static AttachOperation* dequeue();
 #endif // !INCLUDE_SERVICES
+
+ private:
+  static bool has_init_error(TRAPS);
 };
 
 #if INCLUDE_SERVICES
diff --git a/src/share/vm/services/diagnosticArgument.cpp b/src/share/vm/services/diagnosticArgument.cpp
index 51126f0..1a9c2e3 100644
--- a/src/share/vm/services/diagnosticArgument.cpp
+++ b/src/share/vm/services/diagnosticArgument.cpp
@@ -89,7 +89,7 @@
                                                   size_t len, TRAPS) {
   int scanned = -1;
   if (str == NULL
-      || sscanf(str, JLONG_FORMAT"%n", &_value, &scanned) != 1
+      || sscanf(str, JLONG_FORMAT "%n", &_value, &scanned) != 1
       || (size_t)scanned != len)
   {
     ResourceMark rm;
diff --git a/src/share/vm/services/diagnosticCommand.cpp b/src/share/vm/services/diagnosticCommand.cpp
index f9551c9..ede8db1 100644
--- a/src/share/vm/services/diagnosticCommand.cpp
+++ b/src/share/vm/services/diagnosticCommand.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,14 +23,17 @@
  */
 
 #include "precompiled.hpp"
+#include "classfile/classLoaderStats.hpp"
 #include "gc_implementation/shared/vmGCOperations.hpp"
 #include "runtime/javaCalls.hpp"
+#include "runtime/os.hpp"
 #include "services/diagnosticArgument.hpp"
 #include "services/diagnosticCommand.hpp"
 #include "services/diagnosticFramework.hpp"
 #include "services/heapDumper.hpp"
 #include "services/management.hpp"
 #include "utilities/macros.hpp"
+#include "oops/objArrayOop.hpp"
 
 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
 
@@ -46,9 +49,12 @@
   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<CommandLineDCmd>(full_export, true, false));
   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<PrintSystemPropertiesDCmd>(full_export, true, false));
   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<PrintVMFlagsDCmd>(full_export, true, false));
+  DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<VMDynamicLibrariesDCmd>(full_export, true, false));
   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<VMUptimeDCmd>(full_export, true, false));
   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<SystemGCDCmd>(full_export, true, false));
   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<RunFinalizationDCmd>(full_export, true, false));
+  DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<HeapInfoDCmd>(full_export, true, false));
+  DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<FinalizerInfoDCmd>(full_export, true, false));
 #if INCLUDE_SERVICES // Heap dumping/inspection supported
   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<HeapDumpDCmd>(DCmd_Source_Internal | DCmd_Source_AttachAPI, true, false));
   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<ClassHistogramDCmd>(full_export, true, false));
@@ -56,6 +62,7 @@
 #endif // INCLUDE_SERVICES
   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<ThreadDumpDCmd>(full_export, true, false));
   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<RotateGCLogDCmd>(full_export, true, false));
+  DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<ClassLoaderStatsDCmd>(full_export, true, false));
 
   // Enhanced JMX Agent Support
   // These commands won't be exported via the DiagnosticCommandMBean until an
@@ -273,6 +280,60 @@
                          vmSymbols::void_method_signature(), CHECK);
 }
 
+void HeapInfoDCmd::execute(DCmdSource source, TRAPS) {
+  Universe::heap()->print_on(output());
+}
+
+void FinalizerInfoDCmd::execute(DCmdSource source, TRAPS) {
+  ResourceMark rm;
+
+
+  Klass* k = SystemDictionary::resolve_or_null(
+    vmSymbols::finalizer_histogram_klass(), THREAD);
+  assert(k != NULL, "FinalizerHistogram class is not accessible");
+
+  instanceKlassHandle klass(THREAD, k);
+  JavaValue result(T_ARRAY);
+
+  // We are calling lang.ref.FinalizerHistogram.getFinalizerHistogram() method
+  // and expect it to return array of FinalizerHistogramEntry as Object[]
+
+  JavaCalls::call_static(&result, klass,
+                         vmSymbols::get_finalizer_histogram_name(),
+                         vmSymbols::void_finalizer_histogram_entry_array_signature(), CHECK);
+
+  objArrayOop result_oop = (objArrayOop) result.get_jobject();
+  if (result_oop->length() == 0) {
+    output()->print_cr("No instances waiting for finalization found");
+    return;
+  }
+
+  oop foop = result_oop->obj_at(0);
+  InstanceKlass* ik = InstanceKlass::cast(foop->klass());
+
+  fieldDescriptor count_fd, name_fd;
+
+  Klass* count_res = ik->find_field(
+    vmSymbols::finalizer_histogram_entry_count_field(), vmSymbols::int_signature(), &count_fd);
+
+  Klass* name_res = ik->find_field(
+    vmSymbols::finalizer_histogram_entry_name_field(), vmSymbols::string_signature(), &name_fd);
+
+  assert(count_res != NULL && name_res != NULL, "Unexpected layout of FinalizerHistogramEntry");
+
+  output()->print_cr("Unreachable instances waiting for finalization");
+  output()->print_cr("#instances  class name");
+  output()->print_cr("-----------------------");
+
+  for (int i = 0; i < result_oop->length(); ++i) {
+    oop element_oop = result_oop->obj_at(i);
+    oop str_oop = element_oop->obj_field(name_fd.offset());
+    char *name = java_lang_String::as_utf8_string(str_oop);
+    int count = element_oop->int_field(count_fd.offset());
+    output()->print_cr("%10d  %s", count, name);
+  }
+}
+
 #if INCLUDE_SERVICES // Heap dumping/inspection supported
 HeapDumpDCmd::HeapDumpDCmd(outputStream* output, bool heap) :
                            DCmdWithParser(output, heap),
@@ -619,8 +680,7 @@
 }
 
 JMXStartLocalDCmd::JMXStartLocalDCmd(outputStream *output, bool heap_allocated) :
-  DCmd(output, heap_allocated)
-{
+  DCmd(output, heap_allocated) {
   // do nothing
 }
 
@@ -641,7 +701,6 @@
     JavaCalls::call_static(&result, ik, vmSymbols::startLocalAgent_name(), vmSymbols::void_method_signature(), CHECK);
 }
 
-
 void JMXStopRemoteDCmd::execute(DCmdSource source, TRAPS) {
     ResourceMark rm(THREAD);
     HandleMark hm(THREAD);
@@ -659,6 +718,16 @@
     JavaCalls::call_static(&result, ik, vmSymbols::stopRemoteAgent_name(), vmSymbols::void_method_signature(), CHECK);
 }
 
+VMDynamicLibrariesDCmd::VMDynamicLibrariesDCmd(outputStream *output, bool heap_allocated) :
+  DCmd(output, heap_allocated) {
+  // do nothing
+}
+
+void VMDynamicLibrariesDCmd::execute(DCmdSource source, TRAPS) {
+  os::print_dll_info(output());
+  output()->cr();
+}
+
 void RotateGCLogDCmd::execute(DCmdSource source, TRAPS) {
   if (UseGCLogFileRotation) {
     VM_RotateGCLog rotateop(output());
diff --git a/src/share/vm/services/diagnosticCommand.hpp b/src/share/vm/services/diagnosticCommand.hpp
index 3fda342..b1fb57e 100644
--- a/src/share/vm/services/diagnosticCommand.hpp
+++ b/src/share/vm/services/diagnosticCommand.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -132,6 +132,29 @@
   virtual void execute(DCmdSource source, TRAPS);
 };
 
+class VMDynamicLibrariesDCmd : public DCmd {
+public:
+  VMDynamicLibrariesDCmd(outputStream* output, bool heap);
+  static const char* name() {
+    return "VM.dynlibs";
+  }
+  static const char* description() {
+    return "Print loaded dynamic libraries.";
+  }
+  static const char* impact() {
+    return "Low";
+  }
+  static const JavaPermission permission() {
+    JavaPermission p = {"java.lang.management.ManagementPermission",
+                        "monitor", NULL};
+    return p;
+  }
+  static int num_arguments() {
+    return 0;
+  };
+  virtual void execute(DCmdSource source, TRAPS);
+};
+
 class VMUptimeDCmd : public DCmdWithParser {
 protected:
   DCmdArgument<bool> _date;
@@ -176,6 +199,46 @@
     virtual void execute(DCmdSource source, TRAPS);
 };
 
+class HeapInfoDCmd : public DCmd {
+public:
+  HeapInfoDCmd(outputStream* output, bool heap) : DCmd(output, heap) { }
+  static const char* name() { return "GC.heap_info"; }
+  static const char* description() {
+    return "Provide generic Java heap information.";
+  }
+  static const char* impact() {
+    return "Medium";
+  }
+  static int num_arguments() { return 0; }
+  static const JavaPermission permission() {
+    JavaPermission p = {"java.lang.management.ManagementPermission",
+      "monitor", NULL};
+      return p;
+  }
+
+  virtual void execute(DCmdSource source, TRAPS);
+};
+
+class FinalizerInfoDCmd : public DCmd {
+public:
+  FinalizerInfoDCmd(outputStream* output, bool heap) : DCmd(output, heap) { }
+  static const char* name() { return "GC.finalizer_info"; }
+  static const char* description() {
+    return "Provide information about Java finalization queue.";
+  }
+  static const char* impact() {
+    return "Medium";
+  }
+  static int num_arguments() { return 0; }
+  static const JavaPermission permission() {
+    JavaPermission p = {"java.lang.management.ManagementPermission",
+      "monitor", NULL};
+      return p;
+  }
+
+  virtual void execute(DCmdSource source, TRAPS);
+};
+
 #if INCLUDE_SERVICES   // Heap dumping supported
 // See also: dump_heap in attachListener.cpp
 class HeapDumpDCmd : public DCmdWithParser {
diff --git a/src/share/vm/services/heapDumper.cpp b/src/share/vm/services/heapDumper.cpp
index 9086cfb..a62ce91 100644
--- a/src/share/vm/services/heapDumper.cpp
+++ b/src/share/vm/services/heapDumper.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -815,6 +815,28 @@
   for (FieldStream fldc(ikh, true, true); !fldc.eos(); fldc.next()) {
     if (fldc.access_flags().is_static()) field_count++;
   }
+  // Add in resolved_references which is referenced by the cpCache
+  // The resolved_references is an array per InstanceKlass holding the
+  // strings and other oops resolved from the constant pool.
+  oop resolved_references = ikh->constants()->resolved_references_or_null();
+  if (resolved_references != NULL) {
+    field_count++;
+
+    // Add in the resolved_references of the used previous versions of the class
+    // in the case of RedefineClasses
+    InstanceKlass* prev = ikh->previous_versions();
+    while (prev != NULL && prev->constants()->resolved_references_or_null() != NULL) {
+      field_count++;
+      prev = prev->previous_versions();
+    }
+  }
+
+  // Also provide a pointer to the init_lock if present, so there aren't unreferenced int[0]
+  // arrays.
+  oop init_lock = ikh->init_lock();
+  if (init_lock != NULL) {
+    field_count++;
+  }
 
   writer->write_u2(field_count);
 
@@ -833,6 +855,29 @@
       dump_field_value(writer, sig->byte_at(0), addr);
     }
   }
+
+  // Add resolved_references for each class that has them
+  if (resolved_references != NULL) {
+    writer->write_symbolID(vmSymbols::resolved_references_name());  // name
+    writer->write_u1(sig2tag(vmSymbols::object_array_signature())); // type
+    writer->write_objectID(resolved_references);
+
+    // Also write any previous versions
+    InstanceKlass* prev = ikh->previous_versions();
+    while (prev != NULL && prev->constants()->resolved_references_or_null() != NULL) {
+      writer->write_symbolID(vmSymbols::resolved_references_name());  // name
+      writer->write_u1(sig2tag(vmSymbols::object_array_signature())); // type
+      writer->write_objectID(prev->constants()->resolved_references());
+      prev = prev->previous_versions();
+    }
+  }
+
+  // Add init lock to the end if the class is not yet initialized
+  if (init_lock != NULL) {
+    writer->write_symbolID(vmSymbols::init_lock_name());         // name
+    writer->write_u1(sig2tag(vmSymbols::int_array_signature())); // type
+    writer->write_objectID(init_lock);
+  }
 }
 
 // dump the raw values of the instance fields of the given object
@@ -868,7 +913,7 @@
     if (!fld.access_flags().is_static()) {
       Symbol* sig = fld.signature();
 
-      writer->write_symbolID(fld.name());                   // name
+      writer->write_symbolID(fld.name());   // name
       writer->write_u1(sig2tag(sig));       // type
     }
   }
@@ -1758,6 +1803,8 @@
   // HPROF_GC_ROOT_JNI_GLOBAL
   JNIGlobalsDumper jni_dumper(writer());
   JNIHandles::oops_do(&jni_dumper);
+  Universe::oops_do(&jni_dumper);  // technically not jni roots, but global roots
+                                   // for things like preallocated throwable backtraces
   check_segment_length();
 
   // HPROF_GC_ROOT_STICKY_CLASS
diff --git a/src/share/vm/services/mallocSiteTable.cpp b/src/share/vm/services/mallocSiteTable.cpp
index 8090de8..94fe1b9 100644
--- a/src/share/vm/services/mallocSiteTable.cpp
+++ b/src/share/vm/services/mallocSiteTable.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -97,7 +97,7 @@
 
   // Instantiate hash entry for hashtable entry allocation callsite
   MallocSiteHashtableEntry* entry = ::new ((void*)_hash_entry_allocation_site)
-    MallocSiteHashtableEntry(*stack);
+    MallocSiteHashtableEntry(*stack, mtNMT);
 
   // Add the allocation site to hashtable.
   int index = hash_to_index(stack->hash());
@@ -134,15 +134,16 @@
  *  Under any of above circumstances, caller should handle the situation.
  */
 MallocSite* MallocSiteTable::lookup_or_add(const NativeCallStack& key, size_t* bucket_idx,
-  size_t* pos_idx) {
-  int index = hash_to_index(key.hash());
+  size_t* pos_idx, MEMFLAGS flags) {
+  assert(flags != mtNone, "Should have a real memory type");
+  unsigned int index = hash_to_index(key.hash());
   assert(index >= 0, "Negative index");
   *bucket_idx = (size_t)index;
   *pos_idx = 0;
 
   // First entry for this hash bucket
   if (_table[index] == NULL) {
-    MallocSiteHashtableEntry* entry = new_entry(key);
+    MallocSiteHashtableEntry* entry = new_entry(key, flags);
     // OOM check
     if (entry == NULL) return NULL;
 
@@ -157,13 +158,12 @@
   MallocSiteHashtableEntry* head = _table[index];
   while (head != NULL && (*pos_idx) <= MAX_BUCKET_LENGTH) {
     MallocSite* site = head->data();
-    if (site->equals(key)) {
-      // found matched entry
+    if (site->flags() == flags && site->equals(key)) {
       return head->data();
     }
 
     if (head->next() == NULL && (*pos_idx) < MAX_BUCKET_LENGTH) {
-      MallocSiteHashtableEntry* entry = new_entry(key);
+      MallocSiteHashtableEntry* entry = new_entry(key, flags);
       // OOM check
       if (entry == NULL) return NULL;
       if (head->atomic_insert(entry)) {
@@ -192,10 +192,10 @@
 // Allocates MallocSiteHashtableEntry object. Special call stack
 // (pre-installed allocation site) has to be used to avoid infinite
 // recursion.
-MallocSiteHashtableEntry* MallocSiteTable::new_entry(const NativeCallStack& key) {
+MallocSiteHashtableEntry* MallocSiteTable::new_entry(const NativeCallStack& key, MEMFLAGS flags) {
   void* p = AllocateHeap(sizeof(MallocSiteHashtableEntry), mtNMT,
     *hash_entry_allocation_stack(), AllocFailStrategy::RETURN_NULL);
-  return ::new (p) MallocSiteHashtableEntry(key);
+  return ::new (p) MallocSiteHashtableEntry(key, flags);
 }
 
 void MallocSiteTable::reset() {
diff --git a/src/share/vm/services/mallocSiteTable.hpp b/src/share/vm/services/mallocSiteTable.hpp
index cff9816..b2e34af 100644
--- a/src/share/vm/services/mallocSiteTable.hpp
+++ b/src/share/vm/services/mallocSiteTable.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -37,12 +37,16 @@
 // MallocSite represents a code path that eventually calls
 // os::malloc() to allocate memory
 class MallocSite : public AllocationSite<MemoryCounter> {
+ private:
+  MEMFLAGS _flags;
+
  public:
   MallocSite() :
-    AllocationSite<MemoryCounter>(NativeCallStack::EMPTY_STACK) { }
+    AllocationSite<MemoryCounter>(NativeCallStack::empty_stack()), _flags(mtNone) {}
 
-  MallocSite(const NativeCallStack& stack) :
-    AllocationSite<MemoryCounter>(stack) { }
+  MallocSite(const NativeCallStack& stack, MEMFLAGS flags) :
+    AllocationSite<MemoryCounter>(stack), _flags(flags) {}
+
 
   void allocate(size_t size)      { data()->allocate(size);   }
   void deallocate(size_t size)    { data()->deallocate(size); }
@@ -51,6 +55,7 @@
   size_t size()  const { return peek()->size(); }
   // The number of calls were made
   size_t count() const { return peek()->count(); }
+  MEMFLAGS flags() const { return (MEMFLAGS)_flags; }
 };
 
 // Malloc site hashtable entry
@@ -62,8 +67,10 @@
  public:
   MallocSiteHashtableEntry() : _next(NULL) { }
 
-  MallocSiteHashtableEntry(NativeCallStack stack):
-    _malloc_site(stack), _next(NULL) { }
+  MallocSiteHashtableEntry(NativeCallStack stack, MEMFLAGS flags):
+    _malloc_site(stack, flags), _next(NULL) {
+    assert(flags != mtNone, "Expect a real memory type");
+  }
 
   inline const MallocSiteHashtableEntry* next() const {
     return _next;
@@ -198,11 +205,11 @@
   //  1. out of memory
   //  2. overflow hash bucket
   static inline bool allocation_at(const NativeCallStack& stack, size_t size,
-    size_t* bucket_idx, size_t* pos_idx) {
+    size_t* bucket_idx, size_t* pos_idx, MEMFLAGS flags) {
     AccessLock locker(&_access_count);
     if (locker.sharedLock()) {
       NOT_PRODUCT(_peak_count = MAX2(_peak_count, _access_count);)
-      MallocSite* site = lookup_or_add(stack, bucket_idx, pos_idx);
+      MallocSite* site = lookup_or_add(stack, bucket_idx, pos_idx, flags);
       if (site != NULL) site->allocate(size);
       return site != NULL;
     }
@@ -228,18 +235,17 @@
   static bool walk_malloc_site(MallocSiteWalker* walker);
 
  private:
-  static MallocSiteHashtableEntry* new_entry(const NativeCallStack& key);
+  static MallocSiteHashtableEntry* new_entry(const NativeCallStack& key, MEMFLAGS flags);
   static void reset();
 
   // Delete a bucket linked list
   static void delete_linked_list(MallocSiteHashtableEntry* head);
 
-  static MallocSite* lookup_or_add(const NativeCallStack& key, size_t* bucket_idx, size_t* pos_idx);
+  static MallocSite* lookup_or_add(const NativeCallStack& key, size_t* bucket_idx, size_t* pos_idx, MEMFLAGS flags);
   static MallocSite* malloc_site(size_t bucket_idx, size_t pos_idx);
   static bool walk(MallocSiteWalker* walker);
 
-  static inline int hash_to_index(int  hash) {
-    hash = (hash > 0) ? hash : (-hash);
+  static inline unsigned int hash_to_index(unsigned int hash) {
     return (hash % table_size);
   }
 
diff --git a/src/share/vm/services/mallocTracker.cpp b/src/share/vm/services/mallocTracker.cpp
index dc4f08f..8d32df3 100644
--- a/src/share/vm/services/mallocTracker.cpp
+++ b/src/share/vm/services/mallocTracker.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -78,8 +78,8 @@
 }
 
 bool MallocHeader::record_malloc_site(const NativeCallStack& stack, size_t size,
-  size_t* bucket_idx, size_t* pos_idx) const {
-  bool ret =  MallocSiteTable::allocation_at(stack, size, bucket_idx, pos_idx);
+  size_t* bucket_idx, size_t* pos_idx, MEMFLAGS flags) const {
+  bool ret = MallocSiteTable::allocation_at(stack, size, bucket_idx, pos_idx, flags);
 
   // Something went wrong, could be OOM or overflow malloc site table.
   // We want to keep tracking data under OOM circumstance, so transition to
diff --git a/src/share/vm/services/mallocTracker.hpp b/src/share/vm/services/mallocTracker.hpp
index 3c61aa4..d770e41 100644
--- a/src/share/vm/services/mallocTracker.hpp
+++ b/src/share/vm/services/mallocTracker.hpp
@@ -268,7 +268,7 @@
     if (level == NMT_detail) {
       size_t bucket_idx;
       size_t pos_idx;
-      if (record_malloc_site(stack, size, &bucket_idx, &pos_idx)) {
+      if (record_malloc_site(stack, size, &bucket_idx, &pos_idx, flags)) {
         assert(bucket_idx <= MAX_MALLOCSITE_TABLE_SIZE, "Overflow bucket index");
         assert(pos_idx <= MAX_BUCKET_LENGTH, "Overflow bucket position index");
         _bucket_idx = bucket_idx;
@@ -292,7 +292,7 @@
     _size = size;
   }
   bool record_malloc_site(const NativeCallStack& stack, size_t size,
-    size_t* bucket_idx, size_t* pos_idx) const;
+    size_t* bucket_idx, size_t* pos_idx, MEMFLAGS flags) const;
 };
 
 
diff --git a/src/share/vm/services/memBaseline.cpp b/src/share/vm/services/memBaseline.cpp
index 02b4924..f580aad 100644
--- a/src/share/vm/services/memBaseline.cpp
+++ b/src/share/vm/services/memBaseline.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -59,6 +59,15 @@
   return s1.call_stack()->compare(*s2.call_stack());
 }
 
+// Sort into allocation site addresses and memory type order for baseline comparison
+int compare_malloc_site_and_type(const MallocSite& s1, const MallocSite& s2) {
+  int res = compare_malloc_site(s1, s2);
+  if (res == 0) {
+    res = (int)(s1.flags() - s2.flags());
+  }
+
+  return res;
+}
 
 int compare_virtual_memory_site(const VirtualMemoryAllocationSite& s1,
   const VirtualMemoryAllocationSite& s2) {
@@ -225,6 +234,9 @@
     case by_site:
       malloc_sites_to_allocation_site_order();
       break;
+    case by_site_and_type:
+      malloc_sites_to_allocation_site_and_type_order();
+      break;
     case by_address:
     default:
       ShouldNotReachHere();
@@ -263,7 +275,7 @@
 }
 
 void MemBaseline::malloc_sites_to_allocation_site_order() {
-  if (_malloc_sites_order != by_site) {
+  if (_malloc_sites_order != by_site && _malloc_sites_order != by_site_and_type) {
     SortedLinkedList<MallocSite, compare_malloc_site> tmp;
     // Add malloc sites to sorted linked list to sort into site (address) order
     tmp.move(&_malloc_sites);
@@ -273,6 +285,17 @@
   }
 }
 
+void MemBaseline::malloc_sites_to_allocation_site_and_type_order() {
+  if (_malloc_sites_order != by_site_and_type) {
+    SortedLinkedList<MallocSite, compare_malloc_site_and_type> tmp;
+    // Add malloc sites to sorted linked list to sort into site (address) order
+    tmp.move(&_malloc_sites);
+    _malloc_sites.set_head(tmp.head());
+    tmp.set_head(NULL);
+    _malloc_sites_order = by_site_and_type;
+  }
+}
+
 void MemBaseline::virtual_memory_sites_to_size_order() {
   if (_virtual_memory_sites_order != by_size) {
     SortedLinkedList<VirtualMemoryAllocationSite, compare_virtual_memory_size> tmp;
diff --git a/src/share/vm/services/memBaseline.hpp b/src/share/vm/services/memBaseline.hpp
index fdcb76d..238d29d 100644
--- a/src/share/vm/services/memBaseline.hpp
+++ b/src/share/vm/services/memBaseline.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -55,9 +55,10 @@
   };
 
   enum SortingOrder {
-    by_address,   // by memory address
-    by_size,      // by memory size
-    by_site       // by call site where the memory is allocated from
+    by_address,      // by memory address
+    by_size,         // by memory size
+    by_site,         // by call site where the memory is allocated from
+    by_site_and_type // by call site and memory type
   };
 
  private:
@@ -188,6 +189,8 @@
   void malloc_sites_to_size_order();
   // Sort allocation sites in call site address order
   void malloc_sites_to_allocation_site_order();
+  // Sort allocation sites in call site address and memory type order
+  void malloc_sites_to_allocation_site_and_type_order();
 
   // Sort allocation sites in reserved size order
   void virtual_memory_sites_to_size_order();
diff --git a/src/share/vm/services/memReporter.cpp b/src/share/vm/services/memReporter.cpp
index 0269619..8199ee0 100644
--- a/src/share/vm/services/memReporter.cpp
+++ b/src/share/vm/services/memReporter.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -43,11 +43,16 @@
     amount_in_current_scale(reserved), scale, amount_in_current_scale(committed), scale);
 }
 
-void MemReporterBase::print_malloc(size_t amount, size_t count) const {
+void MemReporterBase::print_malloc(size_t amount, size_t count, MEMFLAGS flag) const {
   const char* scale = current_scale();
   outputStream* out = output();
-  out->print("(malloc=" SIZE_FORMAT "%s",
-    amount_in_current_scale(amount), scale);
+  if (flag != mtNone) {
+    out->print("(malloc=" SIZE_FORMAT "%s type=%s",
+      amount_in_current_scale(amount), scale, NMTUtil::flag_to_name(flag));
+  } else {
+    out->print("(malloc=" SIZE_FORMAT "%s",
+      amount_in_current_scale(amount), scale);
+  }
 
   if (count > 0) {
     out->print(" #" SIZE_FORMAT "", count);
@@ -200,7 +205,10 @@
     const NativeCallStack* stack = malloc_site->call_stack();
     stack->print_on(out);
     out->print("%29s", " ");
-    print_malloc(malloc_site->size(), malloc_site->count());
+    MEMFLAGS flag = malloc_site->flags();
+    assert((flag >= 0 && flag < (int)mt_number_of_types) && flag != mtNone,
+      "Must have a valid memory type");
+    print_malloc(malloc_site->size(), malloc_site->count(),flag);
     out->print_cr("\n");
   }
 }
@@ -304,11 +312,16 @@
 }
 
 void MemSummaryDiffReporter::print_malloc_diff(size_t current_amount, size_t current_count,
-    size_t early_amount, size_t early_count) const {
+    size_t early_amount, size_t early_count, MEMFLAGS flags) const {
   const char* scale = current_scale();
   outputStream* out = output();
 
   out->print("malloc=" SIZE_FORMAT "%s", amount_in_current_scale(current_amount), scale);
+  // Report type only if it is valid
+  if (flags != mtNone) {
+    out->print(" type=%s", NMTUtil::flag_to_name(flags));
+  }
+
   long amount_diff = diff_in_current_scale(current_amount, early_amount);
   if (amount_diff != 0) {
     out->print(" %+ld%s", amount_diff, scale);
@@ -437,7 +450,7 @@
         diff_in_current_scale(current_malloc_amount, early_malloc_amount) != 0) {
       out->print("%28s(", " ");
       print_malloc_diff(current_malloc_amount, (flag == mtChunk) ? 0 : current_malloc->malloc_count(),
-        early_malloc_amount, early_malloc->malloc_count());
+        early_malloc_amount, early_malloc->malloc_count(), mtNone);
       out->print_cr(")");
     }
 
@@ -485,8 +498,8 @@
 }
 
 void MemDetailDiffReporter::diff_malloc_sites() const {
-  MallocSiteIterator early_itr = _early_baseline.malloc_sites(MemBaseline::by_site);
-  MallocSiteIterator current_itr = _current_baseline.malloc_sites(MemBaseline::by_site);
+  MallocSiteIterator early_itr = _early_baseline.malloc_sites(MemBaseline::by_site_and_type);
+  MallocSiteIterator current_itr = _current_baseline.malloc_sites(MemBaseline::by_site_and_type);
 
   const MallocSite* early_site   = early_itr.next();
   const MallocSite* current_site = current_itr.next();
@@ -549,22 +562,23 @@
 
 void MemDetailDiffReporter::new_malloc_site(const MallocSite* malloc_site) const {
   diff_malloc_site(malloc_site->call_stack(), malloc_site->size(), malloc_site->count(),
-    0, 0);
+    0, 0, malloc_site->flags());
 }
 
 void MemDetailDiffReporter::old_malloc_site(const MallocSite* malloc_site) const {
   diff_malloc_site(malloc_site->call_stack(), 0, 0, malloc_site->size(),
-    malloc_site->count());
+    malloc_site->count(), malloc_site->flags());
 }
 
 void MemDetailDiffReporter::diff_malloc_site(const MallocSite* early,
   const MallocSite* current)  const {
+  assert(early->flags() == current->flags(), "Must be the same memory type");
   diff_malloc_site(current->call_stack(), current->size(), current->count(),
-    early->size(), early->count());
+    early->size(), early->count(), early->flags());
 }
 
 void MemDetailDiffReporter::diff_malloc_site(const NativeCallStack* stack, size_t current_size,
-  size_t current_count, size_t early_size, size_t early_count) const {
+  size_t current_count, size_t early_size, size_t early_count, MEMFLAGS flags) const {
   outputStream* out = output();
 
   assert(stack != NULL, "NULL stack");
@@ -576,7 +590,7 @@
   stack->print_on(out);
   out->print("%28s (", " ");
   print_malloc_diff(current_size, current_count,
-    early_size, early_count);
+    early_size, early_count, flags);
 
   out->print_cr(")\n");
 }
diff --git a/src/share/vm/services/memReporter.hpp b/src/share/vm/services/memReporter.hpp
index 951076c..9b83f8c 100644
--- a/src/share/vm/services/memReporter.hpp
+++ b/src/share/vm/services/memReporter.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -76,7 +76,7 @@
 
   // Print summary total, malloc and virtual memory
   void print_total(size_t reserved, size_t committed) const;
-  void print_malloc(size_t amount, size_t count) const;
+  void print_malloc(size_t amount, size_t count, MEMFLAGS flag = mtNone) const;
   void print_virtual_memory(size_t reserved, size_t committed) const;
 
   void print_malloc_line(size_t amount, size_t count) const;
@@ -174,7 +174,7 @@
 
  protected:
   void print_malloc_diff(size_t current_amount, size_t current_count,
-    size_t early_amount, size_t early_count) const;
+    size_t early_amount, size_t early_count, MEMFLAGS flags) const;
   void print_virtual_memory_diff(size_t current_reserved, size_t current_committed,
     size_t early_reserved, size_t early_committed) const;
   void print_arena_diff(size_t current_amount, size_t current_count,
@@ -216,7 +216,7 @@
                                 const VirtualMemoryAllocationSite* current)  const;
 
   void diff_malloc_site(const NativeCallStack* stack, size_t current_size,
-    size_t currrent_count, size_t early_size, size_t early_count) const;
+    size_t currrent_count, size_t early_size, size_t early_count, MEMFLAGS flags) const;
   void diff_virtual_memory_site(const NativeCallStack* stack, size_t current_reserved,
     size_t current_committed, size_t early_reserved, size_t early_committed) const;
 };
diff --git a/src/share/vm/services/memTracker.hpp b/src/share/vm/services/memTracker.hpp
index 38a027e..7ad2b71 100644
--- a/src/share/vm/services/memTracker.hpp
+++ b/src/share/vm/services/memTracker.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -31,8 +31,8 @@
 
 #if !INCLUDE_NMT
 
-#define CURRENT_PC   NativeCallStack::EMPTY_STACK
-#define CALLER_PC    NativeCallStack::EMPTY_STACK
+#define CURRENT_PC   NativeCallStack::empty_stack()
+#define CALLER_PC    NativeCallStack::empty_stack()
 
 class Tracker : public StackObj {
  public:
@@ -83,9 +83,9 @@
 extern volatile bool NMT_stack_walkable;
 
 #define CURRENT_PC ((MemTracker::tracking_level() == NMT_detail && NMT_stack_walkable) ? \
-                    NativeCallStack(0, true) : NativeCallStack::EMPTY_STACK)
+                    NativeCallStack(0, true) : NativeCallStack::empty_stack())
 #define CALLER_PC  ((MemTracker::tracking_level() == NMT_detail && NMT_stack_walkable) ?  \
-                    NativeCallStack(1, true) : NativeCallStack::EMPTY_STACK)
+                    NativeCallStack(1, true) : NativeCallStack::empty_stack())
 
 class MemBaseline;
 class Mutex;
diff --git a/src/share/vm/services/memoryManager.cpp b/src/share/vm/services/memoryManager.cpp
index 0daa0a3..d3c41fe 100644
--- a/src/share/vm/services/memoryManager.cpp
+++ b/src/share/vm/services/memoryManager.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2013, 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
@@ -46,7 +46,7 @@
 
 MemoryManager::MemoryManager() {
   _num_pools = 0;
-  (void)const_cast<instanceOop&>(_memory_mgr_obj = NULL);
+  (void)const_cast<instanceOop&>(_memory_mgr_obj = instanceOop(NULL));
 }
 
 void MemoryManager::add_pool(MemoryPool* pool) {
diff --git a/src/share/vm/services/memoryPool.cpp b/src/share/vm/services/memoryPool.cpp
index 1510cd5..2d686cb 100644
--- a/src/share/vm/services/memoryPool.cpp
+++ b/src/share/vm/services/memoryPool.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2013, 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
@@ -46,7 +46,7 @@
   _name = name;
   _initial_size = init_size;
   _max_size = max_size;
-  (void)const_cast<instanceOop&>(_memory_pool_obj = NULL);
+  (void)const_cast<instanceOop&>(_memory_pool_obj = instanceOop(NULL));
   _available_for_allocation = true;
   _num_managers = 0;
   _type = type;
diff --git a/src/share/vm/services/threadService.cpp b/src/share/vm/services/threadService.cpp
index 02156a2..be5acfd 100644
--- a/src/share/vm/services/threadService.cpp
+++ b/src/share/vm/services/threadService.cpp
@@ -889,7 +889,7 @@
       st->print("  waiting to lock monitor " INTPTR_FORMAT, waitingToLockMonitor);
       oop obj = (oop)waitingToLockMonitor->object();
       if (obj != NULL) {
-        st->print(" (object "INTPTR_FORMAT ", a %s)", (address)obj,
+        st->print(" (object " INTPTR_FORMAT ", a %s)", (address)obj,
                    (InstanceKlass::cast(obj->klass()))->external_name());
 
         if (!currentThread->current_pending_monitor_is_from_java()) {
diff --git a/src/share/vm/services/virtualMemoryTracker.cpp b/src/share/vm/services/virtualMemoryTracker.cpp
index 37b9dc3..c914c1d 100644
--- a/src/share/vm/services/virtualMemoryTracker.cpp
+++ b/src/share/vm/services/virtualMemoryTracker.cpp
@@ -167,7 +167,7 @@
           // higher part
           address high_base = addr + sz;
           size_t  high_size = top - high_base;
-          CommittedMemoryRegion high_rgn(high_base, high_size, NativeCallStack::EMPTY_STACK);
+          CommittedMemoryRegion high_rgn(high_base, high_size, NativeCallStack::empty_stack());
           return add_committed_region(high_rgn);
         } else {
           return false;
diff --git a/src/share/vm/services/virtualMemoryTracker.hpp b/src/share/vm/services/virtualMemoryTracker.hpp
index d2f8abd..1be43b5 100644
--- a/src/share/vm/services/virtualMemoryTracker.hpp
+++ b/src/share/vm/services/virtualMemoryTracker.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -305,7 +305,7 @@
 
 
   ReservedMemoryRegion(address base, size_t size) :
-    VirtualMemoryRegion(base, size), _stack(NativeCallStack::EMPTY_STACK), _flag(mtNone),
+    VirtualMemoryRegion(base, size), _stack(NativeCallStack::empty_stack()), _flag(mtNone),
     _all_committed(false) { }
 
   // Copy constructor
diff --git a/src/share/vm/trace/traceEventClasses.xsl b/src/share/vm/trace/traceEventClasses.xsl
index 375274e..d3cdc60 100644
--- a/src/share/vm/trace/traceEventClasses.xsl
+++ b/src/share/vm/trace/traceEventClasses.xsl
@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="utf-8"?>
 <!--
- Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
+ Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved.
  DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 
  This code is free software; you can redistribute it and/or modify it
@@ -36,7 +36,6 @@
 // Some parts of traceEvent.hpp are used outside of
 // INCLUDE_TRACE
 
-#include "memory/resourceArea.hpp"
 #include "tracefiles/traceTypes.hpp"
 #include "trace/traceEvent.hpp"
 #include "utilities/macros.hpp"
@@ -135,7 +134,6 @@
 </xsl:text>
   <xsl:value-of select="concat('  Event', @id, '(EventStartTime timing=TIMED) : TraceEvent&lt;Event', @id, '&gt;(timing) {}', $newline)"/>
   void writeEvent(void) {
-    ResourceMark rm;
     if (UseLockedTracing) {
       ttyLocker lock;
       writeEventContent();
diff --git a/src/share/vm/trace/traceStream.hpp b/src/share/vm/trace/traceStream.hpp
index 89911ea..cefd969 100644
--- a/src/share/vm/trace/traceStream.hpp
+++ b/src/share/vm/trace/traceStream.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,7 @@
 
 #include "utilities/macros.hpp"
 #if INCLUDE_TRACE
+#include "memory/resourceArea.hpp"
 #include "oops/klass.hpp"
 #include "oops/method.hpp"
 #include "oops/symbol.hpp"
@@ -40,31 +41,31 @@
   TraceStream(outputStream& stream): _st(stream) {}
 
   void print_val(const char* label, u1 val) {
-    _st.print("%s = "UINT32_FORMAT, label, val);
+    _st.print("%s = " UINT32_FORMAT, label, val);
   }
 
   void print_val(const char* label, u2 val) {
-    _st.print("%s = "UINT32_FORMAT, label, val);
+    _st.print("%s = " UINT32_FORMAT, label, val);
   }
 
   void print_val(const char* label, s2 val) {
-    _st.print("%s = "INT32_FORMAT, label, val);
+    _st.print("%s = " INT32_FORMAT, label, val);
   }
 
   void print_val(const char* label, u4 val) {
-    _st.print("%s = "UINT32_FORMAT, label, val);
+    _st.print("%s = " UINT32_FORMAT, label, val);
   }
 
   void print_val(const char* label, s4 val) {
-    _st.print("%s = "INT32_FORMAT, label, val);
+    _st.print("%s = " INT32_FORMAT, label, val);
   }
 
   void print_val(const char* label, u8 val) {
-    _st.print("%s = "UINT64_FORMAT, label, val);
+    _st.print("%s = " UINT64_FORMAT, label, val);
   }
 
   void print_val(const char* label, s8 val) {
-    _st.print("%s = "INT64_FORMAT, label, (int64_t) val);
+    _st.print("%s = " INT64_FORMAT, label, (int64_t) val);
   }
 
   void print_val(const char* label, bool val) {
@@ -79,11 +80,8 @@
     _st.print("%s = %f", label, val);
   }
 
-  // Caller is machine generated code located in traceEventClasses.hpp
-  // Event<TraceId>::writeEvent() (pseudocode) contains the
-  // necessary ResourceMark for the resource allocations below.
-  // See traceEventClasses.xsl for details.
   void print_val(const char* label, const Klass* const val) {
+    ResourceMark rm;
     const char* description = "NULL";
     if (val != NULL) {
       Symbol* name = val->name();
@@ -94,11 +92,8 @@
     _st.print("%s = %s", label, description);
   }
 
-  // Caller is machine generated code located in traceEventClasses.hpp
-  // Event<TraceId>::writeEvent() (pseudocode) contains the
-  // necessary ResourceMark for the resource allocations below.
-  // See traceEventClasses.xsl for details.
   void print_val(const char* label, const Method* const val) {
+    ResourceMark rm;
     const char* description = "NULL";
     if (val != NULL) {
       description = val->name_and_sig_as_C_string();
diff --git a/src/share/vm/utilities/array.hpp b/src/share/vm/utilities/array.hpp
index b7ce8e7..920b875 100644
--- a/src/share/vm/utilities/array.hpp
+++ b/src/share/vm/utilities/array.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -322,7 +322,7 @@
   void* operator new(size_t size, ClassLoaderData* loader_data, int length, bool read_only, TRAPS) throw() {
     size_t word_size = Array::size(length);
     return (void*) Metaspace::allocate(loader_data, word_size, read_only,
-                                       MetaspaceObj::array_type(sizeof(T)), CHECK_NULL);
+                                       MetaspaceObj::array_type(sizeof(T)), THREAD);
   }
 
   static size_t byte_sizeof(int length) { return sizeof(Array<T>) + MAX2(length - 1, 0) * sizeof(T); }
diff --git a/src/share/vm/utilities/copy.cpp b/src/share/vm/utilities/copy.cpp
index 56e1cfc..0d64178 100644
--- a/src/share/vm/utilities/copy.cpp
+++ b/src/share/vm/utilities/copy.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2006, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -53,6 +53,175 @@
   }
 }
 
+class CopySwap : AllStatic {
+public:
+  /**
+   * Copy and byte swap elements
+   *
+   * @param src address of source
+   * @param dst address of destination
+   * @param byte_count number of bytes to copy
+   * @param elem_size size of the elements to copy-swap
+   */
+  static void conjoint_swap(address src, address dst, size_t byte_count, size_t elem_size) {
+    assert(src != NULL, "address must not be NULL");
+    assert(dst != NULL, "address must not be NULL");
+    assert(elem_size == 2 || elem_size == 4 || elem_size == 8,
+           err_msg("incorrect element size: " SIZE_FORMAT, elem_size));
+    assert(is_size_aligned(byte_count, elem_size),
+           err_msg("byte_count " SIZE_FORMAT " must be multiple of element size " SIZE_FORMAT, byte_count, elem_size));
+
+    address src_end = src + byte_count;
+
+    if (dst <= src || dst >= src_end) {
+      do_conjoint_swap<RIGHT>(src, dst, byte_count, elem_size);
+    } else {
+      do_conjoint_swap<LEFT>(src, dst, byte_count, elem_size);
+    }
+  }
+
+private:
+  /**
+   * Byte swap a 16-bit value
+   */
+  static uint16_t byte_swap(uint16_t x) {
+    return (x << 8) | (x >> 8);
+  }
+
+  /**
+   * Byte swap a 32-bit value
+   */
+  static uint32_t byte_swap(uint32_t x) {
+    uint16_t lo = (uint16_t)x;
+    uint16_t hi = (uint16_t)(x >> 16);
+
+    return ((uint32_t)byte_swap(lo) << 16) | (uint32_t)byte_swap(hi);
+  }
+
+  /**
+   * Byte swap a 64-bit value
+   */
+  static uint64_t byte_swap(uint64_t x) {
+    uint32_t lo = (uint32_t)x;
+    uint32_t hi = (uint32_t)(x >> 32);
+
+    return ((uint64_t)byte_swap(lo) << 32) | (uint64_t)byte_swap(hi);
+  }
+
+  enum CopyDirection {
+    RIGHT, // lower -> higher address
+    LEFT   // higher -> lower address
+  };
+
+  /**
+   * Copy and byte swap elements
+   *
+   * <T> - type of element to copy
+   * <D> - copy direction
+   * <is_src_aligned> - true if src argument is aligned to element size
+   * <is_dst_aligned> - true if dst argument is aligned to element size
+   *
+   * @param src address of source
+   * @param dst address of destination
+   * @param byte_count number of bytes to copy
+   */
+  template <typename T, CopyDirection D, bool is_src_aligned, bool is_dst_aligned>
+  static void do_conjoint_swap(address src, address dst, size_t byte_count) {
+    address cur_src, cur_dst;
+
+    switch (D) {
+    case RIGHT:
+      cur_src = src;
+      cur_dst = dst;
+      break;
+    case LEFT:
+      cur_src = src + byte_count - sizeof(T);
+      cur_dst = dst + byte_count - sizeof(T);
+      break;
+    }
+
+    for (size_t i = 0; i < byte_count / sizeof(T); i++) {
+      T tmp;
+
+      if (is_src_aligned) {
+        tmp = *(T*)cur_src;
+      } else {
+        memcpy(&tmp, cur_src, sizeof(T));
+      }
+
+      tmp = byte_swap(tmp);
+
+      if (is_dst_aligned) {
+        *(T*)cur_dst = tmp;
+      } else {
+        memcpy(cur_dst, &tmp, sizeof(T));
+      }
+
+      switch (D) {
+      case RIGHT:
+        cur_src += sizeof(T);
+        cur_dst += sizeof(T);
+        break;
+      case LEFT:
+        cur_src -= sizeof(T);
+        cur_dst -= sizeof(T);
+        break;
+      }
+    }
+  }
+
+  /**
+   * Copy and byte swap elements
+   *
+   * <T> - type of element to copy
+   * <D> - copy direction
+   *
+   * @param src address of source
+   * @param dst address of destination
+   * @param byte_count number of bytes to copy
+   */
+  template <typename T, CopyDirection direction>
+  static void do_conjoint_swap(address src, address dst, size_t byte_count) {
+    if (is_ptr_aligned(src, sizeof(T))) {
+      if (is_ptr_aligned(dst, sizeof(T))) {
+        do_conjoint_swap<T,direction,true,true>(src, dst, byte_count);
+      } else {
+        do_conjoint_swap<T,direction,true,false>(src, dst, byte_count);
+      }
+    } else {
+      if (is_ptr_aligned(dst, sizeof(T))) {
+        do_conjoint_swap<T,direction,false,true>(src, dst, byte_count);
+      } else {
+        do_conjoint_swap<T,direction,false,false>(src, dst, byte_count);
+      }
+    }
+  }
+
+
+  /**
+   * Copy and byte swap elements
+   *
+   * <D> - copy direction
+   *
+   * @param src address of source
+   * @param dst address of destination
+   * @param byte_count number of bytes to copy
+   * @param elem_size size of the elements to copy-swap
+   */
+  template <CopyDirection D>
+  static void do_conjoint_swap(address src, address dst, size_t byte_count, size_t elem_size) {
+    switch (elem_size) {
+    case 2: do_conjoint_swap<uint16_t,D>(src, dst, byte_count); break;
+    case 4: do_conjoint_swap<uint32_t,D>(src, dst, byte_count); break;
+    case 8: do_conjoint_swap<uint64_t,D>(src, dst, byte_count); break;
+    default: guarantee(false, err_msg("do_conjoint_swap: Invalid elem_size %zd\n", elem_size));
+    }
+  }
+};
+
+void Copy::conjoint_swap(address src, address dst, size_t byte_count, size_t elem_size) {
+  CopySwap::conjoint_swap(src, dst, byte_count, elem_size);
+}
 
 // Fill bytes; larger units are filled atomically if everything is aligned.
 void Copy::fill_to_memory_atomic(void* to, size_t size, jubyte value) {
diff --git a/src/share/vm/utilities/copy.hpp b/src/share/vm/utilities/copy.hpp
index 3dcbfee..66f9887 100644
--- a/src/share/vm/utilities/copy.hpp
+++ b/src/share/vm/utilities/copy.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -227,6 +227,16 @@
     }
   }
 
+  /**
+   * Copy and *unconditionally* byte swap elements
+   *
+   * @param src address of source
+   * @param dst address of destination
+   * @param byte_count number of bytes to copy
+   * @param elem_size size of the elements to copy-swap
+   */
+  static void conjoint_swap(address src, address dst, size_t byte_count, size_t elem_size);
+
   // Fill methods
 
   // Fill word-aligned words, not atomic on each word
diff --git a/src/share/vm/utilities/debug.cpp b/src/share/vm/utilities/debug.cpp
index 232f350..4f7cbdd 100644
--- a/src/share/vm/utilities/debug.cpp
+++ b/src/share/vm/utilities/debug.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -315,6 +315,14 @@
   }
 }
 
+void report_insufficient_metaspace(size_t required_size) {
+  warning("\nThe MaxMetaspaceSize of " SIZE_FORMAT " bytes is not large enough.\n"
+          "Either don't specify the -XX:MaxMetaspaceSize=<size>\n"
+          "or increase the size to at least " SIZE_FORMAT ".\n",
+          MaxMetaspaceSize, required_size);
+  exit(2);
+}
+
 static bool error_reported = false;
 
 // call this when the VM is dying--it might loosen some asserts
diff --git a/src/share/vm/utilities/debug.hpp b/src/share/vm/utilities/debug.hpp
index 5b47e61..86fc6b1 100644
--- a/src/share/vm/utilities/debug.hpp
+++ b/src/share/vm/utilities/debug.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -222,6 +222,7 @@
 void report_should_not_reach_here(const char* file, int line);
 void report_unimplemented(const char* file, int line);
 void report_untested(const char* file, int line, const char* message);
+void report_insufficient_metaspace(size_t required_size);
 
 void warning(const char* format, ...) ATTRIBUTE_PRINTF(1, 2);
 
diff --git a/src/share/vm/utilities/exceptions.cpp b/src/share/vm/utilities/exceptions.cpp
index 5295c9b..db4a170 100644
--- a/src/share/vm/utilities/exceptions.cpp
+++ b/src/share/vm/utilities/exceptions.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -30,6 +30,7 @@
 #include "runtime/init.hpp"
 #include "runtime/java.hpp"
 #include "runtime/javaCalls.hpp"
+#include "runtime/os.hpp"
 #include "runtime/thread.inline.hpp"
 #include "runtime/threadCritical.hpp"
 #include "utilities/events.hpp"
@@ -154,6 +155,10 @@
     return;
   }
 
+  if (h_exception->is_a(SystemDictionary::OutOfMemoryError_klass())) {
+    count_out_of_memory_exceptions(h_exception);
+  }
+
   assert(h_exception->is_a(SystemDictionary::Throwable_klass()), "exception is not a subclass of java/lang/Throwable");
 
   // set the pending exception
@@ -228,6 +233,8 @@
     if (StackTraceInThrowable) {
       java_lang_Throwable::fill_in_stack_trace(exception, method());
     }
+    // Increment counter for hs_err file reporting
+    Atomic::inc(&Exceptions::_stack_overflow_errors);
   } else {
     // if prior exception, throw that one instead
     exception = Handle(THREAD, THREAD->pending_exception());
@@ -240,8 +247,7 @@
   va_list ap;
   va_start(ap, format);
   char msg[max_msg_size];
-  vsnprintf(msg, max_msg_size, format, ap);
-  msg[max_msg_size-1] = '\0';
+  os::vsnprintf(msg, max_msg_size, format, ap);
   va_end(ap);
   _throw_msg(thread, file, line, h_name, msg);
 }
@@ -404,6 +410,44 @@
                                    h_prot, to_utf8_safe);
 }
 
+
+// Exception counting for hs_err file
+volatile int Exceptions::_stack_overflow_errors = 0;
+volatile int Exceptions::_out_of_memory_error_java_heap_errors = 0;
+volatile int Exceptions::_out_of_memory_error_metaspace_errors = 0;
+volatile int Exceptions::_out_of_memory_error_class_metaspace_errors = 0;
+
+void Exceptions::count_out_of_memory_exceptions(Handle exception) {
+  if (exception() == Universe::out_of_memory_error_metaspace()) {
+     Atomic::inc(&_out_of_memory_error_metaspace_errors);
+  } else if (exception() == Universe::out_of_memory_error_class_metaspace()) {
+     Atomic::inc(&_out_of_memory_error_class_metaspace_errors);
+  } else {
+     // everything else reported as java heap OOM
+     Atomic::inc(&_out_of_memory_error_java_heap_errors);
+  }
+}
+
+void print_oom_count(outputStream* st, const char *err, int count) {
+  if (count > 0) {
+    st->print_cr("OutOfMemoryError %s=%d", err, count);
+  }
+}
+
+bool Exceptions::has_exception_counts() {
+  return (_stack_overflow_errors + _out_of_memory_error_java_heap_errors +
+         _out_of_memory_error_metaspace_errors + _out_of_memory_error_class_metaspace_errors) > 0;
+}
+
+void Exceptions::print_exception_counts_on_error(outputStream* st) {
+  print_oom_count(st, "java_heap_errors", _out_of_memory_error_java_heap_errors);
+  print_oom_count(st, "metaspace_errors", _out_of_memory_error_metaspace_errors);
+  print_oom_count(st, "class_metaspace_errors", _out_of_memory_error_class_metaspace_errors);
+  if (_stack_overflow_errors > 0) {
+    st->print_cr("StackOverflowErrors=%d", _stack_overflow_errors);
+  }
+}
+
 // Implementation of ExceptionMark
 
 ExceptionMark::ExceptionMark(Thread*& thread) {
diff --git a/src/share/vm/utilities/exceptions.hpp b/src/share/vm/utilities/exceptions.hpp
index 3dfe338..7e10f73 100644
--- a/src/share/vm/utilities/exceptions.hpp
+++ b/src/share/vm/utilities/exceptions.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -102,6 +102,11 @@
 class Exceptions {
   static bool special_exception(Thread *thread, const char* file, int line, Handle exception);
   static bool special_exception(Thread* thread, const char* file, int line, Symbol* name, const char* message);
+
+  // Count out of memory errors that are interesting in error diagnosis
+  static volatile int _out_of_memory_error_java_heap_errors;
+  static volatile int _out_of_memory_error_metaspace_errors;
+  static volatile int _out_of_memory_error_class_metaspace_errors;
  public:
   // this enum is defined to indicate whether it is safe to
   // ignore the encoding scheme of the original message string.
@@ -160,6 +165,14 @@
 
   static void throw_stack_overflow_exception(Thread* thread, const char* file, int line, methodHandle method);
 
+  // Exception counting for error files of interesting exceptions that may have
+  // caused a problem for the jvm
+  static volatile int _stack_overflow_errors;
+
+  static bool has_exception_counts();
+  static void count_out_of_memory_exceptions(Handle exception);
+  static void print_exception_counts_on_error(outputStream* st);
+
   // for AbortVMOnException flag
   NOT_PRODUCT(static void debug_check_abort(Handle exception, const char* message = NULL);)
   NOT_PRODUCT(static void debug_check_abort(const char *value_string, const char* message = NULL);)
@@ -188,7 +201,7 @@
 //
 // CAUTION: make sure that the function call using a CHECK macro is not the only statement of a
 // conditional branch w/o enclosing {} braces, since the CHECK macros expand into several state-
-// ments!
+// ments! Also make sure it is not used on a function call that is part of a return statement!
 
 #define PENDING_EXCEPTION                        (((ThreadShadow*)THREAD)->pending_exception())
 #define HAS_PENDING_EXCEPTION                    (((ThreadShadow*)THREAD)->has_pending_exception())
diff --git a/src/share/vm/utilities/globalDefinitions.hpp b/src/share/vm/utilities/globalDefinitions.hpp
index 58efd16..2fb6a3c 100644
--- a/src/share/vm/utilities/globalDefinitions.hpp
+++ b/src/share/vm/utilities/globalDefinitions.hpp
@@ -1038,8 +1038,8 @@
 // Special constants for debugging
 
 const jint     badInt           = -3;                       // generic "bad int" value
-const long     badAddressVal    = -2;                       // generic "bad address" value
-const long     badOopVal        = -1;                       // generic "bad oop" value
+const intptr_t badAddressVal    = -2;                       // generic "bad address" value
+const intptr_t badOopVal        = -1;                       // generic "bad oop" value
 const intptr_t badHeapOopVal    = (intptr_t) CONST64(0x2BAD4B0BBAADBABE); // value used to zap heap after GC
 const int      badHandleValue   = 0xBC;                     // value used to zap vm handle area
 const int      badResourceValue = 0xAB;                     // value used to zap resource area
diff --git a/src/share/vm/utilities/globalDefinitions_visCPP.hpp b/src/share/vm/utilities/globalDefinitions_visCPP.hpp
index 46e8f9e..21adbdf 100644
--- a/src/share/vm/utilities/globalDefinitions_visCPP.hpp
+++ b/src/share/vm/utilities/globalDefinitions_visCPP.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -187,14 +187,6 @@
 #pragma warning( disable : 4996 ) // unsafe string functions. Same as define _CRT_SECURE_NO_WARNINGS/_CRT_SECURE_NO_DEPRICATE
 #endif
 
-inline int vsnprintf(char* buf, size_t count, const char* fmt, va_list argptr) {
-  // If number of characters written == count, Windows doesn't write a
-  // terminating NULL, so we do it ourselves.
-  int ret = _vsnprintf(buf, count, fmt, argptr);
-  if (count > 0) buf[count-1] = '\0';
-  return ret;
-}
-
 // Portability macros
 #define PRAGMA_INTERFACE
 #define PRAGMA_IMPLEMENTATION
diff --git a/src/share/vm/utilities/nativeCallStack.cpp b/src/share/vm/utilities/nativeCallStack.cpp
index aa3a1e6..ee6eb31 100644
--- a/src/share/vm/utilities/nativeCallStack.cpp
+++ b/src/share/vm/utilities/nativeCallStack.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,7 +27,7 @@
 #include "utilities/globalDefinitions.hpp"
 #include "utilities/nativeCallStack.hpp"
 
-const NativeCallStack NativeCallStack::EMPTY_STACK(0, false);
+NativeCallStack NativeCallStack::EMPTY_STACK(0, false);
 
 NativeCallStack::NativeCallStack(int toSkip, bool fillStack) :
   _hash_value(0) {
@@ -55,6 +55,7 @@
   for (; index < NMT_TrackingStackDepth; index ++) {
     _stack[index] = NULL;
   }
+  _hash_value = 0;
 }
 
 // number of stack frames captured
@@ -69,19 +70,16 @@
 }
 
 // Hash code. Any better algorithm?
-int NativeCallStack::hash() const {
-  long hash_val = _hash_value;
+unsigned int NativeCallStack::hash() const {
+  uintptr_t hash_val = _hash_value;
   if (hash_val == 0) {
-    long pc;
-    int  index;
-    for (index = 0; index < NMT_TrackingStackDepth; index ++) {
-      pc = (long)_stack[index];
-      if (pc == 0) break;
-      hash_val += pc;
+    for (int index = 0; index < NMT_TrackingStackDepth; index++) {
+      if (_stack[index] == NULL) break;
+      hash_val += (uintptr_t)_stack[index];
     }
 
     NativeCallStack* p = const_cast<NativeCallStack*>(this);
-    p->_hash_value = (int)(hash_val & 0xFFFFFFFF);
+    p->_hash_value = (unsigned int)(hash_val & 0xFFFFFFFF);
   }
   return _hash_value;
 }
@@ -116,4 +114,3 @@
     }
   }
 }
-
diff --git a/src/share/vm/utilities/nativeCallStack.hpp b/src/share/vm/utilities/nativeCallStack.hpp
index b6d6a35..cb58f94 100644
--- a/src/share/vm/utilities/nativeCallStack.hpp
+++ b/src/share/vm/utilities/nativeCallStack.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -51,18 +51,23 @@
  * 2. The class is strict stack object, no heap or virtual memory can be allocated
  *    from it.
  */
+class MemTracker;
+
 class NativeCallStack : public StackObj {
- public:
-  static const NativeCallStack EMPTY_STACK;
+  friend class MemTracker;
 
- private:
-  address   _stack[NMT_TrackingStackDepth];
-  int       _hash_value;
+private:
+  address       _stack[NMT_TrackingStackDepth];
+  unsigned int  _hash_value;
 
- public:
+  static NativeCallStack EMPTY_STACK;
+public:
   NativeCallStack(int toSkip = 0, bool fillStack = false);
   NativeCallStack(address* pc, int frameCount);
 
+  static inline const NativeCallStack& empty_stack() {
+    return EMPTY_STACK;
+  }
 
   // if it is an empty stack
   inline bool is_empty() const {
@@ -89,7 +94,7 @@
   }
 
   // Hash code. Any better algorithm?
-  int hash() const;
+  unsigned int hash() const;
 
   void print_on(outputStream* out) const;
   void print_on(outputStream* out, int indent) const;
diff --git a/src/share/vm/utilities/ostream.cpp b/src/share/vm/utilities/ostream.cpp
index 21bdd69..1b00f82 100644
--- a/src/share/vm/utilities/ostream.cpp
+++ b/src/share/vm/utilities/ostream.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,7 @@
 #include "gc_implementation/shared/gcId.hpp"
 #include "oops/oop.inline.hpp"
 #include "runtime/arguments.hpp"
+#include "runtime/os.hpp"
 #include "utilities/defaultStream.hpp"
 #include "utilities/ostream.hpp"
 #include "utilities/top.hpp"
@@ -89,6 +90,8 @@
                                        const char* format, va_list ap,
                                        bool add_cr,
                                        size_t& result_len) {
+  assert(buflen >= 2, "buffer too small");
+
   const char* result;
   if (add_cr)  buflen--;
   if (!strchr(format, '%')) {
@@ -101,18 +104,20 @@
     result = va_arg(ap, const char*);
     result_len = strlen(result);
     if (add_cr && result_len >= buflen)  result_len = buflen-1;  // truncate
-  } else if (vsnprintf(buffer, buflen, format, ap) >= 0) {
-    result = buffer;
-    result_len = strlen(result);
   } else {
-    DEBUG_ONLY(warning("increase O_BUFLEN in ostream.hpp -- output truncated");)
+    int written = os::vsnprintf(buffer, buflen, format, ap);
+    assert(written >= 0, "vsnprintf encoding error");
     result = buffer;
-    result_len = buflen - 1;
-    buffer[result_len] = 0;
+    if ((size_t)written < buflen) {
+      result_len = written;
+    } else {
+      DEBUG_ONLY(warning("increase O_BUFLEN in ostream.hpp -- output truncated");)
+      result_len = buflen - 1;
+    }
   }
   if (add_cr) {
     if (result != buffer) {
-      strncpy(buffer, result, buflen);
+      memcpy(buffer, result, result_len);
       result = buffer;
     }
     buffer[result_len++] = '\n';
@@ -277,7 +282,7 @@
   size_t limit = (len + 16) / 16 * 16;
   for (size_t i = 0; i < limit; ++i) {
     if (i % 16 == 0) {
-      indent().print(SIZE_FORMAT_HEX_W(07)":", i);
+      indent().print(SIZE_FORMAT_HEX_W(07) ":", i);
     }
     if (i % 2 == 0) {
       print(" ");
@@ -578,6 +583,117 @@
     assert(o_result == NULL, err_msg("Too long file name after pid expansion should return NULL, but got '%s'", o_result));
   }
 }
+
+//////////////////////////////////////////////////////////////////////////////
+// Test os::vsnprintf and friends.
+
+void check_snprintf_result(int expected, size_t limit, int actual, bool expect_count) {
+  if (expect_count || ((size_t)expected < limit)) {
+    assert(expected == actual, "snprintf result not expected value");
+  } else {
+    // Make this check more permissive for jdk8u, don't assert that actual == 0.
+    // e.g. jio_vsnprintf_wrapper and jio_snprintf return -1 when expected >= limit
+    if (expected >= (int) limit) {
+      assert(actual == -1, "snprintf result should be -1 for expected >= limit");
+    } else {
+      assert(actual > 0, "snprintf result should be >0 for expected < limit");
+    }
+  }
+}
+
+// PrintFn is expected to be int (*)(char*, size_t, const char*, ...).
+// But jio_snprintf is a C-linkage function with that signature, which
+// has a different type on some platforms (like Solaris).
+template<typename PrintFn>
+void test_snprintf(PrintFn pf, bool expect_count) {
+  const char expected[] = "abcdefghijklmnopqrstuvwxyz";
+  const int expected_len = sizeof(expected) - 1;
+  const size_t padding_size = 10;
+  char buffer[2 * (sizeof(expected) + padding_size)];
+  char check_buffer[sizeof(buffer)];
+  const char check_char = '1';  // Something not in expected.
+  memset(check_buffer, check_char, sizeof(check_buffer));
+  const size_t sizes_to_test[] = {
+    sizeof(buffer) - padding_size,       // Fits, with plenty of space to spare.
+    sizeof(buffer)/2,                    // Fits, with space to spare.
+    sizeof(buffer)/4,                    // Doesn't fit.
+    sizeof(expected) + padding_size + 1, // Fits, with a little room to spare
+    sizeof(expected) + padding_size,     // Fits exactly.
+    sizeof(expected) + padding_size - 1, // Doesn't quite fit.
+    2,                                   // One char + terminating NUL.
+    1,                                   // Only space for terminating NUL.
+    0 };                                 // No space at all.
+  for (unsigned i = 0; i < ARRAY_SIZE(sizes_to_test); ++i) {
+    memset(buffer, check_char, sizeof(buffer)); // To catch stray writes.
+    size_t test_size = sizes_to_test[i];
+    ResourceMark rm;
+    stringStream s;
+    s.print("test_size: " SIZE_FORMAT, test_size);
+    size_t prefix_size = padding_size;
+    guarantee(test_size <= (sizeof(buffer) - prefix_size), "invariant");
+    size_t write_size = MIN2(sizeof(expected), test_size);
+    size_t suffix_size = sizeof(buffer) - prefix_size - write_size;
+    char* write_start = buffer + prefix_size;
+    char* write_end = write_start + write_size;
+
+    int result = pf(write_start, test_size, "%s", expected);
+
+    check_snprintf_result(expected_len, test_size, result, expect_count);
+
+    // Verify expected output.
+    if (test_size > 0) {
+      assert(0 == strncmp(write_start, expected, write_size - 1), "strncmp failure");
+      // Verify terminating NUL of output.
+      assert('\0' == write_start[write_size - 1], "null terminator failure");
+    } else {
+      guarantee(test_size == 0, "invariant");
+      guarantee(write_size == 0, "invariant");
+      guarantee(prefix_size + suffix_size == sizeof(buffer), "invariant");
+      guarantee(write_start == write_end, "invariant");
+    }
+
+    // Verify no scribbling on prefix or suffix.
+    assert(0 == strncmp(buffer, check_buffer, prefix_size), "prefix scribble");
+    assert(0 == strncmp(write_end, check_buffer, suffix_size), "suffix scribble");
+  }
+
+  // Special case of 0-length buffer with empty (except for terminator) output.
+  check_snprintf_result(0, 0, pf(NULL, 0, "%s", ""), expect_count);
+  check_snprintf_result(0, 0, pf(NULL, 0, ""), expect_count);
+}
+
+// This is probably equivalent to os::snprintf, but we're being
+// explicit about what we're testing here.
+static int vsnprintf_wrapper(char* buf, size_t len, const char* fmt, ...) {
+  va_list args;
+  va_start(args, fmt);
+  int result = os::vsnprintf(buf, len, fmt, args);
+  va_end(args);
+  return result;
+}
+
+// These are declared in jvm.h; test here, with related functions.
+extern "C" {
+int jio_vsnprintf(char*, size_t, const char*, va_list);
+int jio_snprintf(char*, size_t, const char*, ...);
+}
+
+// This is probably equivalent to jio_snprintf, but we're being
+// explicit about what we're testing here.
+static int jio_vsnprintf_wrapper(char* buf, size_t len, const char* fmt, ...) {
+  va_list args;
+  va_start(args, fmt);
+  int result = jio_vsnprintf(buf, len, fmt, args);
+  va_end(args);
+  return result;
+}
+
+void test_snprintf() {
+  test_snprintf(vsnprintf_wrapper, true);
+  test_snprintf(os::snprintf, true);
+  test_snprintf(jio_vsnprintf_wrapper, false); // jio_vsnprintf returns -1 on error including exceeding buffer size
+  test_snprintf(jio_snprintf, false);          // jio_snprintf calls jio_vsnprintf
+}
 #endif // PRODUCT
 
 fileStream::fileStream(const char* file_name) {
@@ -945,7 +1061,7 @@
     // %%% Should be: jlong time_ms = os::start_time_milliseconds(), if
     // we ever get round to introduce that method on the os class
     xs->head("hotspot_log version='%d %d'"
-             " process='%d' time_ms='"INT64_FORMAT"'",
+             " process='%d' time_ms='" INT64_FORMAT "'",
              LOG_MAJOR_VERSION, LOG_MINOR_VERSION,
              os::current_process_id(), (int64_t)time_ms);
     // Write VM version header immediately.
diff --git a/src/share/vm/utilities/ostream.hpp b/src/share/vm/utilities/ostream.hpp
index 3569619..b4e7378 100644
--- a/src/share/vm/utilities/ostream.hpp
+++ b/src/share/vm/utilities/ostream.hpp
@@ -258,6 +258,7 @@
 #ifndef PRODUCT
 // unit test for checking -Xloggc:<filename> parsing result
 void test_loggc_filename();
+void test_snprintf();
 #endif
 
 void ostream_init();
diff --git a/src/share/vm/utilities/stack.hpp b/src/share/vm/utilities/stack.hpp
index 4814bf9..7c86689 100644
--- a/src/share/vm/utilities/stack.hpp
+++ b/src/share/vm/utilities/stack.hpp
@@ -96,11 +96,16 @@
 public:
   friend class StackIterator<E, F>;
 
+  // Number of elements that fit in 4K bytes minus the size of two pointers
+  // (link field and malloc header).
+  static const size_t _default_segment_size =  (4096 - 2 * sizeof(E*)) / sizeof(E);
+  static size_t default_segment_size() { return _default_segment_size; }
+
   // segment_size:    number of items per segment
   // max_cache_size:  maxmium number of *segments* to cache
   // max_size:        maximum number of items allowed, rounded to a multiple of
   //                  the segment size (0 == unlimited)
-  inline Stack(size_t segment_size = default_segment_size(),
+  inline Stack(size_t segment_size = _default_segment_size,
                size_t max_cache_size = 4, size_t max_size = 0);
   inline ~Stack() { clear(true); }
 
@@ -122,8 +127,6 @@
   // clear_cache is true, also release any cached segments.
   void clear(bool clear_cache = false);
 
-  static inline size_t default_segment_size();
-
 protected:
   // Each segment includes space for _seg_size elements followed by a link
   // (pointer) to the previous segment; the space is allocated as a single block
diff --git a/src/share/vm/utilities/stack.inline.hpp b/src/share/vm/utilities/stack.inline.hpp
index 7fe7d1d..4b1efee 100644
--- a/src/share/vm/utilities/stack.inline.hpp
+++ b/src/share/vm/utilities/stack.inline.hpp
@@ -86,14 +86,6 @@
 }
 
 template <class E, MEMFLAGS F>
-size_t Stack<E, F>::default_segment_size()
-{
-  // Number of elements that fit in 4K bytes minus the size of two pointers
-  // (link field and malloc header).
-  return (4096 - 2 * sizeof(E*)) / sizeof(E);
-}
-
-template <class E, MEMFLAGS F>
 size_t Stack<E, F>::adjust_segment_size(size_t seg_size)
 {
   const size_t elem_sz = sizeof(E);
diff --git a/src/share/vm/utilities/vmError.cpp b/src/share/vm/utilities/vmError.cpp
index 01774cb..5b4225b 100644
--- a/src/share/vm/utilities/vmError.cpp
+++ b/src/share/vm/utilities/vmError.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -304,6 +304,47 @@
 #endif // ZERO
 }
 
+static void print_oom_reasons(outputStream* st) {
+  st->print_cr("# Possible reasons:");
+  st->print_cr("#   The system is out of physical RAM or swap space");
+  if (UseCompressedOops) {
+    st->print_cr("#   The process is running with CompressedOops enabled, and the Java Heap may be blocking the growth of the native heap");
+  }
+  if (LogBytesPerWord == 2) {
+    st->print_cr("#   In 32 bit mode, the process size limit was hit");
+  }
+  st->print_cr("# Possible solutions:");
+  st->print_cr("#   Reduce memory load on the system");
+  st->print_cr("#   Increase physical memory or swap space");
+  st->print_cr("#   Check if swap backing store is full");
+  if (LogBytesPerWord == 2) {
+    st->print_cr("#   Use 64 bit Java on a 64 bit OS");
+  }
+  st->print_cr("#   Decrease Java heap size (-Xmx/-Xms)");
+  st->print_cr("#   Decrease number of Java threads");
+  st->print_cr("#   Decrease Java thread stack sizes (-Xss)");
+  st->print_cr("#   Set larger code cache with -XX:ReservedCodeCacheSize=");
+  if (UseCompressedOops) {
+    switch (Universe::narrow_oop_mode()) {
+      case Universe::UnscaledNarrowOop:
+        st->print_cr("#   JVM is running with Unscaled Compressed Oops mode in which the Java heap is");
+        st->print_cr("#     placed in the first 4GB address space. The Java Heap base address is the");
+        st->print_cr("#     maximum limit for the native heap growth. Please use -XX:HeapBaseMinAddress");
+        st->print_cr("#     to set the Java Heap base and to place the Java Heap above 4GB virtual address.");
+        break;
+      case Universe::ZeroBasedNarrowOop:
+        st->print_cr("#   JVM is running with Zero Based Compressed Oops mode in which the Java heap is");
+        st->print_cr("#     placed in the first 32GB address space. The Java Heap base address is the");
+        st->print_cr("#     maximum limit for the native heap growth. Please use -XX:HeapBaseMinAddress");
+        st->print_cr("#     to set the Java Heap base and to place the Java Heap above 32GB virtual address.");
+        break;
+      default:
+        break;
+    }
+  }
+  st->print_cr("# This output file may be truncated or incomplete.");
+}
+
 // This is the main function to report a fatal error. Only one thread can
 // call this function, so we don't need to worry about MT-safety. But it's
 // possible that the error handler itself may crash or die on an internal
@@ -375,19 +416,7 @@
          }
          // In error file give some solutions
          if (_verbose) {
-           st->print_cr("# Possible reasons:");
-           st->print_cr("#   The system is out of physical RAM or swap space");
-           st->print_cr("#   In 32 bit mode, the process size limit was hit");
-           st->print_cr("# Possible solutions:");
-           st->print_cr("#   Reduce memory load on the system");
-           st->print_cr("#   Increase physical memory or swap space");
-           st->print_cr("#   Check if swap backing store is full");
-           st->print_cr("#   Use 64 bit Java on a 64 bit OS");
-           st->print_cr("#   Decrease Java heap size (-Xmx/-Xms)");
-           st->print_cr("#   Decrease number of Java threads");
-           st->print_cr("#   Decrease Java thread stack sizes (-Xss)");
-           st->print_cr("#   Set larger code cache with -XX:ReservedCodeCacheSize=");
-           st->print_cr("# This output file may be truncated or incomplete.");
+           print_oom_reasons(st);
          } else {
            return;  // that's enough for the screen
          }
@@ -675,6 +704,24 @@
        st->cr();
      }
 
+  STEP(182, "(printing number of OutOfMemoryError and StackOverflow exceptions)")
+
+     if (_verbose && Exceptions::has_exception_counts()) {
+       st->print_cr("OutOfMemory and StackOverflow Exception counts:");
+       Exceptions::print_exception_counts_on_error(st);
+       st->cr();
+     }
+
+  STEP(185, "(printing compressed oops mode")
+
+     if (_verbose && UseCompressedOops) {
+       Universe::print_compressed_oops_mode(st);
+       if (UseCompressedClassPointers) {
+         Metaspace::print_compressed_class_space(st);
+       }
+       st->cr();
+     }
+
   STEP(190, "(printing heap information)" )
 
      if (_verbose && Universe::is_fully_initialized()) {
@@ -780,7 +827,7 @@
   STEP(280, "(printing date and time)" )
 
      if (_verbose) {
-       os::print_date_and_time(st);
+       os::print_date_and_time(st, buf, sizeof(buf));
        st->cr();
      }
 
diff --git a/test/TEST.groups b/test/TEST.groups
index f2209c8..4075036 100644
--- a/test/TEST.groups
+++ b/test/TEST.groups
@@ -96,6 +96,7 @@
   runtime/XCheckJniJsig/XCheckJSig.java \
   serviceability/attach/AttachWithStalePidFile.java \
   serviceability/sa/jmap-hprof/JMapHProfLargeHeapTest.java \
+  serviceability/dcmd/DynLibDcmdTest.java \
   testlibrary_tests/
 
 
diff --git a/test/compiler/6857159/Test6857159.java b/test/compiler/6857159/Test6857159.java
index 58efa37..4e813ce 100644
--- a/test/compiler/6857159/Test6857159.java
+++ b/test/compiler/6857159/Test6857159.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,15 +26,24 @@
  * @test
  * @bug 6857159
  * @summary local schedule failed with checkcast of Thread.currentThread()
- *
- * @run shell Test6857159.sh
+ * @library /testlibrary
  */
 
-public class Test6857159 extends Thread {
-    static class ct0 extends Test6857159 {
-        public void message() {
-            // System.out.println("message");
-        }
+import com.oracle.java.testlibrary.*;
+
+public class Test6857159 {
+    public static void main(String[] args) throws Throwable {
+        OutputAnalyzer analyzer = ProcessTools.executeTestJvm("-Xbatch",
+                "-XX:+PrintCompilation", "-XX:CompileOnly=Test$ct.run", "Test");
+        analyzer.shouldNotContain("COMPILE SKIPPED");
+        analyzer.shouldContain("Test$ct0::run (16 bytes)");
+        analyzer.shouldHaveExitValue(0);
+    }
+}
+
+class Test extends Thread {
+    static class ct0 extends Test {
+        public void message() { }
 
         public void run() {
              message();
@@ -43,14 +52,10 @@
         }
     }
     static class ct1 extends ct0 {
-        public void message() {
-            // System.out.println("message");
-        }
+        public void message() { }
     }
     static class ct2 extends ct0 {
-        public void message() {
-            // System.out.println("message");
-        }
+        public void message() { }
     }
 
     public static void main(String[] args) throws Exception {
diff --git a/test/compiler/6857159/Test6857159.sh b/test/compiler/6857159/Test6857159.sh
deleted file mode 100644
index e0430c4..0000000
--- a/test/compiler/6857159/Test6857159.sh
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/bin/sh
-# 
-# Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-# 
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-# 
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-# 
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-# 
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-# 
-# 
-## some tests require path to find test source dir
-if [ "${TESTSRC}" = "" ]
-then
-  TESTSRC=${PWD}
-  echo "TESTSRC not set.  Using "${TESTSRC}" as default"
-fi
-echo "TESTSRC=${TESTSRC}"
-## Adding common setup Variables for running shell tests.
-. ${TESTSRC}/../../test_env.sh
-
-set -x
-
-cp ${TESTSRC}/Test6857159.java .
-cp ${TESTSRC}/Test6857159.sh .
-
-${COMPILEJAVA}/bin/javac ${TESTJAVACOPTS} -d . Test6857159.java
-
-${TESTJAVA}/bin/java  ${TESTVMOPTS} -Xbatch -XX:+PrintCompilation -XX:CompileOnly=Test6857159\$ct.run Test6857159 > test.out 2>&1
-
-grep "COMPILE SKIPPED" test.out
-
-result=$?
-if [ $result -eq 1 ]
-then
-  echo "Passed"
-  exit 0
-else
-  echo "Failed"
-  exit 1
-fi
diff --git a/test/compiler/c2/SubsumingLoadsCauseFlagSpill.java b/test/compiler/c2/SubsumingLoadsCauseFlagSpill.java
new file mode 100644
index 0000000..9167549
--- /dev/null
+++ b/test/compiler/c2/SubsumingLoadsCauseFlagSpill.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2018, Red Hat, Inc. 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 8209639
+ * @summary assert failure in coalesce.cpp: attempted to spill a non-spillable item
+ *
+ * @run main/othervm -XX:-BackgroundCompilation -XX:CompileCommand=dontinline,SubsumingLoadsCauseFlagSpill::not_inlined -Xmx1024m SubsumingLoadsCauseFlagSpill
+ *
+ */
+
+public class SubsumingLoadsCauseFlagSpill {
+    private static Object field;
+    private static boolean do_throw;
+    private static volatile boolean barrier;
+
+    public static void main(String[] args) {
+        for (int i = 0; i < 20_000; i++) {
+            do_throw = true;
+            field = null;
+            test(0);
+            do_throw = false;
+            field = new Object();
+            test(0);
+        }
+    }
+
+    private static float test(float f) {
+        Object v = null;
+        try {
+            not_inlined();
+            v = field;
+        } catch (MyException me) {
+            v = field;
+            barrier = true;
+        }
+        if (v == null) {
+            return f * f;
+        }
+        return f;
+    }
+
+    private static void not_inlined() throws MyException{
+        if (do_throw) {
+            throw new MyException();
+        }
+    }
+
+    private static class MyException extends Throwable {
+    }
+}
diff --git a/test/compiler/gcbarriers/PreserveFPRegistersTest.java b/test/compiler/gcbarriers/PreserveFPRegistersTest.java
new file mode 100644
index 0000000..5ac6a94
--- /dev/null
+++ b/test/compiler/gcbarriers/PreserveFPRegistersTest.java
@@ -0,0 +1,120 @@
+/*
+ * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * 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 8148175
+ * @requires vm.gc=="G1" | vm.gc=="null"
+ * @library /testlibrary /testlibrary/whitebox
+ * @run main/bootclasspath/othervm -Xbatch -XX:+UnlockDiagnosticVMOptions
+ *      -XX:+WhiteBoxAPI -Xmx300m -XX:+UseG1GC PreserveFPRegistersTest
+ */
+
+import sun.hotspot.WhiteBox;
+
+public class PreserveFPRegistersTest {
+
+    public static void main(String... args) throws InterruptedException {
+        new PreserveFPRegistersTest().go();
+    }
+
+    private static WhiteBox wb = WhiteBox.getWhiteBox();
+
+    public final Object[][] storage;
+
+    /**
+     * Number of objects per region.
+     */
+    public final int K = 10;
+
+    /**
+     * Length of object array: sizeOf(Object[N]) ~= regionSize / K .
+     */
+    public final int N;
+
+    /**
+     * How many regions involved into testing.
+     */
+    public final int regionCount;
+
+    PreserveFPRegistersTest() {
+        long regionSize = wb.g1RegionSize();
+        Runtime rt = Runtime.getRuntime();
+        long used = rt.totalMemory() - rt.freeMemory();
+        long totalFree = rt.maxMemory() - used;
+        regionCount = (int) ( (totalFree / regionSize) * 0.9);
+        int refSize = wb.getHeapOopSize();
+        N = (int) ((regionSize / K ) / refSize) - 5;
+
+        System.out.println("%% Memory");
+        System.out.println("%%   used          :        " + used / 1024 + "M");
+        System.out.println("%%   available     :        " + totalFree / 1024 + "M");
+        System.out.println("%%   G1 Region Size:        " + regionSize / 1024 + "M");
+        System.out.println("%%   region count  :        " + regionCount);
+
+        System.out.println("%% Objects storage");
+        System.out.println("%%   N (array length)      : " + N);
+        System.out.println("%%   K (objects in regions): " + K);
+        System.out.println("%%   Reference size        : " + refSize);
+
+        try {
+            storage = new Object[regionCount * K][];
+            for (int i = 0; i < storage.length; i++) {
+                storage[i] = new Object[N];
+            }
+        } catch(OutOfMemoryError e) {
+            throw new AssertionError("Test Failed with unexpected OutOfMemoryError exception");
+        }
+    }
+
+    public void go() throws InterruptedException {
+        final float FINAL = getValue();
+
+        for (int to = 0; to < regionCount; to++) {
+            Object celebrity = storage[to * K];
+            for (int from = 0; from < regionCount; from++) {
+                for (int rn = 0; rn != 100; rn++) {
+                    storage[getY(to, from, rn)][getX(to, from, rn)] = celebrity;
+                }
+                if (FINAL != getValue()) {
+                    throw new AssertionError("Final value has changed: " + FINAL + " != " + getValue());
+                }
+            }
+        }
+
+        System.out.println("TEST PASSED");
+    }
+
+    public float getValue() {
+        return 6;
+    }
+
+    private int getX(int to, int from, int rn) {
+        return (rn*regionCount + to) % N;
+    }
+
+    private int getY(int to, int from, int rn) {
+        return ((rn*regionCount + to) / N + from * K) % (regionCount*K) ;
+    }
+}
diff --git a/test/compiler/gcbarriers/TestMembarDependencies.java b/test/compiler/gcbarriers/TestMembarDependencies.java
new file mode 100644
index 0000000..29cbd08
--- /dev/null
+++ b/test/compiler/gcbarriers/TestMembarDependencies.java
@@ -0,0 +1,98 @@
+/*
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test TestMembarDependencies
+ * @bug 8172850
+ * @summary Tests correct scheduling of memory loads around MembarVolatile emitted by GC barriers.
+ * @library /testlibrary
+ * @run driver compiler.membars.TestMembarDependencies
+ */
+
+package compiler.membars;
+
+import com.oracle.java.testlibrary.*;
+
+public class TestMembarDependencies {
+    private static TestMembarDependencies f1;
+    private static TestMembarDependencies f2;
+
+    public static void main(String args[]) throws Throwable {
+        if (args.length == 0) {
+            // For debugging, add "-XX:+TraceOptoPipelining"
+            OutputAnalyzer oa = ProcessTools.executeTestJvm("-XX:+IgnoreUnrecognizedVMOptions",
+                "-XX:-TieredCompilation", "-XX:-BackgroundCompilation", "-XX:+PrintOpto",
+                "-XX:CompileCommand=compileonly,compiler.membars.TestMembarDependencies::test*",
+                "-XX:CompileCommand=dontinline,compiler.membars.TestMembarDependencies::test_m1",
+                TestMembarDependencies.class.getName(), "run");
+            // C2 should not crash or bail out from compilation
+            oa.shouldHaveExitValue(0);
+            oa.shouldNotMatch("Bailout: Recompile without subsuming loads");
+            System.out.println(oa.getOutput());
+        } else {
+            f2 = new TestMembarDependencies();
+            // Trigger compilation of test1 and test2
+            for (int i = 0; i < 10_000; ++i) {
+              f2.test1(f2);
+              f2.test2(f2);
+            }
+        }
+    }
+
+    public void test_m1() { }
+    public void test_m2() { }
+
+    public void test1(TestMembarDependencies obj) {
+        // Try/catch/finally is used to create a CFG block without a test + jmpCon
+        // allowing GCM to schedule the testN_mem_reg0 instruction into that block.
+        try {
+            // Method call defines memory state that is then
+            // used by subsequent instructions/blocks (see below).
+            test_m1();
+        } catch (Exception e) {
+
+        } finally {
+            // Oop write to field emits a GC post-barrier with a MembarVolatile
+            // which has a wide memory effect (kills all memory). This creates an
+            // anti-dependency on all surrounding memory loads.
+            f1 = obj;
+        }
+        // The empty method m2 is inlined but the null check of f2 remains. It is encoded
+        // as CmpN(LoadN(MEM), NULL) where MEM is the memory after the call to test_m1().
+        // This is matched to testN_mem_reg0 on x86 which is scheduled before the barrier
+        // in the try/catch block due to the anti-dependency on the MembarVolatile.
+        // C2 crashes in the register allocator when trying to spill the flag register
+        // to keep the result of the testN instruction live from the try/catch block
+        // until it is here.
+        f2.test_m2();
+    }
+
+    public void test2(TestMembarDependencies obj) {
+        // Same as test1 but without try/catch/finally.
+        // This causes C2 to bail out in block local scheduling because testN_mem_reg0 is
+        // scheduled into a block that already contains another test + jmpCon instruction.
+        test_m1();
+        f1 = obj;
+        f2.test_m2();
+    }
+}
diff --git a/test/compiler/loopopts/TestCMovSplitThruPhi.java b/test/compiler/loopopts/TestCMovSplitThruPhi.java
new file mode 100644
index 0000000..86e9134
--- /dev/null
+++ b/test/compiler/loopopts/TestCMovSplitThruPhi.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2017, Red Hat, Inc. 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 8187822
+ * @summary C2 conditonal move optimization might create broken graph
+ * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:-UseOnStackReplacement -XX:-BackgroundCompilation -XX:CompileCommand=dontinline,TestCMovSplitThruPhi::not_inlined -XX:CompileOnly=TestCMovSplitThruPhi::test -XX:-LoopUnswitching TestCMovSplitThruPhi
+ *
+ */
+
+public class TestCMovSplitThruPhi {
+    static int f;
+
+    static int test(boolean flag1, boolean flag2, boolean flag3, boolean flag4) {
+        int v3 = 0;
+        if (flag4) {
+            for (int i = 0; i < 10; i++) {
+                int v1 = 0;
+                if (flag1) {
+                    v1 = not_inlined();
+                }
+                // AddI below will be candidate for split through Phi
+                int v2 = v1;
+                if (flag2) {
+                    v2 = f + v1;
+                }
+                // test above will be converted to CMovI
+                if (flag3) {
+                    v3 = v2 * 2;
+                    break;
+                }
+            }
+        }
+        return v3;
+    }
+
+    private static int not_inlined() {
+        return 0;
+    }
+
+    public static void main(String[] args) {
+        for (int i = 0; i < 20000; i++) {
+            test((i % 2) == 0, (i % 2) == 0, (i % 100) == 1, (i % 1000) == 1);
+        }
+    }
+}
diff --git a/test/compiler/profiling/spectrapredefineclass/Agent.java b/test/compiler/profiling/spectrapredefineclass/Agent.java
new file mode 100644
index 0000000..4227046
--- /dev/null
+++ b/test/compiler/profiling/spectrapredefineclass/Agent.java
@@ -0,0 +1,142 @@
+/*
+ * 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.
+ */
+
+import java.security.*;
+import java.lang.instrument.*;
+import java.lang.reflect.*;
+import java.lang.management.ManagementFactory;
+import com.sun.tools.attach.VirtualMachine;
+
+class A {
+    void m() {
+    }
+}
+
+class B extends A {
+    void m() {
+    }
+}
+
+class C extends A {
+    void m() {
+    }
+}
+
+class Test {
+
+    static public void m() throws Exception {
+        for (int i = 0; i < 20000; i++) {
+            m1(a);
+        }
+        for (int i = 0; i < 4; i++) {
+            m1(b);
+        }
+    }
+
+    static boolean m1(A a) {
+        boolean res =  Agent.m2(a);
+        return res;
+    }
+
+    static public A a = new A();
+    static public B b = new B();
+    static public C c = new C();
+}
+
+public class Agent implements ClassFileTransformer {
+
+
+    static class MemoryChunk {
+        MemoryChunk other;
+        long[] array;
+        MemoryChunk(MemoryChunk other) {
+            other = other;
+            array = new long[1024 * 1024 * 1024];
+        }
+    }
+
+    static public boolean m2(A a) {
+        boolean res = false;
+        if (a.getClass() == B.class) {
+            a.m();
+        } else {
+            res = true;
+        }
+        return res;
+    }
+
+    static public void main(String[] args) throws Exception {
+        // Create speculative trap entries
+        Test.m();
+
+        String nameOfRunningVM = ManagementFactory.getRuntimeMXBean().getName();
+        int p = nameOfRunningVM.indexOf('@');
+        String pid = nameOfRunningVM.substring(0, p);
+
+        // Make the nmethod go away
+        for (int i = 0; i < 10; i++) {
+            System.gc();
+        }
+
+        // Redefine class
+        try {
+            VirtualMachine vm = VirtualMachine.attach(pid);
+            vm.loadAgent(System.getProperty("test.classes",".") + "/agent.jar", "");
+            vm.detach();
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+
+        Test.m();
+        // GC will hit dead method pointer
+        for (int i = 0; i < 10; i++) {
+            System.gc();
+        }
+    }
+
+    public synchronized byte[] transform(final ClassLoader classLoader,
+                                         final String className,
+                                         Class<?> classBeingRedefined,
+                                         ProtectionDomain protectionDomain,
+                                         byte[] classfileBuffer) {
+        System.out.println("Transforming class " + className);
+        return classfileBuffer;
+    }
+
+    public static void redefine(String agentArgs, Instrumentation instrumentation, Class to_redefine) {
+
+        try {
+            instrumentation.retransformClasses(to_redefine);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+
+    }
+
+    public static void agentmain(String agentArgs, Instrumentation instrumentation) throws Exception {
+        Agent transformer = new Agent();
+        instrumentation.addTransformer(transformer, true);
+
+        redefine(agentArgs, instrumentation, Test.class);
+    }
+}
diff --git a/test/compiler/profiling/spectrapredefineclass/Launcher.java b/test/compiler/profiling/spectrapredefineclass/Launcher.java
new file mode 100644
index 0000000..9142738
--- /dev/null
+++ b/test/compiler/profiling/spectrapredefineclass/Launcher.java
@@ -0,0 +1,47 @@
+/*
+ * 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.
+ */
+import java.io.PrintWriter;
+import com.oracle.java.testlibrary.*;
+
+/*
+ * @test
+ * @bug 8038636
+ * @library /testlibrary
+ * @build Agent
+ * @run main ClassFileInstaller Agent
+ * @run main Launcher
+ * @run main/othervm -XX:-TieredCompilation -XX:-BackgroundCompilation -XX:-UseOnStackReplacement -XX:TypeProfileLevel=222 -Xmx1M -XX:ReservedCodeCacheSize=3M Agent
+ */
+public class Launcher {
+    public static void main(String[] args) throws Exception  {
+
+      PrintWriter pw = new PrintWriter("MANIFEST.MF");
+      pw.println("Agent-Class: Agent");
+      pw.println("Can-Retransform-Classes: true");
+      pw.close();
+
+      ProcessBuilder pb = new ProcessBuilder();
+      pb.command(new String[] { JDKToolFinder.getJDKTool("jar"), "cmf", "MANIFEST.MF", System.getProperty("test.classes",".") + "/agent.jar", "Agent.class"});
+      pb.start().waitFor();
+    }
+}
diff --git a/test/compiler/whitebox/CompilerWhiteBoxTest.java b/test/compiler/whitebox/CompilerWhiteBoxTest.java
index 5ca2bb5..a391ba2 100644
--- a/test/compiler/whitebox/CompilerWhiteBoxTest.java
+++ b/test/compiler/whitebox/CompilerWhiteBoxTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -84,8 +84,8 @@
             BACKEDGE_THRESHOLD = THRESHOLD = 150000;
         } else {
             THRESHOLD = COMPILE_THRESHOLD;
-            BACKEDGE_THRESHOLD = COMPILE_THRESHOLD * Long.parseLong(getVMOption(
-                    "OnStackReplacePercentage"));
+            BACKEDGE_THRESHOLD = Math.max(10000, COMPILE_THRESHOLD *
+                    Long.parseLong(getVMOption("OnStackReplacePercentage")));
         }
     }
 
diff --git a/test/gc/arguments/TestG1HeapRegionSize.java b/test/gc/arguments/TestG1HeapRegionSize.java
index b55dc8b..0442d2c 100644
--- a/test/gc/arguments/TestG1HeapRegionSize.java
+++ b/test/gc/arguments/TestG1HeapRegionSize.java
@@ -1,5 +1,5 @@
 /*
-* Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
+* Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
@@ -25,12 +25,11 @@
  * @test TestG1HeapRegionSize
  * @key gc
  * @bug 8021879
- * @requires vm.gc=="G1" | vm.gc=="null"
  * @summary Verify that the flag G1HeapRegionSize is updated properly
  * @run main/othervm -Xmx64m TestG1HeapRegionSize 1048576
- * @run main/othervm -XX:G1HeapRegionSize=2m -Xmx64m -XX:+UseG1GC TestG1HeapRegionSize 2097152
- * @run main/othervm -XX:G1HeapRegionSize=3m -Xmx64m -XX:+UseG1GC TestG1HeapRegionSize 2097152
- * @run main/othervm -XX:G1HeapRegionSize=64m -Xmx256m -XX:+UseG1GC TestG1HeapRegionSize 33554432
+ * @run main/othervm -XX:G1HeapRegionSize=2m -Xmx64m TestG1HeapRegionSize 2097152
+ * @run main/othervm -XX:G1HeapRegionSize=3m -Xmx64m TestG1HeapRegionSize 2097152
+ * @run main/othervm -XX:G1HeapRegionSize=64m -Xmx256m TestG1HeapRegionSize 33554432
  */
 
 import sun.management.ManagementFactoryHelper;
@@ -43,7 +42,13 @@
     HotSpotDiagnosticMXBean diagnostic = ManagementFactoryHelper.getDiagnosticMXBean();
 
     String expectedValue = getExpectedValue(args);
-    VMOption option = diagnostic.getVMOption("G1HeapRegionSize");
+    VMOption option = diagnostic.getVMOption("UseG1GC");
+    if (option.getValue().equals("false")) {
+      System.out.println("Skipping this test. It is only a G1 test.");
+      return;
+    }
+
+    option = diagnostic.getVMOption("G1HeapRegionSize");
     if (!expectedValue.equals(option.getValue())) {
       throw new RuntimeException("Wrong value for G1HeapRegionSize. Expected " + expectedValue + " but got " + option.getValue());
     }
diff --git a/test/gc/class_unloading/TestClassUnloadingDisabled.java b/test/gc/class_unloading/TestClassUnloadingDisabled.java
new file mode 100644
index 0000000..fbc5a28
--- /dev/null
+++ b/test/gc/class_unloading/TestClassUnloadingDisabled.java
@@ -0,0 +1,116 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @key gc
+ * @bug 8114823
+ * @requires vm.gc == null
+ * @requires vm.opt.ExplicitGCInvokesConcurrent != true
+ * @requires vm.opt.ClassUnloading != true
+ * @library  /testlibrary /testlibrary/whitebox
+ * @build sun.hotspot.WhiteBox
+ * @run main ClassFileInstaller sun.hotspot.WhiteBox
+ *                              sun.hotspot.WhiteBox$WhiteBoxPermission
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI
+ *                   -XX:-ClassUnloading -XX:+UseG1GC TestClassUnloadingDisabled
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI
+ *                   -XX:-ClassUnloading -XX:+UseSerialGC TestClassUnloadingDisabled
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI
+ *                   -XX:-ClassUnloading -XX:+UseParallelGC TestClassUnloadingDisabled
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI
+ *                   -XX:-ClassUnloading -XX:+UseConcMarkSweepGC TestClassUnloadingDisabled
+ */
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
+import sun.hotspot.WhiteBox;
+
+import com.oracle.java.testlibrary.Asserts;
+
+public class TestClassUnloadingDisabled {
+    public static void main(String args[]) throws Exception {
+        final WhiteBox wb = WhiteBox.getWhiteBox();
+        // Fetch the dir where the test class and the class
+        // to be loaded resides.
+        String classDir = TestClassUnloadingDisabled.class.getProtectionDomain().getCodeSource().getLocation().getPath();
+        String className = "ClassToLoadUnload";
+
+        Asserts.assertFalse(wb.isClassAlive(className), "Should not be loaded yet");
+
+        // The NoPDClassLoader handles loading classes in the test directory
+        // and loads them without a protection domain, which in some cases
+        // keeps the class live regardless of marking state.
+        NoPDClassLoader nopd = new NoPDClassLoader(classDir);
+        nopd.loadClass(className);
+
+        Asserts.assertTrue(wb.isClassAlive(className), "Class should be loaded");
+
+        // Clear the class-loader, class and object references to make
+        // class unloading possible.
+        nopd = null;
+
+        System.gc();
+        Asserts.assertTrue(wb.isClassAlive(className), "Class should not have ben unloaded");
+    }
+}
+
+class NoPDClassLoader extends ClassLoader {
+    String path;
+
+    NoPDClassLoader(String path) {
+        this.path = path;
+    }
+
+    public Class<?> loadClass(String name) throws ClassNotFoundException {
+        byte[] cls = null;
+        File f = new File(path,name + ".class");
+
+        // Delegate class loading if class not present in the given
+        // directory.
+        if (!f.exists()) {
+            return super.loadClass(name);
+        }
+
+        try {
+            Path path = Paths.get(f.getAbsolutePath());
+            cls = Files.readAllBytes(path);
+        } catch (IOException e) {
+            throw new ClassNotFoundException(name);
+        }
+
+        // Define class with no protection domain and resolve it.
+        return defineClass(name, cls, 0, cls.length, null);
+    }
+}
+
+class ClassToLoadUnload {
+}
diff --git a/test/gc/metaspace/CompressedClassSpaceSizeInJmapHeap.java b/test/gc/metaspace/CompressedClassSpaceSizeInJmapHeap.java
index 8152a9e..0ca0878 100644
--- a/test/gc/metaspace/CompressedClassSpaceSizeInJmapHeap.java
+++ b/test/gc/metaspace/CompressedClassSpaceSizeInJmapHeap.java
@@ -37,6 +37,11 @@
 
 public class CompressedClassSpaceSizeInJmapHeap {
     public static void main(String[] args) throws Exception {
+        if (!Platform.shouldSAAttach()) {
+            System.out.println("SA attach not expected to work - test skipped.");
+            return;
+        }
+
         String pid = Integer.toString(ProcessTools.getProcessId());
 
         JDKToolLauncher jmap = JDKToolLauncher.create("jmap")
diff --git a/test/jbProblemsList.txt b/test/jbProblemsList.txt
new file mode 100644
index 0000000..5ff6416
--- /dev/null
+++ b/test/jbProblemsList.txt
@@ -0,0 +1,4 @@
+# Wrong value for java.vendor property, "JetBrains s.r.o", expected to be of form: "Oracle Corporation"
+runtime/6981737/Test6981737.java                                                            generic-all
+runtime/NMT/NMTWithCDS.java                                                         8180936 linux-all
+8180936`
\ No newline at end of file
diff --git a/test/runtime/EnableTracing/TestEnableTracing.java b/test/runtime/EnableTracing/TestEnableTracing.java
new file mode 100644
index 0000000..9b2ad48
--- /dev/null
+++ b/test/runtime/EnableTracing/TestEnableTracing.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test TestEnableTracing
+ * @summary Test if tracing produces the expected output when enabled.
+ * @bug 8209863 8145788
+ * @library /testlibrary
+ * @run main TestEnableTracing
+ */
+
+import com.oracle.java.testlibrary.ProcessTools;
+import com.oracle.java.testlibrary.OutputAnalyzer;
+
+public class TestEnableTracing {
+    public static final String OPENJDK_MARK = "OpenJDK";
+
+    public static void main(String[] args) throws Exception {
+        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+EnableTracing", "-version");
+        OutputAnalyzer output = new OutputAnalyzer(pb.start());
+        if (output.getStderr().contains(OPENJDK_MARK)) {
+            output.shouldMatch("^Class Load");
+            output.shouldContain("Loaded Class ="); // verify TraceStream print_val Klass*
+        }
+        output.shouldHaveExitValue(0);
+
+        pb = ProcessTools.createJavaProcessBuilder("-XX:+EnableTracing", "-XX:+UseLockedTracing", "-Xcomp ", "-version");
+        output = new OutputAnalyzer(pb.start());
+        if (output.getStderr().contains(OPENJDK_MARK)) {
+            output.shouldMatch("^Class Load");
+            output.shouldMatch("^Compilation");
+            output.shouldContain("Java Method ="); // verify TraceStream print_val Method*
+        }
+        output.shouldHaveExitValue(0);
+    }
+}
diff --git a/test/runtime/Metaspace/MaxMetaspaceSizeTest.java b/test/runtime/Metaspace/MaxMetaspaceSizeTest.java
new file mode 100644
index 0000000..a10b54d
--- /dev/null
+++ b/test/runtime/Metaspace/MaxMetaspaceSizeTest.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import com.oracle.java.testlibrary.ProcessTools;
+import com.oracle.java.testlibrary.OutputAnalyzer;
+
+/*
+ * @test MaxMetaspaceSizeTest
+ * @requires vm.bits == "64"
+ * @bug 8087291
+ * @library /testlibrary
+ * @run main/othervm MaxMetaspaceSizeTest
+ */
+
+public class MaxMetaspaceSizeTest {
+    public static void main(String... args) throws Exception {
+        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
+            "-Xmx1g",
+            "-XX:InitialBootClassLoaderMetaspaceSize=4195328",
+            "-XX:MaxMetaspaceSize=4195328",
+            "-XX:+UseCompressedClassPointers",
+            "-XX:CompressedClassSpaceSize=1g",
+            "-version");
+        OutputAnalyzer output = new OutputAnalyzer(pb.start());
+        output.shouldContain("MaxMetaspaceSize is too small.");
+    }
+}
diff --git a/test/runtime/RedefineFinalizer/RedefineFinalizer.java b/test/runtime/RedefineTests/RedefineFinalizer.java
similarity index 95%
rename from test/runtime/RedefineFinalizer/RedefineFinalizer.java
rename to test/runtime/RedefineTests/RedefineFinalizer.java
index 227b9e8..3d98452 100644
--- a/test/runtime/RedefineFinalizer/RedefineFinalizer.java
+++ b/test/runtime/RedefineTests/RedefineFinalizer.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
diff --git a/test/runtime/RedefineTests/RedefineInterfaceCall.java b/test/runtime/RedefineTests/RedefineInterfaceCall.java
new file mode 100644
index 0000000..01945f6
--- /dev/null
+++ b/test/runtime/RedefineTests/RedefineInterfaceCall.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8174962
+ * @summary Redefine class with interface method call
+ * @library /testlibrary
+ * @build RedefineClassHelper
+ * @run main RedefineClassHelper
+ * @run main/othervm -javaagent:redefineagent.jar -XX:TraceRedefineClasses=3174407 RedefineInterfaceCall
+ */
+
+import static com.oracle.java.testlibrary.Asserts.assertEquals;
+
+interface I1 { default int m() { return 0; } }
+interface I2 extends I1 {}
+
+public class RedefineInterfaceCall {
+
+    public static class C implements I2 {
+        public int test(I2 i) {
+            return i.m(); // invokeinterface cpCacheEntry
+        }
+    }
+
+    static String newI1 =
+      "interface I1 { default int m() { return 1; } }";
+
+    static String newC =
+        "public class RedefineInterfaceCall$C implements I2 { " +
+        "  public int test(I2 i) { " +
+        "    return i.m(); " +
+        "  } " +
+        "} ";
+
+    static int test(I2 i) {
+        return i.m(); // invokeinterface cpCacheEntry
+    }
+
+    public static void main(String[] args) throws Exception {
+        C c = new C();
+
+        assertEquals(test(c),   0);
+        assertEquals(c.test(c), 0);
+
+        RedefineClassHelper.redefineClass(C.class, newC);
+
+        assertEquals(c.test(c), 0);
+
+        RedefineClassHelper.redefineClass(I1.class, newI1);
+
+        assertEquals(test(c),   1);
+        assertEquals(c.test(c), 1);
+
+        RedefineClassHelper.redefineClass(C.class, newC);
+
+        assertEquals(c.test(c), 1);
+    }
+}
diff --git a/test/runtime/RedefineTests/RedefineRunningMethods.java b/test/runtime/RedefineTests/RedefineRunningMethods.java
new file mode 100644
index 0000000..7d44a8a
--- /dev/null
+++ b/test/runtime/RedefineTests/RedefineRunningMethods.java
@@ -0,0 +1,143 @@
+/*
+ * 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 8055008
+ * @summary Redefine EMCP and non-EMCP methods that are running in an infinite loop
+ * @library /testlibrary
+ * @build RedefineClassHelper
+ * @run main RedefineClassHelper
+ * @run main/othervm -javaagent:redefineagent.jar RedefineRunningMethods
+ */
+public class RedefineRunningMethods {
+
+    public static String newB =
+                "class RedefineRunningMethods$B {" +
+                "   static int count1 = 0;" +
+                "   static int count2 = 0;" +
+                "   public static volatile boolean stop = false;" +
+                "  static void localSleep() { " +
+                "    try{ " +
+                "      Thread.currentThread().sleep(10);" +
+                "    } catch(InterruptedException ie) { " +
+                "    } " +
+                " } " +
+                "   public static void infinite() { " +
+                "       System.out.println(\"infinite called\");" +
+                "   }" +
+                "   public static void infinite_emcp() { " +
+                "       while (!stop) { count2++; localSleep(); }" +
+                "   }" +
+                "}";
+
+    public static String evenNewerB =
+                "class RedefineRunningMethods$B {" +
+                "   static int count1 = 0;" +
+                "   static int count2 = 0;" +
+                "   public static volatile boolean stop = false;" +
+                "  static void localSleep() { " +
+                "    try{ " +
+                "      Thread.currentThread().sleep(1);" +
+                "    } catch(InterruptedException ie) { " +
+                "    } " +
+                " } " +
+                "   public static void infinite() { }" +
+                "   public static void infinite_emcp() { " +
+                "       System.out.println(\"infinite_emcp now obsolete called\");" +
+                "   }" +
+                "}";
+
+    static class B {
+        static int count1 = 0;
+        static int count2 = 0;
+        public static volatile boolean stop = false;
+        static void localSleep() {
+          try{
+            Thread.currentThread().sleep(10);//sleep for 10 ms
+          } catch(InterruptedException ie) {
+          }
+        }
+
+        public static void infinite() {
+            while (!stop) { count1++; localSleep(); }
+        }
+        public static void infinite_emcp() {
+            while (!stop) { count2++; localSleep(); }
+        }
+    }
+
+
+    public static void main(String[] args) throws Exception {
+
+        new Thread() {
+            public void run() {
+                B.infinite();
+            }
+        }.start();
+
+        new Thread() {
+            public void run() {
+                B.infinite_emcp();
+            }
+        }.start();
+
+        RedefineClassHelper.redefineClass(B.class, newB);
+
+        System.gc();
+
+        B.infinite();
+
+        // Start a thread with the second version of infinite_emcp running
+        new Thread() {
+            public void run() {
+                B.infinite_emcp();
+            }
+        }.start();
+
+        for (int i = 0; i < 20 ; i++) {
+            String s = new String("some garbage");
+            System.gc();
+        }
+
+        RedefineClassHelper.redefineClass(B.class, evenNewerB);
+        System.gc();
+
+        for (int i = 0; i < 20 ; i++) {
+            B.infinite();
+            String s = new String("some garbage");
+            System.gc();
+        }
+
+        B.infinite_emcp();
+
+        // purge should clean everything up.
+        B.stop = true;
+
+        for (int i = 0; i < 20 ; i++) {
+            B.infinite();
+            String s = new String("some garbage");
+            System.gc();
+        }
+    }
+}
diff --git a/test/runtime/StackGap/T.java b/test/runtime/StackGap/T.java
new file mode 100644
index 0000000..7d46348
--- /dev/null
+++ b/test/runtime/StackGap/T.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2018, Red Hat, Inc. 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.
+ */
+
+public class T {
+
+  public static void test(int n) {
+    if (n == 0) return;
+    System.out.println (n);
+    test (n - 1);
+
+  }
+
+}
diff --git a/test/runtime/StackGap/exestack-gap.c b/test/runtime/StackGap/exestack-gap.c
new file mode 100644
index 0000000..ebb7b1d
--- /dev/null
+++ b/test/runtime/StackGap/exestack-gap.c
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) 2018, Red Hat, Inc. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+#include <jni.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+JNIEnv* create_vm(JavaVM **jvm, char *extra_option)
+{
+    JNIEnv* env;
+    JavaVMInitArgs args;
+    JavaVMOption options[4];
+    args.version = JNI_VERSION_1_8;
+    args.nOptions = 3 + (extra_option != NULL);
+    options[0].optionString = "-Xss2048k";
+    char classpath[4096];
+    snprintf(classpath, sizeof classpath,
+             "-Djava.class.path=%s", getenv("CLASSPATH"));
+    options[1].optionString = classpath;
+    options[2].optionString = "-XX:+UnlockExperimentalVMOptions";
+    if (extra_option) {
+      options[3].optionString = extra_option;
+    }
+    args.options = &options[0];
+    args.ignoreUnrecognized = 0;
+    int rv;
+    rv = JNI_CreateJavaVM(jvm, (void**)&env, &args);
+    if (rv < 0) return NULL;
+    return env;
+}
+
+void run(char *extra_arg) {
+  JavaVM *jvm;
+  jclass T_class;
+  jmethodID test_method;
+  JNIEnv *env = create_vm(&jvm, extra_arg);
+  if (env == NULL)
+    exit(1);
+  T_class = (*env)->FindClass(env, "T");
+  if ((*env)->ExceptionCheck(env) == JNI_TRUE) {
+    (*env)->ExceptionDescribe(env);
+    exit(1);
+  }
+  test_method = (*env)->GetStaticMethodID(env, T_class, "test", "(I)V");
+  if ((*env)->ExceptionCheck(env) == JNI_TRUE) {
+    (*env)->ExceptionDescribe(env);
+    exit(1);
+  }
+  (*env)->CallStaticVoidMethod(env, T_class, test_method, 1000);
+}
+
+
+int main(int argc, char **argv)
+{
+  if (argc > 1) {
+    run(argv[1]);
+  } else {
+    run(NULL);
+  }
+
+  return 0;
+}
diff --git a/test/runtime/StackGap/testme.sh b/test/runtime/StackGap/testme.sh
new file mode 100644
index 0000000..90265e6
--- /dev/null
+++ b/test/runtime/StackGap/testme.sh
@@ -0,0 +1,73 @@
+# Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# 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.
+#!/bin/sh
+
+#
+# @test testme.sh
+# @bug 8197429
+# @summary Linux kernel stack guard should not cause segfaults on x86-32
+# @compile T.java
+# @run shell testme.sh
+#
+
+if [ "${TESTSRC}" = "" ]
+then
+  TESTSRC=${PWD}
+  echo "TESTSRC not set.  Using "${TESTSRC}" as default"
+fi
+echo "TESTSRC=${TESTSRC}"
+## Adding common setup Variables for running shell tests.
+. ${TESTSRC}/../../test_env.sh
+
+if [ "${VM_OS}" != "linux" ]
+then
+  echo "Test only valid for Linux"
+  exit 0
+fi
+
+gcc_cmd=`which gcc`
+if [ "x$gcc_cmd" = "x" ]; then
+    echo "WARNING: gcc not found. Cannot execute test." 2>&1
+    exit 0;
+fi
+
+CFLAGS="-m${VM_BITS}"
+
+LD_LIBRARY_PATH=.:${COMPILEJAVA}/jre/lib/${VM_CPU}/${VM_TYPE}:/usr/lib:$LD_LIBRARY_PATH
+export LD_LIBRARY_PATH
+
+cp ${TESTSRC}${FS}exestack-gap.c .
+
+# Copy the result of our @compile action:
+cp ${TESTCLASSES}${FS}T.class .
+
+echo "Compilation flag: ${COMP_FLAG}"
+# Note pthread may not be found thus invoke creation will fail to be created.
+# Check to ensure you have a /usr/lib/libpthread.so if you don't please look
+# for /usr/lib/`uname -m`-linux-gnu version ensure to add that path to below compilation.
+
+$gcc_cmd -DLINUX ${CFLAGS} -o stack-gap \
+    -I${COMPILEJAVA}/include -I${COMPILEJAVA}/include/linux \
+    -L${COMPILEJAVA}/jre/lib/${VM_CPU}/${VM_TYPE} \
+    -ljvm -lpthread exestack-gap.c
+
+./stack-gap || exit $?
+./stack-gap -XX:+DisablePrimordialThreadGuardPages || exit $?
diff --git a/test/runtime/containers/docker/AttemptOOM.java b/test/runtime/containers/docker/AttemptOOM.java
new file mode 100644
index 0000000..4d46828
--- /dev/null
+++ b/test/runtime/containers/docker/AttemptOOM.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+public class AttemptOOM {
+    private static MyObj[] data;
+
+    public static void main(String[] args) throws Exception {
+        System.out.println("Entering AttemptOOM main");
+
+        // each MyObj will allocate 1024 byte array
+        int sizeInMb = Integer.parseInt(args[0]);
+        data = new MyObj[sizeInMb*1024];
+
+        System.out.println("data.length = " + data.length);
+
+        for (int i=0; i < data.length; i++) {
+            data[i] = new MyObj(1024);
+        }
+
+        System.out.println("AttemptOOM allocation successful");
+    }
+
+    private static class MyObj {
+        private byte[] myData;
+        MyObj(int size) {
+            myData = new byte[size];
+        }
+    }
+}
diff --git a/test/runtime/containers/docker/CPUSetsReader.java b/test/runtime/containers/docker/CPUSetsReader.java
new file mode 100644
index 0000000..f6fa93e
--- /dev/null
+++ b/test/runtime/containers/docker/CPUSetsReader.java
@@ -0,0 +1,141 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.io.FileReader;
+import java.util.ArrayList;
+import java.util.Optional;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import com.oracle.java.testlibrary.Asserts;
+
+
+// A simple CPU sets reader and parser
+public class CPUSetsReader {
+    public static String PROC_SELF_STATUS_PATH="/proc/self/status";
+
+    // Test the parser
+    public static void test() {
+        assertParse("0-7", "0,1,2,3,4,5,6,7");
+        assertParse("1,3,6", "1,3,6");
+        assertParse("0,2-4,6,10-11", "0,2,3,4,6,10,11");
+        assertParse("0", "0");
+    }
+
+
+    private static void assertParse(String cpuSet, String expectedResult) {
+        Asserts.assertEquals(listToString(parseCpuSet(cpuSet)), expectedResult);
+    }
+
+
+    public static String readFromProcStatus(String setType) {
+        String path = PROC_SELF_STATUS_PATH;
+        Optional<String> o = Optional.empty();
+
+        System.out.println("readFromProcStatus() entering for: " + setType);
+
+        try (Stream<String> stream = Files.lines(Paths.get(path))) {
+            o = stream
+                .filter(line -> line.contains(setType))
+                .findFirst();
+        } catch (IOException e) {
+            return null;
+        }
+
+        if (!o.isPresent()) {
+            return null;    // entry not found
+        }
+
+        String[] parts = o.get().replaceAll("\\s","").split(":");
+
+        // Should be 2 parts, before and after ":"
+        Asserts.assertEquals(parts.length, 2);
+
+        String result = parts[1];
+        System.out.println("readFromProcStatus() returning: " + result);
+        return result;
+    }
+
+
+    public static List<Integer> parseCpuSet(String value) {
+        ArrayList<Integer> result = new ArrayList<Integer>();
+
+        try {
+            String[] commaSeparated = value.split(",");
+
+            for (String item : commaSeparated) {
+                if (item.contains("-")) {
+                    addRange(result, item);
+                } else {
+                    result.add(Integer.parseInt(item));
+                }
+            }
+        } catch (Exception e) {
+            System.err.println("Exception in getMaxCpuSets(): " + e);
+            return null;
+        }
+
+        return result;
+    }
+
+
+    private static void addRange(ArrayList<Integer> list, String s) {
+        String[] range = s.split("-");
+        if ( range.length != 2 ) {
+            throw new RuntimeException("Range should only contain two items, but contains "
+                                       + range.length + " items");
+        }
+
+        int min = Integer.parseInt(range[0]);
+        int max = Integer.parseInt(range[1]);
+
+        if (min >= max) {
+            String msg = String.format("min is greater or equals to max, min = %d, max = %d",
+                                       min, max);
+            throw new RuntimeException(msg);
+        }
+
+        for (int i = min; i <= max; i++) {
+            list.add(i);
+        }
+    }
+
+
+    // Convert list of integers to string with comma-separated values
+    public static String listToString(List<Integer> list) {
+        return listToString(list, Integer.MAX_VALUE);
+    }
+
+    // Convert list of integers to a string with comma-separated values;
+    // include up to maxCount.
+    public static String listToString(List<Integer> list, int maxCount) {
+        return list.stream()
+            .limit(maxCount)
+            .map(Object::toString)
+            .collect(Collectors.joining(","));
+    }
+}
diff --git a/test/runtime/containers/docker/CheckContainerized.java b/test/runtime/containers/docker/CheckContainerized.java
new file mode 100644
index 0000000..c0ca4bf
--- /dev/null
+++ b/test/runtime/containers/docker/CheckContainerized.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import sun.hotspot.WhiteBox;
+
+public class CheckContainerized {
+    public static String OUTSIDE_OF_CONTAINER =
+        "CheckContainerized: Running outside of a container";
+    public static String INSIDE_A_CONTAINER =
+        "CheckContainerized: Running inside a container";
+
+    public static void main(String[] args) {
+        System.out.println("CheckContainerized: Entering");
+        WhiteBox wb = WhiteBox.getWhiteBox();
+
+        if (wb.isContainerized()) {
+            System.out.println(INSIDE_A_CONTAINER);
+
+        } else {
+            System.out.println(OUTSIDE_OF_CONTAINER);
+        }
+    }
+}
+
diff --git a/test/runtime/containers/docker/DockerBasicTest.java b/test/runtime/containers/docker/DockerBasicTest.java
new file mode 100644
index 0000000..fe5d441
--- /dev/null
+++ b/test/runtime/containers/docker/DockerBasicTest.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+
+/*
+ * @test
+ * @summary Basic (sanity) test for JDK-under-test inside a docker image.
+ * @library /testlibrary
+ * @build HelloDocker
+ * @run driver DockerBasicTest
+ */
+
+import com.oracle.java.testlibrary.Utils;
+import com.oracle.java.testlibrary.Platform;
+import com.oracle.java.testlibrary.DockerTestUtils;
+import com.oracle.java.testlibrary.DockerRunOptions;
+
+public class DockerBasicTest {
+    private static final String imageNameAndTag = "jdk8-internal:test";
+    // Diganostics: set to false to examine image after the test
+    private static final boolean removeImageAfterTest = true;
+
+    public static void main(String[] args) throws Exception {
+        if (!DockerTestUtils.canTestDocker()) {
+            return;
+        }
+        DockerTestUtils.buildJdkDockerImage(imageNameAndTag, "Dockerfile-BasicTest", "jdk-docker");
+
+        try {
+            testJavaVersion();
+            testHelloDocker();
+        } finally {
+            if (removeImageAfterTest)
+                DockerTestUtils.removeDockerImage(imageNameAndTag);
+        }
+    }
+
+
+    private static void testJavaVersion() throws Exception {
+        DockerRunOptions opts =
+            new DockerRunOptions(imageNameAndTag, "/jdk/bin/java", "-version");
+
+        DockerTestUtils.dockerRunJava(opts)
+            .shouldHaveExitValue(0)
+            .shouldContain(Platform.vmName);
+    }
+
+
+    private static void testHelloDocker() throws Exception {
+        DockerRunOptions opts =
+            new DockerRunOptions(imageNameAndTag, "/jdk/bin/java", "HelloDocker")
+            .addJavaOpts("-cp", "/test-classes/")
+            .addDockerOpts("--volume", Utils.TEST_CLASSES + ":/test-classes/");
+
+        DockerTestUtils.dockerRunJava(opts)
+            .shouldHaveExitValue(0)
+            .shouldContain("Hello Docker");
+    }
+}
+
diff --git a/test/runtime/containers/docker/Dockerfile-BasicTest b/test/runtime/containers/docker/Dockerfile-BasicTest
new file mode 100644
index 0000000..166c969
--- /dev/null
+++ b/test/runtime/containers/docker/Dockerfile-BasicTest
@@ -0,0 +1,8 @@
+FROM oraclelinux:7.2
+MAINTAINER mikhailo.seledtsov@oracle.com
+
+COPY /jdk /jdk
+
+ENV JAVA_HOME=/jdk
+
+CMD ["/bin/bash"]
diff --git a/test/runtime/containers/docker/Dockerfile-BasicTest-aarch64 b/test/runtime/containers/docker/Dockerfile-BasicTest-aarch64
new file mode 100644
index 0000000..082a4d8
--- /dev/null
+++ b/test/runtime/containers/docker/Dockerfile-BasicTest-aarch64
@@ -0,0 +1,8 @@
+# Use generic ubuntu Linux on AArch64
+FROM aarch64/ubuntu
+
+COPY /jdk /jdk
+
+ENV JAVA_HOME=/jdk
+
+CMD ["/bin/bash"]
diff --git a/test/runtime/containers/docker/Dockerfile-BasicTest-ppc64le b/test/runtime/containers/docker/Dockerfile-BasicTest-ppc64le
new file mode 100644
index 0000000..57dfb0f
--- /dev/null
+++ b/test/runtime/containers/docker/Dockerfile-BasicTest-ppc64le
@@ -0,0 +1,10 @@
+# test on x86_64 uses Oracle Linux but we do not have this for ppc64le
+# so use some other Linux where OpenJDK works 
+# FROM oraclelinux:7.2
+FROM ppc64le/ubuntu
+
+COPY /jdk /jdk
+
+ENV JAVA_HOME=/jdk
+
+CMD ["/bin/bash"]
diff --git a/test/runtime/containers/docker/Dockerfile-BasicTest-s390x b/test/runtime/containers/docker/Dockerfile-BasicTest-s390x
new file mode 100644
index 0000000..940b36e
--- /dev/null
+++ b/test/runtime/containers/docker/Dockerfile-BasicTest-s390x
@@ -0,0 +1,7 @@
+FROM s390x/ubuntu
+
+COPY /jdk /jdk
+
+ENV JAVA_HOME=/jdk
+
+CMD ["/bin/bash"]
diff --git a/test/runtime/containers/docker/HelloDocker.java b/test/runtime/containers/docker/HelloDocker.java
new file mode 100644
index 0000000..5fe7a5a
--- /dev/null
+++ b/test/runtime/containers/docker/HelloDocker.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+public class HelloDocker {
+    public static void main(String args[]) {
+        System.out.println("Hello Docker");
+    }
+}
diff --git a/test/runtime/containers/docker/PrintContainerInfo.java b/test/runtime/containers/docker/PrintContainerInfo.java
new file mode 100644
index 0000000..b060477
--- /dev/null
+++ b/test/runtime/containers/docker/PrintContainerInfo.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import sun.hotspot.WhiteBox;
+
+public class PrintContainerInfo {
+
+    public static void main(String[] args) {
+        System.out.println("PrintContainerInfo: Entering");
+        WhiteBox wb = WhiteBox.getWhiteBox();
+
+        wb.printOsInfo();
+    }
+}
diff --git a/test/runtime/containers/docker/TEST.properties b/test/runtime/containers/docker/TEST.properties
new file mode 100644
index 0000000..3d748e1
--- /dev/null
+++ b/test/runtime/containers/docker/TEST.properties
@@ -0,0 +1 @@
+exclusiveAccess.dirs=.
diff --git a/test/runtime/containers/docker/TestCPUAwareness.java b/test/runtime/containers/docker/TestCPUAwareness.java
new file mode 100644
index 0000000..fe7d449
--- /dev/null
+++ b/test/runtime/containers/docker/TestCPUAwareness.java
@@ -0,0 +1,204 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+
+/*
+ * @test
+ * @summary Test JVM's CPU resource awareness when running inside docker container
+ * @library /testlibrary
+ * @run driver TestCPUAwareness
+ */
+
+import java.util.List;
+import com.oracle.java.testlibrary.Common;
+import com.oracle.java.testlibrary.DockerTestUtils;
+import com.oracle.java.testlibrary.DockerRunOptions;
+
+public class TestCPUAwareness {
+private static final String imageName = Common.imageName("cpu");
+    private static final int availableCPUs = Runtime.getRuntime().availableProcessors();
+
+    public static void main(String[] args) throws Exception {
+        if (!DockerTestUtils.canTestDocker()) {
+            return;
+        }
+
+        System.out.println("Test Environment: detected availableCPUs = " + availableCPUs);
+        DockerTestUtils.buildJdkDockerImage(imageName, "Dockerfile-BasicTest", "jdk-docker");
+
+        try {
+            // cpuset, period, shares, expected Active Processor Count
+            testComboWithCpuSets();
+
+            // cpu shares - it should be safe to use CPU shares exceeding available CPUs
+            testCpuShares(256, 1);
+            testCpuShares(2048, 2);
+            testCpuShares(4096, 4);
+
+            // leave one CPU for system and tools, otherwise this test may be unstable
+            int maxNrOfAvailableCpus =  availableCPUs - 1;
+            for (int i=1; i < maxNrOfAvailableCpus; i = i * 2) {
+                testCpus(i, i);
+            }
+
+            // If ActiveProcessorCount is set, the VM should use it, regardless of other
+            // container settings, host settings or available CPUs on the host.
+            testActiveProcessorCount(1, 1);
+            testActiveProcessorCount(2, 2);
+
+            // cpu quota and period
+            testCpuQuotaAndPeriod(50*1000, 100*1000);
+            testCpuQuotaAndPeriod(100*1000, 100*1000);
+            testCpuQuotaAndPeriod(150*1000, 100*1000);
+            testCpuQuotaAndPeriod(400*1000, 100*1000);
+
+        } finally {
+            DockerTestUtils.removeDockerImage(imageName);
+        }
+    }
+
+
+    private static void testComboWithCpuSets() throws Exception {
+        String cpuSetStr = CPUSetsReader.readFromProcStatus("Cpus_allowed_list");
+        System.out.println("cpuSetStr = " + cpuSetStr);
+
+        if (cpuSetStr == null) {
+            System.out.printf("The cpuset test cases are skipped");
+        } else {
+            List<Integer> cpuSet = CPUSetsReader.parseCpuSet(cpuSetStr);
+
+            // Test subset of cpuset with one element
+            if (cpuSet.size() >= 1) {
+                String testCpuSet = CPUSetsReader.listToString(cpuSet, 1);
+                testAPCCombo(testCpuSet, 200*1000, 100*1000,   4*1024, true, 1);
+            }
+
+            // Test subset of cpuset with two elements
+            if (cpuSet.size() >= 2) {
+                String testCpuSet = CPUSetsReader.listToString(cpuSet, 2);
+                testAPCCombo(testCpuSet, 200*1000, 100*1000, 4*1024, true, 2);
+                testAPCCombo(testCpuSet, 200*1000, 100*1000, 1023,   true, 2);
+                testAPCCombo(testCpuSet, 200*1000, 100*1000, 1023,   false,  1);
+            }
+
+            // Test subset of cpuset with three elements
+            if (cpuSet.size() >= 3) {
+                String testCpuSet = CPUSetsReader.listToString(cpuSet, 3);
+                testAPCCombo(testCpuSet, 100*1000, 100*1000, 2*1024, true, 1);
+                testAPCCombo(testCpuSet, 200*1000, 100*1000, 1023,   true, 2);
+                testAPCCombo(testCpuSet, 200*1000, 100*1000, 1023,   false,  1);
+            }
+        }
+    }
+
+
+    private static void testActiveProcessorCount(int valueToSet, int expectedValue) throws Exception {
+        Common.logNewTestCase("Test ActiveProcessorCount: valueToSet = " + valueToSet);
+
+        DockerRunOptions opts = Common.newOpts(imageName)
+            .addJavaOpts("-XX:ActiveProcessorCount=" + valueToSet, "-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintActiveCpus");
+        Common.run(opts)
+            .shouldMatch("active processor count set by user.*" + expectedValue);
+    }
+
+
+    private static void testCpus(int valueToSet, int expectedTraceValue) throws Exception {
+        Common.logNewTestCase("test cpus: " + valueToSet);
+        DockerRunOptions opts = Common.newOpts(imageName)
+            .addDockerOpts("--cpus", "" + valueToSet);
+        Common.run(opts)
+            .shouldMatch("active_processor_count.*" + expectedTraceValue);
+    }
+
+
+    // Expected active processor count can not exceed available CPU count
+    private static int adjustExpectedAPCForAvailableCPUs(int expectedAPC) {
+        if (expectedAPC > availableCPUs) {
+            expectedAPC = availableCPUs;
+            System.out.println("Adjusted expectedAPC = " + expectedAPC);
+        }
+        return expectedAPC;
+    }
+
+
+    private static void testCpuQuotaAndPeriod(int quota, int period)
+        throws Exception {
+        Common.logNewTestCase("test cpu quota and period: ");
+        System.out.println("quota = " + quota);
+        System.out.println("period = " + period);
+
+        int expectedAPC = (int) Math.ceil((float) quota / (float) period);
+        System.out.println("expectedAPC = " + expectedAPC);
+        expectedAPC = adjustExpectedAPCForAvailableCPUs(expectedAPC);
+
+        DockerRunOptions opts = Common.newOpts(imageName)
+            .addDockerOpts("--cpu-period=" + period)
+            .addDockerOpts("--cpu-quota=" + quota);
+
+        Common.run(opts)
+            .shouldMatch("CPU Period is.*" + period)
+            .shouldMatch("CPU Quota is.*" + quota)
+            .shouldMatch("active_processor_count.*" + expectedAPC);
+    }
+
+
+    // Test correctess of automatically selected active processor cound
+    private static void testAPCCombo(String cpuset, int quota, int period, int shares,
+                                     boolean usePreferContainerQuotaForCPUCount,
+                                     int expectedAPC) throws Exception {
+        Common.logNewTestCase("test APC Combo");
+        System.out.println("cpuset = " + cpuset);
+        System.out.println("quota = " + quota);
+        System.out.println("period = " + period);
+        System.out.println("shares = " + period);
+        System.out.println("usePreferContainerQuotaForCPUCount = " + usePreferContainerQuotaForCPUCount);
+        System.out.println("expectedAPC = " + expectedAPC);
+
+        expectedAPC = adjustExpectedAPCForAvailableCPUs(expectedAPC);
+
+        DockerRunOptions opts = Common.newOpts(imageName)
+            .addDockerOpts("--cpuset-cpus", "" + cpuset)
+            .addDockerOpts("--cpu-period=" + period)
+            .addDockerOpts("--cpu-quota=" + quota)
+            .addDockerOpts("--cpu-shares=" + shares);
+
+        if (!usePreferContainerQuotaForCPUCount) opts.addJavaOpts("-XX:-PreferContainerQuotaForCPUCount");
+
+        Common.run(opts)
+            .shouldMatch("active_processor_count.*" + expectedAPC);
+    }
+
+
+    private static void testCpuShares(int shares, int expectedAPC) throws Exception {
+        Common.logNewTestCase("test cpu shares, shares = " + shares);
+        System.out.println("expectedAPC = " + expectedAPC);
+
+        expectedAPC = adjustExpectedAPCForAvailableCPUs(expectedAPC);
+
+        DockerRunOptions opts = Common.newOpts(imageName)
+            .addDockerOpts("--cpu-shares=" + shares);
+        Common.run(opts)
+            .shouldMatch("CPU Shares is.*" + shares)
+            .shouldMatch("active_processor_count.*" + expectedAPC);
+    }
+}
diff --git a/test/runtime/containers/docker/TestCPUSets.java b/test/runtime/containers/docker/TestCPUSets.java
new file mode 100644
index 0000000..baf0eba
--- /dev/null
+++ b/test/runtime/containers/docker/TestCPUSets.java
@@ -0,0 +1,137 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+
+/*
+ * @test
+ * @summary Test JVM's awareness of cpu sets (cpus and mems)
+ * @library /testlibrary /testlibrary/whitebox
+ * @build AttemptOOM CPUSetsReader sun.hotspot.WhiteBox PrintContainerInfo
+ * @run driver ClassFileInstaller -jar whitebox.jar sun.hotspot.WhiteBox sun.hotspot.WhiteBox$WhiteBoxPermission
+ * @run driver TestCPUSets
+ */
+
+import java.util.List;
+import com.oracle.java.testlibrary.Common;
+import com.oracle.java.testlibrary.DockerRunOptions;
+import com.oracle.java.testlibrary.DockerTestUtils;
+import com.oracle.java.testlibrary.Asserts;
+import com.oracle.java.testlibrary.Platform;
+import com.oracle.java.testlibrary.Utils;
+import com.oracle.java.testlibrary.OutputAnalyzer;
+
+
+public class TestCPUSets {
+    private static final String imageName = Common.imageName("cpusets");
+
+    public static void main(String[] args) throws Exception {
+        if (!DockerTestUtils.canTestDocker()) {
+            return;
+        }
+
+        Common.prepareWhiteBox();
+        DockerTestUtils.buildJdkDockerImage(imageName, "Dockerfile-BasicTest", "jdk-docker");
+
+        try {
+            // Sanity test the cpu sets reader and parser
+            CPUSetsReader.test();
+            testTheSet("Cpus_allowed_list");
+            testTheSet("Mems_allowed_list");
+        } finally {
+            DockerTestUtils.removeDockerImage(imageName);
+        }
+    }
+
+
+    private static void testTheSet(String setType) throws Exception {
+        String cpuSetStr = CPUSetsReader.readFromProcStatus(setType);
+
+        if (cpuSetStr == null) {
+            System.out.printf("The %s test is skipped %n", setType);
+        } else {
+            List<Integer> cpuSet = CPUSetsReader.parseCpuSet(cpuSetStr);
+
+            // Test subset of one, full subset, and half of the subset
+            testCpuSet(CPUSetsReader.listToString(cpuSet, 1));
+            if (cpuSet.size() > 1) {
+                testCpuSet(CPUSetsReader.listToString(cpuSet));
+            }
+            if (cpuSet.size() > 2) {
+                testCpuSet(CPUSetsReader.listToString(cpuSet, cpuSet.size()/2 ));
+            }
+        }
+    }
+
+
+    private static DockerRunOptions commonOpts() {
+        DockerRunOptions opts = new DockerRunOptions(imageName, "/jdk/bin/java",
+                                                     "PrintContainerInfo");
+        opts.addDockerOpts("--volume", Utils.TEST_CLASSES + ":/test-classes/");
+        opts.addJavaOpts("-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintContainerInfo", "-cp", "/test-classes/");
+        Common.addWhiteBoxOpts(opts);
+        return opts;
+    }
+
+
+    private static void checkResult(List<String> lines, String lineMarker, String value) {
+        boolean lineMarkerFound = false;
+
+        for (String line : lines) {
+            if (line.contains(lineMarker)) {
+                lineMarkerFound = true;
+                String[] parts = line.split(":");
+                System.out.println("DEBUG: line = " + line);
+                System.out.println("DEBUG: parts.length = " + parts.length);
+
+                Asserts.assertEquals(parts.length, 2);
+                String set = parts[1].replaceAll("\\s","");
+                String actual = CPUSetsReader.listToString(CPUSetsReader.parseCpuSet(set));
+                Asserts.assertEquals(actual, value);
+                break;
+            }
+        }
+        Asserts.assertTrue(lineMarkerFound);
+    }
+
+
+    private static void testCpuSet(String value) throws Exception {
+        Common.logNewTestCase("cpusets.cpus, value = " + value);
+
+        DockerRunOptions opts = commonOpts();
+        opts.addDockerOpts("--cpuset-cpus=" + value);
+
+        List<String> lines = Common.run(opts).asLines();
+        checkResult(lines, "cpuset.cpus is:", value);
+    }
+
+    private static void testMemSet(String value) throws Exception {
+        Common.logNewTestCase("cpusets.mems, value = " + value);
+
+        DockerRunOptions opts = commonOpts();
+        opts.addDockerOpts("--cpuset-mems=" + value);
+
+        List<String> lines = Common.run(opts).asLines();
+        checkResult(lines, "cpuset.mems is:", value);
+    }
+
+}
diff --git a/test/runtime/containers/docker/TestMemoryAwareness.java b/test/runtime/containers/docker/TestMemoryAwareness.java
new file mode 100644
index 0000000..415f2c9
--- /dev/null
+++ b/test/runtime/containers/docker/TestMemoryAwareness.java
@@ -0,0 +1,109 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+
+/*
+ * @test
+ * @summary Test JVM's memory resource awareness when running inside docker container
+ * @library /testlibrary /testlibrary/whitebox
+ * @build AttemptOOM sun.hotspot.WhiteBox PrintContainerInfo
+ * @run driver ClassFileInstaller -jar whitebox.jar sun.hotspot.WhiteBox sun.hotspot.WhiteBox$WhiteBoxPermission
+ * @run driver TestMemoryAwareness
+ */
+
+import com.oracle.java.testlibrary.Common;
+import com.oracle.java.testlibrary.DockerRunOptions;
+import com.oracle.java.testlibrary.DockerTestUtils;
+
+
+public class TestMemoryAwareness {
+    private static final String imageName = Common.imageName("memory");
+
+    public static void main(String[] args) throws Exception {
+        if (!DockerTestUtils.canTestDocker()) {
+            return;
+        }
+
+        Common.prepareWhiteBox();
+        DockerTestUtils.buildJdkDockerImage(imageName, "Dockerfile-BasicTest", "jdk-docker");
+
+        try {
+            testMemoryLimit("100m", "104857600");
+            testMemoryLimit("500m", "524288000");
+            testMemoryLimit("1g", "1073741824");
+            testMemoryLimit("4g", "4294967296");
+
+            testMemorySoftLimit("500m", "524288000");
+            testMemorySoftLimit("1g", "1073741824");
+
+            // Add extra 10 Mb to allocator limit, to be sure to cause OOM
+            testOOM("256m", 256 + 10);
+
+        } finally {
+            DockerTestUtils.removeDockerImage(imageName);
+        }
+    }
+
+
+    private static void testMemoryLimit(String valueToSet, String expectedTraceValue)
+            throws Exception {
+
+        Common.logNewTestCase("memory limit: " + valueToSet);
+
+        DockerRunOptions opts = Common.newOpts(imageName)
+            .addDockerOpts("--memory", valueToSet);
+
+        Common.run(opts)
+            .shouldMatch("Memory Limit is:.*" + expectedTraceValue);
+    }
+
+
+    private static void testMemorySoftLimit(String valueToSet, String expectedTraceValue)
+            throws Exception {
+        Common.logNewTestCase("memory soft limit: " + valueToSet);
+
+        DockerRunOptions opts = Common.newOpts(imageName, "PrintContainerInfo");
+        Common.addWhiteBoxOpts(opts);
+        opts.addDockerOpts("--memory-reservation=" + valueToSet);
+
+        Common.run(opts)
+            .shouldMatch("Memory Soft Limit.*" + expectedTraceValue);
+    }
+
+
+    // provoke OOM inside the container, see how VM reacts
+    private static void testOOM(String dockerMemLimit, int sizeToAllocInMb) throws Exception {
+        Common.logNewTestCase("OOM");
+
+        DockerRunOptions opts = Common.newOpts(imageName, "AttemptOOM")
+            .addDockerOpts("--memory", dockerMemLimit, "--memory-swap", dockerMemLimit);
+        opts.classParams.add("" + sizeToAllocInMb);
+
+        DockerTestUtils.dockerRunJava(opts)
+            .shouldHaveExitValue(1)
+            .shouldContain("Entering AttemptOOM main")
+            .shouldNotContain("AttemptOOM allocation successful")
+            .shouldContain("java.lang.OutOfMemoryError");
+    }
+
+}
diff --git a/test/runtime/containers/docker/TestMisc.java b/test/runtime/containers/docker/TestMisc.java
new file mode 100644
index 0000000..efd5227
--- /dev/null
+++ b/test/runtime/containers/docker/TestMisc.java
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+
+/*
+ * @test
+ * @summary Test miscellanous functionality related to JVM running in docker container
+ * @library /testlibrary /testlibrary/whitebox
+ * @build CheckContainerized sun.hotspot.WhiteBox PrintContainerInfo
+ * @run driver ClassFileInstaller -jar whitebox.jar sun.hotspot.WhiteBox sun.hotspot.WhiteBox$WhiteBoxPermission
+ * @run driver TestMisc
+ */
+
+import com.oracle.java.testlibrary.Common;
+import com.oracle.java.testlibrary.DockerTestUtils;
+import com.oracle.java.testlibrary.DockerRunOptions;
+import com.oracle.java.testlibrary.OutputAnalyzer;
+import com.oracle.java.testlibrary.ProcessTools;
+
+
+public class TestMisc {
+    private static final String imageName = Common.imageName("misc");
+
+    public static void main(String[] args) throws Exception {
+        if (!DockerTestUtils.canTestDocker()) {
+            return;
+        }
+
+        Common.prepareWhiteBox();
+        DockerTestUtils.buildJdkDockerImage(imageName, "Dockerfile-BasicTest", "jdk-docker");
+
+        try {
+            testMinusContainerSupport();
+            testIsContainerized();
+            testPrintContainerInfo();
+        } finally {
+            DockerTestUtils.removeDockerImage(imageName);
+        }
+    }
+
+
+    private static void testMinusContainerSupport() throws Exception {
+        Common.logNewTestCase("Test related flags: '-UseContainerSupport'");
+        DockerRunOptions opts = new DockerRunOptions(imageName, "/jdk/bin/java", "-version");
+        opts.addJavaOpts("-XX:+UnlockDiagnosticVMOptions", "-XX:-UseContainerSupport", "-XX:+PrintContainerInfo");
+
+        Common.run(opts)
+            .shouldContain("Container Support not enabled");
+    }
+
+
+    private static void testIsContainerized() throws Exception {
+        Common.logNewTestCase("Test is_containerized() inside a docker container");
+
+        DockerRunOptions opts = Common.newOpts(imageName, "CheckContainerized");
+        Common.addWhiteBoxOpts(opts);
+
+        Common.run(opts)
+            .shouldContain(CheckContainerized.INSIDE_A_CONTAINER);
+    }
+
+
+    private static void testPrintContainerInfo() throws Exception {
+        Common.logNewTestCase("Test print_container_info()");
+
+        DockerRunOptions opts = Common.newOpts(imageName, "PrintContainerInfo");
+        Common.addWhiteBoxOpts(opts);
+
+        checkContainerInfo(Common.run(opts));
+    }
+
+
+    private static void checkContainerInfo(OutputAnalyzer out) throws Exception {
+        String[] expectedToContain = new String[] {
+            "cpuset.cpus",
+            "cpuset.mems",
+            "CPU Shares",
+            "CPU Quota",
+            "CPU Period",
+            "OSContainer::active_processor_count",
+            "Memory Limit",
+            "Memory Soft Limit",
+            "Memory Usage",
+            "Maximum Memory Usage",
+            "memory_max_usage_in_bytes"
+        };
+
+        for (String s : expectedToContain) {
+            out.shouldContain(s);
+        }
+    }
+
+}
diff --git a/test/runtime/execstack/TestCheckJDK.java b/test/runtime/execstack/TestCheckJDK.java
new file mode 100644
index 0000000..e22d603
--- /dev/null
+++ b/test/runtime/execstack/TestCheckJDK.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * 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 Testexecstack.java
+ * @summary Searches for all libraries in test VM and checks that they
+ *          have the noexecstack bit set.
+ * @requires (os.family == "linux")
+ * @library /testlibrary /testlibrary/whitebox
+ * @build sun.hotspot.WhiteBox
+ * @run driver ClassFileInstaller sun.hotspot.WhiteBox
+ *                                sun.hotspot.WhiteBox$WhiteBoxPermission
+ * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI
+ *                   TestCheckJDK
+ */
+
+import com.oracle.java.testlibrary.Asserts;
+import sun.hotspot.WhiteBox;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
+public class TestCheckJDK {
+    static boolean testPassed = true;
+    private static final WhiteBox WB = WhiteBox.getWhiteBox();
+
+    static void checkExecStack(Path file) {
+        String filename = file.toString();
+        if (filename.endsWith(".so")) {
+            if (!WB.checkLibSpecifiesNoexecstack(filename)) {
+                System.out.println("Library does not have the noexecstack bit set: " + filename);
+                testPassed = false;
+            }
+        }
+    }
+
+    public static void main(String[] args) throws Throwable {
+        String vmInstallDir = System.getProperty("java.home");
+
+        Files.walk(Paths.get(vmInstallDir)).filter(Files::isRegularFile).forEach(TestCheckJDK::checkExecStack);
+
+        Asserts.assertTrue(testPassed,
+            "The tested VM contains libs that don't have the noexecstack " +
+            "bit set. They must be linked with -z,noexecstack.");
+    }
+}
diff --git a/test/serviceability/dcmd/ClassLoaderStatsTest.java b/test/serviceability/dcmd/ClassLoaderStatsTest.java
new file mode 100644
index 0000000..c22b080
--- /dev/null
+++ b/test/serviceability/dcmd/ClassLoaderStatsTest.java
@@ -0,0 +1,155 @@
+/*
+ * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ *
+ * @build ClassLoaderStatsTest DcmdUtil
+ * @run main ClassLoaderStatsTest
+ */
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.StringReader;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class ClassLoaderStatsTest {
+
+    // ClassLoader         Parent              CLD*               Classes   ChunkSz   BlockSz  Type
+    // 0x00000007c0215928  0x0000000000000000  0x0000000000000000       0         0         0  org.eclipse.osgi.baseadaptor.BaseAdaptor$1
+    // 0x00000007c0009868  0x0000000000000000  0x00007fc52aebcc80       1      6144      3768  sun.reflect.DelegatingClassLoader
+    // 0x00000007c0009868  0x0000000000000000  0x00007fc52b8916d0       1      6144      3688  sun.reflect.DelegatingClassLoader
+    // 0x00000007c0009868  0x00000007c0038ba8  0x00007fc52afb8760       1      6144      3688  sun.reflect.DelegatingClassLoader
+    // 0x00000007c0009868  0x0000000000000000  0x00007fc52afbb1a0       1      6144      3688  sun.reflect.DelegatingClassLoader
+    // 0x0000000000000000  0x0000000000000000  0x00007fc523416070    5019  30060544  29956216  <boot classloader>
+    //                                                                455   1210368    672848   + unsafe anonymous classes
+    // 0x00000007c016b5c8  0x00000007c0038ba8  0x00007fc52a995000       5      8192      5864  org.netbeans.StandardModule$OneModuleClassLoader
+    // 0x00000007c0009868  0x00000007c016b5c8  0x00007fc52ac13640       1      6144      3896  sun.reflect.DelegatingClassLoader
+    // ...
+
+    static Pattern clLine = Pattern.compile("0x\\p{XDigit}*\\s*0x\\p{XDigit}*\\s*0x\\p{XDigit}*\\s*(\\d*)\\s*(\\d*)\\s*(\\d*)\\s*(.*)");
+    static Pattern anonLine = Pattern.compile("\\s*(\\d*)\\s*(\\d*)\\s*(\\d*)\\s*.*");
+
+    public static DummyClassLoader dummyloader;
+
+    public static void main(String arg[]) throws Exception {
+
+        // create a classloader and load our special class
+        dummyloader = new DummyClassLoader();
+        Class<?> c = Class.forName("TestClass", true, dummyloader);
+        if (c.getClassLoader() != dummyloader) {
+            throw new RuntimeException("TestClass defined by wrong classloader: " + c.getClassLoader());
+        }
+
+        String result = DcmdUtil.executeDcmd("VM.classloader_stats");
+        BufferedReader r = new BufferedReader(new StringReader(result));
+        String line;
+        while((line = r.readLine()) != null) {
+            Matcher m = clLine.matcher(line);
+            if (m.matches()) {
+                // verify that DummyClassLoader has loaded 1 class and 1 anonymous class
+                if (m.group(4).equals("ClassLoaderStatsTest$DummyClassLoader")) {
+                    System.out.println("line: " + line);
+                    if (!m.group(1).equals("1")) {
+                        throw new Exception("Should have loaded 1 class: " + line);
+                    }
+                    checkPositiveInt(m.group(2));
+                    checkPositiveInt(m.group(3));
+
+                    String next = r.readLine();
+                    System.out.println("next: " + next);
+                    Matcher m1 = anonLine.matcher(next);
+                    m1.matches();
+                    if (!m1.group(1).equals("1")) {
+                        throw new Exception("Should have loaded 1 anonymous class, but found : " + m1.group(1));
+                    }
+                    checkPositiveInt(m1.group(2));
+                    checkPositiveInt(m1.group(3));
+                }
+            }
+        }
+    }
+
+    private static void checkPositiveInt(String s) throws Exception {
+        if (Integer.parseInt(s) <= 0) {
+            throw new Exception("Value should have been > 0: " + s);
+        }
+    }
+
+    public static class DummyClassLoader extends ClassLoader {
+
+        public static final String CLASS_NAME = "TestClass";
+
+        static ByteBuffer readClassFile(String name)
+        {
+            File f = new File(System.getProperty("test.classes", "."),
+                              name);
+            try (FileInputStream fin = new FileInputStream(f);
+                 FileChannel fc = fin.getChannel())
+            {
+                return fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
+            } catch (IOException e) {
+                throw new RuntimeException("Can't open file: " + name, e);
+            }
+        }
+
+        protected Class<?> loadClass(String name, boolean resolve)
+            throws ClassNotFoundException
+        {
+            Class<?> c;
+            if (!"TestClass".equals(name)) {
+                c = super.loadClass(name, resolve);
+            } else {
+                // should not delegate to the system class loader
+                c = findClass(name);
+                if (resolve) {
+                    resolveClass(c);
+                }
+            }
+            return c;
+        }
+
+        protected Class<?> findClass(String name)
+            throws ClassNotFoundException
+        {
+            if (!"TestClass".equals(name)) {
+                throw new ClassNotFoundException("Unexpected class: " + name);
+            }
+            return defineClass(name, readClassFile(name + ".class"), null);
+        }
+    } /* DummyClassLoader */
+
+}
+
+class TestClass {
+    static {
+        // force creation of anonymous class (for the lambdaform)
+        Runnable r = () -> System.out.println("Hello");
+        r.run();
+    }
+}
diff --git a/test/serviceability/dcmd/DcmdUtil.java b/test/serviceability/dcmd/DcmdUtil.java
new file mode 100644
index 0000000..2542e67
--- /dev/null
+++ b/test/serviceability/dcmd/DcmdUtil.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import sun.management.ManagementFactoryHelper;
+
+import com.sun.management.DiagnosticCommandMBean;
+
+public class DcmdUtil
+{
+    public static String executeDcmd(String cmd, String ... args) {
+        DiagnosticCommandMBean dcmd = ManagementFactoryHelper.getDiagnosticCommandMBean();
+        Object[] dcmdArgs = {args};
+        String[] signature = {String[].class.getName()};
+
+        try {
+            System.out.print("> " + cmd + " ");
+            for (String s : args) {
+                System.out.print(s + " ");
+            }
+            System.out.println(":");
+            String result = (String) dcmd.invoke(transform(cmd), dcmdArgs, signature);
+            System.out.println(result);
+            return result;
+        } catch(Exception ex) {
+            ex.printStackTrace();
+        }
+        return null;
+    }
+
+    private static String transform(String name) {
+        StringBuilder sb = new StringBuilder();
+        boolean toLower = true;
+        boolean toUpper = false;
+        for (int i = 0; i < name.length(); i++) {
+            char c = name.charAt(i);
+            if (c == '.' || c == '_') {
+                toLower = false;
+                toUpper = true;
+            } else {
+                if (toUpper) {
+                    toUpper = false;
+                    sb.append(Character.toUpperCase(c));
+                } else if(toLower) {
+                    sb.append(Character.toLowerCase(c));
+                } else {
+                    sb.append(c);
+                }
+            }
+        }
+        return sb.toString();
+    }
+
+}
diff --git a/test/serviceability/dcmd/DynLibDcmdTest.java b/test/serviceability/dcmd/DynLibDcmdTest.java
new file mode 100644
index 0000000..c1a4a92
--- /dev/null
+++ b/test/serviceability/dcmd/DynLibDcmdTest.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.util.HashSet;
+import java.util.Set;
+import com.oracle.java.testlibrary.Platform;
+
+/*
+ * @test
+ * @summary Test of VM.dynlib diagnostic command via MBean
+ * @library /testlibrary
+ * @compile DcmdUtil.java
+ * @run main DynLibDcmdTest
+ */
+
+public class DynLibDcmdTest {
+
+    public static void main(String[] args) throws Exception {
+        String result = DcmdUtil.executeDcmd("VM.dynlibs");
+
+        String osDependentBaseString = null;
+        if (Platform.isSolaris()) {
+            osDependentBaseString = "lib%s.so";
+        } else if (Platform.isWindows()) {
+            osDependentBaseString = "%s.dll";
+        } else if (Platform.isOSX()) {
+            osDependentBaseString = "lib%s.dylib";
+        } else if (Platform.isLinux()) {
+            osDependentBaseString = "lib%s.so";
+        }
+
+        if (osDependentBaseString == null) {
+            throw new Exception("Unsupported OS");
+        }
+
+        Set<String> expectedContent = new HashSet<>();
+        expectedContent.add(String.format(osDependentBaseString, "jvm"));
+        expectedContent.add(String.format(osDependentBaseString, "java"));
+        expectedContent.add(String.format(osDependentBaseString, "management"));
+
+        for(String expected : expectedContent) {
+            if (!result.contains(expected)) {
+                throw new Exception("Dynamic library list output did not contain the expected string: '" + expected + "'");
+            }
+        }
+    }
+}
diff --git a/test/serviceability/dcmd/gc/FinalizerInfoTest.java b/test/serviceability/dcmd/gc/FinalizerInfoTest.java
new file mode 100644
index 0000000..deb7661
--- /dev/null
+++ b/test/serviceability/dcmd/gc/FinalizerInfoTest.java
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import com.oracle.java.testlibrary.JDKToolFinder;
+import com.oracle.java.testlibrary.OutputAnalyzer;
+import com.oracle.java.testlibrary.ProcessTools;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.Condition;
+import java.util.concurrent.locks.ReentrantLock;
+
+/*
+ * @test
+ * @summary
+ * @library /testlibrary
+ * @run main FinalizerInfoTest
+ */
+public class FinalizerInfoTest {
+    static ReentrantLock lock = new ReentrantLock();
+    static volatile int wasInitialized = 0;
+    static volatile int wasTrapped = 0;
+    static final String cmd = "GC.finalizer_info";
+    static final int objectsCount = 1000;
+
+    class MyObject {
+        public MyObject() {
+            // Make sure object allocation/deallocation is not optimized out
+            wasInitialized += 1;
+        }
+
+        protected void finalize() {
+            // Trap the object in a finalization queue
+            wasTrapped += 1;
+            lock.lock();
+        }
+    }
+
+    void run() throws Exception {
+        try {
+            lock.lock();
+            for(int i = 0; i < objectsCount; ++i) {
+                new MyObject();
+            }
+            System.out.println("Objects initialized: " + objectsCount);
+            System.gc();
+
+            while(wasTrapped < 1) {
+                // Waiting for gc thread.
+            }
+
+
+            String pid = Integer.toString(ProcessTools.getProcessId());
+            ProcessBuilder pb = new ProcessBuilder();
+            pb.command(new String[] { JDKToolFinder.getJDKTool("jcmd"), pid, cmd});
+            OutputAnalyzer output = new OutputAnalyzer(pb.start());
+            output.shouldContain("MyObject");
+        } finally {
+            lock.unlock();
+        }
+    }
+
+    public static void main(String[] args) throws Exception {
+        new  FinalizerInfoTest().run();
+    }
+
+
+}
diff --git a/test/serviceability/dcmd/gc/HeapInfoTest.java b/test/serviceability/dcmd/gc/HeapInfoTest.java
new file mode 100644
index 0000000..23355cd
--- /dev/null
+++ b/test/serviceability/dcmd/gc/HeapInfoTest.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import com.oracle.java.testlibrary.JDKToolFinder;
+import com.oracle.java.testlibrary.OutputAnalyzer;
+import com.oracle.java.testlibrary.ProcessTools;
+
+/*
+ * @test
+ * @summary Test of diagnostic command GC.heap_info
+ * @library /testlibrary
+ * @run main HeapInfoTest
+ */
+public class HeapInfoTest {
+
+    public static void main(String[] args) throws Exception {
+        String pid = Integer.toString(ProcessTools.getProcessId());
+        ProcessBuilder pb = new ProcessBuilder();
+        pb.command(new String[] { JDKToolFinder.getJDKTool("jcmd"), pid, "GC.heap_info"});
+        OutputAnalyzer output = new OutputAnalyzer(pb.start());
+        output.shouldContain("Metaspace");
+    }
+}
+
diff --git a/test/serviceability/sa/TestRevPtrsForInvokeDynamic.java b/test/serviceability/sa/TestRevPtrsForInvokeDynamic.java
new file mode 100644
index 0000000..22b2bd7
--- /dev/null
+++ b/test/serviceability/sa/TestRevPtrsForInvokeDynamic.java
@@ -0,0 +1,105 @@
+/*
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.util.ArrayList;
+import java.util.List;
+
+import sun.jvm.hotspot.HotSpotAgent;
+import sun.jvm.hotspot.utilities.ReversePtrsAnalysis;
+
+import jdk.test.lib.apps.LingeredApp;
+import jdk.test.lib.Asserts;
+import jdk.test.lib.JDKToolFinder;
+import jdk.test.lib.JDKToolLauncher;
+import jdk.test.lib.Platform;
+import jdk.test.lib.process.OutputAnalyzer;
+import jdk.test.lib.process.ProcessTools;
+import jdk.test.lib.Utils;
+
+/*
+ * @test
+ * @library /test/lib
+ * @requires os.family != "mac"
+ * @modules java.base/jdk.internal.misc
+ *          jdk.hotspot.agent/sun.jvm.hotspot
+ *          jdk.hotspot.agent/sun.jvm.hotspot.utilities
+ * @run main/othervm TestRevPtrsForInvokeDynamic
+ */
+
+public class TestRevPtrsForInvokeDynamic {
+
+    private static LingeredAppWithInvokeDynamic theApp = null;
+
+    private static void computeReversePointers(String pid) throws Exception {
+        HotSpotAgent agent = new HotSpotAgent();
+
+        try {
+            agent.attach(Integer.parseInt(pid));
+            ReversePtrsAnalysis analysis = new ReversePtrsAnalysis();
+            analysis.run();
+        } finally {
+            agent.detach();
+        }
+    }
+
+    private static void createAnotherToAttach(long lingeredAppPid)
+            throws Exception {
+        String[] toolArgs = {
+                "--add-modules=jdk.hotspot.agent",
+                "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot=ALL-UNNAMED",
+                "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot.utilities=ALL-UNNAMED",
+                "TestRevPtrsForInvokeDynamic",
+                Long.toString(lingeredAppPid)
+        };
+
+        // Start a new process to attach to the lingered app
+        ProcessBuilder processBuilder = ProcessTools.createJavaProcessBuilder(toolArgs);
+        OutputAnalyzer SAOutput = ProcessTools.executeProcess(processBuilder);
+        SAOutput.shouldHaveExitValue(0);
+        System.out.println(SAOutput.getOutput());
+    }
+
+    public static void main(String... args) throws Exception {
+        if (!Platform.shouldSAAttach()) {
+            System.out.println(
+                    "SA attach not expected to work - test skipped.");
+            return;
+        }
+
+        if (args == null || args.length == 0) {
+            try {
+                List<String> vmArgs = new ArrayList<String>();
+                vmArgs.add("-XX:+UsePerfData");
+                vmArgs.addAll(Utils.getVmOptions());
+
+                theApp = new LingeredAppWithInvokeDynamic();
+                LingeredApp.startApp(vmArgs, theApp);
+                createAnotherToAttach(theApp.getPid());
+            } finally {
+                LingeredApp.stopApp(theApp);
+            }
+        } else {
+            computeReversePointers(args[0]);
+        }
+    }
+}
\ No newline at end of file
diff --git a/test/test_env.sh b/test/test_env.sh
index 27c653b..e76796e 100644
--- a/test/test_env.sh
+++ b/test/test_env.sh
@@ -185,6 +185,15 @@
 if [ $? = 0 ]
 then
   VM_CPU="ppc"
+  if [ $VM_BITS = "64" ]
+  then
+    VM_CPU="ppc64"
+    grep "ppc64le" vm_version.out > ${NULL}
+    if [ $? = 0 ]
+    then
+      VM_CPU="ppc64le"
+    fi
+  fi
 fi
 grep "ia64" vm_version.out > ${NULL}
 if [ $? = 0 ]
diff --git a/test/testlibrary/ClassFileInstaller.java b/test/testlibrary/ClassFileInstaller.java
index 303e96e..d319e45 100644
--- a/test/testlibrary/ClassFileInstaller.java
+++ b/test/testlibrary/ClassFileInstaller.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -21,28 +21,229 @@
  * questions.
  */
 
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.FileNotFoundException;
 import java.io.InputStream;
+import java.io.ByteArrayInputStream;
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.nio.file.Paths;
 import java.nio.file.StandardCopyOption;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
 
 /**
- * Dump a class file for a class on the class path in the current directory
+ * Dump a class file for a class on the class path in the current directory, or
+ * in the specified JAR file. This class is usually used when you build a class
+ * from a test library, but want to use this class in a sub-process.
+ *
+ * For example, to build the following library class:
+ * test/lib/sun/hotspot/WhiteBox.java
+ *
+ * You would use the following tags:
+ *
+ * @library /test/lib
+ * @build sun.hotspot.WhiteBox
+ *
+ * JTREG would build the class file under
+ * ${JTWork}/classes/test/lib/sun/hotspot/WhiteBox.class
+ *
+ * With you run your main test class using "@run main MyMainClass", JTREG would setup the
+ * -classpath to include "${JTWork}/classes/test/lib/", so MyMainClass would be able to
+ * load the WhiteBox class.
+ *
+ * However, if you run a sub process, and do not wish to use the exact same -classpath,
+ * You can use ClassFileInstaller to ensure that WhiteBox is available in the current
+ * directory of your test:
+ *
+ * @run main ClassFileInstaller sun.hotspot.WhiteBox
+ *
+ * Or, you can use the -jar option to store the class in the specified JAR file. If a relative
+ * path name is given, the JAR file would be relative to the current directory of
+ *
+ * @run main ClassFileInstaller -jar myjar.jar sun.hotspot.WhiteBox
  */
 public class ClassFileInstaller {
     /**
+     * You can enable debug tracing of ClassFileInstaller by running JTREG with
+     * jtreg -DClassFileInstaller.debug=true ... <names of tests>
+     */
+    public static boolean DEBUG = Boolean.getBoolean("ClassFileInstaller.debug");
+
+    /**
      * @param args The names of the classes to dump
      * @throws Exception
      */
     public static void main(String... args) throws Exception {
-        for (String arg : args) {
-            ClassLoader cl = ClassFileInstaller.class.getClassLoader();
+        if (args.length > 1 && args[0].equals("-jar")) {
+            if (args.length < 2) {
+                throw new RuntimeException("Usage: ClassFileInstaller <options> <classes>\n" +
+                                           "where possible options include:\n" +
+                                           "  -jar <path>             Write to the JAR file <path>");
+            }
+            writeJar(args[1], null, args, 2, args.length);
+        } else {
+            if (DEBUG) {
+                System.out.println("ClassFileInstaller: Writing to " + System.getProperty("user.dir"));
+            }
+            for (String arg : args) {
+                writeClassToDisk(arg);
+            }
+        }
+    }
 
-            // Convert dotted class name to a path to a class file
-            String pathName = arg.replace('.', '/').concat(".class");
-            InputStream is = cl.getResourceAsStream(pathName);
+    public static class Manifest {
+        private InputStream in;
 
+        private Manifest(InputStream in) {
+            this.in = in;
+        }
+
+        static Manifest fromSourceFile(String fileName) throws Exception {
+            String pathName = System.getProperty("test.src") + File.separator + fileName;
+            return new Manifest(new FileInputStream(pathName));
+        }
+
+        // Example:
+        //  String manifest = "Premain-Class: RedefineClassHelper\n" +
+        //                "Can-Redefine-Classes: true\n";
+        //  ClassFileInstaller.writeJar("redefineagent.jar",
+        //    ClassFileInstaller.Manifest.fromString(manifest),
+        //    "RedefineClassHelper");
+        static Manifest fromString(String manifest) throws Exception {
+            return new Manifest(new ByteArrayInputStream(manifest.getBytes()));
+        }
+
+        public InputStream getInputStream() {
+            return in;
+        }
+    }
+
+    private static void writeJar(String jarFile, Manifest manifest, String classes[], int from, int to) throws Exception {
+        if (DEBUG) {
+            System.out.println("ClassFileInstaller: Writing to " + getJarPath(jarFile));
+        }
+
+        (new File(jarFile)).delete();
+        FileOutputStream fos = new FileOutputStream(jarFile);
+        ZipOutputStream zos = new ZipOutputStream(fos);
+
+        // The manifest must be the first or second entry. See comments in JarInputStream
+        // constructor and JDK-5046178.
+        if (manifest != null) {
+            writeToDisk(zos, "META-INF/MANIFEST.MF", manifest.getInputStream());
+        }
+
+        for (int i=from; i<to; i++) {
+            writeClassToDisk(zos, classes[i]);
+        }
+
+        zos.close();
+        fos.close();
+    }
+
+    /*
+     * You can call ClassFileInstaller.writeJar() from your main test class instead of
+     * using "@run ClassFileInstaller -jar ...". E.g.,
+     *
+     * String jarPath = ClassFileInstaller.getJarPath("myjar.jar", "sun.hotspot.WhiteBox")
+     *
+     * If you call this API, make sure you build ClassFileInstaller with the following tags:
+     *
+     * @library testlibrary
+     * @build ClassFileInstaller
+     */
+    public static String writeJar(String jarFile, String... classes) throws Exception {
+        writeJar(jarFile, null, classes, 0, classes.length);
+        return getJarPath(jarFile);
+    }
+
+    public static String writeJar(String jarFile, Manifest manifest, String... classes) throws Exception {
+        writeJar(jarFile, manifest, classes, 0, classes.length);
+        return getJarPath(jarFile);
+    }
+
+    /**
+     * This returns the absolute path to the file specified in "@ClassFileInstaller -jar myjar.jar",
+     * In your test program, instead of using the JAR file name directly:
+     *
+     * String jarPath = "myjar.jar";
+     *
+     * you should call this function, like:
+     *
+     * String jarPath = ClassFileInstaller.getJarPath("myjar.jar")
+     *
+     * The reasons are:
+     * (1) Using absolute path makes it easy to cut-and-paste from the JTR file and rerun your
+     *     test in any directory.
+     * (2) In the future, we may make the JAR file name unique to avoid clobbering
+     *     during parallel JTREG execution.
+     *
+     */
+    public static String getJarPath(String jarFileName) {
+        return new File(jarFileName).getAbsolutePath();
+    }
+
+    public static void writeClassToDisk(String className) throws Exception {
+        writeClassToDisk((ZipOutputStream)null, className);
+    }
+    private static void writeClassToDisk(ZipOutputStream zos, String className) throws Exception {
+        writeClassToDisk(zos, className, "");
+    }
+
+    public static void writeClassToDisk(String className, String prependPath) throws Exception {
+        writeClassToDisk(null, className, prependPath);
+    }
+    private static void writeClassToDisk(ZipOutputStream zos, String className, String prependPath) throws Exception {
+        ClassLoader cl = ClassFileInstaller.class.getClassLoader();
+
+        // Convert dotted class name to a path to a class file
+        String pathName = className.replace('.', '/').concat(".class");
+        InputStream is = cl.getResourceAsStream(pathName);
+        if (is == null) {
+            throw new RuntimeException("Failed to find " + pathName);
+        }
+        if (prependPath.length() > 0) {
+            pathName = prependPath + "/" + pathName;
+        }
+        writeToDisk(zos, pathName, is);
+    }
+
+    public static void writeClassToDisk(String className, byte[] bytecode) throws Exception {
+        writeClassToDisk(null, className, bytecode);
+    }
+    private static void writeClassToDisk(ZipOutputStream zos, String className, byte[] bytecode) throws Exception {
+        writeClassToDisk(zos, className, bytecode, "");
+    }
+
+    public static void writeClassToDisk(String className, byte[] bytecode, String prependPath) throws Exception {
+        writeClassToDisk(null, className, bytecode, prependPath);
+    }
+    private static void writeClassToDisk(ZipOutputStream zos, String className, byte[] bytecode, String prependPath) throws Exception {
+        // Convert dotted class name to a path to a class file
+        String pathName = className.replace('.', '/').concat(".class");
+        if (prependPath.length() > 0) {
+            pathName = prependPath + "/" + pathName;
+        }
+        writeToDisk(zos, pathName, new ByteArrayInputStream(bytecode));
+    }
+
+    private static void writeToDisk(ZipOutputStream zos, String pathName, InputStream is) throws Exception {
+        if (DEBUG) {
+            System.out.println("ClassFileInstaller: Writing " + pathName);
+        }
+        if (zos != null) {
+            ZipEntry ze = new ZipEntry(pathName);
+            zos.putNextEntry(ze);
+            byte[] buf = new byte[1024];
+            int len;
+            while ((len = is.read(buf))>0){
+                zos.write(buf, 0, len);
+            }
+        } else {
             // Create the class file's package directory
             Path p = Paths.get(pathName);
             if (pathName.contains("/")) {
@@ -51,5 +252,6 @@
             // Create the class file
             Files.copy(is, p, StandardCopyOption.REPLACE_EXISTING);
         }
+        is.close();
     }
 }
diff --git a/test/testlibrary/com/oracle/java/testlibrary/Common.java b/test/testlibrary/com/oracle/java/testlibrary/Common.java
new file mode 100644
index 0000000..3d5a529
--- /dev/null
+++ b/test/testlibrary/com/oracle/java/testlibrary/Common.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.oracle.java.testlibrary;
+
+/*
+ * Methods and definitions common to docker tests container in this directory
+ */
+
+import java.io.File;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import com.oracle.java.testlibrary.DockerTestUtils;
+import com.oracle.java.testlibrary.DockerRunOptions;
+import com.oracle.java.testlibrary.Utils;
+import com.oracle.java.testlibrary.OutputAnalyzer;
+
+
+public class Common {
+    public static final String imageNameAndTag = "jdk-internal:test";
+
+    public static String imageName(String suffix) {
+        return imageNameAndTag + "-" + suffix;
+    }
+
+    public static void prepareWhiteBox() throws Exception {
+        Path whiteboxPath = Paths.get(Utils.TEST_CLASSES, "whitebox.jar");
+        if( !Files.exists(whiteboxPath) ) {
+            Files.copy(Paths.get(new File("whitebox.jar").getAbsolutePath()),
+                   Paths.get(Utils.TEST_CLASSES, "whitebox.jar"));
+        }
+    }
+
+    // create simple commonly used options
+    public static DockerRunOptions newOpts(String imageNameAndTag) {
+        return new DockerRunOptions(imageNameAndTag, "/jdk/bin/java", "-version")
+            .addJavaOpts("-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintContainerInfo");
+    }
+
+
+    // create commonly used options with class to be launched inside container
+    public static DockerRunOptions newOpts(String imageNameAndTag, String testClass) {
+        DockerRunOptions opts =
+            new DockerRunOptions(imageNameAndTag, "/jdk/bin/java", testClass);
+       opts.addDockerOpts("--volume", Utils.TEST_CLASSES + ":/test-classes/");
+        opts.addJavaOpts("-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintContainerInfo", "-cp", "/test-classes/");
+        return opts;
+    }
+
+    public static DockerRunOptions addWhiteBoxOpts(DockerRunOptions opts) {
+        opts.addJavaOpts("-Xbootclasspath/a:/test-classes/whitebox.jar",
+                         "-XX:+UnlockDiagnosticVMOptions", "-XX:+WhiteBoxAPI");
+        return opts;
+    }
+
+    // most common type of run and checks
+    public static OutputAnalyzer run(DockerRunOptions opts) throws Exception {
+        return DockerTestUtils.dockerRunJava(opts)
+            .shouldHaveExitValue(0).shouldContain("Initializing Container Support");
+    }
+
+
+    // log beginning of a test case
+    public static void logNewTestCase(String msg) {
+        System.out.println("========== NEW TEST CASE:      " + msg);
+    }
+
+}
diff --git a/test/testlibrary/com/oracle/java/testlibrary/DockerRunOptions.java b/test/testlibrary/com/oracle/java/testlibrary/DockerRunOptions.java
new file mode 100644
index 0000000..05e3b6b
--- /dev/null
+++ b/test/testlibrary/com/oracle/java/testlibrary/DockerRunOptions.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.oracle.java.testlibrary;
+
+import java.util.ArrayList;
+import java.util.Collections;
+
+
+// This class represents options for running java inside docker containers
+// in test environment.
+public class DockerRunOptions {
+    public String imageNameAndTag;
+    public ArrayList<String> dockerOpts = new ArrayList<String>();
+    public String command;    // normally a full path to java
+    public ArrayList<String> javaOpts = new ArrayList<String>();
+    public String classToRun;  // class or "-version"
+    public ArrayList<String> classParams = new ArrayList<String>();
+
+    public boolean tty = true;
+    public boolean removeContainerAfterUse = true;
+    public boolean appendTestJavaOptions = true;
+    public boolean retainChildStdout = false;
+
+    /**
+     * Convenience constructor for most common use cases in testing.
+     * @param imageNameAndTag  a string representing name and tag for the
+     *        docker image to run, as "name:tag"
+     * @param javaCmd  a java command to run (e.g. /jdk/bin/java)
+     * @param classToRun  a class to run, or "-version"
+     * @param javaOpts  java options to use
+     *
+     * @return Default docker run options
+     */
+    public DockerRunOptions(String imageNameAndTag, String javaCmd,
+                            String classToRun, String... javaOpts) {
+        this.imageNameAndTag = imageNameAndTag;
+        this.command = javaCmd;
+        this.classToRun = classToRun;
+        this.addJavaOpts(javaOpts);
+    }
+
+    public DockerRunOptions addDockerOpts(String... opts) {
+        Collections.addAll(dockerOpts, opts);
+        return this;
+    }
+
+    public DockerRunOptions addJavaOpts(String... opts) {
+        Collections.addAll(javaOpts, opts);
+        return this;
+    }
+
+}
diff --git a/test/testlibrary/com/oracle/java/testlibrary/DockerTestUtils.java b/test/testlibrary/com/oracle/java/testlibrary/DockerTestUtils.java
new file mode 100644
index 0000000..ea125b1
--- /dev/null
+++ b/test/testlibrary/com/oracle/java/testlibrary/DockerTestUtils.java
@@ -0,0 +1,282 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.oracle.java.testlibrary;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.StandardCopyOption;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import com.oracle.java.testlibrary.Utils;
+import com.oracle.java.testlibrary.Platform;
+import com.oracle.java.testlibrary.OutputAnalyzer;
+import com.oracle.java.testlibrary.ProcessTools;
+
+public class DockerTestUtils {
+    private static final String FS = File.separator;
+    private static boolean isDockerEngineAvailable = false;
+    private static boolean wasDockerEngineChecked = false;
+
+    // Diagnostics: set to true to enable more diagnostic info
+    private static final boolean DEBUG = false;
+
+    /**
+     * Optimized check of whether the docker engine is available in a given
+     * environment. Checks only once, then remembers the result in a singleton.
+     *
+     * @return true if docker engine is available
+     * @throws Exception
+     */
+    public static boolean isDockerEngineAvailable() throws Exception {
+        if (wasDockerEngineChecked)
+            return isDockerEngineAvailable;
+
+        isDockerEngineAvailable = isDockerEngineAvailableCheck();
+        wasDockerEngineChecked = true;
+        return isDockerEngineAvailable;
+    }
+
+
+    /**
+     * Convenience method, will check if docker engine is available and usable;
+     * will print the appropriate message when not available.
+     *
+     * @return true if docker engine is available
+     * @throws Exception
+     */
+    public static boolean canTestDocker() throws Exception {
+        if (isDockerEngineAvailable()) {
+            return true;
+        } else {
+            System.out.println("Docker engine is not available on this system");
+            System.out.println("This test is SKIPPED");
+            return false;
+        }
+    }
+
+
+    /**
+     * Simple check - is docker engine available, accessible and usable.
+     * Run basic docker command: 'docker ps' - list docker instances.
+     * If docker engine is available and accesible then true is returned
+     * and we can proceed with testing docker.
+     *
+     * @return true if docker engine is available and usable
+     * @throws Exception
+     */
+    private static boolean isDockerEngineAvailableCheck() throws Exception {
+        try {
+            execute("docker", "ps")
+                .shouldHaveExitValue(0)
+                .shouldContain("CONTAINER")
+                .shouldContain("IMAGE");
+        } catch (Exception e) {
+            return false;
+        }
+        return true;
+    }
+
+
+    /**
+     * Build a docker image that contains JDK under test.
+     * The jdk will be placed under the "/jdk/" folder inside the docker file system.
+     *
+     * @param imageName     name of the image to be created, including version tag
+     * @param dockerfile    name of the dockerfile residing in the test source;
+     *                      we check for a platform specific dockerfile as well
+     *                      and use this one in case it exists
+     * @param buildDirName  name of the docker build/staging directory, which will
+     *                      be created in the jtreg's scratch folder
+     * @throws Exception
+     */
+    public static void
+        buildJdkDockerImage(String imageName, String dockerfile, String buildDirName)
+            throws Exception {
+        Path buildDir = Paths.get(".", buildDirName);
+        if (Files.exists(buildDir)) {
+            throw new RuntimeException("The docker build directory already exists: " + buildDir);
+        }
+        // check for the existance of a platform specific docker file as well
+        String platformSpecificDockerfile = dockerfile + "-" + Platform.getOsArch();
+        if (Files.exists(Paths.get(Utils.TEST_SRC, platformSpecificDockerfile))) {
+          dockerfile = platformSpecificDockerfile;
+        }
+
+        Path jdkSrcDir = Paths.get(Utils.TEST_JDK);
+        Path jdkDstDir = buildDir.resolve("jdk");
+
+        Files.createDirectories(jdkDstDir);
+
+        // Copy JDK-under-test tree to the docker build directory.
+        // This step is required for building a docker image.
+        Files.walkFileTree(jdkSrcDir, new CopyFileVisitor(jdkSrcDir, jdkDstDir));
+        buildDockerImage(imageName, Paths.get(Utils.TEST_SRC, dockerfile), buildDir);
+    }
+
+
+    /**
+     * Build a docker image based on given docker file and docker build directory.
+     *
+     * @param imageName  name of the image to be created, including version tag
+     * @param dockerfile  path to the Dockerfile to be used for building the docker
+     *        image. The specified dockerfile will be copied to the docker build
+     *        directory as 'Dockerfile'
+     * @param buildDir  build directory; it should already contain all the content
+     *        needed to build the docker image.
+     * @throws Exception
+     */
+    public static void
+        buildDockerImage(String imageName, Path dockerfile, Path buildDir) throws Exception {
+        // Copy docker file to the build dir
+        Files.copy(dockerfile, buildDir.resolve("Dockerfile"));
+
+        // Build the docker
+        execute("docker", "build", "--no-cache", "--tag", imageName, buildDir.toString())
+            .shouldHaveExitValue(0)
+            .shouldContain("Successfully built");
+    }
+
+
+    /**
+     * Run Java inside the docker image with specified parameters and options.
+     *
+     * @param DockerRunOptions optins for running docker
+     *
+     * @return output of the run command
+     * @throws Exception
+     */
+    public static OutputAnalyzer dockerRunJava(DockerRunOptions opts) throws Exception {
+        ArrayList<String> cmd = new ArrayList<>();
+
+        cmd.add("docker");
+        cmd.add("run");
+        if (opts.tty)
+            cmd.add("--tty=true");
+        if (opts.removeContainerAfterUse)
+            cmd.add("--rm");
+
+        cmd.addAll(opts.dockerOpts);
+        cmd.add(opts.imageNameAndTag);
+        cmd.add(opts.command);
+
+        cmd.addAll(opts.javaOpts);
+        if (opts.appendTestJavaOptions) {
+            Collections.addAll(cmd, Utils.getTestJavaOpts());
+        }
+
+        cmd.add(opts.classToRun);
+        cmd.addAll(opts.classParams);
+        return execute(cmd);
+    }
+
+
+     /**
+     * Remove docker image
+     *
+     * @param DockerRunOptions optins for running docker
+     * @return output of the command
+     * @throws Exception
+     */
+    public static OutputAnalyzer removeDockerImage(String imageNameAndTag) throws Exception {
+        return execute("docker", "rmi", "--force", imageNameAndTag);
+    }
+
+
+
+    /**
+     * Convenience method - express command as sequence of strings
+     *
+     * @param command to execute
+     * @return The output from the process
+     * @throws Exception
+     */
+    public static OutputAnalyzer execute(List<String> command) throws Exception {
+        return execute(command.toArray(new String[command.size()]));
+    }
+
+
+    /**
+     * Execute a specified command in a process, report diagnostic info.
+     *
+     * @param command to be executed
+     * @return The output from the process
+     * @throws Exception
+     */
+    public static OutputAnalyzer execute(String... command) throws Exception {
+
+        ProcessBuilder pb = new ProcessBuilder(command);
+        System.out.println("[COMMAND]\n" + Utils.getCommandLine(pb));
+
+        long started = System.currentTimeMillis();
+        OutputAnalyzer output = new OutputAnalyzer(pb.start());
+
+        System.out.println("[ELAPSED: " + (System.currentTimeMillis() - started) + " ms]");
+        System.out.println("[STDERR]\n" + output.getStderr());
+        System.out.println("[STDOUT]\n" + output.getStdout());
+
+        return output;
+    }
+
+
+    private static class CopyFileVisitor extends SimpleFileVisitor<Path> {
+        private final Path src;
+        private final Path dst;
+
+        public CopyFileVisitor(Path src, Path dst) {
+            this.src = src;
+            this.dst = dst;
+        }
+
+
+        @Override
+        public FileVisitResult preVisitDirectory(Path file,
+                BasicFileAttributes attrs) throws IOException {
+            Path dstDir = dst.resolve(src.relativize(file));
+            if (!dstDir.toFile().exists()) {
+                Files.createDirectories(dstDir);
+            }
+            return FileVisitResult.CONTINUE;
+        }
+
+
+        @Override
+        public FileVisitResult visitFile(Path file,
+                BasicFileAttributes attrs) throws IOException {
+            if (!file.toFile().isFile()) {
+                return FileVisitResult.CONTINUE;
+            }
+            Path dstFile = dst.resolve(src.relativize(file));
+            Files.copy(file, dstFile, StandardCopyOption.COPY_ATTRIBUTES);
+            return FileVisitResult.CONTINUE;
+        }
+    }
+}
diff --git a/test/testlibrary/com/oracle/java/testlibrary/Platform.java b/test/testlibrary/com/oracle/java/testlibrary/Platform.java
index 93841bf..6a14079 100644
--- a/test/testlibrary/com/oracle/java/testlibrary/Platform.java
+++ b/test/testlibrary/com/oracle/java/testlibrary/Platform.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -32,7 +32,7 @@
     private static final String dataModel   = System.getProperty("sun.arch.data.model");
     private static final String vmVersion   = System.getProperty("java.vm.version");
     private static final String osArch      = System.getProperty("os.arch");
-    private static final String vmName      = System.getProperty("java.vm.name");
+    public static final String vmName      = System.getProperty("java.vm.name");
     private static final String userName    = System.getProperty("user.name");
 
     public static boolean isClient() {
diff --git a/test/testlibrary/com/oracle/java/testlibrary/Utils.java b/test/testlibrary/com/oracle/java/testlibrary/Utils.java
index b332c1e..902e3b1 100644
--- a/test/testlibrary/com/oracle/java/testlibrary/Utils.java
+++ b/test/testlibrary/com/oracle/java/testlibrary/Utils.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -61,6 +61,15 @@
      */
     public static final String JAVA_OPTIONS = System.getProperty("test.java.opts", "").trim();
 
+    public static final String TEST_JDK = System.getProperty("test.jdk");
+
+    public static final String COMPILE_JDK= System.getProperty("compile.jdk", TEST_JDK);
+
+    public static final String TEST_SRC = System.getProperty("test.src", "").trim();
+
+    public static final String TEST_CLASSES = System.getProperty("test.classes", ".");
+
+
     private static Unsafe unsafe = null;
 
     /**
diff --git a/test/testlibrary/whitebox/sun/hotspot/WhiteBox.java b/test/testlibrary/whitebox/sun/hotspot/WhiteBox.java
index 6b3d3e3..d2f49da 100644
--- a/test/testlibrary/whitebox/sun/hotspot/WhiteBox.java
+++ b/test/testlibrary/whitebox/sun/hotspot/WhiteBox.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -235,4 +235,12 @@
 
   // Class Data Sharing
   public native boolean isSharedClass(Class<?> c);
+
+  // Returns true on linux if library has the noexecstack flag set.
+  public native boolean checkLibSpecifiesNoexecstack(String libfilename);
+
+  // Container testing
+  public native boolean isContainerized();
+  public native void printOsInfo();
+
 }