llvm-config.cpp revision b56900aa86aa535fb1f060f5935d1e209e45d907
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/Twine.h"
24#include "llvm/Config/config.h"
25#include "llvm/Config/llvm-config.h"
26#include "llvm/Support/FileSystem.h"
27#include "llvm/Support/Path.h"
28#include "llvm/Support/raw_ostream.h"
29#include <cstdlib>
30#include <set>
31#include <vector>
32
33using namespace llvm;
34
35// Include the build time variables we can report to the user. This is generated
36// at build time from the BuildVariables.inc.in file by the build system.
37#include "BuildVariables.inc"
38
39// Include the component table. This creates an array of struct
40// AvailableComponent entries, which record the component name, library name,
41// and required components for all of the available libraries.
42//
43// Not all components define a library, we also use "library groups" as a way to
44// create entries for pseudo groups like x86 or all-targets.
45#include "LibraryDependencies.inc"
46
47/// \brief Traverse a single component adding to the topological ordering in
48/// \arg RequiredLibs.
49///
50/// \param Name - The component to traverse.
51/// \param ComponentMap - A prebuilt map of component names to descriptors.
52/// \param VisitedComponents [in] [out] - The set of already visited components.
53/// \param RequiredLibs [out] - The ordered list of required libraries.
54static void VisitComponent(StringRef Name,
55                           const StringMap<AvailableComponent*> &ComponentMap,
56                           std::set<AvailableComponent*> &VisitedComponents,
57                           std::vector<StringRef> &RequiredLibs) {
58  // Lookup the component.
59  AvailableComponent *AC = ComponentMap.lookup(Name);
60  assert(AC && "Invalid component name!");
61
62  // Add to the visited table.
63  if (!VisitedComponents.insert(AC).second) {
64    // We are done if the component has already been visited.
65    return;
66  }
67
68  // Otherwise, visit all the dependencies.
69  for (unsigned i = 0; AC->RequiredLibraries[i]; ++i) {
70    VisitComponent(AC->RequiredLibraries[i], ComponentMap, VisitedComponents,
71                   RequiredLibs);
72  }
73
74  // Add to the required library list.
75  if (AC->Library)
76    RequiredLibs.push_back(AC->Library);
77}
78
79/// \brief Compute the list of required libraries for a given list of
80/// components, in an order suitable for passing to a linker (that is, libraries
81/// appear prior to their dependencies).
82///
83/// \param Components - The names of the components to find libraries for.
84/// \param RequiredLibs [out] - On return, the ordered list of libraries that
85/// are required to link the given components.
86void ComputeLibsForComponents(const std::vector<StringRef> &Components,
87                              std::vector<StringRef> &RequiredLibs) {
88  std::set<AvailableComponent*> VisitedComponents;
89
90  // Build a map of component names to information.
91  StringMap<AvailableComponent*> ComponentMap;
92  for (unsigned i = 0; i != array_lengthof(AvailableComponents); ++i) {
93    AvailableComponent *AC = &AvailableComponents[i];
94    ComponentMap[AC->Name] = AC;
95  }
96
97  // Visit the components.
98  for (unsigned i = 0, e = Components.size(); i != e; ++i) {
99    // Users are allowed to provide mixed case component names.
100    std::string ComponentLower = Components[i].lower();
101
102    // Validate that the user supplied a valid component name.
103    if (!ComponentMap.count(ComponentLower)) {
104      llvm::errs() << "llvm-config: unknown component name: " << Components[i]
105                   << "\n";
106      exit(1);
107    }
108
109    VisitComponent(ComponentLower, ComponentMap, VisitedComponents,
110                   RequiredLibs);
111  }
112
113  // The list is now ordered with leafs first, we want the libraries to printed
114  // in the reverse order of dependency.
115  std::reverse(RequiredLibs.begin(), RequiredLibs.end());
116}
117
118/* *** */
119
120void usage() {
121  errs() << "\
122usage: llvm-config <OPTION>... [<COMPONENT>...]\n\
123\n\
124Get various configuration information needed to compile programs which use\n\
125LLVM.  Typically called from 'configure' scripts.  Examples:\n\
126  llvm-config --cxxflags\n\
127  llvm-config --ldflags\n\
128  llvm-config --libs engine bcreader scalaropts\n\
129\n\
130Options:\n\
131  --version         Print LLVM version.\n\
132  --prefix          Print the installation prefix.\n\
133  --src-root        Print the source root LLVM was built from.\n\
134  --obj-root        Print the object root used to build LLVM.\n\
135  --bindir          Directory containing LLVM executables.\n\
136  --includedir      Directory containing LLVM headers.\n\
137  --libdir          Directory containing LLVM libraries.\n\
138  --cppflags        C preprocessor flags for files that include LLVM headers.\n\
139  --cflags          C compiler flags for files that include LLVM headers.\n\
140  --cxxflags        C++ compiler flags for files that include LLVM headers.\n\
141  --ldflags         Print Linker flags.\n\
142  --libs            Libraries needed to link against LLVM components.\n\
143  --libnames        Bare library names for in-tree builds.\n\
144  --libfiles        Fully qualified library filenames for makefile depends.\n\
145  --components      List of all possible components.\n\
146  --targets-built   List of all targets currently built.\n\
147  --host-target     Target triple used to configure LLVM.\n\
148  --build-mode      Print build mode of LLVM tree (e.g. Debug or Release).\n\
149Typical components:\n\
150  all               All LLVM libraries (default).\n\
151  engine            Either a native JIT or a bitcode interpreter.\n";
152  exit(1);
153}
154
155/// \brief Compute the path to the main executable.
156llvm::sys::Path GetExecutablePath(const char *Argv0) {
157  // This just needs to be some symbol in the binary; C++ doesn't
158  // allow taking the address of ::main however.
159  void *P = (void*) (intptr_t) GetExecutablePath;
160  return llvm::sys::Path::GetMainExecutable(Argv0, P);
161}
162
163int main(int argc, char **argv) {
164  std::vector<StringRef> Components;
165  bool PrintLibs = false, PrintLibNames = false, PrintLibFiles = false;
166  bool HasAnyOption = false;
167
168  // llvm-config is designed to support being run both from a development tree
169  // and from an installed path. We try and auto-detect which case we are in so
170  // that we can report the correct information when run from a development
171  // tree.
172  bool IsInDevelopmentTree;
173  enum { MakefileStyle, CMakeStyle, CMakeBuildModeStyle } DevelopmentTreeLayout;
174  llvm::SmallString<256> CurrentPath(GetExecutablePath(argv[0]).str());
175  std::string CurrentExecPrefix;
176  std::string ActiveObjRoot;
177
178  // Create an absolute path, and pop up one directory (we expect to be inside a
179  // bin dir).
180  sys::fs::make_absolute(CurrentPath);
181  CurrentExecPrefix = sys::path::parent_path(
182    sys::path::parent_path(CurrentPath)).str();
183
184  // Check to see if we are inside a development tree by comparing to possible
185  // locations (prefix style or CMake style). This could be wrong in the face of
186  // symbolic links, but is good enough.
187  if (CurrentExecPrefix == std::string(LLVM_OBJ_ROOT) + "/" + LLVM_BUILDMODE) {
188    IsInDevelopmentTree = true;
189    DevelopmentTreeLayout = MakefileStyle;
190
191    // If we are in a development tree, then check if we are in a BuildTools
192    // directory. This indicates we are built for the build triple, but we
193    // always want to provide information for the host triple.
194    if (sys::path::filename(LLVM_OBJ_ROOT) == "BuildTools") {
195      ActiveObjRoot = sys::path::parent_path(LLVM_OBJ_ROOT);
196    } else {
197      ActiveObjRoot = LLVM_OBJ_ROOT;
198    }
199  } else if (CurrentExecPrefix == std::string(LLVM_OBJ_ROOT)) {
200    IsInDevelopmentTree = true;
201    DevelopmentTreeLayout = CMakeStyle;
202    ActiveObjRoot = LLVM_OBJ_ROOT;
203  } else if (CurrentExecPrefix == std::string(LLVM_OBJ_ROOT) + "/bin") {
204    IsInDevelopmentTree = true;
205    DevelopmentTreeLayout = CMakeBuildModeStyle;
206    ActiveObjRoot = LLVM_OBJ_ROOT;
207  } else {
208    IsInDevelopmentTree = false;
209  }
210
211  // Compute various directory locations based on the derived location
212  // information.
213  std::string ActivePrefix, ActiveBinDir, ActiveIncludeDir, ActiveLibDir;
214  std::string ActiveIncludeOption;
215  if (IsInDevelopmentTree) {
216    ActiveIncludeDir = std::string(LLVM_SRC_ROOT) + "/include";
217    ActivePrefix = CurrentExecPrefix;
218
219    // CMake organizes the products differently than a normal prefix style
220    // layout.
221    switch (DevelopmentTreeLayout) {
222    case MakefileStyle:
223      ActiveBinDir = ActiveObjRoot + "/" + LLVM_BUILDMODE + "/bin";
224      ActiveLibDir = ActiveObjRoot + "/" + LLVM_BUILDMODE + "/lib";
225      break;
226    case CMakeStyle:
227      ActiveBinDir = ActiveObjRoot + "/bin";
228      ActiveLibDir = ActiveObjRoot + "/lib";
229      break;
230    case CMakeBuildModeStyle:
231      ActiveBinDir = ActiveObjRoot + "/bin/" + LLVM_BUILDMODE;
232      ActiveLibDir = ActiveObjRoot + "/lib/" + LLVM_BUILDMODE;
233      break;
234    }
235
236    // We need to include files from both the source and object trees.
237    ActiveIncludeOption = ("-I" + ActiveIncludeDir + " " +
238                           "-I" + ActiveObjRoot + "/include");
239  } else {
240    ActivePrefix = CurrentExecPrefix;
241    ActiveIncludeDir = ActivePrefix + "/include";
242    ActiveBinDir = ActivePrefix + "/bin";
243    ActiveLibDir = ActivePrefix + "/lib";
244    ActiveIncludeOption = "-I" + ActiveIncludeDir;
245  }
246
247  raw_ostream &OS = outs();
248  for (int i = 1; i != argc; ++i) {
249    StringRef Arg = argv[i];
250
251    if (Arg.startswith("-")) {
252      HasAnyOption = true;
253      if (Arg == "--version") {
254        OS << PACKAGE_VERSION << '\n';
255      } else if (Arg == "--prefix") {
256        OS << ActivePrefix << '\n';
257      } else if (Arg == "--bindir") {
258        OS << ActiveBinDir << '\n';
259      } else if (Arg == "--includedir") {
260        OS << ActiveIncludeDir << '\n';
261      } else if (Arg == "--libdir") {
262        OS << ActiveLibDir << '\n';
263      } else if (Arg == "--cppflags") {
264        OS << ActiveIncludeOption << ' ' << LLVM_CPPFLAGS << '\n';
265      } else if (Arg == "--cflags") {
266        OS << ActiveIncludeOption << ' ' << LLVM_CFLAGS << '\n';
267      } else if (Arg == "--cxxflags") {
268        OS << ActiveIncludeOption << ' ' << LLVM_CXXFLAGS << '\n';
269      } else if (Arg == "--ldflags") {
270        OS << "-L" << ActiveLibDir << ' ' << LLVM_LDFLAGS
271           << ' ' << LLVM_SYSTEM_LIBS << '\n';
272      } else if (Arg == "--libs") {
273        PrintLibs = true;
274      } else if (Arg == "--libnames") {
275        PrintLibNames = true;
276      } else if (Arg == "--libfiles") {
277        PrintLibFiles = true;
278      } else if (Arg == "--components") {
279        for (unsigned j = 0; j != array_lengthof(AvailableComponents); ++j) {
280          OS << ' ';
281          OS << AvailableComponents[j].Name;
282        }
283        OS << '\n';
284      } else if (Arg == "--targets-built") {
285        OS << LLVM_TARGETS_BUILT << '\n';
286      } else if (Arg == "--host-target") {
287        OS << LLVM_DEFAULT_TARGET_TRIPLE << '\n';
288      } else if (Arg == "--build-mode") {
289        OS << LLVM_BUILDMODE << '\n';
290      } else if (Arg == "--obj-root") {
291        OS << LLVM_OBJ_ROOT << '\n';
292      } else if (Arg == "--src-root") {
293        OS << LLVM_SRC_ROOT << '\n';
294      } else {
295        usage();
296      }
297    } else {
298      Components.push_back(Arg);
299    }
300  }
301
302  if (!HasAnyOption)
303    usage();
304
305  if (PrintLibs || PrintLibNames || PrintLibFiles) {
306    // If no components were specified, default to "all".
307    if (Components.empty())
308      Components.push_back("all");
309
310    // Construct the list of all the required libraries.
311    std::vector<StringRef> RequiredLibs;
312    ComputeLibsForComponents(Components, RequiredLibs);
313
314    for (unsigned i = 0, e = RequiredLibs.size(); i != e; ++i) {
315      StringRef Lib = RequiredLibs[i];
316      if (i)
317        OS << ' ';
318
319      if (PrintLibNames) {
320        OS << Lib;
321      } else if (PrintLibFiles) {
322        OS << ActiveLibDir << '/' << Lib;
323      } else if (PrintLibs) {
324        // If this is a typical library name, include it using -l.
325        if (Lib.startswith("lib") && Lib.endswith(".a")) {
326          OS << "-l" << Lib.slice(3, Lib.size()-2);
327          continue;
328        }
329
330        // Otherwise, print the full path.
331        OS << ActiveLibDir << '/' << Lib;
332      }
333    }
334    OS << '\n';
335  } else if (!Components.empty()) {
336    errs() << "llvm-config: error: components given, but unused\n\n";
337    usage();
338  }
339
340  return 0;
341}
342