SConscript revision 8881:042d509574c1
12789Sktlim@umich.edu# -*- mode:python -*-
22789Sktlim@umich.edu
32789Sktlim@umich.edu# Copyright (c) 2004-2005 The Regents of The University of Michigan
42789Sktlim@umich.edu# All rights reserved.
52789Sktlim@umich.edu#
62789Sktlim@umich.edu# Redistribution and use in source and binary forms, with or without
72789Sktlim@umich.edu# modification, are permitted provided that the following conditions are
82789Sktlim@umich.edu# met: redistributions of source code must retain the above copyright
92789Sktlim@umich.edu# notice, this list of conditions and the following disclaimer;
102789Sktlim@umich.edu# redistributions in binary form must reproduce the above copyright
112789Sktlim@umich.edu# notice, this list of conditions and the following disclaimer in the
122789Sktlim@umich.edu# documentation and/or other materials provided with the distribution;
132789Sktlim@umich.edu# neither the name of the copyright holders nor the names of its
142789Sktlim@umich.edu# contributors may be used to endorse or promote products derived from
152789Sktlim@umich.edu# this software without specific prior written permission.
162789Sktlim@umich.edu#
172789Sktlim@umich.edu# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
182789Sktlim@umich.edu# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
192789Sktlim@umich.edu# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
202789Sktlim@umich.edu# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
212789Sktlim@umich.edu# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
222789Sktlim@umich.edu# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
232789Sktlim@umich.edu# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
242789Sktlim@umich.edu# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
252789Sktlim@umich.edu# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
262789Sktlim@umich.edu# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
272789Sktlim@umich.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
282789Sktlim@umich.edu#
292789Sktlim@umich.edu# Authors: Nathan Binkert
302789Sktlim@umich.edu
312789Sktlim@umich.eduimport array
322789Sktlim@umich.eduimport bisect
332789Sktlim@umich.eduimport imp
348793Sgblack@eecs.umich.eduimport marshal
358793Sgblack@eecs.umich.eduimport os
368229Snate@binkert.orgimport re
372789Sktlim@umich.eduimport sys
382789Sktlim@umich.eduimport zlib
393348Sbinkertn@umich.edu
402789Sktlim@umich.edufrom os.path import basename, dirname, exists, isdir, isfile, join as joinpath
412789Sktlim@umich.edu
422789Sktlim@umich.eduimport SCons
432789Sktlim@umich.edu
442789Sktlim@umich.edu# This file defines how to build a particular configuration of gem5
452789Sktlim@umich.edu# based on variable settings in the 'env' build environment.
462789Sktlim@umich.edu
472789Sktlim@umich.eduImport('*')
482789Sktlim@umich.edu
492789Sktlim@umich.edu# Children need to see the environment
502789Sktlim@umich.eduExport('env')
512789Sktlim@umich.edu
522789Sktlim@umich.edubuild_env = [(opt, env[opt]) for opt in export_vars]
532789Sktlim@umich.edu
542789Sktlim@umich.edufrom m5.util import code_formatter, compareVersions
552789Sktlim@umich.edu
562789Sktlim@umich.edu########################################################################
572789Sktlim@umich.edu# Code for adding source files of various types
582789Sktlim@umich.edu#
592789Sktlim@umich.edu# When specifying a source file of some type, a set of guards can be
602789Sktlim@umich.edu# specified for that file.  When get() is used to find the files, if
612789Sktlim@umich.edu# get specifies a set of filters, only files that match those filters
622789Sktlim@umich.edu# will be accepted (unspecified filters on files are assumed to be
632789Sktlim@umich.edu# false).  Current filters are:
642789Sktlim@umich.edu#     main -- specifies the gem5 main() function
652789Sktlim@umich.edu#     skip_lib -- do not put this file into the gem5 library
662789Sktlim@umich.edu#     <unittest> -- unit tests use filters based on the unit test name
672789Sktlim@umich.edu#
682789Sktlim@umich.edu# A parent can now be specified for a source file and default filter
692789Sktlim@umich.edu# values will be retrieved recursively from parents (children override
706331Sgblack@eecs.umich.edu# parents).
713402Sktlim@umich.edu#
723402Sktlim@umich.educlass SourceMeta(type):
733402Sktlim@umich.edu    '''Meta class for source files that keeps track of all files of a
742789Sktlim@umich.edu    particular type and has a get function for finding all functions
752789Sktlim@umich.edu    of a certain type that match a set of guards'''
762789Sktlim@umich.edu    def __init__(cls, name, bases, dict):
772789Sktlim@umich.edu        super(SourceMeta, cls).__init__(name, bases, dict)
782789Sktlim@umich.edu        cls.all = []
792789Sktlim@umich.edu        
802789Sktlim@umich.edu    def get(cls, **guards):
812789Sktlim@umich.edu        '''Find all files that match the specified guards.  If a source
822789Sktlim@umich.edu        file does not specify a flag, the default is False'''
832789Sktlim@umich.edu        for src in cls.all:
842789Sktlim@umich.edu            for flag,value in guards.iteritems():
852789Sktlim@umich.edu                # if the flag is found and has a different value, skip
862789Sktlim@umich.edu                # this file
872789Sktlim@umich.edu                if src.all_guards.get(flag, False) != value:
882789Sktlim@umich.edu                    break
892789Sktlim@umich.edu            else:
902789Sktlim@umich.edu                yield src
912789Sktlim@umich.edu
922789Sktlim@umich.educlass SourceFile(object):
932789Sktlim@umich.edu    '''Base object that encapsulates the notion of a source file.
942789Sktlim@umich.edu    This includes, the source node, target node, various manipulations
952789Sktlim@umich.edu    of those.  A source file also specifies a set of guards which
962789Sktlim@umich.edu    describing which builds the source file applies to.  A parent can
972789Sktlim@umich.edu    also be specified to get default guards from'''
982789Sktlim@umich.edu    __metaclass__ = SourceMeta
992789Sktlim@umich.edu    def __init__(self, source, parent=None, **guards):
1002789Sktlim@umich.edu        self.guards = guards
1012789Sktlim@umich.edu        self.parent = parent
1022789Sktlim@umich.edu
1032789Sktlim@umich.edu        tnode = source
1042789Sktlim@umich.edu        if not isinstance(source, SCons.Node.FS.File):
1052789Sktlim@umich.edu            tnode = File(source)
1062789Sktlim@umich.edu
1072789Sktlim@umich.edu        self.tnode = tnode
1082789Sktlim@umich.edu        self.snode = tnode.srcnode()
1092789Sktlim@umich.edu
1102789Sktlim@umich.edu        for base in type(self).__mro__:
1112789Sktlim@umich.edu            if issubclass(base, SourceFile):
1122789Sktlim@umich.edu                base.all.append(self)
1132789Sktlim@umich.edu
1142789Sktlim@umich.edu    @property
1152789Sktlim@umich.edu    def filename(self):
1162789Sktlim@umich.edu        return str(self.tnode)
1172789Sktlim@umich.edu
1182789Sktlim@umich.edu    @property
1192789Sktlim@umich.edu    def dirname(self):
1202789Sktlim@umich.edu        return dirname(self.filename)
1212789Sktlim@umich.edu
1222789Sktlim@umich.edu    @property
1232789Sktlim@umich.edu    def basename(self):
1242789Sktlim@umich.edu        return basename(self.filename)
1252789Sktlim@umich.edu
1262789Sktlim@umich.edu    @property
1272789Sktlim@umich.edu    def extname(self):
1282789Sktlim@umich.edu        index = self.basename.rfind('.')
1292789Sktlim@umich.edu        if index <= 0:
1302789Sktlim@umich.edu            # dot files aren't extensions
1312789Sktlim@umich.edu            return self.basename, None
1322789Sktlim@umich.edu
1332789Sktlim@umich.edu        return self.basename[:index], self.basename[index+1:]
1342789Sktlim@umich.edu
1352789Sktlim@umich.edu    @property
1362789Sktlim@umich.edu    def all_guards(self):
1372789Sktlim@umich.edu        '''find all guards for this object getting default values
1382789Sktlim@umich.edu        recursively from its parents'''
1395891Sgblack@eecs.umich.edu        guards = {}
1402789Sktlim@umich.edu        if self.parent:
1413349Sbinkertn@umich.edu            guards.update(self.parent.guards)
1422789Sktlim@umich.edu        guards.update(self.guards)
1432789Sktlim@umich.edu        return guards
1442789Sktlim@umich.edu
1453172Sstever@eecs.umich.edu    def __lt__(self, other): return self.filename < other.filename
1462789Sktlim@umich.edu    def __le__(self, other): return self.filename <= other.filename
1472789Sktlim@umich.edu    def __gt__(self, other): return self.filename > other.filename
1482789Sktlim@umich.edu    def __ge__(self, other): return self.filename >= other.filename
1492789Sktlim@umich.edu    def __eq__(self, other): return self.filename == other.filename
1502789Sktlim@umich.edu    def __ne__(self, other): return self.filename != other.filename
1512789Sktlim@umich.edu        
1522789Sktlim@umich.educlass Source(SourceFile):
1532789Sktlim@umich.edu    '''Add a c/c++ source file to the build'''
1542789Sktlim@umich.edu    def __init__(self, source, Werror=True, swig=False, **guards):
1552789Sktlim@umich.edu        '''specify the source file, and any guards'''
1562789Sktlim@umich.edu        super(Source, self).__init__(source, **guards)
1572789Sktlim@umich.edu
1582789Sktlim@umich.edu        self.Werror = Werror
1592789Sktlim@umich.edu        self.swig = swig
1602789Sktlim@umich.edu
1612789Sktlim@umich.educlass PySource(SourceFile):
1622789Sktlim@umich.edu    '''Add a python source file to the named package'''
1632789Sktlim@umich.edu    invalid_sym_char = re.compile('[^A-z0-9_]')
1642789Sktlim@umich.edu    modules = {}
1652789Sktlim@umich.edu    tnodes = {}
1662789Sktlim@umich.edu    symnames = {}
1672789Sktlim@umich.edu    
1682789Sktlim@umich.edu    def __init__(self, package, source, **guards):
1692789Sktlim@umich.edu        '''specify the python package, the source file, and any guards'''
1702789Sktlim@umich.edu        super(PySource, self).__init__(source, **guards)
1712789Sktlim@umich.edu
1722789Sktlim@umich.edu        modname,ext = self.extname
1732789Sktlim@umich.edu        assert ext == 'py'
1742789Sktlim@umich.edu
1752789Sktlim@umich.edu        if package:
1762789Sktlim@umich.edu            path = package.split('.')
1772789Sktlim@umich.edu        else:
1782789Sktlim@umich.edu            path = []
1792789Sktlim@umich.edu
1802789Sktlim@umich.edu        modpath = path[:]
1812789Sktlim@umich.edu        if modname != '__init__':
1822789Sktlim@umich.edu            modpath += [ modname ]
1832789Sktlim@umich.edu        modpath = '.'.join(modpath)
1842789Sktlim@umich.edu
1852789Sktlim@umich.edu        arcpath = path + [ self.basename ]
1862789Sktlim@umich.edu        abspath = self.snode.abspath
1872789Sktlim@umich.edu        if not exists(abspath):
1882789Sktlim@umich.edu            abspath = self.tnode.abspath
1892789Sktlim@umich.edu
1902789Sktlim@umich.edu        self.package = package
1912789Sktlim@umich.edu        self.modname = modname
1922789Sktlim@umich.edu        self.modpath = modpath
1932789Sktlim@umich.edu        self.arcname = joinpath(*arcpath)
1942789Sktlim@umich.edu        self.abspath = abspath
1952789Sktlim@umich.edu        self.compiled = File(self.filename + 'c')
1962789Sktlim@umich.edu        self.cpp = File(self.filename + '.cc')
1972789Sktlim@umich.edu        self.symname = PySource.invalid_sym_char.sub('_', modpath)
1982789Sktlim@umich.edu
1992789Sktlim@umich.edu        PySource.modules[modpath] = self
2002789Sktlim@umich.edu        PySource.tnodes[self.tnode] = self
2012789Sktlim@umich.edu        PySource.symnames[self.symname] = self
2022789Sktlim@umich.edu
2032789Sktlim@umich.educlass SimObject(PySource):
2042789Sktlim@umich.edu    '''Add a SimObject python file as a python source object and add
2052789Sktlim@umich.edu    it to a list of sim object modules'''
2062789Sktlim@umich.edu
2072789Sktlim@umich.edu    fixed = False
2082789Sktlim@umich.edu    modnames = []
2095891Sgblack@eecs.umich.edu
2102789Sktlim@umich.edu    def __init__(self, source, **guards):
2112789Sktlim@umich.edu        '''Specify the source file and any guards (automatically in
2122789Sktlim@umich.edu        the m5.objects package)'''
2132789Sktlim@umich.edu        super(SimObject, self).__init__('m5.objects', source, **guards)
2142789Sktlim@umich.edu        if self.fixed:
2152789Sktlim@umich.edu            raise AttributeError, "Too late to call SimObject now."
2162789Sktlim@umich.edu
2172789Sktlim@umich.edu        bisect.insort_right(SimObject.modnames, self.modname)
2182789Sktlim@umich.edu
2192789Sktlim@umich.educlass SwigSource(SourceFile):
2202789Sktlim@umich.edu    '''Add a swig file to build'''
2213172Sstever@eecs.umich.edu
2226102Sgblack@eecs.umich.edu    def __init__(self, package, source, **guards):
2236102Sgblack@eecs.umich.edu        '''Specify the python package, the source file, and any guards'''
2244052Ssaidi@eecs.umich.edu        super(SwigSource, self).__init__(source, **guards)
2252789Sktlim@umich.edu
2262789Sktlim@umich.edu        modname,ext = self.extname
2272789Sktlim@umich.edu        assert ext == 'i'
2283349Sbinkertn@umich.edu
2292789Sktlim@umich.edu        self.module = modname
2302789Sktlim@umich.edu        cc_file = joinpath(self.dirname, modname + '_wrap.cc')
2312789Sktlim@umich.edu        py_file = joinpath(self.dirname, modname + '.py')
2322789Sktlim@umich.edu
2332789Sktlim@umich.edu        self.cc_source = Source(cc_file, swig=True, parent=self)
2342789Sktlim@umich.edu        self.py_source = PySource(package, py_file, parent=self)
2352789Sktlim@umich.edu
2362789Sktlim@umich.educlass UnitTest(object):
2372789Sktlim@umich.edu    '''Create a UnitTest'''
2382789Sktlim@umich.edu
2392789Sktlim@umich.edu    all = []
2407823Ssteve.reinhardt@amd.com    def __init__(self, target, *sources):
2412789Sktlim@umich.edu        '''Specify the target name and any sources.  Sources that are
2422789Sktlim@umich.edu        not SourceFiles are evalued with Source().  All files are
2432789Sktlim@umich.edu        guarded with a guard of the same name as the UnitTest
2442789Sktlim@umich.edu        target.'''
2452789Sktlim@umich.edu
2462789Sktlim@umich.edu        srcs = []
2472789Sktlim@umich.edu        for src in sources:
2482789Sktlim@umich.edu            if not isinstance(src, SourceFile):
2494052Ssaidi@eecs.umich.edu                src = Source(src, skip_lib=True)
2502789Sktlim@umich.edu            src.guards[target] = True
2512789Sktlim@umich.edu            srcs.append(src)
2522789Sktlim@umich.edu
2532789Sktlim@umich.edu        self.sources = srcs
2542789Sktlim@umich.edu        self.target = target
2552789Sktlim@umich.edu        UnitTest.all.append(self)
2562789Sktlim@umich.edu
2572789Sktlim@umich.edu# Children should have access
2582789Sktlim@umich.eduExport('Source')
2592789Sktlim@umich.eduExport('PySource')
2602789Sktlim@umich.eduExport('SimObject')
2612789Sktlim@umich.eduExport('SwigSource')
2622789Sktlim@umich.eduExport('UnitTest')
2632789Sktlim@umich.edu
2642789Sktlim@umich.edu########################################################################
2652789Sktlim@umich.edu#
2662789Sktlim@umich.edu# Debug Flags
2672789Sktlim@umich.edu#
2682789Sktlim@umich.edudebug_flags = {}
2692789Sktlim@umich.edudef DebugFlag(name, desc=None):
2702789Sktlim@umich.edu    if name in debug_flags:
2712789Sktlim@umich.edu        raise AttributeError, "Flag %s already specified" % name
2722789Sktlim@umich.edu    debug_flags[name] = (name, (), desc)
2732789Sktlim@umich.edu
2742789Sktlim@umich.edudef CompoundFlag(name, flags, desc=None):
2752789Sktlim@umich.edu    if name in debug_flags:
2762789Sktlim@umich.edu        raise AttributeError, "Flag %s already specified" % name
2772789Sktlim@umich.edu
2782789Sktlim@umich.edu    compound = tuple(flags)
2792789Sktlim@umich.edu    debug_flags[name] = (name, compound, desc)
2802789Sktlim@umich.edu
2812789Sktlim@umich.eduExport('DebugFlag')
2822789Sktlim@umich.eduExport('CompoundFlag')
2832789Sktlim@umich.edu
2842789Sktlim@umich.edu########################################################################
2852789Sktlim@umich.edu#
2862789Sktlim@umich.edu# Set some compiler variables
2872789Sktlim@umich.edu#
2882789Sktlim@umich.edu
2892789Sktlim@umich.edu# Include file paths are rooted in this directory.  SCons will
2902789Sktlim@umich.edu# automatically expand '.' to refer to both the source directory and
2912789Sktlim@umich.edu# the corresponding build directory to pick up generated include
2922789Sktlim@umich.edu# files.
2932789Sktlim@umich.eduenv.Append(CPPPATH=Dir('.'))
2942789Sktlim@umich.edu
2952789Sktlim@umich.edufor extra_dir in extras_dir_list:
2962789Sktlim@umich.edu    env.Append(CPPPATH=Dir(extra_dir))
2972789Sktlim@umich.edu
2982789Sktlim@umich.edu# Workaround for bug in SCons version > 0.97d20071212
2992789Sktlim@umich.edu# Scons bug id: 2006 gem5 Bug id: 308
3002789Sktlim@umich.edufor root, dirs, files in os.walk(base_dir, topdown=True):
3012789Sktlim@umich.edu    Dir(root[len(base_dir) + 1:])
3022789Sktlim@umich.edu
3032789Sktlim@umich.edu########################################################################
3042789Sktlim@umich.edu#
3052789Sktlim@umich.edu# Walk the tree and execute all SConscripts in subdirectories
3062789Sktlim@umich.edu#
3076739Sgblack@eecs.umich.edu
3082789Sktlim@umich.eduhere = Dir('.').srcnode().abspath
3092789Sktlim@umich.edufor root, dirs, files in os.walk(base_dir, topdown=True):
3102789Sktlim@umich.edu    if root == here:
3112789Sktlim@umich.edu        # we don't want to recurse back into this SConscript
3122789Sktlim@umich.edu        continue
3132789Sktlim@umich.edu
3142789Sktlim@umich.edu    if 'SConscript' in files:
3152789Sktlim@umich.edu        build_dir = joinpath(env['BUILDDIR'], root[len(base_dir) + 1:])
3162789Sktlim@umich.edu        SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3172789Sktlim@umich.edu
3182789Sktlim@umich.edufor extra_dir in extras_dir_list:
3192789Sktlim@umich.edu    prefix_len = len(dirname(extra_dir)) + 1
3207823Ssteve.reinhardt@amd.com    for root, dirs, files in os.walk(extra_dir, topdown=True):
3212789Sktlim@umich.edu        # if build lives in the extras directory, don't walk down it
3222789Sktlim@umich.edu        if 'build' in dirs:
323            dirs.remove('build')
324
325        if 'SConscript' in files:
326            build_dir = joinpath(env['BUILDDIR'], root[prefix_len:])
327            SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
328
329for opt in export_vars:
330    env.ConfigFile(opt)
331
332def makeTheISA(source, target, env):
333    isas = [ src.get_contents() for src in source ]
334    target_isa = env['TARGET_ISA']
335    def define(isa):
336        return isa.upper() + '_ISA'
337    
338    def namespace(isa):
339        return isa[0].upper() + isa[1:].lower() + 'ISA' 
340
341
342    code = code_formatter()
343    code('''\
344#ifndef __CONFIG_THE_ISA_HH__
345#define __CONFIG_THE_ISA_HH__
346
347''')
348
349    for i,isa in enumerate(isas):
350        code('#define $0 $1', define(isa), i + 1)
351
352    code('''
353
354#define THE_ISA ${{define(target_isa)}}
355#define TheISA ${{namespace(target_isa)}}
356
357#endif // __CONFIG_THE_ISA_HH__''')
358
359    code.write(str(target[0]))
360
361env.Command('config/the_isa.hh', map(Value, all_isa_list),
362            MakeAction(makeTheISA, Transform("CFG ISA", 0)))
363
364########################################################################
365#
366# Prevent any SimObjects from being added after this point, they
367# should all have been added in the SConscripts above
368#
369SimObject.fixed = True
370
371class DictImporter(object):
372    '''This importer takes a dictionary of arbitrary module names that
373    map to arbitrary filenames.'''
374    def __init__(self, modules):
375        self.modules = modules
376        self.installed = set()
377
378    def __del__(self):
379        self.unload()
380
381    def unload(self):
382        import sys
383        for module in self.installed:
384            del sys.modules[module]
385        self.installed = set()
386
387    def find_module(self, fullname, path):
388        if fullname == 'm5.defines':
389            return self
390
391        if fullname == 'm5.objects':
392            return self
393
394        if fullname.startswith('m5.internal'):
395            return None
396
397        source = self.modules.get(fullname, None)
398        if source is not None and fullname.startswith('m5.objects'):
399            return self
400
401        return None
402
403    def load_module(self, fullname):
404        mod = imp.new_module(fullname)
405        sys.modules[fullname] = mod
406        self.installed.add(fullname)
407
408        mod.__loader__ = self
409        if fullname == 'm5.objects':
410            mod.__path__ = fullname.split('.')
411            return mod
412
413        if fullname == 'm5.defines':
414            mod.__dict__['buildEnv'] = m5.util.SmartDict(build_env)
415            return mod
416
417        source = self.modules[fullname]
418        if source.modname == '__init__':
419            mod.__path__ = source.modpath
420        mod.__file__ = source.abspath
421
422        exec file(source.abspath, 'r') in mod.__dict__
423
424        return mod
425
426import m5.SimObject
427import m5.params
428from m5.util import code_formatter
429
430m5.SimObject.clear()
431m5.params.clear()
432
433# install the python importer so we can grab stuff from the source
434# tree itself.  We can't have SimObjects added after this point or
435# else we won't know about them for the rest of the stuff.
436importer = DictImporter(PySource.modules)
437sys.meta_path[0:0] = [ importer ]
438
439# import all sim objects so we can populate the all_objects list
440# make sure that we're working with a list, then let's sort it
441for modname in SimObject.modnames:
442    exec('from m5.objects import %s' % modname)
443
444# we need to unload all of the currently imported modules so that they
445# will be re-imported the next time the sconscript is run
446importer.unload()
447sys.meta_path.remove(importer)
448
449sim_objects = m5.SimObject.allClasses
450all_enums = m5.params.allEnums
451
452# Find param types that need to be explicitly wrapped with swig.
453# These will be recognized because the ParamDesc will have a
454# swig_decl() method.  Most param types are based on types that don't
455# need this, either because they're based on native types (like Int)
456# or because they're SimObjects (which get swigged independently).
457# For now the only things handled here are VectorParam types.
458params_to_swig = {}
459for name,obj in sorted(sim_objects.iteritems()):
460    for param in obj._params.local.values():
461        # load the ptype attribute now because it depends on the
462        # current version of SimObject.allClasses, but when scons
463        # actually uses the value, all versions of
464        # SimObject.allClasses will have been loaded
465        param.ptype
466
467        if not hasattr(param, 'swig_decl'):
468            continue
469        pname = param.ptype_str
470        if pname not in params_to_swig:
471            params_to_swig[pname] = param
472
473########################################################################
474#
475# calculate extra dependencies
476#
477module_depends = ["m5", "m5.SimObject", "m5.params"]
478depends = [ PySource.modules[dep].snode for dep in module_depends ]
479
480########################################################################
481#
482# Commands for the basic automatically generated python files
483#
484
485# Generate Python file containing a dict specifying the current
486# buildEnv flags.
487def makeDefinesPyFile(target, source, env):
488    build_env = source[0].get_contents()
489
490    code = code_formatter()
491    code("""
492import m5.internal
493import m5.util
494
495buildEnv = m5.util.SmartDict($build_env)
496
497compileDate = m5.internal.core.compileDate
498_globals = globals()
499for key,val in m5.internal.core.__dict__.iteritems():
500    if key.startswith('flag_'):
501        flag = key[5:]
502        _globals[flag] = val
503del _globals
504""")
505    code.write(target[0].abspath)
506
507defines_info = Value(build_env)
508# Generate a file with all of the compile options in it
509env.Command('python/m5/defines.py', defines_info,
510            MakeAction(makeDefinesPyFile, Transform("DEFINES", 0)))
511PySource('m5', 'python/m5/defines.py')
512
513# Generate python file containing info about the M5 source code
514def makeInfoPyFile(target, source, env):
515    code = code_formatter()
516    for src in source:
517        data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
518        code('$src = ${{repr(data)}}')
519    code.write(str(target[0]))
520
521# Generate a file that wraps the basic top level files
522env.Command('python/m5/info.py',
523            [ '#/COPYING', '#/LICENSE', '#/README', ],
524            MakeAction(makeInfoPyFile, Transform("INFO")))
525PySource('m5', 'python/m5/info.py')
526
527########################################################################
528#
529# Create all of the SimObject param headers and enum headers
530#
531
532def createSimObjectParamStruct(target, source, env):
533    assert len(target) == 1 and len(source) == 1
534
535    name = str(source[0].get_contents())
536    obj = sim_objects[name]
537
538    code = code_formatter()
539    obj.cxx_param_decl(code)
540    code.write(target[0].abspath)
541
542def createParamSwigWrapper(target, source, env):
543    assert len(target) == 1 and len(source) == 1
544
545    name = str(source[0].get_contents())
546    param = params_to_swig[name]
547
548    code = code_formatter()
549    param.swig_decl(code)
550    code.write(target[0].abspath)
551
552def createEnumStrings(target, source, env):
553    assert len(target) == 1 and len(source) == 1
554
555    name = str(source[0].get_contents())
556    obj = all_enums[name]
557
558    code = code_formatter()
559    obj.cxx_def(code)
560    code.write(target[0].abspath)
561
562def createEnumDecls(target, source, env):
563    assert len(target) == 1 and len(source) == 1
564
565    name = str(source[0].get_contents())
566    obj = all_enums[name]
567
568    code = code_formatter()
569    obj.cxx_decl(code)
570    code.write(target[0].abspath)
571
572def createEnumSwigWrapper(target, source, env):
573    assert len(target) == 1 and len(source) == 1
574
575    name = str(source[0].get_contents())
576    obj = all_enums[name]
577
578    code = code_formatter()
579    obj.swig_decl(code)
580    code.write(target[0].abspath)
581
582def createSimObjectSwigWrapper(target, source, env):
583    name = source[0].get_contents()
584    obj = sim_objects[name]
585
586    code = code_formatter()
587    obj.swig_decl(code)
588    code.write(target[0].abspath)
589
590# Generate all of the SimObject param C++ struct header files
591params_hh_files = []
592for name,simobj in sorted(sim_objects.iteritems()):
593    py_source = PySource.modules[simobj.__module__]
594    extra_deps = [ py_source.tnode ]
595
596    hh_file = File('params/%s.hh' % name)
597    params_hh_files.append(hh_file)
598    env.Command(hh_file, Value(name),
599                MakeAction(createSimObjectParamStruct, Transform("SO PARAM")))
600    env.Depends(hh_file, depends + extra_deps)
601
602# Generate any needed param SWIG wrapper files
603params_i_files = []
604for name,param in params_to_swig.iteritems():
605    i_file = File('python/m5/internal/%s.i' % (param.swig_module_name()))
606    params_i_files.append(i_file)
607    env.Command(i_file, Value(name),
608                MakeAction(createParamSwigWrapper, Transform("SW PARAM")))
609    env.Depends(i_file, depends)
610    SwigSource('m5.internal', i_file)
611
612# Generate all enum header files
613for name,enum in sorted(all_enums.iteritems()):
614    py_source = PySource.modules[enum.__module__]
615    extra_deps = [ py_source.tnode ]
616
617    cc_file = File('enums/%s.cc' % name)
618    env.Command(cc_file, Value(name),
619                MakeAction(createEnumStrings, Transform("ENUM STR")))
620    env.Depends(cc_file, depends + extra_deps)
621    Source(cc_file)
622
623    hh_file = File('enums/%s.hh' % name)
624    env.Command(hh_file, Value(name),
625                MakeAction(createEnumDecls, Transform("ENUMDECL")))
626    env.Depends(hh_file, depends + extra_deps)
627
628    i_file = File('python/m5/internal/enum_%s.i' % name)
629    env.Command(i_file, Value(name),
630                MakeAction(createEnumSwigWrapper, Transform("ENUMSWIG")))
631    env.Depends(i_file, depends + extra_deps)
632    SwigSource('m5.internal', i_file)
633
634# Generate SimObject SWIG wrapper files
635for name in sim_objects.iterkeys():
636    i_file = File('python/m5/internal/param_%s.i' % name)
637    env.Command(i_file, Value(name),
638                MakeAction(createSimObjectSwigWrapper, Transform("SO SWIG")))
639    env.Depends(i_file, depends)
640    SwigSource('m5.internal', i_file)
641
642# Generate the main swig init file
643def makeEmbeddedSwigInit(target, source, env):
644    code = code_formatter()
645    module = source[0].get_contents()
646    code('''\
647#include "sim/init.hh"
648
649extern "C" {
650    void init_${module}();
651}
652
653EmbeddedSwig embed_swig_${module}(init_${module});
654''')
655    code.write(str(target[0]))
656    
657# Build all swig modules
658for swig in SwigSource.all:
659    env.Command([swig.cc_source.tnode, swig.py_source.tnode], swig.tnode,
660                MakeAction('$SWIG $SWIGFLAGS -outdir ${TARGETS[1].dir} '
661                '-o ${TARGETS[0]} $SOURCES', Transform("SWIG")))
662    cc_file = str(swig.tnode)
663    init_file = '%s/%s_init.cc' % (dirname(cc_file), basename(cc_file))
664    env.Command(init_file, Value(swig.module),
665                MakeAction(makeEmbeddedSwigInit, Transform("EMBED SW")))
666    Source(init_file, **swig.guards)
667
668#
669# Handle debug flags
670#
671def makeDebugFlagCC(target, source, env):
672    assert(len(target) == 1 and len(source) == 1)
673
674    val = eval(source[0].get_contents())
675    name, compound, desc = val
676    compound = list(sorted(compound))
677
678    code = code_formatter()
679
680    # file header
681    code('''
682/*
683 * DO NOT EDIT THIS FILE! Automatically generated
684 */
685
686#include "base/debug.hh"
687''')
688
689    for flag in compound:
690        code('#include "debug/$flag.hh"')
691    code()
692    code('namespace Debug {')
693    code()
694
695    if not compound:
696        code('SimpleFlag $name("$name", "$desc");')
697    else:
698        code('CompoundFlag $name("$name", "$desc",')
699        code.indent()
700        last = len(compound) - 1
701        for i,flag in enumerate(compound):
702            if i != last:
703                code('$flag,')
704            else:
705                code('$flag);')
706        code.dedent()
707
708    code()
709    code('} // namespace Debug')
710
711    code.write(str(target[0]))
712
713def makeDebugFlagHH(target, source, env):
714    assert(len(target) == 1 and len(source) == 1)
715
716    val = eval(source[0].get_contents())
717    name, compound, desc = val
718
719    code = code_formatter()
720
721    # file header boilerplate
722    code('''\
723/*
724 * DO NOT EDIT THIS FILE!
725 *
726 * Automatically generated by SCons
727 */
728
729#ifndef __DEBUG_${name}_HH__
730#define __DEBUG_${name}_HH__
731
732namespace Debug {
733''')
734
735    if compound:
736        code('class CompoundFlag;')
737    code('class SimpleFlag;')
738
739    if compound:
740        code('extern CompoundFlag $name;')
741        for flag in compound:
742            code('extern SimpleFlag $flag;')
743    else:
744        code('extern SimpleFlag $name;')
745
746    code('''
747}
748
749#endif // __DEBUG_${name}_HH__
750''')
751
752    code.write(str(target[0]))
753
754for name,flag in sorted(debug_flags.iteritems()):
755    n, compound, desc = flag
756    assert n == name
757
758    env.Command('debug/%s.hh' % name, Value(flag),
759                MakeAction(makeDebugFlagHH, Transform("TRACING", 0)))
760    env.Command('debug/%s.cc' % name, Value(flag),
761                MakeAction(makeDebugFlagCC, Transform("TRACING", 0)))
762    Source('debug/%s.cc' % name)
763
764# Embed python files.  All .py files that have been indicated by a
765# PySource() call in a SConscript need to be embedded into the M5
766# library.  To do that, we compile the file to byte code, marshal the
767# byte code, compress it, and then generate a c++ file that
768# inserts the result into an array.
769def embedPyFile(target, source, env):
770    def c_str(string):
771        if string is None:
772            return "0"
773        return '"%s"' % string
774
775    '''Action function to compile a .py into a code object, marshal
776    it, compress it, and stick it into an asm file so the code appears
777    as just bytes with a label in the data section'''
778
779    src = file(str(source[0]), 'r').read()
780
781    pysource = PySource.tnodes[source[0]]
782    compiled = compile(src, pysource.abspath, 'exec')
783    marshalled = marshal.dumps(compiled)
784    compressed = zlib.compress(marshalled)
785    data = compressed
786    sym = pysource.symname
787
788    code = code_formatter()
789    code('''\
790#include "sim/init.hh"
791
792namespace {
793
794const char data_${sym}[] = {
795''')
796    code.indent()
797    step = 16
798    for i in xrange(0, len(data), step):
799        x = array.array('B', data[i:i+step])
800        code(''.join('%d,' % d for d in x))
801    code.dedent()
802    
803    code('''};
804
805EmbeddedPython embedded_${sym}(
806    ${{c_str(pysource.arcname)}},
807    ${{c_str(pysource.abspath)}},
808    ${{c_str(pysource.modpath)}},
809    data_${sym},
810    ${{len(data)}},
811    ${{len(marshalled)}});
812
813} // anonymous namespace
814''')
815    code.write(str(target[0]))
816
817for source in PySource.all:
818    env.Command(source.cpp, source.tnode, 
819                MakeAction(embedPyFile, Transform("EMBED PY")))
820    Source(source.cpp)
821
822########################################################################
823#
824# Define binaries.  Each different build type (debug, opt, etc.) gets
825# a slightly different build environment.
826#
827
828# List of constructed environments to pass back to SConstruct
829envList = []
830
831date_source = Source('base/date.cc', skip_lib=True)
832
833# Function to create a new build environment as clone of current
834# environment 'env' with modified object suffix and optional stripped
835# binary.  Additional keyword arguments are appended to corresponding
836# build environment vars.
837def makeEnv(label, objsfx, strip = False, **kwargs):
838    # SCons doesn't know to append a library suffix when there is a '.' in the
839    # name.  Use '_' instead.
840    libname = 'gem5_' + label
841    exename = 'gem5.' + label
842    secondary_exename = 'm5.' + label
843
844    new_env = env.Clone(OBJSUFFIX=objsfx, SHOBJSUFFIX=objsfx + 's')
845    new_env.Label = label
846    new_env.Append(**kwargs)
847
848    swig_env = new_env.Clone()
849    swig_env.Append(CCFLAGS='-Werror')
850    if env['GCC']:
851        swig_env.Append(CCFLAGS='-Wno-uninitialized')
852        swig_env.Append(CCFLAGS='-Wno-sign-compare')
853        swig_env.Append(CCFLAGS='-Wno-parentheses')
854        swig_env.Append(CCFLAGS='-Wno-unused-label')
855        if compareVersions(env['GCC_VERSION'], '4.6.0') != -1:
856            swig_env.Append(CCFLAGS='-Wno-unused-but-set-variable')
857    if env['CLANG']:
858        swig_env.Append(CCFLAGS=['-Wno-unused-label'])
859
860
861    werror_env = new_env.Clone()
862    werror_env.Append(CCFLAGS='-Werror')
863
864    def make_obj(source, static, extra_deps = None):
865        '''This function adds the specified source to the correct
866        build environment, and returns the corresponding SCons Object
867        nodes'''
868
869        if source.swig:
870            env = swig_env
871        elif source.Werror:
872            env = werror_env
873        else:
874            env = new_env
875
876        if static:
877            obj = env.StaticObject(source.tnode)
878        else:
879            obj = env.SharedObject(source.tnode)
880
881        if extra_deps:
882            env.Depends(obj, extra_deps)
883
884        return obj
885
886    static_objs = \
887        [ make_obj(s, True) for s in Source.get(main=False, skip_lib=False) ]
888    shared_objs = \
889        [ make_obj(s, False) for s in Source.get(main=False, skip_lib=False) ]
890
891    static_date = make_obj(date_source, static=True, extra_deps=static_objs)
892    static_objs.append(static_date)
893    
894    shared_date = make_obj(date_source, static=False, extra_deps=shared_objs)
895    shared_objs.append(shared_date)
896
897    # First make a library of everything but main() so other programs can
898    # link against m5.
899    static_lib = new_env.StaticLibrary(libname, static_objs)
900    shared_lib = new_env.SharedLibrary(libname, shared_objs)
901
902    # Now link a stub with main() and the static library.
903    main_objs = [ make_obj(s, True) for s in Source.get(main=True) ]
904
905    for test in UnitTest.all:
906        flags = { test.target : True }
907        test_sources = Source.get(**flags)
908        test_objs = [ make_obj(s, static=True) for s in test_sources ]
909        testname = "unittest/%s.%s" % (test.target, label)
910        new_env.Program(testname, main_objs + test_objs + static_objs)
911
912    progname = exename
913    if strip:
914        progname += '.unstripped'
915
916    targets = new_env.Program(progname, main_objs + static_objs)
917
918    if strip:
919        if sys.platform == 'sunos5':
920            cmd = 'cp $SOURCE $TARGET; strip $TARGET'
921        else:
922            cmd = 'strip $SOURCE -o $TARGET'
923        targets = new_env.Command(exename, progname,
924                    MakeAction(cmd, Transform("STRIP")))
925
926    new_env.Command(secondary_exename, exename,
927            MakeAction('ln $SOURCE $TARGET', Transform("HARDLINK")))
928
929    new_env.M5Binary = targets[0]
930    envList.append(new_env)
931
932# Debug binary
933ccflags = {}
934if env['GCC'] or env['CLANG']:
935    if sys.platform == 'sunos5':
936        ccflags['debug'] = '-gstabs+'
937    else:
938        ccflags['debug'] = '-ggdb3'
939    ccflags['opt'] = '-g -O3'
940    ccflags['fast'] = '-O3'
941    ccflags['prof'] = '-O3 -g -pg'
942elif env['SUNCC']:
943    ccflags['debug'] = '-g0'
944    ccflags['opt'] = '-g -O'
945    ccflags['fast'] = '-fast'
946    ccflags['prof'] = '-fast -g -pg'
947elif env['ICC']:
948    ccflags['debug'] = '-g -O0'
949    ccflags['opt'] = '-g -O'
950    ccflags['fast'] = '-fast'
951    ccflags['prof'] = '-fast -g -pg'
952else:
953    print 'Unknown compiler, please fix compiler options'
954    Exit(1)
955
956
957# To speed things up, we only instantiate the build environments we
958# need.  We try to identify the needed environment for each target; if
959# we can't, we fall back on instantiating all the environments just to
960# be safe.
961target_types = ['debug', 'opt', 'fast', 'prof']
962obj2target = {'do': 'debug', 'o': 'opt', 'fo': 'fast', 'po': 'prof'}
963
964def identifyTarget(t):
965    ext = t.split('.')[-1]
966    if ext in target_types:
967        return ext
968    if obj2target.has_key(ext):
969        return obj2target[ext]
970    match = re.search(r'/tests/([^/]+)/', t)
971    if match and match.group(1) in target_types:
972        return match.group(1)
973    return 'all'
974
975needed_envs = [identifyTarget(target) for target in BUILD_TARGETS]
976if 'all' in needed_envs:
977    needed_envs += target_types
978
979# Debug binary
980if 'debug' in needed_envs:
981    makeEnv('debug', '.do',
982            CCFLAGS = Split(ccflags['debug']),
983            CPPDEFINES = ['DEBUG', 'TRACING_ON=1'])
984
985# Optimized binary
986if 'opt' in needed_envs:
987    makeEnv('opt', '.o',
988            CCFLAGS = Split(ccflags['opt']),
989            CPPDEFINES = ['TRACING_ON=1'])
990
991# "Fast" binary
992if 'fast' in needed_envs:
993    makeEnv('fast', '.fo', strip = True,
994            CCFLAGS = Split(ccflags['fast']),
995            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'])
996
997# Profiled binary
998if 'prof' in needed_envs:
999    makeEnv('prof', '.po',
1000            CCFLAGS = Split(ccflags['prof']),
1001            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1002            LINKFLAGS = '-pg')
1003
1004Return('envList')
1005