From 53494a2dbef5d916caf7a79aa9185a899ab19924 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Klinkovsk=C3=BD?= Date: Sat, 20 Nov 2021 09:46:16 +0100 Subject: [PATCH 1/8] CMakeLists.txt: refactored compiler flags for tests and code coverage --- CMakeLists.txt | 12 +++--- cmake/BuildGtest.cmake | 14 ++----- src/Examples/simple-examples/CMakeLists.txt | 4 +- src/UnitTests/Algorithms/CMakeLists.txt | 16 +++++--- .../Algorithms/Segments/CMakeLists.txt | 8 ++-- .../Algorithms/Sorting/CMakeLists.txt | 8 ++-- src/UnitTests/Arithmetics/CMakeLists.txt | 13 +++--- src/UnitTests/CMakeLists.txt | 11 +++-- src/UnitTests/Containers/CMakeLists.txt | 38 +++++++++++------- .../Containers/ndarray/CMakeLists.txt | 40 ++++++++++++------- src/UnitTests/Functions/CMakeLists.txt | 8 ++-- src/UnitTests/MPI/CMakeLists.txt | 3 +- src/UnitTests/Matrices/CMakeLists.txt | 14 ++++--- src/UnitTests/Matrices/Legacy/CMakeLists.txt | 8 ++-- src/UnitTests/Meshes/CMakeLists.txt | 30 +++++++++----- .../Meshes/DistributedMeshes/CMakeLists.txt | 30 +++++++++----- src/UnitTests/Pointers/CMakeLists.txt | 8 ++-- 17 files changed, 157 insertions(+), 108 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 3903ca058..b9a935815 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -164,19 +164,21 @@ if( ${BUILD_TESTS} OR ${BUILD_MATRIX_TESTS} ) # find gtest installed in the local system find_package(GTest REQUIRED) if( GTEST_FOUND ) - set( CXX_TESTS_FLAGS ${CXX_TESTS_FLAGS} -DHAVE_GTEST ) include_directories( ${GTEST_INCLUDE_DIRS} ) - link_libraries( ${GTEST_LIBRARIES} ) endif( GTEST_FOUND ) else() # build gtest libs include( BuildGtest ) endif() - + set( CXX_TESTS_FLAGS ${CXX_TESTS_FLAGS} -DHAVE_GTEST ) + set( CUDA_TESTS_FLAGS ${CUDA_TESTS_FLAGS} -DHAVE_GTEST ) + set( TESTS_LIBRARIES ${TESTS_LIBRARIES} ${GTEST_LIBRARIES} ) if( ${WITH_COVERAGE} AND CMAKE_BUILD_TYPE STREQUAL "Debug" ) - # enable code coverage reports - include( UseCodeCoverage ) + # set compiler flags needed for code coverage + set( CXX_TESTS_FLAGS ${CXX_TESTS_FLAGS} --coverage ) + set( CUDA_TESTS_FLAGS ${CUDA_TESTS_FLAGS} -Xcompiler --coverage ) + set( TESTS_LINKER_FLAGS ${TESTS_LINKER_FLAGS} --coverage ) endif() endif() diff --git a/cmake/BuildGtest.cmake b/cmake/BuildGtest.cmake index 095a34d7a..4e1db0ae0 100644 --- a/cmake/BuildGtest.cmake +++ b/cmake/BuildGtest.cmake @@ -2,17 +2,6 @@ # the projects' build systems, see # https://github.com/google/googletest/tree/master/googletest#incorporating-into-an-existing-cmake-project -#find_package( GTest ) -#if( GTEST_FOUND ) -# set( CXX_TESTS_FLAGS "${CXX_TESTS_FLAGS} -DHAVE_GTEST" ) -#endif( GTEST_FOUND ) - - -# compatibility with the GTest package -set( GTEST_BOTH_LIBRARIES gtest gtest_main ) -set( CXX_TESTS_FLAGS ${CXX_TESTS_FLAGS} -DHAVE_GTEST ) - - # Download and unpack googletest at configure time configure_file(cmake/Gtest.cmake.in googletest-download/CMakeLists.txt) execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" . @@ -47,3 +36,6 @@ add_subdirectory(${CMAKE_BINARY_DIR}/googletest-src if (CMAKE_VERSION VERSION_LESS 2.8.11) include_directories("${gtest_SOURCE_DIR}/include") endif() + +# compatibility with the GTest package +set( GTEST_LIBRARIES gtest gtest_main ) diff --git a/src/Examples/simple-examples/CMakeLists.txt b/src/Examples/simple-examples/CMakeLists.txt index 21fed2b18..8fd9c7f79 100644 --- a/src/Examples/simple-examples/CMakeLists.txt +++ b/src/Examples/simple-examples/CMakeLists.txt @@ -1,9 +1,9 @@ IF( BUILD_CUDA ) CUDA_ADD_EXECUTABLE( large-meshfunction-example large-meshfunction-example.cu ) TARGET_COMPILE_OPTIONS( large-meshfunction-example PRIVATE ${CXX_TESTS_FLAGS} ) - TARGET_LINK_LIBRARIES( large-meshfunction-example ${GTEST_BOTH_LIBRARIES} ) + TARGET_LINK_LIBRARIES( large-meshfunction-example ${TESTS_LIBRARIES} ) ELSE( BUILD_CUDA ) ADD_EXECUTABLE( large-meshfunction-example large-meshfunction-example.cpp ) TARGET_COMPILE_OPTIONS( large-meshfunction-example PRIVATE ${CXX_TESTS_FLAGS} ) - TARGET_LINK_LIBRARIES( large-meshfunction-example ${GTEST_BOTH_LIBRARIES} ) + TARGET_LINK_LIBRARIES( large-meshfunction-example ${TESTS_LIBRARIES} ) ENDIF( BUILD_CUDA ) diff --git a/src/UnitTests/Algorithms/CMakeLists.txt b/src/UnitTests/Algorithms/CMakeLists.txt index aa14ae462..9d949e1d9 100644 --- a/src/UnitTests/Algorithms/CMakeLists.txt +++ b/src/UnitTests/Algorithms/CMakeLists.txt @@ -28,14 +28,16 @@ endif() foreach( target IN ITEMS ${CPP_TESTS} ) add_executable( ${target} ${target}.cpp ) target_compile_options( ${target} PRIVATE ${CXX_TESTS_FLAGS} ) - target_link_libraries( ${target} ${GTEST_BOTH_LIBRARIES} ) + target_link_libraries( ${target} ${TESTS_LIBRARIES} ) + target_link_options( ${target} PRIVATE ${TESTS_LINKER_FLAGS} ) add_test( ${target} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${target}${CMAKE_EXECUTABLE_SUFFIX} ) endforeach() if( BUILD_CUDA ) foreach( target IN ITEMS ${CUDA_TESTS} ) - cuda_add_executable( ${target} ${target}.cu OPTIONS ${CXX_TESTS_FLAGS} ) - target_link_libraries( ${target} ${GTEST_BOTH_LIBRARIES} ) + cuda_add_executable( ${target} ${target}.cu OPTIONS ${CUDA_TESTS_FLAGS} ) + target_link_libraries( ${target} ${TESTS_LIBRARIES} ) + target_link_options( ${target} PRIVATE ${TESTS_LINKER_FLAGS} ) add_test( ${target} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${target}${CMAKE_EXECUTABLE_SUFFIX} ) endforeach() endif() @@ -44,12 +46,14 @@ endif() if( ${BUILD_MPI} ) ADD_EXECUTABLE( distributedScanTest distributedScanTest.cpp ) TARGET_COMPILE_OPTIONS( distributedScanTest PRIVATE ${CXX_TESTS_FLAGS} ) - TARGET_LINK_LIBRARIES( distributedScanTest ${GTEST_BOTH_LIBRARIES} ) + TARGET_LINK_LIBRARIES( distributedScanTest ${TESTS_LIBRARIES} ) + TARGET_LINK_OPTIONS( distributedScanTest PRIVATE ${TESTS_LINKER_FLAGS} ) if( BUILD_CUDA ) CUDA_ADD_EXECUTABLE( distributedScanTestCuda distributedScanTestCuda.cu - OPTIONS ${CXX_TESTS_FLAGS} ) - TARGET_LINK_LIBRARIES( distributedScanTestCuda ${GTEST_BOTH_LIBRARIES} ) + OPTIONS ${CUDA_TESTS_FLAGS} ) + TARGET_LINK_LIBRARIES( distributedScanTestCuda ${TESTS_LIBRARIES} ) + TARGET_LINK_OPTIONS( distributedScanTestCuda PRIVATE ${TESTS_LINKER_FLAGS} ) endif() SET( mpi_test_parameters -np 4 -H localhost:4 "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/distributedScanTest${CMAKE_EXECUTABLE_SUFFIX}" ) diff --git a/src/UnitTests/Algorithms/Segments/CMakeLists.txt b/src/UnitTests/Algorithms/Segments/CMakeLists.txt index 22f0794ad..5dd9726bb 100644 --- a/src/UnitTests/Algorithms/Segments/CMakeLists.txt +++ b/src/UnitTests/Algorithms/Segments/CMakeLists.txt @@ -18,14 +18,16 @@ endif() foreach( target IN ITEMS ${CPP_TESTS} ) add_executable( ${target} ${target}.cpp ) target_compile_options( ${target} PRIVATE ${CXX_TESTS_FLAGS} ) - target_link_libraries( ${target} ${GTEST_BOTH_LIBRARIES} ) + target_link_libraries( ${target} ${TESTS_LIBRARIES} ) + target_link_options( ${target} PRIVATE ${TESTS_LINKER_FLAGS} ) add_test( ${target} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${target}${CMAKE_EXECUTABLE_SUFFIX} ) endforeach() if( BUILD_CUDA ) foreach( target IN ITEMS ${CUDA_TESTS} ) - cuda_add_executable( ${target} ${target}.cu OPTIONS ${CXX_TESTS_FLAGS} ) - target_link_libraries( ${target} ${GTEST_BOTH_LIBRARIES} ) + cuda_add_executable( ${target} ${target}.cu OPTIONS ${CUDA_TESTS_FLAGS} ) + target_link_libraries( ${target} ${TESTS_LIBRARIES} ) + target_link_options( ${target} PRIVATE ${TESTS_LINKER_FLAGS} ) add_test( ${target} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${target}${CMAKE_EXECUTABLE_SUFFIX} ) endforeach() endif() diff --git a/src/UnitTests/Algorithms/Sorting/CMakeLists.txt b/src/UnitTests/Algorithms/Sorting/CMakeLists.txt index 56fca2216..692314ab6 100644 --- a/src/UnitTests/Algorithms/Sorting/CMakeLists.txt +++ b/src/UnitTests/Algorithms/Sorting/CMakeLists.txt @@ -15,14 +15,16 @@ endif() foreach( target IN ITEMS ${CPP_TESTS} ) add_executable( ${target} ${target}.cpp ) target_compile_options( ${target} PRIVATE ${CXX_TESTS_FLAGS} ) - target_link_libraries( ${target} ${GTEST_BOTH_LIBRARIES} ) + target_link_libraries( ${target} ${TESTS_LIBRARIES} ) + target_link_options( ${target} PRIVATE ${TESTS_LINKER_FLAGS} ) add_test( ${target} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${target}${CMAKE_EXECUTABLE_SUFFIX} ) endforeach() if( BUILD_CUDA ) foreach( target IN ITEMS ${CUDA_TESTS} ) - cuda_add_executable( ${target} ${target}.cu OPTIONS ${CXX_TESTS_FLAGS} ) - target_link_libraries( ${target} ${GTEST_BOTH_LIBRARIES} ) + cuda_add_executable( ${target} ${target}.cu OPTIONS ${CUDA_TESTS_FLAGS} ) + target_link_libraries( ${target} ${TESTS_LIBRARIES} ) + target_link_options( ${target} PRIVATE ${TESTS_LINKER_FLAGS} ) add_test( ${target} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${target}${CMAKE_EXECUTABLE_SUFFIX} ) endforeach() endif() diff --git a/src/UnitTests/Arithmetics/CMakeLists.txt b/src/UnitTests/Arithmetics/CMakeLists.txt index 17986122a..eb0acde7b 100644 --- a/src/UnitTests/Arithmetics/CMakeLists.txt +++ b/src/UnitTests/Arithmetics/CMakeLists.txt @@ -4,21 +4,22 @@ if( HAVE_GMP ) ADD_EXECUTABLE( MultiPrecisionTest MultiPrecisionTest.cpp ../MultiPrecision.cpp ) TARGET_COMPILE_OPTIONS( MultiPrecisionTest PRIVATE ${CXX_TESTS_FLAGS} ) TARGET_LINK_LIBRARIES( MultiPrecisionTest - ${GTEST_BOTH_LIBRARIES} + ${TESTS_LIBRARIES} ${GMP_LIBRARIES} ) + TARGET_LINK_OPTIONS( MultiPrecisionTest PRIVATE ${TESTS_LINKER_FLAGS} ) ADD_TEST( MultiPrecisionTest ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/MultiPrecisionTest${CMAKE_EXECUTABLE_SUFFIX} ) endif( HAVE_GMP ) -# TODO: Fix the following tests +# TODO: Fix the following tests #ADD_EXECUTABLE( QuadTest QuadTest.cpp ) #TARGET_COMPILE_OPTIONS( QuadTest PRIVATE ${CXX_TESTS_FLAGS} ) -#TARGET_LINK_LIBRARIES( QuadTest ${GTEST_BOTH_LIBRARIES} ) - +#TARGET_LINK_LIBRARIES( QuadTest ${TESTS_LIBRARIES} ) + #ADD_EXECUTABLE( DoubleTest DoubleTest.cpp ) #TARGET_COMPILE_OPTIONS( DoubleTest PRIVATE ${CXX_TESTS_FLAGS} ) -#TARGET_LINK_LIBRARIES( DoubleTest ${GTEST_BOTH_LIBRARIES} ) - +#TARGET_LINK_LIBRARIES( DoubleTest ${TESTS_LIBRARIES} ) + #ADD_TEST( QuadTest ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/QuadTest${CMAKE_EXECUTABLE_SUFFIX} ) #ADD_TEST( DoubleTest ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/DoubleTest${CMAKE_EXECUTABLE_SUFFIX} ) diff --git a/src/UnitTests/CMakeLists.txt b/src/UnitTests/CMakeLists.txt index e2ea5edee..f006fb32d 100644 --- a/src/UnitTests/CMakeLists.txt +++ b/src/UnitTests/CMakeLists.txt @@ -26,14 +26,16 @@ endif() foreach( target IN ITEMS ${CPP_TESTS} ) add_executable( ${target} ${target}.cpp ) target_compile_options( ${target} PRIVATE ${CXX_TESTS_FLAGS} ) - target_link_libraries( ${target} ${GTEST_BOTH_LIBRARIES} ) + target_link_libraries( ${target} ${TESTS_LIBRARIES} ) + target_link_options( ${target} PRIVATE ${TESTS_LINKER_FLAGS} ) add_test( ${target} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${target}${CMAKE_EXECUTABLE_SUFFIX} ) endforeach() if( BUILD_CUDA ) foreach( target IN ITEMS ${CUDA_TESTS} ) - cuda_add_executable( ${target} ${target}.cu OPTIONS ${CXX_TESTS_FLAGS} ) - target_link_libraries( ${target} ${GTEST_BOTH_LIBRARIES} ) + cuda_add_executable( ${target} ${target}.cu OPTIONS ${CUDA_TESTS_FLAGS} ) + target_link_libraries( ${target} ${TESTS_LIBRARIES} ) + target_link_options( ${target} PRIVATE ${TESTS_LINKER_FLAGS} ) add_test( ${target} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${target}${CMAKE_EXECUTABLE_SUFFIX} ) endforeach() endif() @@ -46,7 +48,8 @@ if( ZLIB_FOUND ) target_compile_definitions( ${target} PUBLIC "-DHAVE_ZLIB" ) target_compile_options( ${target} PRIVATE ${CXX_TESTS_FLAGS} ) target_include_directories(${target} PUBLIC ${ZLIB_INCLUDE_DIRS}) - target_link_libraries( ${target} ${GTEST_BOTH_LIBRARIES} ${ZLIB_LIBRARIES} ) + target_link_libraries( ${target} ${TESTS_LIBRARIES} ${ZLIB_LIBRARIES} ) + target_link_options( ${target} PRIVATE ${TESTS_LINKER_FLAGS} ) add_test( ${target} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${target}${CMAKE_EXECUTABLE_SUFFIX} ) endforeach() endif() diff --git a/src/UnitTests/Containers/CMakeLists.txt b/src/UnitTests/Containers/CMakeLists.txt index 4c3945202..b2d0994dd 100644 --- a/src/UnitTests/Containers/CMakeLists.txt +++ b/src/UnitTests/Containers/CMakeLists.txt @@ -30,14 +30,16 @@ set( CUDA_TESTS foreach( target IN ITEMS ${CPP_TESTS} ) add_executable( ${target} ${target}.cpp ) target_compile_options( ${target} PRIVATE ${CXX_TESTS_FLAGS} ) - target_link_libraries( ${target} ${GTEST_BOTH_LIBRARIES} ) + target_link_libraries( ${target} ${TESTS_LIBRARIES} ) + target_link_options( ${target} PRIVATE ${TESTS_LINKER_FLAGS} ) add_test( ${target} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${target}${CMAKE_EXECUTABLE_SUFFIX} ) endforeach() if( BUILD_CUDA ) foreach( target IN ITEMS ${CUDA_TESTS} ) - cuda_add_executable( ${target} ${target}.cu OPTIONS ${CXX_TESTS_FLAGS} ) - target_link_libraries( ${target} ${GTEST_BOTH_LIBRARIES} ) + cuda_add_executable( ${target} ${target}.cu OPTIONS ${CUDA_TESTS_FLAGS} ) + target_link_libraries( ${target} ${TESTS_LIBRARIES} ) + target_link_options( ${target} PRIVATE ${TESTS_LINKER_FLAGS} ) add_test( ${target} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${target}${CMAKE_EXECUTABLE_SUFFIX} ) endforeach() endif() @@ -46,35 +48,41 @@ endif() if( ${BUILD_MPI} ) if( BUILD_CUDA ) CUDA_ADD_EXECUTABLE( DistributedArrayTest DistributedArrayTestCuda.cu - OPTIONS ${CXX_TESTS_FLAGS} ) - TARGET_LINK_LIBRARIES( DistributedArrayTest ${GTEST_BOTH_LIBRARIES} ) + OPTIONS ${CUDA_TESTS_FLAGS} ) else() ADD_EXECUTABLE( DistributedArrayTest DistributedArrayTest.cpp ) TARGET_COMPILE_OPTIONS( DistributedArrayTest PRIVATE ${CXX_TESTS_FLAGS} ) - TARGET_LINK_LIBRARIES( DistributedArrayTest ${GTEST_BOTH_LIBRARIES} ) endif() + target_link_libraries( DistributedArrayTest ${TESTS_LIBRARIES} ) + target_link_options( DistributedArrayTest PRIVATE ${TESTS_LINKER_FLAGS} ) ADD_EXECUTABLE( DistributedVectorBinaryOperationsTest DistributedVectorBinaryOperationsTest.cpp ) TARGET_COMPILE_OPTIONS( DistributedVectorBinaryOperationsTest PRIVATE ${CXX_TESTS_FLAGS} ) - TARGET_LINK_LIBRARIES( DistributedVectorBinaryOperationsTest ${GTEST_BOTH_LIBRARIES} ) + TARGET_LINK_LIBRARIES( DistributedVectorBinaryOperationsTest ${TESTS_LIBRARIES} ) + target_link_options( DistributedVectorBinaryOperationsTest PRIVATE ${TESTS_LINKER_FLAGS} ) ADD_EXECUTABLE( DistributedVectorUnaryOperationsTest DistributedVectorUnaryOperationsTest.cpp ) TARGET_COMPILE_OPTIONS( DistributedVectorUnaryOperationsTest PRIVATE ${CXX_TESTS_FLAGS} ) - TARGET_LINK_LIBRARIES( DistributedVectorUnaryOperationsTest ${GTEST_BOTH_LIBRARIES} ) + TARGET_LINK_LIBRARIES( DistributedVectorUnaryOperationsTest ${TESTS_LIBRARIES} ) + target_link_options( DistributedVectorUnaryOperationsTest PRIVATE ${TESTS_LINKER_FLAGS} ) ADD_EXECUTABLE( DistributedVectorVerticalOperationsTest DistributedVectorVerticalOperationsTest.cpp ) TARGET_COMPILE_OPTIONS( DistributedVectorVerticalOperationsTest PRIVATE ${CXX_TESTS_FLAGS} ) - TARGET_LINK_LIBRARIES( DistributedVectorVerticalOperationsTest ${GTEST_BOTH_LIBRARIES} ) + TARGET_LINK_LIBRARIES( DistributedVectorVerticalOperationsTest ${TESTS_LIBRARIES} ) + target_link_options( DistributedVectorVerticalOperationsTest PRIVATE ${TESTS_LINKER_FLAGS} ) if( BUILD_CUDA ) - CUDA_ADD_EXECUTABLE( DistributedVectorBinaryOperationsTestCuda DistributedVectorBinaryOperationsTestCuda.cu OPTIONS ${CXX_TESTS_FLAGS} ) - TARGET_LINK_LIBRARIES( DistributedVectorBinaryOperationsTestCuda ${GTEST_BOTH_LIBRARIES} ) + CUDA_ADD_EXECUTABLE( DistributedVectorBinaryOperationsTestCuda DistributedVectorBinaryOperationsTestCuda.cu OPTIONS ${CUDA_TESTS_FLAGS} ) + TARGET_LINK_LIBRARIES( DistributedVectorBinaryOperationsTestCuda ${TESTS_LIBRARIES} ) + target_link_options( DistributedVectorBinaryOperationsTestCuda PRIVATE ${TESTS_LINKER_FLAGS} ) - CUDA_ADD_EXECUTABLE( DistributedVectorUnaryOperationsTestCuda DistributedVectorUnaryOperationsTestCuda.cu OPTIONS ${CXX_TESTS_FLAGS} ) - TARGET_LINK_LIBRARIES( DistributedVectorUnaryOperationsTestCuda ${GTEST_BOTH_LIBRARIES} ) + CUDA_ADD_EXECUTABLE( DistributedVectorUnaryOperationsTestCuda DistributedVectorUnaryOperationsTestCuda.cu OPTIONS ${CUDA_TESTS_FLAGS} ) + TARGET_LINK_LIBRARIES( DistributedVectorUnaryOperationsTestCuda ${TESTS_LIBRARIES} ) + target_link_options( DistributedVectorUnaryOperationsTestCuda PRIVATE ${TESTS_LINKER_FLAGS} ) - CUDA_ADD_EXECUTABLE( DistributedVectorVerticalOperationsTestCuda DistributedVectorVerticalOperationsTestCuda.cu OPTIONS ${CXX_TESTS_FLAGS} ) - TARGET_LINK_LIBRARIES( DistributedVectorVerticalOperationsTestCuda ${GTEST_BOTH_LIBRARIES} ) + CUDA_ADD_EXECUTABLE( DistributedVectorVerticalOperationsTestCuda DistributedVectorVerticalOperationsTestCuda.cu OPTIONS ${CUDA_TESTS_FLAGS} ) + TARGET_LINK_LIBRARIES( DistributedVectorVerticalOperationsTestCuda ${TESTS_LIBRARIES} ) + target_link_options( DistributedVectorVerticalOperationsTestCuda PRIVATE ${TESTS_LINKER_FLAGS} ) endif( BUILD_CUDA ) SET( mpi_test_parameters -np 4 -H localhost:4 "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/DistributedArrayTest${CMAKE_EXECUTABLE_SUFFIX}" ) diff --git a/src/UnitTests/Containers/ndarray/CMakeLists.txt b/src/UnitTests/Containers/ndarray/CMakeLists.txt index f5fb11bdf..dff746f15 100644 --- a/src/UnitTests/Containers/ndarray/CMakeLists.txt +++ b/src/UnitTests/Containers/ndarray/CMakeLists.txt @@ -9,14 +9,16 @@ endif() foreach( target IN ITEMS ${CPP_TESTS} ) add_executable( ${target} ${target}.cpp ) target_compile_options( ${target} PRIVATE ${CXX_TESTS_FLAGS} ) - target_link_libraries( ${target} ${GTEST_BOTH_LIBRARIES} ) + target_link_libraries( ${target} ${TESTS_LIBRARIES} ) + target_link_options( ${target} PRIVATE ${TESTS_LINKER_FLAGS} ) add_test( ${target} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${target}${CMAKE_EXECUTABLE_SUFFIX} ) endforeach() if( BUILD_CUDA ) foreach( target IN ITEMS ${CUDA_TESTS} ) - cuda_add_executable( ${target} ${target}.cu OPTIONS ${CXX_TESTS_FLAGS} ) - target_link_libraries( ${target} ${GTEST_BOTH_LIBRARIES} ) + cuda_add_executable( ${target} ${target}.cu OPTIONS ${CUDA_TESTS_FLAGS} ) + target_link_libraries( ${target} ${TESTS_LIBRARIES} ) + target_link_options( ${target} PRIVATE ${TESTS_LINKER_FLAGS} ) add_test( ${target} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${target}${CMAKE_EXECUTABLE_SUFFIX} ) endforeach() endif() @@ -24,36 +26,44 @@ endif() if( ${BUILD_MPI} ) if( BUILD_CUDA ) CUDA_ADD_EXECUTABLE( DistributedNDArray_1D_test DistributedNDArray_1D_test.cu - OPTIONS ${CXX_TESTS_FLAGS} ) - TARGET_LINK_LIBRARIES( DistributedNDArray_1D_test ${GTEST_BOTH_LIBRARIES} ) + OPTIONS ${CUDA_TESTS_FLAGS} ) + TARGET_LINK_LIBRARIES( DistributedNDArray_1D_test ${TESTS_LIBRARIES} ) + target_link_options( DistributedNDArray_1D_test PRIVATE ${TESTS_LINKER_FLAGS} ) CUDA_ADD_EXECUTABLE( DistributedNDArray_semi1D_test DistributedNDArray_semi1D_test.cu - OPTIONS ${CXX_TESTS_FLAGS} ) - TARGET_LINK_LIBRARIES( DistributedNDArray_semi1D_test ${GTEST_BOTH_LIBRARIES} ) + OPTIONS ${CUDA_TESTS_FLAGS} ) + TARGET_LINK_LIBRARIES( DistributedNDArray_semi1D_test ${TESTS_LIBRARIES} ) + target_link_options( DistributedNDArray_semi1D_test PRIVATE ${TESTS_LINKER_FLAGS} ) CUDA_ADD_EXECUTABLE( DistributedNDArrayOverlaps_1D_test DistributedNDArrayOverlaps_1D_test.cu - OPTIONS ${CXX_TESTS_FLAGS} ) - TARGET_LINK_LIBRARIES( DistributedNDArrayOverlaps_1D_test ${GTEST_BOTH_LIBRARIES} ) + OPTIONS ${CUDA_TESTS_FLAGS} ) + TARGET_LINK_LIBRARIES( DistributedNDArrayOverlaps_1D_test ${TESTS_LIBRARIES} ) + target_link_options( DistributedNDArrayOverlaps_1D_test PRIVATE ${TESTS_LINKER_FLAGS} ) CUDA_ADD_EXECUTABLE( DistributedNDArrayOverlaps_semi1D_test DistributedNDArrayOverlaps_semi1D_test.cu - OPTIONS ${CXX_TESTS_FLAGS} ) - TARGET_LINK_LIBRARIES( DistributedNDArrayOverlaps_semi1D_test ${GTEST_BOTH_LIBRARIES} ) + OPTIONS ${CUDA_TESTS_FLAGS} ) + TARGET_LINK_LIBRARIES( DistributedNDArrayOverlaps_semi1D_test ${TESTS_LIBRARIES} ) + target_link_options( DistributedNDArrayOverlaps_semi1D_test PRIVATE ${TESTS_LINKER_FLAGS} ) else() ADD_EXECUTABLE( DistributedNDArray_1D_test DistributedNDArray_1D_test.cpp ) TARGET_COMPILE_OPTIONS( DistributedNDArray_1D_test PRIVATE ${CXX_TESTS_FLAGS} ) - TARGET_LINK_LIBRARIES( DistributedNDArray_1D_test ${GTEST_BOTH_LIBRARIES} ) + TARGET_LINK_LIBRARIES( DistributedNDArray_1D_test ${TESTS_LIBRARIES} ) + target_link_options( DistributedNDArray_1D_test PRIVATE ${TESTS_LINKER_FLAGS} ) ADD_EXECUTABLE( DistributedNDArray_semi1D_test DistributedNDArray_semi1D_test.cpp ) TARGET_COMPILE_OPTIONS( DistributedNDArray_semi1D_test PRIVATE ${CXX_TESTS_FLAGS} ) - TARGET_LINK_LIBRARIES( DistributedNDArray_semi1D_test ${GTEST_BOTH_LIBRARIES} ) + TARGET_LINK_LIBRARIES( DistributedNDArray_semi1D_test ${TESTS_LIBRARIES} ) + target_link_options( DistributedNDArray_semi1D_test PRIVATE ${TESTS_LINKER_FLAGS} ) ADD_EXECUTABLE( DistributedNDArrayOverlaps_1D_test DistributedNDArrayOverlaps_1D_test.cpp ) TARGET_COMPILE_OPTIONS( DistributedNDArrayOverlaps_1D_test PRIVATE ${CXX_TESTS_FLAGS} ) - TARGET_LINK_LIBRARIES( DistributedNDArrayOverlaps_1D_test ${GTEST_BOTH_LIBRARIES} ) + TARGET_LINK_LIBRARIES( DistributedNDArrayOverlaps_1D_test ${TESTS_LIBRARIES} ) + target_link_options( DistributedNDArrayOverlaps_1D_test PRIVATE ${TESTS_LINKER_FLAGS} ) ADD_EXECUTABLE( DistributedNDArrayOverlaps_semi1D_test DistributedNDArrayOverlaps_semi1D_test.cpp ) TARGET_COMPILE_OPTIONS( DistributedNDArrayOverlaps_semi1D_test PRIVATE ${CXX_TESTS_FLAGS} ) - TARGET_LINK_LIBRARIES( DistributedNDArrayOverlaps_semi1D_test ${GTEST_BOTH_LIBRARIES} ) + TARGET_LINK_LIBRARIES( DistributedNDArrayOverlaps_semi1D_test ${TESTS_LIBRARIES} ) + target_link_options( DistributedNDArrayOverlaps_semi1D_test PRIVATE ${TESTS_LINKER_FLAGS} ) endif() SET( mpi_test_parameters -np 4 -H localhost:4 "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/DistributedNDArray_1D_test${CMAKE_EXECUTABLE_SUFFIX}" ) diff --git a/src/UnitTests/Functions/CMakeLists.txt b/src/UnitTests/Functions/CMakeLists.txt index 36f46f70e..81636f5f4 100644 --- a/src/UnitTests/Functions/CMakeLists.txt +++ b/src/UnitTests/Functions/CMakeLists.txt @@ -13,7 +13,8 @@ find_package( tinyxml2 QUIET ) foreach( target IN ITEMS ${CPP_TESTS} ) add_executable( ${target} ${target}.cpp ) target_compile_options( ${target} PRIVATE ${CXX_TESTS_FLAGS} ) - target_link_libraries( ${target} ${GTEST_BOTH_LIBRARIES} ) + target_link_libraries( ${target} ${TESTS_LIBRARIES} ) + target_link_options( ${target} PRIVATE ${TESTS_LINKER_FLAGS} ) target_compile_definitions(${target} PUBLIC "-DHAVE_ZLIB") target_include_directories(${target} PUBLIC ${ZLIB_INCLUDE_DIRS}) @@ -27,8 +28,9 @@ endforeach() if( BUILD_CUDA ) foreach( target IN ITEMS ${CUDA_TESTS} ) - cuda_add_executable( ${target} ${target}.cu OPTIONS ${CXX_TESTS_FLAGS} ) - target_link_libraries( ${target} ${GTEST_BOTH_LIBRARIES} ) + cuda_add_executable( ${target} ${target}.cu OPTIONS ${CUDA_TESTS_FLAGS} ) + target_link_libraries( ${target} ${TESTS_LIBRARIES} ) + target_link_options( ${target} PRIVATE ${TESTS_LINKER_FLAGS} ) add_test( ${target} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${target}${CMAKE_EXECUTABLE_SUFFIX} ) endforeach() endif() diff --git a/src/UnitTests/MPI/CMakeLists.txt b/src/UnitTests/MPI/CMakeLists.txt index 5ed7534bd..2c79e14a2 100644 --- a/src/UnitTests/MPI/CMakeLists.txt +++ b/src/UnitTests/MPI/CMakeLists.txt @@ -4,7 +4,8 @@ if( ${BUILD_MPI} ) foreach( target IN ITEMS ${CPP_TESTS} ) add_executable( ${target} ${target}.cpp ) target_compile_options( ${target} PRIVATE ${CXX_TESTS_FLAGS} ) - target_link_libraries( ${target} ${GTEST_BOTH_LIBRARIES} ) + target_link_libraries( ${target} ${TESTS_LIBRARIES} ) + target_link_options( ${target} PRIVATE ${TESTS_LINKER_FLAGS} ) foreach( np IN ITEMS 2 3 4 ) set( mpirun_parameters -np ${np} -H localhost:${np} ) diff --git a/src/UnitTests/Matrices/CMakeLists.txt b/src/UnitTests/Matrices/CMakeLists.txt index 2fe0f39ee..4cc18556f 100644 --- a/src/UnitTests/Matrices/CMakeLists.txt +++ b/src/UnitTests/Matrices/CMakeLists.txt @@ -48,14 +48,16 @@ endif() foreach( target IN ITEMS ${CPP_TESTS} ) add_executable( ${target} ${target}.cpp ) target_compile_options( ${target} PRIVATE ${CXX_TESTS_FLAGS} ) - target_link_libraries( ${target} ${GTEST_BOTH_LIBRARIES} ) + target_link_libraries( ${target} ${TESTS_LIBRARIES} ) + target_link_options( ${target} PRIVATE ${TESTS_LINKER_FLAGS} ) add_test( ${target} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${target}${CMAKE_EXECUTABLE_SUFFIX} ) endforeach() if( BUILD_CUDA ) foreach( target IN ITEMS ${CUDA_TESTS} ) - cuda_add_executable( ${target} ${target}.cu OPTIONS ${CXX_TESTS_FLAGS} ) - target_link_libraries( ${target} ${GTEST_BOTH_LIBRARIES} ) + cuda_add_executable( ${target} ${target}.cu OPTIONS ${CUDA_TESTS_FLAGS} ) + target_link_libraries( ${target} ${TESTS_LIBRARIES} ) + target_link_options( ${target} PRIVATE ${TESTS_LINKER_FLAGS} ) add_test( ${target} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${target}${CMAKE_EXECUTABLE_SUFFIX} ) endforeach() endif() @@ -63,13 +65,13 @@ endif() if( ${BUILD_MPI} ) if( BUILD_CUDA ) CUDA_ADD_EXECUTABLE( DistributedMatrixTest DistributedMatrixTest.cu - OPTIONS ${CXX_TESTS_FLAGS} ) - TARGET_LINK_LIBRARIES( DistributedMatrixTest ${GTEST_BOTH_LIBRARIES} ${CUDA_cudadevrt_LIBRARY} ) + OPTIONS ${CUDA_TESTS_FLAGS} ) else() ADD_EXECUTABLE( DistributedMatrixTest DistributedMatrixTest.cpp ) TARGET_COMPILE_OPTIONS( DistributedMatrixTest PRIVATE ${CXX_TESTS_FLAGS} ) - TARGET_LINK_LIBRARIES( DistributedMatrixTest ${GTEST_BOTH_LIBRARIES} ) endif() + target_link_libraries( DistributedMatrixTest ${TESTS_LIBRARIES} ) + target_link_options( DistributedMatrixTest PRIVATE ${TESTS_LINKER_FLAGS} ) SET( mpi_test_parameters -np 4 -H localhost:4 "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/DistributedMatrixTest${CMAKE_EXECUTABLE_SUFFIX}" ) ADD_TEST( NAME DistributedMatrixTest COMMAND "mpirun" ${mpi_test_parameters}) diff --git a/src/UnitTests/Matrices/Legacy/CMakeLists.txt b/src/UnitTests/Matrices/Legacy/CMakeLists.txt index 0decf44e2..e4aa19a7f 100644 --- a/src/UnitTests/Matrices/Legacy/CMakeLists.txt +++ b/src/UnitTests/Matrices/Legacy/CMakeLists.txt @@ -26,14 +26,16 @@ endif() foreach( target IN ITEMS ${CPP_TESTS} ) add_executable( ${target} ${target}.cpp ) target_compile_options( ${target} PRIVATE ${CXX_TESTS_FLAGS} ) - target_link_libraries( ${target} ${GTEST_BOTH_LIBRARIES} ) + target_link_libraries( ${target} ${TESTS_LIBRARIES} ) + target_link_options( ${target} PRIVATE ${TESTS_LINKER_FLAGS} ) add_test( ${target} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${target}${CMAKE_EXECUTABLE_SUFFIX} ) endforeach() if( BUILD_CUDA ) foreach( target IN ITEMS ${CUDA_TESTS} ) - cuda_add_executable( ${target} ${target}.cu OPTIONS ${CXX_TESTS_FLAGS} ) - target_link_libraries( ${target} ${GTEST_BOTH_LIBRARIES} ) + cuda_add_executable( ${target} ${target}.cu OPTIONS ${CUDA_TESTS_FLAGS} ) + target_link_libraries( ${target} ${TESTS_LIBRARIES} ) + target_link_options( ${target} PRIVATE ${TESTS_LINKER_FLAGS} ) add_test( ${target} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${target}${CMAKE_EXECUTABLE_SUFFIX} ) endforeach() endif() diff --git a/src/UnitTests/Meshes/CMakeLists.txt b/src/UnitTests/Meshes/CMakeLists.txt index b9af39b54..86cb34d5c 100644 --- a/src/UnitTests/Meshes/CMakeLists.txt +++ b/src/UnitTests/Meshes/CMakeLists.txt @@ -2,33 +2,40 @@ ADD_SUBDIRECTORY( DistributedMeshes ) ADD_EXECUTABLE( EntityTagsTest EntityTagsTest.cpp ) TARGET_COMPILE_OPTIONS( EntityTagsTest PRIVATE ${CXX_TESTS_FLAGS} ) -TARGET_LINK_LIBRARIES( EntityTagsTest ${GTEST_BOTH_LIBRARIES} ) +TARGET_LINK_LIBRARIES( EntityTagsTest ${TESTS_LIBRARIES} ) +target_link_options( EntityTagsTest PRIVATE ${TESTS_LINKER_FLAGS} ) # Mesh cannot be compiled by nvcc < 9 due to bugs in the compiler if( ${BUILD_CUDA} AND ${CUDA_VERSION_MAJOR} GREATER_EQUAL 9 ) CUDA_ADD_EXECUTABLE( MeshTest MeshTest.cu - OPTIONS ${CXX_TESTS_FLAGS} ) - TARGET_LINK_LIBRARIES( MeshTest ${GTEST_BOTH_LIBRARIES} ) + OPTIONS ${CUDA_TESTS_FLAGS} ) + TARGET_LINK_LIBRARIES( MeshTest ${TESTS_LIBRARIES} ) + target_link_options( MeshTest PRIVATE ${TESTS_LINKER_FLAGS} ) CUDA_ADD_EXECUTABLE( MeshTraverserTest MeshTraverserTest.cu - OPTIONS ${CXX_TESTS_FLAGS} ) - TARGET_LINK_LIBRARIES( MeshTraverserTest ${GTEST_BOTH_LIBRARIES} ) + OPTIONS ${CUDA_TESTS_FLAGS} ) + TARGET_LINK_LIBRARIES( MeshTraverserTest ${TESTS_LIBRARIES} ) + target_link_options( MeshTraverserTest PRIVATE ${TESTS_LINKER_FLAGS} ) CUDA_ADD_EXECUTABLE( MeshOrderingTest MeshOrderingTest.cu - OPTIONS ${CXX_TESTS_FLAGS} ) - TARGET_LINK_LIBRARIES( MeshOrderingTest ${GTEST_BOTH_LIBRARIES} ) + OPTIONS ${CUDA_TESTS_FLAGS} ) + TARGET_LINK_LIBRARIES( MeshOrderingTest ${TESTS_LIBRARIES} ) + target_link_options( MeshOrderingTest PRIVATE ${TESTS_LINKER_FLAGS} ) else() ADD_EXECUTABLE( MeshTest MeshTest.cpp ) TARGET_COMPILE_OPTIONS( MeshTest PRIVATE ${CXX_TESTS_FLAGS} ) - TARGET_LINK_LIBRARIES( MeshTest ${GTEST_BOTH_LIBRARIES} ) + TARGET_LINK_LIBRARIES( MeshTest ${TESTS_LIBRARIES} ) + target_link_options( MeshTest PRIVATE ${TESTS_LINKER_FLAGS} ) ADD_EXECUTABLE( MeshTraverserTest MeshTraverserTest.cpp ) TARGET_COMPILE_OPTIONS( MeshTraverserTest PRIVATE ${CXX_TESTS_FLAGS} ) - TARGET_LINK_LIBRARIES( MeshTraverserTest ${GTEST_BOTH_LIBRARIES} ) + TARGET_LINK_LIBRARIES( MeshTraverserTest ${TESTS_LIBRARIES} ) + target_link_options( MeshTraverserTest PRIVATE ${TESTS_LINKER_FLAGS} ) ADD_EXECUTABLE( MeshOrderingTest MeshOrderingTest.cpp ) TARGET_COMPILE_OPTIONS( MeshOrderingTest PRIVATE ${CXX_TESTS_FLAGS} ) - TARGET_LINK_LIBRARIES( MeshOrderingTest ${GTEST_BOTH_LIBRARIES} ) + TARGET_LINK_LIBRARIES( MeshOrderingTest ${TESTS_LIBRARIES} ) + target_link_options( MeshOrderingTest PRIVATE ${TESTS_LINKER_FLAGS} ) endif() ADD_TEST( EntityTagsTest ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/EntityTagsTest${CMAKE_EXECUTABLE_SUFFIX} ) @@ -45,7 +52,8 @@ if( ZLIB_FOUND AND tinyxml2_FOUND ) foreach( target IN ITEMS NetgenReaderTest VTKReaderTest VTUReaderTest VTIReaderTest ) add_executable(${target} ${target}.cpp) target_compile_options(${target} PRIVATE ${CXX_TESTS_FLAGS} ) - target_link_libraries(${target} ${GTEST_BOTH_LIBRARIES}) + target_link_libraries(${target} ${TESTS_LIBRARIES}) + target_link_options( ${target} PRIVATE ${TESTS_LINKER_FLAGS} ) target_compile_definitions(${target} PUBLIC "-DHAVE_ZLIB") target_include_directories(${target} PUBLIC ${ZLIB_INCLUDE_DIRS}) diff --git a/src/UnitTests/Meshes/DistributedMeshes/CMakeLists.txt b/src/UnitTests/Meshes/DistributedMeshes/CMakeLists.txt index a48177c58..1d7aaadaa 100644 --- a/src/UnitTests/Meshes/DistributedMeshes/CMakeLists.txt +++ b/src/UnitTests/Meshes/DistributedMeshes/CMakeLists.txt @@ -1,15 +1,18 @@ ADD_EXECUTABLE( DirectionsTest DirectionsTest.cpp ) TARGET_COMPILE_OPTIONS( DirectionsTest PRIVATE ${CXX_TESTS_FLAGS} ) - TARGET_LINK_LIBRARIES( DirectionsTest ${GTEST_BOTH_LIBRARIES} ) + TARGET_LINK_LIBRARIES( DirectionsTest ${TESTS_LIBRARIES} ) + target_link_options( DirectionsTest PRIVATE ${TESTS_LINKER_FLAGS} ) ADD_EXECUTABLE( CopyEntitesTest CopyEntitiesTest.cpp ) TARGET_COMPILE_OPTIONS( CopyEntitesTest PRIVATE ${CXX_TESTS_FLAGS} ) - TARGET_LINK_LIBRARIES( CopyEntitesTest ${GTEST_BOTH_LIBRARIES} ) + TARGET_LINK_LIBRARIES( CopyEntitesTest ${TESTS_LIBRARIES} ) + target_link_options( CopyEntitesTest PRIVATE ${TESTS_LINKER_FLAGS} ) # FIXME: DistributedGrid refucktoring #ADD_EXECUTABLE( CutMeshFunctionTest CutMeshFunctionTest.cpp ) # TARGET_COMPILE_OPTIONS( CutMeshFunctionTest PRIVATE ${CXX_TESTS_FLAGS} ) -# TARGET_LINK_LIBRARIES( CutMeshFunctionTest ${GTEST_BOTH_LIBRARIES} ) +# TARGET_LINK_LIBRARIES( CutMeshFunctionTest ${TESTS_LIBRARIES} ) +# target_link_options( CutMeshFunctionTest PRIVATE ${TESTS_LINKER_FLAGS} ) ADD_TEST( NAME DirectionsTest COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/DirectionsTest${CMAKE_EXECUTABLE_SUFFIX} ) ADD_TEST( NAME CopyEntitesTest COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/CopyEntitesTest${CMAKE_EXECUTABLE_SUFFIX} ) @@ -18,32 +21,37 @@ ADD_TEST( NAME CopyEntitesTest COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/CopyEnt if( BUILD_MPI ) ADD_EXECUTABLE( DistributedGridTest_1D DistributedGridTest_1D.cpp ) TARGET_COMPILE_OPTIONS( DistributedGridTest_1D PRIVATE ${CXX_TESTS_FLAGS} ) - TARGET_LINK_LIBRARIES( DistributedGridTest_1D ${GTEST_BOTH_LIBRARIES} ) + TARGET_LINK_LIBRARIES( DistributedGridTest_1D ${TESTS_LIBRARIES} ) + target_link_options( DistributedGridTest_1D PRIVATE ${TESTS_LINKER_FLAGS} ) ADD_EXECUTABLE( DistributedGridTest_2D DistributedGridTest_2D.cpp ) TARGET_COMPILE_OPTIONS( DistributedGridTest_2D PRIVATE ${CXX_TESTS_FLAGS} ) - TARGET_LINK_LIBRARIES( DistributedGridTest_2D ${GTEST_BOTH_LIBRARIES} ) + TARGET_LINK_LIBRARIES( DistributedGridTest_2D ${TESTS_LIBRARIES} ) + target_link_options( DistributedGridTest_2D PRIVATE ${TESTS_LINKER_FLAGS} ) ADD_EXECUTABLE( DistributedGridTest_3D DistributedGridTest_3D.cpp ) TARGET_COMPILE_OPTIONS( DistributedGridTest_3D PRIVATE ${CXX_TESTS_FLAGS} ) - TARGET_LINK_LIBRARIES( DistributedGridTest_3D ${GTEST_BOTH_LIBRARIES} ) + TARGET_LINK_LIBRARIES( DistributedGridTest_3D ${TESTS_LIBRARIES} ) + target_link_options( DistributedGridTest_3D PRIVATE ${TESTS_LINKER_FLAGS} ) ADD_EXECUTABLE( CutDistributedGridTest CutDistributedGridTest.cpp ) TARGET_COMPILE_OPTIONS( CutDistributedGridTest PRIVATE ${CXX_TESTS_FLAGS} ) - TARGET_LINK_LIBRARIES( CutDistributedGridTest ${GTEST_BOTH_LIBRARIES} ) + TARGET_LINK_LIBRARIES( CutDistributedGridTest ${TESTS_LIBRARIES} ) + target_link_options( CutDistributedGridTest PRIVATE ${TESTS_LINKER_FLAGS} ) #ADD_EXECUTABLE( CutDistributedMeshFunctionTest CutDistributedMeshFunctionTest.cpp ) # TARGET_COMPILE_OPTIONS( CutDistributedMeshFunctionTest PRIVATE ${CXX_TESTS_FLAGS} ) -# TARGET_LINK_LIBRARIES( CutDistributedMeshFunctionTest ${GTEST_BOTH_LIBRARIES} ) +# TARGET_LINK_LIBRARIES( CutDistributedMeshFunctionTest ${TESTS_LIBRARIES} ) +# target_link_options( CutDistributedMeshFunctionTest PRIVATE ${TESTS_LINKER_FLAGS} ) if( BUILD_CUDA ) - cuda_add_executable( DistributedMeshTest DistributedMeshTest.cu OPTIONS ${CXX_TESTS_FLAGS}) - target_link_libraries( DistributedMeshTest ${GTEST_BOTH_LIBRARIES} ) + cuda_add_executable( DistributedMeshTest DistributedMeshTest.cu OPTIONS ${CUDA_TESTS_FLAGS}) else() add_executable( DistributedMeshTest DistributedMeshTest.cpp ) target_compile_options( DistributedMeshTest PRIVATE ${CXX_TESTS_FLAGS} ) - target_link_libraries( DistributedMeshTest ${GTEST_BOTH_LIBRARIES} ) endif() +target_link_libraries( DistributedMeshTest ${TESTS_LIBRARIES} ) +target_link_options( DistributedMeshTest PRIVATE ${TESTS_LINKER_FLAGS} ) # external libraries for tests which use mesh readers diff --git a/src/UnitTests/Pointers/CMakeLists.txt b/src/UnitTests/Pointers/CMakeLists.txt index 64f8414d1..2e15dafb2 100644 --- a/src/UnitTests/Pointers/CMakeLists.txt +++ b/src/UnitTests/Pointers/CMakeLists.txt @@ -7,14 +7,16 @@ endif() foreach( target IN ITEMS ${CPP_TESTS} ) add_executable( ${target} ${target}.cpp ) target_compile_options( ${target} PRIVATE ${CXX_TESTS_FLAGS} ) - target_link_libraries( ${target} ${GTEST_BOTH_LIBRARIES} ) + target_link_libraries( ${target} ${TESTS_LIBRARIES} ) + target_link_options( ${target} PRIVATE ${TESTS_LINKER_FLAGS} ) add_test( ${target} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${target}${CMAKE_EXECUTABLE_SUFFIX} ) endforeach() if( BUILD_CUDA ) foreach( target IN ITEMS ${CUDA_TESTS} ) - cuda_add_executable( ${target} ${target}.cu OPTIONS ${CXX_TESTS_FLAGS} ) - target_link_libraries( ${target} ${GTEST_BOTH_LIBRARIES} ) + cuda_add_executable( ${target} ${target}.cu OPTIONS ${CUDA_TESTS_FLAGS} ) + target_link_libraries( ${target} ${TESTS_LIBRARIES} ) + target_link_options( ${target} PRIVATE ${TESTS_LINKER_FLAGS} ) add_test( ${target} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${target}${CMAKE_EXECUTABLE_SUFFIX} ) endforeach() endif() -- GitLab From dc5ed0dd75b52203fadd2d41027ef21e64bc071e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Klinkovsk=C3=BD?= Date: Sat, 20 Nov 2021 09:48:05 +0100 Subject: [PATCH 2/8] Removed scripts for generating code coverage reports using clang --- cmake/UseCodeCoverage.cmake | 32 -- scripts/code_coverage/coverage.py | 483 ---------------- scripts/code_coverage/coverage_utils.py | 534 ------------------ .../code_coverage/html_templates/footer.html | 3 - .../code_coverage/html_templates/header.html | 24 - .../code_coverage/html_templates/table.html | 157 ----- scripts/code_coverage/static/css/style.css | 28 - scripts/make_coverage_report | 83 --- 8 files changed, 1344 deletions(-) delete mode 100644 cmake/UseCodeCoverage.cmake delete mode 100755 scripts/code_coverage/coverage.py delete mode 100644 scripts/code_coverage/coverage_utils.py delete mode 100644 scripts/code_coverage/html_templates/footer.html delete mode 100644 scripts/code_coverage/html_templates/header.html delete mode 100644 scripts/code_coverage/html_templates/table.html delete mode 100644 scripts/code_coverage/static/css/style.css delete mode 100755 scripts/make_coverage_report diff --git a/cmake/UseCodeCoverage.cmake b/cmake/UseCodeCoverage.cmake deleted file mode 100644 index d9ba5000c..000000000 --- a/cmake/UseCodeCoverage.cmake +++ /dev/null @@ -1,32 +0,0 @@ -#http://www.cmake.org/pipermail/cmake/2010-March/036063.html - - -if ( NOT CMAKE_BUILD_TYPE STREQUAL "Debug" ) - message( WARNING "Code coverage results with an optimised (non-Debug) build may be misleading" ) -endif ( NOT CMAKE_BUILD_TYPE STREQUAL "Debug" ) - -if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") - if ( NOT DEFINED CODECOV_OUTPUTFILE ) - set( CODECOV_OUTPUTFILE cmake_coverage.output ) - endif ( NOT DEFINED CODECOV_OUTPUTFILE ) - - if ( NOT DEFINED CODECOV_HTMLOUTPUTDIR ) - set( CODECOV_HTMLOUTPUTDIR coverage_results ) - endif ( NOT DEFINED CODECOV_HTMLOUTPUTDIR ) - - find_program( CODECOV_GCOV gcov ) - find_program( CODECOV_LCOV lcov ) - find_program( CODECOV_GENHTML genhtml ) - add_compile_options( -fprofile-arcs -ftest-coverage ) - link_libraries( gcov ) - set( CMAKE_EXE_LINKER_FLAGS ${CMAKE_EXE_LINKER_FLAGS} --coverage ) - add_custom_target( coverage_init ALL ${CODECOV_LCOV} --base-directory . --directory ${CMAKE_SOURCE_DIR} --no-external --output-file ${CODECOV_OUTPUTFILE} --capture --initial --quiet ) - add_custom_target( coverage ${CODECOV_LCOV} --base-directory . --directory ${CMAKE_SOURCE_DIR} --no-external --output-file ${CODECOV_OUTPUTFILE} --capture --quiet COMMAND genhtml --quiet -o ${CODECOV_HTMLOUTPUTDIR} ${CODECOV_OUTPUTFILE} ) -elseif(CMAKE_CXX_COMPILER_ID STREQUAL "Clang") - # http://clang.llvm.org/docs/SourceBasedCodeCoverage.html - add_compile_options( -fprofile-instr-generate -fcoverage-mapping ) - add_link_options( -fprofile-instr-generate -fcoverage-mapping ) - if( ${WITH_CUDA} ) - set(CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS} ; -Xcompiler -fprofile-instr-generate ; -Xcompiler -fcoverage-mapping ; -g ) - endif() -endif() diff --git a/scripts/code_coverage/coverage.py b/scripts/code_coverage/coverage.py deleted file mode 100755 index 68c20ba51..000000000 --- a/scripts/code_coverage/coverage.py +++ /dev/null @@ -1,483 +0,0 @@ -#! /usr/bin/env python3 -# vim: tabstop=4 softtabstop=4 - -""" -This script helps to generate code coverage report. - -It uses Clang Source-based Code Coverage, see -https://clang.llvm.org/docs/SourceBasedCodeCoverage.html - -Example usage: - python3 scripts/code_coverage/coverage.py \\ - crypto_unittests url_unittests \\ - -b out/coverage -o out/report \\ - -f url/ -f crypto/ - -The command above runs the crypto_unittests and url_unittests targets and -creates a coverage report for them. The coverage report is filtered to include -only files and sub-directories under url/ and crypto/ directories. - -For more options, please refer to tools/code_coverage/coverage.py -h. - -This script is based on Chromium code coverage scripts. For an overview of how -code coverage works in Chromium, please refer to -https://chromium.googlesource.com/chromium/src/+/master/docs/testing/code_coverage.md -""" - -import argparse -import json -import logging -import os -import shutil -import subprocess - -import coverage_utils - -# Absolute path to the root of the checkout. -SRC_ROOT_PATH = None - -# Build directory, the value is parsed from command line arguments. -BUILD_DIR = None - -# Output directory for generated artifacts, the value is parsed from command -# line arguemnts. -OUTPUT_DIR = None - -# Name of the file extension for profraw data files. -PROFRAW_FILE_EXTENSION = "profraw" - -# Name of the final profdata file, and this file needs to be passed to -# "llvm-cov" command in order to call "llvm-cov show" to inspect the -# line-by-line coverage of specific files. -PROFDATA_FILE_NAME = "coverage.profdata" - -# Name of the file with summary information generated by llvm-cov export. -SUMMARY_FILE_NAME = "summary.json" - -LOGS_DIR_NAME = "logs" - -# Retry failed merges. -MERGE_RETRIES = 3 - -# String to replace with actual llvm profile path. -LLVM_PROFILE_FILE_PATH_SUBSTITUTION = "" - - -def generate_per_file_line_by_line_coverage_in_html(binary_paths, profdata_file_path, filters, ignore_filename_regex): - """Generates per file line-by-line coverage in html using `llvm-cov show`. - - For a file with absolute path /a/b/x.cc, a html report is generated as: - OUTPUT_DIR/coverage/a/b/x.cc.html. An index html file is also generated as: - OUTPUT_DIR/index.html. - - Args: - binary_paths: A list of paths to the instrumented binaries. - profdata_file_path: A path to the profdata file. - filters: A list of directories and files to get coverage for. - """ - # llvm-cov show [options] -instr-profile PROFILE BIN [-object BIN,...] - # [[-object BIN]] [SOURCES] - # NOTE: For object files, the first one is specified as a positional argument, - # and the rest are specified as keyword argument. - logging.debug("Generating per file line by line coverage reports using " - "`llvm-cov show` command.") - subprocess_cmd = [ - "llvm-cov", "show", "-format=html", - "-output-dir={}".format(OUTPUT_DIR), - "-instr-profile={}".format(profdata_file_path), binary_paths[0], - ] - subprocess_cmd.extend( - ["-object=" + binary_path for binary_path in binary_paths[1:]]) - subprocess_cmd.extend(["-Xdemangler", "c++filt", "-Xdemangler", "-n"]) - subprocess_cmd.extend(filters) - if ignore_filename_regex: - subprocess_cmd.append("-ignore-filename-regex={}".format(ignore_filename_regex)) - subprocess.check_call(subprocess_cmd) - logging.debug("Finished running `llvm-cov show` command.") - - -def get_logs_directory_path(): - """Path to the logs directory.""" - return os.path.join(coverage_utils.get_coverage_report_root_dir_path(OUTPUT_DIR), LOGS_DIR_NAME) - - -def get_profdata_file_path(): - """Path to the resulting .profdata file.""" - return os.path.join(coverage_utils.get_coverage_report_root_dir_path(OUTPUT_DIR), PROFDATA_FILE_NAME) - - -def get_summary_file_path(): - """The JSON file that contains coverage summary written by llvm-cov export.""" - return os.path.join(coverage_utils.get_coverage_report_root_dir_path(OUTPUT_DIR), SUMMARY_FILE_NAME) - - -def create_coverage_profdata_for_targets(targets, commands): - """Runs target to generate the coverage profile data. - - Args: - targets: A list of targets. - commands: A list of commands used to run the targets. - - Returns: - A relative path to the generated profdata file. - """ - target_profdata_file_paths = get_target_profdata_paths_by_executing_commands(targets, commands) - coverage_profdata_file_path = merge_target_profdata_files(target_profdata_file_paths) - - for target_profdata_file_path in target_profdata_file_paths: - os.remove(target_profdata_file_path) - - return coverage_profdata_file_path - - -def get_target_profdata_paths_by_executing_commands(targets, commands): - """Runs commands and returns the relative paths to the profraw data files. - - Args: - targets: A list of targets built with coverage instrumentation. - commands: A list of commands used to run the targets. - - Returns: - A list of relative paths to the generated profraw data files. - """ - logging.debug("Executing the test commands.") - - # Remove existing profraw data files. - report_root_dir = coverage_utils.get_coverage_report_root_dir_path(OUTPUT_DIR) - for file_or_dir in os.listdir(report_root_dir): - if file_or_dir.endswith(PROFRAW_FILE_EXTENSION): - os.remove(os.path.join(report_root_dir, file_or_dir)) - - # Ensure that logs directory exists. - if not os.path.exists(get_logs_directory_path()): - os.makedirs(get_logs_directory_path()) - - profdata_file_paths = [] - - # Run all test targets to generate profraw data files. - for target, command in zip(targets, commands): - output_file_name = target + "_output.log" - output_file_path = os.path.join(get_logs_directory_path(), output_file_name) - - profdata_file_path = None - for _ in range(MERGE_RETRIES): - logging.info("Running command `{}`, the output is redirected to '{}'.".format(command, output_file_path)) - - # profraw files are generated inside the OUTPUT_DIR. - output = execute_command(target, command, output_file_path) - - profraw_file_paths = [] - for file_or_dir in os.listdir(report_root_dir): - if file_or_dir.endswith(PROFRAW_FILE_EXTENSION): - profraw_file_paths.append(os.path.join(report_root_dir, file_or_dir)) - - assert profraw_file_paths, ( - "Running target '{}' failed to generate any profraw data file, " - "please make sure the binary exists, is properly instrumented and " - "does not crash.".format(target)) - - assert isinstance(profraw_file_paths, list), ( - "Variable 'profraw_file_paths' is expected to be of type 'list', " - "but it is a {}.".format(type(profraw_file_paths))) - - try: - profdata_file_path = merge_target_profraw_files(target, profraw_file_paths) - break - except Exception: - logging.info("Retrying...") - finally: - # Remove profraw files now so that they are not used in next iteration. - for profraw_file_path in profraw_file_paths: - os.remove(profraw_file_path) - - assert profdata_file_path, ( - "Failed to merge target '{}' profraw files after {} retries.".format(target, MERGE_RETRIES)) - profdata_file_paths.append(profdata_file_path) - - logging.debug("Finished executing the test commands.") - - return profdata_file_paths - - -def get_environment_vars(profraw_file_path): - """Return environment vars for subprocess, given a profraw file path.""" - env = os.environ.copy() - env.update({ - "LLVM_PROFILE_FILE": profraw_file_path, - }) - return env - - -def execute_command(target, command, output_file_path): - """Runs a single command and generates a profraw data file.""" - # Per Clang "Source-based Code Coverage" doc: - # - # "%p" expands out to the process ID. It's not used by this scripts due to: - # 1) If a target program spawns too many processess, it may exhaust all disk - # space available. For example, unit_tests writes thousands of .profraw - # files each of size 1GB+. - # 2) If a target binary uses shared libraries, coverage profile data for them - # will be missing, resulting in incomplete coverage reports. - # - # "%Nm" expands out to the instrumented binary's signature. When this pattern - # is specified, the runtime creates a pool of N raw profiles which are used - # for on-line profile merging. The runtime takes care of selecting a raw - # profile from the pool, locking it, and updating it before the program exits. - # N must be between 1 and 9. The merge pool specifier can only occur once per - # filename pattern. - # - # "%1m" is used when tests run in single process, such as fuzz targets. - # - # For other cases, "%4m" is chosen as it creates some level of parallelism, - # but it's not too big to consume too much computing resource or disk space. - profile_pattern_string = "%1m" - if "mpi" in command: - profile_pattern_string = "%4m" - expected_profraw_file_name = os.extsep.join( - [target, profile_pattern_string, PROFRAW_FILE_EXTENSION]) - expected_profraw_file_path = os.path.join( - coverage_utils.get_coverage_report_root_dir_path(OUTPUT_DIR), - expected_profraw_file_name) - command = command.replace(LLVM_PROFILE_FILE_PATH_SUBSTITUTION, - expected_profraw_file_path) - - try: - # Some fuzz targets or tests may write into stderr, redirect it as well. - with open(output_file_path, "wb") as output_file_handle: - subprocess.check_call( - command, - shell=True, - stdout=output_file_handle, - stderr=subprocess.STDOUT, - env=get_environment_vars(expected_profraw_file_path)) - except subprocess.CalledProcessError as e: - logging.warning("Command `{}` exited with non-zero return code.".format(command)) - - return open(output_file_path, "rb").read() - - -def merge_target_profdata_files(profdata_file_paths): - """Returns a relative path to coverage profdata file by merging target - profdata files. - - Args: - profdata_file_paths: A list of relative paths to the profdata data files - that are to be merged. - - Returns: - A relative path to the merged coverage profdata file. - - Raises: - CalledProcessError: An error occurred merging profdata files. - """ - logging.debug("Merging target profraw files to create target profdata file.") - profdata_file_path = get_profdata_file_path() - try: - subprocess_cmd = [ - "llvm-profdata", "merge", "-o", profdata_file_path, "-sparse=true" - ] - subprocess_cmd.extend(profdata_file_paths) - - output = subprocess.check_output(subprocess_cmd) - logging.debug("Merge output: {}".format(output)) - except subprocess.CalledProcessError: - logging.error("Failed to merge target profdata files to create coverage profdata.") - raise - - logging.debug("Finished merging target profdata files.") - logging.info("Code coverage profile data is created as '{}'.".format(profdata_file_path)) - return profdata_file_path - - -def merge_target_profraw_files(target, profraw_file_paths): - """Returns a relative path to target profdata file by merging target - profraw files. - - Args: - profraw_file_paths: A list of relative paths to the profdata data files - that are to be merged. - - Returns: - A relative path to the merged coverage profdata file. - - Raises: - CalledProcessError: An error occurred merging profdata files. - """ - logging.debug("Merging target profraw files to create target profdata file.") - profdata_file_path = os.path.join(OUTPUT_DIR, "{}.profdata".format(target)) - - try: - subprocess_cmd = [ - "llvm-profdata", "merge", "-o", profdata_file_path, "-sparse=true" - ] - subprocess_cmd.extend(profraw_file_paths) - - output = subprocess.check_output(subprocess_cmd) - logging.debug("Merge output: {}".format(output)) - except subprocess.CalledProcessError as error: - logging.error("Failed to merge target profraw files to create target profdata.") - raise error - - logging.debug("Finished merging target profraw files.") - logging.info("Target '{}' profile data is created as '{}'.".format(target, profdata_file_path)) - return profdata_file_path - - -def generate_per_file_coverage_summary(binary_paths, profdata_file_path, filters, ignore_filename_regex): - """Generates per file coverage summary using "llvm-cov export" command.""" - # llvm-cov export [options] -instr-profile PROFILE BIN [-object BIN,...] - # [[-object BIN]] [SOURCES]. - # NOTE: For object files, the first one is specified as a positional argument, - # and the rest are specified as keyword argument. - logging.debug("Generating per-file code coverage summary using `llvm-cov export -summary-only` command.") - subprocess_cmd = [ - "llvm-cov", "export", "-summary-only", - "-instr-profile=" + profdata_file_path, binary_paths[0] - ] - subprocess_cmd.extend( - ["-object=" + binary_path for binary_path in binary_paths[1:]]) - subprocess_cmd.extend(filters) - if ignore_filename_regex: - subprocess_cmd.append("-ignore-filename-regex={}".format(ignore_filename_regex)) - - export_output = subprocess.check_output(subprocess_cmd) - - # Write output on the disk to be used by code coverage bot. - with open(get_summary_file_path(), "wb") as f: - f.write(export_output) - - return export_output - - -def verify_paths_and_return_absolutes(paths): - """Verifies that the paths specified in |paths| exist and returns absolute versions. - - Args: - paths: A list of files or directories. - """ - absolute_paths = [] - for path in paths: - absolute_path = os.path.join(SRC_ROOT_PATH, path) - assert os.path.exists(absolute_path), "Path '{}' doesn't exist.".format(path) - - absolute_paths.append(absolute_path) - - return absolute_paths - - -def parse_targets_arguments(targets_args, build_dir): - """Return binary paths from target names.""" - targets = [] - commands = [] - binary_paths = [] - for target in targets_args: - if "::" in target: - target, command = target.split("::") - target = target.strip() - else: - command = target - - binary_path = os.path.join(build_dir, "bin", target) - if not os.path.exists(binary_path): - logging.warning("Target binary '{}' not found in build directory, skipping.".format(os.path.basename(binary_path))) - continue - - targets.append(target) - command = command.replace(target, binary_path) - commands.append(command) - binary_paths.append(binary_path) - - return targets, commands, binary_paths - - -def setup_output_dir(): - """Setup output directory.""" - if os.path.exists(OUTPUT_DIR): - shutil.rmtree(OUTPUT_DIR) - # Creates OUTPUT_DIR and its platform sub-directory. - os.makedirs(coverage_utils.get_coverage_report_root_dir_path(OUTPUT_DIR)) - - -def parse_command_arguments(): - """Adds and parses relevant arguments for tool comands. - - Returns: - A dictionary representing the arguments. - """ - arg_parser = argparse.ArgumentParser() - arg_parser.usage = __doc__ - - arg_parser.add_argument("-b", "--build-dir", type=str, required=True, - help="The build directory, the path needs to be relative to the root of the checkout.") - - arg_parser.add_argument("-o", "--output-dir", type=str, required=True, - help="Output directory for generated artifacts.") - - arg_parser.add_argument("-f", "--filters", action="append", required=False, - help="Directories or files to get code coverage for, and all files under " - "the directories are included recursively.") - - arg_parser.add_argument("-i", "--ignore-filename-regex", type=str, - help="Skip source code files with file paths that match the given " - "regular expression. For example, use -i=\'.*/out/.*|.*/third_party/.*\' " - "to exclude files in third_party/ and out/ folders from the report.") - - arg_parser.add_argument("--no-file-view", action="store_true", - help="Don't generate the file view in the coverage report. When there " - "are large number of html files, the file view becomes heavy and may " - "cause the browser to freeze, and this argument comes handy.") - - arg_parser.add_argument("-v", "--verbose", action="store_true", - help="Prints additional output for diagnostics.") - - arg_parser.add_argument("-l", "--log_file", type=str, - help="Redirects logs to a file.") - - arg_parser.add_argument("targets", nargs="+", - help="The names of the test targets to run.") - - args = arg_parser.parse_args() - return args - - -if __name__ == "__main__": - """Execute tool commands.""" - - # Change directory to source root to aid in relative paths calculations. - SRC_ROOT_PATH = coverage_utils.get_full_path( - os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir)) - os.chdir(SRC_ROOT_PATH) - - args = parse_command_arguments() - coverage_utils.configure_logging(verbose=args.verbose, log_file=args.log_file) - - BUILD_DIR = coverage_utils.get_full_path(args.build_dir) - OUTPUT_DIR = coverage_utils.get_full_path(args.output_dir) - - assert os.path.exists(BUILD_DIR), ( - "Build directory '{}' doesn't exist. Please rebuild TNL.".format(BUILD_DIR)) - - absolute_filter_paths = [] - if args.filters: - absolute_filter_paths = verify_paths_and_return_absolutes(args.filters) - - setup_output_dir() - - targets, commands, binary_paths = parse_targets_arguments(args.targets, args.build_dir) - profdata_file_path = create_coverage_profdata_for_targets(targets, commands) - - logging.info("Generating code coverage report in html...") - per_file_summary_data = generate_per_file_coverage_summary( - binary_paths, profdata_file_path, absolute_filter_paths, - args.ignore_filename_regex) - generate_per_file_line_by_line_coverage_in_html(binary_paths, profdata_file_path, - absolute_filter_paths, - args.ignore_filename_regex) - # Call prepare here. - processor = coverage_utils.CoverageReportPostProcessor( - OUTPUT_DIR, - SRC_ROOT_PATH + "/src/TNL", - per_file_summary_data, - no_file_view=args.no_file_view) - - processor.prepare_html_report() diff --git a/scripts/code_coverage/coverage_utils.py b/scripts/code_coverage/coverage_utils.py deleted file mode 100644 index 85cdbf563..000000000 --- a/scripts/code_coverage/coverage_utils.py +++ /dev/null @@ -1,534 +0,0 @@ -#! /usr/bin/env python3 -# vim: tabstop=4 softtabstop=4 - -import argparse -from collections import defaultdict -import functools -import jinja2 -import json -import logging -import os -import shutil -import sys - -# The default name of the html coverage report for a directory. -DIRECTORY_COVERAGE_HTML_REPORT_NAME = "report.html" - -# Name of the html index files for different views. -DIRECTORY_VIEW_INDEX_FILE = "directory_view_index.html" -FILE_VIEW_INDEX_FILE = "file_view_index.html" -INDEX_HTML_FILE = "index.html" - - -def configure_logging(verbose=False, log_file=None): - """Configures logging settings for later use.""" - log_level = logging.DEBUG if verbose else logging.INFO - log_format = "[%(levelname)s] %(message)s" - logging.basicConfig(filename=log_file, level=log_level, format=log_format) - - -def get_coverage_report_root_dir_path(output_dir): - """The root directory that contains all generated coverage html reports.""" - return os.path.join(output_dir, get_host_platform()) - - -def get_directory_view_path(output_dir): - """Path to the HTML file for the directory view.""" - return os.path.join(get_coverage_report_root_dir_path(output_dir), DIRECTORY_VIEW_INDEX_FILE) - - -def get_file_view_path(output_dir): - """Path to the HTML file for the file view.""" - return os.path.join(get_coverage_report_root_dir_path(output_dir), FILE_VIEW_INDEX_FILE) - - -def get_html_index_path(output_dir): - """Path to the main HTML index file.""" - return os.path.join(get_coverage_report_root_dir_path(output_dir), INDEX_HTML_FILE) - - -def get_full_path(path): - """Return full absolute path.""" - return os.path.abspath(os.path.expandvars(os.path.expanduser(path))) - - -def get_host_platform(): - """Returns the host platform. - - This is separate from the target platform/os that coverage is running for. - """ - if sys.platform == "win32" or sys.platform == "cygwin": - return "win" - if sys.platform.startswith("linux"): - return "linux" - else: - assert sys.platform == "darwin" - return "mac" - - -def get_relative_path_to_directory_of_file(target_path, base_path): - """Returns a target path relative to the directory of base_path. - - This method requires base_path to be a file, otherwise, one should call - os.path.relpath directly. - """ - assert os.path.dirname(base_path) != base_path, "Base path '{}' is a directory, please call os.path.relpath directly.".format(base_path) - base_dir = os.path.dirname(base_path) - return os.path.relpath(target_path, base_dir) - - -def merge_two_directories(src_dir_path, dst_dir_path): - """Merge src_dir_path directory into dst_path directory.""" - for filename in os.listdir(src_dir_path): - dst_path = os.path.join(dst_dir_path, filename) - if os.path.exists(dst_path): - shutil.rmtree(dst_path) - os.rename(os.path.join(src_dir_path, filename), dst_path) - shutil.rmtree(src_dir_path) - - -def WriteRedirectHtmlFile(from_html_path, to_html_path): - """Writes a html file that redirects to another html file.""" - to_html_relative_path = get_relative_path_to_directory_of_file(to_html_path, from_html_path) - content = """\ - - - - - - -""".format(to_html_relative_path) - - with open(from_html_path, "w") as f: - f.write(content) - - -class CoverageSummary: - """Encapsulates coverage summary representation.""" - - def __init__(self, - regions_total=0, - regions_covered=0, - functions_total=0, - functions_covered=0, - lines_total=0, - lines_covered=0): - """Initializes CoverageSummary object.""" - self._summary = { - "regions": { - "total": regions_total, - "covered": regions_covered - }, - "functions": { - "total": functions_total, - "covered": functions_covered - }, - "lines": { - "total": lines_total, - "covered": lines_covered - } - } - - def get(self): - """Returns summary as a dictionary.""" - return self._summary - - def add_summary(self, other_summary): - """Adds another summary to this one element-wise.""" - for feature in self._summary: - self._summary[feature]["total"] += other_summary.get()[feature]["total"] - self._summary[feature]["covered"] += other_summary.get()[feature]["covered"] - - -class CoverageReportHtmlGenerator: - """Encapsulates coverage html report generation. - - The generated html has a table that contains links to other coverage reports. - """ - - def __init__(self, output_dir, output_path, table_entry_type): - """ - Args: - output_dir: Path to the dir for writing coverage report to. - output_path: Path to the html report that will be generated. - table_entry_type: Type of the table entries to be displayed in the table - header. For example: "Path". - """ - css_file_name = "style.css" - css_absolute_path = os.path.join(output_dir, css_file_name) - assert os.path.exists(css_absolute_path), ( - "css file doesn\'t exit. Please make sure `llvm-cov show -format=html` " - "is called first, and the css file is generated at '{}'.".format( - css_absolute_path)) - - self._css_absolute_path = css_absolute_path - self._output_dir = output_dir - self._output_path = output_path - self._table_entry_type = table_entry_type - - self._table_entries = [] - self._total_entry = {} - - source_dir = os.path.dirname(os.path.realpath(__file__)) - template_dir = os.path.join(source_dir, "html_templates") - - jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir), - trim_blocks=True) - self._header_template = jinja_env.get_template("header.html") - self._table_template = jinja_env.get_template("table.html") - self._footer_template = jinja_env.get_template("footer.html") - - css_path = os.path.join(source_dir, "static", "css", "style.css") - self._style_overrides = open(css_path).read() - - def add_link_to_another_report(self, html_report_path, name, summary): - """Adds a link to another html report in this report. - - The link to be added is assumed to be an entry in this directory. - """ - # Use relative paths instead of absolute paths to make the generated reports - # portable. - html_report_relative_path = get_relative_path_to_directory_of_file( - html_report_path, self._output_path) - - table_entry = self._create_table_entry_from_coverage_summary( - summary, html_report_relative_path, name, - os.path.basename(html_report_path) == - DIRECTORY_COVERAGE_HTML_REPORT_NAME) - self._table_entries.append(table_entry) - - def create_totals_entry(self, summary): - """Creates an entry corresponds to the "Totals" row in the html report.""" - self._total_entry = self._create_table_entry_from_coverage_summary(summary) - - def _create_table_entry_from_coverage_summary(self, summary, href=None, name=None, is_dir=None): - """Creates an entry to display in the html report.""" - assert (href is None and name is None and is_dir is None) or ( - href is not None and name is not None and is_dir is not None), ( - "The only scenario when href or name or is_dir can be None is when " - "creating an entry for the Totals row, and in that case, all three " - "attributes must be None.") - - entry = {} - if href is not None: - entry["href"] = href - if name is not None: - entry["name"] = name - if is_dir is not None: - entry["is_dir"] = is_dir - - summary_dict = summary.get() - for feature in summary_dict: - if summary_dict[feature]["total"] == 0: - percentage = 0.0 - else: - percentage = float(summary_dict[feature]["covered"]) / summary_dict[feature]["total"] * 100 - - color_class = self._get_color_class(percentage) - entry[feature] = { - "total": summary_dict[feature]["total"], - "covered": summary_dict[feature]["covered"], - "percentage": "{:6.2f}".format(percentage), - "color_class": color_class - } - - return entry - - def _get_color_class(self, percentage): - """Returns the css color class based on coverage percentage.""" - if percentage >= 0 and percentage < 80: - return "red" - if percentage >= 80 and percentage < 100: - return "yellow" - if percentage == 100: - return "green" - raise ValueError("Invalid coverage percentage: {}".format(percentage)) - - def write_html_coverage_report(self, no_file_view): - """Writes html coverage report. - - In the report, sub-directories are displayed before files and within each - category, entries are sorted alphabetically. - """ - - def entry_cmp(left, right): - """Compare function for table entries.""" - if left["is_dir"] != right["is_dir"]: - return -1 if left["is_dir"] == True else 1 - return -1 if left["name"] < right["name"] else 1 - - self._table_entries = sorted(self._table_entries, key=functools.cmp_to_key(entry_cmp)) - - css_path = os.path.join(self._output_dir, "style.css") - - directory_view_path = get_directory_view_path(self._output_dir) - directory_view_href = get_relative_path_to_directory_of_file(directory_view_path, self._output_path) - - # File view is optional in the report. - file_view_href = None - if not no_file_view: - file_view_path = get_file_view_path(self._output_dir) - file_view_href = get_relative_path_to_directory_of_file(file_view_path, self._output_path) - - html_header = self._header_template.render( - css_path=get_relative_path_to_directory_of_file(css_path, self._output_path), - directory_view_href=directory_view_href, - file_view_href=file_view_href, - style_overrides=self._style_overrides) - - html_table = self._table_template.render( - entries=self._table_entries, - total_entry=self._total_entry, - table_entry_type=self._table_entry_type) - - html_footer = self._footer_template.render() - - with open(self._output_path, "w") as html_file: - html_file.write(html_header + html_table + html_footer) - - -class CoverageReportPostProcessor: - """Post processing of code coverage reports produced by llvm-cov.""" - - def __init__(self, output_dir, src_root_dir, summary_data, no_file_view, path_equivalence=None): - # Caller provided parameters. - self.output_dir = output_dir - self.src_root_dir = os.path.normpath(get_full_path(src_root_dir)) - if not self.src_root_dir.endswith(os.sep): - self.src_root_dir += os.sep - self.summary_data = json.loads(summary_data) - assert len(self.summary_data["data"]) == 1 - self.no_file_view = no_file_view - - # The root directory that contains all generated coverage html reports. - self.report_root_dir = get_coverage_report_root_dir_path(self.output_dir) - - # Path to the HTML file for the directory view. - self.directory_view_path = get_directory_view_path(self.output_dir) - - # Path to the HTML file for the file view. - self.file_view_path = get_file_view_path(self.output_dir) - - # Path to the main HTML index file. - self.html_index_path = get_html_index_path(self.output_dir) - - self.path_map = None - if path_equivalence: - def _prepare_path(path): - path = os.path.normpath(path) - if not path.endswith(os.sep): - # A normalized path does not end with '/', unless it is a root dir. - path += os.sep - return path - - self.path_map = [_prepare_path(p) for p in path_equivalence.split(",")] - assert len(self.path_map) == 2, "Path equivalence argument is incorrect." - - def _map_to_local(self, path): - """Maps a path from the coverage data to a local path.""" - if not self.path_map: - return path - return path.replace(self.path_map[0], self.path_map[1], 1) - - def calculate_per_directory_coverage_summary(self, per_file_coverage_summary): - """Calculates per directory coverage summary.""" - logging.debug("Calculating per-directory coverage summary.") - per_directory_coverage_summary = defaultdict(lambda: CoverageSummary()) - - for file_path in per_file_coverage_summary: - summary = per_file_coverage_summary[file_path] - parent_dir = os.path.dirname(file_path) - - while True: - per_directory_coverage_summary[parent_dir].add_summary(summary) - if os.path.normpath(parent_dir) == os.path.normpath(self.src_root_dir): - break - parent_dir = os.path.dirname(parent_dir) - - logging.debug("Finished calculating per-directory coverage summary.") - return per_directory_coverage_summary - - def get_coverage_html_report_path_for_directory(self, dir_path): - """Given a directory path, returns the corresponding html report path.""" - assert os.path.isdir(self._map_to_local(dir_path)), "'{}' is not a directory.".format(dir_path) - html_report_path = os.path.join(get_full_path(dir_path), DIRECTORY_COVERAGE_HTML_REPORT_NAME) - - # '+' is used instead of os.path.join because both of them are absolute - # paths and os.path.join ignores the first path. - return self.report_root_dir + html_report_path - - def get_coverage_html_report_path_for_file(self, file_path): - """Given a file path, returns the corresponding html report path.""" - assert os.path.isfile(self._map_to_local(file_path)), "'{}' is not a file.".format(file_path) - html_report_path = os.extsep.join([get_full_path(file_path), "html"]) - - # '+' is used instead of os.path.join because both of them are absolute - # paths and os.path.join ignores the first path. - return self.report_root_dir + html_report_path - - def generate_file_view_html_index_file(self, per_file_coverage_summary, file_view_index_file_path): - """Generates html index file for file view.""" - logging.debug("Generating file view html index file as '{}'.".format(file_view_index_file_path)) - html_generator = CoverageReportHtmlGenerator(self.output_dir, file_view_index_file_path, "Path") - totals_coverage_summary = CoverageSummary() - - for file_path in per_file_coverage_summary: - totals_coverage_summary.add_summary(per_file_coverage_summary[file_path]) - html_generator.add_link_to_another_report( - self.get_coverage_html_report_path_for_file(file_path), - os.path.relpath(file_path, self.src_root_dir), - per_file_coverage_summary[file_path]) - - html_generator.create_totals_entry(totals_coverage_summary) - html_generator.write_html_coverage_report(self.no_file_view) - logging.debug("Finished generating file view html index file.") - - def generate_per_file_coverage_summary(self): - """Generate per file coverage summary using coverage data in JSON format.""" - files_coverage_data = self.summary_data["data"][0]["files"] - - per_file_coverage_summary = {} - for file_coverage_data in files_coverage_data: - file_path = file_coverage_data["filename"] - # skip files which are outside the source root (e.g. unit tests themselves) - if not file_path.startswith(self.src_root_dir): - continue - - summary = file_coverage_data["summary"] - if summary["lines"]["count"] == 0: - continue - - per_file_coverage_summary[file_path] = CoverageSummary( - regions_total=summary["regions"]["count"], - regions_covered=summary["regions"]["covered"], - functions_total=summary["functions"]["count"], - functions_covered=summary["functions"]["covered"], - lines_total=summary["lines"]["count"], - lines_covered=summary["lines"]["covered"]) - - logging.debug("Finished generating per-file code coverage summary.") - return per_file_coverage_summary - - def generate_per_directory_coverage_in_html(self, per_directory_coverage_summary, per_file_coverage_summary): - """Generates per directory coverage breakdown in html.""" - logging.debug("Writing per-directory coverage html reports.") - for dir_path in per_directory_coverage_summary: - self.generate_coverage_in_html_for_directory(dir_path, per_directory_coverage_summary, per_file_coverage_summary) - logging.debug("Finished writing per-directory coverage html reports.") - - def generate_coverage_in_html_for_directory(self, dir_path, per_directory_coverage_summary, per_file_coverage_summary): - """Generates coverage html report for a single directory.""" - html_generator = CoverageReportHtmlGenerator( - self.output_dir, self.get_coverage_html_report_path_for_directory(dir_path), - "Path") - - for entry_name in os.listdir(self._map_to_local(dir_path)): - entry_path = os.path.normpath(os.path.join(dir_path, entry_name)) - - if entry_path in per_file_coverage_summary: - entry_html_report_path = self.get_coverage_html_report_path_for_file(entry_path) - entry_coverage_summary = per_file_coverage_summary[entry_path] - elif entry_path in per_directory_coverage_summary: - entry_html_report_path = self.get_coverage_html_report_path_for_directory(entry_path) - entry_coverage_summary = per_directory_coverage_summary[entry_path] - else: - # Any file without executable lines shouldn't be included into the - # report. For example, OWNER and README.md files. - continue - - html_generator.add_link_to_another_report(entry_html_report_path, - os.path.basename(entry_path), - entry_coverage_summary) - - html_generator.create_totals_entry(per_directory_coverage_summary[dir_path]) - html_generator.write_html_coverage_report(self.no_file_view) - - def generate_directory_view_html_index_file(self): - """Generates the html index file for directory view. - - Note that the index file is already generated under src_root_dir, so this - file simply redirects to it, and the reason of this extra layer is for - structural consistency with other views. - """ - directory_view_index_file_path = self.directory_view_path - logging.debug("Generating directory view html index file as '{}'.".format( - directory_view_index_file_path)) - src_root_html_report_path = self.get_coverage_html_report_path_for_directory(self.src_root_dir) - WriteRedirectHtmlFile(directory_view_index_file_path, src_root_html_report_path) - logging.debug("Finished generating directory view html index file.") - - def rename_default_coverage_directory(self): - """Rename the default coverage directory into platform specific name.""" - # llvm-cov creates "coverage" subdir in the output dir. We would like to use - # the platform name instead, as it simplifies the report dir structure when - # the same report is generated for different platforms. - default_report_subdir_path = os.path.join(self.output_dir, "coverage") - if not os.path.exists(default_report_subdir_path): - logging.error("Default coverage report dir does not exist: {}.".format(default_report_subdir_path)) - - if not os.path.exists(self.report_root_dir): - os.mkdir(self.report_root_dir) - - merge_two_directories(default_report_subdir_path, self.report_root_dir) - - def overwrite_html_reports_index_file(self): - """Overwrites the root index file to redirect to the default view.""" - html_index_file_path = self.html_index_path - directory_view_index_file_path = self.directory_view_path - WriteRedirectHtmlFile(html_index_file_path, directory_view_index_file_path) - - def clean_up_output_dir(self): - """Perform a cleanup of the output dir.""" - # Remove the default index.html file produced by llvm-cov. - index_path = os.path.join(self.output_dir, INDEX_HTML_FILE) - if os.path.exists(index_path): - os.remove(index_path) - - def prepare_html_report(self): - self.rename_default_coverage_directory() - - per_file_coverage_summary = self.generate_per_file_coverage_summary() - - if not self.no_file_view: - self.generate_file_view_html_index_file(per_file_coverage_summary, self.file_view_path) - - per_directory_coverage_summary = self.calculate_per_directory_coverage_summary(per_file_coverage_summary) - - self.generate_per_directory_coverage_in_html(per_directory_coverage_summary, per_file_coverage_summary) - self.generate_directory_view_html_index_file() - - # The default index file is generated only for the list of source files, - # needs to overwrite it to display per directory coverage view by default. - self.overwrite_html_reports_index_file() - self.clean_up_output_dir() - - html_index_file_path = "file://" + get_full_path(self.html_index_path) - logging.info("Index file for html report is generated as '{}'.".format(html_index_file_path)) - - -if __name__ == "__main__": - parser = argparse.ArgumentParser("coverage_utils", description="Code coverage utils.") - parser.add_argument("-v", "--verbose", action="store_true", - help="Prints additional debug output.") - parser.add_argument("--output-dir", - help="Path to the report dir.", required=True) - parser.add_argument("--src-root-dir", - help="Path to the src root dir.", required=True) - parser.add_argument("--summary-file", - help="Path to the summary file.", required=True) - parser.add_argument("--path-equivalence", - help="Map the paths in the coverage data to local source files path (=,)") - - args = parser.parse_args() - configure_logging(args.verbose) - - with open(args.summary_file) as f: - summary_data = f.read() - - processor = CoverageReportPostProcessor( - args.output_dir, - args.src_root_dir, - summary_data, - no_file_view=False, - path_equivalence=args.path_equivalence) - processor.prepare_html_report() diff --git a/scripts/code_coverage/html_templates/footer.html b/scripts/code_coverage/html_templates/footer.html deleted file mode 100644 index afb7967fa..000000000 --- a/scripts/code_coverage/html_templates/footer.html +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/scripts/code_coverage/html_templates/header.html b/scripts/code_coverage/html_templates/header.html deleted file mode 100644 index 7a425995b..000000000 --- a/scripts/code_coverage/html_templates/header.html +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - -

Coverage Report

-

- View results by: - {% if component_view_href %} - Components | - {% endif %} - Directories - {% if file_view_href %} - | Files - {% endif %} -

-
\ No newline at end of file diff --git a/scripts/code_coverage/html_templates/table.html b/scripts/code_coverage/html_templates/table.html deleted file mode 100644 index e6e38e24c..000000000 --- a/scripts/code_coverage/html_templates/table.html +++ /dev/null @@ -1,157 +0,0 @@ -{% if table_entry_type == "Component" %} -

- Filter: (e.g. "crypto,VR") -

-{% endif %} - - - - - - - - - - - {% for entry in entries %} - - - {% for feature in ("lines", "functions", "regions") %} - - {% endfor %} - - {% endfor %} - - {% if total_entry %} - - - - {% for feature in ("lines", "functions", "regions") %} - - {% endfor %} - - - {% endif %} -
{{ table_entry_type }} - Line Coverage - - Function Coverage - - Region Coverage -
- {% if entry["is_dir"] == True %} -
{{ entry["name"] }}/
- {% else %} -
{{ entry["name"] }}
- {% endif %} -
-
{{ entry[feature]["percentage"] }}% ({{ entry[feature]["covered"] }}/{{ entry[feature]["total"] }})
-
-
Totals
-
-
{{ total_entry[feature]["percentage"] }}% ({{ total_entry[feature]["covered"] }}/{{ total_entry[feature]["total"] }})
-
- - diff --git a/scripts/code_coverage/static/css/style.css b/scripts/code_coverage/static/css/style.css deleted file mode 100644 index e59c22ae0..000000000 --- a/scripts/code_coverage/static/css/style.css +++ /dev/null @@ -1,28 +0,0 @@ -/* Copyright 2018 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. */ - -th, td { - padding: 5px 16px; -} - -tbody td, tfoot td { - font-size: 14px; -} - -thead th { - font-size: 16px; -} - -thead th, tfoot td { - background-color: #f5f5f5; - border-left: 1px solid #e4e4e4; - border-right: 1px solid #e4e4e4; - color: #484848; - text-transform: uppercase; -} - -tbody tr:hover td, tfoot tr:hover td { - background-color: #f5f5f5; - border-color: #e4e4e4 !important; -} \ No newline at end of file diff --git a/scripts/make_coverage_report b/scripts/make_coverage_report deleted file mode 100755 index 645158a30..000000000 --- a/scripts/make_coverage_report +++ /dev/null @@ -1,83 +0,0 @@ -#!/bin/bash - -set -e - -# compile the tests -[[ ! -d Debug ]] && mkdir Debug -pushd Debug -../build --root-dir=.. --build=Debug \ - --with-examples=no --with-benchmarks=no --with-tools=no --with-python=no --with-doc=no \ - --with-tests=yes --run-tests=no \ - --with-clang=yes --with-cuda=yes --with-coverage=yes -popd - -tests=( - AllocatorsTest-dbg - AssertTest-dbg - AssertCudaTest-dbg - FileNameTest-dbg - FileTest-dbg - ObjectTest-dbg -# ParallelForTest-dbg # FIXME: too slow - StringTest-dbg - TimerTest-dbg - TypeInfoTest-dbg - - # Containers - ArrayOperationsTest-dbg - ArrayTest-dbg - ArrayTestCuda-dbg - ArrayViewTest-dbg - VectorTest-dbg - VectorPrefixSumTest-dbg - VectorEvaluateAndReduceTest-dbg - VectorBinaryOperationsTest-dbg - VectorUnaryOperationsTest-dbg - VectorVerticalOperationsTest-dbg - StaticArrayTest-dbg - StaticVectorTest-dbg - StaticVectorOperationsTest-dbg - NDArrayTest-dbg - NDSubarrayTest-dbg - SlicedNDArrayTest-dbg - StaticNDArrayTest-dbg - StaticNDArrayCudaTest-dbg - MultireductionTest-dbg - ListTest-dbg - MultimapTest-dbg - StaticMultimapTest-dbg - "DistributedArrayTest-dbg :: mpirun -np 4 DistributedArrayTest-dbg" - "DistributedVectorTest-dbg :: mpirun -np 4 DistributedVectorTest-dbg" - "DistributedVectorBinaryOperationsTest-dbg :: mpirun -np 4 DistributedVectorBinaryOperationsTest-dbg" - "DistributedVectorUnaryOperationsTest-dbg :: mpirun -np 4 DistributedVectorUnaryOperationsTest-dbg" - "DistributedVectorVerticalOperationsTest-dbg :: mpirun -np 4 DistributedVectorVerticalOperationsTest-dbg" - "DistributedNDArray_1D_test-dbg :: mpirun -np 4 DistributedNDArray_1D_test-dbg" - "DistributedNDArray_semi1D_test-dbg :: mpirun -np 4 DistributedNDArray_semi1D_test-dbg" - "DistributedNDArrayOverlaps_1D_test-dbg :: mpirun -np 4 DistributedNDArrayOverlaps_1D_test-dbg" - "DistributedNDArrayOverlaps_semi1D_test-dbg :: mpirun -np 4 DistributedNDArrayOverlaps_semi1D_test-dbg" - - # Functions - BoundaryMeshFunctionTest-dbg - MeshFunctionTest-dbg - - # Matrices - DenseMatrixTest-dbg - SparseMatrixCopyTest-dbg - SparseMatrixTest_AdEllpack-dbg - SparseMatrixTest_BiEllpack-dbg - SparseMatrixTest_ChunkedEllpack-dbg - SparseMatrixTest_CSR-dbg - SparseMatrixTest_Ellpack-dbg - SparseMatrixTest_SlicedEllpack-dbg - "DistributedMatrixTest-dbg :: mpirun -np 4 DistributedMatrixTest-dbg" - - # Meshes - BoundaryTagsTest-dbg -# MeshEntityTest-dbg -# MeshOrderingTest-dbg -# MeshReaderTest-dbg -# MeshTest-dbg -) - -# run the programs and create coverage reports -./scripts/code_coverage/coverage.py -b builddir/Debug -o builddir/coverage_report/ --ignore-filename-regex="^\/tmp\/tmpxft_.*" "${tests[@]}" -- GitLab From 67e36fb9c2985617adcea41edcabefe01d64378e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Klinkovsk=C3=BD?= Date: Sat, 20 Nov 2021 10:06:26 +0100 Subject: [PATCH 3/8] CI: configured code coverage via CI using gcovr --- .gitlab-ci.yml | 37 ++++++++++++++++++++++++++++++++----- 1 file changed, 32 insertions(+), 5 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 1c1921b69..d80381157 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -23,7 +23,7 @@ stages: # build targets BUILD_TESTS: "no" BUILD_MATRIX_TESTS: "no" - WITH_COVERAGE: "no" + WITH_COVERAGE: "yes" BUILD_DOC: "no" BUILD_BENCHMARKS: "no" BUILD_EXAMPLES: "no" @@ -100,6 +100,25 @@ stages: - .gitlab-ci.yml interruptible: true +# template for collecting code coverage +.coverage_template: + after_script: + - mkdir coverage_html + - if [[ ${CXX} == "clang++" ]]; then + GCOV_COMMAND="llvm-cov gcov"; + else + GCOV_COMMAND="gcov"; + fi + - gcovr --print-summary --html-details coverage_html/coverage.html --xml coverage.xml --xml-pretty --gcov-executable "${GCOV_COMMAND}" --exclude-unreachable-branches --root "${CI_PROJECT_DIR}" --filter "${CI_PROJECT_DIR}/src/TNL/" + coverage: /^\s*lines:\s*\d+.\d+\%/ + artifacts: + name: ${CI_JOB_NAME}-${CI_COMMIT_REF_NAME}-${CI_COMMIT_SHA} + expire_in: 7 days + reports: + cobertura: coverage.xml + paths: + - coverage_html/ + # Dummy build job to ensure that a pipeline is created for a merge request, even # when there were no changes. dummy build job: @@ -123,7 +142,9 @@ dummy build job: # significantly more time than debug builds). cuda_tests_Debug: - extends: .build_template + extends: + - .build_template + - .coverage_template stage: build:cuda tags: - docker @@ -148,7 +169,9 @@ cuda_tests_Release: cuda_matrix_tests_Debug: - extends: .build_template + extends: + - .build_template + - .coverage_template stage: build:cuda tags: - docker @@ -232,7 +255,9 @@ cuda_mpi_nontests_Release: default_tests_Debug: - extends: .build_template + extends: + - .build_template + - .coverage_template variables: <<: *default_cmake_flags BUILD_TYPE: Debug @@ -246,7 +271,9 @@ default_tests_Release: BUILD_TESTS: "yes" default_matrix_tests_Debug: - extends: .build_template + extends: + - .build_template + - .coverage_template variables: <<: *default_cmake_flags BUILD_TYPE: Debug -- GitLab From b2a72eb74950a6340476f64c5447b062bf758f74 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Klinkovsk=C3=BD?= Date: Sat, 20 Nov 2021 13:33:15 +0100 Subject: [PATCH 4/8] CI: upload XML report of test results to Gitlab --- .gitlab-ci.yml | 25 +++++++++++++++++++++---- CMakeLists.txt | 3 +++ 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index d80381157..5cafa245f 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -116,9 +116,18 @@ stages: expire_in: 7 days reports: cobertura: coverage.xml + junit: "builddir/$CI_JOB_NAME/tests-report.xml" paths: - coverage_html/ +# template for registering tests-report.xml as an artifact +.tests_report_template: + artifacts: + name: ${CI_JOB_NAME}-${CI_COMMIT_REF_NAME}-${CI_COMMIT_SHA} + expire_in: 7 days + reports: + junit: "builddir/$CI_JOB_NAME/tests-report.xml" + # Dummy build job to ensure that a pipeline is created for a merge request, even # when there were no changes. dummy build job: @@ -156,7 +165,9 @@ cuda_tests_Debug: BUILD_TESTS: "yes" cuda_tests_Release: - extends: .build_template + extends: + - .build_template + - .tests_report_template stage: build:cuda tags: - docker @@ -183,7 +194,9 @@ cuda_matrix_tests_Debug: BUILD_MATRIX_TESTS: "yes" cuda_matrix_tests_Release: - extends: .build_template + extends: + - .build_template + - .tests_report_template stage: build:cuda tags: - docker @@ -264,7 +277,9 @@ default_tests_Debug: BUILD_TESTS: "yes" default_tests_Release: - extends: .build_template + extends: + - .build_template + - .tests_report_template variables: <<: *default_cmake_flags BUILD_TYPE: Release @@ -280,7 +295,9 @@ default_matrix_tests_Debug: BUILD_MATRIX_TESTS: "yes" default_matrix_tests_Release: - extends: .build_template + extends: + - .build_template + - .tests_report_template variables: <<: *default_cmake_flags BUILD_TYPE: Release diff --git a/CMakeLists.txt b/CMakeLists.txt index b9a935815..d145cd1cd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -160,6 +160,9 @@ link_libraries( stdc++fs ) if( ${BUILD_TESTS} OR ${BUILD_MATRIX_TESTS} ) enable_testing() + # let CTest write test results in the JUnit XML format + set( CMAKE_CTEST_ARGUMENTS ${CMAKE_CTEST_ARGUMENTS} --output-junit "${CMAKE_BINARY_DIR}/tests-report.xml" ) + if( ${WITH_SYSTEM_GTEST} OR ${OFFLINE_BUILD} ) # find gtest installed in the local system find_package(GTest REQUIRED) -- GitLab From 249651c7c1d4c7b40acd5cac7a995992c4e1ddb2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Klinkovsk=C3=BD?= Date: Sat, 20 Nov 2021 21:38:35 +0100 Subject: [PATCH 5/8] Reduced size of some overly large unit tests to have faster runs with instrumented code --- src/UnitTests/Algorithms/ParallelForTest.h | 12 +++++------ src/UnitTests/Algorithms/reduceTest.h | 23 ++++++++++++---------- src/UnitTests/Matrices/DenseMatrixTest.h | 4 ++-- 3 files changed, 21 insertions(+), 18 deletions(-) diff --git a/src/UnitTests/Algorithms/ParallelForTest.h b/src/UnitTests/Algorithms/ParallelForTest.h index fe07247d2..5c833afc0 100644 --- a/src/UnitTests/Algorithms/ParallelForTest.h +++ b/src/UnitTests/Algorithms/ParallelForTest.h @@ -26,7 +26,7 @@ TEST( ParallelForTest, 1D_host ) { using Array = Containers::Array< int, Devices::Host >; Array a; - for (int size = 100; size <= 100000000; size *= 100) + for (int size = 1; size <= 100000; size *= 10) { Array expected; expected.setSize( size ); @@ -53,7 +53,7 @@ TEST( ParallelForTest, 2D_host ) { using Array = Containers::Array< int, Devices::Host >; Array a; - for (int size = 100; size <= 100000000; size *= 100) + for (int size = 1; size <= 100000; size *= 10) { Array expected; expected.setSize( size ); @@ -92,7 +92,7 @@ TEST( ParallelForTest, 3D_host ) { using Array = Containers::Array< int, Devices::Host >; Array a; - for (int size = 100; size <= 100000000; size *= 100) + for (int size = 1; size <= 100000; size *= 10) { Array expected; expected.setSize( size ); @@ -146,7 +146,7 @@ void test_1D_cuda() using Array = Containers::Array< int, Devices::Cuda >; using ArrayHost = Containers::Array< int, Devices::Host >; Array a; - for (int size = 100; size <= 100000000; size *= 100) + for (int size = 1; size <= 100000000; size *= 100) { ArrayHost expected; expected.setSize( size ); @@ -182,7 +182,7 @@ void test_2D_cuda() using Array = Containers::Array< int, Devices::Cuda >; using ArrayHost = Containers::Array< int, Devices::Host >; Array a; - for (int size = 100; size <= 100000000; size *= 100) + for (int size = 1; size <= 100000000; size *= 100) { ArrayHost expected; expected.setSize( size ); @@ -231,7 +231,7 @@ void test_3D_cuda() using Array = Containers::Array< int, Devices::Cuda >; using ArrayHost = Containers::Array< int, Devices::Host >; Array a; - for (int size = 100; size <= 100000000; size *= 100) + for (int size = 1; size <= 100000000; size *= 100) { ArrayHost expected; expected.setSize( size ); diff --git a/src/UnitTests/Algorithms/reduceTest.h b/src/UnitTests/Algorithms/reduceTest.h index c39215f47..75918e4e7 100644 --- a/src/UnitTests/Algorithms/reduceTest.h +++ b/src/UnitTests/Algorithms/reduceTest.h @@ -92,7 +92,7 @@ TYPED_TEST( ReduceTest, sum ) { using ArrayType = typename TestFixture::ArrayType; ArrayType a; - for( int size = 100; size <= 1000000; size *= 10 ) + for( int size = 1; size <= 100000; size *= 10 ) { a.setSize( size ); a.setValue( 1 ); @@ -131,7 +131,7 @@ TYPED_TEST( ReduceTest, min ) { using ArrayType = typename TestFixture::ArrayType; ArrayType a; - for( int size = 100; size <= 1000000; size *= 10 ) + for( int size = 1; size <= 100000; size *= 10 ) { a.setSize( size ); iota( a, 1 ); @@ -145,7 +145,7 @@ TYPED_TEST( ReduceTest, max ) { using ArrayType = typename TestFixture::ArrayType; ArrayType a; - for( int size = 100; size <= 1000000; size *= 10 ) + for( int size = 1; size <= 100000; size *= 10 ) { a.setSize( size ); iota( a, 1 ); @@ -159,7 +159,7 @@ TYPED_TEST( ReduceTest, minWithArg ) { using ArrayType = typename TestFixture::ArrayType; ArrayType a; - for( int size = 100; size <= 1000000; size *= 10 ) + for( int size = 1; size <= 100000; size *= 10 ) { a.setSize( size ); iota( a, 1 ); @@ -174,7 +174,7 @@ TYPED_TEST( ReduceTest, maxWithArg ) { using ArrayType = typename TestFixture::ArrayType; ArrayType a; - for( int size = 100; size <= 1000000; size *= 10 ) + for( int size = 1; size <= 100000; size *= 10 ) { a.setSize( size ); iota( a, 1 ); @@ -189,7 +189,7 @@ TYPED_TEST( ReduceTest, logicalAnd ) { using ArrayType = typename TestFixture::ArrayType; ArrayType a; - for( int size = 100; size <= 1000000; size *= 10 ) + for( int size = 1; size <= 100000; size *= 10 ) { a.setSize( size ); @@ -207,11 +207,14 @@ TYPED_TEST( ReduceTest, logicalOr ) { using ArrayType = typename TestFixture::ArrayType; ArrayType a; - for( int size = 100; size <= 1000000; size *= 10 ) + for( int size = 1; size <= 100000; size *= 10 ) { a.setSize( size ); - mod( a, 2 ); + if( size == 1 ) + a.setValue( 1 ); + else + mod( a, 2 ); auto res = reduce< typename ArrayType::DeviceType >( 0, size, a.getConstView(), TNL::LogicalOr{} ); EXPECT_EQ( res, true ); @@ -226,7 +229,7 @@ template< typename ArrayType > std::enable_if_t< std::is_integral< typename ArrayType::ValueType >::value > test_bitAnd( ArrayType& a ) { - for( int size = 100; size <= 1000000; size *= 10 ) + for( int size = 1; size <= 100000; size *= 10 ) { a.setSize( size ); a.forAllElements( [] __cuda_callable__ ( typename ArrayType::IndexType idx, typename ArrayType::ValueType& value ) { value = 1 | ( 1 << ( idx % 8 ) ); } ); @@ -254,7 +257,7 @@ template< typename ArrayType > std::enable_if_t< std::is_integral< typename ArrayType::ValueType >::value > test_bitOr( ArrayType& a ) { - for( int size = 100; size <= 1000000; size *= 10 ) + for( int size = 10; size <= 100000; size *= 10 ) { a.setSize( size ); a.forAllElements( [] __cuda_callable__ ( typename ArrayType::IndexType idx, typename ArrayType::ValueType& value ) { value = 1 << ( idx % 8 );} ); diff --git a/src/UnitTests/Matrices/DenseMatrixTest.h b/src/UnitTests/Matrices/DenseMatrixTest.h index 4558387e4..8b8633415 100644 --- a/src/UnitTests/Matrices/DenseMatrixTest.h +++ b/src/UnitTests/Matrices/DenseMatrixTest.h @@ -1006,8 +1006,8 @@ void test_LargeVectorProduct() if( std::is_same< IndexType, short >::value ) return; - const IndexType rows = 5000; - const IndexType cols = 5000; + const IndexType rows = 997; + const IndexType cols = 997; Matrix m( rows, cols ); m.forAllElements( -- GitLab From f2a9c82cee5b3e4fccd5855dd20f21912e5d1759 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Klinkovsk=C3=BD?= Date: Sun, 21 Nov 2021 12:25:58 +0100 Subject: [PATCH 6/8] Removed obsolete and unused cmake modules --- cmake/AddCompilerFlag.cmake | 16 -- cmake/MacroEnsureVersion.cmake | 117 ---------- cmake/OptimizeForArchitecture.cmake | 334 ---------------------------- 3 files changed, 467 deletions(-) delete mode 100644 cmake/AddCompilerFlag.cmake delete mode 100644 cmake/MacroEnsureVersion.cmake delete mode 100644 cmake/OptimizeForArchitecture.cmake diff --git a/cmake/AddCompilerFlag.cmake b/cmake/AddCompilerFlag.cmake deleted file mode 100644 index 853c90ead..000000000 --- a/cmake/AddCompilerFlag.cmake +++ /dev/null @@ -1,16 +0,0 @@ -include (CheckCCompilerFlag) -include (CheckCXXCompilerFlag) -macro(AddCompilerFlag _flag) - string(REGEX REPLACE "[+/:= ]" "_" _flag_esc "${_flag}") - check_c_compiler_flag("${_flag}" check_c_compiler_flag_${_flag_esc}) - check_cxx_compiler_flag("${_flag}" check_cxx_compiler_flag_${_flag_esc}) - if(check_c_compiler_flag_${_flag_esc}) - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${_flag}") - endif(check_c_compiler_flag_${_flag_esc}) - if(check_cxx_compiler_flag_${_flag_esc}) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${_flag}") - endif(check_cxx_compiler_flag_${_flag_esc}) - if(${ARGC} EQUAL 2) - set(${ARGV1} "${check_cxx_compiler_flag_${_flag_esc}}") - endif(${ARGC} EQUAL 2) -endmacro(AddCompilerFlag) diff --git a/cmake/MacroEnsureVersion.cmake b/cmake/MacroEnsureVersion.cmake deleted file mode 100644 index 6797e5b7d..000000000 --- a/cmake/MacroEnsureVersion.cmake +++ /dev/null @@ -1,117 +0,0 @@ -# This file defines the following macros for developers to use in ensuring -# that installed software is of the right version: -# -# MACRO_ENSURE_VERSION - test that a version number is greater than -# or equal to some minimum -# MACRO_ENSURE_VERSION_RANGE - test that a version number is greater than -# or equal to some minimum and less than some -# maximum -# MACRO_ENSURE_VERSION2 - deprecated, do not use in new code -# - -# MACRO_ENSURE_VERSION -# This macro compares version numbers of the form "x.y.z" or "x.y" -# MACRO_ENSURE_VERSION( FOO_MIN_VERSION FOO_VERSION_FOUND FOO_VERSION_OK) -# will set FOO_VERSION_OK to true if FOO_VERSION_FOUND >= FOO_MIN_VERSION -# Leading and trailing text is ok, e.g. -# MACRO_ENSURE_VERSION( "2.5.31" "flex 2.5.4a" VERSION_OK) -# which means 2.5.31 is required and "flex 2.5.4a" is what was found on the system - -# Copyright (c) 2006, David Faure, -# Copyright (c) 2007, Will Stephenson -# -# Redistribution and use is allowed according to the terms of the BSD license. -# For details see the accompanying COPYING-CMAKE-SCRIPTS file. - -# MACRO_ENSURE_VERSION_RANGE -# This macro ensures that a version number of the form -# "x.y.z" or "x.y" falls within a range defined by -# min_version <= found_version < max_version. -# If this expression holds, FOO_VERSION_OK will be set TRUE -# -# Example: MACRO_ENSURE_VERSION_RANGE3( "0.1.0" ${FOOCODE_VERSION} "0.7.0" FOO_VERSION_OK ) -# -# This macro will break silently if any of x,y,z are greater than 100. -# -# Copyright (c) 2007, Will Stephenson -# -# Redistribution and use is allowed according to the terms of the BSD license. -# For details see the accompanying COPYING-CMAKE-SCRIPTS file. - -# NORMALIZE_VERSION -# Helper macro to convert version numbers of the form "x.y.z" -# to an integer equal to 10^4 * x + 10^2 * y + z -# -# This macro will break silently if any of x,y,z are greater than 100. -# -# Copyright (c) 2006, David Faure, -# Copyright (c) 2007, Will Stephenson -# -# Redistribution and use is allowed according to the terms of the BSD license. -# For details see the accompanying COPYING-CMAKE-SCRIPTS file. - -# CHECK_RANGE_INCLUSIVE_LOWER -# Helper macro to check whether x <= y < z -# -# Copyright (c) 2007, Will Stephenson -# -# Redistribution and use is allowed according to the terms of the BSD license. -# For details see the accompanying COPYING-CMAKE-SCRIPTS file. - - -MACRO(NORMALIZE_VERSION _requested_version _normalized_version) - STRING(REGEX MATCH "[^0-9]*[0-9]+\\.[0-9]+\\.[0-9]+.*" _threePartMatch "${_requested_version}") - if (_threePartMatch) - # parse the parts of the version string - STRING(REGEX REPLACE "[^0-9]*([0-9]+)\\.[0-9]+\\.[0-9]+.*" "\\1" _major_vers "${_requested_version}") - STRING(REGEX REPLACE "[^0-9]*[0-9]+\\.([0-9]+)\\.[0-9]+.*" "\\1" _minor_vers "${_requested_version}") - STRING(REGEX REPLACE "[^0-9]*[0-9]+\\.[0-9]+\\.([0-9]+).*" "\\1" _patch_vers "${_requested_version}") - else (_threePartMatch) - STRING(REGEX REPLACE "([0-9]+)\\.[0-9]+" "\\1" _major_vers "${_requested_version}") - STRING(REGEX REPLACE "[0-9]+\\.([0-9]+)" "\\1" _minor_vers "${_requested_version}") - set(_patch_vers "0") - endif (_threePartMatch) - - # compute an overall version number which can be compared at once - MATH(EXPR ${_normalized_version} "${_major_vers}*10000 + ${_minor_vers}*100 + ${_patch_vers}") -ENDMACRO(NORMALIZE_VERSION) - -MACRO(MACRO_CHECK_RANGE_INCLUSIVE_LOWER _lower_limit _value _upper_limit _ok) - if (${_value} LESS ${_lower_limit}) - set( ${_ok} FALSE ) - elseif (${_value} EQUAL ${_lower_limit}) - set( ${_ok} TRUE ) - elseif (${_value} EQUAL ${_upper_limit}) - set( ${_ok} FALSE ) - elseif (${_value} GREATER ${_upper_limit}) - set( ${_ok} FALSE ) - else (${_value} LESS ${_lower_limit}) - set( ${_ok} TRUE ) - endif (${_value} LESS ${_lower_limit}) -ENDMACRO(MACRO_CHECK_RANGE_INCLUSIVE_LOWER) - -MACRO(MACRO_ENSURE_VERSION requested_version found_version var_too_old) - NORMALIZE_VERSION( ${requested_version} req_vers_num ) - NORMALIZE_VERSION( ${found_version} found_vers_num ) - - if (found_vers_num LESS req_vers_num) - set( ${var_too_old} FALSE ) - else (found_vers_num LESS req_vers_num) - set( ${var_too_old} TRUE ) - endif (found_vers_num LESS req_vers_num) - -ENDMACRO(MACRO_ENSURE_VERSION) - -MACRO(MACRO_ENSURE_VERSION2 requested_version2 found_version2 var_too_old2) - MACRO_ENSURE_VERSION( ${requested_version2} ${found_version2} ${var_too_old2}) -ENDMACRO(MACRO_ENSURE_VERSION2) - -MACRO(MACRO_ENSURE_VERSION_RANGE min_version found_version max_version var_ok) - NORMALIZE_VERSION( ${min_version} req_vers_num ) - NORMALIZE_VERSION( ${found_version} found_vers_num ) - NORMALIZE_VERSION( ${max_version} max_vers_num ) - - MACRO_CHECK_RANGE_INCLUSIVE_LOWER( ${req_vers_num} ${found_vers_num} ${max_vers_num} ${var_ok}) -ENDMACRO(MACRO_ENSURE_VERSION_RANGE) - - diff --git a/cmake/OptimizeForArchitecture.cmake b/cmake/OptimizeForArchitecture.cmake deleted file mode 100644 index 36ec19875..000000000 --- a/cmake/OptimizeForArchitecture.cmake +++ /dev/null @@ -1,334 +0,0 @@ -include (AddCompilerFlag) -include (MacroEnsureVersion) - -macro(_my_find _list _value _ret) - list(FIND ${_list} "${_value}" _found) - if(_found EQUAL -1) - set(${_ret} FALSE) - else(_found EQUAL -1) - set(${_ret} TRUE) - endif(_found EQUAL -1) -endmacro(_my_find) - -macro(OptimizeForArchitecture) - set(TARGET_ARCHITECTURE "auto" CACHE STRING "CPU architecture to optimize for. Using an incorrect setting here can result in crashes of the resulting binary because of invalid instructions used.\nSetting the value to \"auto\" will try to optimize for the architecture where cmake is called.\nOther supported values are: \"generic\", \"core\", \"merom\" (65nm Core2), \"penryn\" (45nm Core2), \"nehalem\", \"westmere\", \"sandy-bridge\", \"atom\", \"k8\", \"k8-sse3\", \"barcelona\", \"istanbul\", \"magny-cours\", \"bulldozer\", \"interlagos\".") - set(_force) - if(NOT _last_target_arch STREQUAL "${TARGET_ARCHITECTURE}") - message(STATUS "${TARGET_ARCHITECTURE} changed") - set(_force FORCE) - endif(NOT _last_target_arch STREQUAL "${TARGET_ARCHITECTURE}") - set(_last_target_arch "${TARGET_ARCHITECTURE}" CACHE STRING "" FORCE) - mark_as_advanced(_last_target_arch) - string(TOLOWER "${TARGET_ARCHITECTURE}" TARGET_ARCHITECTURE) - - set(_march_flag_list) - set(_available_vector_units_list) - - if(TARGET_ARCHITECTURE STREQUAL "auto") - set(TARGET_ARCHITECTURE "generic") - set(_vendor_id) - set(_cpu_family) - set(_cpu_model) - if(CMAKE_SYSTEM_NAME STREQUAL "Linux") - file(READ "/proc/cpuinfo" _cpuinfo) - string(REGEX REPLACE ".*vendor_id[ \t]*:[ \t]+([a-zA-Z0-9_-]+).*" "\\1" _vendor_id "${_cpuinfo}") - string(REGEX REPLACE ".*cpu family[ \t]*:[ \t]+([a-zA-Z0-9_-]+).*" "\\1" _cpu_family "${_cpuinfo}") - string(REGEX REPLACE ".*model[ \t]*:[ \t]+([a-zA-Z0-9_-]+).*" "\\1" _cpu_model "${_cpuinfo}") - string(REGEX REPLACE ".*flags[ \t]*:[ \t]+([a-zA-Z0-9_-]+).*" "\\1" _cpu_flags "${_cpuinfo}") - elseif(CMAKE_SYSTEM_NAME STREQUAL "Darwin") - exec_program("/usr/sbin/sysctl -n machdep.cpu.vendor" OUTPUT_VARIABLE _vendor_id) - exec_program("/usr/sbin/sysctl -n machdep.cpu.model" OUTPUT_VARIABLE _cpu_model) - exec_program("/usr/sbin/sysctl -n machdep.cpu.family" OUTPUT_VARIABLE _cpu_family) - exec_program("/usr/sbin/sysctl -n machdep.cpu.features" OUTPUT_VARIABLE _cpu_flags) - string(TOLOWER "${_cpu_flags}" _cpu_flags) - string(REPLACE "." "_" _cpu_flags "${_cpu_flags}") - elseif(CMAKE_SYSTEM_NAME STREQUAL "Windows") - get_filename_component(_vendor_id "[HKEY_LOCAL_MACHINE\\Hardware\\Description\\System\\CentralProcessor\\0;VendorIdentifier]" NAME CACHE) - get_filename_component(_cpu_id "[HKEY_LOCAL_MACHINE\\Hardware\\Description\\System\\CentralProcessor\\0;Identifier]" NAME CACHE) - mark_as_advanced(_vendor_id _cpu_id) - string(REGEX REPLACE ".* Family ([0-9]+) .*" "\\1" _cpu_family "${_cpu_id}") - string(REGEX REPLACE ".* Model ([0-9]+) .*" "\\1" _cpu_model "${_cpu_id}") - message(AUTHOR_WARNING "If you know how to query the processor capabilities wrt. SSE on Windows, let me know!") - endif(CMAKE_SYSTEM_NAME STREQUAL "Linux") - if(_vendor_id STREQUAL "GenuineIntel") - if(_cpu_family EQUAL 6) - # Any recent Intel CPU except NetBurst - if(_cpu_model EQUAL 46) # Xeon 7500 series - set(TARGET_ARCHITECTURE "westmere") - elseif(_cpu_model EQUAL 45) # Xeon TNG - set(TARGET_ARCHITECTURE "sandy-bridge") - elseif(_cpu_model EQUAL 44) # Xeon 5600 series - set(TARGET_ARCHITECTURE "westmere") - elseif(_cpu_model EQUAL 42) # Core TNG - set(TARGET_ARCHITECTURE "sandy-bridge") - elseif(_cpu_model EQUAL 37) # Core i7/i5/i3 - set(TARGET_ARCHITECTURE "westmere") - elseif(_cpu_model EQUAL 31) # Core i7/i5 - set(TARGET_ARCHITECTURE "westmere") - elseif(_cpu_model EQUAL 30) # Core i7/i5 - set(TARGET_ARCHITECTURE "westmere") - elseif(_cpu_model EQUAL 29) - set(TARGET_ARCHITECTURE "penryn") - elseif(_cpu_model EQUAL 28) - set(TARGET_ARCHITECTURE "atom") - elseif(_cpu_model EQUAL 26) - set(TARGET_ARCHITECTURE "nehalem") - elseif(_cpu_model EQUAL 23) - set(TARGET_ARCHITECTURE "penryn") - elseif(_cpu_model EQUAL 15) - set(TARGET_ARCHITECTURE "merom") - elseif(_cpu_model EQUAL 14) - set(TARGET_ARCHITECTURE "core") - elseif(_cpu_model LESS 14) - message(WARNING "Your CPU (family ${_cpu_family}, model ${_cpu_model}) is not known. Auto-detection of optimization flags failed and will use the generic CPU settings with SSE2.") - set(TARGET_ARCHITECTURE "generic") - else() - message(WARNING "Your CPU (family ${_cpu_family}, model ${_cpu_model}) is not known. Auto-detection of optimization flags failed and will use the 65nm Core 2 CPU settings.") - set(TARGET_ARCHITECTURE "merom") - endif() - elseif(_cpu_family EQUAL 7) # Itanium (not supported) - message(WARNING "Your CPU (Itanium: family ${_cpu_family}, model ${_cpu_model}) is not supported by OptimizeForArchitecture.cmake.") - elseif(_cpu_family EQUAL 15) # NetBurst - list(APPEND _available_vector_units_list "sse" "sse2") - if(_cpu_model GREATER 2) # Not sure whether this must be 3 or even 4 instead - list(APPEND _available_vector_units_list "sse" "sse2" "sse3") - endif(_cpu_model GREATER 2) - endif(_cpu_family EQUAL 6) - elseif(_vendor_id STREQUAL "AuthenticAMD") - if(_cpu_family EQUAL 21) # 15h - set(TARGET_ARCHITECTURE "bulldozer") - elseif(_cpu_family EQUAL 20) # 14h - elseif(_cpu_family EQUAL 18) # 12h - elseif(_cpu_family EQUAL 16) # 10h - set(TARGET_ARCHITECTURE "barcelona") - elseif(_cpu_family EQUAL 15) - set(TARGET_ARCHITECTURE "k8") - if(_cpu_model GREATER 64) # I don't know the right number to put here. This is just a guess from the hardware I have access to - set(TARGET_ARCHITECTURE "k8-sse3") - endif(_cpu_model GREATER 64) - endif() - endif(_vendor_id STREQUAL "GenuineIntel") - message(STATUS "Detected CPU: ${TARGET_ARCHITECTURE}") - endif(TARGET_ARCHITECTURE STREQUAL "auto") - - if(TARGET_ARCHITECTURE STREQUAL "core") - list(APPEND _march_flag_list "core2") - list(APPEND _available_vector_units_list "sse" "sse2" "sse3") - elseif(TARGET_ARCHITECTURE STREQUAL "merom") - list(APPEND _march_flag_list "merom") - list(APPEND _march_flag_list "core2") - list(APPEND _available_vector_units_list "sse" "sse2" "sse3" "ssse3") - elseif(TARGET_ARCHITECTURE STREQUAL "penryn") - list(APPEND _march_flag_list "penryn") - list(APPEND _march_flag_list "core2") - list(APPEND _available_vector_units_list "sse" "sse2" "sse3" "ssse3") - message(STATUS "Sadly the Penryn architecture exists in variants with SSE4.1 and without SSE4.1.") - if(_cpu_flags MATCHES "sse4_1") - message(STATUS "SSE4.1: enabled (auto-detected from this computer's CPU flags)") - list(APPEND _available_vector_units_list "sse4.1") - else() - message(STATUS "SSE4.1: disabled (auto-detected from this computer's CPU flags)") - endif() - elseif(TARGET_ARCHITECTURE STREQUAL "nehalem") - list(APPEND _march_flag_list "nehalem") - list(APPEND _march_flag_list "corei7") - list(APPEND _march_flag_list "core2") - list(APPEND _available_vector_units_list "sse" "sse2" "sse3" "ssse3" "sse4.1" "sse4.2") - elseif(TARGET_ARCHITECTURE STREQUAL "westmere") - list(APPEND _march_flag_list "westmere") - list(APPEND _march_flag_list "corei7") - list(APPEND _march_flag_list "core2") - list(APPEND _available_vector_units_list "sse" "sse2" "sse3" "ssse3" "sse4.1" "sse4.2") - elseif(TARGET_ARCHITECTURE STREQUAL "sandy-bridge") - list(APPEND _march_flag_list "sandybridge") - list(APPEND _march_flag_list "corei7-avx") - list(APPEND _march_flag_list "core2") - list(APPEND _available_vector_units_list "sse" "sse2" "sse3" "ssse3" "sse4.1" "sse4.2" "avx") - elseif(TARGET_ARCHITECTURE STREQUAL "atom") - list(APPEND _march_flag_list "atom") - list(APPEND _march_flag_list "core2") - list(APPEND _available_vector_units_list "sse" "sse2" "sse3" "ssse3") - elseif(TARGET_ARCHITECTURE STREQUAL "k8") - list(APPEND _march_flag_list "k8") - list(APPEND _available_vector_units_list "sse" "sse2") - elseif(TARGET_ARCHITECTURE STREQUAL "k8-sse3") - list(APPEND _march_flag_list "k8-sse3") - list(APPEND _march_flag_list "k8") - list(APPEND _available_vector_units_list "sse" "sse2" "sse3") - elseif(TARGET_ARCHITECTURE STREQUAL "interlagos") - list(APPEND _march_flag_list "bulldozer") - list(APPEND _march_flag_list "barcelona") - list(APPEND _march_flag_list "core2") - list(APPEND _available_vector_units_list "sse" "sse2" "sse3" "ssse3" "sse4a" "sse4.1" "sse4.2" "avx" "xop" "fma4") - elseif(TARGET_ARCHITECTURE STREQUAL "bulldozer") - list(APPEND _march_flag_list "bulldozer") - list(APPEND _march_flag_list "barcelona") - list(APPEND _march_flag_list "core2") - list(APPEND _available_vector_units_list "sse" "sse2" "sse3" "ssse3" "sse4a" "sse4.1" "sse4.2" "avx" "xop" "fma4") - elseif(TARGET_ARCHITECTURE STREQUAL "barcelona") - list(APPEND _march_flag_list "barcelona") - list(APPEND _march_flag_list "core2") - list(APPEND _available_vector_units_list "sse" "sse2" "sse3" "sse4a") - elseif(TARGET_ARCHITECTURE STREQUAL "istanbul") - list(APPEND _march_flag_list "barcelona") - list(APPEND _march_flag_list "core2") - list(APPEND _available_vector_units_list "sse" "sse2" "sse3" "sse4a") - elseif(TARGET_ARCHITECTURE STREQUAL "magny-cours") - list(APPEND _march_flag_list "barcelona") - list(APPEND _march_flag_list "core2") - list(APPEND _available_vector_units_list "sse" "sse2" "sse3" "sse4a") - elseif(TARGET_ARCHITECTURE STREQUAL "generic") - list(APPEND _march_flag_list "generic") - else(TARGET_ARCHITECTURE STREQUAL "core") - message(FATAL_ERROR "Unknown target architecture: \"${TARGET_ARCHITECTURE}\". Please set TARGET_ARCHITECTURE to a supported value.") - endif(TARGET_ARCHITECTURE STREQUAL "core") - - set(_disable_vector_unit_list) - set(_enable_vector_unit_list) - _my_find(_available_vector_units_list "sse2" SSE2_FOUND) - _my_find(_available_vector_units_list "sse3" SSE3_FOUND) - _my_find(_available_vector_units_list "ssse3" SSSE3_FOUND) - _my_find(_available_vector_units_list "sse4.1" SSE4_1_FOUND) - _my_find(_available_vector_units_list "sse4.2" SSE4_2_FOUND) - _my_find(_available_vector_units_list "sse4a" SSE4a_FOUND) - _my_find(_available_vector_units_list "avx" AVX_FOUND) - _my_find(_available_vector_units_list "xop" XOP_FOUND) - _my_find(_available_vector_units_list "fma4" FMA4_FOUND) - set(USE_SSE2 ${SSE2_FOUND} CACHE BOOL "Use SSE2. If SSE2 instructions are not enabled the SSE implementation will be disabled." ${_force}) - set(USE_SSE3 ${SSE3_FOUND} CACHE BOOL "Use SSE3. If SSE3 instructions are not enabled they will be emulated." ${_force}) - set(USE_SSSE3 ${SSSE3_FOUND} CACHE BOOL "Use SSSE3. If SSSE3 instructions are not enabled they will be emulated." ${_force}) - set(USE_SSE4_1 ${SSE4_1_FOUND} CACHE BOOL "Use SSE4.1. If SSE4.1 instructions are not enabled they will be emulated." ${_force}) - set(USE_SSE4_2 ${SSE4_2_FOUND} CACHE BOOL "Use SSE4.2. If SSE4.2 instructions are not enabled they will be emulated." ${_force}) - set(USE_SSE4a ${SSE4a_FOUND} CACHE BOOL "Use SSE4a. If SSE4a instructions are not enabled they will be emulated." ${_force}) - set(USE_AVX ${AVX_FOUND} CACHE BOOL "Use AVX. This will double some of the vector sizes relative to SSE." ${_force}) - set(USE_XOP ${XOP_FOUND} CACHE BOOL "Use XOP." ${_force}) - set(USE_FMA4 ${FMA4_FOUND} CACHE BOOL "Use FMA4." ${_force}) - mark_as_advanced(USE_SSE2 USE_SSE3 USE_SSSE3 USE_SSE4_1 USE_SSE4_2 USE_SSE4a USE_AVX) - if(USE_SSE2) - list(APPEND _enable_vector_unit_list "sse2") - else(USE_SSE2) - list(APPEND _disable_vector_unit_list "sse2") - endif(USE_SSE2) - if(USE_SSE3) - list(APPEND _enable_vector_unit_list "sse3") - else(USE_SSE3) - list(APPEND _disable_vector_unit_list "sse3") - endif(USE_SSE3) - if(USE_SSSE3) - list(APPEND _enable_vector_unit_list "ssse3") - else(USE_SSSE3) - list(APPEND _disable_vector_unit_list "ssse3") - endif(USE_SSSE3) - if(USE_SSE4_1) - list(APPEND _enable_vector_unit_list "sse4.1") - else(USE_SSE4_1) - list(APPEND _disable_vector_unit_list "sse4.1") - endif(USE_SSE4_1) - if(USE_SSE4_2) - list(APPEND _enable_vector_unit_list "sse4.2") - else(USE_SSE4_2) - list(APPEND _disable_vector_unit_list "sse4.2") - endif(USE_SSE4_2) - if(USE_SSE4a) - list(APPEND _enable_vector_unit_list "sse4a") - else(USE_SSE4a) - list(APPEND _disable_vector_unit_list "sse4a") - endif(USE_SSE4a) - if(USE_AVX) - list(APPEND _enable_vector_unit_list "avx") - # we want SSE intrinsics to result in instructions using the VEX prefix. - # Otherwise integer ops (which require the older SSE intrinsics) would - # always have a large penalty. - list(APPEND _enable_vector_unit_list "sse2avx") - else(USE_AVX) - list(APPEND _disable_vector_unit_list "avx") - endif(USE_AVX) - if(USE_XOP) - list(APPEND _enable_vector_unit_list "xop") - else() - list(APPEND _disable_vector_unit_list "xop") - endif() - if(USE_FMA4) - list(APPEND _enable_vector_unit_list "fma4") - else() - list(APPEND _disable_vector_unit_list "fma4") - endif() - if(CMAKE_C_COMPILER MATCHES "cl(.exe)?$") # MSVC - # MSVC on 32 bit can select only /arch:SSE2 - # MSVC on 64 bit cannot select anything - if(NOT CMAKE_CL_64) - _my_find(_enable_vector_unit_list "sse2") - AddCompilerFlag("/arch:SSE2") - endif(NOT CMAKE_CL_64) - foreach(_flag ${_enable_vector_unit_list}) - string(TOUPPER "${_flag}" _flag) - string(REPLACE "." "_" _flag "__${_flag}__") - add_definitions("-D${_flag}") - endforeach(_flag) - elseif(CMAKE_CXX_COMPILER MATCHES "/(icpc|icc)$") # ICC - _my_find(_available_vector_units_list "avx" _found) - if(_found) - AddCompilerFlag("-xAVX") - else(_found) - _my_find(_available_vector_units_list "sse4.2" _found) - if(_found) - AddCompilerFlag("-xSSE4.2") - else(_found) - _my_find(_available_vector_units_list "sse4.1" _found) - if(_found) - AddCompilerFlag("-xSSE4.1") - else(_found) - _my_find(_available_vector_units_list "ssse3" _found) - if(_found) - AddCompilerFlag("-xSSSE3") - else(_found) - _my_find(_available_vector_units_list "sse3" _found) - if(_found) - # If the target host is an AMD machine then we still want to use -xSSE2 because the binary would refuse to run at all otherwise - _my_find(_march_flag_list "barcelona" _found) - if(NOT _found) - _my_find(_march_flag_list "k8-sse3" _found) - endif(NOT _found) - if(_found) - AddCompilerFlag("-xSSE2") - else(_found) - AddCompilerFlag("-xSSE3") - endif(_found) - else(_found) - _my_find(_available_vector_units_list "sse2" _found) - if(_found) - AddCompilerFlag("-xSSE2") - endif(_found) - endif(_found) - endif(_found) - endif(_found) - endif(_found) - endif(_found) - else(CMAKE_C_COMPILER MATCHES "cl(.exe)?$") - foreach(_flag ${_march_flag_list}) - AddCompilerFlag("-march=${_flag}" _good) - if(_good) - break() - endif(_good) - endforeach(_flag) - foreach(_flag ${_enable_vector_unit_list}) - AddCompilerFlag("-m${_flag}") - endforeach(_flag) - foreach(_flag ${_disable_vector_unit_list}) - AddCompilerFlag("-mno-${_flag}") - endforeach(_flag) - # Not really target architecture specific, but GCC 4.5.[01] fail at inlining some functions, - # creating functions with a single instructions, thus a large overhead. This is a good - # (because central) place to fix the problem - if(CMAKE_COMPILER_IS_GNUCXX) - exec_program(${CMAKE_C_COMPILER} ARGS -dumpversion OUTPUT_VARIABLE _gcc_version) - macro_ensure_version("4.5.0" "${_gcc_version}" GCC_4_5_0) - if(GCC_4_5_0) - macro_ensure_version("4.5.2" "${_gcc_version}" GCC_4_5_2) - if(NOT GCC_4_5_2) - AddCompilerFlag("--param early-inlining-insns=12") - endif(NOT GCC_4_5_2) - endif(GCC_4_5_0) - endif(CMAKE_COMPILER_IS_GNUCXX) - endif(CMAKE_C_COMPILER MATCHES "cl(.exe)?$") -endmacro(OptimizeForArchitecture) -- GitLab From 81e08530ce18b6ffb8f1ce5e85dcddff23183bb7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Klinkovsk=C3=BD?= Date: Sun, 21 Nov 2021 10:15:01 +0100 Subject: [PATCH 7/8] Updated FindPETSC.cmake file and its dependencies Taken from https://github.com/jedbrown/cmake-modules --- cmake/CorrectWindowsPaths.cmake | 14 ++ cmake/FindPETSc.cmake | 221 +++++++++++++++++++------------ cmake/FindPackageMultipass.cmake | 66 ++++----- cmake/ResolveCompilerPaths.cmake | 34 +++-- 4 files changed, 208 insertions(+), 127 deletions(-) create mode 100644 cmake/CorrectWindowsPaths.cmake diff --git a/cmake/CorrectWindowsPaths.cmake b/cmake/CorrectWindowsPaths.cmake new file mode 100644 index 000000000..09bcdd67d --- /dev/null +++ b/cmake/CorrectWindowsPaths.cmake @@ -0,0 +1,14 @@ +# CorrectWindowsPaths - this module defines one macro +# +# CONVERT_CYGWIN_PATH( PATH ) +# This uses the command cygpath (provided by cygwin) to convert +# unix-style paths into paths useable by cmake on windows + +macro (CONVERT_CYGWIN_PATH _path) + if (WIN32) + EXECUTE_PROCESS(COMMAND cygpath.exe -m ${${_path}} + OUTPUT_VARIABLE ${_path}) + string (STRIP ${${_path}} ${_path}) + endif (WIN32) +endmacro (CONVERT_CYGWIN_PATH) + diff --git a/cmake/FindPETSc.cmake b/cmake/FindPETSc.cmake index d50c60f1d..41e02d979 100644 --- a/cmake/FindPETSc.cmake +++ b/cmake/FindPETSc.cmake @@ -1,33 +1,40 @@ # - Try to find PETSc # Once done this will define # -# PETSC_FOUND - system has PETSc -# PETSC_INCLUDES - the PETSc include directories -# PETSC_LIBRARIES - Link these to use PETSc -# PETSC_COMPILER - Compiler used by PETSc, helpful to find a compatible MPI -# PETSC_DEFINITIONS - Compiler switches for using PETSc -# PETSC_MPIEXEC - Executable for running MPI programs -# PETSC_VERSION - Version string (MAJOR.MINOR.SUBMINOR) +# PETSC_FOUND - system has PETSc +# PETSC_INCLUDES - the PETSc include directories +# PETSC_LIBRARIES - Link these to use PETSc +# PETSC_COMPILER - Compiler used by PETSc, helpful to find a compatible MPI +# PETSC_DEFINITIONS - Compiler switches for using PETSc +# PETSC_MPIEXEC - Executable for running MPI programs +# PETSC_VERSION - Version string (MAJOR.MINOR.SUBMINOR) # -# Usage: -# find_package(PETSc COMPONENTS CXX) - required if build --with-clanguage=C++ --with-c-support=0 -# find_package(PETSc COMPONENTS C) - standard behavior of checking build using a C compiler -# find_package(PETSc) - same as above +# Usage: +# find_package(PETSc COMPONENTS CXX) - required if build --with-clanguage=C++ --with-c-support=0 +# find_package(PETSc COMPONENTS C) - standard behavior of checking build using a C compiler +# find_package(PETSc) - same as above # # Setting these changes the behavior of the search -# PETSC_DIR - directory in which PETSc resides -# PETSC_ARCH - build architecture +# PETSC_DIR - directory in which PETSc resides +# PETSC_ARCH - build architecture # # Redistribution and use is allowed according to the terms of the BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. # +cmake_policy(VERSION 3.3) + set(PETSC_VALID_COMPONENTS C CXX) if(NOT PETSc_FIND_COMPONENTS) - set(PETSC_LANGUAGE_BINDINGS "C") + get_property (_enabled_langs GLOBAL PROPERTY ENABLED_LANGUAGES) + if ("C" IN_LIST _enabled_langs) + set(PETSC_LANGUAGE_BINDINGS "C") + else () + set(PETSC_LANGUAGE_BINDINGS "CXX") + endif () else() # Right now, this is designed for compatability with the --with-clanguage option, so # only allow one item in the components list. @@ -41,37 +48,50 @@ else() list(FIND PETSC_VALID_COMPONENTS ${component} component_location) if(${component_location} EQUAL -1) message(FATAL_ERROR "\"${component}\" is not a valid PETSc component.") -else() -list(APPEND PETSC_LANGUAGE_BINDINGS ${component}) -endif() -endforeach() + else() + list(APPEND PETSC_LANGUAGE_BINDINGS ${component}) + endif() + endforeach() endif() function (petsc_get_version) -if (EXISTS "${PETSC_DIR}/include/petscversion.h") -file (STRINGS "${PETSC_DIR}/include/petscversion.h" vstrings REGEX "#define PETSC_VERSION_(RELEASE|MAJOR|MINOR|SUBMINOR|PATCH) ") + if (EXISTS "${PETSC_DIR}/include/petscversion.h") + file (STRINGS "${PETSC_DIR}/include/petscversion.h" vstrings REGEX "#define PETSC_VERSION_(RELEASE|MAJOR|MINOR|SUBMINOR|PATCH) ") foreach (line ${vstrings}) string (REGEX REPLACE " +" ";" fields ${line}) # break line into three fields (the first is always "#define") list (GET fields 1 var) list (GET fields 2 val) set (${var} ${val} PARENT_SCOPE) - set (${var} ${val}) # Also in local scope so we have access below + set (${var} ${val}) # Also in local scope so we have access below endforeach () if (PETSC_VERSION_RELEASE) - set (PETSC_VERSION "${PETSC_VERSION_MAJOR}.${PETSC_VERSION_MINOR}.${PETSC_VERSION_SUBMINOR}p${PETSC_VERSION_PATCH}" PARENT_SCOPE) + if ($(PETSC_VERSION_PATCH) GREATER 0) + set (PETSC_VERSION "${PETSC_VERSION_MAJOR}.${PETSC_VERSION_MINOR}.${PETSC_VERSION_SUBMINOR}p${PETSC_VERSION_PATCH}" CACHE INTERNAL "PETSc version") + else () + set (PETSC_VERSION "${PETSC_VERSION_MAJOR}.${PETSC_VERSION_MINOR}.${PETSC_VERSION_SUBMINOR}" CACHE INTERNAL "PETSc version") + endif () else () # make dev version compare higher than any patch level of a released version - set (PETSC_VERSION "${PETSC_VERSION_MAJOR}.${PETSC_VERSION_MINOR}.${PETSC_VERSION_SUBMINOR}.99" PARENT_SCOPE) + set (PETSC_VERSION "${PETSC_VERSION_MAJOR}.${PETSC_VERSION_MINOR}.${PETSC_VERSION_SUBMINOR}.99" CACHE INTERNAL "PETSc version") endif () else () message (SEND_ERROR "PETSC_DIR can not be used, ${PETSC_DIR}/include/petscversion.h does not exist") endif () endfunction () +# Debian uses versioned paths e.g /usr/lib/petscdir/3.5/ +file (GLOB DEB_PATHS "/usr/lib/petscdir/*") + find_path (PETSC_DIR include/petsc.h HINTS ENV PETSC_DIR PATHS - /usr/lib/petscdir/3.1 /usr/lib/petscdir/3.0.0 /usr/lib/petscdir/2.3.3 /usr/lib/petscdir/2.3.2 # Debian + /usr/lib/petsc + # Debian paths + ${DEB_PATHS} + # Arch Linux path + /opt/petsc/linux-c-opt + # MacPorts path + /opt/local/lib/petsc $ENV{HOME}/petsc DOC "PETSc Directory") @@ -79,18 +99,18 @@ find_program (MAKE_EXECUTABLE NAMES make gmake) if (PETSC_DIR AND NOT PETSC_ARCH) set (_petsc_arches - $ENV{PETSC_ARCH} # If set, use environment variable first - linux-gnu-c-debug linux-gnu-c-opt # Debian defaults + $ENV{PETSC_ARCH} # If set, use environment variable first + linux-gnu-c-debug linux-gnu-c-opt # Debian defaults x86_64-unknown-linux-gnu i386-unknown-linux-gnu) set (petscconf "NOTFOUND" CACHE FILEPATH "Cleared" FORCE) foreach (arch ${_petsc_arches}) if (NOT PETSC_ARCH) find_path (petscconf petscconf.h -HINTS ${PETSC_DIR} -PATH_SUFFIXES ${arch}/include bmake/${arch} -NO_DEFAULT_PATH) + HINTS ${PETSC_DIR} + PATH_SUFFIXES ${arch}/include bmake/${arch} + NO_DEFAULT_PATH) if (petscconf) -set (PETSC_ARCH "${arch}" CACHE STRING "PETSc build architecture") + set (PETSC_ARCH "${arch}" CACHE STRING "PETSc build architecture") endif (petscconf) endif (NOT PETSC_ARCH) endforeach (arch) @@ -106,7 +126,10 @@ find_package_multipass (PETSc petsc_config_current # Determine whether the PETSc layout is old-style (through 2.3.3) or # new-style (>= 3.0.0) -if (EXISTS "${PETSC_DIR}/${PETSC_ARCH}/include/petscconf.h") # > 2.3.3 +if (EXISTS "${PETSC_DIR}/${PETSC_ARCH}/lib/petsc/conf/petscvariables") # > 3.5 + set (petsc_conf_rules "${PETSC_DIR}/lib/petsc/conf/rules") + set (petsc_conf_variables "${PETSC_DIR}/lib/petsc/conf/variables") +elseif (EXISTS "${PETSC_DIR}/${PETSC_ARCH}/include/petscconf.h") # > 2.3.3 set (petsc_conf_rules "${PETSC_DIR}/conf/rules") set (petsc_conf_variables "${PETSC_DIR}/conf/variables") elseif (EXISTS "${PETSC_DIR}/bmake/${PETSC_ARCH}/petscconf.h") # <= 2.3.3 @@ -128,12 +151,12 @@ if (petsc_conf_rules AND petsc_conf_variables AND NOT petsc_config_current) set (petsc_config_makefile "${PROJECT_BINARY_DIR}/Makefile.petsc") file (WRITE "${petsc_config_makefile}" "## This file was autogenerated by FindPETSc.cmake -# PETSC_DIR = ${PETSC_DIR} +# PETSC_DIR = ${PETSC_DIR} # PETSC_ARCH = ${PETSC_ARCH} include ${petsc_conf_rules} include ${petsc_conf_variables} show : --@echo -n \${\${VARIABLE}} +\t-@echo -n \${\${VARIABLE}} ") macro (PETSC_GET_VARIABLE name var) @@ -142,12 +165,13 @@ show : OUTPUT_VARIABLE ${var} RESULT_VARIABLE petsc_return) endmacro (PETSC_GET_VARIABLE) - petsc_get_variable (PETSC_LIB_DIR petsc_lib_dir) + petsc_get_variable (PETSC_LIB_DIR petsc_lib_dir) petsc_get_variable (PETSC_EXTERNAL_LIB_BASIC petsc_libs_external) - petsc_get_variable (PETSC_CCPPFLAGS petsc_cpp_line) - petsc_get_variable (PETSC_INCLUDE petsc_include) - petsc_get_variable (PCC petsc_cc) - petsc_get_variable (MPIEXEC petsc_mpiexec) + petsc_get_variable (PETSC_CCPPFLAGS petsc_cpp_line) + petsc_get_variable (PETSC_INCLUDE petsc_include) + petsc_get_variable (PCC petsc_cc) + petsc_get_variable (PCC_FLAGS petsc_cc_flags) + petsc_get_variable (MPIEXEC petsc_mpiexec) # We are done with the temporary Makefile, calling PETSC_GET_VARIABLE after this point is invalid! file (REMOVE ${petsc_config_makefile}) @@ -155,11 +179,39 @@ show : # Extract include paths and libraries from compile command line resolve_includes (petsc_includes_all "${petsc_cpp_line}") + #on windows we need to make sure we're linking against the right + #runtime library + if (WIN32) + if (petsc_cc_flags MATCHES "-MT") + set(using_md False) + foreach(flag_var + CMAKE_C_FLAGS CMAKE_C_FLAGS_DEBUG CMAKE_C_FLAGS_RELEASE + CMAKE_C_FLAGS_MINSIZEREL CMAKE_C_FLAGS_RELWITHDEBINFO + CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE + CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO) + if(${flag_var} MATCHES "/MD") + set(using_md True) + endif(${flag_var} MATCHES "/MD") + endforeach(flag_var) + if(${using_md} MATCHES "True") + message(WARNING "PETSc was built with /MT, but /MD is currently set. + See http://www.cmake.org/Wiki/CMake_FAQ#How_can_I_build_my_MSVC_application_with_a_static_runtime.3F") + endif(${using_md} MATCHES "True") + endif (petsc_cc_flags MATCHES "-MT") + endif (WIN32) + + include (CorrectWindowsPaths) + convert_cygwin_path(petsc_lib_dir) message (STATUS "petsc_lib_dir ${petsc_lib_dir}") macro (PETSC_FIND_LIBRARY suffix name) set (PETSC_LIBRARY_${suffix} "NOTFOUND" CACHE INTERNAL "Cleared" FORCE) # Clear any stale value, if we got here, we need to find it again - find_library (PETSC_LIBRARY_${suffix} NAMES ${name} HINTS ${petsc_lib_dir} NO_DEFAULT_PATH) + if (WIN32) + set (libname lib${name}) #windows expects "libfoo", linux expects "foo" + else (WIN32) + set (libname ${name}) + endif (WIN32) + find_library (PETSC_LIBRARY_${suffix} NAMES ${libname} HINTS ${petsc_lib_dir} NO_DEFAULT_PATH) set (PETSC_LIBRARIES_${suffix} "${PETSC_LIBRARY_${suffix}}") mark_as_advanced (PETSC_LIBRARY_${suffix}) endmacro (PETSC_FIND_LIBRARY suffix name) @@ -167,25 +219,32 @@ show : # Look for petscvec first, if it doesn't exist, we must be using single-library petsc_find_library (VEC petscvec) if (PETSC_LIBRARY_VEC) - petsc_find_library (SYS "petscsys;petsc") # libpetscsys is called libpetsc prior to 3.1 (when single-library was introduced) - petsc_find_library (MAT petscmat) - petsc_find_library (DM petscdm) - petsc_find_library (KSP petscksp) + petsc_find_library (SYS "petscsys;petsc") # libpetscsys is called libpetsc prior to 3.1 (when single-library was introduced) + petsc_find_library (MAT petscmat) + petsc_find_library (DM petscdm) + petsc_find_library (KSP petscksp) petsc_find_library (SNES petscsnes) - petsc_find_library (TS petscts) + petsc_find_library (TS petscts) macro (PETSC_JOIN libs deps) list (APPEND PETSC_LIBRARIES_${libs} ${PETSC_LIBRARIES_${deps}}) endmacro (PETSC_JOIN libs deps) - petsc_join (VEC SYS) - petsc_join (MAT VEC) - petsc_join (DM MAT) - petsc_join (KSP DM) + petsc_join (VEC SYS) + petsc_join (MAT VEC) + petsc_join (DM MAT) + petsc_join (KSP DM) petsc_join (SNES KSP) - petsc_join (TS SNES) - petsc_join (ALL TS) + petsc_join (TS SNES) + petsc_join (ALL TS) else () set (PETSC_LIBRARY_VEC "NOTFOUND" CACHE INTERNAL "Cleared" FORCE) # There is no libpetscvec petsc_find_library (SINGLE petsc) + # Debian 9/Ubuntu 16.04 uses _real and _complex extensions when using libraries in /usr/lib/petsc. + if (NOT PETSC_LIBRARY_SINGLE) + petsc_find_library (SINGLE petsc_real) + endif() + if (NOT PETSC_LIBRARY_SINGLE) + petsc_find_library (SINGLE petsc_complex) + endif() foreach (pkg SYS VEC MAT DM KSP SNES TS ALL) set (PETSC_LIBRARIES_${pkg} "${PETSC_LIBRARY_SINGLE}") endforeach () @@ -198,36 +257,31 @@ show : include(Check${PETSC_LANGUAGE_BINDINGS}SourceRuns) macro (PETSC_TEST_RUNS includes libraries runs) - if(${PETSC_LANGUAGE_BINDINGS} STREQUAL "C") - set(_PETSC_ERR_FUNC "CHKERRQ(ierr)") - elseif(${PETSC_LANGUAGE_BINDINGS} STREQUAL "CXX") - set(_PETSC_ERR_FUNC "CHKERRXX(ierr)") - endif() if (PETSC_VERSION VERSION_GREATER 3.1) set (_PETSC_TSDestroy "TSDestroy(&ts)") else () set (_PETSC_TSDestroy "TSDestroy(ts)") endif () - + set(_PETSC_TEST_SOURCE " static const char help[] = \"PETSc test program.\"; #include int main(int argc,char *argv[]) { -PetscErrorCode ierr; -TS ts; + PetscErrorCode ierr; + TS ts; -ierr = PetscInitialize(&argc,&argv,0,help);${_PETSC_ERR_FUNC}; -ierr = TSCreate(PETSC_COMM_WORLD,&ts);${_PETSC_ERR_FUNC}; -ierr = TSSetFromOptions(ts);${_PETSC_ERR_FUNC}; -ierr = ${_PETSC_TSDestroy};${_PETSC_ERR_FUNC}; -ierr = PetscFinalize();${_PETSC_ERR_FUNC}; -return 0; + ierr = PetscInitialize(&argc,&argv,0,help);CHKERRQ(ierr); + ierr = TSCreate(PETSC_COMM_WORLD,&ts);CHKERRQ(ierr); + ierr = TSSetFromOptions(ts);CHKERRQ(ierr); + ierr = ${_PETSC_TSDestroy};CHKERRQ(ierr); + ierr = PetscFinalize();CHKERRQ(ierr); + return 0; } ") multipass_source_runs ("${includes}" "${libraries}" "${_PETSC_TEST_SOURCE}" ${runs} "${PETSC_LANGUAGE_BINDINGS}") if (${${runs}}) set (PETSC_EXECUTABLE_RUNS "YES" CACHE BOOL -"Can the system successfully run a PETSc executable? This variable can be manually set to \"YES\" to force CMake to accept a given PETSc configuration, but this will almost always result in a broken build. If you change PETSC_DIR, PETSC_ARCH, or PETSC_CURRENT you would have to reset this variable." FORCE) + "Can the system successfully run a PETSc executable? This variable can be manually set to \"YES\" to force CMake to accept a given PETSc configuration, but this will almost always result in a broken build. If you change PETSC_DIR, PETSC_ARCH, or PETSC_CURRENT you would have to reset this variable." FORCE) endif (${${runs}}) endmacro (PETSC_TEST_RUNS) @@ -239,31 +293,31 @@ return 0; petsc_test_runs ("${petsc_includes_minimal}" "${PETSC_LIBRARIES_TS}" petsc_works_minimal) if (petsc_works_minimal) - message (STATUS "Minimal PETSc includes and libraries work. This probably means we are building with shared libs.") + message (STATUS "Minimal PETSc includes and libraries work. This probably means we are building with shared libs.") set (petsc_includes_needed "${petsc_includes_minimal}") - else (petsc_works_minimal) # Minimal includes fail, see if just adding full includes fixes it + else (petsc_works_minimal) # Minimal includes fail, see if just adding full includes fixes it petsc_test_runs ("${petsc_includes_all}" "${PETSC_LIBRARIES_TS}" petsc_works_allincludes) if (petsc_works_allincludes) # It does, we just need all the includes ( - message (STATUS "PETSc requires extra include paths, but links correctly with only interface libraries. This is an unexpected configuration (but it seems to work fine).") + message (STATUS "PETSc requires extra include paths, but links correctly with only interface libraries. This is an unexpected configuration (but it seems to work fine).") set (petsc_includes_needed ${petsc_includes_all}) else (petsc_works_allincludes) # We are going to need to link the external libs explicitly resolve_libraries (petsc_libraries_external "${petsc_libs_external}") foreach (pkg SYS VEC MAT DM KSP SNES TS ALL) -list (APPEND PETSC_LIBRARIES_${pkg} ${petsc_libraries_external}) + list (APPEND PETSC_LIBRARIES_${pkg} ${petsc_libraries_external}) endforeach (pkg) petsc_test_runs ("${petsc_includes_minimal}" "${PETSC_LIBRARIES_TS}" petsc_works_alllibraries) if (petsc_works_alllibraries) -message (STATUS "PETSc only need minimal includes, but requires explicit linking to all dependencies. This is expected when PETSc is built with static libraries.") -set (petsc_includes_needed ${petsc_includes_minimal}) + message (STATUS "PETSc only need minimal includes, but requires explicit linking to all dependencies. This is expected when PETSc is built with static libraries.") + set (petsc_includes_needed ${petsc_includes_minimal}) else (petsc_works_alllibraries) -# It looks like we really need everything, should have listened to Matt -set (petsc_includes_needed ${petsc_includes_all}) -petsc_test_runs ("${petsc_includes_all}" "${PETSC_LIBRARIES_TS}" petsc_works_all) -if (petsc_works_all) # We fail anyways -message (STATUS "PETSc requires extra include paths and explicit linking to all dependencies. This probably means you have static libraries and something unexpected in PETSc headers.") -else (petsc_works_all) # We fail anyways -message (STATUS "PETSc could not be used, maybe the install is broken.") -endif (petsc_works_all) + # It looks like we really need everything, should have listened to Matt + set (petsc_includes_needed ${petsc_includes_all}) + petsc_test_runs ("${petsc_includes_all}" "${PETSC_LIBRARIES_TS}" petsc_works_all) + if (petsc_works_all) # We fail anyways + message (STATUS "PETSc requires extra include paths and explicit linking to all dependencies. This probably means you have static libraries and something unexpected in PETSc headers.") + else (petsc_works_all) # We fail anyways + message (STATUS "PETSc could not be used, maybe the install is broken.") + endif (petsc_works_all) endif (petsc_works_alllibraries) endif (petsc_works_allincludes) endif (petsc_works_minimal) @@ -279,13 +333,14 @@ endif (petsc_works_all) set (PETSC_INCLUDES ${petsc_includes_needed} CACHE STRING "PETSc include path" FORCE) set (PETSC_LIBRARIES ${PETSC_LIBRARIES_ALL} CACHE STRING "PETSc libraries" FORCE) set (PETSC_COMPILER ${petsc_cc} CACHE FILEPATH "PETSc compiler" FORCE) - # Note that we have forced values for all these choices. If you + # Note that we have forced values for all these choices. If you # change these, you are telling the system to trust you that they - # work. It is likely that you will end up with a broken build. + # work. It is likely that you will end up with a broken build. mark_as_advanced (PETSC_INCLUDES PETSC_LIBRARIES PETSC_COMPILER PETSC_DEFINITIONS PETSC_MPIEXEC PETSC_EXECUTABLE_RUNS) endif () include (FindPackageHandleStandardArgs) find_package_handle_standard_args (PETSc - "PETSc could not be found. Be sure to set PETSC_DIR and PETSC_ARCH." - PETSC_INCLUDES PETSC_LIBRARIES PETSC_EXECUTABLE_RUNS) \ No newline at end of file + REQUIRED_VARS PETSC_INCLUDES PETSC_LIBRARIES PETSC_EXECUTABLE_RUNS + VERSION_VAR PETSC_VERSION + FAIL_MESSAGE "PETSc could not be found. Be sure to set PETSC_DIR and PETSC_ARCH.") diff --git a/cmake/FindPackageMultipass.cmake b/cmake/FindPackageMultipass.cmake index 4d9ff5346..fbf06a7f0 100644 --- a/cmake/FindPackageMultipass.cmake +++ b/cmake/FindPackageMultipass.cmake @@ -1,36 +1,36 @@ # PackageMultipass - this module defines two macros # # FIND_PACKAGE_MULTIPASS (Name CURRENT -# STATES VAR0 VAR1 ... -# DEPENDENTS DEP0 DEP1 ...) +# STATES VAR0 VAR1 ... +# DEPENDENTS DEP0 DEP1 ...) # -# This function creates a cache entry _CURRENT which -# the user can set to "NO" to trigger a reconfiguration of the package. -# The first time this function is called, the values of -# _VAR0, ... are saved. If _CURRENT -# is false or if any STATE has changed since the last time -# FIND_PACKAGE_MULTIPASS() was called, then CURRENT will be set to "NO", -# otherwise CURRENT will be "YES". IF not CURRENT, then -# _DEP0, ... will be FORCED to NOTFOUND. -# Example: -# find_path (FOO_DIR include/foo.h) -# FIND_PACKAGE_MULTIPASS (Foo foo_current -# STATES DIR -# DEPENDENTS INCLUDES LIBRARIES) -# if (NOT foo_current) -# # Make temporary files, run programs, etc, to determine FOO_INCLUDES and FOO_LIBRARIES -# endif (NOT foo_current) +# This function creates a cache entry _CURRENT which +# the user can set to "NO" to trigger a reconfiguration of the package. +# The first time this function is called, the values of +# _VAR0, ... are saved. If _CURRENT +# is false or if any STATE has changed since the last time +# FIND_PACKAGE_MULTIPASS() was called, then CURRENT will be set to "NO", +# otherwise CURRENT will be "YES". IF not CURRENT, then +# _DEP0, ... will be FORCED to NOTFOUND. +# Example: +# find_path (FOO_DIR include/foo.h) +# FIND_PACKAGE_MULTIPASS (Foo foo_current +# STATES DIR +# DEPENDENTS INCLUDES LIBRARIES) +# if (NOT foo_current) +# # Make temporary files, run programs, etc, to determine FOO_INCLUDES and FOO_LIBRARIES +# endif (NOT foo_current) # # MULTIPASS_SOURCE_RUNS (Name INCLUDES LIBRARIES SOURCE RUNS LANGUAGE) -# Always runs the given test, use this when you need to re-run tests -# because parent variables have made old cache entries stale. The LANGUAGE -# variable is either C or CXX indicating which compiler the test should -# use. +# Always runs the given test, use this when you need to re-run tests +# because parent variables have made old cache entries stale. The LANGUAGE +# variable is either C or CXX indicating which compiler the test should +# use. # MULTIPASS_C_SOURCE_RUNS (Name INCLUDES LIBRARIES SOURCE RUNS) -# DEPRECATED! This is only included for backwards compatability. Use -# the more general MULTIPASS_SOURCE_RUNS instead. -# Always runs the given test, use this when you need to re-run tests -# because parent variables have made old cache entries stale. +# DEPRECATED! This is only included for backwards compatability. Use +# the more general MULTIPASS_SOURCE_RUNS instead. +# Always runs the given test, use this when you need to re-run tests +# because parent variables have made old cache entries stale. macro (FIND_PACKAGE_MULTIPASS _name _current) string (TOUPPER ${_name} _NAME) @@ -46,7 +46,7 @@ macro (FIND_PACKAGE_MULTIPASS _name _current) # The name of the stored value for the given state set (_stored_var PACKAGE_MULTIPASS_${_NAME}_${_state}) if (NOT "${${_stored_var}}" STREQUAL "${${_NAME}_${_state}}") -set (_states_current "NO") + set (_states_current "NO") endif (NOT "${${_stored_var}}" STREQUAL "${${_NAME}_${_state}}") set (${_stored_var} "${${_NAME}_${_state}}" CACHE INTERNAL "Stored state for ${_name}." FORCE) list (REMOVE_AT _args 0) @@ -56,7 +56,7 @@ set (_states_current "NO") set (_stored ${_NAME}_CURRENT) if (NOT ${_stored}) - set (${_stored} "YES" CACHE BOOL "Is the configuration for ${_name} current? Set to \"NO\" to reconfigure." FORCE) + set (${_stored} "YES" CACHE BOOL "Is the configuration for ${_name} current? Set to \"NO\" to reconfigure." FORCE) set (_states_current "NO") endif (NOT ${_stored}) @@ -68,7 +68,7 @@ set (_states_current "NO") if (_cmd STREQUAL "DEPENDENTS") list (REMOVE_AT _args 0) foreach (dep ${_args}) -set (${_NAME}_${dep} "NOTFOUND" CACHE INTERNAL "Cleared" FORCE) + set (${_NAME}_${dep} "NOTFOUND" CACHE INTERNAL "Cleared" FORCE) endforeach (dep) endif (_cmd STREQUAL "DEPENDENTS") set (${_NAME}_FOUND "NOTFOUND" CACHE INTERNAL "Cleared" FORCE) @@ -79,10 +79,10 @@ endmacro (FIND_PACKAGE_MULTIPASS) macro (MULTIPASS_SOURCE_RUNS includes libraries source runs language) include (Check${language}SourceRuns) - # This is a ridiculous hack. CHECK_${language}_SOURCE_* thinks that if the + # This is a ridiculous hack. CHECK_${language}_SOURCE_* thinks that if the # *name* of the return variable doesn't change, then the test does - # not need to be re-run. We keep an internal count which we - # increment to guarantee that every test name is unique. If we've + # not need to be re-run. We keep an internal count which we + # increment to guarantee that every test name is unique. If we've # gotten here, then the configuration has changed enough that the # test *needs* to be rerun. if (NOT MULTIPASS_TEST_COUNT) @@ -103,4 +103,4 @@ endmacro (MULTIPASS_SOURCE_RUNS) macro (MULTIPASS_C_SOURCE_RUNS includes libraries source runs) multipass_source_runs("${includes}" "${libraries}" "${source}" ${runs} "C") -endmacro (MULTIPASS_C_SOURCE_RUNS) \ No newline at end of file +endmacro (MULTIPASS_C_SOURCE_RUNS) diff --git a/cmake/ResolveCompilerPaths.cmake b/cmake/ResolveCompilerPaths.cmake index b3a92f1a3..54787fa38 100644 --- a/cmake/ResolveCompilerPaths.cmake +++ b/cmake/ResolveCompilerPaths.cmake @@ -1,4 +1,4 @@ -#ResolveCompilerPaths - this module defines two macros +# ResolveCompilerPaths - this module defines two macros # # RESOLVE_LIBRARIES (XXX_LIBRARIES LINK_LINE) # This macro is intended to be used by FindXXX.cmake modules. @@ -38,23 +38,34 @@ # # assuming both directories exist. # Note: as currently implemented, the -I/string will be picked up mistakenly (cry, cry) +include (CorrectWindowsPaths) macro (RESOLVE_LIBRARIES LIBS LINK_LINE) - string (REGEX MATCHALL "((-L|-l|-Wl)([^\" ]+|\"[^\"]+\")|/[^\" ]+(a|so|dll))" _all_tokens "${LINK_LINE}") - set (_libs_found) - set (_directory_list) + string (REGEX MATCHALL "((-L|-l|-Wl)([^\" ]+|\"[^\"]+\")|[^\" ]+\\.(a|so|dll|lib))" _all_tokens "${LINK_LINE}") + set (_libs_found "") + set (_directory_list "") foreach (token ${_all_tokens}) if (token MATCHES "-L([^\" ]+|\"[^\"]+\")") # If it's a library path, add it to the list string (REGEX REPLACE "^-L" "" token ${token}) string (REGEX REPLACE "//" "/" token ${token}) + convert_cygwin_path(token) list (APPEND _directory_list ${token}) - elseif (token MATCHES "^(-l([^\" ]+|\"[^\"]+\")|/[^\" ]+(a|so|dll))") + elseif (token MATCHES "^(-l([^\" ]+|\"[^\"]+\")|[^\" ]+\\.(a|so|dll|lib))") # It's a library, resolve the path by looking in the list and then (by default) in system directories - string (REGEX REPLACE "^-l" "" token ${token}) - set (_root) - if (token MATCHES "^/") # We have an absolute path, add root to the search path - set (_root "/") + if (WIN32) #windows expects "libfoo", linux expects "foo" + string (REGEX REPLACE "^-l" "lib" token ${token}) + else (WIN32) + string (REGEX REPLACE "^-l" "" token ${token}) + endif (WIN32) + set (_root "") + if (token MATCHES "^/") # We have an absolute path + #separate into a path and a library name: + string (REGEX MATCH "[^/]*\\.(a|so|dll|lib)$" libname ${token}) + string (REGEX MATCH ".*[^${libname}$]" libpath ${token}) + convert_cygwin_path(libpath) + set (_directory_list ${_directory_list} ${libpath}) + set (token ${libname}) endif (token MATCHES "^/") set (_lib "NOTFOUND" CACHE FILEPATH "Cleared" FORCE) find_library (_lib ${token} HINTS ${_directory_list} ${_root}) @@ -78,10 +89,11 @@ endmacro (RESOLVE_LIBRARIES) macro (RESOLVE_INCLUDES INCS COMPILE_LINE) string (REGEX MATCHALL "-I([^\" ]+|\"[^\"]+\")" _all_tokens "${COMPILE_LINE}") - set (_incs_found) + set (_incs_found "") foreach (token ${_all_tokens}) string (REGEX REPLACE "^-I" "" token ${token}) string (REGEX REPLACE "//" "/" token ${token}) + convert_cygwin_path(token) if (EXISTS ${token}) list (APPEND _incs_found ${token}) else (EXISTS ${token}) @@ -90,4 +102,4 @@ macro (RESOLVE_INCLUDES INCS COMPILE_LINE) endforeach (token) list (REMOVE_DUPLICATES _incs_found) set (${INCS} "${_incs_found}") -endmacro (RESOLVE_INCLUDES) \ No newline at end of file +endmacro (RESOLVE_INCLUDES) -- GitLab From 62dd27b5131147c3cb1e55b75eb4a27059acd555 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Klinkovsk=C3=BD?= Date: Sun, 21 Nov 2021 12:26:40 +0100 Subject: [PATCH 8/8] Refactored test for PETSc using the FindPETSc module --- CMakeLists.txt | 31 ------------------------------ src/Benchmarks/SpMV/CMakeLists.txt | 18 +++++++++++++++-- 2 files changed, 16 insertions(+), 33 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index d145cd1cd..d74bbb48f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -314,35 +314,6 @@ if( ${WITH_GMP} ) endif() endif() -#### -# Test for PETSc -if( BUILD_MPI ) - FIND_PATH( PETSC_INCLUDE_DIR petsc.h - /usr/include/petsc - ${PETSC_DIR}/${PETSC_ARCH}/include - ${PETSC_DIR}/include - DOC "PETSC headers." - ) - if( ${PETSC_INCLUDE_DIR} STREQUAL "PETSC_INCLUDE_DIR-NOTFOUND" ) - message( "PETSC not found." ) - else() - message( "PETSC headers found -- ${PETSC_INCLUDE_DIR}" ) - FIND_LIBRARY(PETSC_LIBRARY petsc - ${PETSC_INCLUDE_DIR}/../lib - /usr/local/lib - /usr/lib) - if( PETSC_LIBRARY ) - #string( REPLACE ";" " " MPI_LIBRARIES "${MPI_CXX_LIBRARIES}" ) - #set( PETSC_LIBRARY "${MPI_LIBRARIES} ${PETSC_LIBRARY}") - message( "PETSC library found -- ${PETSC_LIBRARY}") - #list( GET MPI_CXX_INCLUDE_PATH 0 MPI_CXX_PATH ) - #set(PETSC_CXX_FLAGS "-DHAVE_PETSC -I${PETSC_INCLUDE_DIR} -DHAVE_MPI -I${MPI_CXX_PATH}") - set(PETSC_CXX_FLAGS -DHAVE_PETSC -I${PETSC_INCLUDE_DIR}) - set(PETSC_LINKER_FLAGS ${PETSC_LIBRARY}) - endif() - endif() -endif() - # configure build paths set( CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/bin ) set( CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib ) @@ -422,8 +393,6 @@ message( " CMAKE_SHARED_LINKER_FLAGS_RELEASE = ${CMAKE_SHARED_LINKER_FLAGS_REL message( " CUDA_NVCC_FLAGS = ${CUDA_NVCC_FLAGS}" ) message( " CUDA_SAMPLES_FLAGS = ${CUDA_SAMPLES_FLAGS}" ) message( " GMP_LIBRARIES = ${GMP_LIBRARIES}" ) -message( " PETSC_CXX_FLAGS = ${PETSC_CXX_FLAGS}" ) -message( " PETSC_LINKER_FLAGS = ${PETSC_LINKER_FLAGS}" ) if( MPI_CXX_FOUND AND ${WITH_MPI} ) message( " MPI_CXX_COMPILE_OPTIONS = ${MPI_CXX_COMPILE_OPTIONS}" ) diff --git a/src/Benchmarks/SpMV/CMakeLists.txt b/src/Benchmarks/SpMV/CMakeLists.txt index 499808853..75f0173e8 100644 --- a/src/Benchmarks/SpMV/CMakeLists.txt +++ b/src/Benchmarks/SpMV/CMakeLists.txt @@ -8,18 +8,32 @@ # #include( cmake/BuildCSR5.cmake ) +# PETSc requires MPI +if( BUILD_MPI ) + find_package( PETSc COMPONENTS CXX ) +endif() + +if( PETSC_FOUND ) + message( "PETSC library found: ${PETSC_VERSION}") + set( PETSC_CXX_FLAGS -DHAVE_PETSC ${PETSC_DEFINITIONS} ) + message( " PETSC_INCLUDES = ${PETSC_INCLUDES}" ) + message( " PETSC_CXX_FLAGS = ${PETSC_CXX_FLAGS}" ) + message( " PETSC_LIBRARIES = ${PETSC_LIBRARIES}" ) +endif() + if( BUILD_CUDA ) file( GLOB EXPLICIT_TEMPLATES spmv.templates/*.cu ) cuda_include_directories( ${CXX_BENCHMARKS_INCLUDE_DIRS} ) cuda_add_executable( tnl-benchmark-spmv tnl-benchmark-spmv.cu ${EXPLICIT_TEMPLATES} ReferenceFormats/LightSpMV-1.0/SpMV.cu ReferenceFormats/LightSpMV-1.0/SpMVCSR.cu OPTIONS ${CXX_BENCHMARKS_FLAGS} ${PETSC_CXX_FLAGS} ) - target_link_libraries( tnl-benchmark-spmv ${CUDA_cusparse_LIBRARY} ${CUDA_cudadevrt_LIBRARY} ${PETSC_LINKER_FLAGS}) + target_link_libraries( tnl-benchmark-spmv ${CUDA_cusparse_LIBRARY} ${CUDA_cudadevrt_LIBRARY} ) else() file( GLOB EXPLICIT_TEMPLATES spmv.templates/*.cpp ) add_executable( tnl-benchmark-spmv tnl-benchmark-spmv.cpp ${EXPLICIT_TEMPLATES} ) target_compile_options( tnl-benchmark-spmv PRIVATE ${CXX_BENCHMARKS_FLAGS} ${PETSC_CXX_FLAGS} ) target_include_directories( tnl-benchmark-spmv PRIVATE ${CXX_BENCHMARKS_INCLUDE_DIRS} ) - target_link_libraries( tnl-benchmark-spmv ${PETSC_LINKER_FLAGS} ) endif() +set_property( TARGET tnl-benchmark-spmv APPEND PROPERTY INCLUDE_DIRECTORIES ${PETSC_INCLUDES} ) +target_link_libraries( tnl-benchmark-spmv ${PETSC_LIBRARIES} ) install( TARGETS tnl-benchmark-spmv RUNTIME DESTINATION bin ) -- GitLab