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