ea9a2e856eb56e0c0b6125b43100c74c2346efc5
[alexxy/gromacs.git] / CMakeLists.txt
1 #
2 # This file is part of the GROMACS molecular simulation package.
3 #
4 # Copyright (c) 2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019, 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 cmake_minimum_required(VERSION 3.9.6)
36
37 # CMake modules/macros are in a subdirectory to keep this file cleaner
38 # This needs to be set before project() in order to pick up toolchain files
39 list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake ${CMAKE_CURRENT_SOURCE_DIR}/cmake/Platform)
40
41 project(Gromacs)
42
43 if (MSVC)
44     set(CMAKE_CXX_STANDARD 14)
45 else()
46     set(CMAKE_CXX_STANDARD 11)
47 endif()
48 set(CMAKE_CXX_STANDARD_REQUIRED ON)
49 set(CMAKE_CXX_EXTENSIONS OFF)
50
51 include(gmxManageCcache)
52
53 set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
54 set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
55 set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
56
57 # Set up common version variables, as well as general information about
58 # the build tree (whether the build is from a source package or from a git
59 # repository).  Also declares a few functions that will be used for generating
60 # version info files later.
61 include(gmxBuildTreeInfo)
62 include(gmxVersionInfo)
63
64 if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT AND UNIX)
65     set(CMAKE_INSTALL_PREFIX "/usr/local/gromacs" CACHE STRING "Installation prefix (installation will need write permissions here)" FORCE)
66 endif()
67 if("${CMAKE_INSTALL_PREFIX}" STREQUAL "${CMAKE_BINARY_DIR}")
68     message(FATAL_ERROR "GROMACS cannot be installed into the build tree, choose a different location for CMAKE_INSTALL_PREFIX")
69 endif()
70
71 include(gmxBuildTypeReference)
72 include(gmxBuildTypeProfile)
73 include(gmxBuildTypeTSAN)
74 include(gmxBuildTypeASAN)
75 include(gmxBuildTypeMSAN)
76 include(gmxBuildTypeReleaseWithAssert)
77
78 if(NOT CMAKE_BUILD_TYPE)
79     set(CMAKE_BUILD_TYPE "Release" CACHE STRING "Choose the type of build, options are: Debug Release RelWithDebInfo MinSizeRel Reference RelWithAssert Profile TSAN ASAN MSAN." FORCE)
80     # Set the possible values of build type for cmake-gui
81     set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release"
82         "MinSizeRel" "RelWithDebInfo" "Reference" "RelWithAssert" "Profile" "TSAN" "ASAN" "MSAN")
83 endif()
84 if(CMAKE_CONFIGURATION_TYPES)
85     # Add appropriate GROMACS-specific build types for the Visual
86     # Studio generator (Debug, Release, MinSizeRel and RelWithDebInfo
87     # are already present by default).
88     list(APPEND CMAKE_CONFIGURATION_TYPES "RelWithAssert" "Reference")
89     list(REMOVE_DUPLICATES CMAKE_CONFIGURATION_TYPES)
90     set(CMAKE_CONFIGURATION_TYPES "${CMAKE_CONFIGURATION_TYPES}" CACHE STRING
91         "List of configuration types"
92         FORCE)
93 endif()
94 set(build_types_with_explicit_flags RELEASE DEBUG RELWITHDEBINFO RELWITHASSERT MINSIZEREL PROFILE)
95
96 set_property(GLOBAL PROPERTY FIND_LIBRARY_USE_LIB64_PATHS ON)
97
98 include(gmxCTestUtilities)
99 gmx_ctest_init()
100
101 include(gmxCPackUtilities)
102 gmx_cpack_init()
103
104 # Variables that accumulate stuff influencing the installed headers
105 set(INSTALLED_HEADER_INCLUDE_DIRS "")
106 set(INSTALLED_HEADER_DEFINITIONS "")
107
108 ########################################################################
109 # Global non-cache variables for implementing the build system
110 ########################################################################
111
112 # These variables collect libraries that GROMACS requires for
113 # linking. They should be appended to with list(APPEND ${name}
114 # new-library) calls. They are:
115 #  - Libraries that are required for libgromacs (only)
116 set(GMX_EXTRA_LIBRARIES "")
117 #  - Libraries that are required for all code in the repository
118 set(GMX_COMMON_LIBRARIES "")
119 #  - Libraries that all code linked against libgromacs needs
120 #    (i.e., something that is exposed in installed headers).
121 set(GMX_PUBLIC_LIBRARIES "")
122
123 ########################################################################
124 # Check and warn if cache generated on a different host is being reused
125 ########################################################################
126 if(CMAKE_HOST_UNIX)
127     execute_process(COMMAND hostname
128                     OUTPUT_VARIABLE TMP_HOSTNAME
129                     OUTPUT_STRIP_TRAILING_WHITESPACE)
130     if(GMX_BUILD_HOSTNAME AND NOT "${GMX_BUILD_HOSTNAME}" STREQUAL "${TMP_HOSTNAME}")
131         message(WARNING "
132             The CMake cache, probably generated on a different host (${GMX_BUILD_HOSTNAME}),
133             is being reused! This could lead to inconsistencies; therefore, it is
134             recommended to regenerate the cache!")
135     endif()
136     set(GMX_BUILD_HOSTNAME "${TMP_HOSTNAME}" CACHE INTERNAL
137             "Hostname of the machine where the cache was generated.")
138 endif()
139
140 ########################################################################
141 # Detect architecture before setting options so we can alter defaults
142 ########################################################################
143 # Detect the architecture the compiler is targetting, detect
144 # SIMD instructions possibilities on that hardware, suggest SIMD instruction set
145 # to use if none is specified, and populate the cache option for CPU
146 # SIMD.
147 include(gmxDetectTargetArchitecture)
148 gmx_detect_target_architecture()
149
150 include(CheckCCompilerFlag)
151 include(CheckCXXCompilerFlag)
152
153 ########################################################################
154 # User input options                                                   #
155 ########################################################################
156 include(gmxOptionUtilities)
157
158 set(CMAKE_PREFIX_PATH "" CACHE STRING "Extra locations to search for external libraries and tools (give directory without lib, bin, or include)")
159
160 # Fujitsu only has SIMD in double precision, so this will be faster
161 gmx_set_boolean(GMX_DOUBLE_DEFAULT GMX_TARGET_FUJITSU_SPARC64)
162 option(GMX_DOUBLE "Use double precision (much slower, use only if you really need it)" ${GMX_DOUBLE_DEFAULT})
163 option(GMX_RELAXED_DOUBLE_PRECISION "Accept single precision 1/sqrt(x) when using Fujitsu HPC-ACE SIMD" OFF)
164 mark_as_advanced(GMX_RELAXED_DOUBLE_PRECISION)
165
166 option(GMX_MPI    "Build a parallel (message-passing) version of GROMACS" OFF)
167 option(GMX_THREAD_MPI  "Build a thread-MPI-based multithreaded version of GROMACS (not compatible with MPI)" ON)
168 gmx_dependent_option(
169     GMX_MPI_IN_PLACE
170     "Enable MPI_IN_PLACE for MPIs that have it defined"
171     ON
172     GMX_MPI)
173 mark_as_advanced(GMX_MPI_IN_PLACE)
174
175 option(GMX_MIMIC "Enable MiMiC QM/MM interface (CPMD is required)" OFF)
176
177 option(GMX_FAHCORE "Build a library with mdrun functionality" OFF)
178 mark_as_advanced(GMX_FAHCORE)
179
180 option(GMX_COOL_QUOTES "Enable GROMACS cool quotes" ON)
181 mark_as_advanced(GMX_COOL_QUOTES)
182 gmx_add_cache_dependency(GMX_COOL_QUOTES BOOL "NOT GMX_FAHCORE" OFF)
183
184 option(GMX_USE_OPENCL "Enable OpenCL acceleration" OFF)
185
186 # Decide on GPU settings based on user-settings and GPU/CUDA
187 # detection. VS2017 requires CUDA 9.0, for the other arch/compilers
188 # rest we require CUDA 8.0 or later (including for clang-CUDA)
189 # because that is the earliest version that supports gcc 5.x
190 if(MSVC)
191     set(REQUIRED_CUDA_VERSION 9.0)
192 else()
193     set(REQUIRED_CUDA_VERSION 8.0)
194 endif()
195 set(REQUIRED_CUDA_COMPUTE_CAPABILITY 3.0)
196
197 # OpenCL required version: 1.2 or newer
198 set(REQUIRED_OPENCL_MIN_VERSION_MAJOR 1)
199 set(REQUIRED_OPENCL_MIN_VERSION_MINOR 2)
200 set(REQUIRED_OPENCL_MIN_VERSION ${REQUIRED_OPENCL_MIN_VERSION_MAJOR}.${REQUIRED_OPENCL_MIN_VERSION_MINOR})
201
202 if(NOT GMX_USE_OPENCL)
203     # CUDA detection is done only if GMX_USE_OPENCL is OFF.
204     include(gmxManageGPU)
205     set(GMX_USE_CUDA ${GMX_GPU})
206     if(GMX_GPU)
207         set(GMX_GPU_ACCELERATION_FRAMEWORK "GMX_GPU_CUDA")
208     else()
209         set(GMX_GPU_ACCELERATION_FRAMEWORK "GMX_GPU_NONE")
210     endif()
211 else()
212     #Now the OpenCL path (for both AMD and NVIDIA)
213     if(GMX_GPU)
214         include(gmxManageOpenCL)
215         set(GMX_GPU_ACCELERATION_FRAMEWORK "GMX_GPU_OPENCL")
216     else()
217         message(FATAL_ERROR "OpenCL requested but GPU option is not enabled (try -DGMX_GPU=on) ")
218     endif()
219 endif()
220
221 gmx_option_multichoice(
222     GMX_SIMD
223     "SIMD instruction set for CPU kernels and compiler optimization"
224     "AUTO"
225     AUTO None SSE2 SSE4.1 AVX_128_FMA AVX_256 AVX2_256 AVX2_128 AVX_512 AVX_512_KNL MIC ARM_NEON ARM_NEON_ASIMD IBM_VMX IBM_VSX Sparc64_HPC_ACE Reference)
226
227 if(GMX_TARGET_MIC)
228     set(GMX_FFT_LIBRARY_DEFAULT "mkl")
229 else()
230     set(GMX_FFT_LIBRARY_DEFAULT "fftw3")
231 endif()
232
233 gmx_option_multichoice(
234     GMX_FFT_LIBRARY
235     "FFT library"
236     "${GMX_FFT_LIBRARY_DEFAULT}"
237     fftw3 mkl "fftpack[built-in]")
238 gmx_dependent_option(
239     GMX_BUILD_OWN_FFTW
240     "Download and build FFTW 3 during the GROMACS build process, rather than fall back on the really slow fftpack."
241     OFF
242     "GMX_FFT_LIBRARY STREQUAL FFTW3")
243 gmx_dependent_option(
244     GMX_DISABLE_FFTW_MEASURE
245     "Do not optimize FFTW setups (not needed with SSE)"
246     OFF
247     "GMX_FFT_LIBRARY STREQUAL FFTW3")
248 mark_as_advanced(GMX_BUILD_OWN_FFTW)
249 mark_as_advanced(GMX_DISABLE_FFTW_MEASURE)
250
251 gmx_option_multichoice(
252     GMX_QMMM_PROGRAM
253     "QM package for QM/MM"
254     None
255     none gaussian mopac gamess orca)
256
257 gmx_dependent_cache_variable(GMX_SIMD_REF_FLOAT_WIDTH  "Reference SIMD single precision width" STRING "4" "GMX_SIMD STREQUAL REFERENCE")
258 gmx_dependent_cache_variable(GMX_SIMD_REF_DOUBLE_WIDTH "Reference SIMD double precision width" STRING "2" "GMX_SIMD STREQUAL REFERENCE")
259
260 # This should be moved to a separate NBNXN cmake module when that code is cleaned up and modularized
261
262 option(GMX_BROKEN_CALLOC "Work around broken calloc()" OFF)
263 mark_as_advanced(GMX_BROKEN_CALLOC)
264
265 option(GMX_OPENMP "Enable OpenMP-based multithreading" ON)
266
267 option(GMX_USE_TNG "Use the TNG library for trajectory I/O" ON)
268
269 option(GMX_BUILD_MDRUN_ONLY "Build and install only the mdrun binary" OFF)
270
271 option(GMX_CYCLE_SUBCOUNTERS "Enable cycle subcounters to get a more detailed cycle timings" OFF)
272 mark_as_advanced(GMX_CYCLE_SUBCOUNTERS)
273
274 option(GMX_SKIP_DEFAULT_CFLAGS "Don't automatically add suggested/required Compiler flags." OFF)
275 mark_as_advanced(GMX_SKIP_DEFAULT_CFLAGS)
276
277 option(GMX_BUILD_FOR_COVERAGE
278        "Tune build for better code coverage metrics (e.g., disable asserts)"
279        OFF)
280 mark_as_advanced(GMX_BUILD_FOR_COVERAGE)
281
282 option(GMX_DEVELOPER_BUILD
283     "Enable Developer convenience features: always build unit-tests"
284     OFF)
285 mark_as_advanced(GMX_DEVELOPER_BUILD)
286
287 gmx_set_boolean(GMX_COMPILER_WARNINGS_DEFAULT "NOT SOURCE_IS_SOURCE_DISTRIBUTION")
288 option(GMX_COMPILER_WARNINGS
289     "Enable a default set of compiler warnings"
290     ${GMX_COMPILER_WARNINGS_DEFAULT})
291 mark_as_advanced(GMX_COMPILER_WARNINGS)
292 # Always turn on compiler warnings with a developer build.
293 gmx_add_cache_dependency(GMX_COMPILER_WARNINGS BOOL "NOT GMX_DEVELOPER_BUILD" ON)
294
295 option(GMX_BUILD_SHARED_EXE
296     "Build exectuables as shared binaries. If not set, this disables rpath and dynamic linker flags in an attempt to build a static binary, but this may require setting up the toolchain properly and making appropriate libraries available."
297     ON)
298 mark_as_advanced(GMX_BUILD_SHARED_EXE)
299
300 option(GMX_PHYSICAL_VALIDATION
301        "Include physical validation tests in ctest environment. These can then be called using 'make check-phys' or
302        'make check-all'. Warning: Running the physical validation tests takes significantly more time than other tests!"
303        OFF)
304 mark_as_advanced(GMX_PHYSICAL_VALIDATION)
305
306 ######################################################################
307 # Detect OpenMP support
308 ######################################################################
309 # The OpenMP detection _must_ come before tests for other CFLAGS.
310 include(gmxManageOpenMP)
311
312
313
314 ######################################################################
315 # Compiler tests
316 # These need to be done early (before further tests).
317 #####################################################################
318
319 include(gmxCFlags)
320 gmx_c_flags()
321
322 # This variable should be used for additional compiler flags which are not
323 # generated in gmxCFlags nor are SIMD or MPI related.
324 #
325 # TODO These variables should be consolidated into
326 # EXTRA_COMPILER_FLAGS so that we we don't perpetrate bugs where
327 # things that work in C compilation (e.g. merging from old branches)
328 # also work for C++ compilation.
329 set(EXTRA_C_FLAGS "")
330 set(EXTRA_CXX_FLAGS "")
331
332 # Run through a number of tests for buggy compilers and other issues
333 include(gmxTestCompilerProblems)
334 gmx_test_compiler_problems()
335
336 # Implement double-precision option. This is complicated because we
337 # need installed headers to use the precision mode of the build that
338 # produced the library, but cannot use config.h in that case. We also
339 # want such variables to always have a definition, because #if is more
340 # robust than #ifdef. So, we put this value on the compiler command
341 # line in all cases.
342 #
343 # GMX_RELAXED_DOUBLE_PRECISION does not need to be handled here,
344 # because no installed header needs it
345 if(GMX_DOUBLE)
346     set(GMX_DOUBLE_VALUE 1)
347 else()
348     set(GMX_DOUBLE_VALUE 0)
349 endif()
350 add_definitions(-DGMX_DOUBLE=${GMX_DOUBLE_VALUE})
351 list(APPEND INSTALLED_HEADER_DEFINITIONS "-DGMX_DOUBLE=${GMX_DOUBLE_VALUE}")
352
353 if(WIN32)
354     list(APPEND GMX_EXTRA_LIBRARIES "wsock32")
355     add_definitions(-DGMX_HAVE_WINSOCK)
356 endif()
357
358
359
360 ########################################################################
361 # Basic system tests (standard libraries, headers, functions, types)   #
362 ########################################################################
363 include(CheckIncludeFiles)
364 include(CheckIncludeFileCXX)
365 check_include_files(unistd.h     HAVE_UNISTD_H)
366 check_include_files(pwd.h        HAVE_PWD_H)
367 check_include_files(dirent.h     HAVE_DIRENT_H)
368 check_include_files(time.h       HAVE_TIME_H)
369 check_include_files(sys/time.h   HAVE_SYS_TIME_H)
370 check_include_files(io.h         HAVE_IO_H)
371 check_include_files(sched.h      HAVE_SCHED_H)
372
373 include(CheckCXXSymbolExists)
374 check_cxx_symbol_exists(gettimeofday      sys/time.h   HAVE_GETTIMEOFDAY)
375 check_cxx_symbol_exists(sysconf           unistd.h     HAVE_SYSCONF)
376 check_cxx_symbol_exists(nice              unistd.h     HAVE_NICE)
377 check_cxx_symbol_exists(fsync             unistd.h     HAVE_FSYNC)
378 check_cxx_symbol_exists(_fileno           stdio.h      HAVE__FILENO)
379 check_cxx_symbol_exists(fileno            stdio.h      HAVE_FILENO)
380 check_cxx_symbol_exists(_commit           io.h         HAVE__COMMIT)
381 check_cxx_symbol_exists(sigaction         signal.h     HAVE_SIGACTION)
382
383 # We cannot check for the __builtins as symbols, but check if code compiles
384 check_cxx_source_compiles("int main(){ return __builtin_clz(1);}"   HAVE_BUILTIN_CLZ)
385 check_cxx_source_compiles("int main(){ return __builtin_clzll(1);}" HAVE_BUILTIN_CLZLL)
386 if(MSVC)
387     check_cxx_source_compiles("#include <intrin.h>\n int main(){unsigned long r;unsigned long i=1;_BitScanReverse(&r,i);return r;}" HAVE_BITSCANREVERSE)
388     check_cxx_source_compiles("#include <intrin.h>\n int main(){unsigned long r;unsigned __int64 i=1;_BitScanReverse(&r,i);return r;}" HAVE_BITSCANREVERSE64)
389 elseif(CMAKE_CXX_COMPILER_ID MATCHES "XL")
390     check_cxx_source_compiles("int main(){ return __cntlz4(1);}" HAVE_CNTLZ4)
391     check_cxx_source_compiles("int main(){ return __cntlz8(1);}" HAVE_CNTLZ8)
392 endif()
393
394 include(CheckLibraryExists)
395 find_library(HAVE_LIBM m)
396 mark_as_advanced(HAVE_LIBM)
397 check_library_exists(rt clock_gettime "" HAVE_CLOCK_GETTIME)
398 check_library_exists(m feenableexcept "" HAVE_FEENABLEEXCEPT)
399 check_library_exists(m fedisableexcept "" HAVE_FEDISABLEEXCEPT)
400
401 include(TestSchedAffinity)
402 test_sched_affinity(HAVE_SCHED_AFFINITY)
403
404 # Aligned memory allocation. We need to check for both mm_malloc(),
405 # posix_memalign(), memalign(), and on windows also _aligned_malloc()
406 include(gmxTestMMMalloc)
407 gmx_test_mm_malloc(HAVE__MM_MALLOC)
408 check_cxx_symbol_exists(posix_memalign    stdlib.h     HAVE_POSIX_MEMALIGN)
409 check_cxx_symbol_exists(memalign          stdlib.h     HAVE_MEMALIGN)
410 if(MSVC)
411     # No need to waste time on this test on platforms where it will never be true
412     check_cxx_symbol_exists(_aligned_malloc   stdlib.h     HAVE__ALIGNED_MALLOC)
413 endif()
414
415 include(TestBigEndian)
416 test_big_endian(GMX_INTEGER_BIG_ENDIAN)
417
418 gmx_set_boolean(GMX_USE_NICE "HAVE_UNISTD_H AND HAVE_NICE")
419
420 # Management of GROMACS options for specific toolchains should go
421 # here. Because the initial settings for some of the main options have
422 # already happened, but things like library detection and MPI compiler
423 # feature detection have not, the docstrings for any over-rides of
424 # GROMACS defaults or user settings will make sense. Also, any
425 # toolchain-related reasons for choosing whether to detect various
426 # things can be sorted out now, before the detection takes place.
427 if(GMX_TARGET_FUJITSU_SPARC64)
428     include(gmxManageFujitsuSparc64)
429 endif()
430
431 ########################################################################
432 #Process MPI settings
433 ########################################################################
434 include(gmxManageMPI)
435
436 ########################################################################
437 #Process MiMiC settings
438 ########################################################################
439 include(gmxManageMimic)
440
441 ########################################################################
442 #Process shared/static library settings
443 ########################################################################
444 include(gmxManageSharedLibraries)
445
446
447 ########################################################################
448 # Find external packages                                               #
449 ########################################################################
450
451 # Unconditionally find the package, as it is also required for unit
452 # tests. This exports LIBXML2_FOUND, which we should not use because
453 # it does not tell us that linking will succeed. Instead, we test that
454 # next.
455 #if(DEFINED LIBXML2_LIBRARIES)
456 #  set(LibXml2_FIND_QUIETLY TRUE)
457 #endif()
458 #find_package(LibXml2)
459 #include(gmxTestLibXml2)
460 #gmx_test_libxml2(HAVE_LIBXML2)
461 #option(GMX_XML "Use libxml2 to parse xml files (currently has no effect)" ${HAVE_LIBXML2})
462 #set(PKG_XML "")
463 #mark_as_advanced(GMX_XML)
464 # Don't actually do anything, since libxml2 is currently not used by libgromacs
465 #if(GMX_XML AND NOT HAVE_LIBXML2)
466 #    message(FATAL_ERROR "libxml2 not found. Set GMX_XML=OFF to compile without XML support")
467 #endif()
468 #if(GMX_XML)
469 #    include_directories(${LIBXML2_INCLUDE_DIR})
470 #    set(PKG_XML libxml-2.0)
471 #    set(XML_LIBRARIES ${LIBXML2_LIBRARIES})
472 #endif()
473
474 gmx_option_trivalue(
475     GMX_HWLOC
476     "Use hwloc portable hardware locality library"
477     "AUTO")
478
479 if (GMX_HWLOC)
480     # Find quietly the second time.
481     if(DEFINED HWLOC_LIBRARIES)
482         set(Hwloc_FIND_QUIETLY TRUE)
483     endif()
484     find_package(Hwloc 1.5)
485
486     if (HWLOC_FOUND)
487         if (HWLOC_LIBRARIES MATCHES ".a$")
488             set(_STATIC_HWLOC TRUE)
489         endif()
490
491         gmx_check_if_changed(HWLOC_FOUND_CHANGED HWLOC_FOUND)
492         if (_STATIC_HWLOC AND HWLOC_FOUND_CHANGED)
493             message(STATUS "Static hwloc library found, will not attempt using it as it could lead to link-time errors. To use the detected library, manually set GMX_HWLOC=ON and you will likely have to pass appropriate linker flags too to satisfy the link-time dependencies of your hwloc library. Try \"pkg-config --libs --static hwloc\" for suggestions on what you will need.")
494             set(GMX_USE_HWLOC OFF)
495         else()
496             set(GMX_USE_HWLOC ON)
497         endif()
498
499         if (GMX_USE_HWLOC)
500             include_directories(SYSTEM ${HWLOC_INCLUDE_DIRS})
501             list(APPEND GMX_EXTRA_LIBRARIES ${HWLOC_LIBRARIES})
502         endif()
503     elseif(GMX_HWLOC_FORCE)
504         message(FATAL_ERROR "Hwloc package support required, but not found.")
505     endif()
506 endif()
507
508 option(GMX_EXTERNAL_TINYXML2 "Use external TinyXML-2 instead of compiling the version bundled with GROMACS." OFF)
509 mark_as_advanced(GMX_EXTERNAL_TINYXML2)
510 if(GMX_EXTERNAL_TINYXML2)
511     # Find an external TinyXML-2 library.
512     find_package(TinyXML-2 3.0.0)
513     set(HAVE_TINYXML2 ${TinyXML2_FOUND})
514     if(NOT HAVE_TINYXML2)
515         message(FATAL_ERROR "External TinyXML-2 could not be found, please adjust your search paths")
516     endif()
517 endif()
518
519 option(GMX_EXTRAE "Add support for tracing using EXTRAE" OFF)
520 mark_as_advanced(GMX_EXTRAE)
521
522 if (GMX_EXTRAE)
523   find_package(EXTRAE)
524   if(EXTRAE_FOUND)
525     include_directories(SYSTEM ${EXTRAE_INCLUDE_DIR})
526     set(HAVE_EXTRAE 1)
527   else()
528     message(FATAL_ERROR "EXTRAE library was not found. Please add the correct path to CMAKE_PREFIX_PATH")
529   endif()
530 endif()
531
532 option(GMX_X11 "Use X window system" OFF)
533 if (GMX_X11)
534     find_package(X11)
535     # X11 includes/libraries are only set in the ngmx subdirectory!
536     if(NOT X11_FOUND)
537         message(FATAL_ERROR
538                 "X11 include files and/or libraries were not found. "
539                 "Set GMX_X11=OFF to compile without X11 support. "
540                 "gmx view will not be available.")
541     endif()
542     include_directories(SYSTEM ${X11_INCLUDE_DIR})
543 endif()
544
545 include(ThreadMPI)
546 # Enable core threading facilities
547 tmpi_enable_core("${CMAKE_SOURCE_DIR}/src/external/thread_mpi/include")
548 if(GMX_THREAD_MPI)
549     # enable MPI functions
550     tmpi_enable()
551     set(MPI_IN_PLACE_EXISTS 1)
552 endif()
553 # If atomics are manually disabled a define is needed because atomics.h doesn't depend on config.h
554 if (TMPI_ATOMICS_DISABLED)
555    add_definitions(-DTMPI_ATOMICS_DISABLED)
556 endif()
557
558 include(gmxManageTNG)
559
560 include(gmxManageLmfit)
561
562 if(GMX_GPU)
563     # now that we have detected the dependencies, do the second configure pass
564     gmx_gpu_setup()
565     if (GMX_CLANG_CUDA)
566         list(APPEND GMX_EXTRA_LIBRARIES ${GMX_CUDA_CLANG_LINK_LIBS})
567         link_directories("${GMX_CUDA_CLANG_LINK_DIRS}")
568     endif()
569 endif()
570
571 if(CYGWIN)
572     set(GMX_CYGWIN 1)
573 endif()
574
575 if(WIN32)
576     set(GMX_NATIVE_WINDOWS 1)
577     # This makes windows.h not declare min/max as macros that would break
578     # C++ code using std::min/std::max.
579     add_definitions(-DNOMINMAX)
580 endif()
581
582 if(CMAKE_SYSTEM_NAME STREQUAL "Darwin") #Work-around for cmake bug #10837
583     if (CMAKE_COMPILER_IS_GNUCC OR CMAKE_C_COMPILER_ID MATCHES "Intel" OR CMAKE_C_COMPILER_ID MATCHES "Clang")
584         set(CMAKE_INCLUDE_SYSTEM_FLAG_C "-isystem ")
585     endif()
586     if (CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Intel" OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
587         set(CMAKE_INCLUDE_SYSTEM_FLAG_CXX "-isystem ")
588     endif()
589 endif()
590
591 option(GMX_BUILD_UNITTESTS "Build unit tests with BUILD_TESTING" ON)
592 mark_as_advanced(GMX_BUILD_UNITTESTS)
593 gmx_add_cache_dependency(GMX_BUILD_UNITTESTS BOOL BUILD_TESTING OFF)
594
595 ########################################################################
596 # Our own GROMACS tests
597 ########################################################################
598
599 add_definitions( -DHAVE_CONFIG_H )
600 include_directories(BEFORE ${CMAKE_SOURCE_DIR}/src)
601 # TODO required at high level because both libgromacs and progs/mdrun
602 # require it, both for thread-MPI and its atomics and mutexes.
603 include_directories(BEFORE SYSTEM ${CMAKE_SOURCE_DIR}/src/external/thread_mpi/include)
604 # Required for config.h, maybe should only be set in src/CMakeLists.txt
605 include_directories(BEFORE ${CMAKE_BINARY_DIR}/src)
606
607 include(gmxTestInlineASM)
608 gmx_test_inline_asm_gcc_x86(GMX_X86_GCC_INLINE_ASM)
609
610 include(gmxSetBuildInformation)
611 gmx_set_build_information()
612
613 gmx_option_multichoice(
614     GMX_USE_RDTSCP
615     "Use low-latency RDTSCP instruction for CPU-based timers for mdrun execution; might need to be off when compiling for heterogeneous environments)"
616     "AUTO"
617     OFF ON AUTO DETECT)
618 mark_as_advanced(GMX_USE_RDTSCP)
619
620 macro(gmx_check_rdtscp)
621     if (CPU_DETECTION_FEATURES MATCHES "rdtscp")
622         set(HAVE_RDTSCP 1)
623         set(RDTSCP_DETECTION_MESSAGE " - detected on the build host")
624     else()
625         set(RDTSCP_DETECTION_MESSAGE " - not detected on the build host")
626     endif()
627 endmacro()
628
629 set(HAVE_RDTSCP 0)
630 if (GMX_USE_RDTSCP STREQUAL "ON")
631     set(HAVE_RDTSCP 1)
632 elseif(GMX_USE_RDTSCP STREQUAL "DETECT")
633     gmx_check_rdtscp()
634 elseif(GMX_USE_RDTSCP STREQUAL "AUTO")
635     # If the user specified automated SIMD selection, that the choice
636     # is made based on detection on the build host. If so, then RDTSCP
637     # should be chosen the same way.
638     #
639     # If the user specified an AVX SIMD level (e.g. when
640     # cross-compiling GROMACS) then they will get our best guess, ie
641     # that in practice AVX mostly correlates with rdtscp (and anyway
642     # is only relevant in rather old x86 hardware).
643     if (GMX_SIMD STREQUAL "AUTO")
644         gmx_check_rdtscp()
645     elseif (GMX_SIMD MATCHES "AVX")
646         set(HAVE_RDTSCP 1)
647     endif()
648 endif()
649 gmx_check_if_changed(HAVE_RDTSCP_CHANGED HAVE_RDTSCP)
650 if (HAVE_RDTSCP_CHANGED)
651     if (HAVE_RDTSCP)
652         message(STATUS "Enabling RDTSCP support${RDTSCP_DETECTION_MESSAGE}")
653     else()
654         message(STATUS "Disabling RDTSCP support${RDTSCP_DETECTION_MESSAGE}")
655     endif()
656 endif()
657
658 include(gmxTestLargeFiles)
659 gmx_test_large_files(GMX_LARGEFILES)
660
661 include(gmxTestSignal)
662 gmx_test_sigusr1(HAVE_SIGUSR1)
663
664 include(gmxTestPipes)
665 gmx_test_pipes(HAVE_PIPES)
666
667 include(gmxTestXDR)
668 gmx_test_xdr(GMX_SYSTEM_XDR)
669 # Darwin has system XDR, but it uses a three-argument flavour of
670 # xdrproc_t that it guarantees will still work if you pass the normal
671 # two-argument xdr filters, but gcc 8 warns about the cast necessary
672 # to do that, so it's simpler to just use our own XDR library.
673 #
674 # TODO It would be better to craft a cmake test which fails if such
675 # XDR operations cause warnings, and succeeds otherwise, because it is
676 # generally preferable to use system libraries where possible.
677 if(NOT GMX_SYSTEM_XDR OR CMAKE_SYSTEM_NAME STREQUAL "Darwin")
678     set(GMX_INTERNAL_XDR 1)
679 endif()
680
681
682 ##################################################
683 # Process SIMD instruction settings
684 ##################################################
685 # This checks what flags to add in order to
686 # support the SIMD instructions we need, it sets
687 # correct defines for the SIMD instructions supported,
688 # and adds advanced options to control accuracy
689 # for SIMD math operations.
690 include(gmxManageSimd)
691 gmx_manage_simd()
692
693 include(gmxManageCycleCounters)
694 gmx_manage_cycle_counters()
695
696 # Process QM/MM Settings
697 if(${GMX_QMMM_PROGRAM} STREQUAL "GAUSSIAN")
698     set(GMX_QMMM_GAUSSIAN 1)
699 elseif(${GMX_QMMM_PROGRAM} STREQUAL "MOPAC")
700     set(GMX_QMMM_MOPAC 1)
701 elseif(${GMX_QMMM_PROGRAM} STREQUAL "GAMESS")
702     set(GMX_QMMM_GAMESS 1)
703 elseif(${GMX_QMMM_PROGRAM} STREQUAL "ORCA")
704     set(GMX_QMMM_ORCA 1)
705 elseif(${GMX_QMMM_PROGRAM} STREQUAL "NONE")
706     # nothing to do
707 else()
708     gmx_invalid_option_value(GMX_QMMM_PROGRAM)
709 endif()
710
711
712 ##################################################
713 # Process FFT library settings
714 ##################################################
715 include(gmxManageFFTLibraries)
716
717
718 include(gmxManageLinearAlgebraLibraries)
719
720 include(gmxManagePluginSupport)
721
722 if (GMX_USE_PLUGINS)
723     if(NOT GMX_VMD_PLUGIN_PATH)
724         find_package(VMD)
725     endif()
726 endif()
727
728 # Link real-time library for POSIX timers. The check for clock_gettime
729 # confirms the linkability of rt.
730 if(HAVE_TIME_H AND HAVE_UNISTD_H AND HAVE_CLOCK_GETTIME)
731     list(APPEND GMX_EXTRA_LIBRARIES rt)
732 endif()
733
734 # Math and thread libraries must often come after all others when linking...
735 if (HAVE_LIBM)
736     list(APPEND GMX_PUBLIC_LIBRARIES m)
737 endif()
738
739 option(GMX_NACL "Configure for Native Client builds" OFF)
740 if (GMX_NACL)
741   list(APPEND GMX_EXTRA_LIBRARIES nosys)
742   set(GMX_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -lnosys")
743   # TODO: Is this still necessary with the check for its presence?
744   set(GMX_USE_NICE 0)
745   set(GMX_NO_RENAME 1)
746 endif()
747 mark_as_advanced(GMX_NACL)
748
749 if(GMX_FAHCORE)
750   set(COREWRAP_INCLUDE_DIR "${CMAKE_SOURCE_DIR}/../corewrap" CACHE STRING
751       "Path to swindirect.h")
752   include_directories(${COREWRAP_INCLUDE_DIR})
753 endif()
754
755 # Value of GMX_BUILD_HELP=AUTO tries to generate things, but will only
756 # produce warnings if that fails.
757 set(build_help_default AUTO)
758 if (SOURCE_IS_SOURCE_DISTRIBUTION OR CMAKE_CROSSCOMPILING)
759     set(build_help_default OFF)
760 endif()
761 gmx_option_trivalue(GMX_BUILD_HELP "Build completions automatically (requires that compiled binaries can be executed on the build host) and install man pages if built (requires building the 'man' target manually)" ${build_help_default})
762 mark_as_advanced(GMX_BUILD_HELP)
763 if (GMX_BUILD_HELP AND SOURCE_IS_SOURCE_DISTRIBUTION AND BUILD_IS_INSOURCE)
764     message(FATAL_ERROR
765         "Rebuilding shell completions or man pages is not supported for "
766         "in-source builds from a source distribution. "
767         "Set GMX_BUILD_HELP=OFF or do an out-of-source build to proceed.")
768 endif()
769
770 # # # # # # # # # # NO MORE TESTS AFTER THIS LINE! # # # # # # # # # # #
771 # these are set after everything else
772 if (NOT GMX_SKIP_DEFAULT_CFLAGS)
773     set(CMAKE_C_FLAGS "${SIMD_C_FLAGS} ${MPI_COMPILE_FLAGS} ${EXTRA_C_FLAGS} ${CMAKE_C_FLAGS}")
774     set(CMAKE_CXX_FLAGS "${SIMD_CXX_FLAGS} ${MPI_COMPILE_FLAGS} ${EXTRA_CXX_FLAGS} ${CMAKE_CXX_FLAGS}")
775     set(CMAKE_EXE_LINKER_FLAGS "${FFT_LINKER_FLAGS} ${MPI_LINKER_FLAGS} ${CMAKE_EXE_LINKER_FLAGS}")
776     set(CMAKE_SHARED_LINKER_FLAGS "${FFT_LINKER_FLAGS} ${MPI_LINKER_FLAGS} ${CMAKE_SHARED_LINKER_FLAGS}")
777 else()
778     message("Recommended flags which are not added because GMX_SKIP_DEFAULT_CFLAGS=yes:")
779     message("CMAKE_C_FLAGS: ${SIMD_C_FLAGS} ${MPI_COMPILE_FLAGS} ${EXTRA_C_FLAGS} ${GMXC_CFLAGS}")
780     message("CMAKE_C_FLAGS_RELEASE: ${GMXC_CFLAGS_RELEASE}")
781     message("CMAKE_C_FLAGS_DEBUG: ${GMXC_CFLAGS_DEBUG}")
782     message("CMAKE_CXX_FLAGS: ${SIMD_CXX_FLAGS} ${MPI_COMPILE_FLAGS} ${EXTRA_CXX_FLAGS} ${GMXC_CXXFLAGS}")
783     message("CMAKE_CXX_FLAGS_RELEASE: ${GMXC_CXXFLAGS_RELEASE}")
784     message("CMAKE_CXX_FLAGS_DEBUG: ${GMXC_CXXFLAGS_DEBUG}")
785     message("CMAKE_EXE_LINKER_FLAGS: ${FFT_LINKER_FLAGS} ${MPI_LINKER_FLAGS}")
786     message("CMAKE_SHARED_LINKER_FLAGS: ${FFT_LINKER_FLAGS} ${MPI_LINKER_FLAGS}")
787 endif()
788
789 ########################################################################
790 # Specify install locations
791 ########################################################################
792 # Use GNUInstallDirs to set paths on multiarch systems.
793 include(GNUInstallDirs)
794
795 set(GMX_INSTALL_DATASUBDIR "gromacs" CACHE STRING "Subdirectory for GROMACS data under CMAKE_INSTALL_DATADIR")
796 mark_as_advanced(GMX_INSTALL_DATASUBDIR)
797
798 # Internal convenience so we do not have to join two path segments in the code
799 set(GMX_INSTALL_GMXDATADIR ${CMAKE_INSTALL_DATADIR}/${GMX_INSTALL_DATASUBDIR})
800
801 # If the nesting level wrt. the installation root is changed,
802 # gromacs-config.cmake.cmakein needs to be adapted.
803 set(GMX_INSTALL_CMAKEDIR  ${CMAKE_INSTALL_DATAROOTDIR}/cmake)
804
805 # TODO: Make GMXRC adapt if this is changed
806 set(GMX_INSTALL_PKGCONFIGDIR ${CMAKE_INSTALL_LIBDIR}/pkgconfig)
807 set(GMX_INSTALL_OCLDIR       ${GMX_INSTALL_GMXDATADIR}/opencl)
808
809 list(APPEND INSTALLED_HEADER_INCLUDE_DIRS ${CMAKE_INSTALL_INCLUDEDIR})
810
811 # Binary and library suffix options
812 include(gmxManageSuffixes)
813
814 ################################################################
815 # Shared library load path settings
816 ################################################################
817 if(NOT GMX_BUILD_SHARED_EXE)
818     # No rpath
819     set(CMAKE_SKIP_RPATH TRUE)
820     set(CMAKE_EXE_LINK_DYNAMIC_C_FLAGS) # remove -Wl,-Bdynamic
821     set(CMAKE_EXE_LINK_DYNAMIC_CXX_FLAGS)
822 else()
823     # The build folder always has bin/ and lib/; if we are also going to
824     # install to lib/, then the installation RPATH works also in the build
825     # tree.  This makes installation slightly faster (no need to rewrite the
826     # RPATHs), and makes the binaries in the build tree relocatable.
827     if(CMAKE_INSTALL_LIBDIR STREQUAL "lib")
828         set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE)
829         if(POLICY CMP0068)
830             cmake_policy(SET CMP0068 NEW) # From CMake-3.9
831             set(CMAKE_BUILD_WITH_INSTALL_NAME_DIR TRUE)
832         endif()
833     endif()
834     # Set the RPATH as relative to the executable location to make the
835     # binaries relocatable.
836     if(CMAKE_SYSTEM_NAME STREQUAL "Darwin") #Assume OS X >=10.5
837         set(CMAKE_INSTALL_RPATH "@loader_path/../${CMAKE_INSTALL_LIBDIR}")
838         set(CMAKE_INSTALL_NAME_DIR ${CMAKE_INSTALL_RPATH})
839     else()
840         set(CMAKE_INSTALL_RPATH "\$ORIGIN/../${CMAKE_INSTALL_LIBDIR}")
841     endif()
842     set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
843     set(CMAKE_MACOSX_RPATH 1)
844 endif()
845
846 #COPYING file: Only necessary for binary distributions.
847 #Simpler to always install.
848 install(FILES COPYING DESTINATION ${GMX_INSTALL_GMXDATADIR} COMPONENT data)
849
850 if (GMX_BUILD_FOR_COVERAGE)
851     # Code heavy with asserts makes conditional coverage close to useless metric,
852     # as by design most of the false branches are impossible to trigger in
853     # correctly functioning code.  And the benefit of testing those that could
854     # be triggered by using an API against its specification isn't usually
855     # worth the effort.
856     add_definitions(-DNDEBUG -DGMX_DISABLE_ASSERTS)
857 endif()
858
859 if (BUILD_TESTING)
860     include(tests/CheckTarget.cmake)
861 endif()
862
863 if (NOT GMX_BUILD_MDRUN_ONLY)
864     find_package(ImageMagick QUIET COMPONENTS convert)
865     include(gmxTestImageMagick)
866     GMX_TEST_IMAGEMAGICK(IMAGE_CONVERT_POSSIBLE)
867     add_subdirectory(docs)
868     add_subdirectory(share)
869     add_subdirectory(scripts)
870 endif()
871 add_subdirectory(src)
872
873 if (BUILD_TESTING)
874     add_subdirectory(tests)
875 endif()
876
877 gmx_cpack_write_config()
878
879 # Issue a warning if NVIDIA GPUs were detected, but CUDA was not found.
880 # Don't bother the user after the first configure pass.
881 if ((CUDA_NOTFOUND_AUTO AND GMX_DETECT_GPU_AVAILABLE) AND NOT GMX_GPU_DETECTION_DONE)
882     message(WARNING "${CUDA_NOTFOUND_MESSAGE}")
883 endif()
884 set(GMX_GPU_DETECTION_DONE TRUE CACHE INTERNAL "Whether GPU detection has already been done")
885
886 #######################
887 ## uninstall target
888 #######################
889 CONFIGURE_FILE(   "${CMAKE_CURRENT_SOURCE_DIR}/cmake/cmake_uninstall.cmake.in"
890                   "${CMAKE_CURRENT_BINARY_DIR}/cmake/cmake_uninstall.cmake"
891                   IMMEDIATE @ONLY)
892 ###########################
893 ADD_CUSTOM_TARGET(uninstall
894                   "${CMAKE_COMMAND}" -P
895                   "${CMAKE_CURRENT_BINARY_DIR}/cmake/cmake_uninstall.cmake")
896 ###########################
897 set_directory_properties(PROPERTIES
898             ADDITIONAL_MAKE_CLEAN_FILES "install_manifest.txt")