xref: /llvm-project/llvm/tools/llvm-config/llvm-config.cpp (revision a5640968f2f7485b2aa4919f5fa68fd8f23e2d1f)
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/Triple.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/Config/config.h"
26 #include "llvm/Support/FileSystem.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Support/WithColor.h"
29 #include "llvm/Support/raw_ostream.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.
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.
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 (unsigned i = 0; i != array_lengthof(AvailableComponents); ++i) {
174     AvailableComponent *AC = &AvailableComponents[i];
175     ComponentMap[AC->Name] = AC;
176   }
177 
178   // Visit the components.
179   for (unsigned i = 0, e = Components.size(); i != e; ++i) {
180     // Users are allowed to provide mixed case component names.
181     std::string ComponentLower = Components[i].lower();
182 
183     // Validate that the user supplied a valid component name.
184     if (!ComponentMap.count(ComponentLower)) {
185       llvm::errs() << "llvm-config: unknown component name: " << Components[i]
186                    << "\n";
187       exit(1);
188     }
189 
190     VisitComponent(ComponentLower, ComponentMap, VisitedComponents,
191                    RequiredLibs, IncludeNonInstalled, GetComponentNames,
192                    GetComponentLibraryPath, Missing, DirSep);
193   }
194 
195   // The list is now ordered with leafs first, we want the libraries to printed
196   // in the reverse order of dependency.
197   std::reverse(RequiredLibs.begin(), RequiredLibs.end());
198 
199   return RequiredLibs;
200 }
201 
202 /* *** */
203 
204 static void usage(bool ExitWithFailure = true) {
205   errs() << "\
206 usage: llvm-config <OPTION>... [<COMPONENT>...]\n\
207 \n\
208 Get various configuration information needed to compile programs which use\n\
209 LLVM.  Typically called from 'configure' scripts.  Examples:\n\
210   llvm-config --cxxflags\n\
211   llvm-config --ldflags\n\
212   llvm-config --libs engine bcreader scalaropts\n\
213 \n\
214 Options:\n\
215   --assertion-mode  Print assertion mode of LLVM tree (ON or OFF).\n\
216   --bindir          Directory containing LLVM executables.\n\
217   --build-mode      Print build mode of LLVM tree (e.g. Debug or Release).\n\
218   --build-system    Print the build system used to build LLVM (e.g. `cmake` or `gn`).\n\
219   --cflags          C compiler flags for files that include LLVM headers.\n\
220   --cmakedir        Directory containing LLVM CMake modules.\n\
221   --components      List of all possible components.\n\
222   --cppflags        C preprocessor flags for files that include LLVM headers.\n\
223   --cxxflags        C++ compiler flags for files that include LLVM headers.\n\
224   --has-rtti        Print whether or not LLVM was built with rtti (YES or NO).\n\
225   --help            Print a summary of llvm-config arguments.\n\
226   --host-target     Target triple used to configure LLVM.\n\
227   --ignore-libllvm  Ignore libLLVM and link component libraries instead.\n\
228   --includedir      Directory containing LLVM headers.\n\
229   --ldflags         Print Linker flags.\n\
230   --libdir          Directory containing LLVM libraries.\n\
231   --libfiles        Fully qualified library filenames for makefile depends.\n\
232   --libnames        Bare library names for in-tree builds.\n\
233   --libs            Libraries needed to link against LLVM components.\n\
234   --link-shared     Link the components as shared libraries.\n\
235   --link-static     Link the component libraries statically.\n\
236   --obj-root        Print the object root used to build LLVM.\n\
237   --prefix          Print the installation prefix.\n\
238   --shared-mode     Print how the provided components can be collectively linked (`shared` or `static`).\n\
239   --src-root        Print the source root LLVM was built from.\n\
240   --system-libs     System Libraries needed to link against LLVM components.\n\
241   --targets-built   List of all targets currently built.\n\
242   --version         Print LLVM version.\n\
243 Typical components:\n\
244   all               All LLVM libraries (default).\n\
245   engine            Either a native JIT or a bitcode interpreter.\n";
246   if (ExitWithFailure)
247     exit(1);
248 }
249 
250 /// Compute the path to the main executable.
251 std::string GetExecutablePath(const char *Argv0) {
252   // This just needs to be some symbol in the binary; C++ doesn't
253   // allow taking the address of ::main however.
254   void *P = (void *)(intptr_t)GetExecutablePath;
255   return llvm::sys::fs::getMainExecutable(Argv0, P);
256 }
257 
258 /// Expand the semi-colon delimited LLVM_DYLIB_COMPONENTS into
259 /// the full list of components.
260 std::vector<std::string> GetAllDyLibComponents(const bool IsInDevelopmentTree,
261                                                const bool GetComponentNames,
262                                                const std::string &DirSep) {
263   std::vector<StringRef> DyLibComponents;
264 
265   StringRef DyLibComponentsStr(LLVM_DYLIB_COMPONENTS);
266   size_t Offset = 0;
267   while (true) {
268     const size_t NextOffset = DyLibComponentsStr.find(';', Offset);
269     DyLibComponents.push_back(DyLibComponentsStr.substr(Offset, NextOffset-Offset));
270     if (NextOffset == std::string::npos) {
271       break;
272     }
273     Offset = NextOffset + 1;
274   }
275 
276   assert(!DyLibComponents.empty());
277 
278   return ComputeLibsForComponents(DyLibComponents,
279                                   /*IncludeNonInstalled=*/IsInDevelopmentTree,
280                                   GetComponentNames, nullptr, nullptr, DirSep);
281 }
282 
283 int main(int argc, char **argv) {
284   std::vector<StringRef> Components;
285   bool PrintLibs = false, PrintLibNames = false, PrintLibFiles = false;
286   bool PrintSystemLibs = false, PrintSharedMode = false;
287   bool HasAnyOption = false;
288 
289   // llvm-config is designed to support being run both from a development tree
290   // and from an installed path. We try and auto-detect which case we are in so
291   // that we can report the correct information when run from a development
292   // tree.
293   bool IsInDevelopmentTree;
294   enum { CMakeStyle, CMakeBuildModeStyle } DevelopmentTreeLayout;
295   llvm::SmallString<256> CurrentPath(GetExecutablePath(argv[0]));
296   std::string CurrentExecPrefix;
297   std::string ActiveObjRoot;
298 
299   // If CMAKE_CFG_INTDIR is given, honor it as build mode.
300   char const *build_mode = LLVM_BUILDMODE;
301 #if defined(CMAKE_CFG_INTDIR)
302   if (!(CMAKE_CFG_INTDIR[0] == '.' && CMAKE_CFG_INTDIR[1] == '\0'))
303     build_mode = CMAKE_CFG_INTDIR;
304 #endif
305 
306   // Create an absolute path, and pop up one directory (we expect to be inside a
307   // bin dir).
308   sys::fs::make_absolute(CurrentPath);
309   CurrentExecPrefix =
310       sys::path::parent_path(sys::path::parent_path(CurrentPath)).str();
311 
312   // Check to see if we are inside a development tree by comparing to possible
313   // locations (prefix style or CMake style).
314   if (sys::fs::equivalent(CurrentExecPrefix, LLVM_OBJ_ROOT)) {
315     IsInDevelopmentTree = true;
316     DevelopmentTreeLayout = CMakeStyle;
317     ActiveObjRoot = LLVM_OBJ_ROOT;
318   } else if (sys::fs::equivalent(sys::path::parent_path(CurrentExecPrefix),
319                                  LLVM_OBJ_ROOT)) {
320     IsInDevelopmentTree = true;
321     DevelopmentTreeLayout = CMakeBuildModeStyle;
322     ActiveObjRoot = LLVM_OBJ_ROOT;
323   } else {
324     IsInDevelopmentTree = false;
325     DevelopmentTreeLayout = CMakeStyle; // Initialized to avoid warnings.
326   }
327 
328   // Compute various directory locations based on the derived location
329   // information.
330   std::string ActivePrefix, ActiveBinDir, ActiveIncludeDir, ActiveLibDir,
331               ActiveCMakeDir;
332   std::string ActiveIncludeOption;
333   if (IsInDevelopmentTree) {
334     ActiveIncludeDir = std::string(LLVM_SRC_ROOT) + "/include";
335     ActivePrefix = CurrentExecPrefix;
336 
337     // CMake organizes the products differently than a normal prefix style
338     // layout.
339     switch (DevelopmentTreeLayout) {
340     case CMakeStyle:
341       ActiveBinDir = ActiveObjRoot + "/bin";
342       ActiveLibDir = ActiveObjRoot + "/lib" + LLVM_LIBDIR_SUFFIX;
343       ActiveCMakeDir = ActiveLibDir + "/cmake/llvm";
344       break;
345     case CMakeBuildModeStyle:
346       // FIXME: Should we consider the build-mode-specific path as the prefix?
347       ActivePrefix = ActiveObjRoot;
348       ActiveBinDir = ActiveObjRoot + "/" + build_mode + "/bin";
349       ActiveLibDir =
350           ActiveObjRoot + "/" + build_mode + "/lib" + LLVM_LIBDIR_SUFFIX;
351       // The CMake directory isn't separated by build mode.
352       ActiveCMakeDir =
353           ActivePrefix + "/lib" + LLVM_LIBDIR_SUFFIX + "/cmake/llvm";
354       break;
355     }
356 
357     // We need to include files from both the source and object trees.
358     ActiveIncludeOption =
359         ("-I" + ActiveIncludeDir + " " + "-I" + ActiveObjRoot + "/include");
360   } else {
361     ActivePrefix = CurrentExecPrefix;
362     {
363       SmallString<256> Path(LLVM_INSTALL_INCLUDEDIR);
364       sys::fs::make_absolute(ActivePrefix, Path);
365       ActiveIncludeDir = std::string(Path.str());
366     }
367     {
368       SmallString<256> Path(LLVM_TOOLS_INSTALL_DIR);
369       sys::fs::make_absolute(ActivePrefix, Path);
370       ActiveBinDir = std::string(Path.str());
371     }
372     ActiveLibDir = ActivePrefix + "/lib" + LLVM_LIBDIR_SUFFIX;
373     {
374       SmallString<256> Path(LLVM_INSTALL_PACKAGE_DIR);
375       sys::fs::make_absolute(ActivePrefix, Path);
376       ActiveCMakeDir = std::string(Path.str());
377     }
378     ActiveIncludeOption = "-I" + ActiveIncludeDir;
379   }
380 
381   /// We only use `shared library` mode in cases where the static library form
382   /// of the components provided are not available; note however that this is
383   /// skipped if we're run from within the build dir. However, once installed,
384   /// we still need to provide correct output when the static archives are
385   /// removed or, as in the case of CMake's `BUILD_SHARED_LIBS`, never present
386   /// in the first place. This can't be done at configure/build time.
387 
388   StringRef SharedExt, SharedVersionedExt, SharedDir, SharedPrefix, StaticExt,
389       StaticPrefix, StaticDir = "lib";
390   std::string DirSep = "/";
391   const Triple HostTriple(Triple::normalize(LLVM_HOST_TRIPLE));
392   if (HostTriple.isOSWindows()) {
393     SharedExt = "dll";
394     SharedVersionedExt = LLVM_DYLIB_VERSION ".dll";
395     if (HostTriple.isOSCygMing()) {
396       SharedPrefix = "lib";
397       StaticExt = "a";
398       StaticPrefix = "lib";
399     } else {
400       StaticExt = "lib";
401       DirSep = "\\";
402       std::replace(ActiveObjRoot.begin(), ActiveObjRoot.end(), '/', '\\');
403       std::replace(ActivePrefix.begin(), ActivePrefix.end(), '/', '\\');
404       std::replace(ActiveBinDir.begin(), ActiveBinDir.end(), '/', '\\');
405       std::replace(ActiveLibDir.begin(), ActiveLibDir.end(), '/', '\\');
406       std::replace(ActiveCMakeDir.begin(), ActiveCMakeDir.end(), '/', '\\');
407       std::replace(ActiveIncludeOption.begin(), ActiveIncludeOption.end(), '/',
408                    '\\');
409     }
410     SharedDir = ActiveBinDir;
411     StaticDir = ActiveLibDir;
412   } else if (HostTriple.isOSDarwin()) {
413     SharedExt = "dylib";
414     SharedVersionedExt = LLVM_DYLIB_VERSION ".dylib";
415     StaticExt = "a";
416     StaticDir = SharedDir = ActiveLibDir;
417     StaticPrefix = SharedPrefix = "lib";
418   } else {
419     // default to the unix values:
420     SharedExt = "so";
421     SharedVersionedExt = LLVM_DYLIB_VERSION ".so";
422     StaticExt = "a";
423     StaticDir = SharedDir = ActiveLibDir;
424     StaticPrefix = SharedPrefix = "lib";
425   }
426 
427   const bool BuiltDyLib = !!LLVM_ENABLE_DYLIB;
428 
429   /// CMake style shared libs, ie each component is in a shared library.
430   const bool BuiltSharedLibs = !!LLVM_ENABLE_SHARED;
431 
432   bool DyLibExists = false;
433   const std::string DyLibName =
434       (SharedPrefix + "LLVM-" + SharedVersionedExt).str();
435 
436   // If LLVM_LINK_DYLIB is ON, the single shared library will be returned
437   // for "--libs", etc, if they exist. This behaviour can be overridden with
438   // --link-static or --link-shared.
439   bool LinkDyLib = !!LLVM_LINK_DYLIB;
440 
441   if (BuiltDyLib) {
442     std::string path((SharedDir + DirSep + DyLibName).str());
443     if (DirSep == "\\") {
444       std::replace(path.begin(), path.end(), '/', '\\');
445     }
446     DyLibExists = sys::fs::exists(path);
447     if (!DyLibExists) {
448       // The shared library does not exist: don't error unless the user
449       // explicitly passes --link-shared.
450       LinkDyLib = false;
451     }
452   }
453   LinkMode LinkMode =
454       (LinkDyLib || BuiltSharedLibs) ? LinkModeShared : LinkModeAuto;
455 
456   /// Get the component's library name without the lib prefix and the
457   /// extension. Returns true if Lib is in a recognized format.
458   auto GetComponentLibraryNameSlice = [&](const StringRef &Lib,
459                                           StringRef &Out) {
460     if (Lib.startswith("lib")) {
461       unsigned FromEnd;
462       if (Lib.endswith(StaticExt)) {
463         FromEnd = StaticExt.size() + 1;
464       } else if (Lib.endswith(SharedExt)) {
465         FromEnd = SharedExt.size() + 1;
466       } else {
467         FromEnd = 0;
468       }
469 
470       if (FromEnd != 0) {
471         Out = Lib.slice(3, Lib.size() - FromEnd);
472         return true;
473       }
474     }
475 
476     return false;
477   };
478   /// Maps Unixizms to the host platform.
479   auto GetComponentLibraryFileName = [&](const StringRef &Lib,
480                                          const bool Shared) {
481     std::string LibFileName;
482     if (Shared) {
483       if (Lib == DyLibName) {
484         // Treat the DyLibName specially. It is not a component library and
485         // already has the necessary prefix and suffix (e.g. `.so`) added so
486         // just return it unmodified.
487         assert(Lib.endswith(SharedExt) && "DyLib is missing suffix");
488         LibFileName = std::string(Lib);
489       } else {
490         LibFileName = (SharedPrefix + Lib + "." + SharedExt).str();
491       }
492     } else {
493       // default to static
494       LibFileName = (StaticPrefix + Lib + "." + StaticExt).str();
495     }
496 
497     return LibFileName;
498   };
499   /// Get the full path for a possibly shared component library.
500   auto GetComponentLibraryPath = [&](const StringRef &Name, const bool Shared) {
501     auto LibFileName = GetComponentLibraryFileName(Name, Shared);
502     if (Shared) {
503       return (SharedDir + DirSep + LibFileName).str();
504     } else {
505       return (StaticDir + DirSep + LibFileName).str();
506     }
507   };
508 
509   raw_ostream &OS = outs();
510   for (int i = 1; i != argc; ++i) {
511     StringRef Arg = argv[i];
512 
513     if (Arg.startswith("-")) {
514       HasAnyOption = true;
515       if (Arg == "--version") {
516         OS << PACKAGE_VERSION << '\n';
517       } else if (Arg == "--prefix") {
518         OS << ActivePrefix << '\n';
519       } else if (Arg == "--bindir") {
520         OS << ActiveBinDir << '\n';
521       } else if (Arg == "--includedir") {
522         OS << ActiveIncludeDir << '\n';
523       } else if (Arg == "--libdir") {
524         OS << ActiveLibDir << '\n';
525       } else if (Arg == "--cmakedir") {
526         OS << ActiveCMakeDir << '\n';
527       } else if (Arg == "--cppflags") {
528         OS << ActiveIncludeOption << ' ' << LLVM_CPPFLAGS << '\n';
529       } else if (Arg == "--cflags") {
530         OS << ActiveIncludeOption << ' ' << LLVM_CFLAGS << '\n';
531       } else if (Arg == "--cxxflags") {
532         OS << ActiveIncludeOption << ' ' << LLVM_CXXFLAGS << '\n';
533       } else if (Arg == "--ldflags") {
534         OS << ((HostTriple.isWindowsMSVCEnvironment()) ? "-LIBPATH:" : "-L")
535            << ActiveLibDir << ' ' << LLVM_LDFLAGS << '\n';
536       } else if (Arg == "--system-libs") {
537         PrintSystemLibs = true;
538       } else if (Arg == "--libs") {
539         PrintLibs = true;
540       } else if (Arg == "--libnames") {
541         PrintLibNames = true;
542       } else if (Arg == "--libfiles") {
543         PrintLibFiles = true;
544       } else if (Arg == "--components") {
545         /// If there are missing static archives and a dylib was
546         /// built, print LLVM_DYLIB_COMPONENTS instead of everything
547         /// in the manifest.
548         std::vector<std::string> Components;
549         for (unsigned j = 0; j != array_lengthof(AvailableComponents); ++j) {
550           // Only include non-installed components when in a development tree.
551           if (!AvailableComponents[j].IsInstalled && !IsInDevelopmentTree)
552             continue;
553 
554           Components.push_back(AvailableComponents[j].Name);
555           if (AvailableComponents[j].Library && !IsInDevelopmentTree) {
556             std::string path(
557                 GetComponentLibraryPath(AvailableComponents[j].Library, false));
558             if (DirSep == "\\") {
559               std::replace(path.begin(), path.end(), '/', '\\');
560             }
561             if (DyLibExists && !sys::fs::exists(path)) {
562               Components =
563                   GetAllDyLibComponents(IsInDevelopmentTree, true, DirSep);
564               llvm::sort(Components);
565               break;
566             }
567           }
568         }
569 
570         for (unsigned I = 0; I < Components.size(); ++I) {
571           if (I) {
572             OS << ' ';
573           }
574 
575           OS << Components[I];
576         }
577         OS << '\n';
578       } else if (Arg == "--targets-built") {
579         OS << LLVM_TARGETS_BUILT << '\n';
580       } else if (Arg == "--host-target") {
581         OS << Triple::normalize(LLVM_DEFAULT_TARGET_TRIPLE) << '\n';
582       } else if (Arg == "--build-mode") {
583         OS << build_mode << '\n';
584       } else if (Arg == "--assertion-mode") {
585 #if defined(NDEBUG)
586         OS << "OFF\n";
587 #else
588         OS << "ON\n";
589 #endif
590       } else if (Arg == "--build-system") {
591         OS << LLVM_BUILD_SYSTEM << '\n';
592       } else if (Arg == "--has-rtti") {
593         OS << (LLVM_HAS_RTTI ? "YES" : "NO") << '\n';
594       } else if (Arg == "--shared-mode") {
595         PrintSharedMode = true;
596       } else if (Arg == "--obj-root") {
597         OS << ActivePrefix << '\n';
598       } else if (Arg == "--src-root") {
599         OS << LLVM_SRC_ROOT << '\n';
600       } else if (Arg == "--ignore-libllvm") {
601         LinkDyLib = false;
602         LinkMode = BuiltSharedLibs ? LinkModeShared : LinkModeAuto;
603       } else if (Arg == "--link-shared") {
604         LinkMode = LinkModeShared;
605       } else if (Arg == "--link-static") {
606         LinkMode = LinkModeStatic;
607       } else if (Arg == "--help") {
608         usage(false);
609       } else {
610         usage();
611       }
612     } else {
613       Components.push_back(Arg);
614     }
615   }
616 
617   if (!HasAnyOption)
618     usage();
619 
620   if (LinkMode == LinkModeShared && !DyLibExists && !BuiltSharedLibs) {
621     WithColor::error(errs(), "llvm-config") << DyLibName << " is missing\n";
622     return 1;
623   }
624 
625   if (PrintLibs || PrintLibNames || PrintLibFiles || PrintSystemLibs ||
626       PrintSharedMode) {
627 
628     if (PrintSharedMode && BuiltSharedLibs) {
629       OS << "shared\n";
630       return 0;
631     }
632 
633     // If no components were specified, default to "all".
634     if (Components.empty())
635       Components.push_back("all");
636 
637     // Construct the list of all the required libraries.
638     std::function<std::string(const StringRef &)>
639         GetComponentLibraryPathFunction = [&](const StringRef &Name) {
640           return GetComponentLibraryPath(Name, LinkMode == LinkModeShared);
641         };
642     std::vector<std::string> MissingLibs;
643     std::vector<std::string> RequiredLibs = ComputeLibsForComponents(
644         Components,
645         /*IncludeNonInstalled=*/IsInDevelopmentTree, false,
646         &GetComponentLibraryPathFunction, &MissingLibs, DirSep);
647     if (!MissingLibs.empty()) {
648       switch (LinkMode) {
649       case LinkModeShared:
650         if (LinkDyLib && !BuiltSharedLibs)
651           break;
652         // Using component shared libraries.
653         for (auto &Lib : MissingLibs)
654           WithColor::error(errs(), "llvm-config") << "missing: " << Lib << "\n";
655         return 1;
656       case LinkModeAuto:
657         if (DyLibExists) {
658           LinkMode = LinkModeShared;
659           break;
660         }
661         WithColor::error(errs(), "llvm-config")
662             << "component libraries and shared library\n\n";
663         LLVM_FALLTHROUGH;
664       case LinkModeStatic:
665         for (auto &Lib : MissingLibs)
666           WithColor::error(errs(), "llvm-config") << "missing: " << Lib << "\n";
667         return 1;
668       }
669     } else if (LinkMode == LinkModeAuto) {
670       LinkMode = LinkModeStatic;
671     }
672 
673     if (PrintSharedMode) {
674       std::unordered_set<std::string> FullDyLibComponents;
675       std::vector<std::string> DyLibComponents =
676           GetAllDyLibComponents(IsInDevelopmentTree, false, DirSep);
677 
678       for (auto &Component : DyLibComponents) {
679         FullDyLibComponents.insert(Component);
680       }
681       DyLibComponents.clear();
682 
683       for (auto &Lib : RequiredLibs) {
684         if (!FullDyLibComponents.count(Lib)) {
685           OS << "static\n";
686           return 0;
687         }
688       }
689       FullDyLibComponents.clear();
690 
691       if (LinkMode == LinkModeShared) {
692         OS << "shared\n";
693         return 0;
694       } else {
695         OS << "static\n";
696         return 0;
697       }
698     }
699 
700     if (PrintLibs || PrintLibNames || PrintLibFiles) {
701 
702       auto PrintForLib = [&](const StringRef &Lib) {
703         const bool Shared = LinkMode == LinkModeShared;
704         if (PrintLibNames) {
705           OS << GetComponentLibraryFileName(Lib, Shared);
706         } else if (PrintLibFiles) {
707           OS << GetComponentLibraryPath(Lib, Shared);
708         } else if (PrintLibs) {
709           // On Windows, output full path to library without parameters.
710           // Elsewhere, if this is a typical library name, include it using -l.
711           if (HostTriple.isWindowsMSVCEnvironment()) {
712             OS << GetComponentLibraryPath(Lib, Shared);
713           } else {
714             StringRef LibName;
715             if (GetComponentLibraryNameSlice(Lib, LibName)) {
716               // Extract library name (remove prefix and suffix).
717               OS << "-l" << LibName;
718             } else {
719               // Lib is already a library name without prefix and suffix.
720               OS << "-l" << Lib;
721             }
722           }
723         }
724       };
725 
726       if (LinkMode == LinkModeShared && LinkDyLib) {
727         PrintForLib(DyLibName);
728       } else {
729         for (unsigned i = 0, e = RequiredLibs.size(); i != e; ++i) {
730           auto Lib = RequiredLibs[i];
731           if (i)
732             OS << ' ';
733 
734           PrintForLib(Lib);
735         }
736       }
737       OS << '\n';
738     }
739 
740     // Print SYSTEM_LIBS after --libs.
741     // FIXME: Each LLVM component may have its dependent system libs.
742     if (PrintSystemLibs) {
743       // Output system libraries only if linking against a static
744       // library (since the shared library links to all system libs
745       // already)
746       OS << (LinkMode == LinkModeStatic ? LLVM_SYSTEM_LIBS : "") << '\n';
747     }
748   } else if (!Components.empty()) {
749     WithColor::error(errs(), "llvm-config")
750         << "components given, but unused\n\n";
751     usage();
752   }
753 
754   return 0;
755 }
756