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.
17 for dirpath,dirnames,filenames in os.walk(llvmbuild_source_root,
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
23 if 'LLVMBuild.txt' not in filenames:
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):
35 def load_from_path(source_root, llvmbuild_source_root):
37 LLVMProjectInfo.load_infos_from_path(llvmbuild_source_root))
39 return LLVMProjectInfo(source_root, infos)
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
46 # Create the component info map and validate that component names are
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
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")
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(
66 self.component_infos.append(self.component_info_map['$ROOT'])
68 # Topologically order the component information according to their
69 # component references.
70 def visit_component_info(ci, current_stack, 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))
80 # If we have already visited this item, we are done.
81 if ci not in components_to_visit:
84 # Otherwise, mark the component info as visited and traverse.
85 components_to_visit.remove(ci)
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)
91 fatal("component %r has invalid reference %r (via %r)" % (
92 ci.name, ci.parent, 'parent'))
93 ci.set_parent_instance(parent)
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)
99 fatal("component %r has invalid reference %r (via %r)" % (
100 ci.name, referent_name, relation))
102 # Visit the reference.
103 current_stack.append((relation,ci))
105 visit_component_info(referent, current_stack, current_set)
106 current_set.remove(ci)
109 # Finally, add the component info to the ordered list.
110 self.ordered_component_infos.append(ci)
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.
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())
122 # Canonicalize children lists.
123 for c in self.ordered_component_infos:
124 c.children.sort(key = lambda c: c.name)
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:
131 visit(self.component_info_map['$ROOT'])
133 def write_components(self, output_path):
134 # Organize all the components by the directory their LLVMBuild file
137 for ci in self.component_infos:
138 # Ignore the $ROOT component.
139 if ci.parent is None:
142 info_basedir[ci.subpath] = info_basedir.get(ci.subpath, []) + [ci]
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)
149 # Format the components into llvmbuild fragments.
150 fragments = filter(None, [ci.get_llvmbuild_fragment()
155 assert subpath.startswith('/')
156 directory_path = os.path.join(output_path, subpath[1:])
158 # Create the directory if it does not already exist.
159 if not os.path.exists(directory_path):
160 os.makedirs(directory_path)
162 # Create the LLVMBuild file.
163 file_path = os.path.join(directory_path, 'LLVMBuild.txt')
164 f = open(file_path, "w")
165 for i,fragment in enumerate(fragments):
166 print >>f, '[component_%d]' % i
171 def write_library_table(self, output_path):
172 # Write out the mapping from component names to required libraries.
174 # We do this in topological order so that we know we can append the
175 # dependencies for added library groups.
177 for c in self.ordered_component_infos:
178 # Only Library and LibraryGroup components are in the table.
179 if c.type_name not in ('Library', 'LibraryGroup'):
182 # Compute the llvm-config "component name". For historical reasons,
183 # this is lowercased based on the library name.
184 llvmconfig_component_name = c.get_llvmconfig_component_name()
186 # Get the library name, or None for LibraryGroups.
187 if c.type_name == 'LibraryGroup':
190 library_name = c.get_library_name()
192 # Get the component names of all the required libraries.
193 required_llvmconfig_component_names = [
194 self.component_info_map[dep].get_llvmconfig_component_name()
195 for dep in c.required_libraries]
197 # Insert the entries for library groups we should add to.
198 for dep in c.add_to_library_groups:
199 entries[dep][2].append(llvmconfig_component_name)
202 entries[c.name] = (llvmconfig_component_name, library_name,
203 required_llvmconfig_component_names)
205 # Convert to a list of entries and sort by name.
206 entries = entries.values()
208 # Create an 'all' pseudo component. We keep the dependency list small by
209 # only listing entries that have no other dependents.
210 root_entries = set(e[0] for e in entries)
211 for _,_,deps in entries:
212 root_entries -= set(deps)
213 entries.append(('all', None, root_entries))
217 # Compute the maximum number of required libraries, plus one so there is
219 max_required_libraries = max(len(deps)
220 for _,_,deps in entries) + 1
222 # Write out the library table.
223 f = open(output_path, 'w')
225 //===- llvm-build generated file --------------------------------*- C++ -*-===//
227 // Component Library Depenedency Table
229 // Automatically generated file, do not edit!
231 //===----------------------------------------------------------------------===//
233 print >>f, 'struct AvailableComponent {'
234 print >>f, ' /// The name of the component.'
235 print >>f, ' const char *Name;'
237 print >>f, ' /// The name of the library for this component (or NULL).'
238 print >>f, ' const char *Library;'
241 /// The list of libraries required when linking this component.'
242 print >>f, ' const char *RequiredLibraries[%d];' % (
243 max_required_libraries)
244 print >>f, '} AvailableComponents[%d] = {' % len(entries)
245 for name,library_name,required_names in entries:
246 if library_name is None:
247 library_name_as_cstr = '0'
249 # If we had a project level component, we could derive the
251 library_name_as_cstr = '"libLLVM%s.a"' % library_name
252 print >>f, ' { "%s", %s, { %s } },' % (
253 name, library_name_as_cstr,
254 ', '.join('"%s"' % dep
255 for dep in required_names))
260 from optparse import OptionParser, OptionGroup
261 parser = OptionParser("usage: %prog [options]")
262 parser.add_option("", "--source-root", dest="source_root", metavar="PATH",
263 help="Path to the LLVM source (inferred if not given)",
264 action="store", default=None)
265 parser.add_option("", "--print-tree", dest="print_tree",
266 help="Print out the project component tree [%default]",
267 action="store_true", default=False)
268 parser.add_option("", "--write-llvmbuild", dest="write_llvmbuild",
269 help="Write out the LLVMBuild.txt files to PATH",
270 action="store", default=None, metavar="PATH")
271 parser.add_option("", "--write-library-table",
272 dest="write_library_table", metavar="PATH",
273 help="Write the C++ library dependency table to PATH",
274 action="store", default=None)
275 parser.add_option("", "--llvmbuild-source-root",
276 dest="llvmbuild_source_root",
278 "If given, an alternate path to search for LLVMBuild.txt files"),
279 action="store", default=None, metavar="PATH")
280 (opts, args) = parser.parse_args()
282 # Determine the LLVM source path, if not given.
283 source_root = opts.source_root
285 if not os.path.exists(os.path.join(source_root, 'lib', 'VMCore',
287 parser.error('invalid LLVM source root: %r' % source_root)
289 llvmbuild_path = os.path.dirname(__file__)
290 llvm_build_path = os.path.dirname(llvmbuild_path)
291 utils_path = os.path.dirname(llvm_build_path)
292 source_root = os.path.dirname(utils_path)
293 if not os.path.exists(os.path.join(source_root, 'lib', 'VMCore',
295 parser.error('unable to infer LLVM source root, please specify')
297 # Construct the LLVM project information.
298 llvmbuild_source_root = opts.llvmbuild_source_root or source_root
299 project_info = LLVMProjectInfo.load_from_path(
300 source_root, llvmbuild_source_root)
302 # Print the component tree, if requested.
304 project_info.print_tree()
306 # Write out the components, if requested. This is useful for auto-upgrading
308 if opts.write_llvmbuild:
309 project_info.write_components(opts.write_llvmbuild)
311 # Write out the required librariy, if requested.
312 if opts.write_library_table:
313 project_info.write_library_table(opts.write_library_table)
315 if __name__=='__main__':