An easy case where GCC should really be able to work out that the value is only
[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/raw_ostream.h"
29 #include <cstdlib>
30 #include <set>
31 #include <vector>
32
33 using 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.
54 static 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.
86 void 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
120 void usage() {
121   errs() << "\
122 usage: llvm-config <OPTION>... [<COMPONENT>...]\n\
123 \n\
124 Get various configuration information needed to compile programs which use\n\
125 LLVM.  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\
130 Options:\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\
149 Typical 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.
156 llvm::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
163 int 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     DevelopmentTreeLayout = MakefileStyle; // Initialized to avoid warnings.
210   }
211
212   // Compute various directory locations based on the derived location
213   // information.
214   std::string ActivePrefix, ActiveBinDir, ActiveIncludeDir, ActiveLibDir;
215   std::string ActiveIncludeOption;
216   if (IsInDevelopmentTree) {
217     ActiveIncludeDir = std::string(LLVM_SRC_ROOT) + "/include";
218     ActivePrefix = CurrentExecPrefix;
219
220     // CMake organizes the products differently than a normal prefix style
221     // layout.
222     switch (DevelopmentTreeLayout) {
223     case MakefileStyle:
224       ActiveBinDir = ActiveObjRoot + "/" + LLVM_BUILDMODE + "/bin";
225       ActiveLibDir = ActiveObjRoot + "/" + LLVM_BUILDMODE + "/lib";
226       break;
227     case CMakeStyle:
228       ActiveBinDir = ActiveObjRoot + "/bin";
229       ActiveLibDir = ActiveObjRoot + "/lib";
230       break;
231     case CMakeBuildModeStyle:
232       ActiveBinDir = ActiveObjRoot + "/bin/" + LLVM_BUILDMODE;
233       ActiveLibDir = ActiveObjRoot + "/lib/" + LLVM_BUILDMODE;
234       break;
235     }
236
237     // We need to include files from both the source and object trees.
238     ActiveIncludeOption = ("-I" + ActiveIncludeDir + " " +
239                            "-I" + ActiveObjRoot + "/include");
240   } else {
241     ActivePrefix = CurrentExecPrefix;
242     ActiveIncludeDir = ActivePrefix + "/include";
243     ActiveBinDir = ActivePrefix + "/bin";
244     ActiveLibDir = ActivePrefix + "/lib";
245     ActiveIncludeOption = "-I" + ActiveIncludeDir;
246   }
247
248   raw_ostream &OS = outs();
249   for (int i = 1; i != argc; ++i) {
250     StringRef Arg = argv[i];
251
252     if (Arg.startswith("-")) {
253       HasAnyOption = true;
254       if (Arg == "--version") {
255         OS << PACKAGE_VERSION << '\n';
256       } else if (Arg == "--prefix") {
257         OS << ActivePrefix << '\n';
258       } else if (Arg == "--bindir") {
259         OS << ActiveBinDir << '\n';
260       } else if (Arg == "--includedir") {
261         OS << ActiveIncludeDir << '\n';
262       } else if (Arg == "--libdir") {
263         OS << ActiveLibDir << '\n';
264       } else if (Arg == "--cppflags") {
265         OS << ActiveIncludeOption << ' ' << LLVM_CPPFLAGS << '\n';
266       } else if (Arg == "--cflags") {
267         OS << ActiveIncludeOption << ' ' << LLVM_CFLAGS << '\n';
268       } else if (Arg == "--cxxflags") {
269         OS << ActiveIncludeOption << ' ' << LLVM_CXXFLAGS << '\n';
270       } else if (Arg == "--ldflags") {
271         OS << "-L" << ActiveLibDir << ' ' << LLVM_LDFLAGS
272            << ' ' << LLVM_SYSTEM_LIBS << '\n';
273       } else if (Arg == "--libs") {
274         PrintLibs = true;
275       } else if (Arg == "--libnames") {
276         PrintLibNames = true;
277       } else if (Arg == "--libfiles") {
278         PrintLibFiles = true;
279       } else if (Arg == "--components") {
280         for (unsigned j = 0; j != array_lengthof(AvailableComponents); ++j) {
281           OS << ' ';
282           OS << AvailableComponents[j].Name;
283         }
284         OS << '\n';
285       } else if (Arg == "--targets-built") {
286         OS << LLVM_TARGETS_BUILT << '\n';
287       } else if (Arg == "--host-target") {
288         OS << LLVM_DEFAULT_TARGET_TRIPLE << '\n';
289       } else if (Arg == "--build-mode") {
290         OS << LLVM_BUILDMODE << '\n';
291       } else if (Arg == "--obj-root") {
292         OS << LLVM_OBJ_ROOT << '\n';
293       } else if (Arg == "--src-root") {
294         OS << LLVM_SRC_ROOT << '\n';
295       } else {
296         usage();
297       }
298     } else {
299       Components.push_back(Arg);
300     }
301   }
302
303   if (!HasAnyOption)
304     usage();
305
306   if (PrintLibs || PrintLibNames || PrintLibFiles) {
307     // If no components were specified, default to "all".
308     if (Components.empty())
309       Components.push_back("all");
310
311     // Construct the list of all the required libraries.
312     std::vector<StringRef> RequiredLibs;
313     ComputeLibsForComponents(Components, RequiredLibs);
314
315     for (unsigned i = 0, e = RequiredLibs.size(); i != e; ++i) {
316       StringRef Lib = RequiredLibs[i];
317       if (i)
318         OS << ' ';
319
320       if (PrintLibNames) {
321         OS << Lib;
322       } else if (PrintLibFiles) {
323         OS << ActiveLibDir << '/' << Lib;
324       } else if (PrintLibs) {
325         // If this is a typical library name, include it using -l.
326         if (Lib.startswith("lib") && Lib.endswith(".a")) {
327           OS << "-l" << Lib.slice(3, Lib.size()-2);
328           continue;
329         }
330
331         // Otherwise, print the full path.
332         OS << ActiveLibDir << '/' << Lib;
333       }
334     }
335     OS << '\n';
336   } else if (!Components.empty()) {
337     errs() << "llvm-config: error: components given, but unused\n\n";
338     usage();
339   }
340
341   return 0;
342 }