Debian Codegraph @

mesonbuild/compilers/cuda.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2012-2017 The Meson development team
3 # Copyright © 2023-2025 Intel Corporation
4
5 from __future__ import annotations
6
7 import enum
8 import string
9 import typing as T
10
11 from .. import options
12 from ..mesonlib import is_windows, LibType, version_compare
13 from .compilers import Compiler, CompileCheckMode, CrossNoRunException, SimplePrefixLinkerOptionStyle
14
15 if T.TYPE_CHECKING:
16 from ..build import BuildTarget
17 from ..options import MutableKeyedOptionDictType
18 from ..dependencies import Dependency
19 from ..environment import Environment # noqa: F401
20 from ..linkers.linkers import DynamicLinker
21 from ..mesonlib import MachineChoice
22
23
24 cuda_optimization_args: T.Dict[str, T.List[str]] = {
25 'plain': [],
26 '0': ['-G'],
27 'g': ['-O0'],
28 '1': ['-O1'],
29 '2': ['-O2', '-lineinfo'],
30 '3': ['-O3'],
31 's': ['-O3']
32 }
33
34 cuda_debug_args: T.Dict[bool, T.List[str]] = {
35 False: [],
36 True: ['-g']
37 }
38
39
40 class Phase(enum.Enum):
41
42 COMPILER = 'compiler'
43 LINKER = 'linker'
44
45
46 class CudaCompiler(Compiler):
47
48 LINKER_OPTION_STYLE = SimplePrefixLinkerOptionStyle('-Xlinker=')
49 language = 'cuda'
50
51 # NVCC flags taking no arguments.
52 _FLAG_PASSTHRU_NOARGS = {
53 # NVCC --long-option, NVCC -short-option CUDA Toolkit 11.2.1 Reference
54 '--objdir-as-tempdir', '-objtemp', # 4.2.1.2
55 '--generate-dependency-targets', '-MP', # 4.2.1.12
56 '--allow-unsupported-compiler', '-allow-unsupported-compiler', # 4.2.1.14
57 '--link', # 4.2.2.1
58 '--lib', '-lib', # 4.2.2.2
59 '--device-link', '-dlink', # 4.2.2.3
60 '--device-c', '-dc', # 4.2.2.4
61 '--device-w', '-dw', # 4.2.2.5
62 '--cuda', '-cuda', # 4.2.2.6
63 '--compile', '-c', # 4.2.2.7
64 '--fatbin', '-fatbin', # 4.2.2.8
65 '--cubin', '-cubin', # 4.2.2.9
66 '--ptx', '-ptx', # 4.2.2.10
67 '--preprocess', '-E', # 4.2.2.11
68 '--generate-dependencies', '-M', # 4.2.2.12
69 '--generate-nonsystem-dependencies', '-MM', # 4.2.2.13
70 '--generate-dependencies-with-compile', '-MD', # 4.2.2.14
71 '--generate-nonsystem-dependencies-with-compile', '-MMD', # 4.2.2.15
72 '--run', # 4.2.2.16
73 '--profile', '-pg', # 4.2.3.1
74 '--debug', '-g', # 4.2.3.2
75 '--device-debug', '-G', # 4.2.3.3
76 '--extensible-whole-program', '-ewp', # 4.2.3.4
77 '--generate-line-info', '-lineinfo', # 4.2.3.5
78 '--dlink-time-opt', '-dlto', # 4.2.3.8
79 '--no-exceptions', '-noeh', # 4.2.3.11
80 '--shared', '-shared', # 4.2.3.12
81 '--no-host-device-initializer-list', '-nohdinitlist', # 4.2.3.15
82 '--expt-relaxed-constexpr', '-expt-relaxed-constexpr', # 4.2.3.16
83 '--extended-lambda', '-extended-lambda', # 4.2.3.17
84 '--expt-extended-lambda', '-expt-extended-lambda', # 4.2.3.18
85 '--m32', '-m32', # 4.2.3.20
86 '--m64', '-m64', # 4.2.3.21
87 '--forward-unknown-to-host-compiler', '-forward-unknown-to-host-compiler', # 4.2.5.1
88 '--forward-unknown-to-host-linker', '-forward-unknown-to-host-linker', # 4.2.5.2
89 '--dont-use-profile', '-noprof', # 4.2.5.3
90 '--dryrun', '-dryrun', # 4.2.5.5
91 '--verbose', '-v', # 4.2.5.6
92 '--keep', '-keep', # 4.2.5.7
93 '--save-temps', '-save-temps', # 4.2.5.9
94 '--clean-targets', '-clean', # 4.2.5.10
95 '--no-align-double', # 4.2.5.16
96 '--no-device-link', '-nodlink', # 4.2.5.17
97 '--allow-unsupported-compiler', '-allow-unsupported-compiler', # 4.2.5.18
98 '--use_fast_math', '-use_fast_math', # 4.2.7.7
99 '--extra-device-vectorization', '-extra-device-vectorization', # 4.2.7.12
100 '--compile-as-tools-patch', '-astoolspatch', # 4.2.7.13
101 '--keep-device-functions', '-keep-device-functions', # 4.2.7.14
102 '--disable-warnings', '-w', # 4.2.8.1
103 '--source-in-ptx', '-src-in-ptx', # 4.2.8.2
104 '--restrict', '-restrict', # 4.2.8.3
105 '--Wno-deprecated-gpu-targets', '-Wno-deprecated-gpu-targets', # 4.2.8.4
106 '--Wno-deprecated-declarations', '-Wno-deprecated-declarations', # 4.2.8.5
107 '--Wreorder', '-Wreorder', # 4.2.8.6
108 '--Wdefault-stream-launch', '-Wdefault-stream-launch', # 4.2.8.7
109 '--Wext-lambda-captures-this', '-Wext-lambda-captures-this', # 4.2.8.8
110 '--display-error-number', '-err-no', # 4.2.8.10
111 '--resource-usage', '-res-usage', # 4.2.8.14
112 '--help', '-h', # 4.2.8.15
113 '--version', '-V', # 4.2.8.16
114 '--list-gpu-code', '-code-ls', # 4.2.8.20
115 '--list-gpu-arch', '-arch-ls', # 4.2.8.21
116 }
117 # Dictionary of NVCC flags taking either one argument or a comma-separated list.
118 # Maps --long to -short options, because the short options are more GCC-like.
119 _FLAG_LONG2SHORT_WITHARGS = {
120 '--output-file': '-o', # 4.2.1.1
121 '--pre-include': '-include', # 4.2.1.3
122 '--library': '-l', # 4.2.1.4
123 '--define-macro': '-D', # 4.2.1.5
124 '--undefine-macro': '-U', # 4.2.1.6
125 '--include-path': '-I', # 4.2.1.7
126 '--system-include': '-isystem', # 4.2.1.8
127 '--library-path': '-L', # 4.2.1.9
128 '--output-directory': '-odir', # 4.2.1.10
129 '--dependency-output': '-MF', # 4.2.1.11
130 '--compiler-bindir': '-ccbin', # 4.2.1.13
131 '--archiver-binary': '-arbin', # 4.2.1.15
132 '--cudart': '-cudart', # 4.2.1.16
133 '--cudadevrt': '-cudadevrt', # 4.2.1.17
134 '--libdevice-directory': '-ldir', # 4.2.1.18
135 '--target-directory': '-target-dir', # 4.2.1.19
136 '--optimization-info': '-opt-info', # 4.2.3.6
137 '--optimize': '-O', # 4.2.3.7
138 '--ftemplate-backtrace-limit': '-ftemplate-backtrace-limit', # 4.2.3.9
139 '--ftemplate-depth': '-ftemplate-depth', # 4.2.3.10
140 '--x': '-x', # 4.2.3.13
141 '--std': '-std', # 4.2.3.14
142 '--machine': '-m', # 4.2.3.19
143 '--compiler-options': '-Xcompiler', # 4.2.4.1
144 '--linker-options': '-Xlinker', # 4.2.4.2
145 '--archive-options': '-Xarchive', # 4.2.4.3
146 '--ptxas-options': '-Xptxas', # 4.2.4.4
147 '--nvlink-options': '-Xnvlink', # 4.2.4.5
148 '--threads': '-t', # 4.2.5.4
149 '--keep-dir': '-keep-dir', # 4.2.5.8
150 '--run-args': '-run-args', # 4.2.5.11
151 '--input-drive-prefix': '-idp', # 4.2.5.12
152 '--dependency-drive-prefix': '-ddp', # 4.2.5.13
153 '--drive-prefix': '-dp', # 4.2.5.14
154 '--dependency-target-name': '-MT', # 4.2.5.15
155 '--default-stream': '-default-stream', # 4.2.6.1
156 '--gpu-architecture': '-arch', # 4.2.7.1
157 '--gpu-code': '-code', # 4.2.7.2
158 '--generate-code': '-gencode', # 4.2.7.3
159 '--relocatable-device-code': '-rdc', # 4.2.7.4
160 '--entries': '-e', # 4.2.7.5
161 '--maxrregcount': '-maxrregcount', # 4.2.7.6
162 '--ftz': '-ftz', # 4.2.7.8
163 '--prec-div': '-prec-div', # 4.2.7.9
164 '--prec-sqrt': '-prec-sqrt', # 4.2.7.10
165 '--fmad': '-fmad', # 4.2.7.11
166 '--Werror': '-Werror', # 4.2.8.9
167 '--diag-error': '-diag-error', # 4.2.8.11
168 '--diag-suppress': '-diag-suppress', # 4.2.8.12
169 '--diag-warn': '-diag-warn', # 4.2.8.13
170 '--options-file': '-optf', # 4.2.8.17
171 '--time': '-time', # 4.2.8.18
172 '--qpp-config': '-qpp-config', # 4.2.8.19
173 }
174 # Reverse map -short to --long options.
175 _FLAG_SHORT2LONG_WITHARGS = {v: k for k, v in _FLAG_LONG2SHORT_WITHARGS.items()}
176
177 id = 'nvcc'
178
179 def __init__(self, ccache: T.List[str], exelist: T.List[str], version: str, for_machine: MachineChoice,
180 host_compiler: Compiler, env: Environment,
181 linker: T.Optional['DynamicLinker'] = None,
182 full_version: T.Optional[str] = None):
183 self.detected_cc = ''
184 super().__init__(ccache, exelist, version, for_machine, env, linker=linker, full_version=full_version)
185 self.host_compiler = host_compiler
186 self.base_options = host_compiler.base_options
187 # -Wpedantic generates useless churn due to nvcc's dual compilation model producing
188 # a temporary host C++ file that includes gcc-style line directives:
189 # https://stackoverflow.com/a/31001220
190 self.warn_args = {
191 level: self._to_host_flags(list(f for f in flags if f != '-Wpedantic'))
192 for level, flags in host_compiler.warn_args.items()
193 }
194 self.host_werror_args = ['-Xcompiler=' + x for x in self.host_compiler.get_werror_args()]
195 self.debug_macros_available = version_compare(self.version, '>=12.9')
196
197 @classmethod
198 def _shield_nvcc_list_arg(cls, arg: str, listmode: bool = True) -> str:
199 r"""
200 Shield an argument against both splitting by NVCC's list-argument
201 parse logic, and interpretation by any shell.
202
203 NVCC seems to consider every comma , that is neither escaped by \ nor inside
204 a double-quoted string a split-point. Single-quotes do not provide protection
205 against splitting; In fact, after splitting they are \-escaped. Unfortunately,
206 double-quotes don't protect against shell expansion. What follows is a
207 complex dance to accommodate everybody.
208 """
209
210 SQ = "'"
211 DQ = '"'
212 CM = ","
213 BS = "\\"
214 DQSQ = DQ+SQ+DQ
215 quotable = set(string.whitespace+'"$`\\')
216
217 if CM not in arg or not listmode:
218 if SQ not in arg:
219 # If any of the special characters "$`\ or whitespace are present, single-quote.
220 # Otherwise return bare.
221 if set(arg).intersection(quotable):
222 return SQ+arg+SQ
223 else:
224 return arg # Easy case: no splits, no quoting.
225 else:
226 # There are single quotes. Double-quote them, and single-quote the
227 # strings between them.
228 l = [cls._shield_nvcc_list_arg(s) for s in arg.split(SQ)]
229 l = sum([[s, DQSQ] for s in l][:-1], []) # Interleave l with DQSQs
230 return ''.join(l)
231 else:
232 # A comma is present, and list mode was active.
233 # We apply (what we guess is) the (primitive) NVCC splitting rule:
234 l = ['']
235 instring = False
236 argit = iter(arg)
237 for c in argit:
238 if c == CM and not instring:
239 l.append('')
240 elif c == DQ:
241 l[-1] += c
242 instring = not instring
243 elif c == BS:
244 try:
245 l[-1] += next(argit)
246 except StopIteration:
247 break
248 else:
249 l[-1] += c
250
251 # Shield individual strings, without listmode, then return them with
252 # escaped commas between them.
253 l = [cls._shield_nvcc_list_arg(s, listmode=False) for s in l]
254 return r'\,'.join(l)
255
256 @classmethod
257 def _merge_flags(cls, flags: T.List[str]) -> T.List[str]:
258 r"""
259 The flags to NVCC gets exceedingly verbose and unreadable when too many of them
260 are shielded with -Xcompiler. Merge consecutive -Xcompiler-wrapped arguments
261 into one.
262 """
263 if len(flags) <= 1:
264 return flags
265 flagit = iter(flags)
266 xflags = []
267
268 def is_xcompiler_flag_isolated(flag: str) -> bool:
269 return flag == '-Xcompiler'
270
271 def is_xcompiler_flag_glued(flag: str) -> bool:
272 return flag.startswith('-Xcompiler=')
273
274 def is_xcompiler_flag(flag: str) -> bool:
275 return is_xcompiler_flag_isolated(flag) or is_xcompiler_flag_glued(flag)
276
277 def get_xcompiler_val(flag: str, flagit: T.Iterator[str]) -> str:
278 if is_xcompiler_flag_glued(flag):
279 return flag[len('-Xcompiler='):]
280 else:
281 try:
282 return next(flagit)
283 except StopIteration:
284 return ""
285
286 ingroup = False
287 for flag in flagit:
288 if not is_xcompiler_flag(flag):
289 ingroup = False
290 xflags.append(flag)
291 elif ingroup:
292 xflags[-1] += ','
293 xflags[-1] += get_xcompiler_val(flag, flagit)
294 elif is_xcompiler_flag_isolated(flag):
295 ingroup = True
296 xflags.append(flag)
297 xflags.append(get_xcompiler_val(flag, flagit))
298 elif is_xcompiler_flag_glued(flag):
299 ingroup = True
300 xflags.append(flag)
301 else:
302 raise ValueError("-Xcompiler flag merging failed, unknown argument form!")
303 return xflags
304
305 @classmethod
306 def to_host_flags_base(cls, flags: T.List[str], phase: Phase = Phase.COMPILER, default_include_dirs: T.Optional[T.List[str]] = None) -> T.List[str]:
307 """
308 Translate generic "GCC-speak" plus particular "NVCC-speak" flags to NVCC flags.
309
310 NVCC's "short" flags have broad similarities to the GCC standard, but have
311 gratuitous, irritating differences.
312 """
313 xflags = []
314 flagit = iter(flags)
315
316 for flag in flagit:
317 # The CUDA Toolkit Documentation, in 4.1. Command Option Types and Notation,
318 # specifies that NVCC does not parse the standard flags as GCC does. It has
319 # its own strategy, to wit:
320 #
321 # nvcc recognizes three types of command options: boolean options, single
322 # value options, and list options.
323 #
324 # Boolean options do not have an argument; they are either specified on a
325 # command line or not. Single value options must be specified at most once,
326 # and list options may be repeated. Examples of each of these option types
327 # are, respectively: --verbose (switch to verbose mode), --output-file
328 # (specify output file), and --include-path (specify include path).
329 #
330 # Single value options and list options must have arguments, which must
331 # follow the name of the option itself by either one of more spaces or an
332 # equals character. When a one-character short name such as -I, -l, and -L
333 # is used, the value of the option may also immediately follow the option
334 # itself without being separated by spaces or an equal character. The
335 # individual values of list options may be separated by commas in a single
336 # instance of the option, or the option may be repeated, or any
337 # combination of these two cases.
338 #
339 # One strange consequence of this choice is that directory and filenames that
340 # contain commas (',') cannot be passed to NVCC (at least, not as easily as
341 # in GCC). Another strange consequence is that it is legal to supply flags
342 # such as
343 #
344 # -lpthread,rt,dl,util
345 # -l pthread,rt,dl,util
346 # -l=pthread,rt,dl,util
347 #
348 # and each of the above alternatives is equivalent to GCC-speak
349 #
350 # -lpthread -lrt -ldl -lutil
351 # -l pthread -l rt -l dl -l util
352 # -l=pthread -l=rt -l=dl -l=util
353 #
354 # *With the exception of commas in the name*, GCC-speak for these list flags
355 # is a strict subset of NVCC-speak, so we passthrough those flags.
356 #
357 # The -D macro-define flag is documented as somehow shielding commas from
358 # splitting a definition. Balanced parentheses, braces and single-quotes
359 # around the comma are not sufficient, but balanced double-quotes are. The
360 # shielding appears to work with -l, -I, -L flags as well, for instance.
361 #
362 # Since our goal is to replicate GCC-speak as much as possible, we check for
363 # commas in all list-arguments and shield them with double-quotes. We make
364 # an exception for -D (where this would be value-changing) and -U (because
365 # it isn't possible to define a macro with a comma in the name).
366
367 if flag in cls._FLAG_PASSTHRU_NOARGS:
368 xflags.append(flag)
369 continue
370
371 # Handle breakup of flag-values into a flag-part and value-part.
372 if flag[:1] not in '-/':
373 # This is not a flag. It's probably a file input. Pass it through.
374 xflags.append(flag)
375 continue
376 elif flag[:1] == '/':
377 # This is ambiguously either an MVSC-style /switch or an absolute path
378 # to a file. For some magical reason the following works acceptably in
379 # both cases.
380 # We only want to prefix arguments that are NOT static archives, since
381 # the latter could contain relocatable device code (-dc/-rdc=true).
382 prefix = '' if flag.endswith('.a') else f'-X{phase.value}='
383 wrap = '"' if ',' in flag else ''
384 xflags.append(f'{prefix}{wrap}{flag}{wrap}')
385 continue
386 elif len(flag) >= 2 and flag[0] == '-' and flag[1] in 'IDULlmOxmte':
387 # This is a single-letter short option. These options (with the
388 # exception of -o) are allowed to receive their argument with neither
389 # space nor = sign before them. Detect and separate them in that event.
390 if flag[2:3] == '': # -I something
391 try:
392 val = next(flagit)
393 except StopIteration:
394 pass
395 elif flag[2:3] == '=': # -I=something
396 val = flag[3:]
397 else: # -Isomething
398 val = flag[2:]
399 flag = flag[:2] # -I
400 elif flag in cls._FLAG_LONG2SHORT_WITHARGS or \
401 flag in cls._FLAG_SHORT2LONG_WITHARGS:
402 # This is either -o or a multi-letter flag, and it is receiving its
403 # value isolated.
404 try:
405 val = next(flagit) # -o something
406 except StopIteration:
407 pass
408 elif flag.split('=', 1)[0] in cls._FLAG_LONG2SHORT_WITHARGS or \
409 flag.split('=', 1)[0] in cls._FLAG_SHORT2LONG_WITHARGS:
410 # This is either -o or a multi-letter flag, and it is receiving its
411 # value after an = sign.
412 flag, val = flag.split('=', 1) # -o=something
413 # Some dependencies (e.g., BoostDependency) add unspaced "-isystem/usr/include" arguments
414 elif flag.startswith('-isystem'):
415 val = flag[8:].strip()
416 flag = flag[:8]
417 else:
418 # This is a flag, and it's foreign to NVCC.
419 #
420 # We do not know whether this GCC-speak flag takes an isolated
421 # argument. Assuming it does not (the vast majority indeed don't),
422 # wrap this argument in an -Xcompiler flag and send it down to NVCC.
423 if flag == '-ffast-math':
424 xflags.append('-use_fast_math')
425 xflags.append('-Xcompiler='+flag)
426 elif flag == '-fno-fast-math':
427 xflags.append('-ftz=false')
428 xflags.append('-prec-div=true')
429 xflags.append('-prec-sqrt=true')
430 xflags.append('-Xcompiler='+flag)
431 elif flag == '-freciprocal-math':
432 xflags.append('-prec-div=false')
433 xflags.append('-Xcompiler='+flag)
434 elif flag == '-fno-reciprocal-math':
435 xflags.append('-prec-div=true')
436 xflags.append('-Xcompiler='+flag)
437 else:
438 xflags.append('-Xcompiler='+cls._shield_nvcc_list_arg(flag))
439 # The above should securely handle GCC's -Wl, -Wa, -Wp, arguments.
440 continue
441
442 assert val is not None # Should only trip if there is a missing argument.
443
444 # Take care of the various NVCC-supported flags that need special handling.
445 flag = cls._FLAG_LONG2SHORT_WITHARGS.get(flag, flag)
446
447 if flag in {'-include', '-isystem', '-I', '-L', '-l'}:
448 # These flags are known to GCC, but list-valued in NVCC. They potentially
449 # require double-quoting to prevent NVCC interpreting the flags as lists
450 # when GCC would not have done so.
451 #
452 # We avoid doing this quoting for -D to avoid redefining macros and for
453 # -U because it isn't possible to define a macro with a comma in the name.
454 # -U with comma arguments is impossible in GCC-speak (and thus unambiguous
455 #in NVCC-speak, albeit unportable).
456 if len(flag) == 2:
457 xflags.append(flag+cls._shield_nvcc_list_arg(val))
458 elif flag == '-isystem' and default_include_dirs is not None and val in default_include_dirs:
459 # like GnuLikeCompiler, we have to filter out include directories specified
460 # with -isystem that overlap with the host compiler's search path
461 pass
462 else:
463 xflags.append(flag)
464 xflags.append(cls._shield_nvcc_list_arg(val))
465 elif flag == '-O':
466 # Handle optimization levels GCC knows about that NVCC does not.
467 if val == 'fast':
468 xflags.append('-O3')
469 xflags.append('-use_fast_math')
470 xflags.append('-Xcompiler')
471 xflags.append(flag+val)
472 elif val in {'s', 'g', 'z'}:
473 xflags.append('-Xcompiler')
474 xflags.append(flag+val)
475 else:
476 xflags.append(flag+val)
477 elif flag in {'-D', '-U', '-m', '-t'}:
478 xflags.append(flag+val) # For style, keep glued.
479 elif flag in {'-std'}:
480 xflags.append(flag+'='+val) # For style, keep glued.
481 else:
482 xflags.append(flag)
483 xflags.append(val)
484
485 return cls._merge_flags(xflags)
486
487 def _to_host_flags(self, flags: T.List[str], phase: Phase = Phase.COMPILER) -> T.List[str]:
488 return self.to_host_flags_base(flags, phase, self.host_compiler.get_default_include_dirs())
489
490 def needs_static_linker(self) -> bool:
491 return False
492
493 def thread_link_flags(self) -> T.List[str]:
494 return self._to_host_flags(self.host_compiler.thread_link_flags(), Phase.LINKER)
495
496 def init_from_options(self) -> None:
497 super().init_from_options()
498 try:
499 res = self.run(self._sanity_check_source_code())
500 if res.returncode == 0:
501 self.detected_cc = res.stdout.strip()
502 except CrossNoRunException:
503 pass
504
505 def _sanity_check_source_code(self) -> str:
506 return r'''
507 #include <cuda_runtime.h>
508 #include <stdio.h>
509
510 __global__ void kernel (void) {}
511
512 int main(void){
513 struct cudaDeviceProp prop;
514 int count, i;
515 cudaError_t ret = cudaGetDeviceCount(&count);
516 if(ret != cudaSuccess){
517 fprintf(stderr, "%d\n", (int)ret);
518 }else{
519 for(i=0;i<count;i++){
520 if(cudaGetDeviceProperties(&prop, i) == cudaSuccess){
521 fprintf(stdout, "%d.%d\n", prop.major, prop.minor);
522 }
523 }
524 }
525 fflush(stderr);
526 fflush(stdout);
527 return 0;
528 }
529 '''
530
531 def _sanity_check_compile_args(self, sourcename: str, binname: str
532 ) -> T.Tuple[T.List[str], T.List[str]]:
533 # Disable warnings, compile with statically-linked runtime for minimum
534 # reliance on the system.
535 flags = ['-w', '-cudart', 'static', sourcename]
536
537 # Use the -ccbin option, if available, even during sanity checking.
538 # Otherwise, on systems where CUDA does not support the default compiler,
539 # NVCC becomes unusable.
540 flags += self._get_ccbin_args(None, '')
541
542 # If cross-compiling, we can't run the sanity check, only compile it.
543 if self.is_cross and not self.environment.has_exe_wrapper():
544 # Linking cross built apps is painful. You can't really
545 # tell if you should use -nostdlib or not and for example
546 # on OSX the compiler binary is the same but you need
547 # a ton of compiler flags to differentiate between
548 # arm and x86_64. So just compile.
549 flags += self.get_compile_only_args()
550 flags += self.get_output_args(binname)
551
552 return self.exelist + flags, []
553
554 def has_header_symbol(self, hname: str, symbol: str, prefix: str, *,
555 extra_args: T.Union[None, T.List[str], T.Callable[[CompileCheckMode], T.List[str]]] = None,
556 dependencies: T.Optional[T.List['Dependency']] = None) -> T.Tuple[bool, bool]:
557 if extra_args is None:
558 extra_args = []
559 fargs = {'prefix': prefix, 'header': hname, 'symbol': symbol}
560 # Check if it's a C-like symbol
561 t = '''{prefix}
562 #include <{header}>
563 int main(void) {{
564 /* If it's not defined as a macro, try to use as a symbol */
565 #ifndef {symbol}
566 {symbol};
567 #endif
568 return 0;
569 }}'''
570 found, cached = self.compiles(t.format_map(fargs), extra_args=extra_args, dependencies=dependencies)
571 if found:
572 return True, cached
573 # Check if it's a class or a template
574 t = '''{prefix}
575 #include <{header}>
576 using {symbol};
577 int main(void) {{
578 return 0;
579 }}'''
580 return self.compiles(t.format_map(fargs), extra_args=extra_args, dependencies=dependencies)
581
582 _CPP14_VERSION = '>=9.0'
583 _CPP17_VERSION = '>=11.0'
584 _CPP20_VERSION = '>=12.0'
585
586 def get_options(self) -> 'MutableKeyedOptionDictType':
587 cpp_stds = ['none', 'c++03', 'c++11']
588 if version_compare(self.version, self._CPP14_VERSION):
589 cpp_stds += ['c++14']
590 if version_compare(self.version, self._CPP17_VERSION):
591 cpp_stds += ['c++17']
592 if version_compare(self.version, self._CPP20_VERSION):
593 cpp_stds += ['c++20']
594
595 opts = super().get_options()
596
597 key = self.form_compileropt_key('std')
598 opts[key] = options.UserComboOption(
599 self.make_option_name(key),
600 'C++ language standard to use with CUDA',
601 'none',
602 choices=cpp_stds)
603
604 key = self.form_compileropt_key('ccbindir')
605 opts[key] = options.UserStringOption(
606 self.make_option_name(key),
607 'CUDA non-default toolchain directory to use (-ccbin)',
608 '')
609
610 return opts
611
612 def get_option_compile_args(self, target: 'BuildTarget', subproject: T.Optional[str] = None) -> T.List[str]:
613 args = self._get_ccbin_args(target, subproject)
614
615 try:
616 host_compiler_args = self.host_compiler.get_option_compile_args(target, subproject)
617 except KeyError:
618 host_compiler_args = []
619 return args + self._to_host_flags(host_compiler_args)
620
621 def get_option_std_args(self, target: BuildTarget, subproject: T.Optional[str] = None) -> T.List[str]:
622 # On Windows, the version of the C++ standard used by nvcc is dictated by
623 # the combination of CUDA version and MSVC version; the --std= is thus ignored
624 # and attempting to use it will result in a warning: https://stackoverflow.com/a/51272091/741027
625 if not is_windows():
626 std = self.get_compileropt_value('std', target, subproject)
627 assert isinstance(std, str)
628 if std != 'none':
629 return ['--std=' + std]
630
631 try:
632 host_compiler_args = self.host_compiler.get_option_std_args(target, subproject)
633 except KeyError:
634 host_compiler_args = []
635 return self._to_host_flags(host_compiler_args)
636
637 def get_option_link_args(self, target: 'BuildTarget', subproject: T.Optional[str] = None) -> T.List[str]:
638 args = self._get_ccbin_args(target, subproject)
639 return args + self._to_host_flags(self.host_compiler.get_option_link_args(target, subproject), Phase.LINKER)
640
641 def get_soname_args(self, prefix: str, shlib_name: str, suffix: str, soversion: str,
642 darwin_versions: T.Tuple[str, str]) -> T.List[str]:
643 return self._to_host_flags(self.host_compiler.get_soname_args(
644 prefix, shlib_name, suffix, soversion, darwin_versions), Phase.LINKER)
645
646 def get_compile_only_args(self) -> T.List[str]:
647 return ['-c']
648
649 def get_no_optimization_args(self) -> T.List[str]:
650 return ['-O0']
651
652 def get_optimization_args(self, optimization_level: str) -> T.List[str]:
653 # alternatively, consider simply redirecting this to the host compiler, which would
654 # give us more control over options like "optimize for space" (which nvcc doesn't support):
655 # return self._to_host_flags(self.host_compiler.get_optimization_args(optimization_level))
656 return cuda_optimization_args[optimization_level]
657
658 def sanitizer_compile_args(self, target: T.Optional[BuildTarget], value: T.List[str]) -> T.List[str]:
659 return self._to_host_flags(self.host_compiler.sanitizer_compile_args(target, value))
660
661 def sanitizer_link_args(self, target: T.Optional[BuildTarget], value: T.List[str]) -> T.List[str]:
662 return self._to_host_flags(self.host_compiler.sanitizer_link_args(target, value))
663
664 def get_debug_args(self, is_debug: bool) -> T.List[str]:
665 return cuda_debug_args[is_debug]
666
667 def get_werror_args(self) -> T.List[str]:
668 device_werror_args = ['-Werror=cross-execution-space-call,deprecated-declarations,reorder']
669 return device_werror_args + self.host_werror_args
670
671 def get_warn_args(self, level: str) -> T.List[str]:
672 return self.warn_args[level]
673
674 def get_include_args(self, path: str, is_system: bool) -> T.List[str]:
675 if path == '':
676 path = '.'
677 return ['-isystem=' + path] if is_system else ['-I' + path]
678
679 def get_compile_debugfile_args(self, rel_obj: str, pch: bool = False) -> T.List[str]:
680 return self._to_host_flags(self.host_compiler.get_compile_debugfile_args(rel_obj, pch))
681
682 def get_link_debugfile_args(self, targetfile: str) -> T.List[str]:
683 return self._to_host_flags(self.host_compiler.get_link_debugfile_args(targetfile), Phase.LINKER)
684
685 def get_depfile_suffix(self) -> str:
686 return 'd'
687
688 def get_optimization_link_args(self, optimization_level: str) -> T.List[str]:
689 return self._to_host_flags(self.host_compiler.get_optimization_link_args(optimization_level), Phase.LINKER)
690
691 def get_linker_fatal_warnings(self) -> T.List[str]:
692 return self._to_host_flags(self.host_compiler.get_linker_fatal_warnings(), Phase.LINKER)
693
694 def build_rpath_args(self, build_dir: str, from_dir: str, target: BuildTarget,
695 extra_paths: T.Optional[T.List[str]] = None
696 ) -> T.Tuple[T.List[str], T.Set[bytes]]:
697 (rpath_args, rpath_dirs_to_remove) = self.host_compiler.build_rpath_args(
698 build_dir, from_dir, target, extra_paths)
699 return (self._to_host_flags(rpath_args, Phase.LINKER), rpath_dirs_to_remove)
700
701 def linker_to_compiler_args(self, args: T.List[str]) -> T.List[str]:
702 return args
703
704 def get_pic_args(self) -> T.List[str]:
705 return self._to_host_flags(self.host_compiler.get_pic_args())
706
707 def compute_parameters_with_absolute_paths(self, parameter_list: T.List[str],
708 build_dir: str) -> T.List[str]:
709 return []
710
711 def get_output_args(self, target: str) -> T.List[str]:
712 return ['-o', target]
713
714 def get_dependency_gen_args(self, outtarget: str, outfile: str) -> T.List[str]:
715 if version_compare(self.version, '>= 10.2'):
716 # According to nvcc Documentation, `-MD` option is added after 10.2
717 # Reference: [CUDA 10.1](https://docs.nvidia.com/cuda/archive/10.1/cuda-compiler-driver-nvcc/index.html#options-for-specifying-compilation-phase-generate-nonsystem-dependencies)
718 # Reference: [CUDA 10.2](https://docs.nvidia.com/cuda/archive/10.2/cuda-compiler-driver-nvcc/index.html#options-for-specifying-compilation-phase-generate-nonsystem-dependencies)
719 return ['-MD', '-MT', outtarget, '-MF', outfile]
720 else:
721 return []
722
723 def get_std_exe_link_args(self) -> T.List[str]:
724 return self._to_host_flags(self.host_compiler.get_std_exe_link_args(), Phase.LINKER)
725
726 def find_library(self, libname: str, extra_dirs: T.List[str], libtype: LibType = LibType.PREFER_SHARED,
727 lib_prefix_warning: bool = True, ignore_system_dirs: bool = False,
728 skip_link_check: bool = False) -> T.Optional[T.List[str]]:
729 return self.host_compiler.find_library(libname, extra_dirs, libtype, lib_prefix_warning, ignore_system_dirs, skip_link_check)
730
731 def get_crt_compile_args(self, crt_val: str) -> T.List[str]:
732 return self._to_host_flags(self.host_compiler.get_crt_compile_args(crt_val))
733
734 def get_crt_link_args(self, crt_val: str) -> T.List[str]:
735 # nvcc defaults to static, release version of msvc runtime and provides no
736 # native option to override it; override it with /NODEFAULTLIB
737 host_link_arg_overrides = []
738 host_crt_compile_args = self.host_compiler.get_crt_compile_args(crt_val)
739 if any(arg in {'/MDd', '/MD', '/MTd'} for arg in host_crt_compile_args):
740 host_link_arg_overrides += ['/NODEFAULTLIB:LIBCMT.lib']
741 return self._to_host_flags(host_link_arg_overrides + self.host_compiler.get_crt_link_args(crt_val), Phase.LINKER)
742
743 def get_target_link_args(self, target: 'BuildTarget') -> T.List[str]:
744 return self._to_host_flags(super().get_target_link_args(target), Phase.LINKER)
745
746 def get_dependency_compile_args(self, dep: 'Dependency') -> T.List[str]:
747 return self._to_host_flags(super().get_dependency_compile_args(dep))
748
749 def get_dependency_link_args(self, dep: 'Dependency') -> T.List[str]:
750 return self._to_host_flags(super().get_dependency_link_args(dep), Phase.LINKER)
751
752 def _get_ccbin_args(self, target: 'T.Optional[BuildTarget]',
753 subproject: T.Optional[str] = None) -> T.List[str]:
754 key = self.form_compileropt_key('ccbindir').evolve(subproject=subproject)
755 if target:
756 ccbindir = self.environment.coredata.get_option_for_target(target, key)
757 else:
758 ccbindir = self.environment.coredata.optstore.get_value_for(key)
759 if isinstance(ccbindir, str) and ccbindir != '':
760 return [self._shield_nvcc_list_arg('-ccbin='+ccbindir, False)]
761 else:
762 return []
763
764 def get_profile_generate_args(self) -> T.List[str]:
765 return ['-Xcompiler=' + x for x in self.host_compiler.get_profile_generate_args()]
766
767 def get_profile_use_args(self) -> T.List[str]:
768 return ['-Xcompiler=' + x for x in self.host_compiler.get_profile_use_args()]
769
770 def get_assert_args(self, disable: bool) -> T.List[str]:
771 cccl_macros = []
772 if not disable and self.debug_macros_available:
773 # https://github.com/NVIDIA/cccl/pull/2382
774 cccl_macros = ['-DCCCL_ENABLE_ASSERTIONS=1']
775
776 return self.host_compiler.get_assert_args(disable) + cccl_macros
777
778 def has_multi_arguments(self, args: T.List[str]) -> T.Tuple[bool, bool]:
779 args = self._to_host_flags(args)
780 return self.compiles('int main(void) { return 0; }', extra_args=args, mode=CompileCheckMode.COMPILE)
781
782 def has_multi_link_arguments(self, args: T.List[str], to_host_args: bool = True) -> T.Tuple[bool, bool]:
783 if to_host_args:
784 args = self._to_host_flags(args, phase=Phase.LINKER)
785 args = ['-Xnvlink='+self._shield_nvcc_list_arg(s) for s in self.linker.fatal_warnings()] + args
786 return self.compiles('int main(void) { return 0; }', extra_args=args, mode=CompileCheckMode.LINK)