1 //===-- llvm-config.cpp - LLVM project configuration utility --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.).
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.
18 //===----------------------------------------------------------------------===//
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"
32 #include <unordered_set>
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"
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.
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"
49 // LinkMode determines what libraries and flags are returned by llvm-config.
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.
56 // LinkModeDyLib will link with the single dynamic library if it exists,
57 // and return an error if it does not exist.
60 // LinkModeStatic will link with the individual component static libraries
61 // if they exist, and fail if any one does not exist.
65 /// \brief Traverse a single component adding to the topological ordering in
66 /// \arg RequiredLibs.
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
73 /// \param GetComponentNames - Get the component names instead of the
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::string *ActiveLibDir,
81 std::vector<std::string> *Missing) {
82 // Lookup the component.
83 AvailableComponent *AC = ComponentMap.lookup(Name);
84 assert(AC && "Invalid component name!");
86 // Add to the visited table.
87 if (!VisitedComponents.insert(AC).second) {
88 // We are done if the component has already been visited.
92 // Only include non-installed components if requested.
93 if (!AC->IsInstalled && !IncludeNonInstalled)
96 // Otherwise, visit all the dependencies.
97 for (unsigned i = 0; AC->RequiredLibraries[i]; ++i) {
98 VisitComponent(AC->RequiredLibraries[i], ComponentMap, VisitedComponents,
99 RequiredLibs, IncludeNonInstalled, GetComponentNames,
100 ActiveLibDir, Missing);
103 if (GetComponentNames) {
104 RequiredLibs.push_back(Name);
108 // Add to the required library list.
110 if (Missing && ActiveLibDir) {
111 std::string path = *ActiveLibDir + "/" + AC->Library;
112 if (!sys::fs::exists(path))
113 Missing->push_back(path);
115 RequiredLibs.push_back(AC->Library);
119 /// \brief Compute the list of required libraries for a given list of
120 /// components, in an order suitable for passing to a linker (that is, libraries
121 /// appear prior to their dependencies).
123 /// \param Components - The names of the components to find libraries for.
124 /// \param IncludeNonInstalled - Whether non-installed components should be
126 /// \param GetComponentNames - True if one would prefer the component names.
127 static std::vector<std::string>
128 ComputeLibsForComponents(const std::vector<StringRef> &Components,
129 bool IncludeNonInstalled, bool GetComponentNames,
130 const std::string *ActiveLibDir,
131 std::vector<std::string> *Missing) {
132 std::vector<std::string> RequiredLibs;
133 std::set<AvailableComponent *> VisitedComponents;
135 // Build a map of component names to information.
136 StringMap<AvailableComponent *> ComponentMap;
137 for (unsigned i = 0; i != array_lengthof(AvailableComponents); ++i) {
138 AvailableComponent *AC = &AvailableComponents[i];
139 ComponentMap[AC->Name] = AC;
142 // Visit the components.
143 for (unsigned i = 0, e = Components.size(); i != e; ++i) {
144 // Users are allowed to provide mixed case component names.
145 std::string ComponentLower = Components[i].lower();
147 // Validate that the user supplied a valid component name.
148 if (!ComponentMap.count(ComponentLower)) {
149 llvm::errs() << "llvm-config: unknown component name: " << Components[i]
154 VisitComponent(ComponentLower, ComponentMap, VisitedComponents,
155 RequiredLibs, IncludeNonInstalled, GetComponentNames,
156 ActiveLibDir, Missing);
159 // The list is now ordered with leafs first, we want the libraries to printed
160 // in the reverse order of dependency.
161 std::reverse(RequiredLibs.begin(), RequiredLibs.end());
168 static void usage() {
170 usage: llvm-config <OPTION>... [<COMPONENT>...]\n\
172 Get various configuration information needed to compile programs which use\n\
173 LLVM. Typically called from 'configure' scripts. Examples:\n\
174 llvm-config --cxxflags\n\
175 llvm-config --ldflags\n\
176 llvm-config --libs engine bcreader scalaropts\n\
179 --version Print LLVM version.\n\
180 --prefix Print the installation prefix.\n\
181 --src-root Print the source root LLVM was built from.\n\
182 --obj-root Print the object root used to build LLVM.\n\
183 --bindir Directory containing LLVM executables.\n\
184 --includedir Directory containing LLVM headers.\n\
185 --libdir Directory containing LLVM libraries.\n\
186 --cppflags C preprocessor flags for files that include LLVM headers.\n\
187 --cflags C compiler flags for files that include LLVM headers.\n\
188 --cxxflags C++ compiler flags for files that include LLVM headers.\n\
189 --ldflags Print Linker flags.\n\
190 --system-libs System Libraries needed to link against LLVM components.\n\
191 --libs Libraries needed to link against LLVM components.\n\
192 --libnames Bare library names for in-tree builds.\n\
193 --libfiles Fully qualified library filenames for makefile depends.\n\
194 --components List of all possible components.\n\
195 --targets-built List of all targets currently built.\n\
196 --host-target Target triple used to configure LLVM.\n\
197 --build-mode Print build mode of LLVM tree (e.g. Debug or Release).\n\
198 --assertion-mode Print assertion mode of LLVM tree (ON or OFF).\n\
199 --build-system Print the build system used to build LLVM (autoconf or cmake).\n\
200 --has-rtti Print whether or not LLVM was built with rtti (YES or NO).\n\
201 --shared-mode Print how the provided components can be collectively linked (`shared` or `static`).\n\
202 --link-shared Link the components as a shared library.\n\
203 --link-static Link the components as a static libraries.\n\
204 Typical components:\n\
205 all All LLVM libraries (default).\n\
206 engine Either a native JIT or a bitcode interpreter.\n";
210 /// \brief Compute the path to the main executable.
211 std::string GetExecutablePath(const char *Argv0) {
212 // This just needs to be some symbol in the binary; C++ doesn't
213 // allow taking the address of ::main however.
214 void *P = (void *)(intptr_t)GetExecutablePath;
215 return llvm::sys::fs::getMainExecutable(Argv0, P);
218 /// \brief Expand the semi-colon delimited LLVM_DYLIB_COMPONENTS into
219 /// the full list of components.
220 std::vector<std::string> GetAllDyLibComponents(const bool IsInDevelopmentTree,
221 const bool GetComponentNames) {
222 std::vector<StringRef> DyLibComponents;
224 StringRef DyLibComponentsStr(LLVM_DYLIB_COMPONENTS);
227 const size_t NextOffset = DyLibComponentsStr.find(';', Offset);
228 DyLibComponents.push_back(DyLibComponentsStr.substr(Offset, NextOffset));
229 if (NextOffset == std::string::npos) {
232 Offset = NextOffset + 1;
235 assert(!DyLibComponents.empty());
237 return ComputeLibsForComponents(DyLibComponents,
238 /*IncludeNonInstalled=*/IsInDevelopmentTree,
239 GetComponentNames, nullptr, nullptr);
242 int main(int argc, char **argv) {
243 std::vector<StringRef> Components;
244 bool PrintLibs = false, PrintLibNames = false, PrintLibFiles = false;
245 bool PrintSystemLibs = false, PrintSharedMode = false;
246 bool HasAnyOption = false;
248 // llvm-config is designed to support being run both from a development tree
249 // and from an installed path. We try and auto-detect which case we are in so
250 // that we can report the correct information when run from a development
252 bool IsInDevelopmentTree;
253 enum { MakefileStyle, CMakeStyle, CMakeBuildModeStyle } DevelopmentTreeLayout;
254 llvm::SmallString<256> CurrentPath(GetExecutablePath(argv[0]));
255 std::string CurrentExecPrefix;
256 std::string ActiveObjRoot;
258 // If CMAKE_CFG_INTDIR is given, honor it as build mode.
259 char const *build_mode = LLVM_BUILDMODE;
260 #if defined(CMAKE_CFG_INTDIR)
261 if (!(CMAKE_CFG_INTDIR[0] == '.' && CMAKE_CFG_INTDIR[1] == '\0'))
262 build_mode = CMAKE_CFG_INTDIR;
265 // Create an absolute path, and pop up one directory (we expect to be inside a
267 sys::fs::make_absolute(CurrentPath);
269 sys::path::parent_path(sys::path::parent_path(CurrentPath)).str();
271 // Check to see if we are inside a development tree by comparing to possible
272 // locations (prefix style or CMake style).
273 if (sys::fs::equivalent(CurrentExecPrefix,
274 Twine(LLVM_OBJ_ROOT) + "/" + build_mode)) {
275 IsInDevelopmentTree = true;
276 DevelopmentTreeLayout = MakefileStyle;
278 // If we are in a development tree, then check if we are in a BuildTools
279 // directory. This indicates we are built for the build triple, but we
280 // always want to provide information for the host triple.
281 if (sys::path::filename(LLVM_OBJ_ROOT) == "BuildTools") {
282 ActiveObjRoot = sys::path::parent_path(LLVM_OBJ_ROOT);
284 ActiveObjRoot = LLVM_OBJ_ROOT;
286 } else if (sys::fs::equivalent(CurrentExecPrefix, LLVM_OBJ_ROOT)) {
287 IsInDevelopmentTree = true;
288 DevelopmentTreeLayout = CMakeStyle;
289 ActiveObjRoot = LLVM_OBJ_ROOT;
290 } else if (sys::fs::equivalent(CurrentExecPrefix,
291 Twine(LLVM_OBJ_ROOT) + "/bin")) {
292 IsInDevelopmentTree = true;
293 DevelopmentTreeLayout = CMakeBuildModeStyle;
294 ActiveObjRoot = LLVM_OBJ_ROOT;
296 IsInDevelopmentTree = false;
297 DevelopmentTreeLayout = MakefileStyle; // Initialized to avoid warnings.
300 // Compute various directory locations based on the derived location
302 std::string ActivePrefix, ActiveBinDir, ActiveIncludeDir, ActiveLibDir;
303 std::string ActiveIncludeOption;
304 if (IsInDevelopmentTree) {
305 ActiveIncludeDir = std::string(LLVM_SRC_ROOT) + "/include";
306 ActivePrefix = CurrentExecPrefix;
308 // CMake organizes the products differently than a normal prefix style
310 switch (DevelopmentTreeLayout) {
312 ActivePrefix = ActiveObjRoot;
313 ActiveBinDir = ActiveObjRoot + "/" + build_mode + "/bin";
315 ActiveObjRoot + "/" + build_mode + "/lib" + LLVM_LIBDIR_SUFFIX;
318 ActiveBinDir = ActiveObjRoot + "/bin";
319 ActiveLibDir = ActiveObjRoot + "/lib" + LLVM_LIBDIR_SUFFIX;
321 case CMakeBuildModeStyle:
322 ActivePrefix = ActiveObjRoot;
323 ActiveBinDir = ActiveObjRoot + "/bin/" + build_mode;
325 ActiveObjRoot + "/lib" + LLVM_LIBDIR_SUFFIX + "/" + build_mode;
329 // We need to include files from both the source and object trees.
330 ActiveIncludeOption =
331 ("-I" + ActiveIncludeDir + " " + "-I" + ActiveObjRoot + "/include");
333 ActivePrefix = CurrentExecPrefix;
334 ActiveIncludeDir = ActivePrefix + "/include";
335 ActiveBinDir = ActivePrefix + "/bin";
336 ActiveLibDir = ActivePrefix + "/lib" + LLVM_LIBDIR_SUFFIX;
337 ActiveIncludeOption = "-I" + ActiveIncludeDir;
340 /// We only use `shared library` mode in cases where the static library form
341 /// of the components provided are not available; note however that this is
342 /// skipped if we're run from within the build dir. However, once installed,
343 /// we still need to provide correct output when the static archives are
344 /// removed or, as in the case of CMake's `BUILD_SHARED_LIBS`, never present
345 /// in the first place. This can't be done at configure/build time.
347 StringRef SharedExt, SharedVersionedExt, SharedDir, SharedPrefix, StaticExt,
348 StaticPrefix, StaticDir = "lib";
349 const Triple HostTriple(Triple::normalize(LLVM_DEFAULT_TARGET_TRIPLE));
350 if (HostTriple.isOSWindows()) {
352 SharedVersionedExt = LLVM_DYLIB_VERSION ".dll";
354 SharedDir = ActiveBinDir;
355 StaticDir = ActiveLibDir;
356 StaticPrefix = SharedPrefix = "lib";
357 } else if (HostTriple.isOSDarwin()) {
359 SharedVersionedExt = LLVM_DYLIB_VERSION ".dylib";
361 StaticDir = SharedDir = ActiveLibDir;
362 StaticPrefix = SharedPrefix = "lib";
364 // default to the unix values:
366 SharedVersionedExt = LLVM_DYLIB_VERSION ".so";
368 StaticDir = SharedDir = ActiveLibDir;
369 StaticPrefix = SharedPrefix = "lib";
372 const bool BuiltDyLib = (std::strcmp(LLVM_ENABLE_DYLIB, "ON") == 0);
374 enum { CMake, AutoConf } ConfigTool;
375 if (std::strcmp(LLVM_BUILD_SYSTEM, "cmake") == 0) {
378 ConfigTool = AutoConf;
381 /// CMake style shared libs, ie each component is in a shared library.
382 const bool BuiltSharedLibs =
383 (ConfigTool == CMake && std::strcmp(LLVM_ENABLE_SHARED, "ON") == 0);
385 bool DyLibExists = false;
386 const std::string DyLibName =
387 (SharedPrefix + "LLVM-" + SharedVersionedExt).str();
389 // If LLVM_LINK_DYLIB is ON, the single shared library will be returned
390 // for "--libs", etc, if they exist. This behaviour can be overridden with
391 // --link-static or --link-shared.
392 bool LinkDyLib = (std::strcmp(LLVM_LINK_DYLIB, "ON") == 0);
395 DyLibExists = sys::fs::exists(SharedDir + "/" + DyLibName);
397 // The shared library does not exist: don't error unless the user
398 // explicitly passes --link-shared.
402 LinkMode LinkMode = LinkDyLib ? LinkModeDyLib : LinkModeAuto;
404 /// Get the component's library name without the lib prefix and the
405 /// extension. Returns true if Lib is in a recognized format.
406 auto GetComponentLibraryNameSlice = [&](const StringRef &Lib,
408 if (Lib.startswith("lib")) {
410 if (Lib.endswith(StaticExt)) {
411 FromEnd = StaticExt.size() + 1;
412 } else if (Lib.endswith(SharedExt)) {
413 FromEnd = SharedExt.size() + 1;
419 Out = Lib.slice(3, Lib.size() - FromEnd);
426 /// Maps Unixizms to the host platform.
427 auto GetComponentLibraryFileName = [&](const StringRef &Lib,
428 const bool ForceShared) {
429 std::string LibFileName = Lib;
431 if (GetComponentLibraryNameSlice(Lib, LibName)) {
432 if (BuiltSharedLibs || ForceShared) {
433 LibFileName = (SharedPrefix + LibName + "." + SharedExt).str();
436 LibFileName = (StaticPrefix + LibName + "." + StaticExt).str();
442 /// Get the full path for a possibly shared component library.
443 auto GetComponentLibraryPath = [&](const StringRef &Name,
444 const bool ForceShared) {
445 auto LibFileName = GetComponentLibraryFileName(Name, ForceShared);
446 if (BuiltSharedLibs || ForceShared) {
447 return (SharedDir + "/" + LibFileName).str();
449 return (StaticDir + "/" + LibFileName).str();
453 raw_ostream &OS = outs();
454 for (int i = 1; i != argc; ++i) {
455 StringRef Arg = argv[i];
457 if (Arg.startswith("-")) {
459 if (Arg == "--version") {
460 OS << PACKAGE_VERSION << '\n';
461 } else if (Arg == "--prefix") {
462 OS << ActivePrefix << '\n';
463 } else if (Arg == "--bindir") {
464 OS << ActiveBinDir << '\n';
465 } else if (Arg == "--includedir") {
466 OS << ActiveIncludeDir << '\n';
467 } else if (Arg == "--libdir") {
468 OS << ActiveLibDir << '\n';
469 } else if (Arg == "--cppflags") {
470 OS << ActiveIncludeOption << ' ' << LLVM_CPPFLAGS << '\n';
471 } else if (Arg == "--cflags") {
472 OS << ActiveIncludeOption << ' ' << LLVM_CFLAGS << '\n';
473 } else if (Arg == "--cxxflags") {
474 OS << ActiveIncludeOption << ' ' << LLVM_CXXFLAGS << '\n';
475 } else if (Arg == "--ldflags") {
476 OS << "-L" << ActiveLibDir << ' ' << LLVM_LDFLAGS << '\n';
477 } else if (Arg == "--system-libs") {
478 PrintSystemLibs = true;
479 } else if (Arg == "--libs") {
481 } else if (Arg == "--libnames") {
482 PrintLibNames = true;
483 } else if (Arg == "--libfiles") {
484 PrintLibFiles = true;
485 } else if (Arg == "--components") {
486 /// If there are missing static archives and a dylib was
487 /// built, print LLVM_DYLIB_COMPONENTS instead of everything
489 std::vector<std::string> Components;
490 for (unsigned j = 0; j != array_lengthof(AvailableComponents); ++j) {
491 // Only include non-installed components when in a development tree.
492 if (!AvailableComponents[j].IsInstalled && !IsInDevelopmentTree)
495 Components.push_back(AvailableComponents[j].Name);
496 if (AvailableComponents[j].Library && !IsInDevelopmentTree) {
498 !sys::fs::exists(GetComponentLibraryPath(
499 AvailableComponents[j].Library, false))) {
500 Components = GetAllDyLibComponents(IsInDevelopmentTree, true);
501 std::sort(Components.begin(), Components.end());
507 for (unsigned I = 0; I < Components.size(); ++I) {
515 } else if (Arg == "--targets-built") {
516 OS << LLVM_TARGETS_BUILT << '\n';
517 } else if (Arg == "--host-target") {
518 OS << Triple::normalize(LLVM_DEFAULT_TARGET_TRIPLE) << '\n';
519 } else if (Arg == "--build-mode") {
520 OS << build_mode << '\n';
521 } else if (Arg == "--assertion-mode") {
527 } else if (Arg == "--build-system") {
528 OS << LLVM_BUILD_SYSTEM << '\n';
529 } else if (Arg == "--has-rtti") {
530 OS << LLVM_HAS_RTTI << '\n';
531 } else if (Arg == "--shared-mode") {
532 PrintSharedMode = true;
533 } else if (Arg == "--obj-root") {
534 OS << ActivePrefix << '\n';
535 } else if (Arg == "--src-root") {
536 OS << LLVM_SRC_ROOT << '\n';
537 } else if (Arg == "--link-shared") {
538 LinkMode = LinkModeDyLib;
539 } else if (Arg == "--link-static") {
540 LinkMode = LinkModeStatic;
545 Components.push_back(Arg);
552 if (LinkMode == LinkModeDyLib && !DyLibExists) {
553 errs() << "llvm-config: error: " << DyLibName << " is missing\n\n";
557 if (PrintLibs || PrintLibNames || PrintLibFiles || PrintSystemLibs ||
560 if (PrintSharedMode && BuiltSharedLibs) {
565 // If no components were specified, default to "all".
566 if (Components.empty())
567 Components.push_back("all");
569 // Construct the list of all the required libraries.
570 std::vector<std::string> MissingLibs;
571 std::vector<std::string> RequiredLibs =
572 ComputeLibsForComponents(Components,
573 /*IncludeNonInstalled=*/IsInDevelopmentTree,
574 false, &ActiveLibDir, &MissingLibs);
575 if (!MissingLibs.empty()) {
581 LinkMode = LinkModeDyLib;
585 << "llvm-config: error: component libraries and shared library\n\n";
588 for (auto &Lib : MissingLibs)
589 errs() << "llvm-config: error: missing: " << Lib << "\n";
592 } else if (LinkMode == LinkModeAuto) {
593 LinkMode = LinkModeStatic;
596 if (PrintSharedMode) {
597 std::unordered_set<std::string> FullDyLibComponents;
598 std::vector<std::string> DyLibComponents =
599 GetAllDyLibComponents(IsInDevelopmentTree, false);
601 for (auto &Component : DyLibComponents) {
602 FullDyLibComponents.insert(Component);
604 DyLibComponents.clear();
606 for (auto &Lib : RequiredLibs) {
607 if (!FullDyLibComponents.count(Lib)) {
612 FullDyLibComponents.clear();
614 if (LinkMode == LinkModeDyLib) {
623 if (PrintLibs || PrintLibNames || PrintLibFiles) {
625 auto PrintForLib = [&](const StringRef &Lib, const bool ForceShared) {
627 OS << GetComponentLibraryFileName(Lib, ForceShared);
628 } else if (PrintLibFiles) {
629 OS << GetComponentLibraryPath(Lib, ForceShared);
630 } else if (PrintLibs) {
631 // If this is a typical library name, include it using -l.
633 if (Lib.startswith("lib")) {
634 if (GetComponentLibraryNameSlice(Lib, LibName)) {
635 OS << "-l" << LibName;
637 OS << "-l:" << GetComponentLibraryFileName(Lib, ForceShared);
640 // Otherwise, print the full path.
641 OS << GetComponentLibraryPath(Lib, ForceShared);
646 if (LinkMode == LinkModeDyLib) {
647 PrintForLib(DyLibName, true);
649 for (unsigned i = 0, e = RequiredLibs.size(); i != e; ++i) {
650 auto Lib = RequiredLibs[i];
654 PrintForLib(Lib, false);
660 // Print SYSTEM_LIBS after --libs.
661 // FIXME: Each LLVM component may have its dependent system libs.
663 OS << LLVM_SYSTEM_LIBS << '\n';
664 } else if (!Components.empty()) {
665 errs() << "llvm-config: error: components given, but unused\n\n";