1# Copyright 2019 The meson development team
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""Abstractions for the Intel Compiler families.
16
17Intel provides both a posix/gcc-like compiler (ICC) for MacOS and Linux,
18with Meson mixin IntelGnuLikeCompiler.
19For Windows, the Intel msvc-like compiler (ICL) Meson mixin
20is IntelVisualStudioLikeCompiler.
21"""
22
23import os
24import typing as T
25
26from ... import mesonlib
27from .gnu import GnuLikeCompiler
28from .visualstudio import VisualStudioLikeCompiler
29
30if T.TYPE_CHECKING:
31    import subprocess  # noqa: F401
32
33# XXX: avoid circular dependencies
34# TODO: this belongs in a posix compiler class
35# NOTE: the default Intel optimization is -O2, unlike GNU which defaults to -O0.
36# this can be surprising, particularly for debug builds, so we specify the
37# default as -O0.
38# https://software.intel.com/en-us/cpp-compiler-developer-guide-and-reference-o
39# https://software.intel.com/en-us/cpp-compiler-developer-guide-and-reference-g
40# https://software.intel.com/en-us/fortran-compiler-developer-guide-and-reference-o
41# https://software.intel.com/en-us/fortran-compiler-developer-guide-and-reference-g
42# https://software.intel.com/en-us/fortran-compiler-developer-guide-and-reference-traceback
43# https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html
44
45
46class IntelGnuLikeCompiler(GnuLikeCompiler):
47    """
48    Tested on linux for ICC 14.0.3, 15.0.6, 16.0.4, 17.0.1, 19.0
49    debugoptimized: -g -O2
50    release: -O3
51    minsize: -O2
52    """
53
54    BUILD_ARGS = {
55        'plain': [],
56        'debug': ["-g", "-traceback"],
57        'debugoptimized': ["-g", "-traceback"],
58        'release': [],
59        'minsize': [],
60        'custom': [],
61    }  # type: T.Dict[str, T.List[str]]
62
63    OPTIM_ARGS = {
64        '0': ['-O0'],
65        'g': ['-O0'],
66        '1': ['-O1'],
67        '2': ['-O2'],
68        '3': ['-O3'],
69        's': ['-Os'],
70    }
71
72    def __init__(self):
73        super().__init__()
74        # As of 19.0.0 ICC doesn't have sanitizer, color, or lto support.
75        #
76        # It does have IPO, which serves much the same purpose as LOT, but
77        # there is an unfortunate rule for using IPO (you can't control the
78        # name of the output file) which break assumptions meson makes
79        self.base_options = ['b_pch', 'b_lundef', 'b_asneeded', 'b_pgo',
80                             'b_coverage', 'b_ndebug', 'b_staticpic', 'b_pie']
81        self.id = 'intel'
82        self.lang_header = 'none'
83
84    def get_pch_suffix(self) -> str:
85        return 'pchi'
86
87    def get_pch_use_args(self, pch_dir: str, header: str) -> T.List[str]:
88        return ['-pch', '-pch_dir', os.path.join(pch_dir), '-x',
89                self.lang_header, '-include', header, '-x', 'none']
90
91    def get_pch_name(self, header_name: str) -> str:
92        return os.path.basename(header_name) + '.' + self.get_pch_suffix()
93
94    def openmp_flags(self) -> T.List[str]:
95        if mesonlib.version_compare(self.version, '>=15.0.0'):
96            return ['-qopenmp']
97        else:
98            return ['-openmp']
99
100    def compiles(self, *args, **kwargs) -> T.Tuple[bool, bool]:
101        # This covers a case that .get('foo', []) doesn't, that extra_args is
102        # defined and is None
103        extra_args = kwargs.get('extra_args') or []
104        kwargs['extra_args'] = [
105            extra_args,
106            '-diag-error', '10006',  # ignoring unknown option
107            '-diag-error', '10148',  # Option not supported
108            '-diag-error', '10155',  # ignoring argument required
109            '-diag-error', '10156',  # ignoring not argument allowed
110            '-diag-error', '10157',  # Ignoring argument of the wrong type
111            '-diag-error', '10158',  # Argument must be separate. Can be hit by trying an option like -foo-bar=foo when -foo=bar is a valid option but -foo-bar isn't
112            '-diag-error', '1292',   # unknown __attribute__
113        ]
114        return super().compiles(*args, **kwargs)
115
116    def get_profile_generate_args(self) -> T.List[str]:
117        return ['-prof-gen=threadsafe']
118
119    def get_profile_use_args(self) -> T.List[str]:
120        return ['-prof-use']
121
122    def get_buildtype_args(self, buildtype: str) -> T.List[str]:
123        return self.BUILD_ARGS[buildtype]
124
125    def get_optimization_args(self, optimization_level: str) -> T.List[str]:
126        return self.OPTIM_ARGS[optimization_level]
127
128
129class IntelVisualStudioLikeCompiler(VisualStudioLikeCompiler):
130
131    """Abstractions for ICL, the Intel compiler on Windows."""
132
133    BUILD_ARGS = {
134        'plain': [],
135        'debug': ["/Zi", "/traceback"],
136        'debugoptimized': ["/Zi", "/traceback"],
137        'release': [],
138        'minsize': [],
139        'custom': [],
140    }  # type: T.Dict[str, T.List[str]]
141
142    OPTIM_ARGS = {
143        '0': ['/O0'],
144        'g': ['/O0'],
145        '1': ['/O1'],
146        '2': ['/O2'],
147        '3': ['/O3'],
148        's': ['/Os'],
149    }
150
151    def __init__(self, target: str):
152        super().__init__(target)
153        self.id = 'intel-cl'
154
155    def compile(self, code, *, extra_args: T.Optional[T.List[str]] = None, **kwargs) -> T.Iterator['subprocess.Popen']:
156        # This covers a case that .get('foo', []) doesn't, that extra_args is
157        if kwargs.get('mode', 'compile') != 'link':
158            extra_args = extra_args.copy() if extra_args is not None else []
159            extra_args.extend([
160                '/Qdiag-error:10006',  # ignoring unknown option
161                '/Qdiag-error:10148',  # Option not supported
162                '/Qdiag-error:10155',  # ignoring argument required
163                '/Qdiag-error:10156',  # ignoring not argument allowed
164                '/Qdiag-error:10157',  # Ignoring argument of the wrong type
165                '/Qdiag-error:10158',  # Argument must be separate. Can be hit by trying an option like -foo-bar=foo when -foo=bar is a valid option but -foo-bar isn't
166            ])
167        return super().compile(code, extra_args, **kwargs)
168
169    def get_toolset_version(self) -> T.Optional[str]:
170        # Avoid circular dependencies....
171        from ...environment import search_version
172
173        # ICL provides a cl.exe that returns the version of MSVC it tries to
174        # emulate, so we'll get the version from that and pass it to the same
175        # function the real MSVC uses to calculate the toolset version.
176        _, _, err = mesonlib.Popen_safe(['cl.exe'])
177        v1, v2, *_ = search_version(err).split('.')
178        version = int(v1 + v2)
179        return self._calculate_toolset_version(version)
180
181    def openmp_flags(self) -> T.List[str]:
182        return ['/Qopenmp']
183
184    def get_buildtype_args(self, buildtype: str) -> T.List[str]:
185        return self.BUILD_ARGS[buildtype]
186
187    def get_optimization_args(self, optimization_level: str) -> T.List[str]:
188        return self.OPTIM_ARGS[optimization_level]
189