llvm-build: Add "--write-library-table" option for generating the C++ library
[oota-llvm.git] / utils / llvm-build / llvmbuild / main.py
1 import os
2 import sys
3
4 import componentinfo
5
6 from util import *
7
8 ###
9
10 class LLVMProjectInfo(object):
11     @staticmethod
12     def load_infos_from_path(llvmbuild_source_root):
13         # FIXME: Implement a simple subpath file list cache, so we don't restat
14         # directories we have already traversed.
15
16         # First, discover all the LLVMBuild.txt files.
17         for dirpath,dirnames,filenames in os.walk(llvmbuild_source_root,
18                                                   followlinks = True):
19             # If there is no LLVMBuild.txt file in a directory, we don't recurse
20             # past it. This is a simple way to prune our search, although it
21             # makes it easy for users to add LLVMBuild.txt files in places they
22             # won't be seen.
23             if 'LLVMBuild.txt' not in filenames:
24                 del dirnames[:]
25                 continue
26
27             # Otherwise, load the LLVMBuild file in this directory.
28             assert dirpath.startswith(llvmbuild_source_root)
29             subpath = '/' + dirpath[len(llvmbuild_source_root)+1:]
30             llvmbuild_path = os.path.join(dirpath, 'LLVMBuild.txt')
31             for info in componentinfo.load_from_path(llvmbuild_path, subpath):
32                 yield info
33
34     @staticmethod
35     def load_from_path(source_root, llvmbuild_source_root):
36         infos = list(
37             LLVMProjectInfo.load_infos_from_path(llvmbuild_source_root))
38
39         return LLVMProjectInfo(source_root, infos)
40
41     def __init__(self, source_root, component_infos):
42         # Store our simple ivars.
43         self.source_root = source_root
44         self.component_infos = component_infos
45
46         # Create the component info map and validate that component names are
47         # unique.
48         self.component_info_map = {}
49         for ci in component_infos:
50             existing = self.component_info_map.get(ci.name)
51             if existing is not None:
52                 # We found a duplicate component name, report it and error out.
53                 fatal("found duplicate component %r (at %r and %r)" % (
54                         ci.name, ci.subpath, existing.subpath))
55             self.component_info_map[ci.name] = ci
56
57         # Disallow 'all' as a component name, which is a special case.
58         if 'all' in self.component_info_map:
59             fatal("project is not allowed to define 'all' component")
60
61         # Add the root component.
62         if '$ROOT' in self.component_info_map:
63             fatal("project is not allowed to define $ROOT component")
64         self.component_info_map['$ROOT'] = componentinfo.GroupComponentInfo(
65             '/', '$ROOT', None)
66         self.component_infos.append(self.component_info_map['$ROOT'])
67
68         # Topologically order the component information according to their
69         # component references.
70         def visit_component_info(ci, current_stack, current_set):
71             # Check for a cycles.
72             if ci in current_set:
73                 # We found a cycle, report it and error out.
74                 cycle_description = ' -> '.join(
75                     '%r (%s)' % (ci.name, relation)
76                     for relation,ci in current_stack)
77                 fatal("found cycle to %r after following: %s -> %s" % (
78                         ci.name, cycle_description, ci.name))
79
80             # If we have already visited this item, we are done.
81             if ci not in components_to_visit:
82                 return
83
84             # Otherwise, mark the component info as visited and traverse.
85             components_to_visit.remove(ci)
86
87             # Validate the parent reference, which we treat specially.
88             if ci.parent is not None:
89                 parent = self.component_info_map.get(ci.parent)
90                 if parent is None:
91                     fatal("component %r has invalid reference %r (via %r)" % (
92                             ci.name, ci.parent, 'parent'))
93                 ci.set_parent_instance(parent)
94
95             for relation,referent_name in ci.get_component_references():
96                 # Validate that the reference is ok.
97                 referent = self.component_info_map.get(referent_name)
98                 if referent is None:
99                     fatal("component %r has invalid reference %r (via %r)" % (
100                             ci.name, referent_name, relation))
101
102                 # Visit the reference.
103                 current_stack.append((relation,ci))
104                 current_set.add(ci)
105                 visit_component_info(referent, current_stack, current_set)
106                 current_set.remove(ci)
107                 current_stack.pop()
108
109             # Finally, add the component info to the ordered list.
110             self.ordered_component_infos.append(ci)
111
112         # FIXME: We aren't actually correctly checking for cycles along the
113         # parent edges. Haven't decided how I want to handle this -- I thought
114         # about only checking cycles by relation type. If we do that, it falls
115         # out easily. If we don't, we should special case the check.
116
117         self.ordered_component_infos = []
118         components_to_visit = set(component_infos)
119         while components_to_visit:
120             visit_component_info(iter(components_to_visit).next(), [], set())
121
122         # Canonicalize children lists.
123         for c in self.ordered_component_infos:
124             c.children.sort(key = lambda c: c.name)
125
126     def print_tree(self):
127         def visit(node, depth = 0):
128             print '%s%-40s (%s)' % ('  '*depth, node.name, node.type_name)
129             for c in node.children:
130                 visit(c, depth + 1)
131         visit(self.component_info_map['$ROOT'])
132
133     def write_components(self, output_path):
134         # Organize all the components by the directory their LLVMBuild file
135         # should go in.
136         info_basedir = {}
137         for ci in self.component_infos:
138             # Ignore the $ROOT component.
139             if ci.parent is None:
140                 continue
141
142             info_basedir[ci.subpath] = info_basedir.get(ci.subpath, []) + [ci]
143
144         # Generate the build files.
145         for subpath, infos in info_basedir.items():
146             # Order the components by name to have a canonical ordering.
147             infos.sort(key = lambda ci: ci.name)
148
149             # Format the components into llvmbuild fragments.
150             fragments = filter(None, [ci.get_llvmbuild_fragment()
151                                       for ci in infos])
152             if not fragments:
153                 continue
154
155             assert subpath.startswith('/')
156             directory_path = os.path.join(output_path, subpath[1:])
157
158             # Create the directory if it does not already exist.
159             if not os.path.exists(directory_path):
160                 os.makedirs(directory_path)
161
162             # Create the LLVMBuild file.
163             file_path = os.path.join(directory_path, 'LLVMBuild.txt')
164             f = open(file_path, "w")
165             for i,fragment in enumerate(fragments):
166                 print >>f, '[component_%d]' % i
167                 f.write(fragment)
168                 print >>f
169             f.close()
170
171     def write_library_table(self, output_path):
172         # Write out the mapping from component names to required libraries.
173         #
174         # We do this in topological order so that we know we can append the
175         # dependencies for added library groups.
176         entries = {}
177         for c in self.ordered_component_infos:
178             # Only Library and LibraryGroup components are in the table.
179             if c.type_name not in ('Library', 'LibraryGroup'):
180                 continue
181
182             # Compute the llvm-config "component name". For historical reasons,
183             # this is lowercased based on the library name.
184             llvmconfig_component_name = c.get_llvmconfig_component_name()
185             
186             # Get the library name, or None for LibraryGroups.
187             if c.type_name == 'LibraryGroup':
188                 library_name = None
189             else:
190                 library_name = c.get_library_name()
191
192             # Get the component names of all the required libraries.
193             required_llvmconfig_component_names = [
194                 self.component_info_map[dep].get_llvmconfig_component_name()
195                 for dep in c.required_libraries]
196
197             # Insert the entries for library groups we should add to.
198             for dep in c.add_to_library_groups:
199                 entries[dep][2].append(llvmconfig_component_name)
200
201             # Add the entry.
202             entries[c.name] = (llvmconfig_component_name, library_name,
203                                required_llvmconfig_component_names)
204
205         # Convert to a list of entries and sort by name.
206         entries = entries.values()
207
208         # Create an 'all' pseudo component. We keep the dependency list small by
209         # only listing entries that have no other dependents.
210         root_entries = set(e[0] for e in entries)
211         for _,_,deps in entries:
212             root_entries -= set(deps)
213         entries.append(('all', None, root_entries))
214
215         entries.sort()
216
217         # Compute the maximum number of required libraries, plus one so there is
218         # always a sentinel.
219         max_required_libraries = max(len(deps)
220                                      for _,_,deps in entries) + 1
221
222         # Write out the library table.
223         f = open(output_path, 'w')
224         print >>f, """\
225 //===- llvm-build generated file --------------------------------*- C++ -*-===//
226 //
227 // Component Library Depenedency Table
228 //
229 // Automatically generated file, do not edit!
230 //
231 //===----------------------------------------------------------------------===//
232 """
233         print >>f, 'struct AvailableComponent {'
234         print >>f, '  /// The name of the component.'
235         print >>f, '  const char *Name;'
236         print >>f, ''
237         print >>f, '  /// The name of the library for this component (or NULL).'
238         print >>f, '  const char *Library;'
239         print >>f, ''
240         print >>f, '\
241   /// The list of libraries required when linking this component.'
242         print >>f, '  const char *RequiredLibraries[%d];' % (
243             max_required_libraries)
244         print >>f, '} AvailableComponents[%d] = {' % len(entries)
245         for name,library_name,required_names in entries:
246             if library_name is None:
247                 library_name_as_cstr = '0'
248             else:
249                 # If we had a project level component, we could derive the
250                 # library prefix.
251                 library_name_as_cstr = '"libLLVM%s.a"' % library_name
252             print >>f, '  { "%s", %s, { %s } },' % (
253                 name, library_name_as_cstr,
254                 ', '.join('"%s"' % dep
255                           for dep in required_names))
256         print >>f, '};'
257         f.close()
258
259 def main():
260     from optparse import OptionParser, OptionGroup
261     parser = OptionParser("usage: %prog [options]")
262     parser.add_option("", "--source-root", dest="source_root", metavar="PATH",
263                       help="Path to the LLVM source (inferred if not given)",
264                       action="store", default=None)
265     parser.add_option("", "--print-tree", dest="print_tree",
266                       help="Print out the project component tree [%default]",
267                       action="store_true", default=False)
268     parser.add_option("", "--write-llvmbuild", dest="write_llvmbuild",
269                       help="Write out the LLVMBuild.txt files to PATH",
270                       action="store", default=None, metavar="PATH")
271     parser.add_option("", "--write-library-table",
272                       dest="write_library_table", metavar="PATH",
273                       help="Write the C++ library dependency table to PATH",
274                       action="store", default=None)
275     parser.add_option("", "--llvmbuild-source-root",
276                       dest="llvmbuild_source_root",
277                       help=(
278             "If given, an alternate path to search for LLVMBuild.txt files"),
279                       action="store", default=None, metavar="PATH")
280     (opts, args) = parser.parse_args()
281
282     # Determine the LLVM source path, if not given.
283     source_root = opts.source_root
284     if source_root:
285         if not os.path.exists(os.path.join(source_root, 'lib', 'VMCore',
286                                            'Function.cpp')):
287             parser.error('invalid LLVM source root: %r' % source_root)
288     else:
289         llvmbuild_path = os.path.dirname(__file__)
290         llvm_build_path = os.path.dirname(llvmbuild_path)
291         utils_path = os.path.dirname(llvm_build_path)
292         source_root = os.path.dirname(utils_path)
293         if not os.path.exists(os.path.join(source_root, 'lib', 'VMCore',
294                                            'Function.cpp')):
295             parser.error('unable to infer LLVM source root, please specify')
296
297     # Construct the LLVM project information.
298     llvmbuild_source_root = opts.llvmbuild_source_root or source_root
299     project_info = LLVMProjectInfo.load_from_path(
300         source_root, llvmbuild_source_root)
301
302     # Print the component tree, if requested.
303     if opts.print_tree:
304         project_info.print_tree()
305
306     # Write out the components, if requested. This is useful for auto-upgrading
307     # the schema.
308     if opts.write_llvmbuild:
309         project_info.write_components(opts.write_llvmbuild)
310
311     # Write out the required librariy, if requested.
312     if opts.write_library_table:
313         project_info.write_library_table(opts.write_library_table)
314
315 if __name__=='__main__':
316     main()