1import itertools
2import os
3import platform
4import re
5import subprocess
6import sys
7import errno
8
9import lit.util
10from lit.llvm.subst import FindTool
11from lit.llvm.subst import ToolSubst
12
13lit_path_displayed = False
14
15class LLVMConfig(object):
16
17    def __init__(self, lit_config, config):
18        self.lit_config = lit_config
19        self.config = config
20
21        features = config.available_features
22
23        self.use_lit_shell = False
24        # Tweak PATH for Win32 to decide to use bash.exe or not.
25        if sys.platform == 'win32':
26            # Seek necessary tools in directories and set to $PATH.
27            path = None
28            lit_tools_dir = getattr(config, 'lit_tools_dir', None)
29            required_tools = [
30                'cmp.exe', 'grep.exe', 'sed.exe', 'diff.exe', 'echo.exe']
31            path = self.lit_config.getToolsPath(lit_tools_dir,
32                                                config.environment['PATH'],
33                                                required_tools)
34            if path is None:
35                path = self._find_git_windows_unix_tools(required_tools)
36            if path is not None:
37                self.with_environment('PATH', path, append_path=True)
38            # Many tools behave strangely if these environment variables aren't
39            # set.
40            self.with_system_environment(
41                ['SystemDrive', 'SystemRoot', 'TEMP', 'TMP', 'PLATFORM'])
42            self.use_lit_shell = True
43
44            global lit_path_displayed
45            if not self.lit_config.quiet and lit_path_displayed is False:
46                self.lit_config.note("using lit tools: {}".format(path))
47                lit_path_displayed = True
48
49        # Choose between lit's internal shell pipeline runner and a real shell.
50        # If LIT_USE_INTERNAL_SHELL is in the environment, we use that as an
51        # override.
52        lit_shell_env = os.environ.get('LIT_USE_INTERNAL_SHELL')
53        if lit_shell_env:
54            self.use_lit_shell = lit.util.pythonize_bool(lit_shell_env)
55
56        if not self.use_lit_shell:
57            features.add('shell')
58
59        self.with_system_environment([
60            'ASAN_SYMBOLIZER_PATH',
61            'MSAN_SYMBOLIZER_PATH',
62            'TSAN_SYMBOLIZER_PATH',
63            'UBSAN_SYMBOLIZER_PATH'
64            'ASAN_OPTIONS',
65            'MSAN_OPTIONS',
66            'TSAN_OPTIONS',
67            'UBSAN_OPTIONS',
68        ])
69
70        # Running on Darwin OS
71        if platform.system() == 'Darwin':
72            # FIXME: lld uses the first, other projects use the second.
73            # We should standardize on the former.
74            features.add('system-linker-mach-o')
75            features.add('system-darwin')
76        elif platform.system() == 'Windows':
77            # For tests that require Windows to run.
78            features.add('system-windows')
79        elif platform.system() == 'Linux':
80            features.add('system-linux')
81        elif platform.system() in ['FreeBSD']:
82            features.add('system-freebsd')
83        elif platform.system() == 'NetBSD':
84            features.add('system-netbsd')
85        elif platform.system() == 'AIX':
86            features.add('system-aix')
87        elif platform.system() == 'SunOS':
88            features.add('system-solaris')
89
90        # Native compilation: host arch == default triple arch
91        # Both of these values should probably be in every site config (e.g. as
92        # part of the standard header.  But currently they aren't)
93        host_triple = getattr(config, 'host_triple', None)
94        target_triple = getattr(config, 'target_triple', None)
95        if host_triple and host_triple == target_triple:
96            features.add('native')
97
98        # Sanitizers.
99        sanitizers = getattr(config, 'llvm_use_sanitizer', '')
100        sanitizers = frozenset(x.lower() for x in sanitizers.split(';'))
101        if 'address' in sanitizers:
102            features.add('asan')
103        if 'memory' in sanitizers or 'memorywithorigins' in sanitizers:
104            features.add('msan')
105        if 'undefined' in sanitizers:
106            features.add('ubsan')
107
108        have_zlib = getattr(config, 'have_zlib', None)
109        if have_zlib:
110            features.add('zlib')
111
112        # Check if we should run long running tests.
113        long_tests = lit_config.params.get('run_long_tests', None)
114        if lit.util.pythonize_bool(long_tests):
115            features.add('long_tests')
116
117        if target_triple:
118            if re.match(r'^x86_64.*-apple', target_triple):
119                features.add('x86_64-apple')
120                host_cxx = getattr(config, 'host_cxx', None)
121                if ('address' in sanitizers and
122                        self.get_clang_has_lsan(host_cxx, target_triple)):
123                    self.with_environment(
124                        'ASAN_OPTIONS', 'detect_leaks=1', append_path=True)
125            if re.match(r'^x86_64.*-linux', target_triple):
126                features.add('x86_64-linux')
127            if re.match(r'^i.86.*', target_triple):
128                features.add('target-x86')
129            elif re.match(r'^x86_64.*', target_triple):
130                features.add('target-x86_64')
131            elif re.match(r'^aarch64.*', target_triple):
132                features.add('target-aarch64')
133            elif re.match(r'^arm64.*', target_triple):
134                features.add('target-aarch64')
135            elif re.match(r'^arm.*', target_triple):
136                features.add('target-arm')
137
138        use_gmalloc = lit_config.params.get('use_gmalloc', None)
139        if lit.util.pythonize_bool(use_gmalloc):
140            # Allow use of an explicit path for gmalloc library.
141            # Will default to '/usr/lib/libgmalloc.dylib' if not set.
142            gmalloc_path_str = lit_config.params.get(
143                'gmalloc_path', '/usr/lib/libgmalloc.dylib')
144            if gmalloc_path_str is not None:
145                self.with_environment(
146                    'DYLD_INSERT_LIBRARIES', gmalloc_path_str)
147
148    def _find_git_windows_unix_tools(self, tools_needed):
149        assert(sys.platform == 'win32')
150        if sys.version_info.major >= 3:
151            import winreg
152        else:
153            import _winreg as winreg
154
155        # Search both the 64 and 32-bit hives, as well as HKLM + HKCU
156        masks = [0, winreg.KEY_WOW64_64KEY]
157        hives = [winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER]
158        for mask, hive in itertools.product(masks, hives):
159            try:
160                with winreg.OpenKey(hive, r"SOFTWARE\GitForWindows", 0,
161                                    winreg.KEY_READ | mask) as key:
162                    install_root, _ = winreg.QueryValueEx(key, 'InstallPath')
163
164                    if not install_root:
165                        continue
166                    candidate_path = os.path.join(install_root, 'usr', 'bin')
167                    if not lit.util.checkToolsPath(
168                               candidate_path, tools_needed):
169                        continue
170
171                    # We found it, stop enumerating.
172                    return lit.util.to_string(candidate_path)
173            except:
174                continue
175
176        return None
177
178    def with_environment(self, variable, value, append_path=False):
179        if append_path:
180            # For paths, we should be able to take a list of them and process
181            # all of them.
182            paths_to_add = value
183            if lit.util.is_string(paths_to_add):
184                paths_to_add = [paths_to_add]
185
186            def norm(x):
187                return os.path.normcase(os.path.normpath(x))
188
189            current_paths = self.config.environment.get(variable, None)
190            if current_paths:
191                current_paths = current_paths.split(os.path.pathsep)
192                paths = [norm(p) for p in current_paths]
193            else:
194                paths = []
195
196            # If we are passed a list [a b c], then iterating this list forwards
197            # and adding each to the beginning would result in c b a.  So we
198            # need to iterate in reverse to end up with the original ordering.
199            for p in reversed(paths_to_add):
200                # Move it to the front if it already exists, otherwise insert
201                # it at the beginning.
202                p = norm(p)
203                try:
204                    paths.remove(p)
205                except ValueError:
206                    pass
207                paths = [p] + paths
208            value = os.pathsep.join(paths)
209        self.config.environment[variable] = value
210
211    def with_system_environment(self, variables, append_path=False):
212        if lit.util.is_string(variables):
213            variables = [variables]
214        for v in variables:
215            value = os.environ.get(v)
216            if value:
217                self.with_environment(v, value, append_path)
218
219    def clear_environment(self, variables):
220        for name in variables:
221            if name in self.config.environment:
222                del self.config.environment[name]
223
224    def get_process_output(self, command):
225        try:
226            cmd = subprocess.Popen(
227                command, stdout=subprocess.PIPE,
228                stderr=subprocess.PIPE, env=self.config.environment)
229            stdout, stderr = cmd.communicate()
230            stdout = lit.util.to_string(stdout)
231            stderr = lit.util.to_string(stderr)
232            return (stdout, stderr)
233        except OSError:
234            self.lit_config.fatal('Could not run process %s' % command)
235
236    def feature_config(self, features):
237        # Ask llvm-config about the specified feature.
238        arguments = [x for (x, _) in features]
239        config_path = os.path.join(self.config.llvm_tools_dir, 'llvm-config')
240
241        output, _ = self.get_process_output([config_path] + arguments)
242        lines = output.split('\n')
243
244        for (feature_line, (_, patterns)) in zip(lines, features):
245            # We should have either a callable or a dictionary.  If it's a
246            # dictionary, grep each key against the output and use the value if
247            # it matches.  If it's a callable, it does the entire translation.
248            if callable(patterns):
249                features_to_add = patterns(feature_line)
250                self.config.available_features.update(features_to_add)
251            else:
252                for (re_pattern, feature) in patterns.items():
253                    if re.search(re_pattern, feature_line):
254                        self.config.available_features.add(feature)
255
256    # Note that when substituting %clang_cc1 also fill in the include directory
257    # of the builtin headers. Those are part of even a freestanding
258    # environment, but Clang relies on the driver to locate them.
259    def get_clang_builtin_include_dir(self, clang):
260        # FIXME: Rather than just getting the version, we should have clang
261        # print out its resource dir here in an easy to scrape form.
262        clang_dir, _ = self.get_process_output(
263            [clang, '-print-file-name=include'])
264
265        if not clang_dir:
266            print(clang)
267            self.lit_config.fatal(
268                "Couldn't find the include dir for Clang ('%s')" % clang)
269
270        clang_dir = clang_dir.strip()
271        if sys.platform in ['win32'] and not self.use_lit_shell:
272            # Don't pass dosish path separator to msys bash.exe.
273            clang_dir = clang_dir.replace('\\', '/')
274        # Ensure the result is an ascii string, across Python2.5+ - Python3.
275        return clang_dir
276
277    # On macOS, LSan is only supported on clang versions 5 and higher
278    def get_clang_has_lsan(self, clang, triple):
279        if not clang:
280            self.lit_config.warning(
281                'config.host_cxx is unset but test suite is configured '
282                'to use sanitizers.')
283            return False
284
285        clang_binary = clang.split()[0]
286        version_string, _ = self.get_process_output(
287            [clang_binary, '--version'])
288        if not 'clang' in version_string:
289            self.lit_config.warning(
290                "compiler '%s' does not appear to be clang, " % clang_binary +
291                'but test suite is configured to use sanitizers.')
292            return False
293
294        if re.match(r'.*-linux', triple):
295            return True
296
297        if re.match(r'^x86_64.*-apple', triple):
298            version_regex = re.search(r'version ([0-9]+)\.([0-9]+).([0-9]+)',
299                                      version_string)
300            major_version_number = int(version_regex.group(1))
301            minor_version_number = int(version_regex.group(2))
302            patch_version_number = int(version_regex.group(3))
303            if ('Apple LLVM' in version_string or
304                'Apple clang' in version_string):
305                # Apple clang doesn't yet support LSan
306                return False
307            return major_version_number >= 5
308
309        return False
310
311    def make_itanium_abi_triple(self, triple):
312        m = re.match(r'(\w+)-(\w+)-(\w+)', triple)
313        if not m:
314            self.lit_config.fatal(
315                "Could not turn '%s' into Itanium ABI triple" % triple)
316        if m.group(3).lower() != 'windows':
317            # All non-windows triples use the Itanium ABI.
318            return triple
319        return m.group(1) + '-' + m.group(2) + '-' + m.group(3) + '-gnu'
320
321    def make_msabi_triple(self, triple):
322        m = re.match(r'(\w+)-(\w+)-(\w+)', triple)
323        if not m:
324            self.lit_config.fatal(
325                "Could not turn '%s' into MS ABI triple" % triple)
326        isa = m.group(1).lower()
327        vendor = m.group(2).lower()
328        os = m.group(3).lower()
329        if os == 'windows' and re.match(r'.*-msvc$', triple):
330            # If the OS is windows and environment is msvc, we're done.
331            return triple
332        if isa.startswith('x86') or isa == 'amd64' or re.match(r'i\d86', isa):
333            # For x86 ISAs, adjust the OS.
334            return isa + '-' + vendor + '-windows-msvc'
335        # -msvc is not supported for non-x86 targets; use a default.
336        return 'i686-pc-windows-msvc'
337
338    def add_tool_substitutions(self, tools, search_dirs=None):
339        if not search_dirs:
340            search_dirs = [self.config.llvm_tools_dir]
341
342        if lit.util.is_string(search_dirs):
343            search_dirs = [search_dirs]
344
345        tools = [x if isinstance(x, ToolSubst) else ToolSubst(x)
346                 for x in tools]
347
348        search_dirs = os.pathsep.join(search_dirs)
349        substitutions = []
350
351        for tool in tools:
352            match = tool.resolve(self, search_dirs)
353
354            # Either no match occurred, or there was an unresolved match that
355            # is ignored.
356            if not match:
357                continue
358
359            subst_key, tool_pipe, command = match
360
361            # An unresolved match occurred that can't be ignored.  Fail without
362            # adding any of the previously-discovered substitutions.
363            if not command:
364                return False
365
366            substitutions.append((subst_key, tool_pipe + command))
367
368        self.config.substitutions.extend(substitutions)
369        return True
370
371    def add_err_msg_substitutions(self):
372        # Python's strerror may not supply the same message
373        # as C++ std::error_code. One example of such a platform is
374        # Visual Studio. errc_messages may be supplied which contains the error
375        # messages for ENOENT, EISDIR, EINVAL and EACCES as a semi colon
376        # separated string. LLVM testsuites can use get_errc_messages in cmake
377        # to automatically get the messages and pass them into lit.
378        errc_messages = getattr(self.config, 'errc_messages', '')
379        if len(errc_messages) != 0:
380            (errc_enoent, errc_eisdir,
381             errc_einval, errc_eacces) = errc_messages.split(';')
382            self.config.substitutions.append(
383                ('%errc_ENOENT', '\'' + errc_enoent + '\''))
384            self.config.substitutions.append(
385                ('%errc_EISDIR', '\'' + errc_eisdir + '\''))
386            self.config.substitutions.append(
387                ('%errc_EINVAL', '\'' + errc_einval + '\''))
388            self.config.substitutions.append(
389                ('%errc_EACCES', '\'' + errc_eacces + '\''))
390        else:
391            self.config.substitutions.append(
392                ('%errc_ENOENT', '\'' + os.strerror(errno.ENOENT) + '\''))
393            self.config.substitutions.append(
394                ('%errc_EISDIR', '\'' + os.strerror(errno.EISDIR) + '\''))
395            self.config.substitutions.append(
396                ('%errc_EINVAL', '\'' + os.strerror(errno.EINVAL) + '\''))
397            self.config.substitutions.append(
398                ('%errc_EACCES', '\'' + os.strerror(errno.EACCES) + '\''))
399
400    def use_default_substitutions(self):
401        tool_patterns = [
402            ToolSubst('FileCheck', unresolved='fatal'),
403            # Handle these specially as they are strings searched for during
404            # testing.
405            ToolSubst(r'\| \bcount\b', command=FindTool('count'),
406                verbatim=True, unresolved='fatal'),
407            ToolSubst(r'\| \bnot\b', command=FindTool('not'),
408                verbatim=True, unresolved='fatal')]
409
410        self.config.substitutions.append(('%python', '"%s"' % (sys.executable)))
411
412        self.add_tool_substitutions(
413            tool_patterns, [self.config.llvm_tools_dir])
414
415        self.add_err_msg_substitutions()
416
417    def use_llvm_tool(self, name, search_env=None, required=False, quiet=False,
418                      search_paths=None, use_installed=False):
419        """Find the executable program 'name', optionally using the specified
420        environment variable as an override before searching the build directory
421        and then optionally the configuration's PATH."""
422        # If the override is specified in the environment, use it without
423        # validation.
424        tool = None
425        if search_env:
426            tool = self.config.environment.get(search_env)
427
428        if not tool:
429            if search_paths is None:
430                search_paths = [self.config.llvm_tools_dir]
431            # Use the specified search paths.
432            path = os.pathsep.join(search_paths)
433            tool = lit.util.which(name, path)
434
435        if not tool and use_installed:
436            # Otherwise look in the path, if enabled.
437            tool = lit.util.which(name, self.config.environment['PATH'])
438
439        if required and not tool:
440            message = "couldn't find '{}' program".format(name)
441            if search_env:
442                message = message + \
443                    ', try setting {} in your environment'.format(search_env)
444            self.lit_config.fatal(message)
445
446        if tool:
447            tool = os.path.normpath(tool)
448            if not self.lit_config.quiet and not quiet:
449                self.lit_config.note('using {}: {}'.format(name, tool))
450        return tool
451
452    def use_clang(self, additional_tool_dirs=[], additional_flags=[],
453                  required=True, use_installed=False):
454        """Configure the test suite to be able to invoke clang.
455
456        Sets up some environment variables important to clang, locates a
457        just-built or optionally an installed clang, and add a set of standard
458        substitutions useful to any test suite that makes use of clang.
459
460        """
461        # Clear some environment variables that might affect Clang.
462        #
463        # This first set of vars are read by Clang, but shouldn't affect tests
464        # that aren't specifically looking for these features, or are required
465        # simply to run the tests at all.
466        #
467        # FIXME: Should we have a tool that enforces this?
468
469        # safe_env_vars = (
470        #     'TMPDIR', 'TEMP', 'TMP', 'USERPROFILE', 'PWD',
471        #     'MACOSX_DEPLOYMENT_TARGET', 'IPHONEOS_DEPLOYMENT_TARGET',
472        #     'VCINSTALLDIR', 'VC100COMNTOOLS', 'VC90COMNTOOLS',
473        #     'VC80COMNTOOLS')
474        possibly_dangerous_env_vars = [
475            'COMPILER_PATH', 'RC_DEBUG_OPTIONS',
476            'CINDEXTEST_PREAMBLE_FILE', 'LIBRARY_PATH',
477            'CPATH', 'C_INCLUDE_PATH', 'CPLUS_INCLUDE_PATH',
478            'OBJC_INCLUDE_PATH', 'OBJCPLUS_INCLUDE_PATH',
479            'LIBCLANG_TIMING', 'LIBCLANG_OBJTRACKING',
480            'LIBCLANG_LOGGING', 'LIBCLANG_BGPRIO_INDEX',
481            'LIBCLANG_BGPRIO_EDIT', 'LIBCLANG_NOTHREADS',
482            'LIBCLANG_RESOURCE_USAGE',
483            'LIBCLANG_CODE_COMPLETION_LOGGING',
484            ]
485        # Clang/Win32 may refer to %INCLUDE%. vsvarsall.bat sets it.
486        if platform.system() != 'Windows':
487            possibly_dangerous_env_vars.append('INCLUDE')
488
489        self.clear_environment(possibly_dangerous_env_vars)
490
491        # Tweak the PATH to include the tools dir and the scripts dir.
492        # Put Clang first to avoid LLVM from overriding out-of-tree clang
493        # builds.
494        exe_dir_props = [self.config.name.lower() + '_tools_dir',
495                         'clang_tools_dir', 'llvm_tools_dir']
496        paths = [getattr(self.config, pp) for pp in exe_dir_props
497                 if getattr(self.config, pp, None)]
498        paths = additional_tool_dirs + paths
499        self.with_environment('PATH', paths, append_path=True)
500
501        lib_dir_props = [
502            self.config.name.lower() + '_libs_dir',
503            'llvm_shlib_dir',
504            'llvm_libs_dir',
505            ]
506        lib_paths = [getattr(self.config, pp) for pp in lib_dir_props
507                     if getattr(self.config, pp, None)]
508
509        self.with_environment('LD_LIBRARY_PATH', lib_paths, append_path=True)
510
511        shl = getattr(self.config, 'llvm_shlib_dir', None)
512        pext = getattr(self.config, 'llvm_plugin_ext', None)
513        if shl:
514            self.config.substitutions.append(('%llvmshlibdir', shl))
515        if pext:
516            self.config.substitutions.append(('%pluginext', pext))
517
518        # Discover the 'clang' and 'clangcc' to use.
519        self.config.clang = self.use_llvm_tool(
520            'clang', search_env='CLANG', required=required,
521            search_paths=paths, use_installed=use_installed)
522        if self.config.clang:
523          self.config.available_features.add('clang')
524          builtin_include_dir = self.get_clang_builtin_include_dir(
525              self.config.clang)
526          tool_substitutions = [
527              ToolSubst('%clang', command=self.config.clang,
528                        extra_args=additional_flags),
529              ToolSubst('%clang_analyze_cc1', command='%clang_cc1',
530                        extra_args=['-analyze', '%analyze',
531                                    '-setup-static-analyzer']+additional_flags),
532              ToolSubst('%clang_cc1', command=self.config.clang,
533                        extra_args=['-cc1', '-internal-isystem',
534                                    builtin_include_dir, '-nostdsysteminc'] +
535                                   additional_flags),
536              ToolSubst('%clang_cpp', command=self.config.clang,
537                        extra_args=['--driver-mode=cpp']+additional_flags),
538              ToolSubst('%clang_cl', command=self.config.clang,
539                        extra_args=['--driver-mode=cl']+additional_flags),
540              ToolSubst('%clangxx', command=self.config.clang,
541                        extra_args=['--driver-mode=g++']+additional_flags),
542              ]
543          self.add_tool_substitutions(tool_substitutions)
544          self.config.substitutions.append(
545              ('%resource_dir', builtin_include_dir))
546
547        self.config.substitutions.append(
548            ('%itanium_abi_triple',
549             self.make_itanium_abi_triple(self.config.target_triple)))
550        self.config.substitutions.append(
551            ('%ms_abi_triple',
552             self.make_msabi_triple(self.config.target_triple)))
553
554        # The host triple might not be set, at least if we're compiling clang
555        # from an already installed llvm.
556        if (self.config.host_triple and
557                self.config.host_triple != '@LLVM_HOST_TRIPLE@'):
558            self.config.substitutions.append(
559                ('%target_itanium_abi_host_triple',
560                 '--target=' + self.make_itanium_abi_triple(
561                                   self.config.host_triple)))
562        else:
563            self.config.substitutions.append(
564                ('%target_itanium_abi_host_triple', ''))
565
566        # FIXME: Find nicer way to prohibit this.
567        def prefer(this, to):
568            return '''\"*** Do not use '%s' in tests, use '%s'. ***\"''' % (
569                to, this)
570        self.config.substitutions.append(
571            (' clang ', prefer('%clang', 'clang')))
572        self.config.substitutions.append(
573            (r' clang\+\+ ', prefer('%clangxx', 'clang++')))
574        self.config.substitutions.append(
575            (' clang-cc ', prefer('%clang_cc1', 'clang-cc')))
576        self.config.substitutions.append(
577            (' clang-cl ', prefer('%clang_cl', 'clang-cl')))
578        self.config.substitutions.append(
579            (' clang -cc1 -analyze ',
580             prefer('%clang_analyze_cc1', 'clang -cc1 -analyze')))
581        self.config.substitutions.append(
582            (' clang -cc1 ', prefer('%clang_cc1', 'clang -cc1')))
583        self.config.substitutions.append(
584            (' %clang-cc1 ',
585             '''\"*** invalid substitution, use '%clang_cc1'. ***\"'''))
586        self.config.substitutions.append(
587            (' %clang-cpp ',
588             '''\"*** invalid substitution, use '%clang_cpp'. ***\"'''))
589        self.config.substitutions.append(
590            (' %clang-cl ',
591             '''\"*** invalid substitution, use '%clang_cl'. ***\"'''))
592
593    def use_lld(self, additional_tool_dirs=[], required=True,
594                use_installed=False):
595        """Configure the test suite to be able to invoke lld.
596
597        Sets up some environment variables important to lld, locates a
598        just-built or optionally an installed lld, and add a set of standard
599        substitutions useful to any test suite that makes use of lld.
600
601        """
602
603        # Tweak the PATH to include the tools dir and the scripts dir.
604        exe_dir_props = [self.config.name.lower() + '_tools_dir',
605                         'lld_tools_dir', 'llvm_tools_dir']
606        paths = [getattr(self.config, pp) for pp in exe_dir_props
607                 if getattr(self.config, pp, None)]
608        paths = additional_tool_dirs + paths
609        self.with_environment('PATH', paths, append_path=True)
610
611        lib_dir_props = [self.config.name.lower() + '_libs_dir',
612                         'lld_libs_dir', 'llvm_shlib_dir', 'llvm_libs_dir']
613        lib_paths = [getattr(self.config, pp) for pp in lib_dir_props
614                     if getattr(self.config, pp, None)]
615
616        self.with_environment('LD_LIBRARY_PATH', lib_paths, append_path=True)
617
618        # Discover the LLD executables to use.
619
620        ld_lld = self.use_llvm_tool('ld.lld', required=required,
621                                    search_paths=paths,
622                                    use_installed=use_installed)
623        lld_link = self.use_llvm_tool('lld-link', required=required,
624                                      search_paths=paths,
625                                      use_installed=use_installed)
626        ld64_lld = self.use_llvm_tool('ld64.lld', required=required,
627                                      search_paths=paths,
628                                      use_installed=use_installed)
629        wasm_ld = self.use_llvm_tool('wasm-ld', required=required,
630                                     search_paths=paths,
631                                     use_installed=use_installed)
632
633        was_found = ld_lld and lld_link and ld64_lld and wasm_ld
634        tool_substitutions = []
635        if ld_lld:
636            tool_substitutions.append(ToolSubst(r'ld\.lld', command=ld_lld))
637            self.config.available_features.add('ld.lld')
638        if lld_link:
639            tool_substitutions.append(ToolSubst('lld-link', command=lld_link))
640            self.config.available_features.add('lld-link')
641        if ld64_lld:
642            tool_substitutions.append(ToolSubst(r'ld64\.lld', command=ld64_lld))
643            self.config.available_features.add('ld64.lld')
644        if wasm_ld:
645            tool_substitutions.append(ToolSubst('wasm-ld', command=wasm_ld))
646            self.config.available_features.add('wasm-ld')
647        self.add_tool_substitutions(tool_substitutions)
648
649        return was_found
650