Merge pull request #11882 from alalek:videoio_vfw_lower_priority
[platform/upstream/opencv.git] / cmake / FindCUDA.cmake
1 #.rst:
2 # FindCUDA
3 # --------
4 #
5 # Tools for building CUDA C files: libraries and build dependencies.
6 #
7 # This script locates the NVIDIA CUDA C tools.  It should work on linux,
8 # windows, and mac and should be reasonably up to date with CUDA C
9 # releases.
10 #
11 # This script makes use of the standard find_package arguments of
12 # <VERSION>, REQUIRED and QUIET.  CUDA_FOUND will report if an
13 # acceptable version of CUDA was found.
14 #
15 # The script will prompt the user to specify CUDA_TOOLKIT_ROOT_DIR if
16 # the prefix cannot be determined by the location of nvcc in the system
17 # path and REQUIRED is specified to find_package().  To use a different
18 # installed version of the toolkit set the environment variable
19 # CUDA_BIN_PATH before running cmake (e.g.
20 # CUDA_BIN_PATH=/usr/local/cuda1.0 instead of the default
21 # /usr/local/cuda) or set CUDA_TOOLKIT_ROOT_DIR after configuring.  If
22 # you change the value of CUDA_TOOLKIT_ROOT_DIR, various components that
23 # depend on the path will be relocated.
24 #
25 # It might be necessary to set CUDA_TOOLKIT_ROOT_DIR manually on certain
26 # platforms, or to use a cuda runtime not installed in the default
27 # location.  In newer versions of the toolkit the cuda library is
28 # included with the graphics driver- be sure that the driver version
29 # matches what is needed by the cuda runtime version.
30 #
31 # The following variables affect the behavior of the macros in the
32 # script (in alphebetical order).  Note that any of these flags can be
33 # changed multiple times in the same directory before calling
34 # CUDA_ADD_EXECUTABLE, CUDA_ADD_LIBRARY, CUDA_COMPILE, CUDA_COMPILE_PTX,
35 # CUDA_COMPILE_FATBIN, CUDA_COMPILE_CUBIN or CUDA_WRAP_SRCS::
36 #
37 #   CUDA_64_BIT_DEVICE_CODE (Default matches host bit size)
38 #   -- Set to ON to compile for 64 bit device code, OFF for 32 bit device code.
39 #      Note that making this different from the host code when generating object
40 #      or C files from CUDA code just won't work, because size_t gets defined by
41 #      nvcc in the generated source.  If you compile to PTX and then load the
42 #      file yourself, you can mix bit sizes between device and host.
43 #
44 #   CUDA_ATTACH_VS_BUILD_RULE_TO_CUDA_FILE (Default ON)
45 #   -- Set to ON if you want the custom build rule to be attached to the source
46 #      file in Visual Studio.  Turn OFF if you add the same cuda file to multiple
47 #      targets.
48 #
49 #      This allows the user to build the target from the CUDA file; however, bad
50 #      things can happen if the CUDA source file is added to multiple targets.
51 #      When performing parallel builds it is possible for the custom build
52 #      command to be run more than once and in parallel causing cryptic build
53 #      errors.  VS runs the rules for every source file in the target, and a
54 #      source can have only one rule no matter how many projects it is added to.
55 #      When the rule is run from multiple targets race conditions can occur on
56 #      the generated file.  Eventually everything will get built, but if the user
57 #      is unaware of this behavior, there may be confusion.  It would be nice if
58 #      this script could detect the reuse of source files across multiple targets
59 #      and turn the option off for the user, but no good solution could be found.
60 #
61 #   CUDA_BUILD_CUBIN (Default OFF)
62 #   -- Set to ON to enable and extra compilation pass with the -cubin option in
63 #      Device mode. The output is parsed and register, shared memory usage is
64 #      printed during build.
65 #
66 #   CUDA_BUILD_EMULATION (Default OFF for device mode)
67 #   -- Set to ON for Emulation mode. -D_DEVICEEMU is defined for CUDA C files
68 #      when CUDA_BUILD_EMULATION is TRUE.
69 #
70 #   CUDA_GENERATED_OUTPUT_DIR (Default CMAKE_CURRENT_BINARY_DIR)
71 #   -- Set to the path you wish to have the generated files placed.  If it is
72 #      blank output files will be placed in CMAKE_CURRENT_BINARY_DIR.
73 #      Intermediate files will always be placed in
74 #      CMAKE_CURRENT_BINARY_DIR/CMakeFiles.
75 #
76 #   CUDA_HOST_COMPILATION_CPP (Default ON)
77 #   -- Set to OFF for C compilation of host code.
78 #
79 #   CUDA_HOST_COMPILER (Default CMAKE_C_COMPILER)
80 #   -- Set the host compiler to be used by nvcc.  Ignored if -ccbin or
81 #      --compiler-bindir is already present in the CUDA_NVCC_FLAGS or
82 #      CUDA_NVCC_FLAGS_<CONFIG> variables.  For Visual Studio targets,
83 #      the host compiler is constructed with one or more visual studio macros
84 #      such as $(VCInstallDir), that expands out to the path when
85 #      the command is run from within VS.
86 #
87 #   CUDA_NVCC_FLAGS
88 #   CUDA_NVCC_FLAGS_<CONFIG>
89 #   -- Additional NVCC command line arguments.  NOTE: multiple arguments must be
90 #      semi-colon delimited (e.g. --compiler-options;-Wall)
91 #
92 #   CUDA_PROPAGATE_HOST_FLAGS (Default ON)
93 #   -- Set to ON to propagate CMAKE_{C,CXX}_FLAGS and their configuration
94 #      dependent counterparts (e.g. CMAKE_C_FLAGS_DEBUG) automatically to the
95 #      host compiler through nvcc's -Xcompiler flag.  This helps make the
96 #      generated host code match the rest of the system better.  Sometimes
97 #      certain flags give nvcc problems, and this will help you turn the flag
98 #      propagation off.  This does not affect the flags supplied directly to nvcc
99 #      via CUDA_NVCC_FLAGS or through the OPTION flags specified through
100 #      CUDA_ADD_LIBRARY, CUDA_ADD_EXECUTABLE, or CUDA_WRAP_SRCS.  Flags used for
101 #      shared library compilation are not affected by this flag.
102 #
103 #   CUDA_SEPARABLE_COMPILATION (Default OFF)
104 #   -- If set this will enable separable compilation for all CUDA runtime object
105 #      files.  If used outside of CUDA_ADD_EXECUTABLE and CUDA_ADD_LIBRARY
106 #      (e.g. calling CUDA_WRAP_SRCS directly),
107 #      CUDA_COMPUTE_SEPARABLE_COMPILATION_OBJECT_FILE_NAME and
108 #      CUDA_LINK_SEPARABLE_COMPILATION_OBJECTS should be called.
109 #
110 #   CUDA_VERBOSE_BUILD (Default OFF)
111 #   -- Set to ON to see all the commands used when building the CUDA file.  When
112 #      using a Makefile generator the value defaults to VERBOSE (run make
113 #      VERBOSE=1 to see output), although setting CUDA_VERBOSE_BUILD to ON will
114 #      always print the output.
115 #
116 # The script creates the following macros (in alphebetical order)::
117 #
118 #   CUDA_ADD_CUFFT_TO_TARGET( cuda_target )
119 #   -- Adds the cufft library to the target (can be any target).  Handles whether
120 #      you are in emulation mode or not.
121 #
122 #   CUDA_ADD_CUBLAS_TO_TARGET( cuda_target )
123 #   -- Adds the cublas library to the target (can be any target).  Handles
124 #      whether you are in emulation mode or not.
125 #
126 #   CUDA_ADD_EXECUTABLE( cuda_target file0 file1 ...
127 #                        [WIN32] [MACOSX_BUNDLE] [EXCLUDE_FROM_ALL] [OPTIONS ...] )
128 #   -- Creates an executable "cuda_target" which is made up of the files
129 #      specified.  All of the non CUDA C files are compiled using the standard
130 #      build rules specified by CMAKE and the cuda files are compiled to object
131 #      files using nvcc and the host compiler.  In addition CUDA_INCLUDE_DIRS is
132 #      added automatically to include_directories().  Some standard CMake target
133 #      calls can be used on the target after calling this macro
134 #      (e.g. set_target_properties and target_link_libraries), but setting
135 #      properties that adjust compilation flags will not affect code compiled by
136 #      nvcc.  Such flags should be modified before calling CUDA_ADD_EXECUTABLE,
137 #      CUDA_ADD_LIBRARY or CUDA_WRAP_SRCS.
138 #
139 #   CUDA_ADD_LIBRARY( cuda_target file0 file1 ...
140 #                     [STATIC | SHARED | MODULE] [EXCLUDE_FROM_ALL] [OPTIONS ...] )
141 #   -- Same as CUDA_ADD_EXECUTABLE except that a library is created.
142 #
143 #   CUDA_BUILD_CLEAN_TARGET()
144 #   -- Creates a convience target that deletes all the dependency files
145 #      generated.  You should make clean after running this target to ensure the
146 #      dependency files get regenerated.
147 #
148 #   CUDA_COMPILE( generated_files file0 file1 ... [STATIC | SHARED | MODULE]
149 #                 [OPTIONS ...] )
150 #   -- Returns a list of generated files from the input source files to be used
151 #      with ADD_LIBRARY or ADD_EXECUTABLE.
152 #
153 #   CUDA_COMPILE_PTX( generated_files file0 file1 ... [OPTIONS ...] )
154 #   -- Returns a list of PTX files generated from the input source files.
155 #
156 #   CUDA_COMPILE_FATBIN( generated_files file0 file1 ... [OPTIONS ...] )
157 #   -- Returns a list of FATBIN files generated from the input source files.
158 #
159 #   CUDA_COMPILE_CUBIN( generated_files file0 file1 ... [OPTIONS ...] )
160 #   -- Returns a list of CUBIN files generated from the input source files.
161 #
162 #   CUDA_COMPUTE_SEPARABLE_COMPILATION_OBJECT_FILE_NAME( output_file_var
163 #                                                        cuda_target
164 #                                                        object_files )
165 #   -- Compute the name of the intermediate link file used for separable
166 #      compilation.  This file name is typically passed into
167 #      CUDA_LINK_SEPARABLE_COMPILATION_OBJECTS.  output_file_var is produced
168 #      based on cuda_target the list of objects files that need separable
169 #      compilation as specified by object_files.  If the object_files list is
170 #      empty, then output_file_var will be empty.  This function is called
171 #      automatically for CUDA_ADD_LIBRARY and CUDA_ADD_EXECUTABLE.  Note that
172 #      this is a function and not a macro.
173 #
174 #   CUDA_INCLUDE_DIRECTORIES( path0 path1 ... )
175 #   -- Sets the directories that should be passed to nvcc
176 #      (e.g. nvcc -Ipath0 -Ipath1 ... ). These paths usually contain other .cu
177 #      files.
178 #
179 #
180 #
181 #   CUDA_LINK_SEPARABLE_COMPILATION_OBJECTS( output_file_var cuda_target
182 #                                            nvcc_flags object_files)
183 #
184 #   -- Generates the link object required by separable compilation from the given
185 #      object files.  This is called automatically for CUDA_ADD_EXECUTABLE and
186 #      CUDA_ADD_LIBRARY, but can be called manually when using CUDA_WRAP_SRCS
187 #      directly.  When called from CUDA_ADD_LIBRARY or CUDA_ADD_EXECUTABLE the
188 #      nvcc_flags passed in are the same as the flags passed in via the OPTIONS
189 #      argument.  The only nvcc flag added automatically is the bitness flag as
190 #      specified by CUDA_64_BIT_DEVICE_CODE.  Note that this is a function
191 #      instead of a macro.
192 #
193 #   CUDA_WRAP_SRCS ( cuda_target format generated_files file0 file1 ...
194 #                    [STATIC | SHARED | MODULE] [OPTIONS ...] )
195 #   -- This is where all the magic happens.  CUDA_ADD_EXECUTABLE,
196 #      CUDA_ADD_LIBRARY, CUDA_COMPILE, and CUDA_COMPILE_PTX all call this
197 #      function under the hood.
198 #
199 #      Given the list of files (file0 file1 ... fileN) this macro generates
200 #      custom commands that generate either PTX or linkable objects (use "PTX" or
201 #      "OBJ" for the format argument to switch).  Files that don't end with .cu
202 #      or have the HEADER_FILE_ONLY property are ignored.
203 #
204 #      The arguments passed in after OPTIONS are extra command line options to
205 #      give to nvcc.  You can also specify per configuration options by
206 #      specifying the name of the configuration followed by the options.  General
207 #      options must precede configuration specific options.  Not all
208 #      configurations need to be specified, only the ones provided will be used.
209 #
210 #         OPTIONS -DFLAG=2 "-DFLAG_OTHER=space in flag"
211 #         DEBUG -g
212 #         RELEASE --use_fast_math
213 #         RELWITHDEBINFO --use_fast_math;-g
214 #         MINSIZEREL --use_fast_math
215 #
216 #      For certain configurations (namely VS generating object files with
217 #      CUDA_ATTACH_VS_BUILD_RULE_TO_CUDA_FILE set to ON), no generated file will
218 #      be produced for the given cuda file.  This is because when you add the
219 #      cuda file to Visual Studio it knows that this file produces an object file
220 #      and will link in the resulting object file automatically.
221 #
222 #      This script will also generate a separate cmake script that is used at
223 #      build time to invoke nvcc.  This is for several reasons.
224 #
225 #        1. nvcc can return negative numbers as return values which confuses
226 #        Visual Studio into thinking that the command succeeded.  The script now
227 #        checks the error codes and produces errors when there was a problem.
228 #
229 #        2. nvcc has been known to not delete incomplete results when it
230 #        encounters problems.  This confuses build systems into thinking the
231 #        target was generated when in fact an unusable file exists.  The script
232 #        now deletes the output files if there was an error.
233 #
234 #        3. By putting all the options that affect the build into a file and then
235 #        make the build rule dependent on the file, the output files will be
236 #        regenerated when the options change.
237 #
238 #      This script also looks at optional arguments STATIC, SHARED, or MODULE to
239 #      determine when to target the object compilation for a shared library.
240 #      BUILD_SHARED_LIBS is ignored in CUDA_WRAP_SRCS, but it is respected in
241 #      CUDA_ADD_LIBRARY.  On some systems special flags are added for building
242 #      objects intended for shared libraries.  A preprocessor macro,
243 #      <target_name>_EXPORTS is defined when a shared library compilation is
244 #      detected.
245 #
246 #      Flags passed into add_definitions with -D or /D are passed along to nvcc.
247 #
248 #
249 #
250 # The script defines the following variables::
251 #
252 #   CUDA_VERSION_MAJOR    -- The major version of cuda as reported by nvcc.
253 #   CUDA_VERSION_MINOR    -- The minor version.
254 #   CUDA_VERSION
255 #   CUDA_VERSION_STRING   -- CUDA_VERSION_MAJOR.CUDA_VERSION_MINOR
256 #
257 #   CUDA_TOOLKIT_ROOT_DIR -- Path to the CUDA Toolkit (defined if not set).
258 #   CUDA_SDK_ROOT_DIR     -- Path to the CUDA SDK.  Use this to find files in the
259 #                            SDK.  This script will not directly support finding
260 #                            specific libraries or headers, as that isn't
261 #                            supported by NVIDIA.  If you want to change
262 #                            libraries when the path changes see the
263 #                            FindCUDA.cmake script for an example of how to clear
264 #                            these variables.  There are also examples of how to
265 #                            use the CUDA_SDK_ROOT_DIR to locate headers or
266 #                            libraries, if you so choose (at your own risk).
267 #   CUDA_INCLUDE_DIRS     -- Include directory for cuda headers.  Added automatically
268 #                            for CUDA_ADD_EXECUTABLE and CUDA_ADD_LIBRARY.
269 #   CUDA_LIBRARIES        -- Cuda RT library.
270 #   CUDA_CUFFT_LIBRARIES  -- Device or emulation library for the Cuda FFT
271 #                            implementation (alternative to:
272 #                            CUDA_ADD_CUFFT_TO_TARGET macro)
273 #   CUDA_CUBLAS_LIBRARIES -- Device or emulation library for the Cuda BLAS
274 #                            implementation (alternative to:
275 #                            CUDA_ADD_CUBLAS_TO_TARGET macro).
276 #   CUDA_cupti_LIBRARY    -- CUDA Profiling Tools Interface library.
277 #                            Only available for CUDA version 4.0+.
278 #   CUDA_curand_LIBRARY   -- CUDA Random Number Generation library.
279 #                            Only available for CUDA version 3.2+.
280 #   CUDA_cusparse_LIBRARY -- CUDA Sparse Matrix library.
281 #                            Only available for CUDA version 3.2+.
282 #   CUDA_npp_LIBRARY      -- NVIDIA Performance Primitives lib.
283 #                            Only available for CUDA version 4.0+.
284 #   CUDA_nppc_LIBRARY     -- NVIDIA Performance Primitives lib (core).
285 #                            Only available for CUDA version 5.5+.
286 #   CUDA_nppi_LIBRARY     -- NVIDIA Performance Primitives lib (image processing).
287 #                            Only available for CUDA version 5.5+.
288 #   CUDA_npps_LIBRARY     -- NVIDIA Performance Primitives lib (signal processing).
289 #                            Only available for CUDA version 5.5+.
290 #   CUDA_nvcuvenc_LIBRARY -- CUDA Video Encoder library.
291 #                            Only available for CUDA version 3.2+.
292 #                            Windows only.
293 #   CUDA_nvcuvid_LIBRARY  -- CUDA Video Decoder library.
294 #                            Only available for CUDA version 3.2+.
295 #                            Windows only.
296 #
297
298 #   James Bigler, NVIDIA Corp (nvidia.com - jbigler)
299 #   Abe Stephens, SCI Institute -- http://www.sci.utah.edu/~abe/FindCuda.html
300 #
301 #   Copyright (c) 2008 - 2009 NVIDIA Corporation.  All rights reserved.
302 #
303 #   Copyright (c) 2007-2009
304 #   Scientific Computing and Imaging Institute, University of Utah
305 #
306 #   This code is licensed under the MIT License.  See the FindCUDA.cmake script
307 #   for the text of the license.
308
309 # The MIT License
310 #
311 # License for the specific language governing rights and limitations under
312 # Permission is hereby granted, free of charge, to any person obtaining a
313 # copy of this software and associated documentation files (the "Software"),
314 # to deal in the Software without restriction, including without limitation
315 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
316 # and/or sell copies of the Software, and to permit persons to whom the
317 # Software is furnished to do so, subject to the following conditions:
318 #
319 # The above copyright notice and this permission notice shall be included
320 # in all copies or substantial portions of the Software.
321 #
322 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
323 # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
324 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
325 # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
326 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
327 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
328 # DEALINGS IN THE SOFTWARE.
329 #
330 ###############################################################################
331
332 # FindCUDA.cmake
333
334 # This macro helps us find the location of helper files we will need the full path to
335 macro(CUDA_FIND_HELPER_FILE _name _extension)
336   set(_full_name "${_name}.${_extension}")
337   # CMAKE_CURRENT_LIST_FILE contains the full path to the file currently being
338   # processed.  Using this variable, we can pull out the current path, and
339   # provide a way to get access to the other files we need local to here.
340   get_filename_component(CMAKE_CURRENT_LIST_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH)
341   set(CUDA_${_name} "${CMAKE_CURRENT_LIST_DIR}/FindCUDA/${_full_name}")
342   if(NOT EXISTS "${CUDA_${_name}}")
343     set(error_message "${_full_name} not found in ${CMAKE_CURRENT_LIST_DIR}/FindCUDA")
344     if(CUDA_FIND_REQUIRED)
345       message(FATAL_ERROR "${error_message}")
346     else()
347       if(NOT CUDA_FIND_QUIETLY)
348         message(STATUS "${error_message}")
349       endif()
350     endif()
351   endif()
352   # Set this variable as internal, so the user isn't bugged with it.
353   set(CUDA_${_name} ${CUDA_${_name}} CACHE INTERNAL "Location of ${_full_name}" FORCE)
354 endmacro()
355
356 #####################################################################
357 ## CUDA_INCLUDE_NVCC_DEPENDENCIES
358 ##
359
360 # So we want to try and include the dependency file if it exists.  If
361 # it doesn't exist then we need to create an empty one, so we can
362 # include it.
363
364 # If it does exist, then we need to check to see if all the files it
365 # depends on exist.  If they don't then we should clear the dependency
366 # file and regenerate it later.  This covers the case where a header
367 # file has disappeared or moved.
368
369 macro(CUDA_INCLUDE_NVCC_DEPENDENCIES dependency_file)
370   set(CUDA_NVCC_DEPEND)
371   set(CUDA_NVCC_DEPEND_REGENERATE FALSE)
372
373
374   # Include the dependency file.  Create it first if it doesn't exist .  The
375   # INCLUDE puts a dependency that will force CMake to rerun and bring in the
376   # new info when it changes.  DO NOT REMOVE THIS (as I did and spent a few
377   # hours figuring out why it didn't work.
378   if(NOT EXISTS ${dependency_file})
379     file(WRITE ${dependency_file} "#FindCUDA.cmake generated file.  Do not edit.\n")
380   endif()
381   # Always include this file to force CMake to run again next
382   # invocation and rebuild the dependencies.
383   #message("including dependency_file = ${dependency_file}")
384   include(${dependency_file})
385
386   # Now we need to verify the existence of all the included files
387   # here.  If they aren't there we need to just blank this variable and
388   # make the file regenerate again.
389 #   if(DEFINED CUDA_NVCC_DEPEND)
390 #     message("CUDA_NVCC_DEPEND set")
391 #   else()
392 #     message("CUDA_NVCC_DEPEND NOT set")
393 #   endif()
394   if(CUDA_NVCC_DEPEND)
395     #message("CUDA_NVCC_DEPEND found")
396     foreach(f ${CUDA_NVCC_DEPEND})
397       # message("searching for ${f}")
398       if(NOT EXISTS ${f})
399         #message("file ${f} not found")
400         set(CUDA_NVCC_DEPEND_REGENERATE TRUE)
401       endif()
402     endforeach()
403   else()
404     #message("CUDA_NVCC_DEPEND false")
405     # No dependencies, so regenerate the file.
406     set(CUDA_NVCC_DEPEND_REGENERATE TRUE)
407   endif()
408
409   #message("CUDA_NVCC_DEPEND_REGENERATE = ${CUDA_NVCC_DEPEND_REGENERATE}")
410   # No incoming dependencies, so we need to generate them.  Make the
411   # output depend on the dependency file itself, which should cause the
412   # rule to re-run.
413   if(CUDA_NVCC_DEPEND_REGENERATE)
414     set(CUDA_NVCC_DEPEND ${dependency_file})
415     #message("Generating an empty dependency_file: ${dependency_file}")
416     file(WRITE ${dependency_file} "#FindCUDA.cmake generated file.  Do not edit.\n")
417   endif()
418
419 endmacro()
420
421 ###############################################################################
422 ###############################################################################
423 # Setup variables' defaults
424 ###############################################################################
425 ###############################################################################
426
427 # Allow the user to specify if the device code is supposed to be 32 or 64 bit.
428 if(CMAKE_SIZEOF_VOID_P EQUAL 8)
429   set(CUDA_64_BIT_DEVICE_CODE_DEFAULT ON)
430 else()
431   set(CUDA_64_BIT_DEVICE_CODE_DEFAULT OFF)
432 endif()
433 option(CUDA_64_BIT_DEVICE_CODE "Compile device code in 64 bit mode" ${CUDA_64_BIT_DEVICE_CODE_DEFAULT})
434
435 # Attach the build rule to the source file in VS.  This option
436 option(CUDA_ATTACH_VS_BUILD_RULE_TO_CUDA_FILE "Attach the build rule to the CUDA source file.  Enable only when the CUDA source file is added to at most one target." ON)
437
438 # Prints out extra information about the cuda file during compilation
439 option(CUDA_BUILD_CUBIN "Generate and parse .cubin files in Device mode." OFF)
440
441 # Set whether we are using emulation or device mode.
442 option(CUDA_BUILD_EMULATION "Build in Emulation mode" OFF)
443
444 # Where to put the generated output.
445 set(CUDA_GENERATED_OUTPUT_DIR "" CACHE PATH "Directory to put all the output files.  If blank it will default to the CMAKE_CURRENT_BINARY_DIR")
446
447 # Parse HOST_COMPILATION mode.
448 option(CUDA_HOST_COMPILATION_CPP "Generated file extension" ON)
449
450 # Extra user settable flags
451 set(CUDA_NVCC_FLAGS "" CACHE STRING "Semi-colon delimit multiple arguments.")
452
453 if(CMAKE_GENERATOR MATCHES "Visual Studio")
454   set(_CUDA_MSVC_HOST_COMPILER "$(VCInstallDir)Tools/MSVC/$(VCToolsVersion)/bin/Host$(Platform)/$(PlatformTarget)")
455   if(MSVC_VERSION LESS 1910)
456    set(_CUDA_MSVC_HOST_COMPILER "$(VCInstallDir)bin")
457   endif()
458
459   set(CUDA_HOST_COMPILER "${_CUDA_MSVC_HOST_COMPILER}" CACHE FILEPATH "Host side compiler used by NVCC")
460
461 else()
462   # Using cc which is symlink to clang may let NVCC think it is GCC and issue
463   # unhandled -dumpspecs option to clang. Also in case neither
464   # CMAKE_C_COMPILER is defined (project does not use C language) nor
465   # CUDA_HOST_COMPILER is specified manually we should skip -ccbin and let
466   # nvcc use its own default C compiler.
467   if(DEFINED CMAKE_C_COMPILER AND NOT DEFINED CUDA_HOST_COMPILER)
468     get_filename_component(c_compiler_realpath "${CMAKE_C_COMPILER}" REALPATH)
469   else()
470     set(c_compiler_realpath "")
471   endif()
472   set(CUDA_HOST_COMPILER "${c_compiler_realpath}" CACHE FILEPATH "Host side compiler used by NVCC")
473 endif()
474
475 # Propagate the host flags to the host compiler via -Xcompiler
476 option(CUDA_PROPAGATE_HOST_FLAGS "Propage C/CXX_FLAGS and friends to the host compiler via -Xcompile" ON)
477
478 # Enable CUDA_SEPARABLE_COMPILATION
479 option(CUDA_SEPARABLE_COMPILATION "Compile CUDA objects with separable compilation enabled.  Requires CUDA 5.0+" OFF)
480
481 # Specifies whether the commands used when compiling the .cu file will be printed out.
482 option(CUDA_VERBOSE_BUILD "Print out the commands run while compiling the CUDA source file.  With the Makefile generator this defaults to VERBOSE variable specified on the command line, but can be forced on with this option." OFF)
483
484 mark_as_advanced(
485   CUDA_64_BIT_DEVICE_CODE
486   CUDA_ATTACH_VS_BUILD_RULE_TO_CUDA_FILE
487   CUDA_GENERATED_OUTPUT_DIR
488   CUDA_HOST_COMPILATION_CPP
489   CUDA_NVCC_FLAGS
490   CUDA_PROPAGATE_HOST_FLAGS
491   )
492
493 # Makefile and similar generators don't define CMAKE_CONFIGURATION_TYPES, so we
494 # need to add another entry for the CMAKE_BUILD_TYPE.  We also need to add the
495 # standerd set of 4 build types (Debug, MinSizeRel, Release, and RelWithDebInfo)
496 # for completeness.  We need run this loop in order to accommodate the addition
497 # of extra configuration types.  Duplicate entries will be removed by
498 # REMOVE_DUPLICATES.
499 set(CUDA_configuration_types ${CMAKE_CONFIGURATION_TYPES} ${CMAKE_BUILD_TYPE} Debug MinSizeRel Release RelWithDebInfo)
500 list(REMOVE_DUPLICATES CUDA_configuration_types)
501 foreach(config ${CUDA_configuration_types})
502     string(TOUPPER ${config} config_upper)
503     set(CUDA_NVCC_FLAGS_${config_upper} "" CACHE STRING "Semi-colon delimit multiple arguments.")
504     mark_as_advanced(CUDA_NVCC_FLAGS_${config_upper})
505 endforeach()
506
507 ###############################################################################
508 ###############################################################################
509 # Locate CUDA, Set Build Type, etc.
510 ###############################################################################
511 ###############################################################################
512
513 macro(cuda_unset_include_and_libraries)
514   unset(CUDA_TOOLKIT_INCLUDE CACHE)
515   unset(CUDA_CUDART_LIBRARY CACHE)
516   unset(CUDA_CUDA_LIBRARY CACHE)
517   # Make sure you run this before you unset CUDA_VERSION.
518   if(CUDA_VERSION VERSION_EQUAL "3.0")
519     # This only existed in the 3.0 version of the CUDA toolkit
520     unset(CUDA_CUDARTEMU_LIBRARY CACHE)
521   endif()
522   unset(CUDA_cupti_LIBRARY CACHE)
523   unset(CUDA_cublas_LIBRARY CACHE)
524   unset(CUDA_cublasemu_LIBRARY CACHE)
525   unset(CUDA_cufft_LIBRARY CACHE)
526   unset(CUDA_cufftemu_LIBRARY CACHE)
527   unset(CUDA_curand_LIBRARY CACHE)
528   unset(CUDA_cusparse_LIBRARY CACHE)
529   unset(CUDA_npp_LIBRARY CACHE)
530   unset(CUDA_nppc_LIBRARY CACHE)
531   unset(CUDA_nppi_LIBRARY CACHE)
532   unset(CUDA_npps_LIBRARY CACHE)
533   unset(CUDA_nvcuvenc_LIBRARY CACHE)
534   unset(CUDA_nvcuvid_LIBRARY CACHE)
535 endmacro()
536
537 # Check to see if the CUDA_TOOLKIT_ROOT_DIR and CUDA_SDK_ROOT_DIR have changed,
538 # if they have then clear the cache variables, so that will be detected again.
539 if(DEFINED CUDA_TOOLKIT_ROOT_DIR_INTERNAL AND (NOT "${CUDA_TOOLKIT_ROOT_DIR}" STREQUAL "${CUDA_TOOLKIT_ROOT_DIR_INTERNAL}"))
540   unset(CUDA_TARGET_TRIPLET CACHE)
541   unset(CUDA_TOOLKIT_TARGET_DIR CACHE)
542   unset(CUDA_NVCC_EXECUTABLE CACHE)
543   unset(CUDA_VERSION CACHE)
544   cuda_unset_include_and_libraries()
545 endif()
546
547 if(DEFINED CUDA_TARGET_TRIPLET_INTERNAL AND (NOT "${CUDA_TARGET_TRIPLET}" STREQUAL "${CUDA_TARGET_TRIPLET_INTERNAL}") OR
548    (DEFINED CUDA_TOOLKIT_TARGET_DIR  AND DEFINED CUDA_TOOLKIT_TARGET_DIR_INTERNAL AND NOT "${CUDA_TOOLKIT_TARGET_DIR}" STREQUAL "${CUDA_TOOLKIT_TARGET_DIR_INTERNAL}"))
549   cuda_unset_include_and_libraries()
550 endif()
551
552 if(NOT "${CUDA_SDK_ROOT_DIR}" STREQUAL "${CUDA_SDK_ROOT_DIR_INTERNAL}")
553   # No specific variables to catch.  Use this kind of code before calling
554   # find_package(CUDA) to clean up any variables that may depend on this path.
555
556   #   unset(MY_SPECIAL_CUDA_SDK_INCLUDE_DIR CACHE)
557   #   unset(MY_SPECIAL_CUDA_SDK_LIBRARY CACHE)
558 endif()
559
560 # Search for the cuda distribution.
561 if(NOT CUDA_TOOLKIT_ROOT_DIR)
562
563   # Search in the CUDA_BIN_PATH first.
564   find_path(CUDA_TOOLKIT_ROOT_DIR
565     NAMES nvcc nvcc.exe
566     PATHS
567       ENV CUDA_PATH
568       ENV CUDA_BIN_PATH
569     PATH_SUFFIXES bin bin64
570     DOC "Toolkit location."
571     NO_DEFAULT_PATH
572     )
573   # Now search default paths
574   find_path(CUDA_TOOLKIT_ROOT_DIR
575     NAMES nvcc nvcc.exe
576     PATHS /usr/local/bin
577           /usr/local/cuda/bin
578     DOC "Toolkit location."
579     )
580
581   if (CUDA_TOOLKIT_ROOT_DIR)
582     string(REGEX REPLACE "[/\\\\]?bin[64]*[/\\\\]?$" "" CUDA_TOOLKIT_ROOT_DIR ${CUDA_TOOLKIT_ROOT_DIR})
583     # We need to force this back into the cache.
584     set(CUDA_TOOLKIT_ROOT_DIR ${CUDA_TOOLKIT_ROOT_DIR} CACHE PATH "Toolkit location." FORCE)
585   endif()
586   if (NOT EXISTS ${CUDA_TOOLKIT_ROOT_DIR})
587     if(CUDA_FIND_REQUIRED)
588       message(FATAL_ERROR "Specify CUDA_TOOLKIT_ROOT_DIR")
589     elseif(NOT CUDA_FIND_QUIETLY)
590       message("CUDA_TOOLKIT_ROOT_DIR not found or specified")
591     endif()
592   endif ()
593 endif ()
594
595 # CUDA_NVCC_EXECUTABLE
596 find_program(CUDA_NVCC_EXECUTABLE
597   NAMES nvcc
598   PATHS "${CUDA_TOOLKIT_ROOT_DIR}"
599   ENV CUDA_PATH
600   ENV CUDA_BIN_PATH
601   PATH_SUFFIXES bin bin64
602   NO_DEFAULT_PATH
603   )
604 # Search default search paths, after we search our own set of paths.
605 find_program(CUDA_NVCC_EXECUTABLE nvcc)
606 mark_as_advanced(CUDA_NVCC_EXECUTABLE)
607
608 if(CUDA_NVCC_EXECUTABLE AND NOT CUDA_VERSION)
609   # Compute the version.
610   execute_process (COMMAND ${CUDA_NVCC_EXECUTABLE} "--version" OUTPUT_VARIABLE NVCC_OUT)
611   string(REGEX REPLACE ".*release ([0-9]+)\\.([0-9]+).*" "\\1" CUDA_VERSION_MAJOR ${NVCC_OUT})
612   string(REGEX REPLACE ".*release ([0-9]+)\\.([0-9]+).*" "\\2" CUDA_VERSION_MINOR ${NVCC_OUT})
613   set(CUDA_VERSION "${CUDA_VERSION_MAJOR}.${CUDA_VERSION_MINOR}" CACHE STRING "Version of CUDA as computed from nvcc.")
614   mark_as_advanced(CUDA_VERSION)
615 else()
616   # Need to set these based off of the cached value
617   string(REGEX REPLACE "([0-9]+)\\.([0-9]+).*" "\\1" CUDA_VERSION_MAJOR "${CUDA_VERSION}")
618   string(REGEX REPLACE "([0-9]+)\\.([0-9]+).*" "\\2" CUDA_VERSION_MINOR "${CUDA_VERSION}")
619 endif()
620
621 # Always set this convenience variable
622 set(CUDA_VERSION_STRING "${CUDA_VERSION}")
623
624 # Target CPU architecture
625 if(DEFINED CUDA_TARGET_CPU_ARCH)
626   set(_cuda_target_cpu_arch_initial "${CUDA_TARGET_CPU_ARCH}")
627 elseif(CUDA_VERSION VERSION_GREATER "5.0" AND CMAKE_CROSSCOMPILING AND CMAKE_SYSTEM_PROCESSOR MATCHES "^(arm|ARM)")
628   set(_cuda_target_cpu_arch_initial "ARM")
629 elseif(CUDA_VERSION VERSION_GREATER "6.5" AND CMAKE_CROSSCOMPILING AND CMAKE_SYSTEM_PROCESSOR MATCHES "^(aarch64|AARCH64)")
630   set(_cuda_target_cpu_arch_initial "AARCH64")
631 else()
632   set(_cuda_target_cpu_arch_initial "")
633 endif()
634 set(CUDA_TARGET_CPU_ARCH "${_cuda_target_cpu_arch_initial}" CACHE STRING "Specify the name of the class of CPU architecture for which the input files must be compiled.")
635 mark_as_advanced(CUDA_TARGET_CPU_ARCH)
636
637 # Target OS variant
638 if(DEFINED CUDA_TARGET_OS_VARIANT)
639   set(_cuda_target_os_variant_initial "${CUDA_TARGET_OS_VARIANT}")
640 else()
641   set(_cuda_target_os_variant_initial "")
642 endif()
643 set(CUDA_TARGET_OS_VARIANT "${_cuda_target_os_variant_initial}" CACHE STRING "Specify the name of the class of OS for which the input files must be compiled.")
644 mark_as_advanced(CUDA_TARGET_OS_VARIANT)
645
646 # Target triplet
647 if(DEFINED CUDA_TARGET_TRIPLET)
648   set(_cuda_target_triplet_initial "${CUDA_TARGET_TRIPLET}")
649 elseif(CUDA_VERSION VERSION_GREATER "5.0" AND CMAKE_CROSSCOMPILING AND "x${CUDA_TARGET_CPU_ARCH}" STREQUAL "xARM")
650   if("${CUDA_TARGET_OS_VARIANT}" STREQUAL "Android" AND EXISTS "${CUDA_TOOLKIT_ROOT_DIR}/targets/armv7-linux-androideabi")
651     set(_cuda_target_triplet_initial "armv7-linux-androideabi")
652   elseif(EXISTS "${CUDA_TOOLKIT_ROOT_DIR}/targets/armv7-linux-gnueabihf")
653     set(_cuda_target_triplet_initial "armv7-linux-gnueabihf")
654   endif()
655 elseif(CUDA_VERSION VERSION_GREATER "6.5" AND CMAKE_CROSSCOMPILING AND "x${CUDA_TARGET_CPU_ARCH}" STREQUAL "xAARCH64")
656   if("${CUDA_TARGET_OS_VARIANT}" STREQUAL "Android" AND EXISTS "${CUDA_TOOLKIT_ROOT_DIR}/targets/aarch64-linux-androideabi")
657     set(_cuda_target_triplet_initial "aarch64-linux-androideabi")
658   elseif(EXISTS "${CUDA_TOOLKIT_ROOT_DIR}/targets/aarch64-linux-gnueabihf")
659     set(_cuda_target_triplet_initial "aarch64-linux-gnueabihf")
660   endif()
661 endif()
662 set(CUDA_TARGET_TRIPLET "${_cuda_target_triplet_initial}" CACHE STRING "Specify the target triplet for which the input files must be compiled.")
663 file(GLOB __cuda_available_target_tiplets RELATIVE "${CUDA_TOOLKIT_ROOT_DIR}/targets" "${CUDA_TOOLKIT_ROOT_DIR}/targets/*" )
664 set_property(CACHE CUDA_TARGET_TRIPLET PROPERTY STRINGS ${__cuda_available_target_tiplets})
665 mark_as_advanced(CUDA_TARGET_TRIPLET)
666
667 # Target directory
668 if(NOT DEFINED CUDA_TOOLKIT_TARGET_DIR AND CUDA_TARGET_TRIPLET AND EXISTS "${CUDA_TOOLKIT_ROOT_DIR}/targets/${CUDA_TARGET_TRIPLET}")
669   set(CUDA_TOOLKIT_TARGET_DIR "${CUDA_TOOLKIT_ROOT_DIR}/targets/${CUDA_TARGET_TRIPLET}")
670 endif()
671
672 # CUDA_TOOLKIT_INCLUDE
673 find_path(CUDA_TOOLKIT_INCLUDE
674   device_functions.h # Header included in toolkit
675   PATHS "${CUDA_TOOLKIT_TARGET_DIR}" "${CUDA_TOOLKIT_ROOT_DIR}"
676   ENV CUDA_PATH
677   ENV CUDA_INC_PATH
678   PATH_SUFFIXES include
679   NO_DEFAULT_PATH
680   )
681 # Search default search paths, after we search our own set of paths.
682 find_path(CUDA_TOOLKIT_INCLUDE device_functions.h)
683 mark_as_advanced(CUDA_TOOLKIT_INCLUDE)
684
685 # Set the user list of include dir to nothing to initialize it.
686 set (CUDA_NVCC_INCLUDE_ARGS_USER "")
687 set (CUDA_INCLUDE_DIRS ${CUDA_TOOLKIT_INCLUDE})
688
689 macro(cuda_find_library_local_first_with_path_ext _var _names _doc _path_ext )
690   if(CMAKE_SIZEOF_VOID_P EQUAL 8)
691     # CUDA 3.2+ on Windows moved the library directories, so we need the new
692     # and old paths.
693     set(_cuda_64bit_lib_dir "${_path_ext}lib/x64" "${_path_ext}lib64" "${_path_ext}libx64" )
694   endif()
695   if(CMAKE_CROSSCOMPILING AND (ARM OR AARCH64))
696     set(_cuda_cross_arm_lib_dir "${_path_ext}lib/stubs")
697   endif()
698   if(CUDA_VERSION VERSION_GREATER "6.0")
699     set(_cuda_static_lib_names "")
700     foreach(name ${_names})
701       list(APPEND _cuda_static_lib_names "${name}_static")
702     endforeach()
703   endif()
704   # CUDA 3.2+ on Windows moved the library directories, so we need to new
705   # (lib/Win32) and the old path (lib).
706   find_library(${_var}
707     NAMES ${_names} ${_cuda_static_lib_names}
708     PATHS "${CUDA_TOOLKIT_TARGET_DIR}" "${CUDA_TOOLKIT_ROOT_DIR}"
709     ENV CUDA_PATH
710     ENV CUDA_LIB_PATH
711     PATH_SUFFIXES ${_cuda_64bit_lib_dir} ${_cuda_cross_arm_lib_dir} "${_path_ext}lib/Win32" "${_path_ext}lib" "${_path_ext}libWin32"
712     DOC ${_doc}
713     NO_DEFAULT_PATH
714     )
715   # Search default search paths, after we search our own set of paths.
716   find_library(${_var}
717     NAMES ${_names} ${_cuda_static_lib_names}
718     PATHS "/usr/lib/nvidia-current"
719     DOC ${_doc}
720     )
721 endmacro()
722
723 macro(cuda_find_library_local_first _var _names _doc)
724   cuda_find_library_local_first_with_path_ext( "${_var}" "${_names}" "${_doc}" "" )
725 endmacro()
726
727 macro(find_library_local_first _var _names _doc )
728   cuda_find_library_local_first( "${_var}" "${_names}" "${_doc}" "" )
729 endmacro()
730
731
732 # CUDA_LIBRARIES
733 cuda_find_library_local_first(CUDA_CUDART_LIBRARY cudart "\"cudart\" library")
734 if(CUDA_VERSION VERSION_EQUAL "3.0")
735   # The cudartemu library only existed for the 3.0 version of CUDA.
736   cuda_find_library_local_first(CUDA_CUDARTEMU_LIBRARY cudartemu "\"cudartemu\" library")
737   mark_as_advanced(
738     CUDA_CUDARTEMU_LIBRARY
739     )
740 endif()
741
742 # CUPTI library showed up in cuda toolkit 4.0
743 if(NOT CUDA_VERSION VERSION_LESS "4.0")
744   cuda_find_library_local_first_with_path_ext(CUDA_cupti_LIBRARY cupti "\"cupti\" library" "extras/CUPTI/")
745   mark_as_advanced(CUDA_cupti_LIBRARY)
746 endif()
747
748 # If we are using emulation mode and we found the cudartemu library then use
749 # that one instead of cudart.
750 if(CUDA_BUILD_EMULATION AND CUDA_CUDARTEMU_LIBRARY)
751   set(CUDA_LIBRARIES ${CUDA_CUDARTEMU_LIBRARY})
752 else()
753   set(CUDA_LIBRARIES ${CUDA_CUDART_LIBRARY})
754 endif()
755
756 # 1.1 toolkit on linux doesn't appear to have a separate library on
757 # some platforms.
758 cuda_find_library_local_first(CUDA_CUDA_LIBRARY cuda "\"cuda\" library (older versions only).")
759
760 mark_as_advanced(
761   CUDA_CUDA_LIBRARY
762   CUDA_CUDART_LIBRARY
763   )
764
765 #######################
766 # Look for some of the toolkit helper libraries
767 macro(FIND_CUDA_HELPER_LIBS _name)
768   cuda_find_library_local_first(CUDA_${_name}_LIBRARY ${_name} "\"${_name}\" library")
769   mark_as_advanced(CUDA_${_name}_LIBRARY)
770 endmacro()
771
772 #######################
773 # Disable emulation for v3.1 onward
774 if(CUDA_VERSION VERSION_GREATER "3.0")
775   if(CUDA_BUILD_EMULATION)
776     message(FATAL_ERROR "CUDA_BUILD_EMULATION is not supported in version 3.1 and onwards.  You must disable it to proceed.  You have version ${CUDA_VERSION}.")
777   endif()
778 endif()
779
780 # Search for additional CUDA toolkit libraries.
781 if(CUDA_VERSION VERSION_LESS "3.1")
782   # Emulation libraries aren't available in version 3.1 onward.
783   find_cuda_helper_libs(cufftemu)
784   find_cuda_helper_libs(cublasemu)
785 endif()
786 find_cuda_helper_libs(cufft)
787 find_cuda_helper_libs(cublas)
788 if(NOT CUDA_VERSION VERSION_LESS "3.2")
789   # cusparse showed up in version 3.2
790   find_cuda_helper_libs(cusparse)
791   find_cuda_helper_libs(curand)
792   if (WIN32)
793     find_cuda_helper_libs(nvcuvenc)
794     find_cuda_helper_libs(nvcuvid)
795   endif()
796 endif()
797 if(CUDA_VERSION VERSION_GREATER "7.5")
798   # In CUDA 8.0 NPPI was split in to many libraries.
799   find_cuda_helper_libs(nppc)
800   find_cuda_helper_libs(nppial)
801   find_cuda_helper_libs(nppicc)
802   find_cuda_helper_libs(nppicom)
803   find_cuda_helper_libs(nppidei)
804   find_cuda_helper_libs(nppif)
805   find_cuda_helper_libs(nppig)
806   find_cuda_helper_libs(nppim)
807   find_cuda_helper_libs(nppist)
808   find_cuda_helper_libs(nppisu)
809   find_cuda_helper_libs(nppitc)
810   find_cuda_helper_libs(npps)
811   set(CUDA_nppi_LIBRARY "${CUDA_nppial_LIBRARY};${CUDA_nppicc_LIBRARY};${CUDA_nppicom_LIBRARY};${CUDA_nppidei_LIBRARY};${CUDA_nppif_LIBRARY};${CUDA_nppig_LIBRARY};${CUDA_nppim_LIBRARY};${CUDA_nppist_LIBRARY};${CUDA_nppisu_LIBRARY};${CUDA_nppitc_LIBRARY}")
812   set(CUDA_npp_LIBRARY "${CUDA_nppc_LIBRARY};${CUDA_nppi_LIBRARY};${CUDA_npps_LIBRARY}")
813 elseif(CUDA_VERSION VERSION_GREATER "5.0")
814   # In CUDA 5.5 NPP was split in to 3 separate libraries.
815   find_cuda_helper_libs(nppc)
816   find_cuda_helper_libs(nppi)
817   find_cuda_helper_libs(npps)
818   set(CUDA_npp_LIBRARY "${CUDA_nppc_LIBRARY};${CUDA_nppi_LIBRARY};${CUDA_npps_LIBRARY}")
819 elseif(NOT CUDA_VERSION VERSION_LESS "4.0")
820   find_cuda_helper_libs(npp)
821 endif()
822
823 if (CUDA_BUILD_EMULATION)
824   set(CUDA_CUFFT_LIBRARIES ${CUDA_cufftemu_LIBRARY})
825   set(CUDA_CUBLAS_LIBRARIES ${CUDA_cublasemu_LIBRARY})
826 else()
827   set(CUDA_CUFFT_LIBRARIES ${CUDA_cufft_LIBRARY})
828   set(CUDA_CUBLAS_LIBRARIES ${CUDA_cublas_LIBRARY})
829 endif()
830
831 ########################
832 # Look for the SDK stuff.  As of CUDA 3.0 NVSDKCUDA_ROOT has been replaced with
833 # NVSDKCOMPUTE_ROOT with the old CUDA C contents moved into the C subdirectory
834 find_path(CUDA_SDK_ROOT_DIR common/inc/cutil.h
835  HINTS
836   "$ENV{NVSDKCOMPUTE_ROOT}/C"
837   ENV NVSDKCUDA_ROOT
838   "[HKEY_LOCAL_MACHINE\\SOFTWARE\\NVIDIA Corporation\\Installed Products\\NVIDIA SDK 10\\Compute;InstallDir]"
839  PATHS
840   "/Developer/GPU\ Computing/C"
841   )
842
843 # Keep the CUDA_SDK_ROOT_DIR first in order to be able to override the
844 # environment variables.
845 set(CUDA_SDK_SEARCH_PATH
846   "${CUDA_SDK_ROOT_DIR}"
847   "${CUDA_TOOLKIT_ROOT_DIR}/local/NVSDK0.2"
848   "${CUDA_TOOLKIT_ROOT_DIR}/NVSDK0.2"
849   "${CUDA_TOOLKIT_ROOT_DIR}/NV_CUDA_SDK"
850   "$ENV{HOME}/NVIDIA_CUDA_SDK"
851   "$ENV{HOME}/NVIDIA_CUDA_SDK_MACOSX"
852   "/Developer/CUDA"
853   )
854
855 # Example of how to find an include file from the CUDA_SDK_ROOT_DIR
856
857 # find_path(CUDA_CUT_INCLUDE_DIR
858 #   cutil.h
859 #   PATHS ${CUDA_SDK_SEARCH_PATH}
860 #   PATH_SUFFIXES "common/inc"
861 #   DOC "Location of cutil.h"
862 #   NO_DEFAULT_PATH
863 #   )
864 # # Now search system paths
865 # find_path(CUDA_CUT_INCLUDE_DIR cutil.h DOC "Location of cutil.h")
866
867 # mark_as_advanced(CUDA_CUT_INCLUDE_DIR)
868
869
870 # Example of how to find a library in the CUDA_SDK_ROOT_DIR
871
872 # # cutil library is called cutil64 for 64 bit builds on windows.  We don't want
873 # # to get these confused, so we are setting the name based on the word size of
874 # # the build.
875
876 # if(CMAKE_SIZEOF_VOID_P EQUAL 8)
877 #   set(cuda_cutil_name cutil64)
878 # else()
879 #   set(cuda_cutil_name cutil32)
880 # endif()
881
882 # find_library(CUDA_CUT_LIBRARY
883 #   NAMES cutil ${cuda_cutil_name}
884 #   PATHS ${CUDA_SDK_SEARCH_PATH}
885 #   # The new version of the sdk shows up in common/lib, but the old one is in lib
886 #   PATH_SUFFIXES "common/lib" "lib"
887 #   DOC "Location of cutil library"
888 #   NO_DEFAULT_PATH
889 #   )
890 # # Now search system paths
891 # find_library(CUDA_CUT_LIBRARY NAMES cutil ${cuda_cutil_name} DOC "Location of cutil library")
892 # mark_as_advanced(CUDA_CUT_LIBRARY)
893 # set(CUDA_CUT_LIBRARIES ${CUDA_CUT_LIBRARY})
894
895
896
897 #############################
898 # Check for required components
899 set(CUDA_FOUND TRUE)
900
901 set(CUDA_TOOLKIT_ROOT_DIR_INTERNAL "${CUDA_TOOLKIT_ROOT_DIR}" CACHE INTERNAL
902   "This is the value of the last time CUDA_TOOLKIT_ROOT_DIR was set successfully." FORCE)
903 set(CUDA_TARGET_TRIPLET_INTERNAL "${CUDA_TARGET_TRIPLET}" CACHE INTERNAL
904   "This is the value of the last time CUDA_TARGET_TRIPLET was set successfully." FORCE)
905 set(CUDA_TOOLKIT_TARGET_DIR_INTERNAL "${CUDA_TOOLKIT_TARGET_DIR}" CACHE INTERNAL
906   "This is the value of the last time CUDA_TOOLKIT_TARGET_DIR was set successfully." FORCE)
907 set(CUDA_SDK_ROOT_DIR_INTERNAL "${CUDA_SDK_ROOT_DIR}" CACHE INTERNAL
908   "This is the value of the last time CUDA_SDK_ROOT_DIR was set successfully." FORCE)
909
910 include(FindPackageHandleStandardArgs)
911 find_package_handle_standard_args(CUDA
912   REQUIRED_VARS
913     CUDA_TOOLKIT_ROOT_DIR
914     CUDA_NVCC_EXECUTABLE
915     CUDA_INCLUDE_DIRS
916     CUDA_CUDART_LIBRARY
917   VERSION_VAR
918     CUDA_VERSION
919   )
920
921
922
923 ###############################################################################
924 ###############################################################################
925 # Macros
926 ###############################################################################
927 ###############################################################################
928
929 ###############################################################################
930 # Add include directories to pass to the nvcc command.
931 macro(CUDA_INCLUDE_DIRECTORIES)
932   foreach(dir ${ARGN})
933     list(APPEND CUDA_NVCC_INCLUDE_ARGS_USER -I${dir})
934   endforeach()
935 endmacro()
936
937
938 ##############################################################################
939 cuda_find_helper_file(parse_cubin cmake)
940 cuda_find_helper_file(make2cmake cmake)
941 cuda_find_helper_file(run_nvcc cmake)
942
943 ##############################################################################
944 # Separate the OPTIONS out from the sources
945 #
946 macro(CUDA_GET_SOURCES_AND_OPTIONS _sources _cmake_options _options)
947   set( ${_sources} )
948   set( ${_cmake_options} )
949   set( ${_options} )
950   set( _found_options FALSE )
951   foreach(arg ${ARGN})
952     if("x${arg}" STREQUAL "xOPTIONS")
953       set( _found_options TRUE )
954     elseif(
955         "x${arg}" STREQUAL "xWIN32" OR
956         "x${arg}" STREQUAL "xMACOSX_BUNDLE" OR
957         "x${arg}" STREQUAL "xEXCLUDE_FROM_ALL" OR
958         "x${arg}" STREQUAL "xSTATIC" OR
959         "x${arg}" STREQUAL "xSHARED" OR
960         "x${arg}" STREQUAL "xMODULE"
961         )
962       list(APPEND ${_cmake_options} ${arg})
963     else()
964       if ( _found_options )
965         list(APPEND ${_options} ${arg})
966       else()
967         # Assume this is a file
968         list(APPEND ${_sources} ${arg})
969       endif()
970     endif()
971   endforeach()
972 endmacro()
973
974 ##############################################################################
975 # Parse the OPTIONS from ARGN and set the variables prefixed by _option_prefix
976 #
977 macro(CUDA_PARSE_NVCC_OPTIONS _option_prefix)
978   set( _found_config )
979   foreach(arg ${ARGN})
980     # Determine if we are dealing with a perconfiguration flag
981     foreach(config ${CUDA_configuration_types})
982       string(TOUPPER ${config} config_upper)
983       if (arg STREQUAL "${config_upper}")
984         set( _found_config _${arg})
985         # Set arg to nothing to keep it from being processed further
986         set( arg )
987       endif()
988     endforeach()
989
990     if ( arg )
991       list(APPEND ${_option_prefix}${_found_config} "${arg}")
992     endif()
993   endforeach()
994 endmacro()
995
996 ##############################################################################
997 # Helper to add the include directory for CUDA only once
998 function(CUDA_ADD_CUDA_INCLUDE_ONCE)
999   get_directory_property(_include_directories INCLUDE_DIRECTORIES)
1000   set(_add TRUE)
1001   if(_include_directories)
1002     foreach(dir ${_include_directories})
1003       if("${dir}" STREQUAL "${CUDA_INCLUDE_DIRS}")
1004         set(_add FALSE)
1005       endif()
1006     endforeach()
1007   endif()
1008   if(_add)
1009     include_directories(${CUDA_INCLUDE_DIRS})
1010   endif()
1011 endfunction()
1012
1013 function(CUDA_BUILD_SHARED_LIBRARY shared_flag)
1014   set(cmake_args ${ARGN})
1015   # If SHARED, MODULE, or STATIC aren't already in the list of arguments, then
1016   # add SHARED or STATIC based on the value of BUILD_SHARED_LIBS.
1017   list(FIND cmake_args SHARED _cuda_found_SHARED)
1018   list(FIND cmake_args MODULE _cuda_found_MODULE)
1019   list(FIND cmake_args STATIC _cuda_found_STATIC)
1020   if( _cuda_found_SHARED GREATER -1 OR
1021       _cuda_found_MODULE GREATER -1 OR
1022       _cuda_found_STATIC GREATER -1)
1023     set(_cuda_build_shared_libs)
1024   else()
1025     if (BUILD_SHARED_LIBS)
1026       set(_cuda_build_shared_libs SHARED)
1027     else()
1028       set(_cuda_build_shared_libs STATIC)
1029     endif()
1030   endif()
1031   set(${shared_flag} ${_cuda_build_shared_libs} PARENT_SCOPE)
1032 endfunction()
1033
1034 ##############################################################################
1035 # Helper to avoid clashes of files with the same basename but different paths.
1036 # This doesn't attempt to do exactly what CMake internals do, which is to only
1037 # add this path when there is a conflict, since by the time a second collision
1038 # in names is detected it's already too late to fix the first one.  For
1039 # consistency sake the relative path will be added to all files.
1040 function(CUDA_COMPUTE_BUILD_PATH path build_path)
1041   #message("CUDA_COMPUTE_BUILD_PATH([${path}] ${build_path})")
1042   # Only deal with CMake style paths from here on out
1043   file(TO_CMAKE_PATH "${path}" bpath)
1044   if (IS_ABSOLUTE "${bpath}")
1045     # Absolute paths are generally unnecessary, especially if something like
1046     # file(GLOB_RECURSE) is used to pick up the files.
1047
1048     string(FIND "${bpath}" "${CMAKE_CURRENT_BINARY_DIR}" _binary_dir_pos)
1049     if (_binary_dir_pos EQUAL 0)
1050       file(RELATIVE_PATH bpath "${CMAKE_CURRENT_BINARY_DIR}" "${bpath}")
1051     else()
1052       file(RELATIVE_PATH bpath "${CMAKE_CURRENT_SOURCE_DIR}" "${bpath}")
1053     endif()
1054   endif()
1055
1056   # This recipe is from cmLocalGenerator::CreateSafeUniqueObjectFileName in the
1057   # CMake source.
1058
1059   # Remove leading /
1060   string(REGEX REPLACE "^[/]+" "" bpath "${bpath}")
1061   # Avoid absolute paths by removing ':'
1062   string(REPLACE ":" "_" bpath "${bpath}")
1063   # Avoid relative paths that go up the tree
1064   string(REPLACE "../" "__/" bpath "${bpath}")
1065   # Avoid spaces
1066   string(REPLACE " " "_" bpath "${bpath}")
1067
1068   # Strip off the filename.  I wait until here to do it, since removing the
1069   # basename can make a path that looked like path/../basename turn into
1070   # path/.. (notice the trailing slash).
1071   get_filename_component(bpath "${bpath}" PATH)
1072
1073   set(${build_path} "${bpath}" PARENT_SCOPE)
1074   #message("${build_path} = ${bpath}")
1075 endfunction()
1076
1077 ##############################################################################
1078 # This helper macro populates the following variables and setups up custom
1079 # commands and targets to invoke the nvcc compiler to generate C or PTX source
1080 # dependent upon the format parameter.  The compiler is invoked once with -M
1081 # to generate a dependency file and a second time with -cuda or -ptx to generate
1082 # a .cpp or .ptx file.
1083 # INPUT:
1084 #   cuda_target         - Target name
1085 #   format              - PTX, CUBIN, FATBIN or OBJ
1086 #   FILE1 .. FILEN      - The remaining arguments are the sources to be wrapped.
1087 #   OPTIONS             - Extra options to NVCC
1088 # OUTPUT:
1089 #   generated_files     - List of generated files
1090 ##############################################################################
1091 ##############################################################################
1092
1093 macro(CUDA_WRAP_SRCS cuda_target format generated_files)
1094
1095   # If CMake doesn't support separable compilation, complain
1096   if(CUDA_SEPARABLE_COMPILATION AND CMAKE_VERSION VERSION_LESS "2.8.10.1")
1097     message(SEND_ERROR "CUDA_SEPARABLE_COMPILATION isn't supported for CMake versions less than 2.8.10.1")
1098   endif()
1099
1100   # Set up all the command line flags here, so that they can be overridden on a per target basis.
1101
1102   set(nvcc_flags "")
1103
1104   # Emulation if the card isn't present.
1105   if (CUDA_BUILD_EMULATION)
1106     # Emulation.
1107     set(nvcc_flags ${nvcc_flags} --device-emulation -D_DEVICEEMU -g)
1108   else()
1109     # Device mode.  No flags necessary.
1110   endif()
1111
1112   if(CUDA_HOST_COMPILATION_CPP)
1113     set(CUDA_C_OR_CXX CXX)
1114   else()
1115     if(CUDA_VERSION VERSION_LESS "3.0")
1116       set(nvcc_flags ${nvcc_flags} --host-compilation C)
1117     else()
1118       message(WARNING "--host-compilation flag is deprecated in CUDA version >= 3.0.  Removing --host-compilation C flag" )
1119     endif()
1120     set(CUDA_C_OR_CXX C)
1121   endif()
1122
1123   set(generated_extension ${CMAKE_${CUDA_C_OR_CXX}_OUTPUT_EXTENSION})
1124
1125   if(CUDA_64_BIT_DEVICE_CODE)
1126     set(nvcc_flags ${nvcc_flags} -m64)
1127   else()
1128     set(nvcc_flags ${nvcc_flags} -m32)
1129   endif()
1130
1131   if(CUDA_TARGET_CPU_ARCH AND CUDA_VERSION VERSION_LESS "7.0")
1132     # CPU architecture is either ARM or X86. Patch AARCH64 to be ARM
1133     string(REPLACE "AARCH64" "ARM" CUDA_TARGET_CPU_ARCH_patched ${CUDA_TARGET_CPU_ARCH})
1134     set(nvcc_flags ${nvcc_flags} "--target-cpu-architecture=${CUDA_TARGET_CPU_ARCH_patched}")
1135   endif()
1136
1137   if(CUDA_TARGET_OS_VARIANT AND CUDA_VERSION VERSION_LESS "7.0")
1138     set(nvcc_flags ${nvcc_flags} "-target-os-variant=${CUDA_TARGET_OS_VARIANT}")
1139   endif()
1140
1141   # This needs to be passed in at this stage, because VS needs to fill out the
1142   # various macros from within VS.  Note that CCBIN is only used if
1143   # -ccbin or --compiler-bindir isn't used and CUDA_HOST_COMPILER matches
1144   # _CUDA_MSVC_HOST_COMPILER
1145   if(CMAKE_GENERATOR MATCHES "Visual Studio")
1146     set(ccbin_flags -D "\"CCBIN:PATH=${_CUDA_MSVC_HOST_COMPILER}\"" )
1147   else()
1148     set(ccbin_flags)
1149   endif()
1150
1151   # Figure out which configure we will use and pass that in as an argument to
1152   # the script.  We need to defer the decision until compilation time, because
1153   # for VS projects we won't know if we are making a debug or release build
1154   # until build time.
1155   if(CMAKE_GENERATOR MATCHES "Visual Studio")
1156     set( CUDA_build_configuration "$(ConfigurationName)" )
1157   else()
1158     set( CUDA_build_configuration "${CMAKE_BUILD_TYPE}")
1159   endif()
1160
1161   # Initialize our list of includes with the user ones followed by the CUDA system ones.
1162   set(CUDA_NVCC_INCLUDE_ARGS ${CUDA_NVCC_INCLUDE_ARGS_USER} "-I${CUDA_INCLUDE_DIRS}")
1163   # Get the include directories for this directory and use them for our nvcc command.
1164   # Remove duplicate entries which may be present since include_directories
1165   # in CMake >= 2.8.8 does not remove them.
1166   get_directory_property(CUDA_NVCC_INCLUDE_DIRECTORIES INCLUDE_DIRECTORIES)
1167   list(REMOVE_DUPLICATES CUDA_NVCC_INCLUDE_DIRECTORIES)
1168   if(CUDA_NVCC_INCLUDE_DIRECTORIES)
1169     foreach(dir ${CUDA_NVCC_INCLUDE_DIRECTORIES})
1170       list(APPEND CUDA_NVCC_INCLUDE_ARGS -I${dir})
1171     endforeach()
1172   endif()
1173
1174   # Reset these variables
1175   set(CUDA_WRAP_OPTION_NVCC_FLAGS)
1176   foreach(config ${CUDA_configuration_types})
1177     string(TOUPPER ${config} config_upper)
1178     set(CUDA_WRAP_OPTION_NVCC_FLAGS_${config_upper})
1179   endforeach()
1180
1181   CUDA_GET_SOURCES_AND_OPTIONS(_cuda_wrap_sources _cuda_wrap_cmake_options _cuda_wrap_options ${ARGN})
1182   CUDA_PARSE_NVCC_OPTIONS(CUDA_WRAP_OPTION_NVCC_FLAGS ${_cuda_wrap_options})
1183
1184   # Figure out if we are building a shared library.  BUILD_SHARED_LIBS is
1185   # respected in CUDA_ADD_LIBRARY.
1186   set(_cuda_build_shared_libs FALSE)
1187   # SHARED, MODULE
1188   list(FIND _cuda_wrap_cmake_options SHARED _cuda_found_SHARED)
1189   list(FIND _cuda_wrap_cmake_options MODULE _cuda_found_MODULE)
1190   if(_cuda_found_SHARED GREATER -1 OR _cuda_found_MODULE GREATER -1)
1191     set(_cuda_build_shared_libs TRUE)
1192   endif()
1193   # STATIC
1194   list(FIND _cuda_wrap_cmake_options STATIC _cuda_found_STATIC)
1195   if(_cuda_found_STATIC GREATER -1)
1196     set(_cuda_build_shared_libs FALSE)
1197   endif()
1198
1199   # CUDA_HOST_FLAGS
1200   if(_cuda_build_shared_libs)
1201     # If we are setting up code for a shared library, then we need to add extra flags for
1202     # compiling objects for shared libraries.
1203     set(CUDA_HOST_SHARED_FLAGS ${CMAKE_SHARED_LIBRARY_${CUDA_C_OR_CXX}_FLAGS})
1204   else()
1205     set(CUDA_HOST_SHARED_FLAGS)
1206   endif()
1207   # Only add the CMAKE_{C,CXX}_FLAGS if we are propagating host flags.  We
1208   # always need to set the SHARED_FLAGS, though.
1209   if(CUDA_PROPAGATE_HOST_FLAGS)
1210     set(_cuda_host_flags "set(CMAKE_HOST_FLAGS ${CMAKE_${CUDA_C_OR_CXX}_FLAGS} ${CUDA_HOST_SHARED_FLAGS})")
1211   else()
1212     set(_cuda_host_flags "set(CMAKE_HOST_FLAGS ${CUDA_HOST_SHARED_FLAGS})")
1213   endif()
1214
1215   set(_cuda_nvcc_flags_config "# Build specific configuration flags")
1216   # Loop over all the configuration types to generate appropriate flags for run_nvcc.cmake
1217   foreach(config ${CUDA_configuration_types})
1218     string(TOUPPER ${config} config_upper)
1219     # CMAKE_FLAGS are strings and not lists.  By not putting quotes around CMAKE_FLAGS
1220     # we convert the strings to lists (like we want).
1221
1222     if(CUDA_PROPAGATE_HOST_FLAGS)
1223       # nvcc chokes on -g3 in versions previous to 3.0, so replace it with -g
1224       set(_cuda_fix_g3 FALSE)
1225
1226       if(CMAKE_COMPILER_IS_GNUCC)
1227         if (CUDA_VERSION VERSION_LESS  "3.0" OR
1228             CUDA_VERSION VERSION_EQUAL "4.1" OR
1229             CUDA_VERSION VERSION_EQUAL "4.2"
1230             )
1231           set(_cuda_fix_g3 TRUE)
1232         endif()
1233       endif()
1234       if(_cuda_fix_g3)
1235         string(REPLACE "-g3" "-g" _cuda_C_FLAGS "${CMAKE_${CUDA_C_OR_CXX}_FLAGS_${config_upper}}")
1236       else()
1237         set(_cuda_C_FLAGS "${CMAKE_${CUDA_C_OR_CXX}_FLAGS_${config_upper}}")
1238       endif()
1239
1240       set(_cuda_host_flags "${_cuda_host_flags}\nset(CMAKE_HOST_FLAGS_${config_upper} ${_cuda_C_FLAGS})")
1241     endif()
1242
1243     # Note that if we ever want CUDA_NVCC_FLAGS_<CONFIG> to be string (instead of a list
1244     # like it is currently), we can remove the quotes around the
1245     # ${CUDA_NVCC_FLAGS_${config_upper}} variable like the CMAKE_HOST_FLAGS_<CONFIG> variable.
1246     set(_cuda_nvcc_flags_config "${_cuda_nvcc_flags_config}\nset(CUDA_NVCC_FLAGS_${config_upper} ${CUDA_NVCC_FLAGS_${config_upper}} ;; ${CUDA_WRAP_OPTION_NVCC_FLAGS_${config_upper}})")
1247   endforeach()
1248
1249   # Get the list of definitions from the directory property
1250   get_directory_property(CUDA_NVCC_DEFINITIONS COMPILE_DEFINITIONS)
1251   if(CUDA_NVCC_DEFINITIONS)
1252     foreach(_definition ${CUDA_NVCC_DEFINITIONS})
1253       list(APPEND nvcc_flags "-D${_definition}")
1254     endforeach()
1255   endif()
1256
1257   if(_cuda_build_shared_libs)
1258     list(APPEND nvcc_flags "-D${cuda_target}_EXPORTS")
1259   endif()
1260
1261   # Reset the output variable
1262   set(_cuda_wrap_generated_files "")
1263
1264   # Iterate over the macro arguments and create custom
1265   # commands for all the .cu files.
1266   foreach(file ${ARGN})
1267     # Ignore any file marked as a HEADER_FILE_ONLY
1268     get_source_file_property(_is_header ${file} HEADER_FILE_ONLY)
1269     if(${file} MATCHES "\\.cu$" AND NOT _is_header)
1270
1271       # Allow per source file overrides of the format.
1272       get_source_file_property(_cuda_source_format ${file} CUDA_SOURCE_PROPERTY_FORMAT)
1273       if(NOT _cuda_source_format)
1274         set(_cuda_source_format ${format})
1275       endif()
1276
1277       if( ${_cuda_source_format} MATCHES "OBJ")
1278         set( cuda_compile_to_external_module OFF )
1279       else()
1280         set( cuda_compile_to_external_module ON )
1281         if( ${_cuda_source_format} MATCHES "PTX" )
1282           set( cuda_compile_to_external_module_type "ptx" )
1283         elseif( ${_cuda_source_format} MATCHES "CUBIN")
1284           set( cuda_compile_to_external_module_type "cubin" )
1285         elseif( ${_cuda_source_format} MATCHES "FATBIN")
1286           set( cuda_compile_to_external_module_type "fatbin" )
1287         else()
1288           message( FATAL_ERROR "Invalid format flag passed to CUDA_WRAP_SRCS for file '${file}': '${_cuda_source_format}'.  Use OBJ, PTX, CUBIN or FATBIN.")
1289         endif()
1290       endif()
1291
1292       if(cuda_compile_to_external_module)
1293         # Don't use any of the host compilation flags for PTX targets.
1294         set(CUDA_HOST_FLAGS)
1295         set(CUDA_NVCC_FLAGS_CONFIG)
1296       else()
1297         set(CUDA_HOST_FLAGS ${_cuda_host_flags})
1298         set(CUDA_NVCC_FLAGS_CONFIG ${_cuda_nvcc_flags_config})
1299       endif()
1300
1301       # Determine output directory
1302       cuda_compute_build_path("${file}" cuda_build_path)
1303       set(cuda_compile_intermediate_directory "${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/${cuda_target}.dir/${cuda_build_path}")
1304       if(CUDA_GENERATED_OUTPUT_DIR)
1305         set(cuda_compile_output_dir "${CUDA_GENERATED_OUTPUT_DIR}")
1306       else()
1307         if ( cuda_compile_to_external_module )
1308           set(cuda_compile_output_dir "${CMAKE_CURRENT_BINARY_DIR}")
1309         else()
1310           set(cuda_compile_output_dir "${cuda_compile_intermediate_directory}")
1311         endif()
1312       endif()
1313
1314       # Add a custom target to generate a c or ptx file. ######################
1315
1316       get_filename_component( basename ${file} NAME )
1317       if( cuda_compile_to_external_module )
1318         set(generated_file_path "${cuda_compile_output_dir}")
1319         set(generated_file_basename "${cuda_target}_generated_${basename}.${cuda_compile_to_external_module_type}")
1320         set(format_flag "-${cuda_compile_to_external_module_type}")
1321         file(MAKE_DIRECTORY "${cuda_compile_output_dir}")
1322       else()
1323         set(generated_file_path "${cuda_compile_output_dir}/${CMAKE_CFG_INTDIR}")
1324         set(generated_file_basename "${cuda_target}_generated_${basename}${generated_extension}")
1325         if(CUDA_SEPARABLE_COMPILATION)
1326           set(format_flag "-dc")
1327         else()
1328           set(format_flag "-c")
1329         endif()
1330       endif()
1331
1332       # Set all of our file names.  Make sure that whatever filenames that have
1333       # generated_file_path in them get passed in through as a command line
1334       # argument, so that the ${CMAKE_CFG_INTDIR} gets expanded at run time
1335       # instead of configure time.
1336       set(generated_file "${generated_file_path}/${generated_file_basename}")
1337       set(cmake_dependency_file "${cuda_compile_intermediate_directory}/${generated_file_basename}.depend")
1338       set(NVCC_generated_dependency_file "${cuda_compile_intermediate_directory}/${generated_file_basename}.NVCC-depend")
1339       set(generated_cubin_file "${generated_file_path}/${generated_file_basename}.cubin.txt")
1340       set(custom_target_script "${cuda_compile_intermediate_directory}/${generated_file_basename}.cmake")
1341
1342       # Setup properties for obj files:
1343       if( NOT cuda_compile_to_external_module )
1344         set_source_files_properties("${generated_file}"
1345           PROPERTIES
1346           EXTERNAL_OBJECT true # This is an object file not to be compiled, but only be linked.
1347           )
1348       endif()
1349
1350       # Don't add CMAKE_CURRENT_SOURCE_DIR if the path is already an absolute path.
1351       get_filename_component(file_path "${file}" PATH)
1352       if(IS_ABSOLUTE "${file_path}")
1353         set(source_file "${file}")
1354       else()
1355         set(source_file "${CMAKE_CURRENT_SOURCE_DIR}/${file}")
1356       endif()
1357
1358       if( NOT cuda_compile_to_external_module AND CUDA_SEPARABLE_COMPILATION)
1359         list(APPEND ${cuda_target}_SEPARABLE_COMPILATION_OBJECTS "${generated_file}")
1360       endif()
1361
1362       # Bring in the dependencies.  Creates a variable CUDA_NVCC_DEPEND #######
1363       cuda_include_nvcc_dependencies(${cmake_dependency_file})
1364
1365       # Convenience string for output ###########################################
1366       if(CUDA_BUILD_EMULATION)
1367         set(cuda_build_type "Emulation")
1368       else()
1369         set(cuda_build_type "Device")
1370       endif()
1371
1372       # Build the NVCC made dependency file ###################################
1373       set(build_cubin OFF)
1374       if ( NOT CUDA_BUILD_EMULATION AND CUDA_BUILD_CUBIN )
1375          if ( NOT cuda_compile_to_external_module )
1376            set ( build_cubin ON )
1377          endif()
1378       endif()
1379
1380       # Configure the build script
1381       configure_file("${CUDA_run_nvcc}" "${custom_target_script}" @ONLY)
1382
1383       # So if a user specifies the same cuda file as input more than once, you
1384       # can have bad things happen with dependencies.  Here we check an option
1385       # to see if this is the behavior they want.
1386       if(CUDA_ATTACH_VS_BUILD_RULE_TO_CUDA_FILE)
1387         set(main_dep MAIN_DEPENDENCY ${source_file})
1388       else()
1389         set(main_dep DEPENDS ${source_file})
1390       endif()
1391
1392       if(CUDA_VERBOSE_BUILD)
1393         set(verbose_output ON)
1394       elseif(CMAKE_GENERATOR MATCHES "Makefiles")
1395         set(verbose_output "$(VERBOSE)")
1396       else()
1397         set(verbose_output OFF)
1398       endif()
1399
1400       # Create up the comment string
1401       file(RELATIVE_PATH generated_file_relative_path "${CMAKE_BINARY_DIR}" "${generated_file}")
1402       if(cuda_compile_to_external_module)
1403         set(cuda_build_comment_string "Building NVCC ${cuda_compile_to_external_module_type} file ${generated_file_relative_path}")
1404       else()
1405         set(cuda_build_comment_string "Building NVCC (${cuda_build_type}) object ${generated_file_relative_path}")
1406       endif()
1407
1408       # Build the generated file and dependency file ##########################
1409       add_custom_command(
1410         OUTPUT ${generated_file}
1411         # These output files depend on the source_file and the contents of cmake_dependency_file
1412         ${main_dep}
1413         DEPENDS ${CUDA_NVCC_DEPEND}
1414         DEPENDS ${custom_target_script}
1415         # Make sure the output directory exists before trying to write to it.
1416         COMMAND ${CMAKE_COMMAND} -E make_directory "${generated_file_path}"
1417         COMMAND ${CMAKE_COMMAND} ARGS
1418           -D verbose:BOOL=${verbose_output}
1419           ${ccbin_flags}
1420           -D build_configuration:STRING=${CUDA_build_configuration}
1421           -D "generated_file:STRING=${generated_file}"
1422           -D "generated_cubin_file:STRING=${generated_cubin_file}"
1423           -P "${custom_target_script}"
1424         WORKING_DIRECTORY "${cuda_compile_intermediate_directory}"
1425         COMMENT "${cuda_build_comment_string}"
1426         )
1427
1428       # Make sure the build system knows the file is generated.
1429       set_source_files_properties(${generated_file} PROPERTIES GENERATED TRUE)
1430
1431       list(APPEND _cuda_wrap_generated_files ${generated_file})
1432
1433       # Add the other files that we want cmake to clean on a cleanup ##########
1434       list(APPEND CUDA_ADDITIONAL_CLEAN_FILES "${cmake_dependency_file}")
1435       list(REMOVE_DUPLICATES CUDA_ADDITIONAL_CLEAN_FILES)
1436       set(CUDA_ADDITIONAL_CLEAN_FILES ${CUDA_ADDITIONAL_CLEAN_FILES} CACHE INTERNAL "List of intermediate files that are part of the cuda dependency scanning.")
1437
1438     endif()
1439   endforeach()
1440
1441   # Set the return parameter
1442   set(${generated_files} ${_cuda_wrap_generated_files})
1443 endmacro()
1444
1445 function(_cuda_get_important_host_flags important_flags flag_string)
1446   if(CMAKE_GENERATOR MATCHES "Visual Studio")
1447     string(REGEX MATCHALL "/M[DT][d]?" flags ${flag_string})
1448     list(APPEND ${important_flags} ${flags})
1449   else()
1450     string(REGEX MATCHALL "-fPIC" flags ${flag_string})
1451     list(APPEND ${important_flags} ${flags})
1452   endif()
1453   set(${important_flags} ${${important_flags}} PARENT_SCOPE)
1454 endfunction()
1455
1456 ###############################################################################
1457 ###############################################################################
1458 # Separable Compilation Link
1459 ###############################################################################
1460 ###############################################################################
1461
1462 # Compute the filename to be used by CUDA_LINK_SEPARABLE_COMPILATION_OBJECTS
1463 function(CUDA_COMPUTE_SEPARABLE_COMPILATION_OBJECT_FILE_NAME output_file_var cuda_target object_files)
1464   if (object_files)
1465     set(generated_extension ${CMAKE_${CUDA_C_OR_CXX}_OUTPUT_EXTENSION})
1466     set(output_file "${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/${cuda_target}.dir/${CMAKE_CFG_INTDIR}/${cuda_target}_intermediate_link${generated_extension}")
1467   else()
1468     set(output_file)
1469   endif()
1470
1471   set(${output_file_var} "${output_file}" PARENT_SCOPE)
1472 endfunction()
1473
1474 # Setup the build rule for the separable compilation intermediate link file.
1475 function(CUDA_LINK_SEPARABLE_COMPILATION_OBJECTS output_file cuda_target options object_files)
1476   if (object_files)
1477
1478     set_source_files_properties("${output_file}"
1479       PROPERTIES
1480       EXTERNAL_OBJECT TRUE # This is an object file not to be compiled, but only
1481                            # be linked.
1482       GENERATED TRUE       # This file is generated during the build
1483       )
1484
1485     # For now we are ignoring all the configuration specific flags.
1486     set(nvcc_flags)
1487     CUDA_PARSE_NVCC_OPTIONS(nvcc_flags ${options})
1488     if(CUDA_64_BIT_DEVICE_CODE)
1489       list(APPEND nvcc_flags -m64)
1490     else()
1491       list(APPEND nvcc_flags -m32)
1492     endif()
1493     # If -ccbin, --compiler-bindir has been specified, don't do anything.  Otherwise add it here.
1494     list( FIND nvcc_flags "-ccbin" ccbin_found0 )
1495     list( FIND nvcc_flags "--compiler-bindir" ccbin_found1 )
1496     if( ccbin_found0 LESS 0 AND ccbin_found1 LESS 0 AND CUDA_HOST_COMPILER )
1497       list(APPEND nvcc_flags -ccbin "\"${CUDA_HOST_COMPILER}\"")
1498     endif()
1499     # Create a list of flags specified by CUDA_NVCC_FLAGS_${CONFIG}
1500     set(config_specific_flags)
1501     set(flags)
1502     foreach(config ${CUDA_configuration_types})
1503       string(TOUPPER ${config} config_upper)
1504       # Add config specific flags
1505       foreach(f ${CUDA_NVCC_FLAGS_${config_upper}})
1506         list(APPEND config_specific_flags $<$<CONFIG:${config}>:${f}>)
1507       endforeach()
1508       set(important_host_flags)
1509       _cuda_get_important_host_flags(important_host_flags ${CMAKE_${CUDA_C_OR_CXX}_FLAGS_${config_upper}})
1510       foreach(f ${important_host_flags})
1511         list(APPEND flags $<$<CONFIG:${config}>:-Xcompiler> $<$<CONFIG:${config}>:${f}>)
1512       endforeach()
1513     endforeach()
1514     # Add our general CUDA_NVCC_FLAGS with the configuration specifig flags
1515     set(nvcc_flags ${CUDA_NVCC_FLAGS} ${config_specific_flags} ${nvcc_flags})
1516
1517     file(RELATIVE_PATH output_file_relative_path "${CMAKE_BINARY_DIR}" "${output_file}")
1518
1519     # Some generators don't handle the multiple levels of custom command
1520     # dependencies correctly (obj1 depends on file1, obj2 depends on obj1), so
1521     # we work around that issue by compiling the intermediate link object as a
1522     # pre-link custom command in that situation.
1523     set(do_obj_build_rule TRUE)
1524     if (MSVC_VERSION GREATER 1599)
1525       # VS 2010 and 2012 have this problem.  If future versions fix this issue,
1526       # it should still work, it just won't be as nice as the other method.
1527       set(do_obj_build_rule FALSE)
1528     endif()
1529
1530     if (do_obj_build_rule)
1531       add_custom_command(
1532         OUTPUT ${output_file}
1533         DEPENDS ${object_files}
1534         COMMAND ${CUDA_NVCC_EXECUTABLE} ${nvcc_flags} -dlink ${object_files} -o ${output_file}
1535         ${flags}
1536         COMMENT "Building NVCC intermediate link file ${output_file_relative_path}"
1537         )
1538     else()
1539       add_custom_command(
1540         TARGET ${cuda_target}
1541         PRE_LINK
1542         COMMAND ${CMAKE_COMMAND} -E echo "Building NVCC intermediate link file ${output_file_relative_path}"
1543         COMMAND ${CUDA_NVCC_EXECUTABLE} ${nvcc_flags} ${flags} -dlink ${object_files} -o "${output_file}"
1544         )
1545     endif()
1546  endif()
1547 endfunction()
1548
1549 ###############################################################################
1550 ###############################################################################
1551 # ADD LIBRARY
1552 ###############################################################################
1553 ###############################################################################
1554 macro(CUDA_ADD_LIBRARY cuda_target)
1555
1556   CUDA_ADD_CUDA_INCLUDE_ONCE()
1557
1558   # Separate the sources from the options
1559   CUDA_GET_SOURCES_AND_OPTIONS(_sources _cmake_options _options ${ARGN})
1560   CUDA_BUILD_SHARED_LIBRARY(_cuda_shared_flag ${ARGN})
1561   # Create custom commands and targets for each file.
1562   CUDA_WRAP_SRCS( ${cuda_target} OBJ _generated_files ${_sources}
1563     ${_cmake_options} ${_cuda_shared_flag}
1564     OPTIONS ${_options} )
1565
1566   # Compute the file name of the intermediate link file used for separable
1567   # compilation.
1568   CUDA_COMPUTE_SEPARABLE_COMPILATION_OBJECT_FILE_NAME(link_file ${cuda_target} "${${cuda_target}_SEPARABLE_COMPILATION_OBJECTS}")
1569
1570   # Add the library.
1571   add_library(${cuda_target} ${_cmake_options}
1572     ${_generated_files}
1573     ${_sources}
1574     ${link_file}
1575     )
1576
1577   # Add a link phase for the separable compilation if it has been enabled.  If
1578   # it has been enabled then the ${cuda_target}_SEPARABLE_COMPILATION_OBJECTS
1579   # variable will have been defined.
1580   CUDA_LINK_SEPARABLE_COMPILATION_OBJECTS("${link_file}" ${cuda_target} "${_options}" "${${cuda_target}_SEPARABLE_COMPILATION_OBJECTS}")
1581
1582   target_link_libraries(${cuda_target} LINK_PRIVATE
1583     ${CUDA_LIBRARIES}
1584     )
1585
1586   # We need to set the linker language based on what the expected generated file
1587   # would be. CUDA_C_OR_CXX is computed based on CUDA_HOST_COMPILATION_CPP.
1588   set_target_properties(${cuda_target}
1589     PROPERTIES
1590     LINKER_LANGUAGE ${CUDA_C_OR_CXX}
1591     )
1592
1593 endmacro()
1594
1595
1596 ###############################################################################
1597 ###############################################################################
1598 # ADD EXECUTABLE
1599 ###############################################################################
1600 ###############################################################################
1601 macro(CUDA_ADD_EXECUTABLE cuda_target)
1602
1603   CUDA_ADD_CUDA_INCLUDE_ONCE()
1604
1605   # Separate the sources from the options
1606   CUDA_GET_SOURCES_AND_OPTIONS(_sources _cmake_options _options ${ARGN})
1607   # Create custom commands and targets for each file.
1608   CUDA_WRAP_SRCS( ${cuda_target} OBJ _generated_files ${_sources} OPTIONS ${_options} )
1609
1610   # Compute the file name of the intermediate link file used for separable
1611   # compilation.
1612   CUDA_COMPUTE_SEPARABLE_COMPILATION_OBJECT_FILE_NAME(link_file ${cuda_target} "${${cuda_target}_SEPARABLE_COMPILATION_OBJECTS}")
1613
1614   # Add the library.
1615   add_executable(${cuda_target} ${_cmake_options}
1616     ${_generated_files}
1617     ${_sources}
1618     ${link_file}
1619     )
1620
1621   # Add a link phase for the separable compilation if it has been enabled.  If
1622   # it has been enabled then the ${cuda_target}_SEPARABLE_COMPILATION_OBJECTS
1623   # variable will have been defined.
1624   CUDA_LINK_SEPARABLE_COMPILATION_OBJECTS("${link_file}" ${cuda_target} "${_options}" "${${cuda_target}_SEPARABLE_COMPILATION_OBJECTS}")
1625
1626   target_link_libraries(${cuda_target} LINK_PRIVATE
1627     ${CUDA_LIBRARIES}
1628     )
1629
1630   # We need to set the linker language based on what the expected generated file
1631   # would be. CUDA_C_OR_CXX is computed based on CUDA_HOST_COMPILATION_CPP.
1632   set_target_properties(${cuda_target}
1633     PROPERTIES
1634     LINKER_LANGUAGE ${CUDA_C_OR_CXX}
1635     )
1636
1637 endmacro()
1638
1639
1640 ###############################################################################
1641 ###############################################################################
1642 # (Internal) helper for manually added cuda source files with specific targets
1643 ###############################################################################
1644 ###############################################################################
1645 macro(cuda_compile_base cuda_target format generated_files)
1646
1647   # Separate the sources from the options
1648   CUDA_GET_SOURCES_AND_OPTIONS(_sources _cmake_options _options ${ARGN})
1649   # Create custom commands and targets for each file.
1650   CUDA_WRAP_SRCS( ${cuda_target} ${format} _generated_files ${_sources} ${_cmake_options}
1651     OPTIONS ${_options} )
1652
1653   set( ${generated_files} ${_generated_files})
1654
1655 endmacro()
1656
1657 ###############################################################################
1658 ###############################################################################
1659 # CUDA COMPILE
1660 ###############################################################################
1661 ###############################################################################
1662 macro(CUDA_COMPILE generated_files)
1663   cuda_compile_base(cuda_compile OBJ ${generated_files} ${ARGN})
1664 endmacro()
1665
1666 ###############################################################################
1667 ###############################################################################
1668 # CUDA COMPILE PTX
1669 ###############################################################################
1670 ###############################################################################
1671 macro(CUDA_COMPILE_PTX generated_files)
1672   cuda_compile_base(cuda_compile_ptx PTX ${generated_files} ${ARGN})
1673 endmacro()
1674
1675 ###############################################################################
1676 ###############################################################################
1677 # CUDA COMPILE FATBIN
1678 ###############################################################################
1679 ###############################################################################
1680 macro(CUDA_COMPILE_FATBIN generated_files)
1681   cuda_compile_base(cuda_compile_fatbin FATBIN ${generated_files} ${ARGN})
1682 endmacro()
1683
1684 ###############################################################################
1685 ###############################################################################
1686 # CUDA COMPILE CUBIN
1687 ###############################################################################
1688 ###############################################################################
1689 macro(CUDA_COMPILE_CUBIN generated_files)
1690   cuda_compile_base(cuda_compile_cubin CUBIN ${generated_files} ${ARGN})
1691 endmacro()
1692
1693
1694 ###############################################################################
1695 ###############################################################################
1696 # CUDA ADD CUFFT TO TARGET
1697 ###############################################################################
1698 ###############################################################################
1699 macro(CUDA_ADD_CUFFT_TO_TARGET target)
1700   if (CUDA_BUILD_EMULATION)
1701     target_link_libraries(${target} LINK_PRIVATE ${CUDA_cufftemu_LIBRARY})
1702   else()
1703     target_link_libraries(${target} LINK_PRIVATE ${CUDA_cufft_LIBRARY})
1704   endif()
1705 endmacro()
1706
1707 ###############################################################################
1708 ###############################################################################
1709 # CUDA ADD CUBLAS TO TARGET
1710 ###############################################################################
1711 ###############################################################################
1712 macro(CUDA_ADD_CUBLAS_TO_TARGET target)
1713   if (CUDA_BUILD_EMULATION)
1714     target_link_libraries(${target} LINK_PRIVATE ${CUDA_cublasemu_LIBRARY})
1715   else()
1716     target_link_libraries(${target} LINK_PRIVATE ${CUDA_cublas_LIBRARY})
1717   endif()
1718 endmacro()
1719
1720 ###############################################################################
1721 ###############################################################################
1722 # CUDA BUILD CLEAN TARGET
1723 ###############################################################################
1724 ###############################################################################
1725 macro(CUDA_BUILD_CLEAN_TARGET)
1726   # Call this after you add all your CUDA targets, and you will get a convenience
1727   # target.  You should also make clean after running this target to get the
1728   # build system to generate all the code again.
1729
1730   set(cuda_clean_target_name clean_cuda_depends)
1731   if (CMAKE_GENERATOR MATCHES "Visual Studio")
1732     string(TOUPPER ${cuda_clean_target_name} cuda_clean_target_name)
1733   endif()
1734   add_custom_target(${cuda_clean_target_name}
1735     COMMAND ${CMAKE_COMMAND} -E remove ${CUDA_ADDITIONAL_CLEAN_FILES})
1736
1737   # Clear out the variable, so the next time we configure it will be empty.
1738   # This is useful so that the files won't persist in the list after targets
1739   # have been removed.
1740   set(CUDA_ADDITIONAL_CLEAN_FILES "" CACHE INTERNAL "List of intermediate files that are part of the cuda dependency scanning.")
1741 endmacro()