12323
|
1 /*
|
|
2 * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
|
|
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
|
4 *
|
|
5 * This code is free software; you can redistribute it and/or modify it
|
|
6 * under the terms of the GNU General Public License version 2 only, as
|
|
7 * published by the Free Software Foundation.
|
|
8 *
|
|
9 * This code is distributed in the hope that it will be useful, but WITHOUT
|
|
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
|
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
|
12 * version 2 for more details (a copy is included in the LICENSE file that
|
|
13 * accompanied this code).
|
|
14 *
|
|
15 * You should have received a copy of the GNU General Public License version
|
|
16 * 2 along with this work; if not, write to the Free Software Foundation,
|
|
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
|
18 *
|
|
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
|
20 * or visit www.oracle.com if you need additional information or have any
|
|
21 * questions.
|
|
22 */
|
|
23
|
|
24 public class Verify {
|
|
25 public static String throwWord(boolean threw) {
|
|
26 return (threw ? "threw" : "didn't throw");
|
|
27 }
|
|
28
|
|
29 public static void verify(int a, int b) {
|
|
30 boolean exception1 = false, exception2 = false;
|
|
31 int result1 = 0, result2 = 0;
|
|
32 try {
|
|
33 result1 = testIntrinsic(a, b);
|
|
34 } catch (ArithmeticException e) {
|
|
35 exception1 = true;
|
|
36 }
|
|
37 try {
|
|
38 result2 = testNonIntrinsic(a, b);
|
|
39 } catch (ArithmeticException e) {
|
|
40 exception2 = true;
|
|
41 }
|
|
42
|
|
43 if (exception1 != exception2) {
|
|
44 throw new RuntimeException("Intrinsic version " + throwWord(exception1) + " exception, NonIntrinsic version " + throwWord(exception2) + " for: " + a + " + " + b);
|
|
45 }
|
|
46 if (result1 != result2) {
|
|
47 throw new RuntimeException("Intrinsic version returned: " + a + " while NonIntrinsic version returned: " + b);
|
|
48 }
|
|
49 }
|
|
50
|
|
51 public static int testIntrinsic(int a, int b) {
|
|
52 return java.lang.Math.addExact(a, b);
|
|
53 }
|
|
54
|
|
55 public static int testNonIntrinsic(int a, int b) {
|
|
56 return safeAddExact(a, b);
|
|
57 }
|
|
58
|
|
59 // Copied java.lang.Math.addExact to avoid intrinsification
|
|
60 public static int safeAddExact(int x, int y) {
|
|
61 int r = x + y;
|
|
62 // HD 2-12 Overflow iff both arguments have the opposite sign of the result
|
|
63 if (((x ^ r) & (y ^ r)) < 0) {
|
|
64 throw new ArithmeticException("integer overflow");
|
|
65 }
|
|
66 return r;
|
|
67 }
|
|
68 }
|