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