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