llvm-build: Update --write-llvmbuild to write out a standard LLVM style file
[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
166             # Write the header.
167             header_fmt = ';===- %s %s-*- Conf -*--===;'
168             header_name = '.' + os.path.join(subpath, 'LLVMBuild.txt')
169             header_pad = '-' * (80 - len(header_fmt % (header_name, '')))
170             header_string = header_fmt % (header_name, header_pad)
171             print >>f, """\
172 %s
173 ;
174 ;                     The LLVM Compiler Infrastructure
175 ;
176 ; This file is distributed under the University of Illinois Open Source
177 ; License. See LICENSE.TXT for details.
178 ;
179 ;===------------------------------------------------------------------------===;
180 ;
181 ; This is an LLVMBuild description file for the components in this subdirectory.
182 ;
183 ; For more information on the LLVMBuild system, please see:
184 ;
185 ;   http://llvm.org/docs/LLVMBuild.html
186 ;
187 ;===------------------------------------------------------------------------===;
188 """ % header_string
189
190             for i,fragment in enumerate(fragments):
191                 print >>f, '[component_%d]' % i
192                 f.write(fragment)
193                 print >>f
194             f.close()
195
196     def write_library_table(self, output_path):
197         # Write out the mapping from component names to required libraries.
198         #
199         # We do this in topological order so that we know we can append the
200         # dependencies for added library groups.
201         entries = {}
202         for c in self.ordered_component_infos:
203             # Only Library and LibraryGroup components are in the table.
204             if c.type_name not in ('Library', 'LibraryGroup'):
205                 continue
206
207             # Compute the llvm-config "component name". For historical reasons,
208             # this is lowercased based on the library name.
209             llvmconfig_component_name = c.get_llvmconfig_component_name()
210             
211             # Get the library name, or None for LibraryGroups.
212             if c.type_name == 'LibraryGroup':
213                 library_name = None
214             else:
215                 library_name = c.get_library_name()
216
217             # Get the component names of all the required libraries.
218             required_llvmconfig_component_names = [
219                 self.component_info_map[dep].get_llvmconfig_component_name()
220                 for dep in c.required_libraries]
221
222             # Insert the entries for library groups we should add to.
223             for dep in c.add_to_library_groups:
224                 entries[dep][2].append(llvmconfig_component_name)
225
226             # Add the entry.
227             entries[c.name] = (llvmconfig_component_name, library_name,
228                                required_llvmconfig_component_names)
229
230         # Convert to a list of entries and sort by name.
231         entries = entries.values()
232
233         # Create an 'all' pseudo component. We keep the dependency list small by
234         # only listing entries that have no other dependents.
235         root_entries = set(e[0] for e in entries)
236         for _,_,deps in entries:
237             root_entries -= set(deps)
238         entries.append(('all', None, root_entries))
239
240         entries.sort()
241
242         # Compute the maximum number of required libraries, plus one so there is
243         # always a sentinel.
244         max_required_libraries = max(len(deps)
245                                      for _,_,deps in entries) + 1
246
247         # Write out the library table.
248         f = open(output_path, 'w')
249         print >>f, """\
250 //===- llvm-build generated file --------------------------------*- C++ -*-===//
251 //
252 // Component Library Depenedency Table
253 //
254 // Automatically generated file, do not edit!
255 //
256 //===----------------------------------------------------------------------===//
257 """
258         print >>f, 'struct AvailableComponent {'
259         print >>f, '  /// The name of the component.'
260         print >>f, '  const char *Name;'
261         print >>f, ''
262         print >>f, '  /// The name of the library for this component (or NULL).'
263         print >>f, '  const char *Library;'
264         print >>f, ''
265         print >>f, '\
266   /// The list of libraries required when linking this component.'
267         print >>f, '  const char *RequiredLibraries[%d];' % (
268             max_required_libraries)
269         print >>f, '} AvailableComponents[%d] = {' % len(entries)
270         for name,library_name,required_names in entries:
271             if library_name is None:
272                 library_name_as_cstr = '0'
273             else:
274                 # If we had a project level component, we could derive the
275                 # library prefix.
276                 library_name_as_cstr = '"libLLVM%s.a"' % library_name
277             print >>f, '  { "%s", %s, { %s } },' % (
278                 name, library_name_as_cstr,
279                 ', '.join('"%s"' % dep
280                           for dep in required_names))
281         print >>f, '};'
282         f.close()
283
284 def main():
285     from optparse import OptionParser, OptionGroup
286     parser = OptionParser("usage: %prog [options]")
287     parser.add_option("", "--source-root", dest="source_root", metavar="PATH",
288                       help="Path to the LLVM source (inferred if not given)",
289                       action="store", default=None)
290     parser.add_option("", "--print-tree", dest="print_tree",
291                       help="Print out the project component tree [%default]",
292                       action="store_true", default=False)
293     parser.add_option("", "--write-llvmbuild", dest="write_llvmbuild",
294                       help="Write out the LLVMBuild.txt files to PATH",
295                       action="store", default=None, metavar="PATH")
296     parser.add_option("", "--write-library-table",
297                       dest="write_library_table", metavar="PATH",
298                       help="Write the C++ library dependency table to PATH",
299                       action="store", default=None)
300     parser.add_option("", "--llvmbuild-source-root",
301                       dest="llvmbuild_source_root",
302                       help=(
303             "If given, an alternate path to search for LLVMBuild.txt files"),
304                       action="store", default=None, metavar="PATH")
305     (opts, args) = parser.parse_args()
306
307     # Determine the LLVM source path, if not given.
308     source_root = opts.source_root
309     if source_root:
310         if not os.path.exists(os.path.join(source_root, 'lib', 'VMCore',
311                                            'Function.cpp')):
312             parser.error('invalid LLVM source root: %r' % source_root)
313     else:
314         llvmbuild_path = os.path.dirname(__file__)
315         llvm_build_path = os.path.dirname(llvmbuild_path)
316         utils_path = os.path.dirname(llvm_build_path)
317         source_root = os.path.dirname(utils_path)
318         if not os.path.exists(os.path.join(source_root, 'lib', 'VMCore',
319                                            'Function.cpp')):
320             parser.error('unable to infer LLVM source root, please specify')
321
322     # Construct the LLVM project information.
323     llvmbuild_source_root = opts.llvmbuild_source_root or source_root
324     project_info = LLVMProjectInfo.load_from_path(
325         source_root, llvmbuild_source_root)
326
327     # Print the component tree, if requested.
328     if opts.print_tree:
329         project_info.print_tree()
330
331     # Write out the components, if requested. This is useful for auto-upgrading
332     # the schema.
333     if opts.write_llvmbuild:
334         project_info.write_components(opts.write_llvmbuild)
335
336     # Write out the required librariy, if requested.
337     if opts.write_library_table:
338         project_info.write_library_table(opts.write_library_table)
339
340 if __name__=='__main__':
341     main()