xref: /llvm-project/llvm/tools/llvm-config/llvm-config.cpp (revision f737865be2a115955880bb398b4bf61145db26a5)
1 //===-- llvm-config.cpp - LLVM project configuration utility --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This tool encapsulates information about an LLVM project configuration for
10 // use by other project's build environments (to determine installed path,
11 // available features, required libraries, etc.).
12 //
13 // Note that although this tool *may* be used by some parts of LLVM's build
14 // itself (i.e., the Makefiles use it to compute required libraries when linking
15 // tools), this tool is primarily designed to support external projects.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/Config/llvm-config.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/Config/config.h"
25 #include "llvm/Support/FileSystem.h"
26 #include "llvm/Support/Path.h"
27 #include "llvm/Support/WithColor.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/TargetParser/Triple.h"
30 #include <cstdlib>
31 #include <set>
32 #include <unordered_set>
33 #include <vector>
34 
35 using namespace llvm;
36 
37 // Include the build time variables we can report to the user. This is generated
38 // at build time from the BuildVariables.inc.in file by the build system.
39 #include "BuildVariables.inc"
40 
41 // Include the component table. This creates an array of struct
42 // AvailableComponent entries, which record the component name, library name,
43 // and required components for all of the available libraries.
44 //
45 // Not all components define a library, we also use "library groups" as a way to
46 // create entries for pseudo groups like x86 or all-targets.
47 #include "LibraryDependencies.inc"
48 
49 // Built-in extensions also register their dependencies, but in a separate file,
50 // later in the process.
51 #include "ExtensionDependencies.inc"
52 
53 // LinkMode determines what libraries and flags are returned by llvm-config.
54 enum LinkMode {
55   // LinkModeAuto will link with the default link mode for the installation,
56   // which is dependent on the value of LLVM_LINK_LLVM_DYLIB, and fall back
57   // to the alternative if the required libraries are not available.
58   LinkModeAuto = 0,
59 
60   // LinkModeShared will link with the dynamic component libraries if they
61   // exist, and return an error otherwise.
62   LinkModeShared = 1,
63 
64   // LinkModeStatic will link with the static component libraries if they
65   // exist, and return an error otherwise.
66   LinkModeStatic = 2,
67 };
68 
69 /// Traverse a single component adding to the topological ordering in
70 /// \arg RequiredLibs.
71 ///
72 /// \param Name - The component to traverse.
73 /// \param ComponentMap - A prebuilt map of component names to descriptors.
74 /// \param VisitedComponents [in] [out] - The set of already visited components.
75 /// \param RequiredLibs [out] - The ordered list of required
76 /// libraries.
77 /// \param GetComponentNames - Get the component names instead of the
78 /// library name.
VisitComponent(const std::string & Name,const StringMap<AvailableComponent * > & ComponentMap,std::set<AvailableComponent * > & VisitedComponents,std::vector<std::string> & RequiredLibs,bool IncludeNonInstalled,bool GetComponentNames,const std::function<std::string (const StringRef &)> * GetComponentLibraryPath,std::vector<std::string> * Missing,const std::string & DirSep)79 static void VisitComponent(const std::string &Name,
80                            const StringMap<AvailableComponent *> &ComponentMap,
81                            std::set<AvailableComponent *> &VisitedComponents,
82                            std::vector<std::string> &RequiredLibs,
83                            bool IncludeNonInstalled, bool GetComponentNames,
84                            const std::function<std::string(const StringRef &)>
85                                *GetComponentLibraryPath,
86                            std::vector<std::string> *Missing,
87                            const std::string &DirSep) {
88   // Lookup the component.
89   AvailableComponent *AC = ComponentMap.lookup(Name);
90   if (!AC) {
91     errs() << "Can't find component: '" << Name << "' in the map. Available components are: ";
92     for (const auto &Component : ComponentMap) {
93       errs() << "'" << Component.first() << "' ";
94     }
95     errs() << "\n";
96     report_fatal_error("abort");
97   }
98   assert(AC && "Invalid component name!");
99 
100   // Add to the visited table.
101   if (!VisitedComponents.insert(AC).second) {
102     // We are done if the component has already been visited.
103     return;
104   }
105 
106   // Only include non-installed components if requested.
107   if (!AC->IsInstalled && !IncludeNonInstalled)
108     return;
109 
110   // Otherwise, visit all the dependencies.
111   for (unsigned i = 0; AC->RequiredLibraries[i]; ++i) {
112     VisitComponent(AC->RequiredLibraries[i], ComponentMap, VisitedComponents,
113                    RequiredLibs, IncludeNonInstalled, GetComponentNames,
114                    GetComponentLibraryPath, Missing, DirSep);
115   }
116 
117   // Special handling for the special 'extensions' component. Its content is
118   // not populated by llvm-build, but later in the process and loaded from
119   // ExtensionDependencies.inc.
120   if (Name == "extensions") {
121     for (auto const &AvailableExtension : AvailableExtensions) {
122       for (const char *const *Iter = &AvailableExtension.RequiredLibraries[0];
123            *Iter; ++Iter) {
124         AvailableComponent *AC = ComponentMap.lookup(*Iter);
125         if (!AC) {
126           RequiredLibs.push_back(*Iter);
127         } else {
128           VisitComponent(*Iter, ComponentMap, VisitedComponents, RequiredLibs,
129                          IncludeNonInstalled, GetComponentNames,
130                          GetComponentLibraryPath, Missing, DirSep);
131         }
132       }
133     }
134   }
135 
136   if (GetComponentNames) {
137     RequiredLibs.push_back(Name);
138     return;
139   }
140 
141   // Add to the required library list.
142   if (AC->Library) {
143     if (Missing && GetComponentLibraryPath) {
144       std::string path = (*GetComponentLibraryPath)(AC->Library);
145       if (DirSep == "\\") {
146         std::replace(path.begin(), path.end(), '/', '\\');
147       }
148       if (!sys::fs::exists(path))
149         Missing->push_back(path);
150     }
151     RequiredLibs.push_back(AC->Library);
152   }
153 }
154 
155 /// Compute the list of required libraries for a given list of
156 /// components, in an order suitable for passing to a linker (that is, libraries
157 /// appear prior to their dependencies).
158 ///
159 /// \param Components - The names of the components to find libraries for.
160 /// \param IncludeNonInstalled - Whether non-installed components should be
161 /// reported.
162 /// \param GetComponentNames - True if one would prefer the component names.
ComputeLibsForComponents(const std::vector<StringRef> & Components,bool IncludeNonInstalled,bool GetComponentNames,const std::function<std::string (const StringRef &)> * GetComponentLibraryPath,std::vector<std::string> * Missing,const std::string & DirSep)163 static std::vector<std::string> ComputeLibsForComponents(
164     const std::vector<StringRef> &Components, bool IncludeNonInstalled,
165     bool GetComponentNames, const std::function<std::string(const StringRef &)>
166                                 *GetComponentLibraryPath,
167     std::vector<std::string> *Missing, const std::string &DirSep) {
168   std::vector<std::string> RequiredLibs;
169   std::set<AvailableComponent *> VisitedComponents;
170 
171   // Build a map of component names to information.
172   StringMap<AvailableComponent *> ComponentMap;
173   for (auto &AC : AvailableComponents)
174     ComponentMap[AC.Name] = &AC;
175 
176   // Visit the components.
177   for (unsigned i = 0, e = Components.size(); i != e; ++i) {
178     // Users are allowed to provide mixed case component names.
179     std::string ComponentLower = Components[i].lower();
180 
181     // Validate that the user supplied a valid component name.
182     if (!ComponentMap.count(ComponentLower)) {
183       llvm::errs() << "llvm-config: unknown component name: " << Components[i]
184                    << "\n";
185       exit(1);
186     }
187 
188     VisitComponent(ComponentLower, ComponentMap, VisitedComponents,
189                    RequiredLibs, IncludeNonInstalled, GetComponentNames,
190                    GetComponentLibraryPath, Missing, DirSep);
191   }
192 
193   // The list is now ordered with leafs first, we want the libraries to printed
194   // in the reverse order of dependency.
195   std::reverse(RequiredLibs.begin(), RequiredLibs.end());
196 
197   return RequiredLibs;
198 }
199 
200 /* *** */
201 
usage(bool ExitWithFailure=true)202 static void usage(bool ExitWithFailure = true) {
203   errs() << "\
204 usage: llvm-config <OPTION>... [<COMPONENT>...]\n\
205 \n\
206 Get various configuration information needed to compile programs which use\n\
207 LLVM.  Typically called from 'configure' scripts.  Examples:\n\
208   llvm-config --cxxflags\n\
209   llvm-config --ldflags\n\
210   llvm-config --libs engine bcreader scalaropts\n\
211 \n\
212 Options:\n\
213   --assertion-mode  Print assertion mode of LLVM tree (ON or OFF).\n\
214   --bindir          Directory containing LLVM executables.\n\
215   --build-mode      Print build mode of LLVM tree (e.g. Debug or Release).\n\
216   --build-system    Print the build system used to build LLVM (e.g. `cmake` or `gn`).\n\
217   --cflags          C compiler flags for files that include LLVM headers.\n\
218   --cmakedir        Directory containing LLVM CMake modules.\n\
219   --components      List of all possible components.\n\
220   --cppflags        C preprocessor flags for files that include LLVM headers.\n\
221   --cxxflags        C++ compiler flags for files that include LLVM headers.\n\
222   --has-rtti        Print whether or not LLVM was built with rtti (YES or NO).\n\
223   --help            Print a summary of llvm-config arguments.\n\
224   --host-target     Target triple used to configure LLVM.\n\
225   --ignore-libllvm  Ignore libLLVM and link component libraries instead.\n\
226   --includedir      Directory containing LLVM headers.\n\
227   --ldflags         Print Linker flags.\n\
228   --libdir          Directory containing LLVM libraries.\n\
229   --libfiles        Fully qualified library filenames for makefile depends.\n\
230   --libnames        Bare library names for in-tree builds.\n\
231   --libs            Libraries needed to link against LLVM components.\n\
232   --link-shared     Link the components as shared libraries.\n\
233   --link-static     Link the component libraries statically.\n\
234   --obj-root        Print the object root used to build LLVM.\n\
235   --prefix          Print the installation prefix.\n\
236   --shared-mode     Print how the provided components can be collectively linked (`shared` or `static`).\n\
237   --system-libs     System Libraries needed to link against LLVM components.\n\
238   --targets-built   List of all targets currently built.\n\
239   --version         Print LLVM version.\n\
240 Typical components:\n\
241   all               All LLVM libraries (default).\n\
242   engine            Either a native JIT or a bitcode interpreter.\n";
243   if (ExitWithFailure)
244     exit(1);
245 }
246 
247 /// Compute the path to the main executable.
GetExecutablePath(const char * Argv0)248 std::string GetExecutablePath(const char *Argv0) {
249   // This just needs to be some symbol in the binary; C++ doesn't
250   // allow taking the address of ::main however.
251   void *P = (void *)(intptr_t)GetExecutablePath;
252   return llvm::sys::fs::getMainExecutable(Argv0, P);
253 }
254 
255 /// Expand the semi-colon delimited LLVM_DYLIB_COMPONENTS into
256 /// the full list of components.
GetAllDyLibComponents(const bool IsInDevelopmentTree,const bool GetComponentNames,const std::string & DirSep)257 std::vector<std::string> GetAllDyLibComponents(const bool IsInDevelopmentTree,
258                                                const bool GetComponentNames,
259                                                const std::string &DirSep) {
260   std::vector<StringRef> DyLibComponents;
261 
262   StringRef DyLibComponentsStr(LLVM_DYLIB_COMPONENTS);
263   size_t Offset = 0;
264   while (true) {
265     const size_t NextOffset = DyLibComponentsStr.find(';', Offset);
266     DyLibComponents.push_back(DyLibComponentsStr.substr(Offset, NextOffset-Offset));
267     if (NextOffset == std::string::npos) {
268       break;
269     }
270     Offset = NextOffset + 1;
271   }
272 
273   assert(!DyLibComponents.empty());
274 
275   return ComputeLibsForComponents(DyLibComponents,
276                                   /*IncludeNonInstalled=*/IsInDevelopmentTree,
277                                   GetComponentNames, nullptr, nullptr, DirSep);
278 }
279 
main(int argc,char ** argv)280 int main(int argc, char **argv) {
281   std::vector<StringRef> Components;
282   bool PrintLibs = false, PrintLibNames = false, PrintLibFiles = false;
283   bool PrintSystemLibs = false, PrintSharedMode = false;
284   bool HasAnyOption = false;
285 
286   // llvm-config is designed to support being run both from a development tree
287   // and from an installed path. We try and auto-detect which case we are in so
288   // that we can report the correct information when run from a development
289   // tree.
290   bool IsInDevelopmentTree;
291   enum { CMakeStyle, CMakeBuildModeStyle } DevelopmentTreeLayout;
292   llvm::SmallString<256> CurrentPath(GetExecutablePath(argv[0]));
293   std::string CurrentExecPrefix;
294   std::string ActiveObjRoot;
295 
296   // If CMAKE_CFG_INTDIR is given, honor it as build mode.
297   char const *build_mode = LLVM_BUILDMODE;
298 #if defined(CMAKE_CFG_INTDIR)
299   if (!(CMAKE_CFG_INTDIR[0] == '.' && CMAKE_CFG_INTDIR[1] == '\0'))
300     build_mode = CMAKE_CFG_INTDIR;
301 #endif
302 
303   // Create an absolute path, and pop up one directory (we expect to be inside a
304   // bin dir).
305   sys::fs::make_absolute(CurrentPath);
306   CurrentExecPrefix =
307       sys::path::parent_path(sys::path::parent_path(CurrentPath)).str();
308 
309   // Check to see if we are inside a development tree by comparing to possible
310   // locations (prefix style or CMake style).
311   if (sys::fs::equivalent(CurrentExecPrefix, LLVM_OBJ_ROOT)) {
312     IsInDevelopmentTree = true;
313     DevelopmentTreeLayout = CMakeStyle;
314     ActiveObjRoot = LLVM_OBJ_ROOT;
315   } else if (sys::fs::equivalent(sys::path::parent_path(CurrentExecPrefix),
316                                  LLVM_OBJ_ROOT)) {
317     IsInDevelopmentTree = true;
318     DevelopmentTreeLayout = CMakeBuildModeStyle;
319     ActiveObjRoot = LLVM_OBJ_ROOT;
320   } else {
321     IsInDevelopmentTree = false;
322     DevelopmentTreeLayout = CMakeStyle; // Initialized to avoid warnings.
323   }
324 
325   // Compute various directory locations based on the derived location
326   // information.
327   std::string ActivePrefix, ActiveBinDir, ActiveIncludeDir, ActiveLibDir,
328               ActiveCMakeDir;
329   std::string ActiveIncludeOption;
330   if (IsInDevelopmentTree) {
331     ActiveIncludeDir = std::string(LLVM_SRC_ROOT) + "/include";
332     ActivePrefix = CurrentExecPrefix;
333 
334     // CMake organizes the products differently than a normal prefix style
335     // layout.
336     switch (DevelopmentTreeLayout) {
337     case CMakeStyle:
338       ActiveBinDir = ActiveObjRoot + "/bin";
339       ActiveLibDir = ActiveObjRoot + "/lib" + LLVM_LIBDIR_SUFFIX;
340       ActiveCMakeDir = ActiveLibDir + "/cmake/llvm";
341       break;
342     case CMakeBuildModeStyle:
343       // FIXME: Should we consider the build-mode-specific path as the prefix?
344       ActivePrefix = ActiveObjRoot;
345       ActiveBinDir = ActiveObjRoot + "/" + build_mode + "/bin";
346       ActiveLibDir =
347           ActiveObjRoot + "/" + build_mode + "/lib" + LLVM_LIBDIR_SUFFIX;
348       // The CMake directory isn't separated by build mode.
349       ActiveCMakeDir =
350           ActivePrefix + "/lib" + LLVM_LIBDIR_SUFFIX + "/cmake/llvm";
351       break;
352     }
353 
354     // We need to include files from both the source and object trees.
355     ActiveIncludeOption =
356         ("-I" + ActiveIncludeDir + " " + "-I" + ActiveObjRoot + "/include");
357   } else {
358     ActivePrefix = CurrentExecPrefix;
359     {
360       SmallString<256> Path(LLVM_INSTALL_INCLUDEDIR);
361       sys::fs::make_absolute(ActivePrefix, Path);
362       ActiveIncludeDir = std::string(Path);
363     }
364     {
365       SmallString<256> Path(LLVM_TOOLS_INSTALL_DIR);
366       sys::fs::make_absolute(ActivePrefix, Path);
367       ActiveBinDir = std::string(Path);
368     }
369     ActiveLibDir = ActivePrefix + "/lib" + LLVM_LIBDIR_SUFFIX;
370     {
371       SmallString<256> Path(LLVM_INSTALL_PACKAGE_DIR);
372       sys::fs::make_absolute(ActivePrefix, Path);
373       ActiveCMakeDir = std::string(Path);
374     }
375     ActiveIncludeOption = "-I" + ActiveIncludeDir;
376   }
377 
378   /// We only use `shared library` mode in cases where the static library form
379   /// of the components provided are not available; note however that this is
380   /// skipped if we're run from within the build dir. However, once installed,
381   /// we still need to provide correct output when the static archives are
382   /// removed or, as in the case of CMake's `BUILD_SHARED_LIBS`, never present
383   /// in the first place. This can't be done at configure/build time.
384 
385   StringRef SharedExt, SharedVersionedExt, SharedDir, SharedPrefix, StaticExt,
386       StaticPrefix, StaticDir = "lib";
387   std::string DirSep = "/";
388   const Triple HostTriple(Triple::normalize(LLVM_HOST_TRIPLE));
389   if (HostTriple.isOSWindows()) {
390     SharedExt = "dll";
391     SharedVersionedExt = LLVM_DYLIB_VERSION ".dll";
392     if (HostTriple.isOSCygMing()) {
393       SharedPrefix = "lib";
394       StaticExt = "a";
395       StaticPrefix = "lib";
396     } else {
397       StaticExt = "lib";
398       DirSep = "\\";
399       std::replace(ActiveObjRoot.begin(), ActiveObjRoot.end(), '/', '\\');
400       std::replace(ActivePrefix.begin(), ActivePrefix.end(), '/', '\\');
401       std::replace(ActiveBinDir.begin(), ActiveBinDir.end(), '/', '\\');
402       std::replace(ActiveLibDir.begin(), ActiveLibDir.end(), '/', '\\');
403       std::replace(ActiveCMakeDir.begin(), ActiveCMakeDir.end(), '/', '\\');
404       std::replace(ActiveIncludeOption.begin(), ActiveIncludeOption.end(), '/',
405                    '\\');
406     }
407     SharedDir = ActiveBinDir;
408     StaticDir = ActiveLibDir;
409   } else if (HostTriple.isOSDarwin()) {
410     SharedExt = "dylib";
411     SharedVersionedExt = LLVM_DYLIB_VERSION ".dylib";
412     StaticExt = "a";
413     StaticDir = SharedDir = ActiveLibDir;
414     StaticPrefix = SharedPrefix = "lib";
415   } else {
416     // default to the unix values:
417     SharedExt = "so";
418     SharedVersionedExt = LLVM_DYLIB_VERSION ".so";
419     StaticExt = "a";
420     StaticDir = SharedDir = ActiveLibDir;
421     StaticPrefix = SharedPrefix = "lib";
422   }
423 
424   const bool BuiltDyLib = !!LLVM_ENABLE_DYLIB;
425 
426   /// CMake style shared libs, ie each component is in a shared library.
427   const bool BuiltSharedLibs = !!LLVM_ENABLE_SHARED;
428 
429   bool DyLibExists = false;
430   const std::string DyLibName =
431       (SharedPrefix + "LLVM-" + SharedVersionedExt).str();
432 
433   // If LLVM_LINK_DYLIB is ON, the single shared library will be returned
434   // for "--libs", etc, if they exist. This behaviour can be overridden with
435   // --link-static or --link-shared.
436   bool LinkDyLib = !!LLVM_LINK_DYLIB;
437 
438   if (BuiltDyLib) {
439     std::string path((SharedDir + DirSep + DyLibName).str());
440     if (DirSep == "\\") {
441       std::replace(path.begin(), path.end(), '/', '\\');
442     }
443     DyLibExists = sys::fs::exists(path);
444     if (!DyLibExists) {
445       // The shared library does not exist: don't error unless the user
446       // explicitly passes --link-shared.
447       LinkDyLib = false;
448     }
449   }
450   LinkMode LinkMode =
451       (LinkDyLib || BuiltSharedLibs) ? LinkModeShared : LinkModeAuto;
452 
453   /// Get the component's library name without the lib prefix and the
454   /// extension. Returns true if Lib is in a recognized format.
455   auto GetComponentLibraryNameSlice = [&](const StringRef &Lib,
456                                           StringRef &Out) {
457     if (Lib.starts_with("lib")) {
458       unsigned FromEnd;
459       if (Lib.ends_with(StaticExt)) {
460         FromEnd = StaticExt.size() + 1;
461       } else if (Lib.ends_with(SharedExt)) {
462         FromEnd = SharedExt.size() + 1;
463       } else {
464         FromEnd = 0;
465       }
466 
467       if (FromEnd != 0) {
468         Out = Lib.slice(3, Lib.size() - FromEnd);
469         return true;
470       }
471     }
472 
473     return false;
474   };
475   /// Maps Unixizms to the host platform.
476   auto GetComponentLibraryFileName = [&](const StringRef &Lib,
477                                          const bool Shared) {
478     std::string LibFileName;
479     if (Shared) {
480       if (Lib == DyLibName) {
481         // Treat the DyLibName specially. It is not a component library and
482         // already has the necessary prefix and suffix (e.g. `.so`) added so
483         // just return it unmodified.
484         assert(Lib.ends_with(SharedExt) && "DyLib is missing suffix");
485         LibFileName = std::string(Lib);
486       } else {
487         LibFileName = (SharedPrefix + Lib + "." + SharedExt).str();
488       }
489     } else {
490       // default to static
491       LibFileName = (StaticPrefix + Lib + "." + StaticExt).str();
492     }
493 
494     return LibFileName;
495   };
496   /// Get the full path for a possibly shared component library.
497   auto GetComponentLibraryPath = [&](const StringRef &Name, const bool Shared) {
498     auto LibFileName = GetComponentLibraryFileName(Name, Shared);
499     if (Shared) {
500       return (SharedDir + DirSep + LibFileName).str();
501     } else {
502       return (StaticDir + DirSep + LibFileName).str();
503     }
504   };
505 
506   raw_ostream &OS = outs();
507   for (int i = 1; i != argc; ++i) {
508     StringRef Arg = argv[i];
509 
510     if (Arg.starts_with("-")) {
511       HasAnyOption = true;
512       if (Arg == "--version") {
513         OS << PACKAGE_VERSION << '\n';
514       } else if (Arg == "--prefix") {
515         OS << ActivePrefix << '\n';
516       } else if (Arg == "--bindir") {
517         OS << ActiveBinDir << '\n';
518       } else if (Arg == "--includedir") {
519         OS << ActiveIncludeDir << '\n';
520       } else if (Arg == "--libdir") {
521         OS << ActiveLibDir << '\n';
522       } else if (Arg == "--cmakedir") {
523         OS << ActiveCMakeDir << '\n';
524       } else if (Arg == "--cppflags") {
525         OS << ActiveIncludeOption << ' ' << LLVM_CPPFLAGS << '\n';
526       } else if (Arg == "--cflags") {
527         OS << ActiveIncludeOption << ' ' << LLVM_CFLAGS << '\n';
528       } else if (Arg == "--cxxflags") {
529         OS << ActiveIncludeOption << ' ' << LLVM_CXXFLAGS << '\n';
530       } else if (Arg == "--ldflags") {
531         OS << ((HostTriple.isWindowsMSVCEnvironment()) ? "-LIBPATH:" : "-L")
532            << ActiveLibDir << ' ' << LLVM_LDFLAGS << '\n';
533       } else if (Arg == "--system-libs") {
534         PrintSystemLibs = true;
535       } else if (Arg == "--libs") {
536         PrintLibs = true;
537       } else if (Arg == "--libnames") {
538         PrintLibNames = true;
539       } else if (Arg == "--libfiles") {
540         PrintLibFiles = true;
541       } else if (Arg == "--components") {
542         /// If there are missing static archives and a dylib was
543         /// built, print LLVM_DYLIB_COMPONENTS instead of everything
544         /// in the manifest.
545         std::vector<std::string> Components;
546         for (const auto &AC : AvailableComponents) {
547           // Only include non-installed components when in a development tree.
548           if (!AC.IsInstalled && !IsInDevelopmentTree)
549             continue;
550 
551           Components.push_back(AC.Name);
552           if (AC.Library && !IsInDevelopmentTree) {
553             std::string path(GetComponentLibraryPath(AC.Library, false));
554             if (DirSep == "\\") {
555               std::replace(path.begin(), path.end(), '/', '\\');
556             }
557             if (DyLibExists && !sys::fs::exists(path)) {
558               Components =
559                   GetAllDyLibComponents(IsInDevelopmentTree, true, DirSep);
560               llvm::sort(Components);
561               break;
562             }
563           }
564         }
565 
566         for (unsigned I = 0; I < Components.size(); ++I) {
567           if (I) {
568             OS << ' ';
569           }
570 
571           OS << Components[I];
572         }
573         OS << '\n';
574       } else if (Arg == "--targets-built") {
575         OS << LLVM_TARGETS_BUILT << '\n';
576       } else if (Arg == "--host-target") {
577         OS << Triple::normalize(LLVM_DEFAULT_TARGET_TRIPLE) << '\n';
578       } else if (Arg == "--build-mode") {
579         OS << build_mode << '\n';
580       } else if (Arg == "--assertion-mode") {
581 #if defined(NDEBUG)
582         OS << "OFF\n";
583 #else
584         OS << "ON\n";
585 #endif
586       } else if (Arg == "--build-system") {
587         OS << LLVM_BUILD_SYSTEM << '\n';
588       } else if (Arg == "--has-rtti") {
589         OS << (LLVM_HAS_RTTI ? "YES" : "NO") << '\n';
590       } else if (Arg == "--shared-mode") {
591         PrintSharedMode = true;
592       } else if (Arg == "--obj-root") {
593         OS << ActivePrefix << '\n';
594       } else if (Arg == "--ignore-libllvm") {
595         LinkDyLib = false;
596         LinkMode = BuiltSharedLibs ? LinkModeShared : LinkModeAuto;
597       } else if (Arg == "--link-shared") {
598         LinkMode = LinkModeShared;
599       } else if (Arg == "--link-static") {
600         LinkMode = LinkModeStatic;
601       } else if (Arg == "--help") {
602         usage(false);
603       } else {
604         usage();
605       }
606     } else {
607       Components.push_back(Arg);
608     }
609   }
610 
611   if (!HasAnyOption)
612     usage();
613 
614   if (LinkMode == LinkModeShared && !DyLibExists && !BuiltSharedLibs) {
615     WithColor::error(errs(), "llvm-config") << DyLibName << " is missing\n";
616     return 1;
617   }
618 
619   if (PrintLibs || PrintLibNames || PrintLibFiles || PrintSystemLibs ||
620       PrintSharedMode) {
621 
622     if (PrintSharedMode && BuiltSharedLibs) {
623       OS << "shared\n";
624       return 0;
625     }
626 
627     // If no components were specified, default to "all".
628     if (Components.empty())
629       Components.push_back("all");
630 
631     // Construct the list of all the required libraries.
632     std::function<std::string(const StringRef &)>
633         GetComponentLibraryPathFunction = [&](const StringRef &Name) {
634           return GetComponentLibraryPath(Name, LinkMode == LinkModeShared);
635         };
636     std::vector<std::string> MissingLibs;
637     std::vector<std::string> RequiredLibs = ComputeLibsForComponents(
638         Components,
639         /*IncludeNonInstalled=*/IsInDevelopmentTree, false,
640         &GetComponentLibraryPathFunction, &MissingLibs, DirSep);
641     if (!MissingLibs.empty()) {
642       switch (LinkMode) {
643       case LinkModeShared:
644         if (LinkDyLib && !BuiltSharedLibs)
645           break;
646         // Using component shared libraries.
647         for (auto &Lib : MissingLibs)
648           WithColor::error(errs(), "llvm-config") << "missing: " << Lib << "\n";
649         return 1;
650       case LinkModeAuto:
651         if (DyLibExists) {
652           LinkMode = LinkModeShared;
653           break;
654         }
655         WithColor::error(errs(), "llvm-config")
656             << "component libraries and shared library\n\n";
657         [[fallthrough]];
658       case LinkModeStatic:
659         for (auto &Lib : MissingLibs)
660           WithColor::error(errs(), "llvm-config") << "missing: " << Lib << "\n";
661         return 1;
662       }
663     } else if (LinkMode == LinkModeAuto) {
664       LinkMode = LinkModeStatic;
665     }
666 
667     if (PrintSharedMode) {
668       std::unordered_set<std::string> FullDyLibComponents;
669       std::vector<std::string> DyLibComponents =
670           GetAllDyLibComponents(IsInDevelopmentTree, false, DirSep);
671 
672       for (auto &Component : DyLibComponents) {
673         FullDyLibComponents.insert(Component);
674       }
675       DyLibComponents.clear();
676 
677       for (auto &Lib : RequiredLibs) {
678         if (!FullDyLibComponents.count(Lib)) {
679           OS << "static\n";
680           return 0;
681         }
682       }
683       FullDyLibComponents.clear();
684 
685       if (LinkMode == LinkModeShared) {
686         OS << "shared\n";
687         return 0;
688       } else {
689         OS << "static\n";
690         return 0;
691       }
692     }
693 
694     if (PrintLibs || PrintLibNames || PrintLibFiles) {
695 
696       auto PrintForLib = [&](const StringRef &Lib) {
697         const bool Shared = LinkMode == LinkModeShared;
698         if (PrintLibNames) {
699           OS << GetComponentLibraryFileName(Lib, Shared);
700         } else if (PrintLibFiles) {
701           OS << GetComponentLibraryPath(Lib, Shared);
702         } else if (PrintLibs) {
703           // On Windows, output full path to library without parameters.
704           // Elsewhere, if this is a typical library name, include it using -l.
705           if (HostTriple.isWindowsMSVCEnvironment()) {
706             OS << GetComponentLibraryPath(Lib, Shared);
707           } else {
708             StringRef LibName;
709             if (GetComponentLibraryNameSlice(Lib, LibName)) {
710               // Extract library name (remove prefix and suffix).
711               OS << "-l" << LibName;
712             } else {
713               // Lib is already a library name without prefix and suffix.
714               OS << "-l" << Lib;
715             }
716           }
717         }
718       };
719 
720       if (LinkMode == LinkModeShared && LinkDyLib) {
721         PrintForLib(DyLibName);
722       } else {
723         for (unsigned i = 0, e = RequiredLibs.size(); i != e; ++i) {
724           auto Lib = RequiredLibs[i];
725           if (i)
726             OS << ' ';
727 
728           PrintForLib(Lib);
729         }
730       }
731       OS << '\n';
732     }
733 
734     // Print SYSTEM_LIBS after --libs.
735     // FIXME: Each LLVM component may have its dependent system libs.
736     if (PrintSystemLibs) {
737       // Output system libraries only if linking against a static
738       // library (since the shared library links to all system libs
739       // already)
740       OS << (LinkMode == LinkModeStatic ? LLVM_SYSTEM_LIBS : "") << '\n';
741     }
742   } else if (!Components.empty()) {
743     WithColor::error(errs(), "llvm-config")
744         << "components given, but unused\n\n";
745     usage();
746   }
747 
748   return 0;
749 }
750