10 class LLVMProjectInfo(object):
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.
16 # First, discover all the LLVMBuild.txt files.
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):
24 # 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
28 if 'LLVMBuild.txt' not in filenames:
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):
40 def load_from_path(source_root, llvmbuild_source_root):
42 LLVMProjectInfo.load_infos_from_path(llvmbuild_source_root))
44 return LLVMProjectInfo(source_root, infos)
46 def __init__(self, source_root, component_infos):
47 # Store our simple ivars.
48 self.source_root = source_root
49 self.component_infos = component_infos
51 # Create the component info map and validate that component names are
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
62 # 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")
66 # Add the root component.
67 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(
71 self.component_infos.append(self.component_info_map['$ROOT'])
73 # Topologically order the component information according to their
74 # component references.
75 def visit_component_info(ci, current_stack, 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))
85 # If we have already visited this item, we are done.
86 if ci not in components_to_visit:
89 # Otherwise, mark the component info as visited and traverse.
90 components_to_visit.remove(ci)
92 # Validate the parent reference, which we treat specially.
93 if ci.parent is not None:
94 parent = self.component_info_map.get(ci.parent)
96 fatal("component %r has invalid reference %r (via %r)" % (
97 ci.name, ci.parent, 'parent'))
98 ci.set_parent_instance(parent)
100 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)
104 fatal("component %r has invalid reference %r (via %r)" % (
105 ci.name, referent_name, relation))
107 # Visit the reference.
108 current_stack.append((relation,ci))
110 visit_component_info(referent, current_stack, current_set)
111 current_set.remove(ci)
114 # Finally, add the component info to the ordered list.
115 self.ordered_component_infos.append(ci)
117 # 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.
122 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())
127 # Canonicalize children lists.
128 for c in self.ordered_component_infos:
129 c.children.sort(key = lambda c: c.name)
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:
136 visit(self.component_info_map['$ROOT'])
138 def write_components(self, output_path):
139 # Organize all the components by the directory their LLVMBuild file
142 for ci in self.component_infos:
143 # Ignore the $ROOT component.
144 if ci.parent is None:
147 info_basedir[ci.subpath] = info_basedir.get(ci.subpath, []) + [ci]
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)
154 # Format the components into llvmbuild fragments.
155 fragments = filter(None, [ci.get_llvmbuild_fragment()
160 assert subpath.startswith('/')
161 directory_path = os.path.join(output_path, subpath[1:])
163 # Create the directory if it does not already exist.
164 if not os.path.exists(directory_path):
165 os.makedirs(directory_path)
167 # Create the LLVMBuild file.
168 file_path = os.path.join(directory_path, 'LLVMBuild.txt')
169 f = open(file_path, "w")
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)
179 ; The LLVM Compiler Infrastructure
181 ; This file is distributed under the University of Illinois Open Source
182 ; License. See LICENSE.TXT for details.
184 ;===------------------------------------------------------------------------===;
186 ; This is an LLVMBuild description file for the components in this subdirectory.
188 ; For more information on the LLVMBuild system, please see:
190 ; http://llvm.org/docs/LLVMBuild.html
192 ;===------------------------------------------------------------------------===;
195 for i,fragment in enumerate(fragments):
196 print >>f, '[component_%d]' % i
201 def write_library_table(self, output_path):
202 # Write out the mapping from component names to required libraries.
204 # We do this in topological order so that we know we can append the
205 # dependencies for added library groups.
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'):
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()
216 # Get the library name, or None for LibraryGroups.
217 if c.type_name == 'LibraryGroup':
220 library_name = c.get_library_name()
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]
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)
232 entries[c.name] = (llvmconfig_component_name, library_name,
233 required_llvmconfig_component_names)
235 # Convert to a list of entries and sort by name.
236 entries = entries.values()
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))
247 # Compute the maximum number of required libraries, plus one so there is
249 max_required_libraries = max(len(deps)
250 for _,_,deps in entries) + 1
252 # Write out the library table.
253 f = open(output_path, 'w')
255 //===- llvm-build generated file --------------------------------*- C++ -*-===//
257 // Component Library Depenedency Table
259 // Automatically generated file, do not edit!
261 //===----------------------------------------------------------------------===//
263 print >>f, 'struct AvailableComponent {'
264 print >>f, ' /// The name of the component.'
265 print >>f, ' const char *Name;'
267 print >>f, ' /// The name of the library for this component (or NULL).'
268 print >>f, ' const char *Library;'
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'
279 # If we had a project level component, we could derive the
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))
289 def get_fragment_dependencies(self):
291 get_fragment_dependencies() -> iter
293 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).
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.
301 for ci in self.component_infos:
302 yield os.path.join(self.source_root, ci.subpath[1:],
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__'):
311 path = getattr(module, '__file__')
315 # Strip off any compiled suffix.
316 if os.path.splitext(path)[1] in ['.pyc', '.pyo', '.pyd']:
319 # If the path exists and is in the source tree, consider it a
321 if (path.startswith(self.source_root) and os.path.exists(path)):
324 def write_cmake_fragment(self, output_path):
326 write_cmake_fragment(output_path) -> None
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.
334 dependencies = list(self.get_fragment_dependencies())
336 # Write out the CMake fragment.
337 f = open(output_path, 'w')
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)
348 # The LLVM Compiler Infrastructure
350 # This file is distributed under the University of Illinois Open Source
351 # License. See LICENSE.TXT for details.
353 #===------------------------------------------------------------------------===#
355 # This file contains the LLVMBuild project information in a format easily
356 # consumed by the CMake based build system.
358 # This file is autogenerated by llvm-build, do not edit!
360 #===------------------------------------------------------------------------===#
363 # Write the dependency information in the best way we can.
365 # LLVMBuild CMake fragment dependencies.
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
373 # FIXME: File a CMake RFE to get a properly supported version of this
375 for dep in dependencies:
377 configure_file(\"%s\"
378 ${CMAKE_CURRENT_BINARY_DIR}/DummyConfigureOutput)""" % (dep,)
382 def write_make_fragment(self, output_path):
384 write_make_fragment(output_path) -> None
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.
392 dependencies = list(self.get_fragment_dependencies())
394 # Write out the Makefile fragment.
395 f = open(output_path, 'w')
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)
406 # The LLVM Compiler Infrastructure
408 # This file is distributed under the University of Illinois Open Source
409 # License. See LICENSE.TXT for details.
411 #===------------------------------------------------------------------------===#
413 # This file contains the LLVMBuild project information in a format easily
414 # consumed by the Makefile based build system.
416 # This file is autogenerated by llvm-build, do not edit!
418 #===------------------------------------------------------------------------===#
421 # Write the dependencies for the fragment.
423 # FIXME: Technically, we need to properly quote for Make here.
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,)
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.
438 # The dummy targets to allow proper regeneration even when files are moved or
440 for dep in dependencies:
441 print >>f, "%s:" % (dep,)
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)
452 parser.add_option("", "--print-tree", dest="print_tree",
453 help="Print out the project component tree [%default]",
454 action="store_true", default=False)
455 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")
458 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)
462 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)
466 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)
470 parser.add_option("", "--llvmbuild-source-root",
471 dest="llvmbuild_source_root",
473 "If given, an alternate path to search for LLVMBuild.txt files"),
474 action="store", default=None, metavar="PATH")
475 (opts, args) = parser.parse_args()
477 # Determine the LLVM source path, if not given.
478 source_root = opts.source_root
480 if not os.path.exists(os.path.join(source_root, 'lib', 'VMCore',
482 parser.error('invalid LLVM source root: %r' % source_root)
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',
490 parser.error('unable to infer LLVM source root, please specify')
492 # 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)
497 # Print the component tree, if requested.
499 project_info.print_tree()
501 # Write out the components, if requested. This is useful for auto-upgrading
503 if opts.write_llvmbuild:
504 project_info.write_components(opts.write_llvmbuild)
506 # Write out the required library table, if requested.
507 if opts.write_library_table:
508 project_info.write_library_table(opts.write_library_table)
510 # Write out the make fragment, if requested.
511 if opts.write_make_fragment:
512 project_info.write_make_fragment(opts.write_make_fragment)
514 # Write out the cmake fragment, if requested.
515 if opts.write_cmake_fragment:
516 project_info.write_cmake_fragment(opts.write_cmake_fragment)
518 if __name__=='__main__':