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