Fix OpenCL compiles on Mac OS
[alexxy/gromacs.git] / src / gromacs / gpu_utils / ocl_compiler.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2012,2013,2014,2015,2016,2017,2018, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35 /*! \internal \file
36  *  \brief Define infrastructure for OpenCL JIT compilation for Gromacs
37  *
38  *  \author Dimitrios Karkoulis <dimitris.karkoulis@gmail.com>
39  *  \author Anca Hamuraru <anca@streamcomputing.eu>
40  *  \author Teemu Virolainen <teemu@streamcomputing.eu>
41  *  \author Mark Abraham <mark.j.abraham@gmail.com>
42  */
43
44 #include "gmxpre.h"
45
46 #include "ocl_compiler.h"
47
48 #include "config.h"
49
50 #include <cstdio>
51
52 #include <algorithm>
53 #include <string>
54 #include <vector>
55
56 #include "gromacs/gpu_utils/oclutils.h"
57 #include "gromacs/utility/cstringutil.h"
58 #include "gromacs/utility/exceptions.h"
59 #include "gromacs/utility/gmxassert.h"
60 #include "gromacs/utility/path.h"
61 #include "gromacs/utility/programcontext.h"
62 #include "gromacs/utility/smalloc.h"
63 #include "gromacs/utility/stringutil.h"
64 #include "gromacs/utility/textreader.h"
65 #include "gromacs/utility/unique_cptr.h"
66
67 #include "ocl_caching.h"
68
69 namespace gmx
70 {
71 namespace ocl
72 {
73
74 /*! \brief True if OpenCL binary caching is enabled.
75  *
76  *  Currently caching is disabled by default unless the env var override
77  *  is used until we resolve concurrency issues. */
78 static bool useBuildCache = getenv("GMX_OCL_GENCACHE"); // (NULL == getenv("GMX_OCL_NOGENCACHE"));
79
80 /*! \brief Handles writing the OpenCL JIT compilation log to \c fplog.
81  *
82  * If \c fplog is non-null and either the GMX_OCL_DUMP_LOG environment
83  * variable is set or the compilation failed, then the OpenCL
84  * compilation log is written.
85  *
86  * \param fplog               Open file pointer to log file
87  * \param program             OpenCL program that was compiled
88  * \param deviceId            Id of the device for which compilation took place
89  * \param kernelFilename      File name containing the kernel
90  * \param preprocessorOptions String containing the preprocessor command-line options used for the build
91  * \param buildFailed         Whether the OpenCL build succeeded
92  *
93  * \throws std::bad_alloc if out of memory */
94 static void
95 writeOclBuildLog(FILE              *fplog,
96                  cl_program         program,
97                  cl_device_id       deviceId,
98                  const std::string &kernelFilename,
99                  const std::string &preprocessorOptions,
100                  bool               buildFailed)
101 {
102     bool writeOutput = ((fplog != nullptr) &&
103                         (buildFailed || (getenv("GMX_OCL_DUMP_LOG") != nullptr)));
104
105     if (!writeOutput)
106     {
107         return;
108     }
109
110     // Get build log string size
111     size_t buildLogSize;
112     cl_int cl_error = clGetProgramBuildInfo(program,
113                                             deviceId,
114                                             CL_PROGRAM_BUILD_LOG,
115                                             0,
116                                             NULL,
117                                             &buildLogSize);
118     if (cl_error != CL_SUCCESS)
119     {
120         GMX_THROW(InternalError("Could not get OpenCL program build log size, error was " + ocl_get_error_string(cl_error)));
121     }
122
123     char             *buildLog = nullptr;
124     unique_cptr<char> buildLogGuard;
125     if (buildLogSize != 0)
126     {
127         /* Allocate memory to fit the build log,
128            it can be very large in case of errors */
129         snew(buildLog, buildLogSize);
130         buildLogGuard.reset(buildLog);
131
132         /* Get the actual compilation log */
133         cl_error = clGetProgramBuildInfo(program,
134                                          deviceId,
135                                          CL_PROGRAM_BUILD_LOG,
136                                          buildLogSize,
137                                          buildLog,
138                                          NULL);
139         if (cl_error != CL_SUCCESS)
140         {
141             GMX_THROW(InternalError("Could not get OpenCL program build log, error was " + ocl_get_error_string(cl_error)));
142         }
143     }
144
145     std::string message;
146     if (buildFailed)
147     {
148         message += "Compilation of source file " + kernelFilename + " failed!\n";
149     }
150     else
151     {
152         message += "Compilation of source file " + kernelFilename + " was successful!\n";
153     }
154     message += "-- Used build options: " + preprocessorOptions + "\n";
155     message += "--------------LOG START---------------\n";
156     message += buildLog;
157     message += "---------------LOG END----------------\n";;
158
159     fputs(message.c_str(), fplog);
160 }
161
162 /*! \brief Construct compiler options string
163  *
164  * \param deviceVendorId  Device vendor id. Used to
165  *          automatically enable some vendor-specific options
166  * \return The string with the compiler options
167  */
168 static std::string
169 selectCompilerOptions(ocl_vendor_id_t deviceVendorId)
170 {
171     std::string compilerOptions;
172
173     if (getenv("GMX_OCL_NOOPT") )
174     {
175         compilerOptions += " -cl-opt-disable";
176     }
177
178     /* Fastmath imprves performance on all supported arch */
179     if (getenv("GMX_OCL_DISABLE_FASTMATH") == NULL)
180     {
181         compilerOptions += " -cl-fast-relaxed-math";
182     }
183
184     if ((deviceVendorId == OCL_VENDOR_NVIDIA) && getenv("GMX_OCL_VERBOSE"))
185     {
186         compilerOptions += " -cl-nv-verbose";
187     }
188
189     if ((deviceVendorId == OCL_VENDOR_AMD) && getenv("GMX_OCL_DUMP_INTERM_FILES"))
190     {
191         /* To dump OpenCL build intermediate files, caching must be off */
192         if (!useBuildCache)
193         {
194             compilerOptions += " -save-temps";
195         }
196     }
197
198     if ( ( deviceVendorId == OCL_VENDOR_AMD ) && getenv("GMX_OCL_DEBUG"))
199     {
200         compilerOptions += " -g";
201     }
202
203     return compilerOptions;
204 }
205
206 /*! \brief Get the path to the main folder storing OpenCL kernels.
207  *
208  * By default, this function constructs the full path to the OpenCL from
209  * the known location of the binary that is running, so that we handle
210  * both in-source and installed builds. The user can override this
211  * behavior by defining GMX_OCL_FILE_PATH environment variable.
212  *
213  * \return OS-normalized path string to the main folder storing OpenCL kernels
214  *
215  * \throws std::bad_alloc    if out of memory.
216  *         FileIOError  if GMX_OCL_FILE_PATH does not specify a readable path
217  */
218 static std::string
219 getKernelRootPath()
220 {
221     std::string kernelRootPath;
222     /* Use GMX_OCL_FILE_PATH if the user has defined it */
223     const char *gmxOclFilePath = getenv("GMX_OCL_FILE_PATH");
224
225     if (gmxOclFilePath == nullptr)
226     {
227         /* Normal way of getting ocl_root_dir. First get the right
228            root path from the path to the binary that is running. */
229         InstallationPrefixInfo      info           = getProgramContext().installationPrefix();
230         std::string                 dataPathSuffix = (info.bSourceLayout ?
231                                                       "src/gromacs/mdlib/nbnxn_ocl" :
232                                                       OCL_INSTALL_DIR);
233         kernelRootPath = Path::join(info.path, dataPathSuffix);
234     }
235     else
236     {
237         if (!Directory::exists(gmxOclFilePath))
238         {
239             GMX_THROW(FileIOError(formatString("GMX_OCL_FILE_PATH must point to the directory where OpenCL"
240                                                "kernels are found, but '%s' does not exist", gmxOclFilePath)));
241         }
242         kernelRootPath = gmxOclFilePath;
243     }
244
245     // Make sure we return an OS-correct path format
246     return Path::normalize(kernelRootPath);
247 }
248
249 /*!  \brief Get the warp size reported by device
250  *
251  *  This is platform implementation dependant and seems to only work on the Nvidia and AMD platforms!
252  *  Nvidia reports 32, AMD for GPU 64. Ignore the rest
253  *
254  *  \param  context   Current OpenCL context
255  *  \param  deviceId OpenCL device with the context
256  *  \return cl_int value of the warp size
257  *
258  * \throws InternalError if an OpenCL error was encountered
259  */
260 static size_t
261 getWarpSize(cl_context context, cl_device_id deviceId)
262 {
263     cl_int      cl_error;
264     const char *warpSizeKernel = "__kernel void test(__global int* test){test[get_local_id(0)] = 0;}";
265     cl_program  program        = clCreateProgramWithSource(context, 1, (const char**)&warpSizeKernel, NULL, &cl_error);
266     if (cl_error != CL_SUCCESS)
267     {
268         GMX_THROW(InternalError("Could not create OpenCL program to determine warp size, error was " + ocl_get_error_string(cl_error)));
269     }
270
271     cl_error = clBuildProgram(program, 0, NULL, NULL, NULL, NULL);
272     if (cl_error != CL_SUCCESS)
273     {
274         GMX_THROW(InternalError("Could not build OpenCL program to determine warp size, error was " + ocl_get_error_string(cl_error)));
275     }
276
277     cl_kernel kernel = clCreateKernel(program, "test", &cl_error);
278     if (cl_error != CL_SUCCESS)
279     {
280         GMX_THROW(InternalError("Could not create OpenCL kernel to determine warp size, error was " + ocl_get_error_string(cl_error)));
281     }
282
283     size_t warpSize = 0;
284     cl_error = clGetKernelWorkGroupInfo(kernel, deviceId, CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE,
285                                         sizeof(warpSize), &warpSize, NULL);
286     if (cl_error != CL_SUCCESS)
287     {
288         GMX_THROW(InternalError("Could not measure OpenCL warp size, error was " + ocl_get_error_string(cl_error)));
289     }
290     if (warpSize == 0)
291     {
292         GMX_THROW(InternalError(formatString("Did not measure a valid OpenCL warp size")));
293     }
294
295     cl_error = clReleaseKernel(kernel);
296     if (cl_error != CL_SUCCESS)
297     {
298         GMX_THROW(InternalError("Could not release OpenCL warp-size kernel, error was " + ocl_get_error_string(cl_error)));
299     }
300     cl_error = clReleaseProgram(program);
301     if (cl_error != CL_SUCCESS)
302     {
303         GMX_THROW(InternalError("Could not release OpenCL warp-size program, error was " + ocl_get_error_string(cl_error)));
304     }
305
306     return warpSize;
307 }
308
309 /*! \brief Select a compilation-line define for a vendor-specific kernel choice from vendor id
310  *
311  * \param[in] vendorId Vendor id enumerator
312  *
313  * \return The appropriate compilation-line define
314  */
315 static const char *
316 makeVendorFlavorChoice(ocl_vendor_id_t vendorId)
317 {
318     const char *choice;
319     switch (vendorId)
320     {
321         case OCL_VENDOR_AMD:
322             choice = "-D_AMD_SOURCE_";
323             break;
324         case OCL_VENDOR_NVIDIA:
325             choice = "-D_NVIDIA_SOURCE_";
326             break;
327         default:
328             choice = "-D_WARPLESS_SOURCE_";
329             break;
330     }
331     return choice;
332 }
333
334 /*! \brief Create include paths for kernel sources.
335  *
336  * All OpenCL kernel files are expected to be stored in one single folder.
337  *
338  * \throws std::bad_alloc  if out of memory.
339  */
340 static std::string makeKernelIncludePathOption(const std::string &unescapedKernelRootPath)
341 {
342     std::string includePathOption;
343
344     /* Apple does not seem to accept the quoted include paths other
345      * OpenCL implementations are happy with. Since the standard still says
346      * it should be quoted, we handle Apple as a special case.
347      */
348 #ifdef __APPLE__
349     includePathOption += "-I";
350
351     // Prepend all the spaces with a backslash
352     for (std::string::size_type i = 0; i < unescapedKernelRootPath.length(); i++)
353     {
354         if (unescapedKernelRootPath[i] == ' ')
355         {
356             includePathOption.push_back('\\');
357         }
358         includePathOption.push_back(unescapedKernelRootPath[i]);
359     }
360 #else
361     includePathOption += "-I\"" + unescapedKernelRootPath + "\"";
362 #endif
363
364     return includePathOption;
365 }
366
367 /*! \brief Replace duplicated spaces with a single one in string
368  *
369  * Only the first character will be kept for multiple adjacent characters that
370  * are both identical and where the first one returns true for isspace().
371  *
372  * \param str String that will be modified.
373  */
374 static void
375 removeExtraSpaces(std::string *str)
376 {
377     GMX_RELEASE_ASSERT(str != nullptr, "A pointer to an actual string must be provided");
378     std::string::iterator newEnd =
379         std::unique( str->begin(), str->end(), [ = ](char a, char b){ return isspace(a) && (a == b); } );
380     str->erase(newEnd, str->end());
381 }
382
383 /*! \brief Builds a string with build options for the OpenCL kernels
384  *
385  * \throws std::bad_alloc  if out of memory. */
386 static std::string
387 makePreprocessorOptions(const std::string   &kernelRootPath,
388                         size_t               warpSize,
389                         ocl_vendor_id_t      deviceVendorId,
390                         const std::string   &extraDefines)
391 {
392     std::string preprocessorOptions;
393
394     /* Compose the complete build options */
395     preprocessorOptions  = formatString("-DWARP_SIZE_TEST=%d", static_cast<int>(warpSize));
396     preprocessorOptions += ' ';
397     preprocessorOptions += makeVendorFlavorChoice(deviceVendorId);
398     preprocessorOptions += ' ';
399     preprocessorOptions += extraDefines;
400     preprocessorOptions += ' ';
401     preprocessorOptions += selectCompilerOptions(deviceVendorId);
402     preprocessorOptions += ' ';
403     preprocessorOptions += makeKernelIncludePathOption(kernelRootPath);
404
405     // Mac OS (and maybe some other implementations) does not accept double spaces in options
406     removeExtraSpaces(&preprocessorOptions);
407
408     return preprocessorOptions;
409 }
410
411 cl_program
412 compileProgram(FILE              *fplog,
413                const std::string &kernelBaseFilename,
414                const std::string &extraDefines,
415                cl_context         context,
416                cl_device_id       deviceId,
417                ocl_vendor_id_t    deviceVendorId)
418 {
419     cl_int      cl_error;
420     std::string kernelRootPath = getKernelRootPath();
421
422     GMX_RELEASE_ASSERT(fplog != nullptr, "Need a valid log file for building OpenCL programs");
423
424     /* Load OpenCL source files */
425     std::string kernelFilename = Path::join(kernelRootPath,
426                                             kernelBaseFilename);
427
428     /* Make the build options */
429     std::string preprocessorOptions = makePreprocessorOptions(kernelRootPath,
430                                                               getWarpSize(context, deviceId),
431                                                               deviceVendorId,
432                                                               extraDefines);
433
434     bool        buildCacheWasRead = false;
435
436     std::string cacheFilename;
437     if (useBuildCache)
438     {
439         cacheFilename = makeBinaryCacheFilename(kernelBaseFilename, deviceId);
440     }
441
442     /* Create OpenCL program */
443     cl_program program = nullptr;
444     if (useBuildCache)
445     {
446         if (File::exists(cacheFilename, File::returnFalseOnError))
447         {
448             /* Check if there's a valid cache available */
449             try
450             {
451                 program           = makeProgramFromCache(cacheFilename, context, deviceId);
452                 buildCacheWasRead = true;
453             }
454             catch (FileIOError &e)
455             {
456                 // Failing to read from the cache is not a critical error
457                 formatExceptionMessageToFile(fplog, e);
458             }
459         }
460         else
461         {
462             fprintf(fplog, "No OpenCL binary cache file was present, so will compile kernels normally.\n");
463         }
464     }
465     if (program == nullptr)
466     {
467         // Compile OpenCL program from source
468         std::string kernelSource = TextReader::readFileToString(kernelFilename);
469         if (kernelSource.empty())
470         {
471             GMX_THROW(FileIOError("Error loading OpenCL code " + kernelFilename));
472         }
473         const char *kernelSourcePtr  = kernelSource.c_str();
474         size_t      kernelSourceSize = kernelSource.size();
475         /* Create program from source code */
476         program = clCreateProgramWithSource(context,
477                                             1,
478                                             &kernelSourcePtr,
479                                             &kernelSourceSize,
480                                             &cl_error);
481         if (cl_error != CL_SUCCESS)
482         {
483             GMX_THROW(InternalError("Could not create OpenCL program, error was " + ocl_get_error_string(cl_error)));
484         }
485     }
486
487     /* Build the OpenCL program, keeping the status to potentially
488        write to the simulation log file. */
489     cl_int buildStatus = clBuildProgram(program, 0, NULL, preprocessorOptions.c_str(), NULL, NULL);
490
491     /* Write log first, and then throw exception that the user know what is
492        the issue even if the build fails. */
493     writeOclBuildLog(fplog,
494                      program,
495                      deviceId,
496                      kernelFilename,
497                      preprocessorOptions,
498                      buildStatus != CL_SUCCESS);
499
500     if (buildStatus != CL_SUCCESS)
501     {
502         GMX_THROW(InternalError("Could not build OpenCL program, error was " + ocl_get_error_string(buildStatus)));
503     }
504
505     if (useBuildCache)
506     {
507         if (!buildCacheWasRead)
508         {
509             /* If OpenCL caching is ON, but the current cache is not
510                valid => update it */
511             try
512             {
513                 writeBinaryToCache(program, cacheFilename);
514             }
515             catch (GromacsException &e)
516             {
517                 // Failing to write the cache is not a critical error
518                 formatExceptionMessageToFile(fplog, e);
519             }
520         }
521     }
522     if ((OCL_VENDOR_NVIDIA == deviceVendorId) && getenv("GMX_OCL_DUMP_INTERM_FILES"))
523     {
524         /* If dumping intermediate files has been requested and this is an NVIDIA card
525            => write PTX to file */
526         char buffer[STRLEN];
527
528         cl_error = clGetDeviceInfo(deviceId, CL_DEVICE_NAME, sizeof(buffer), buffer, NULL);
529         if (cl_error != CL_SUCCESS)
530         {
531             GMX_THROW(InternalError("Could not get OpenCL device info, error was " + ocl_get_error_string(cl_error)));
532         }
533         std::string ptxFilename = buffer;
534         ptxFilename += ".ptx";
535
536         try
537         {
538             writeBinaryToCache(program, ptxFilename);
539         }
540         catch (GromacsException &e)
541         {
542             // Failing to write the cache is not a critical error
543             formatExceptionMessageToFile(fplog, e);
544         }
545     }
546
547     return program;
548 }
549
550 } // namespace
551 } // namespace