blob: d361559de31c07c68c1eca3fdefc003c4a4412c0 [file] [log] [blame]
Daniel Dunbarad5e0122011-11-03 17:56:03 +00001import os
Daniel Dunbar1cf14af2011-11-03 17:56:12 +00002import sys
Daniel Dunbarad5e0122011-11-03 17:56:03 +00003
Daniel Dunbardf578252011-11-03 17:56:06 +00004import componentinfo
5
Daniel Dunbar1cf14af2011-11-03 17:56:12 +00006from util import *
7
8###
9
Daniel Dunbardf578252011-11-03 17:56:06 +000010class 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.
Daniel Dunbare10233b2011-11-03 19:45:52 +000017 #
18 # FIXME: We would like to use followlinks=True here, but that isn't
19 # compatible with Python 2.4. Instead, we will either have to special
20 # case projects we would expect to possibly be linked to, or implement
21 # our own walk that can follow links. For now, it doesn't matter since
22 # we haven't picked up the LLVMBuild system in any other LLVM projects.
23 for dirpath,dirnames,filenames in os.walk(llvmbuild_source_root):
Daniel Dunbardf578252011-11-03 17:56:06 +000024 # If there is no LLVMBuild.txt file in a directory, we don't recurse
25 # past it. This is a simple way to prune our search, although it
26 # makes it easy for users to add LLVMBuild.txt files in places they
27 # won't be seen.
28 if 'LLVMBuild.txt' not in filenames:
29 del dirnames[:]
30 continue
31
32 # Otherwise, load the LLVMBuild file in this directory.
33 assert dirpath.startswith(llvmbuild_source_root)
34 subpath = '/' + dirpath[len(llvmbuild_source_root)+1:]
35 llvmbuild_path = os.path.join(dirpath, 'LLVMBuild.txt')
36 for info in componentinfo.load_from_path(llvmbuild_path, subpath):
37 yield info
38
39 @staticmethod
40 def load_from_path(source_root, llvmbuild_source_root):
41 infos = list(
42 LLVMProjectInfo.load_infos_from_path(llvmbuild_source_root))
43
44 return LLVMProjectInfo(source_root, infos)
45
46 def __init__(self, source_root, component_infos):
Daniel Dunbar1cf14af2011-11-03 17:56:12 +000047 # Store our simple ivars.
Daniel Dunbardf578252011-11-03 17:56:06 +000048 self.source_root = source_root
49 self.component_infos = component_infos
50
Daniel Dunbar1cf14af2011-11-03 17:56:12 +000051 # Create the component info map and validate that component names are
52 # unique.
53 self.component_info_map = {}
54 for ci in component_infos:
55 existing = self.component_info_map.get(ci.name)
56 if existing is not None:
57 # We found a duplicate component name, report it and error out.
58 fatal("found duplicate component %r (at %r and %r)" % (
59 ci.name, ci.subpath, existing.subpath))
60 self.component_info_map[ci.name] = ci
61
Daniel Dunbarefe2f642011-11-03 17:56:28 +000062 # Disallow 'all' as a component name, which is a special case.
63 if 'all' in self.component_info_map:
64 fatal("project is not allowed to define 'all' component")
65
Daniel Dunbar00b4b4f2011-11-03 17:56:18 +000066 # Add the root component.
Daniel Dunbar86c119a2011-11-03 17:56:16 +000067 if '$ROOT' in self.component_info_map:
68 fatal("project is not allowed to define $ROOT component")
69 self.component_info_map['$ROOT'] = componentinfo.GroupComponentInfo(
70 '/', '$ROOT', None)
Daniel Dunbar00b4b4f2011-11-03 17:56:18 +000071 self.component_infos.append(self.component_info_map['$ROOT'])
Daniel Dunbar86c119a2011-11-03 17:56:16 +000072
Daniel Dunbar1cf14af2011-11-03 17:56:12 +000073 # Topologically order the component information according to their
74 # component references.
75 def visit_component_info(ci, current_stack, current_set):
76 # Check for a cycles.
77 if ci in current_set:
78 # We found a cycle, report it and error out.
79 cycle_description = ' -> '.join(
80 '%r (%s)' % (ci.name, relation)
81 for relation,ci in current_stack)
82 fatal("found cycle to %r after following: %s -> %s" % (
83 ci.name, cycle_description, ci.name))
84
85 # If we have already visited this item, we are done.
86 if ci not in components_to_visit:
87 return
88
89 # Otherwise, mark the component info as visited and traverse.
90 components_to_visit.remove(ci)
91
Daniel Dunbar86c119a2011-11-03 17:56:16 +000092 # Validate the parent reference, which we treat specially.
Daniel Dunbar00b4b4f2011-11-03 17:56:18 +000093 if ci.parent is not None:
94 parent = self.component_info_map.get(ci.parent)
95 if parent is None:
96 fatal("component %r has invalid reference %r (via %r)" % (
97 ci.name, ci.parent, 'parent'))
98 ci.set_parent_instance(parent)
Daniel Dunbar86c119a2011-11-03 17:56:16 +000099
Daniel Dunbar1cf14af2011-11-03 17:56:12 +0000100 for relation,referent_name in ci.get_component_references():
101 # Validate that the reference is ok.
102 referent = self.component_info_map.get(referent_name)
103 if referent is None:
104 fatal("component %r has invalid reference %r (via %r)" % (
105 ci.name, referent_name, relation))
106
107 # Visit the reference.
108 current_stack.append((relation,ci))
109 current_set.add(ci)
110 visit_component_info(referent, current_stack, current_set)
111 current_set.remove(ci)
112 current_stack.pop()
113
114 # Finally, add the component info to the ordered list.
115 self.ordered_component_infos.append(ci)
116
Daniel Dunbar86c119a2011-11-03 17:56:16 +0000117 # FIXME: We aren't actually correctly checking for cycles along the
118 # parent edges. Haven't decided how I want to handle this -- I thought
119 # about only checking cycles by relation type. If we do that, it falls
120 # out easily. If we don't, we should special case the check.
121
Daniel Dunbar1cf14af2011-11-03 17:56:12 +0000122 self.ordered_component_infos = []
123 components_to_visit = set(component_infos)
124 while components_to_visit:
125 visit_component_info(iter(components_to_visit).next(), [], set())
126
Daniel Dunbar00b4b4f2011-11-03 17:56:18 +0000127 # Canonicalize children lists.
128 for c in self.ordered_component_infos:
129 c.children.sort(key = lambda c: c.name)
130
131 def print_tree(self):
132 def visit(node, depth = 0):
133 print '%s%-40s (%s)' % (' '*depth, node.name, node.type_name)
134 for c in node.children:
135 visit(c, depth + 1)
136 visit(self.component_info_map['$ROOT'])
137
Daniel Dunbar43120df2011-11-03 17:56:21 +0000138 def write_components(self, output_path):
139 # Organize all the components by the directory their LLVMBuild file
140 # should go in.
141 info_basedir = {}
142 for ci in self.component_infos:
143 # Ignore the $ROOT component.
144 if ci.parent is None:
145 continue
146
147 info_basedir[ci.subpath] = info_basedir.get(ci.subpath, []) + [ci]
148
149 # Generate the build files.
150 for subpath, infos in info_basedir.items():
151 # Order the components by name to have a canonical ordering.
152 infos.sort(key = lambda ci: ci.name)
153
154 # Format the components into llvmbuild fragments.
155 fragments = filter(None, [ci.get_llvmbuild_fragment()
156 for ci in infos])
157 if not fragments:
158 continue
159
160 assert subpath.startswith('/')
161 directory_path = os.path.join(output_path, subpath[1:])
162
163 # Create the directory if it does not already exist.
164 if not os.path.exists(directory_path):
165 os.makedirs(directory_path)
166
167 # Create the LLVMBuild file.
168 file_path = os.path.join(directory_path, 'LLVMBuild.txt')
169 f = open(file_path, "w")
Daniel Dunbarfb6d79a2011-11-03 17:56:31 +0000170
171 # Write the header.
172 header_fmt = ';===- %s %s-*- Conf -*--===;'
173 header_name = '.' + os.path.join(subpath, 'LLVMBuild.txt')
174 header_pad = '-' * (80 - len(header_fmt % (header_name, '')))
175 header_string = header_fmt % (header_name, header_pad)
176 print >>f, """\
177%s
178;
179; The LLVM Compiler Infrastructure
180;
181; This file is distributed under the University of Illinois Open Source
182; License. See LICENSE.TXT for details.
183;
184;===------------------------------------------------------------------------===;
185;
186; This is an LLVMBuild description file for the components in this subdirectory.
187;
188; For more information on the LLVMBuild system, please see:
189;
190; http://llvm.org/docs/LLVMBuild.html
191;
192;===------------------------------------------------------------------------===;
193""" % header_string
194
Daniel Dunbar43120df2011-11-03 17:56:21 +0000195 for i,fragment in enumerate(fragments):
196 print >>f, '[component_%d]' % i
197 f.write(fragment)
198 print >>f
199 f.close()
200
Daniel Dunbarefe2f642011-11-03 17:56:28 +0000201 def write_library_table(self, output_path):
202 # Write out the mapping from component names to required libraries.
203 #
204 # We do this in topological order so that we know we can append the
205 # dependencies for added library groups.
206 entries = {}
207 for c in self.ordered_component_infos:
208 # Only Library and LibraryGroup components are in the table.
209 if c.type_name not in ('Library', 'LibraryGroup'):
210 continue
211
212 # Compute the llvm-config "component name". For historical reasons,
213 # this is lowercased based on the library name.
214 llvmconfig_component_name = c.get_llvmconfig_component_name()
215
216 # Get the library name, or None for LibraryGroups.
217 if c.type_name == 'LibraryGroup':
218 library_name = None
219 else:
220 library_name = c.get_library_name()
221
222 # Get the component names of all the required libraries.
223 required_llvmconfig_component_names = [
224 self.component_info_map[dep].get_llvmconfig_component_name()
225 for dep in c.required_libraries]
226
227 # Insert the entries for library groups we should add to.
228 for dep in c.add_to_library_groups:
229 entries[dep][2].append(llvmconfig_component_name)
230
231 # Add the entry.
232 entries[c.name] = (llvmconfig_component_name, library_name,
233 required_llvmconfig_component_names)
234
235 # Convert to a list of entries and sort by name.
236 entries = entries.values()
237
238 # Create an 'all' pseudo component. We keep the dependency list small by
239 # only listing entries that have no other dependents.
240 root_entries = set(e[0] for e in entries)
241 for _,_,deps in entries:
242 root_entries -= set(deps)
243 entries.append(('all', None, root_entries))
244
245 entries.sort()
246
247 # Compute the maximum number of required libraries, plus one so there is
248 # always a sentinel.
249 max_required_libraries = max(len(deps)
250 for _,_,deps in entries) + 1
251
252 # Write out the library table.
253 f = open(output_path, 'w')
254 print >>f, """\
255//===- llvm-build generated file --------------------------------*- C++ -*-===//
256//
257// Component Library Depenedency Table
258//
259// Automatically generated file, do not edit!
260//
261//===----------------------------------------------------------------------===//
262"""
263 print >>f, 'struct AvailableComponent {'
264 print >>f, ' /// The name of the component.'
265 print >>f, ' const char *Name;'
266 print >>f, ''
267 print >>f, ' /// The name of the library for this component (or NULL).'
268 print >>f, ' const char *Library;'
269 print >>f, ''
270 print >>f, '\
271 /// The list of libraries required when linking this component.'
272 print >>f, ' const char *RequiredLibraries[%d];' % (
273 max_required_libraries)
274 print >>f, '} AvailableComponents[%d] = {' % len(entries)
275 for name,library_name,required_names in entries:
276 if library_name is None:
277 library_name_as_cstr = '0'
278 else:
279 # If we had a project level component, we could derive the
280 # library prefix.
281 library_name_as_cstr = '"libLLVM%s.a"' % library_name
282 print >>f, ' { "%s", %s, { %s } },' % (
283 name, library_name_as_cstr,
284 ', '.join('"%s"' % dep
285 for dep in required_names))
286 print >>f, '};'
287 f.close()
288
Daniel Dunbar16889612011-11-04 23:10:37 +0000289 def get_fragment_dependencies(self):
Daniel Dunbar02271a72011-11-03 22:46:19 +0000290 """
Daniel Dunbar16889612011-11-04 23:10:37 +0000291 get_fragment_dependencies() -> iter
Daniel Dunbar02271a72011-11-03 22:46:19 +0000292
Daniel Dunbar16889612011-11-04 23:10:37 +0000293 Compute the list of files (as absolute paths) on which the output
294 fragments depend (i.e., files for which a modification should trigger a
295 rebuild of the fragment).
Daniel Dunbar02271a72011-11-03 22:46:19 +0000296 """
297
298 # Construct a list of all the dependencies of the Makefile fragment
299 # itself. These include all the LLVMBuild files themselves, as well as
300 # all of our own sources.
Daniel Dunbar02271a72011-11-03 22:46:19 +0000301 for ci in self.component_infos:
Daniel Dunbar16889612011-11-04 23:10:37 +0000302 yield os.path.join(self.source_root, ci.subpath[1:],
303 'LLVMBuild.txt')
Daniel Dunbar02271a72011-11-03 22:46:19 +0000304
305 # Gather the list of necessary sources by just finding all loaded
306 # modules that are inside the LLVM source tree.
307 for module in sys.modules.values():
308 # Find the module path.
309 if not hasattr(module, '__file__'):
310 continue
311 path = getattr(module, '__file__')
312 if not path:
313 continue
314
315 # Strip off any compiled suffix.
316 if os.path.splitext(path)[1] in ['.pyc', '.pyo', '.pyd']:
317 path = path[:-1]
318
319 # If the path exists and is in the source tree, consider it a
320 # dependency.
321 if (path.startswith(self.source_root) and os.path.exists(path)):
Daniel Dunbar16889612011-11-04 23:10:37 +0000322 yield path
323
324 def write_cmake_fragment(self, output_path):
325 """
326 write_cmake_fragment(output_path) -> None
327
328 Generate a CMake fragment which includes all of the collated LLVMBuild
329 information in a format that is easily digestible by a CMake. The exact
330 contents of this are closely tied to how the CMake configuration
331 integrates LLVMBuild, see CMakeLists.txt in the top-level.
332 """
333
334 dependencies = list(self.get_fragment_dependencies())
335
336 # Write out the CMake fragment.
337 f = open(output_path, 'w')
338
339 # Write the header.
340 header_fmt = '\
341#===-- %s - LLVMBuild Configuration for LLVM %s-*- CMake -*--===#'
342 header_name = os.path.basename(output_path)
343 header_pad = '-' * (80 - len(header_fmt % (header_name, '')))
344 header_string = header_fmt % (header_name, header_pad)
345 print >>f, """\
346%s
347#
348# The LLVM Compiler Infrastructure
349#
350# This file is distributed under the University of Illinois Open Source
351# License. See LICENSE.TXT for details.
352#
353#===------------------------------------------------------------------------===#
354#
355# This file contains the LLVMBuild project information in a format easily
356# consumed by the CMake based build system.
357#
358# This file is autogenerated by llvm-build, do not edit!
359#
360#===------------------------------------------------------------------------===#
361""" % header_string
362
363 # Write the dependency information in the best way we can.
364 print >>f, """
365# LLVMBuild CMake fragment dependencies.
366#
367# CMake has no builtin way to declare that the configuration depends on
368# a particular file. However, a side effect of configure_file is to add
369# said input file to CMake's internal dependency list. So, we use that
370# and a dummy output file to communicate the dependency information to
371# CMake.
372#
373# FIXME: File a CMake RFE to get a properly supported version of this
374# feature."""
375 for dep in dependencies:
376 print >>f, """\
377configure_file(\"%s\"
378 ${CMAKE_CURRENT_BINARY_DIR}/DummyConfigureOutput)""" % (dep,)
379
380 f.close()
381
382 def write_make_fragment(self, output_path):
383 """
384 write_make_fragment(output_path) -> None
385
386 Generate a Makefile fragment which includes all of the collated
387 LLVMBuild information in a format that is easily digestible by a
388 Makefile. The exact contents of this are closely tied to how the LLVM
389 Makefiles integrate LLVMBuild, see Makefile.rules in the top-level.
390 """
391
392 dependencies = list(self.get_fragment_dependencies())
Daniel Dunbar02271a72011-11-03 22:46:19 +0000393
394 # Write out the Makefile fragment.
395 f = open(output_path, 'w')
396
397 # Write the header.
398 header_fmt = '\
399#===-- %s - LLVMBuild Configuration for LLVM %s-*- Makefile -*--===#'
400 header_name = os.path.basename(output_path)
401 header_pad = '-' * (80 - len(header_fmt % (header_name, '')))
402 header_string = header_fmt % (header_name, header_pad)
403 print >>f, """\
404%s
405#
406# The LLVM Compiler Infrastructure
407#
408# This file is distributed under the University of Illinois Open Source
409# License. See LICENSE.TXT for details.
410#
411#===------------------------------------------------------------------------===#
412#
413# This file contains the LLVMBuild project information in a format easily
414# consumed by the Makefile based build system.
415#
416# This file is autogenerated by llvm-build, do not edit!
417#
418#===------------------------------------------------------------------------===#
419""" % header_string
420
421 # Write the dependencies for the fragment.
422 #
423 # FIXME: Technically, we need to properly quote for Make here.
424 print >>f, """\
425# Clients must explicitly enable LLVMBUILD_INCLUDE_DEPENDENCIES to get
426# these dependencies. This is a compromise to help improve the
427# performance of recursive Make systems."""
428 print >>f, 'ifeq ($(LLVMBUILD_INCLUDE_DEPENDENCIES),1)'
429 print >>f, "# The dependencies for this Makefile fragment itself."
430 print >>f, "%s: \\" % (output_path,)
431 for dep in dependencies:
432 print >>f, "\t%s \\" % (dep,)
433 print >>f
434
435 # Generate dummy rules for each of the dependencies, so that things
436 # continue to work correctly if any of those files are moved or removed.
437 print >>f, """\
438# The dummy targets to allow proper regeneration even when files are moved or
439# removed."""
440 for dep in dependencies:
441 print >>f, "%s:" % (dep,)
442 print >>f, 'endif'
443
444 f.close()
445
Daniel Dunbarad5e0122011-11-03 17:56:03 +0000446def main():
447 from optparse import OptionParser, OptionGroup
448 parser = OptionParser("usage: %prog [options]")
449 parser.add_option("", "--source-root", dest="source_root", metavar="PATH",
450 help="Path to the LLVM source (inferred if not given)",
451 action="store", default=None)
Daniel Dunbar00b4b4f2011-11-03 17:56:18 +0000452 parser.add_option("", "--print-tree", dest="print_tree",
453 help="Print out the project component tree [%default]",
454 action="store_true", default=False)
Daniel Dunbar43120df2011-11-03 17:56:21 +0000455 parser.add_option("", "--write-llvmbuild", dest="write_llvmbuild",
456 help="Write out the LLVMBuild.txt files to PATH",
457 action="store", default=None, metavar="PATH")
Daniel Dunbarefe2f642011-11-03 17:56:28 +0000458 parser.add_option("", "--write-library-table",
459 dest="write_library_table", metavar="PATH",
460 help="Write the C++ library dependency table to PATH",
461 action="store", default=None)
Daniel Dunbar16889612011-11-04 23:10:37 +0000462 parser.add_option("", "--write-cmake-fragment",
463 dest="write_cmake_fragment", metavar="PATH",
464 help="Write the CMake project information to PATH",
465 action="store", default=None)
Daniel Dunbar02271a72011-11-03 22:46:19 +0000466 parser.add_option("", "--write-make-fragment",
467 dest="write_make_fragment", metavar="PATH",
468 help="Write the Makefile project information to PATH",
469 action="store", default=None)
Daniel Dunbarefe2f642011-11-03 17:56:28 +0000470 parser.add_option("", "--llvmbuild-source-root",
471 dest="llvmbuild_source_root",
472 help=(
473 "If given, an alternate path to search for LLVMBuild.txt files"),
474 action="store", default=None, metavar="PATH")
Daniel Dunbarad5e0122011-11-03 17:56:03 +0000475 (opts, args) = parser.parse_args()
476
477 # Determine the LLVM source path, if not given.
478 source_root = opts.source_root
479 if source_root:
480 if not os.path.exists(os.path.join(source_root, 'lib', 'VMCore',
481 'Function.cpp')):
482 parser.error('invalid LLVM source root: %r' % source_root)
483 else:
484 llvmbuild_path = os.path.dirname(__file__)
485 llvm_build_path = os.path.dirname(llvmbuild_path)
486 utils_path = os.path.dirname(llvm_build_path)
487 source_root = os.path.dirname(utils_path)
488 if not os.path.exists(os.path.join(source_root, 'lib', 'VMCore',
489 'Function.cpp')):
490 parser.error('unable to infer LLVM source root, please specify')
491
Daniel Dunbardf578252011-11-03 17:56:06 +0000492 # Construct the LLVM project information.
493 llvmbuild_source_root = opts.llvmbuild_source_root or source_root
494 project_info = LLVMProjectInfo.load_from_path(
495 source_root, llvmbuild_source_root)
496
Daniel Dunbar00b4b4f2011-11-03 17:56:18 +0000497 # Print the component tree, if requested.
498 if opts.print_tree:
499 project_info.print_tree()
500
Daniel Dunbar43120df2011-11-03 17:56:21 +0000501 # Write out the components, if requested. This is useful for auto-upgrading
502 # the schema.
503 if opts.write_llvmbuild:
504 project_info.write_components(opts.write_llvmbuild)
505
Daniel Dunbar16889612011-11-04 23:10:37 +0000506 # Write out the required library table, if requested.
Daniel Dunbarefe2f642011-11-03 17:56:28 +0000507 if opts.write_library_table:
508 project_info.write_library_table(opts.write_library_table)
509
Daniel Dunbar16889612011-11-04 23:10:37 +0000510 # Write out the make fragment, if requested.
Daniel Dunbar02271a72011-11-03 22:46:19 +0000511 if opts.write_make_fragment:
512 project_info.write_make_fragment(opts.write_make_fragment)
513
Daniel Dunbar16889612011-11-04 23:10:37 +0000514 # Write out the cmake fragment, if requested.
515 if opts.write_cmake_fragment:
516 project_info.write_cmake_fragment(opts.write_cmake_fragment)
517
Daniel Dunbarad5e0122011-11-03 17:56:03 +0000518if __name__=='__main__':
519 main()