Debian Codegraph @

mesonbuild/compilers/mixins/gnu.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2019-2022 The meson development team
3 # Copyright © 2023-2025 Intel Corporation
4
5 from __future__ import annotations
6
7 """Provides mixins for GNU compilers and GNU-like compilers."""
8
9 import abc
10 import functools
11 import os
12 import pathlib
13 import re
14 import subprocess
15 import typing as T
16
17 from ... import mesonlib
18 from ... import mlog
19 from ...options import OptionKey, UserStdOption
20 from mesonbuild.compilers.compilers import CompileCheckMode, ManyInOneLinkerOptionStyle, PrefixArgumentLinkerOptionStyle
21
22 if T.TYPE_CHECKING:
23 from ..._typing import ImmutableListProtocol
24 from ...build import BuildTarget
25 from ...options import MutableKeyedOptionDictType
26 from ..compilers import Compiler
27 else:
28 # This is a bit clever, for mypy we pretend that these mixins descend from
29 # Compiler, so we get all of the methods and attributes defined for us, but
30 # for runtime we make them descend from object (which all classes normally
31 # do). This gives up DRYer type checking, with no runtime impact
32 Compiler = object
33
34 # XXX: prevent circular references.
35 # FIXME: this really is a posix interface not a c-like interface
36 clike_debug_args: T.Dict[bool, T.List[str]] = {
37 False: [],
38 True: ['-g'],
39 }
40
41 gnu_optimization_args: T.Dict[str, T.List[str]] = {
42 'plain': [],
43 '0': ['-O0'],
44 'g': ['-Og'],
45 '1': ['-O1'],
46 '2': ['-O2'],
47 '3': ['-O3'],
48 's': ['-Os'],
49 }
50
51 gnulike_instruction_set_args: T.Dict[str, T.List[str]] = {
52 'mmx': ['-mmmx'],
53 'sse': ['-msse'],
54 'sse2': ['-msse2'],
55 'sse3': ['-msse3'],
56 'ssse3': ['-mssse3'],
57 'sse41': ['-msse4.1'],
58 'sse42': ['-msse4.2'],
59 'avx': ['-mavx'],
60 'avx2': ['-mavx2'],
61 'neon': ['-mfpu=neon'],
62 }
63
64 gnu_symbol_visibility_args: T.Dict[str, T.List[str]] = {
65 '': [],
66 'default': ['-fvisibility=default'],
67 'internal': ['-fvisibility=internal'],
68 'hidden': ['-fvisibility=hidden'],
69 'protected': ['-fvisibility=protected'],
70 'inlineshidden': ['-fvisibility=hidden', '-fvisibility-inlines-hidden'],
71 }
72
73 gnu_color_args: T.Dict[str, T.List[str]] = {
74 'auto': ['-fdiagnostics-color=auto'],
75 'always': ['-fdiagnostics-color=always'],
76 'never': ['-fdiagnostics-color=never'],
77 }
78
79 # Warnings collected from the GCC source and documentation. This is an
80 # objective set of all the warnings flags that apply to general projects: the
81 # only ones omitted are those that require a project-specific value, or are
82 # related to non-standard or legacy language support. This behaves roughly
83 # like -Weverything in clang. Warnings implied by -Wall, -Wextra, or
84 # higher-level warnings already enabled here are not included in these lists to
85 # keep them as short as possible. History goes back to GCC 3.0.0, everything
86 # earlier is considered historical and listed under version 0.0.0.
87
88 # GCC warnings for all C-family languages
89 # Omitted non-general warnings:
90 # -Wabi=
91 # -Waggregate-return
92 # -Walloc-size-larger-than=BYTES
93 # -Walloca-larger-than=BYTES
94 # -Wframe-larger-than=BYTES
95 # -Wlarger-than=BYTES
96 # -Wstack-usage=BYTES
97 # -Wsystem-headers
98 # -Wtrampolines
99 # -Wvla-larger-than=BYTES
100 #
101 # Omitted warnings enabled elsewhere in meson:
102 # -Winvalid-pch (GCC 3.4.0)
103 gnu_common_warning_args: T.Dict[str, T.List[str]] = {
104 "0.0.0": [
105 "-Wcast-qual",
106 "-Wconversion",
107 "-Wfloat-equal",
108 "-Wformat=2",
109 "-Winline",
110 "-Wmissing-declarations",
111 "-Wredundant-decls",
112 "-Wshadow",
113 "-Wundef",
114 "-Wuninitialized",
115 "-Wwrite-strings",
116 ],
117 "3.0.0": [
118 "-Wdisabled-optimization",
119 "-Wpacked",
120 "-Wpadded",
121 ],
122 "3.3.0": [
123 "-Wmultichar",
124 "-Wswitch-default",
125 "-Wswitch-enum",
126 "-Wunused-macros",
127 ],
128 "4.0.0": [
129 "-Wmissing-include-dirs",
130 ],
131 "4.1.0": [
132 "-Wunsafe-loop-optimizations",
133 "-Wstack-protector",
134 ],
135 "4.2.0": [
136 "-Wstrict-overflow=5",
137 ],
138 "4.3.0": [
139 "-Warray-bounds=2",
140 "-Wlogical-op",
141 "-Wstrict-aliasing=3",
142 "-Wvla",
143 ],
144 "4.6.0": [
145 "-Wdouble-promotion",
146 "-Wsuggest-attribute=const",
147 "-Wsuggest-attribute=noreturn",
148 "-Wsuggest-attribute=pure",
149 "-Wtrampolines",
150 ],
151 "4.7.0": [
152 "-Wvector-operation-performance",
153 ],
154 "4.8.0": [
155 "-Wsuggest-attribute=format",
156 ],
157 "4.9.0": [
158 "-Wdate-time",
159 ],
160 "5.1.0": [
161 "-Wformat-signedness",
162 "-Wnormalized=nfc",
163 ],
164 "6.1.0": [
165 "-Wduplicated-cond",
166 "-Wnull-dereference",
167 "-Wshift-negative-value",
168 "-Wshift-overflow=2",
169 "-Wunused-const-variable=2",
170 ],
171 "7.1.0": [
172 "-Walloca",
173 "-Walloc-zero",
174 "-Wformat-overflow=2",
175 "-Wformat-truncation=2",
176 "-Wstringop-overflow=3",
177 ],
178 "7.2.0": [
179 "-Wduplicated-branches",
180 ],
181 "8.1.0": [
182 "-Wcast-align=strict",
183 "-Wsuggest-attribute=cold",
184 "-Wsuggest-attribute=malloc",
185 ],
186 "9.1.0": [
187 "-Wattribute-alias=2",
188 ],
189 "10.1.0": [
190 "-Wanalyzer-too-complex",
191 "-Warith-conversion",
192 ],
193 "12.1.0": [
194 "-Wbidi-chars=ucn",
195 "-Wopenacc-parallelism",
196 "-Wtrivial-auto-var-init",
197 ],
198 }
199
200 # GCC warnings for C
201 # Omitted non-general or legacy warnings:
202 # -Wc11-c2x-compat
203 # -Wc90-c99-compat
204 # -Wc99-c11-compat
205 # -Wdeclaration-after-statement
206 # -Wtraditional
207 # -Wtraditional-conversion
208 # -Wunsuffixed-float-constants
209 gnu_c_warning_args: T.Dict[str, T.List[str]] = {
210 "0.0.0": [
211 "-Wbad-function-cast",
212 "-Wmissing-prototypes",
213 "-Wnested-externs",
214 "-Wstrict-prototypes",
215 ],
216 "3.4.0": [
217 "-Wold-style-definition",
218 "-Winit-self",
219 ],
220 "4.1.0": [
221 "-Wc++-compat",
222 ],
223 }
224
225 # GCC warnings for C++
226 # Omitted non-general or legacy warnings:
227 # -Wc++0x-compat
228 # -Wc++1z-compat
229 # -Wc++2a-compat
230 # -Wctad-maybe-unsupported
231 # -Wnamespaces
232 # -Wtemplates
233 gnu_cpp_warning_args: T.Dict[str, T.List[str]] = {
234 "0.0.0": [
235 "-Wctor-dtor-privacy",
236 "-Weffc++",
237 "-Wnon-virtual-dtor",
238 "-Wold-style-cast",
239 "-Woverloaded-virtual",
240 "-Wsign-promo",
241 ],
242 "4.0.1": [
243 "-Wstrict-null-sentinel",
244 ],
245 "4.6.0": [
246 "-Wnoexcept",
247 ],
248 "4.7.0": [
249 "-Wzero-as-null-pointer-constant",
250 ],
251 "4.8.0": [
252 "-Wabi-tag",
253 "-Wuseless-cast",
254 ],
255 "4.9.0": [
256 "-Wconditionally-supported",
257 ],
258 "5.1.0": [
259 "-Wsuggest-final-methods",
260 "-Wsuggest-final-types",
261 "-Wsuggest-override",
262 ],
263 "6.1.0": [
264 "-Wmultiple-inheritance",
265 "-Wplacement-new=2",
266 "-Wvirtual-inheritance",
267 ],
268 "7.1.0": [
269 "-Waligned-new=all",
270 "-Wnoexcept-type",
271 "-Wregister",
272 ],
273 "8.1.0": [
274 "-Wcatch-value=3",
275 "-Wextra-semi",
276 ],
277 "9.1.0": [
278 "-Wdeprecated-copy-dtor",
279 "-Wredundant-move",
280 ],
281 "10.1.0": [
282 "-Wcomma-subscript",
283 "-Wmismatched-tags",
284 "-Wredundant-tags",
285 "-Wvolatile",
286 ],
287 "11.1.0": [
288 "-Wdeprecated-enum-enum-conversion",
289 "-Wdeprecated-enum-float-conversion",
290 "-Winvalid-imported-macros",
291 ],
292 }
293
294 # GCC warnings for Objective C and Objective C++
295 # Omitted non-general or legacy warnings:
296 # -Wtraditional
297 # -Wtraditional-conversion
298 gnu_objc_warning_args: T.Dict[str, T.List[str]] = {
299 "0.0.0": [
300 "-Wselector",
301 ],
302 "3.3": [
303 "-Wundeclared-selector",
304 ],
305 "4.1.0": [
306 "-Wassign-intercept",
307 "-Wstrict-selector-match",
308 ],
309 }
310
311 gnu_lang_map = {
312 'c': 'c',
313 'cpp': 'c++',
314 'objc': 'objective-c',
315 'objcpp': 'objective-c++'
316 }
317
318 @functools.lru_cache(maxsize=None)
319 def gnulike_default_include_dirs(compiler: T.Tuple[str, ...], lang: str) -> 'ImmutableListProtocol[str]':
320 if lang not in gnu_lang_map:
321 return []
322 lang = gnu_lang_map[lang]
323 env = os.environ.copy()
324 env["LC_ALL"] = 'C'
325 cmd = list(compiler) + [f'-x{lang}', '-E', '-v', '-']
326 _, stdout, _ = mesonlib.Popen_safe(cmd, stderr=subprocess.STDOUT, env=env)
327 parse_state = 0
328 paths: T.List[str] = []
329 for line in stdout.split('\n'):
330 line = line.strip(' \n\r\t')
331 if parse_state == 0:
332 if line == '#include "..." search starts here:':
333 parse_state = 1
334 elif parse_state == 1:
335 if line == '#include <...> search starts here:':
336 parse_state = 2
337 else:
338 paths.append(line)
339 elif parse_state == 2:
340 if line == 'End of search list.':
341 break
342 else:
343 paths.append(line)
344 if not paths:
345 mlog.warning('No include directory found parsing "{cmd}" output'.format(cmd=" ".join(cmd)))
346 # Append a normalized copy of paths to make path lookup easier
347 paths += [os.path.normpath(x) for x in paths]
348 return paths
349
350
351 class GnuLikeCompiler(Compiler, metaclass=mesonlib.SimpleABC):
352 """
353 GnuLikeCompiler is a common interface to all compilers implementing
354 the GNU-style commandline interface. This includes GCC, Clang
355 and ICC. Certain functionality between them is different and requires
356 that the actual concrete subclass define their own implementation.
357 """
358
359 LINKER_OPTION_STYLE = ManyInOneLinkerOptionStyle('-Wl,', ',',
360 fallback=PrefixArgumentLinkerOptionStyle('-Xlinker'))
361
362 def __init__(self) -> None:
363 self.base_options = {
364 OptionKey(o) for o in ['b_pch', 'b_lto', 'b_pgo', 'b_coverage',
365 'b_ndebug', 'b_staticpic', 'b_pie']}
366 if not (self.info.is_windows() or self.info.is_cygwin() or self.info.is_openbsd()):
367 self.base_options.add(OptionKey('b_lundef'))
368 if not self.info.is_windows() or self.info.is_cygwin():
369 self.base_options.add(OptionKey('b_asneeded'))
370 if not self.info.is_hurd():
371 self.base_options.add(OptionKey('b_sanitize'))
372 # All GCC-like backends can do assembly
373 self.can_compile_suffixes.add('s')
374 self.can_compile_suffixes.add('sx')
375
376 def get_pic_args(self) -> T.List[str]:
377 if self.info.is_windows() or self.info.is_cygwin() or self.info.is_darwin() or self.info.is_os2():
378 return [] # On Window, OS X and OS/2, pic is always on.
379 return ['-fPIC']
380
381 def get_pie_args(self) -> T.List[str]:
382 return ['-fPIE']
383
384 def get_cpp_permissive_args(self) -> T.List[str]:
385 return ['-fpermissive']
386
387 @abc.abstractmethod
388 def get_optimization_args(self, optimization_level: str) -> T.List[str]:
389 pass
390
391 def get_debug_args(self, is_debug: bool) -> T.List[str]:
392 return clike_debug_args[is_debug]
393
394 @abc.abstractmethod
395 def get_pch_suffix(self) -> str:
396 pass
397
398 def split_shlib_to_parts(self, fname: str) -> T.Tuple[str, str]:
399 return os.path.dirname(fname), fname
400
401 def get_instruction_set_args(self, instruction_set: str) -> T.Optional[T.List[str]]:
402 return gnulike_instruction_set_args.get(instruction_set, None)
403
404 def get_default_include_dirs(self) -> T.List[str]:
405 return gnulike_default_include_dirs(tuple(self.get_exelist(ccache=False)), self.language).copy()
406
407 @abc.abstractmethod
408 def openmp_flags(self) -> T.List[str]:
409 pass
410
411 def gnu_symbol_visibility_args(self, vistype: str) -> T.List[str]:
412 if vistype == 'inlineshidden' and self.language not in {'cpp', 'objcpp'}:
413 vistype = 'hidden'
414 return gnu_symbol_visibility_args[vistype]
415
416 @staticmethod
417 def get_argument_syntax() -> str:
418 return 'gcc'
419
420 def get_profile_generate_args(self) -> T.List[str]:
421 return ['-fprofile-generate']
422
423 def get_profile_use_args(self) -> T.List[str]:
424 return ['-fprofile-use']
425
426 def compute_parameters_with_absolute_paths(self, parameter_list: T.List[str], build_dir: str) -> T.List[str]:
427 for idx, i in enumerate(parameter_list):
428 if i[:2] == '-I' or i[:2] == '-L':
429 parameter_list[idx] = i[:2] + os.path.normpath(os.path.join(build_dir, i[2:]))
430
431 return parameter_list
432
433 @functools.lru_cache()
434 def _get_search_dirs(self) -> str:
435 extra_args = ['--print-search-dirs']
436 with self._build_wrapper('', extra_args=extra_args,
437 dependencies=None, mode=CompileCheckMode.COMPILE,
438 want_output=True) as p:
439 return p.stdout
440
441 def _split_fetch_real_dirs(self, pathstr: str) -> T.List[str]:
442 # We need to use the path separator used by the compiler for printing
443 # lists of paths ("gcc --print-search-dirs"). By default
444 # we assume it uses the platform native separator.
445 pathsep = os.pathsep
446
447 # clang uses ':' instead of ';' on Windows https://reviews.llvm.org/D61121
448 # so we need to repair things like 'C:\foo:C:\bar'
449 if pathsep == ';':
450 pathstr = re.sub(r':([^/\\])', r';\1', pathstr)
451
452 # pathlib treats empty paths as '.', so filter those out
453 paths = [p for p in pathstr.split(pathsep) if p]
454
455 result: T.List[str] = []
456 for p in paths:
457 # GCC returns paths like this:
458 # /usr/lib/gcc/x86_64-linux-gnu/8/../../../../x86_64-linux-gnu/lib
459 # It would make sense to normalize them to get rid of the .. parts
460 # Sadly when you are on a merged /usr fs it also kills these:
461 # /lib/x86_64-linux-gnu
462 # since /lib is a symlink to /usr/lib. This would mean
463 # paths under /lib would be considered not a "system path",
464 # which is wrong and breaks things. Store everything, just to be sure.
465 pobj = pathlib.Path(p)
466 if pobj.exists():
467 try:
468 resolved = pobj.resolve(True).as_posix()
469 if resolved not in result:
470 result.append(resolved)
471 except FileNotFoundError:
472 pass
473 unresolved = pobj.as_posix()
474 if unresolved not in result:
475 result.append(unresolved)
476 return result
477
478 def get_compiler_dirs(self, name: str) -> T.List[str]:
479 '''
480 Get dirs from the compiler, either `libraries:` or `programs:`
481 '''
482 stdo = self._get_search_dirs()
483 for line in stdo.split('\n'):
484 if line.startswith(name + ':'):
485 return self._split_fetch_real_dirs(line.split('=', 1)[1])
486 return []
487
488 def get_lto_compile_args(self, *, target: T.Optional[BuildTarget] = None, threads: int = 0,
489 mode: str = 'default') -> T.List[str]:
490 # This provides a base for many compilers, GCC and Clang override this
491 # for their specific arguments
492 return ['-flto']
493
494 def sanitizer_compile_args(self, target: T.Optional[BuildTarget], value: T.List[str]) -> T.List[str]:
495 if not value:
496 return value
497 args = ['-fsanitize=' + ','.join(value)]
498 if 'address' in value:
499 args.append('-fno-omit-frame-pointer')
500 return args
501
502 def get_output_args(self, outputname: str) -> T.List[str]:
503 return ['-o', outputname]
504
505 def get_dependency_gen_args(self, outtarget: str, outfile: str) -> T.List[str]:
506 return ['-MD', '-MQ', outtarget, '-MF', outfile]
507
508 def get_compile_only_args(self) -> T.List[str]:
509 return ['-c']
510
511 def get_include_args(self, path: str, is_system: bool) -> T.List[str]:
512 if not path:
513 path = '.'
514 if is_system:
515 return ['-isystem' + path]
516 return ['-I' + path]
517
518 @classmethod
519 def use_linker_args(cls, linker: str, version: str) -> T.List[str]:
520 if linker not in {'bfd', 'eld', 'gold', 'lld'}:
521 raise mesonlib.MesonException(
522 f'Unsupported linker, only bfd, eld, gold, and lld are supported, not {linker}.')
523 return [f'-fuse-ld={linker}']
524
525 def get_coverage_args(self) -> T.List[str]:
526 return ['--coverage']
527
528 def get_preprocess_to_file_args(self) -> T.List[str]:
529 # We want to allow preprocessing files with any extension, such as
530 # foo.c.in. In that case we need to tell GCC/CLANG to treat them as
531 # assembly file.
532 if self.language == 'fortran':
533 return self.get_preprocess_only_args()
534 lang = gnu_lang_map.get(self.language, 'assembler-with-cpp')
535 return self.get_preprocess_only_args() + [f'-x{lang}']
536
537
538 class GnuCompiler(GnuLikeCompiler):
539 """
540 GnuCompiler represents an actual GCC in its many incarnations.
541 Compilers imitating GCC (Clang/Intel) should use the GnuLikeCompiler ABC.
542 """
543 id = 'gcc'
544
545 _COLOR_VERSION = '>=4.9.0'
546 _WPEDANTIC_VERSION = '>=4.8.0'
547 _LTO_AUTO_VERSION = '>=10.0'
548 _LTO_CACHE_VERSION = '>=15.1'
549 _USE_MOLD_VERSION = '>=12.0.1'
550
551 def __init__(self, defines: T.Optional[T.Dict[str, str]]):
552 super().__init__()
553 self.defines = defines or {}
554 self.base_options.update({OptionKey('b_colorout'), OptionKey('b_lto_threads'),
555 OptionKey('b_thinlto_cache'), OptionKey('b_thinlto_cache_dir')})
556 self._has_color_support = mesonlib.version_compare(self.version, self._COLOR_VERSION)
557 self._has_wpedantic_support = mesonlib.version_compare(self.version, self._WPEDANTIC_VERSION)
558 self._has_lto_auto_support = mesonlib.version_compare(self.version, self._LTO_AUTO_VERSION)
559 self._has_lto_cache_support = mesonlib.version_compare(self.version, self._LTO_CACHE_VERSION)
560
561 def get_colorout_args(self, colortype: str) -> T.List[str]:
562 if self._has_color_support:
563 return gnu_color_args[colortype][:]
564 return []
565
566 def get_warn_args(self, level: str) -> T.List[str]:
567 # Mypy doesn't understand cooperative inheritance
568 args = super().get_warn_args(level)
569 if not self._has_wpedantic_support and '-Wpedantic' in args:
570 # -Wpedantic was added in 4.8.0
571 # https://gcc.gnu.org/gcc-4.8/changes.html
572 args[args.index('-Wpedantic')] = '-pedantic'
573 return args
574
575 def supported_warn_args(self, warn_args_by_version: T.Dict[str, T.List[str]]) -> T.List[str]:
576 result: T.List[str] = []
577 for version, warn_args in warn_args_by_version.items():
578 if mesonlib.version_compare(self.version, '>=' + version):
579 result += warn_args
580 return result
581
582 def has_builtin_define(self, define: str) -> bool:
583 return define in self.defines
584
585 def get_builtin_define(self, define: str) -> T.Optional[str]:
586 if define in self.defines:
587 return self.defines[define]
588 return None
589
590 def get_optimization_args(self, optimization_level: str) -> T.List[str]:
591 return gnu_optimization_args[optimization_level]
592
593 def get_pch_suffix(self) -> str:
594 return 'gch'
595
596 def openmp_flags(self) -> T.List[str]:
597 return ['-fopenmp']
598
599 def has_arguments(self, args: T.List[str], code: str,
600 mode: CompileCheckMode) -> T.Tuple[bool, bool]:
601 # For some compiler command line arguments, the GNU compilers will
602 # emit a warning on stderr indicating that an option is valid for a
603 # another language, but still complete with exit_success
604 with self._build_wrapper(code, args, None, mode) as p:
605 result = p.returncode == 0
606 if self.language in {'cpp', 'objcpp'} and 'is valid for C/ObjC' in p.stderr:
607 result = False
608 if self.language in {'c', 'objc'} and 'is valid for C++/ObjC++' in p.stderr:
609 result = False
610 return result, p.cached
611
612 def get_has_func_attribute_extra_args(self, name: str) -> T.List[str]:
613 # GCC only warns about unknown or ignored attributes, so force an
614 # error.
615 return ['-Werror=attributes']
616
617 def get_prelink_args(self, prelink_name: str, obj_list: T.List[str]) -> T.Tuple[T.List[str], T.List[str]]:
618 return [prelink_name], ['-r', '-o', prelink_name] + obj_list
619
620 def get_lto_compile_args(self, *, target: T.Optional[BuildTarget] = None, threads: int = 0,
621 mode: str = 'default', thinlto_cache_dir: T.Optional[str] = None) -> T.List[str]:
622 args: T.List[str] = []
623
624 if threads == 0:
625 if self._has_lto_auto_support:
626 args.append('-flto=auto')
627 else:
628 # This matches gcc's behavior of using the number of cpus, but
629 # obeying meson's MESON_NUM_PROCESSES convention.
630 args.append(f'-flto={mesonlib.determine_worker_count()}')
631 elif threads > 0:
632 args.append(f'-flto={threads}')
633 else:
634 args.extend(super().get_lto_compile_args(target=target, threads=threads))
635
636 if thinlto_cache_dir is not None:
637 # We check for ThinLTO linker support above in get_lto_compile_args, and all of them support
638 # get_thinlto_cache_args as well
639 args.extend(self.get_thinlto_cache_args(thinlto_cache_dir))
640
641 return args
642
643 def get_thinlto_cache_args(self, path: str) -> T.List[str]:
644 # Unlike the ThinLTO support for Clang, everything is handled in GCC
645 # and the linker has no direct involvement other than the usual w/ LTO.
646 return [f'-flto-incremental={path}']
647
648 @classmethod
649 def use_linker_args(cls, linker: str, version: str) -> T.List[str]:
650 if linker == 'mold' and mesonlib.version_compare(version, cls._USE_MOLD_VERSION):
651 return ['-fuse-ld=mold']
652 return super().use_linker_args(linker, version)
653
654 def get_lto_link_args(self, *, target: T.Optional[BuildTarget] = None, threads: int = 0,
655 mode: str = 'default', thinlto_cache_dir: T.Optional[str] = None) -> T.List[str]:
656 args: T.List[str] = []
657 args.extend(self.get_lto_compile_args(target=target, threads=threads, thinlto_cache_dir=thinlto_cache_dir))
658 return args
659
660 def get_profile_use_args(self) -> T.List[str]:
661 return super().get_profile_use_args() + ['-fprofile-correction']
662
663 def get_always_args(self) -> T.List[str]:
664 args: T.List[str] = []
665 if self.info.is_os2() and self.environment.coredata.optstore.get_value_for(OptionKey('os2_emxomf')):
666 args += ['-Zomf']
667 return super().get_always_args() + args
668
669
670 class GnuCStds(Compiler):
671
672 """Mixin class for gcc based compilers for setting C standards."""
673
674 _C18_VERSION = '>=8.0.0'
675 _C2X_VERSION = '>=9.0.0'
676 _C23_VERSION = '>=14.0.0'
677 _C2Y_VERSION = '>=15.0.0'
678
679 def get_options(self) -> MutableKeyedOptionDictType:
680 opts = super().get_options()
681 stds = ['c89', 'c99', 'c11']
682 if mesonlib.version_compare(self.version, self._C18_VERSION):
683 stds += ['c17', 'c18']
684 if mesonlib.version_compare(self.version, self._C2X_VERSION):
685 stds += ['c2x']
686 if mesonlib.version_compare(self.version, self._C23_VERSION):
687 stds += ['c23']
688 if mesonlib.version_compare(self.version, self._C2Y_VERSION):
689 stds += ['c2y']
690 key = self.form_compileropt_key('std')
691 std_opt = opts[key]
692 assert isinstance(std_opt, UserStdOption), 'for mypy'
693 std_opt.set_versions(stds, gnu=True)
694 return opts
695
696
697 class GnuCPPStds(Compiler):
698
699 """Mixin class for GNU based compilers for setting CPP standards."""
700
701 _CPP23_VERSION = '>=11.0.0'
702 _CPP26_VERSION = '>=14.0.0'
703
704 def get_options(self) -> MutableKeyedOptionDictType:
705 opts = super().get_options()
706
707 stds = [
708 'c++98', 'c++03', 'c++11', 'c++14', 'c++17', 'c++1z',
709 'c++2a', 'c++20',
710 ]
711 if mesonlib.version_compare(self.version, self._CPP23_VERSION):
712 stds.append('c++23')
713 if mesonlib.version_compare(self.version, self._CPP26_VERSION):
714 stds.append('c++26')
715 key = self.form_compileropt_key('std')
716 std_opt = opts[key]
717 assert isinstance(std_opt, UserStdOption), 'for mypy'
718 std_opt.set_versions(stds, gnu=True)
719 return opts