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 @abc.abstractmethod
385 def get_optimization_args(self, optimization_level: str) -> T.List[str]:
386 pass
387
388 def get_debug_args(self, is_debug: bool) -> T.List[str]:
389 return clike_debug_args[is_debug]
390
391 @abc.abstractmethod
392 def get_pch_suffix(self) -> str:
393 pass
394
395 def split_shlib_to_parts(self, fname: str) -> T.Tuple[str, str]:
396 return os.path.dirname(fname), fname
397
398 def get_instruction_set_args(self, instruction_set: str) -> T.Optional[T.List[str]]:
399 return gnulike_instruction_set_args.get(instruction_set, None)
400
401 def get_default_include_dirs(self) -> T.List[str]:
402 return gnulike_default_include_dirs(tuple(self.get_exelist(ccache=False)), self.language).copy()
403
404 @abc.abstractmethod
405 def openmp_flags(self) -> T.List[str]:
406 pass
407
408 def gnu_symbol_visibility_args(self, vistype: str) -> T.List[str]:
409 if vistype == 'inlineshidden' and self.language not in {'cpp', 'objcpp'}:
410 vistype = 'hidden'
411 return gnu_symbol_visibility_args[vistype]
412
413 @staticmethod
414 def get_argument_syntax() -> str:
415 return 'gcc'
416
417 def get_profile_generate_args(self) -> T.List[str]:
418 return ['-fprofile-generate']
419
420 def get_profile_use_args(self) -> T.List[str]:
421 return ['-fprofile-use']
422
423 def compute_parameters_with_absolute_paths(self, parameter_list: T.List[str], build_dir: str) -> T.List[str]:
424 for idx, i in enumerate(parameter_list):
425 if i[:2] == '-I' or i[:2] == '-L':
426 parameter_list[idx] = i[:2] + os.path.normpath(os.path.join(build_dir, i[2:]))
427
428 return parameter_list
429
430 @functools.lru_cache()
431 def _get_search_dirs(self) -> str:
432 extra_args = ['--print-search-dirs']
433 with self._build_wrapper('', extra_args=extra_args,
434 dependencies=None, mode=CompileCheckMode.COMPILE,
435 want_output=True) as p:
436 return p.stdout
437
438 def _split_fetch_real_dirs(self, pathstr: str) -> T.List[str]:
439 # We need to use the path separator used by the compiler for printing
440 # lists of paths ("gcc --print-search-dirs"). By default
441 # we assume it uses the platform native separator.
442 pathsep = os.pathsep
443
444 # clang uses ':' instead of ';' on Windows https://reviews.llvm.org/D61121
445 # so we need to repair things like 'C:\foo:C:\bar'
446 if pathsep == ';':
447 pathstr = re.sub(r':([^/\\])', r';\1', pathstr)
448
449 # pathlib treats empty paths as '.', so filter those out
450 paths = [p for p in pathstr.split(pathsep) if p]
451
452 result: T.List[str] = []
453 for p in paths:
454 # GCC returns paths like this:
455 # /usr/lib/gcc/x86_64-linux-gnu/8/../../../../x86_64-linux-gnu/lib
456 # It would make sense to normalize them to get rid of the .. parts
457 # Sadly when you are on a merged /usr fs it also kills these:
458 # /lib/x86_64-linux-gnu
459 # since /lib is a symlink to /usr/lib. This would mean
460 # paths under /lib would be considered not a "system path",
461 # which is wrong and breaks things. Store everything, just to be sure.
462 pobj = pathlib.Path(p)
463 if pobj.exists():
464 try:
465 resolved = pobj.resolve(True).as_posix()
466 if resolved not in result:
467 result.append(resolved)
468 except FileNotFoundError:
469 pass
470 unresolved = pobj.as_posix()
471 if unresolved not in result:
472 result.append(unresolved)
473 return result
474
475 def get_compiler_dirs(self, name: str) -> T.List[str]:
476 '''
477 Get dirs from the compiler, either `libraries:` or `programs:`
478 '''
479 stdo = self._get_search_dirs()
480 for line in stdo.split('\n'):
481 if line.startswith(name + ':'):
482 return self._split_fetch_real_dirs(line.split('=', 1)[1])
483 return []
484
485 def get_lto_compile_args(self, *, target: T.Optional[BuildTarget] = None, threads: int = 0,
486 mode: str = 'default') -> T.List[str]:
487 # This provides a base for many compilers, GCC and Clang override this
488 # for their specific arguments
489 return ['-flto']
490
491 def sanitizer_compile_args(self, target: T.Optional[BuildTarget], value: T.List[str]) -> T.List[str]:
492 if not value:
493 return value
494 args = ['-fsanitize=' + ','.join(value)]
495 if 'address' in value:
496 args.append('-fno-omit-frame-pointer')
497 return args
498
499 def get_output_args(self, outputname: str) -> T.List[str]:
500 return ['-o', outputname]
501
502 def get_dependency_gen_args(self, outtarget: str, outfile: str) -> T.List[str]:
503 return ['-MD', '-MQ', outtarget, '-MF', outfile]
504
505 def get_compile_only_args(self) -> T.List[str]:
506 return ['-c']
507
508 def get_include_args(self, path: str, is_system: bool) -> T.List[str]:
509 if not path:
510 path = '.'
511 if is_system:
512 return ['-isystem' + path]
513 return ['-I' + path]
514
515 @classmethod
516 def use_linker_args(cls, linker: str, version: str) -> T.List[str]:
517 if linker not in {'bfd', 'eld', 'gold', 'lld'}:
518 raise mesonlib.MesonException(
519 f'Unsupported linker, only bfd, eld, gold, and lld are supported, not {linker}.')
520 return [f'-fuse-ld={linker}']
521
522 def get_coverage_args(self) -> T.List[str]:
523 return ['--coverage']
524
525 def get_preprocess_to_file_args(self) -> T.List[str]:
526 # We want to allow preprocessing files with any extension, such as
527 # foo.c.in. In that case we need to tell GCC/CLANG to treat them as
528 # assembly file.
529 if self.language == 'fortran':
530 return self.get_preprocess_only_args()
531 lang = gnu_lang_map.get(self.language, 'assembler-with-cpp')
532 return self.get_preprocess_only_args() + [f'-x{lang}']
533
534
535 class GnuCompiler(GnuLikeCompiler):
536 """
537 GnuCompiler represents an actual GCC in its many incarnations.
538 Compilers imitating GCC (Clang/Intel) should use the GnuLikeCompiler ABC.
539 """
540 id = 'gcc'
541
542 _COLOR_VERSION = '>=4.9.0'
543 _WPEDANTIC_VERSION = '>=4.8.0'
544 _LTO_AUTO_VERSION = '>=10.0'
545 _LTO_CACHE_VERSION = '>=15.1'
546 _USE_MOLD_VERSION = '>=12.0.1'
547
548 def __init__(self, defines: T.Optional[T.Dict[str, str]]):
549 super().__init__()
550 self.defines = defines or {}
551 self.base_options.update({OptionKey('b_colorout'), OptionKey('b_lto_threads'),
552 OptionKey('b_thinlto_cache'), OptionKey('b_thinlto_cache_dir')})
553 self._has_color_support = mesonlib.version_compare(self.version, self._COLOR_VERSION)
554 self._has_wpedantic_support = mesonlib.version_compare(self.version, self._WPEDANTIC_VERSION)
555 self._has_lto_auto_support = mesonlib.version_compare(self.version, self._LTO_AUTO_VERSION)
556 self._has_lto_cache_support = mesonlib.version_compare(self.version, self._LTO_CACHE_VERSION)
557
558 def get_colorout_args(self, colortype: str) -> T.List[str]:
559 if self._has_color_support:
560 return gnu_color_args[colortype][:]
561 return []
562
563 def get_warn_args(self, level: str) -> T.List[str]:
564 # Mypy doesn't understand cooperative inheritance
565 args = super().get_warn_args(level)
566 if not self._has_wpedantic_support and '-Wpedantic' in args:
567 # -Wpedantic was added in 4.8.0
568 # https://gcc.gnu.org/gcc-4.8/changes.html
569 args[args.index('-Wpedantic')] = '-pedantic'
570 return args
571
572 def supported_warn_args(self, warn_args_by_version: T.Dict[str, T.List[str]]) -> T.List[str]:
573 result: T.List[str] = []
574 for version, warn_args in warn_args_by_version.items():
575 if mesonlib.version_compare(self.version, '>=' + version):
576 result += warn_args
577 return result
578
579 def has_builtin_define(self, define: str) -> bool:
580 return define in self.defines
581
582 def get_builtin_define(self, define: str) -> T.Optional[str]:
583 if define in self.defines:
584 return self.defines[define]
585 return None
586
587 def get_optimization_args(self, optimization_level: str) -> T.List[str]:
588 return gnu_optimization_args[optimization_level]
589
590 def get_pch_suffix(self) -> str:
591 return 'gch'
592
593 def openmp_flags(self) -> T.List[str]:
594 return ['-fopenmp']
595
596 def has_arguments(self, args: T.List[str], code: str,
597 mode: CompileCheckMode) -> T.Tuple[bool, bool]:
598 # For some compiler command line arguments, the GNU compilers will
599 # emit a warning on stderr indicating that an option is valid for a
600 # another language, but still complete with exit_success
601 with self._build_wrapper(code, args, None, mode) as p:
602 result = p.returncode == 0
603 if self.language in {'cpp', 'objcpp'} and 'is valid for C/ObjC' in p.stderr:
604 result = False
605 if self.language in {'c', 'objc'} and 'is valid for C++/ObjC++' in p.stderr:
606 result = False
607 return result, p.cached
608
609 def get_has_func_attribute_extra_args(self, name: str) -> T.List[str]:
610 # GCC only warns about unknown or ignored attributes, so force an
611 # error.
612 return ['-Werror=attributes']
613
614 def get_prelink_args(self, prelink_name: str, obj_list: T.List[str]) -> T.Tuple[T.List[str], T.List[str]]:
615 return [prelink_name], ['-r', '-o', prelink_name] + obj_list
616
617 def get_lto_compile_args(self, *, target: T.Optional[BuildTarget] = None, threads: int = 0,
618 mode: str = 'default', thinlto_cache_dir: T.Optional[str] = None) -> T.List[str]:
619 args: T.List[str] = []
620
621 if threads == 0:
622 if self._has_lto_auto_support:
623 args.append('-flto=auto')
624 else:
625 # This matches gcc's behavior of using the number of cpus, but
626 # obeying meson's MESON_NUM_PROCESSES convention.
627 args.append(f'-flto={mesonlib.determine_worker_count()}')
628 elif threads > 0:
629 args.append(f'-flto={threads}')
630 else:
631 args.extend(super().get_lto_compile_args(target=target, threads=threads))
632
633 if thinlto_cache_dir is not None:
634 # We check for ThinLTO linker support above in get_lto_compile_args, and all of them support
635 # get_thinlto_cache_args as well
636 args.extend(self.get_thinlto_cache_args(thinlto_cache_dir))
637
638 return args
639
640 def get_thinlto_cache_args(self, path: str) -> T.List[str]:
641 # Unlike the ThinLTO support for Clang, everything is handled in GCC
642 # and the linker has no direct involvement other than the usual w/ LTO.
643 return [f'-flto-incremental={path}']
644
645 @classmethod
646 def use_linker_args(cls, linker: str, version: str) -> T.List[str]:
647 if linker == 'mold' and mesonlib.version_compare(version, cls._USE_MOLD_VERSION):
648 return ['-fuse-ld=mold']
649 return super().use_linker_args(linker, version)
650
651 def get_lto_link_args(self, *, target: T.Optional[BuildTarget] = None, threads: int = 0,
652 mode: str = 'default', thinlto_cache_dir: T.Optional[str] = None) -> T.List[str]:
653 args: T.List[str] = []
654 args.extend(self.get_lto_compile_args(target=target, threads=threads, thinlto_cache_dir=thinlto_cache_dir))
655 return args
656
657 def get_profile_use_args(self) -> T.List[str]:
658 return super().get_profile_use_args() + ['-fprofile-correction']
659
660 def get_always_args(self) -> T.List[str]:
661 args: T.List[str] = []
662 if self.info.is_os2() and self.environment.coredata.optstore.get_value_for(OptionKey('os2_emxomf')):
663 args += ['-Zomf']
664 return super().get_always_args() + args
665
666
667 class GnuCStds(Compiler):
668
669 """Mixin class for gcc based compilers for setting C standards."""
670
671 _C18_VERSION = '>=8.0.0'
672 _C2X_VERSION = '>=9.0.0'
673 _C23_VERSION = '>=14.0.0'
674 _C2Y_VERSION = '>=15.0.0'
675
676 def get_options(self) -> MutableKeyedOptionDictType:
677 opts = super().get_options()
678 stds = ['c89', 'c99', 'c11']
679 if mesonlib.version_compare(self.version, self._C18_VERSION):
680 stds += ['c17', 'c18']
681 if mesonlib.version_compare(self.version, self._C2X_VERSION):
682 stds += ['c2x']
683 if mesonlib.version_compare(self.version, self._C23_VERSION):
684 stds += ['c23']
685 if mesonlib.version_compare(self.version, self._C2Y_VERSION):
686 stds += ['c2y']
687 key = self.form_compileropt_key('std')
688 std_opt = opts[key]
689 assert isinstance(std_opt, UserStdOption), 'for mypy'
690 std_opt.set_versions(stds, gnu=True)
691 return opts
692
693
694 class GnuCPPStds(Compiler):
695
696 """Mixin class for GNU based compilers for setting CPP standards."""
697
698 _CPP23_VERSION = '>=11.0.0'
699 _CPP26_VERSION = '>=14.0.0'
700
701 def get_options(self) -> MutableKeyedOptionDictType:
702 opts = super().get_options()
703
704 stds = [
705 'c++98', 'c++03', 'c++11', 'c++14', 'c++17', 'c++1z',
706 'c++2a', 'c++20',
707 ]
708 if mesonlib.version_compare(self.version, self._CPP23_VERSION):
709 stds.append('c++23')
710 if mesonlib.version_compare(self.version, self._CPP26_VERSION):
711 stds.append('c++26')
712 key = self.form_compileropt_key('std')
713 std_opt = opts[key]
714 assert isinstance(std_opt, UserStdOption), 'for mypy'
715 std_opt.set_versions(stds, gnu=True)
716 return opts