1 /*
  2  * Copyright (c) 2024, 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.  Oracle designates this
  8  * particular file as subject to the "Classpath" exception as provided
  9  * by Oracle in the LICENSE file that accompanied this code.
 10  *
 11  * This code is distributed in the hope that it will be useful, but WITHOUT
 12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 14  * version 2 for more details (a copy is included in the LICENSE file that
 15  * accompanied this code).
 16  *
 17  * You should have received a copy of the GNU General Public License version
 18  * 2 along with this work; if not, write to the Free Software Foundation,
 19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  * or visit www.oracle.com if you need additional information or have any
 23  * questions.
 24  */
 25 
 26 import job.*;
 27 
 28 static void logo(){
 29     System.out.println("""
 30         ⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⣀⣀⣀⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
 31         ⠀⠀⠀⠀⠀⠀⠀⢰⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣶⣤⣀⠀⠀⠀⠀⠀⠀⠀
 32         ⠀⠀⠀⠀⠀⠀⠀ ⠙⠿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠿⠀⠀⠀⠀⠀⠀⠀
 33         ⠀⠀⠀⠀⠀⠀⠀⠀⣷⣶⣤⣄⣈⣉⣉⣉⣉⣉⣉⣉⣁⣤⡄⠀⠀⠀⠀⠀⠀⠀
 34         ⠀⠀⠀⠀⠀⠀ ⠀⣿⣿⣿⣿⣿ HAT ⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀
 35         ⠀⠀⢀⣠⣶⣾⡏⢀⡈⠛⠻⠿⢿⣿⣿⣿⣿⣿⠿⠿⠟⠛⢁⠀⢶⣤⣀⠀⠀⠀
 36         ⠀⢠⣿⣿⣿⣿⡇⠸⣿⣿⣶⣶⣤⣤⣤⣤⣤⣤⣤⣶⣶⣿⡿⠂⣸⣿⣿⣷⡄⠀
 37         ⠀⢸⣿⣿⣿⣿⣿⣦⣄⡉⠛⠛⠛⠿⠿⠿⠿⠛⠛⠛⢉⣁⣤⣾⣿⣿⣿⣿⡷⠀
 38         ⠀⠀⠙⢿⣿⣿⣿⣿⣿⣿⣿⣷⣶⣶⣶⣶⣶⣶⣾⣿⣿⣿⣿⣿⣿⣿⡿⠛⠁⠀
 39         ⠀⠀⠀⠀⠈⠙⠛⠿⠿⢿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠿⠿⠿⠛⠛⠉⠁⠀⠀⠀⠀
 40         """);
 41 }
 42 static void help(){
 43     System.out.println("""
 44         Usage  bld|clean|run ...
 45              bld:
 46                    Compile all buildable (based on capabilities) available jars and native code.
 47 
 48              dot:
 49                    Create dot graph  (bld.dot) of buildable dependencies (based on capabilities)
 50                       dot bld.dot -Tsvg > bld.svg  && chrome bld.svg
 51            clean:
 52                    Removes build directory entirely
 53                    conf dir and jextracted artifacts (opencl/cuda/opengl) remain
 54 
 55 
 56              run:  [ffi|my|seq]-[opencl|java|cuda|mock|hip] [-DXXX ...] runnable  args
 57                       run ffi-opencl mandel
 58                       run ffi-opencl nbody 4096
 59                       run ffi-opencl -DHAT=SHOW_CODE nbody 4096
 60                       run ffi-opencl -DHAT=SHOW_KERNEL_MODEL heal
 61                       run ffi-opencl -DHAT=MINIMIZE_BUFFERS life
 62 
 63              exp:  [ffi|my|seq]-[opencl|java|cuda|mock|hip] [-DXXX ... ] experimentClassName  args
 64                       exp ffi-opencl QuotedConstantArgs
 65 
 66              test-suite:  [ffi|my|seq]-[opencl|java|cuda|mock|hip]
 67                       test-suite ffi-opencl
 68 
 69              test:  [ffi|my|seq]-[opencl|java|cuda|mock|hip] classToTest (also classToTest#method)
 70                       test ffi-opencl  hat.test.TestMatMul
 71 
 72           sanity:  Check source files for copyright and WS issues (tabs and trailing EOL WS)
 73         """);
 74 }
 75 
 76 static  void logoAndHelp(){
 77     logo();
 78     help();
 79 }
 80 
 81 public static void main(String[] argArr) throws IOException, InterruptedException {
 82     var args = new ArrayList<>(List.of(argArr));
 83     if (args.isEmpty()) {
 84         help();
 85     } else {
 86         var hat = new Project(
 87                 Util.currentDirAsPath(),
 88                 // These opts will be applied to all javac, cmake and jextract tools
 89                 Jar.JavacConfig.of(o -> o.progress(true)
 90                         .debug().enablePreview().source(26).addModules("jdk.incubator.code")
 91                 ),
 92                 CMake.Config.of(o -> o.progress(true)),
 93                 JExtract.Config.of(o -> o.progress(true))
 94         );
 95 
 96         var commonJavaOpts = Jar.JavaConfig.of(o -> o
 97                 .verbose(true)
 98                 .command(true)
 99                 .enablePreview()
100                 .addModules("jdk.incubator.code")
101                 .enableNativeAccess("ALL-UNNAMED"));
102 
103         var cmake = hat.isAvailable("cmake", "--version");
104         if (!cmake.isAvailable()) {
105             System.out.println("We need cmake, to check the availability of opencl, cuda etc so we wont be able to build much  ");
106         }
107         var jextract = hat.isAvailable("jextract", "--version");
108         if (!jextract.isAvailable()) {
109             System.out.println("We will need jextract to create jextracted backends and for examples requiring opengl ");
110         }
111 
112         // This is an example of a user defined optional dependency.
113         // Anything depending on this will only build if (In this case) the property is true
114         // So in our case if the headless system property
115         var ui = new Opt(hat.id("ui"), !Boolean.getBoolean("headless")); //-Dheadless=true|false
116 
117         // These dependencies are  'true' on the appropriate platform.
118         // So any target depending on one these, will only build on that platform
119         var mac = new Mac(hat.id("os-mac"));
120         var linux = new Linux(hat.id("os-linux"));
121 
122         // These next three 'optional' dependencies use cmake to determine availability.  We delegate to cmake which
123         //    a) determines if capability is available,
124         //    b) if they are, they extract from cmake vars (see conf/cmake-info/OpenCL/properties for example) information export headers and libs needed by JExtract
125         var jextractOpts = JExtract.Config.of(o -> o.command(true));
126         var cmakeOpts = CMake.Config.of(o -> o.command(true));
127         var openclCmakeInfo = new OpenCL(hat.id("cmake-info-opencl"), cmake);
128         var openglCmakeInfo = new OpenGL(hat.id("cmake-info-opengl"), cmake);
129         var cudaCmakeInfo = new Cuda(hat.id("cmake-info-cuda"), cmake);
130 
131         // Now we just create jars and shared libs and declare dependencies
132         var optkl = hat.jar("optkl");
133         var core = hat.jar("core", optkl);
134         var tools = hat.jar("tools", core);
135         var tests = hat.jar("tests", core, tools);
136 
137         var backend_ffi_native = hat.cmakeAndJar("backend{s}-ffi", core, cmake);
138         var ffiSharedBackend = hat.jar("backend{s}-ffi-shared", backend_ffi_native);
139         var backend_ffi_cuda = hat.jar("backend{s}-ffi-cuda", ffiSharedBackend);
140         var backend_ffi_opencl = hat.jar("backend{s}-ffi-opencl", ffiSharedBackend);
141         var backend_ffi_mock = hat.jar("backend{s}-ffi-mock", ffiSharedBackend);
142 
143         // These examples just rely on core
144         var backend_mt_java = hat.jar("backend{s}-java-mt", core);
145         var backend_seq_java = hat.jar("backend{s}-java-seq", core);
146         var example_squares = hat.jar("example{s}-squares", core);
147         var example_matmul = hat.jar("example{s}-matmul", core);
148         var example_blackscholes = hat.jar("example{s}-blackscholes", core);
149         var example_view = hat.jar("example{s}-view", core);
150         var example_normmap = hat.jar("example{s}-normmap", core); // will probabvly need shared when we hatify
151 
152         // example_shared allows us to break out common UI functions, views, even loops etc
153         var example_shared = hat.jar("example{s}-shared", ui, core);
154 
155         // These examples use example_shared, so they are UI based
156         var example_mandel = hat.jar("example{s}-mandel", example_shared);
157         var example_life = hat.jar("example{s}-life", example_shared);
158         var example_heal = hat.jar("example{s}-heal", example_shared);
159         var example_violajones = hat.jar("example{s}-violajones", example_shared);
160 
161         // experiments include code that expects an opencl backend, this is not idea, but we can accomodate
162         var example_experiments = hat.jar("example{s}-experiments", core);
163 
164         // Now we have the more complex nonsense for nbody (which needs opengl and opencl extracted)
165         var wrapped_shared = hat.jar("wrap{s}-shared");
166         var jextracted_opencl = hat.jextract("extract{ions|ed}-opencl", jextract, openclCmakeInfo, core);
167         var wrapped_jextracted_opencl = hat.jar("wrap{s}-opencl", jextracted_opencl, wrapped_shared);
168         var backend_jextracted_shared = hat.jar("backend{s}-jextracted-shared", core);
169         var backend_jextracted_opencl = hat.jar("backend{s}-jextracted-opencl", wrapped_jextracted_opencl, backend_jextracted_shared);
170         var jextracted_opengl = hat.jextract("extract{ions|ed}-opengl", jextract, ui, openglCmakeInfo, core);
171 
172         // Sigh... We have different src exclusions for wrapped opengl depending on the OS
173         var excludedOpenGLWrapSrc = hat.rootPath().resolve(
174                 "wraps/opengl/src/main/java/wrap/opengl/GL" + (mac.isAvailable() ? "Callback" : "Func") + "EventHandler.java");
175 
176         var wrapped_jextracted_opengl = hat.jar("wrap{s}-opengl", Set.of(excludedOpenGLWrapSrc), jextracted_opengl, wrapped_shared);
177 
178         // Finally we have everything needed for nbody
179         var example_nbody = hat.jar("example{s}-nbody", ui, wrapped_jextracted_opengl, wrapped_jextracted_opencl);
180 
181         var testEnginePackage = "hat.test.engine";
182         var testEngineClassName = "HATTestEngine";
183         while (!args.isEmpty()) {
184             var arg = args.removeFirst();
185             switch (arg) {
186                 case "help" -> logoAndHelp();
187                 case "clean" -> hat.clean(true);
188                 case "dot" -> {
189                     Files.writeString(Path.of("bld.dot"), hat.all().available().toDot());
190                     System.out.println("Consider...\n    dot bld.dot -Tsvg > bld.svg");
191                 }
192                 case "bld" -> {
193                     hat.build(hat.all().available());
194                 }
195                 case "sanity" -> {
196                     final var copyrightPattern = Pattern.compile("^.*Copyright.*202[0-9].*(Intel|Oracle).*$");
197                     final var copyrightExemptPattern = Pattern.compile("^(robertograham|CMakeFiles|hip)");
198                     final var tabOrEolWsPattern = Pattern.compile("^(.*\\t.*|.* )$");
199                     final var textSuffix = Pattern.compile("^(.*\\.(java|cpp|h|hpp|md)|pom.xml)$");
200                     final var sourceSuffix = Pattern.compile("^(.*\\.(java|cpp|h|hpp)|pom.xml)$");
201 
202                     Stream.of("hat", "tests", "optkl", "core", "tools", "examples", "backends", "docs", "wraps")
203                             .map(hat.rootPath()::resolve)
204                             .forEach(dir -> {
205                                 System.out.println("Checking " + dir);
206                                 Util.recurse(dir,
207                                         (d) -> true, // we do this for all subdirs
208                                         (f) -> textSuffix.matcher(f.getFileName().toString()).matches() && Util.grepLines(tabOrEolWsPattern, f),
209                                         (c) -> System.out.println("File contains WS issue (TAB or EOLWs) " + c)
210                                 );
211                                 Util.recurse(dir,
212                                         (d) -> !copyrightExemptPattern.matcher(d.getFileName().toString()).matches(), // we skip these subdirs
213                                         (f) -> sourceSuffix.matcher(f.getFileName().toString()).matches() && !Util.grepLines(copyrightPattern, f),
214                                         (c) -> System.out.println("File does not contain copyright " + c)
215                                 );
216                             });
217                     args.clear();
218                 }
219                 case "run" -> {
220                     if (args.size() > 1) {
221                         var backendName = args.removeFirst();
222                         if (hat.get(backendName) instanceof Jar backend) {
223                             var javaOpts = commonJavaOpts.with(o -> o
224                                     .collectVmOpts(args).mainClass(args.removeFirst(), "Main")
225                                     .startOnFirstThreadIf(o.packageName().equals("nbody") && mac.isAvailable()).collectArgs(args)
226                             );
227                             if (hat.get(javaOpts.packageName()) instanceof Jar runnable) {
228                                 runnable.run(javaOpts, runnable, backend);
229                             } else {
230                                 System.err.println("Found backend " + backendName + " but failed to find runnable/example " + javaOpts.packageName());
231                             }
232                         } else {
233                             System.err.println("Failed to find backend " + backendName);
234                         }
235                     } else {
236                         System.err.println("For run we expect 'run backend runnable' ");
237                     }
238                 }
239                 case "test-suite" -> {
240                     if (!args.isEmpty()) {
241                         var backendName = args.removeFirst();
242                         if (hat.get(backendName) instanceof Jar backend) {
243                             System.out.println("""
244                                     *****************************************************************
245                                     HAT Test Report
246                                     *****************************************************************
247                                     """);
248                             var test_reports_txt = Paths.get("test_report.txt");
249                             Files.deleteIfExists(test_reports_txt); // because we will append to it in the next loop
250                             var commonTestSuiteJavaOpts = commonJavaOpts.with(o -> o
251                                     .command(false).collectVmOpts(args).mainClass(testEnginePackage, testEngineClassName) //  note no app args as add them below
252                             );
253 
254                             tests.forEachMatchingEntry("(hat/test/Test[a-zA-Z0-9]*).class", (_, matcher) ->
255                                     tests.run(Jar.JavaConfig.of(commonTestSuiteJavaOpts, o -> o.arg(matcher.group(1).replace('/', '.'))), tests, backend)
256                             );
257                             args.clear();
258                             var pattern = Pattern.compile("passed: (\\d+), failed: (\\d+), unsupported: (\\d+), precision-errors: (\\d+)");
259                             class Stats {
260                                 int passed = 0;
261                                 int failed = 0;
262                                 int unsupported = 0;
263                                 int precisionError = 0;
264 
265                                 @Override
266                                 public String toString() {
267                                     return String.format("Global passed: %d, failed: %d, unsupported: %d, precision-errors: %d, pass-rate: %.2f%%\\n",
268                                             passed, failed, unsupported, precisionError, ((float) (passed * 100 / (passed + failed + unsupported + precisionError))));
269                                 }
270                             }
271                             var stats = new Stats();
272                             Files.readAllLines(test_reports_txt).forEach(line -> {
273                                 if (!commonTestSuiteJavaOpts.verbose()) { //We already dumped this info to stdout above
274                                     System.out.println(line);
275                                 }
276                                 if (pattern.matcher(line) instanceof Matcher matcher && matcher.find()) {
277                                     stats.passed += Integer.parseInt(matcher.group(1));
278                                     stats.failed += Integer.parseInt(matcher.group(2));
279                                     stats.unsupported += Integer.parseInt(matcher.group(3));
280                                     stats.precisionError += Integer.parseInt(matcher.group(4));
281                                 }
282                             });
283                             System.out.println(stats);
284                             if (stats.failed > 0) {
285                                 System.exit(-1);
286                             } else {
287                                 System.exit(0);
288                             }
289                         } else {
290                             System.err.println("Failed to find backend   " + backendName);
291                         }
292                     } else {
293                         System.err.println("For test-suite we require a backend ");
294                     }
295                 }
296                 case "test" -> {
297                     if (args.size() >= 2) {
298                         var backendName = args.removeFirst();
299                         if (hat.get(backendName) instanceof Jar backend) {
300                             var javaOpts = commonJavaOpts.with(o -> o
301                                     .verbose(true).command(true).collectVmOpts(args).mainClass(testEnginePackage, testEngineClassName).collectArgs(args)
302                             );
303                             tests.run(javaOpts, tests, backend);
304                         } else {
305                             System.err.println("Failed to find backend   " + backendName);
306                         }
307                     } else {
308                         System.err.println("""
309                                 For test we require a backend and a TestClass.");
310                                 Examples:
311                                     $ test ffi-opencl hat.test.TestMatMul
312                                     $ test ffi-opencl hat.test.TestMatMul#method
313                                 """);
314                     }
315                     args.clear(); //!! :)
316                 }
317                 case "exp" -> {
318                     if (args.size() > 1) {
319                         var backendName = args.removeFirst();
320                         if (hat.get(backendName) instanceof Jar backend) {
321                             var javaOpts = Jar.JavaConfig.of(commonJavaOpts, o -> o
322                                     .collectVmOpts(args).mainClass("experiments", args.removeFirst()).collectArgs(args)
323                             );
324                             if (hat.get(javaOpts.packageName()) instanceof Jar runnable) {
325                                 runnable.run(javaOpts, runnable, backend);
326                             } else {
327                                 System.err.println("Failed to find runnable " + javaOpts.mainClassName());
328                             }
329                         } else {
330                             System.err.println("Failed to find " + backendName);
331                         }
332                     } else {
333                         System.err.println("For exp we expect 'exp backend [-DXXX ...] testclass' ");
334                     }
335                     args.clear(); //!! :)
336                 }
337                 default -> {
338                     System.err.println("'" + arg + "' was unexpected ");
339                     help();
340                     args.clear();
341                 }
342             }
343         }
344     }
345 }