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