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