SConscript revision 9175:8083b5195207
1955SN/A# -*- mode:python -*-
2955SN/A
31762SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
4955SN/A# All rights reserved.
5955SN/A#
6955SN/A# Redistribution and use in source and binary forms, with or without
7955SN/A# modification, are permitted provided that the following conditions are
8955SN/A# met: redistributions of source code must retain the above copyright
9955SN/A# notice, this list of conditions and the following disclaimer;
10955SN/A# redistributions in binary form must reproduce the above copyright
11955SN/A# notice, this list of conditions and the following disclaimer in the
12955SN/A# documentation and/or other materials provided with the distribution;
13955SN/A# neither the name of the copyright holders nor the names of its
14955SN/A# contributors may be used to endorse or promote products derived from
15955SN/A# this software without specific prior written permission.
16955SN/A#
17955SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18955SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22955SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23955SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24955SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26955SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27955SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28955SN/A#
29955SN/A# Authors: Nathan Binkert
30955SN/A
31955SN/Aimport array
32955SN/Aimport bisect
332632Sstever@eecs.umich.eduimport imp
342632Sstever@eecs.umich.eduimport marshal
352632Sstever@eecs.umich.eduimport os
362632Sstever@eecs.umich.eduimport re
37955SN/Aimport sys
382632Sstever@eecs.umich.eduimport zlib
392632Sstever@eecs.umich.edu
402632Sstever@eecs.umich.edufrom os.path import basename, dirname, exists, isdir, isfile, join as joinpath
412632Sstever@eecs.umich.edu
422632Sstever@eecs.umich.eduimport SCons
432632Sstever@eecs.umich.edu
442632Sstever@eecs.umich.edu# This file defines how to build a particular configuration of gem5
452632Sstever@eecs.umich.edu# based on variable settings in the 'env' build environment.
462632Sstever@eecs.umich.edu
472632Sstever@eecs.umich.eduImport('*')
482632Sstever@eecs.umich.edu
492632Sstever@eecs.umich.edu# Children need to see the environment
502632Sstever@eecs.umich.eduExport('env')
512632Sstever@eecs.umich.edu
522632Sstever@eecs.umich.edubuild_env = [(opt, env[opt]) for opt in export_vars]
532632Sstever@eecs.umich.edu
542632Sstever@eecs.umich.edufrom m5.util import code_formatter, compareVersions
552632Sstever@eecs.umich.edu
562632Sstever@eecs.umich.edu########################################################################
572632Sstever@eecs.umich.edu# Code for adding source files of various types
58955SN/A#
59955SN/A# When specifying a source file of some type, a set of guards can be
60955SN/A# specified for that file.  When get() is used to find the files, if
61955SN/A# get specifies a set of filters, only files that match those filters
62955SN/A# will be accepted (unspecified filters on files are assumed to be
63955SN/A# false).  Current filters are:
64955SN/A#     main -- specifies the gem5 main() function
651858SN/A#     skip_lib -- do not put this file into the gem5 library
661858SN/A#     <unittest> -- unit tests use filters based on the unit test name
672653Sstever@eecs.umich.edu#
682653Sstever@eecs.umich.edu# A parent can now be specified for a source file and default filter
692653Sstever@eecs.umich.edu# values will be retrieved recursively from parents (children override
702653Sstever@eecs.umich.edu# parents).
712653Sstever@eecs.umich.edu#
722653Sstever@eecs.umich.educlass SourceMeta(type):
732653Sstever@eecs.umich.edu    '''Meta class for source files that keeps track of all files of a
742653Sstever@eecs.umich.edu    particular type and has a get function for finding all functions
752653Sstever@eecs.umich.edu    of a certain type that match a set of guards'''
762653Sstever@eecs.umich.edu    def __init__(cls, name, bases, dict):
772653Sstever@eecs.umich.edu        super(SourceMeta, cls).__init__(name, bases, dict)
781852SN/A        cls.all = []
79955SN/A        
80955SN/A    def get(cls, **guards):
81955SN/A        '''Find all files that match the specified guards.  If a source
822632Sstever@eecs.umich.edu        file does not specify a flag, the default is False'''
832632Sstever@eecs.umich.edu        for src in cls.all:
84955SN/A            for flag,value in guards.iteritems():
851533SN/A                # if the flag is found and has a different value, skip
862632Sstever@eecs.umich.edu                # this file
871533SN/A                if src.all_guards.get(flag, False) != value:
88955SN/A                    break
89955SN/A            else:
902632Sstever@eecs.umich.edu                yield src
912632Sstever@eecs.umich.edu
92955SN/Aclass SourceFile(object):
93955SN/A    '''Base object that encapsulates the notion of a source file.
94955SN/A    This includes, the source node, target node, various manipulations
95955SN/A    of those.  A source file also specifies a set of guards which
962632Sstever@eecs.umich.edu    describing which builds the source file applies to.  A parent can
97955SN/A    also be specified to get default guards from'''
982632Sstever@eecs.umich.edu    __metaclass__ = SourceMeta
99955SN/A    def __init__(self, source, parent=None, **guards):
100955SN/A        self.guards = guards
1012632Sstever@eecs.umich.edu        self.parent = parent
1022632Sstever@eecs.umich.edu
1032632Sstever@eecs.umich.edu        tnode = source
1042632Sstever@eecs.umich.edu        if not isinstance(source, SCons.Node.FS.File):
1052632Sstever@eecs.umich.edu            tnode = File(source)
1062632Sstever@eecs.umich.edu
1072632Sstever@eecs.umich.edu        self.tnode = tnode
1082632Sstever@eecs.umich.edu        self.snode = tnode.srcnode()
1092632Sstever@eecs.umich.edu
1102632Sstever@eecs.umich.edu        for base in type(self).__mro__:
1112632Sstever@eecs.umich.edu            if issubclass(base, SourceFile):
1122632Sstever@eecs.umich.edu                base.all.append(self)
1132632Sstever@eecs.umich.edu
1142632Sstever@eecs.umich.edu    @property
1152632Sstever@eecs.umich.edu    def filename(self):
1162632Sstever@eecs.umich.edu        return str(self.tnode)
1172632Sstever@eecs.umich.edu
1182634Sstever@eecs.umich.edu    @property
1192634Sstever@eecs.umich.edu    def dirname(self):
1202632Sstever@eecs.umich.edu        return dirname(self.filename)
1212638Sstever@eecs.umich.edu
1222632Sstever@eecs.umich.edu    @property
1232632Sstever@eecs.umich.edu    def basename(self):
1242632Sstever@eecs.umich.edu        return basename(self.filename)
1252632Sstever@eecs.umich.edu
1262632Sstever@eecs.umich.edu    @property
1272632Sstever@eecs.umich.edu    def extname(self):
1281858SN/A        index = self.basename.rfind('.')
1292638Sstever@eecs.umich.edu        if index <= 0:
1302638Sstever@eecs.umich.edu            # dot files aren't extensions
1312638Sstever@eecs.umich.edu            return self.basename, None
1322638Sstever@eecs.umich.edu
1332638Sstever@eecs.umich.edu        return self.basename[:index], self.basename[index+1:]
1342638Sstever@eecs.umich.edu
1352638Sstever@eecs.umich.edu    @property
1362638Sstever@eecs.umich.edu    def all_guards(self):
1372634Sstever@eecs.umich.edu        '''find all guards for this object getting default values
1382634Sstever@eecs.umich.edu        recursively from its parents'''
1392634Sstever@eecs.umich.edu        guards = {}
140955SN/A        if self.parent:
141955SN/A            guards.update(self.parent.guards)
142955SN/A        guards.update(self.guards)
143955SN/A        return guards
144955SN/A
145955SN/A    def __lt__(self, other): return self.filename < other.filename
146955SN/A    def __le__(self, other): return self.filename <= other.filename
147955SN/A    def __gt__(self, other): return self.filename > other.filename
1481858SN/A    def __ge__(self, other): return self.filename >= other.filename
1491858SN/A    def __eq__(self, other): return self.filename == other.filename
1502632Sstever@eecs.umich.edu    def __ne__(self, other): return self.filename != other.filename
151955SN/A        
1521858SN/Aclass Source(SourceFile):
1531105SN/A    '''Add a c/c++ source file to the build'''
1541869SN/A    def __init__(self, source, Werror=True, swig=False, **guards):
1551869SN/A        '''specify the source file, and any guards'''
1561869SN/A        super(Source, self).__init__(source, **guards)
1571869SN/A
1581869SN/A        self.Werror = Werror
1591065SN/A        self.swig = swig
1602632Sstever@eecs.umich.edu
1612632Sstever@eecs.umich.educlass PySource(SourceFile):
162955SN/A    '''Add a python source file to the named package'''
1631858SN/A    invalid_sym_char = re.compile('[^A-z0-9_]')
1641858SN/A    modules = {}
1651858SN/A    tnodes = {}
1661858SN/A    symnames = {}
1671851SN/A    
1681851SN/A    def __init__(self, package, source, **guards):
1691858SN/A        '''specify the python package, the source file, and any guards'''
1702632Sstever@eecs.umich.edu        super(PySource, self).__init__(source, **guards)
171955SN/A
1722655Sstever@eecs.umich.edu        modname,ext = self.extname
1732655Sstever@eecs.umich.edu        assert ext == 'py'
1742655Sstever@eecs.umich.edu
1752655Sstever@eecs.umich.edu        if package:
1762655Sstever@eecs.umich.edu            path = package.split('.')
1772655Sstever@eecs.umich.edu        else:
1782655Sstever@eecs.umich.edu            path = []
1791858SN/A
1801858SN/A        modpath = path[:]
1812638Sstever@eecs.umich.edu        if modname != '__init__':
1822638Sstever@eecs.umich.edu            modpath += [ modname ]
1832638Sstever@eecs.umich.edu        modpath = '.'.join(modpath)
1842638Sstever@eecs.umich.edu
1852638Sstever@eecs.umich.edu        arcpath = path + [ self.basename ]
1861858SN/A        abspath = self.snode.abspath
1871858SN/A        if not exists(abspath):
1881858SN/A            abspath = self.tnode.abspath
1891858SN/A
1901858SN/A        self.package = package
1911858SN/A        self.modname = modname
1921858SN/A        self.modpath = modpath
1931859SN/A        self.arcname = joinpath(*arcpath)
1941858SN/A        self.abspath = abspath
1951858SN/A        self.compiled = File(self.filename + 'c')
1961858SN/A        self.cpp = File(self.filename + '.cc')
1971859SN/A        self.symname = PySource.invalid_sym_char.sub('_', modpath)
1981859SN/A
1991862SN/A        PySource.modules[modpath] = self
2001862SN/A        PySource.tnodes[self.tnode] = self
2011862SN/A        PySource.symnames[self.symname] = self
2021862SN/A
2031859SN/Aclass SimObject(PySource):
2041859SN/A    '''Add a SimObject python file as a python source object and add
2051963SN/A    it to a list of sim object modules'''
2061963SN/A
2071859SN/A    fixed = False
2081859SN/A    modnames = []
2091859SN/A
2101859SN/A    def __init__(self, source, **guards):
2111859SN/A        '''Specify the source file and any guards (automatically in
2121859SN/A        the m5.objects package)'''
2131859SN/A        super(SimObject, self).__init__('m5.objects', source, **guards)
2141859SN/A        if self.fixed:
2151862SN/A            raise AttributeError, "Too late to call SimObject now."
2161859SN/A
2171859SN/A        bisect.insort_right(SimObject.modnames, self.modname)
2181859SN/A
2191858SN/Aclass SwigSource(SourceFile):
2201858SN/A    '''Add a swig file to build'''
2212139SN/A
2222139SN/A    def __init__(self, package, source, **guards):
2232139SN/A        '''Specify the python package, the source file, and any guards'''
2242155SN/A        super(SwigSource, self).__init__(source, **guards)
2252623SN/A
2262637Sstever@eecs.umich.edu        modname,ext = self.extname
2272155SN/A        assert ext == 'i'
2281869SN/A
2291869SN/A        self.module = modname
2301869SN/A        cc_file = joinpath(self.dirname, modname + '_wrap.cc')
2311869SN/A        py_file = joinpath(self.dirname, modname + '.py')
2321869SN/A
2332139SN/A        self.cc_source = Source(cc_file, swig=True, parent=self)
2341869SN/A        self.py_source = PySource(package, py_file, parent=self)
2352508SN/A
2362508SN/Aclass UnitTest(object):
2372508SN/A    '''Create a UnitTest'''
2382508SN/A
2392635Sstever@eecs.umich.edu    all = []
2402635Sstever@eecs.umich.edu    def __init__(self, target, *sources, **kwargs):
2411869SN/A        '''Specify the target name and any sources.  Sources that are
2421869SN/A        not SourceFiles are evalued with Source().  All files are
2431869SN/A        guarded with a guard of the same name as the UnitTest
2441869SN/A        target.'''
2451869SN/A
2461869SN/A        srcs = []
2471869SN/A        for src in sources:
2481869SN/A            if not isinstance(src, SourceFile):
2491965SN/A                src = Source(src, skip_lib=True)
2501965SN/A            src.guards[target] = True
2511965SN/A            srcs.append(src)
2521869SN/A
2531869SN/A        self.sources = srcs
2541869SN/A        self.target = target
2551869SN/A        self.main = kwargs.get('main', False)
2561884SN/A        UnitTest.all.append(self)
2571884SN/A
2581884SN/A# Children should have access
2591869SN/AExport('Source')
2601858SN/AExport('PySource')
2611869SN/AExport('SimObject')
2621869SN/AExport('SwigSource')
2631869SN/AExport('UnitTest')
2641869SN/A
2651869SN/A########################################################################
2661858SN/A#
2671869SN/A# Debug Flags
2681869SN/A#
2691869SN/Adebug_flags = {}
2701869SN/Adef DebugFlag(name, desc=None):
2711869SN/A    if name in debug_flags:
2721869SN/A        raise AttributeError, "Flag %s already specified" % name
2731869SN/A    debug_flags[name] = (name, (), desc)
2741869SN/A
2751869SN/Adef CompoundFlag(name, flags, desc=None):
2761869SN/A    if name in debug_flags:
2771858SN/A        raise AttributeError, "Flag %s already specified" % name
278955SN/A
279955SN/A    compound = tuple(flags)
2801869SN/A    debug_flags[name] = (name, compound, desc)
2811869SN/A
2821869SN/AExport('DebugFlag')
2831869SN/AExport('CompoundFlag')
2841869SN/A
2851869SN/A########################################################################
2861869SN/A#
2871869SN/A# Set some compiler variables
2881869SN/A#
2891869SN/A
2901869SN/A# Include file paths are rooted in this directory.  SCons will
2911869SN/A# automatically expand '.' to refer to both the source directory and
2921869SN/A# the corresponding build directory to pick up generated include
2931869SN/A# files.
2941869SN/Aenv.Append(CPPPATH=Dir('.'))
2951869SN/A
2961869SN/Afor extra_dir in extras_dir_list:
2971869SN/A    env.Append(CPPPATH=Dir(extra_dir))
2981869SN/A
2991869SN/A# Workaround for bug in SCons version > 0.97d20071212
3001869SN/A# Scons bug id: 2006 gem5 Bug id: 308
3011869SN/Afor root, dirs, files in os.walk(base_dir, topdown=True):
3021869SN/A    Dir(root[len(base_dir) + 1:])
3031869SN/A
3041869SN/A########################################################################
3051869SN/A#
3061869SN/A# Walk the tree and execute all SConscripts in subdirectories
3071869SN/A#
3081869SN/A
3091869SN/Ahere = Dir('.').srcnode().abspath
3101869SN/Afor root, dirs, files in os.walk(base_dir, topdown=True):
3111869SN/A    if root == here:
3121869SN/A        # we don't want to recurse back into this SConscript
3131869SN/A        continue
3141869SN/A
3151869SN/A    if 'SConscript' in files:
3161869SN/A        build_dir = joinpath(env['BUILDDIR'], root[len(base_dir) + 1:])
3171869SN/A        SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3181869SN/A
3192655Sstever@eecs.umich.edufor extra_dir in extras_dir_list:
3202655Sstever@eecs.umich.edu    prefix_len = len(dirname(extra_dir)) + 1
3212655Sstever@eecs.umich.edu    for root, dirs, files in os.walk(extra_dir, topdown=True):
3222655Sstever@eecs.umich.edu        # if build lives in the extras directory, don't walk down it
3232655Sstever@eecs.umich.edu        if 'build' in dirs:
3242655Sstever@eecs.umich.edu            dirs.remove('build')
3252655Sstever@eecs.umich.edu
3262655Sstever@eecs.umich.edu        if 'SConscript' in files:
3272655Sstever@eecs.umich.edu            build_dir = joinpath(env['BUILDDIR'], root[prefix_len:])
3282655Sstever@eecs.umich.edu            SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3292655Sstever@eecs.umich.edu
3302655Sstever@eecs.umich.edufor opt in export_vars:
3312655Sstever@eecs.umich.edu    env.ConfigFile(opt)
3322655Sstever@eecs.umich.edu
3332655Sstever@eecs.umich.edudef makeTheISA(source, target, env):
3342655Sstever@eecs.umich.edu    isas = [ src.get_contents() for src in source ]
3352655Sstever@eecs.umich.edu    target_isa = env['TARGET_ISA']
3362655Sstever@eecs.umich.edu    def define(isa):
3372655Sstever@eecs.umich.edu        return isa.upper() + '_ISA'
3382655Sstever@eecs.umich.edu    
3392655Sstever@eecs.umich.edu    def namespace(isa):
3402655Sstever@eecs.umich.edu        return isa[0].upper() + isa[1:].lower() + 'ISA' 
3412655Sstever@eecs.umich.edu
3422655Sstever@eecs.umich.edu
3432655Sstever@eecs.umich.edu    code = code_formatter()
3442655Sstever@eecs.umich.edu    code('''\
3452634Sstever@eecs.umich.edu#ifndef __CONFIG_THE_ISA_HH__
3462634Sstever@eecs.umich.edu#define __CONFIG_THE_ISA_HH__
3472634Sstever@eecs.umich.edu
3482634Sstever@eecs.umich.edu''')
3492634Sstever@eecs.umich.edu
3502634Sstever@eecs.umich.edu    for i,isa in enumerate(isas):
3512638Sstever@eecs.umich.edu        code('#define $0 $1', define(isa), i + 1)
3522638Sstever@eecs.umich.edu
3532638Sstever@eecs.umich.edu    code('''
3542638Sstever@eecs.umich.edu
3552638Sstever@eecs.umich.edu#define THE_ISA ${{define(target_isa)}}
3561869SN/A#define TheISA ${{namespace(target_isa)}}
3571869SN/A#define THE_ISA_STR "${{target_isa}}"
358955SN/A
359955SN/A#endif // __CONFIG_THE_ISA_HH__''')
360955SN/A
361955SN/A    code.write(str(target[0]))
3621858SN/A
3631858SN/Aenv.Command('config/the_isa.hh', map(Value, all_isa_list),
3641858SN/A            MakeAction(makeTheISA, Transform("CFG ISA", 0)))
3652632Sstever@eecs.umich.edu
3662632Sstever@eecs.umich.edu########################################################################
3672632Sstever@eecs.umich.edu#
3682632Sstever@eecs.umich.edu# Prevent any SimObjects from being added after this point, they
3692632Sstever@eecs.umich.edu# should all have been added in the SConscripts above
3702634Sstever@eecs.umich.edu#
3712638Sstever@eecs.umich.eduSimObject.fixed = True
3722023SN/A
3732632Sstever@eecs.umich.educlass DictImporter(object):
3742632Sstever@eecs.umich.edu    '''This importer takes a dictionary of arbitrary module names that
3752632Sstever@eecs.umich.edu    map to arbitrary filenames.'''
3762632Sstever@eecs.umich.edu    def __init__(self, modules):
3772632Sstever@eecs.umich.edu        self.modules = modules
3782632Sstever@eecs.umich.edu        self.installed = set()
3792632Sstever@eecs.umich.edu
3802632Sstever@eecs.umich.edu    def __del__(self):
3812632Sstever@eecs.umich.edu        self.unload()
3822632Sstever@eecs.umich.edu
3832632Sstever@eecs.umich.edu    def unload(self):
3842023SN/A        import sys
3852632Sstever@eecs.umich.edu        for module in self.installed:
3862632Sstever@eecs.umich.edu            del sys.modules[module]
3871889SN/A        self.installed = set()
3881889SN/A
3892632Sstever@eecs.umich.edu    def find_module(self, fullname, path):
3902632Sstever@eecs.umich.edu        if fullname == 'm5.defines':
3912632Sstever@eecs.umich.edu            return self
3922632Sstever@eecs.umich.edu
3932632Sstever@eecs.umich.edu        if fullname == 'm5.objects':
3942632Sstever@eecs.umich.edu            return self
3952632Sstever@eecs.umich.edu
3962632Sstever@eecs.umich.edu        if fullname.startswith('m5.internal'):
3972632Sstever@eecs.umich.edu            return None
3982632Sstever@eecs.umich.edu
3992632Sstever@eecs.umich.edu        source = self.modules.get(fullname, None)
4002632Sstever@eecs.umich.edu        if source is not None and fullname.startswith('m5.objects'):
4012632Sstever@eecs.umich.edu            return self
4022632Sstever@eecs.umich.edu
4031888SN/A        return None
4041888SN/A
4051869SN/A    def load_module(self, fullname):
4061869SN/A        mod = imp.new_module(fullname)
4071858SN/A        sys.modules[fullname] = mod
4082598SN/A        self.installed.add(fullname)
4092598SN/A
4102598SN/A        mod.__loader__ = self
4112598SN/A        if fullname == 'm5.objects':
4122598SN/A            mod.__path__ = fullname.split('.')
4131858SN/A            return mod
4141858SN/A
4151858SN/A        if fullname == 'm5.defines':
4161858SN/A            mod.__dict__['buildEnv'] = m5.util.SmartDict(build_env)
4171858SN/A            return mod
4181858SN/A
4191858SN/A        source = self.modules[fullname]
4201858SN/A        if source.modname == '__init__':
4211858SN/A            mod.__path__ = source.modpath
4221871SN/A        mod.__file__ = source.abspath
4231858SN/A
4241858SN/A        exec file(source.abspath, 'r') in mod.__dict__
4251858SN/A
4261858SN/A        return mod
4271858SN/A
4281858SN/Aimport m5.SimObject
4291858SN/Aimport m5.params
4301858SN/Afrom m5.util import code_formatter
4311858SN/A
4321858SN/Am5.SimObject.clear()
4331858SN/Am5.params.clear()
4341859SN/A
4351859SN/A# install the python importer so we can grab stuff from the source
4361869SN/A# tree itself.  We can't have SimObjects added after this point or
4371888SN/A# else we won't know about them for the rest of the stuff.
4382632Sstever@eecs.umich.eduimporter = DictImporter(PySource.modules)
4391869SN/Asys.meta_path[0:0] = [ importer ]
4401884SN/A
4411884SN/A# import all sim objects so we can populate the all_objects list
4421884SN/A# make sure that we're working with a list, then let's sort it
4431884SN/Afor modname in SimObject.modnames:
4441884SN/A    exec('from m5.objects import %s' % modname)
4451884SN/A
4461965SN/A# we need to unload all of the currently imported modules so that they
4471965SN/A# will be re-imported the next time the sconscript is run
4481965SN/Aimporter.unload()
449955SN/Asys.meta_path.remove(importer)
4501869SN/A
4511869SN/Asim_objects = m5.SimObject.allClasses
4522632Sstever@eecs.umich.eduall_enums = m5.params.allEnums
4531869SN/A
4541869SN/A# Find param types that need to be explicitly wrapped with swig.
4551869SN/A# These will be recognized because the ParamDesc will have a
4562632Sstever@eecs.umich.edu# swig_decl() method.  Most param types are based on types that don't
4572632Sstever@eecs.umich.edu# need this, either because they're based on native types (like Int)
4582632Sstever@eecs.umich.edu# or because they're SimObjects (which get swigged independently).
4592632Sstever@eecs.umich.edu# For now the only things handled here are VectorParam types.
460955SN/Aparams_to_swig = {}
4612598SN/Afor name,obj in sorted(sim_objects.iteritems()):
4622598SN/A    for param in obj._params.local.values():
463955SN/A        # load the ptype attribute now because it depends on the
464955SN/A        # current version of SimObject.allClasses, but when scons
465955SN/A        # actually uses the value, all versions of
4661530SN/A        # SimObject.allClasses will have been loaded
467955SN/A        param.ptype
468955SN/A
469955SN/A        if not hasattr(param, 'swig_decl'):
470            continue
471        pname = param.ptype_str
472        if pname not in params_to_swig:
473            params_to_swig[pname] = param
474
475########################################################################
476#
477# calculate extra dependencies
478#
479module_depends = ["m5", "m5.SimObject", "m5.params"]
480depends = [ PySource.modules[dep].snode for dep in module_depends ]
481
482########################################################################
483#
484# Commands for the basic automatically generated python files
485#
486
487# Generate Python file containing a dict specifying the current
488# buildEnv flags.
489def makeDefinesPyFile(target, source, env):
490    build_env = source[0].get_contents()
491
492    code = code_formatter()
493    code("""
494import m5.internal
495import m5.util
496
497buildEnv = m5.util.SmartDict($build_env)
498
499compileDate = m5.internal.core.compileDate
500_globals = globals()
501for key,val in m5.internal.core.__dict__.iteritems():
502    if key.startswith('flag_'):
503        flag = key[5:]
504        _globals[flag] = val
505del _globals
506""")
507    code.write(target[0].abspath)
508
509defines_info = Value(build_env)
510# Generate a file with all of the compile options in it
511env.Command('python/m5/defines.py', defines_info,
512            MakeAction(makeDefinesPyFile, Transform("DEFINES", 0)))
513PySource('m5', 'python/m5/defines.py')
514
515# Generate python file containing info about the M5 source code
516def makeInfoPyFile(target, source, env):
517    code = code_formatter()
518    for src in source:
519        data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
520        code('$src = ${{repr(data)}}')
521    code.write(str(target[0]))
522
523# Generate a file that wraps the basic top level files
524env.Command('python/m5/info.py',
525            [ '#/COPYING', '#/LICENSE', '#/README', ],
526            MakeAction(makeInfoPyFile, Transform("INFO")))
527PySource('m5', 'python/m5/info.py')
528
529########################################################################
530#
531# Create all of the SimObject param headers and enum headers
532#
533
534def createSimObjectParamStruct(target, source, env):
535    assert len(target) == 1 and len(source) == 1
536
537    name = str(source[0].get_contents())
538    obj = sim_objects[name]
539
540    code = code_formatter()
541    obj.cxx_param_decl(code)
542    code.write(target[0].abspath)
543
544def createParamSwigWrapper(target, source, env):
545    assert len(target) == 1 and len(source) == 1
546
547    name = str(source[0].get_contents())
548    param = params_to_swig[name]
549
550    code = code_formatter()
551    param.swig_decl(code)
552    code.write(target[0].abspath)
553
554def createEnumStrings(target, source, env):
555    assert len(target) == 1 and len(source) == 1
556
557    name = str(source[0].get_contents())
558    obj = all_enums[name]
559
560    code = code_formatter()
561    obj.cxx_def(code)
562    code.write(target[0].abspath)
563
564def createEnumDecls(target, source, env):
565    assert len(target) == 1 and len(source) == 1
566
567    name = str(source[0].get_contents())
568    obj = all_enums[name]
569
570    code = code_formatter()
571    obj.cxx_decl(code)
572    code.write(target[0].abspath)
573
574def createEnumSwigWrapper(target, source, env):
575    assert len(target) == 1 and len(source) == 1
576
577    name = str(source[0].get_contents())
578    obj = all_enums[name]
579
580    code = code_formatter()
581    obj.swig_decl(code)
582    code.write(target[0].abspath)
583
584def createSimObjectSwigWrapper(target, source, env):
585    name = source[0].get_contents()
586    obj = sim_objects[name]
587
588    code = code_formatter()
589    obj.swig_decl(code)
590    code.write(target[0].abspath)
591
592# Generate all of the SimObject param C++ struct header files
593params_hh_files = []
594for name,simobj in sorted(sim_objects.iteritems()):
595    py_source = PySource.modules[simobj.__module__]
596    extra_deps = [ py_source.tnode ]
597
598    hh_file = File('params/%s.hh' % name)
599    params_hh_files.append(hh_file)
600    env.Command(hh_file, Value(name),
601                MakeAction(createSimObjectParamStruct, Transform("SO PARAM")))
602    env.Depends(hh_file, depends + extra_deps)
603
604# Generate any needed param SWIG wrapper files
605params_i_files = []
606for name,param in params_to_swig.iteritems():
607    i_file = File('python/m5/internal/%s.i' % (param.swig_module_name()))
608    params_i_files.append(i_file)
609    env.Command(i_file, Value(name),
610                MakeAction(createParamSwigWrapper, Transform("SW PARAM")))
611    env.Depends(i_file, depends)
612    SwigSource('m5.internal', i_file)
613
614# Generate all enum header files
615for name,enum in sorted(all_enums.iteritems()):
616    py_source = PySource.modules[enum.__module__]
617    extra_deps = [ py_source.tnode ]
618
619    cc_file = File('enums/%s.cc' % name)
620    env.Command(cc_file, Value(name),
621                MakeAction(createEnumStrings, Transform("ENUM STR")))
622    env.Depends(cc_file, depends + extra_deps)
623    Source(cc_file)
624
625    hh_file = File('enums/%s.hh' % name)
626    env.Command(hh_file, Value(name),
627                MakeAction(createEnumDecls, Transform("ENUMDECL")))
628    env.Depends(hh_file, depends + extra_deps)
629
630    i_file = File('python/m5/internal/enum_%s.i' % name)
631    env.Command(i_file, Value(name),
632                MakeAction(createEnumSwigWrapper, Transform("ENUMSWIG")))
633    env.Depends(i_file, depends + extra_deps)
634    SwigSource('m5.internal', i_file)
635
636# Generate SimObject SWIG wrapper files
637for name in sim_objects.iterkeys():
638    i_file = File('python/m5/internal/param_%s.i' % name)
639    env.Command(i_file, Value(name),
640                MakeAction(createSimObjectSwigWrapper, Transform("SO SWIG")))
641    env.Depends(i_file, depends)
642    SwigSource('m5.internal', i_file)
643
644# Generate the main swig init file
645def makeEmbeddedSwigInit(target, source, env):
646    code = code_formatter()
647    module = source[0].get_contents()
648    code('''\
649#include "sim/init.hh"
650
651extern "C" {
652    void init_${module}();
653}
654
655EmbeddedSwig embed_swig_${module}(init_${module});
656''')
657    code.write(str(target[0]))
658    
659# Build all swig modules
660for swig in SwigSource.all:
661    env.Command([swig.cc_source.tnode, swig.py_source.tnode], swig.tnode,
662                MakeAction('$SWIG $SWIGFLAGS -outdir ${TARGETS[1].dir} '
663                '-o ${TARGETS[0]} $SOURCES', Transform("SWIG")))
664    cc_file = str(swig.tnode)
665    init_file = '%s/%s_init.cc' % (dirname(cc_file), basename(cc_file))
666    env.Command(init_file, Value(swig.module),
667                MakeAction(makeEmbeddedSwigInit, Transform("EMBED SW")))
668    Source(init_file, **swig.guards)
669
670#
671# Handle debug flags
672#
673def makeDebugFlagCC(target, source, env):
674    assert(len(target) == 1 and len(source) == 1)
675
676    val = eval(source[0].get_contents())
677    name, compound, desc = val
678    compound = list(sorted(compound))
679
680    code = code_formatter()
681
682    # file header
683    code('''
684/*
685 * DO NOT EDIT THIS FILE! Automatically generated
686 */
687
688#include "base/debug.hh"
689''')
690
691    for flag in compound:
692        code('#include "debug/$flag.hh"')
693    code()
694    code('namespace Debug {')
695    code()
696
697    if not compound:
698        code('SimpleFlag $name("$name", "$desc");')
699    else:
700        code('CompoundFlag $name("$name", "$desc",')
701        code.indent()
702        last = len(compound) - 1
703        for i,flag in enumerate(compound):
704            if i != last:
705                code('$flag,')
706            else:
707                code('$flag);')
708        code.dedent()
709
710    code()
711    code('} // namespace Debug')
712
713    code.write(str(target[0]))
714
715def makeDebugFlagHH(target, source, env):
716    assert(len(target) == 1 and len(source) == 1)
717
718    val = eval(source[0].get_contents())
719    name, compound, desc = val
720
721    code = code_formatter()
722
723    # file header boilerplate
724    code('''\
725/*
726 * DO NOT EDIT THIS FILE!
727 *
728 * Automatically generated by SCons
729 */
730
731#ifndef __DEBUG_${name}_HH__
732#define __DEBUG_${name}_HH__
733
734namespace Debug {
735''')
736
737    if compound:
738        code('class CompoundFlag;')
739    code('class SimpleFlag;')
740
741    if compound:
742        code('extern CompoundFlag $name;')
743        for flag in compound:
744            code('extern SimpleFlag $flag;')
745    else:
746        code('extern SimpleFlag $name;')
747
748    code('''
749}
750
751#endif // __DEBUG_${name}_HH__
752''')
753
754    code.write(str(target[0]))
755
756for name,flag in sorted(debug_flags.iteritems()):
757    n, compound, desc = flag
758    assert n == name
759
760    env.Command('debug/%s.hh' % name, Value(flag),
761                MakeAction(makeDebugFlagHH, Transform("TRACING", 0)))
762    env.Command('debug/%s.cc' % name, Value(flag),
763                MakeAction(makeDebugFlagCC, Transform("TRACING", 0)))
764    Source('debug/%s.cc' % name)
765
766# Embed python files.  All .py files that have been indicated by a
767# PySource() call in a SConscript need to be embedded into the M5
768# library.  To do that, we compile the file to byte code, marshal the
769# byte code, compress it, and then generate a c++ file that
770# inserts the result into an array.
771def embedPyFile(target, source, env):
772    def c_str(string):
773        if string is None:
774            return "0"
775        return '"%s"' % string
776
777    '''Action function to compile a .py into a code object, marshal
778    it, compress it, and stick it into an asm file so the code appears
779    as just bytes with a label in the data section'''
780
781    src = file(str(source[0]), 'r').read()
782
783    pysource = PySource.tnodes[source[0]]
784    compiled = compile(src, pysource.abspath, 'exec')
785    marshalled = marshal.dumps(compiled)
786    compressed = zlib.compress(marshalled)
787    data = compressed
788    sym = pysource.symname
789
790    code = code_formatter()
791    code('''\
792#include "sim/init.hh"
793
794namespace {
795
796const uint8_t data_${sym}[] = {
797''')
798    code.indent()
799    step = 16
800    for i in xrange(0, len(data), step):
801        x = array.array('B', data[i:i+step])
802        code(''.join('%d,' % d for d in x))
803    code.dedent()
804    
805    code('''};
806
807EmbeddedPython embedded_${sym}(
808    ${{c_str(pysource.arcname)}},
809    ${{c_str(pysource.abspath)}},
810    ${{c_str(pysource.modpath)}},
811    data_${sym},
812    ${{len(data)}},
813    ${{len(marshalled)}});
814
815} // anonymous namespace
816''')
817    code.write(str(target[0]))
818
819for source in PySource.all:
820    env.Command(source.cpp, source.tnode, 
821                MakeAction(embedPyFile, Transform("EMBED PY")))
822    Source(source.cpp)
823
824########################################################################
825#
826# Define binaries.  Each different build type (debug, opt, etc.) gets
827# a slightly different build environment.
828#
829
830# List of constructed environments to pass back to SConstruct
831envList = []
832
833date_source = Source('base/date.cc', skip_lib=True)
834
835# Function to create a new build environment as clone of current
836# environment 'env' with modified object suffix and optional stripped
837# binary.  Additional keyword arguments are appended to corresponding
838# build environment vars.
839def makeEnv(label, objsfx, strip = False, **kwargs):
840    # SCons doesn't know to append a library suffix when there is a '.' in the
841    # name.  Use '_' instead.
842    libname = 'gem5_' + label
843    exename = 'gem5.' + label
844    secondary_exename = 'm5.' + label
845
846    new_env = env.Clone(OBJSUFFIX=objsfx, SHOBJSUFFIX=objsfx + 's')
847    new_env.Label = label
848    new_env.Append(**kwargs)
849
850    swig_env = new_env.Clone()
851    swig_env.Append(CCFLAGS='-Werror')
852    if env['GCC']:
853        swig_env.Append(CCFLAGS=['-Wno-uninitialized', '-Wno-sign-compare',
854                                 '-Wno-parentheses', '-Wno-unused-label',
855                                 '-Wno-unused-value'])
856        if compareVersions(env['GCC_VERSION'], '4.6') >= 0:
857            swig_env.Append(CCFLAGS='-Wno-unused-but-set-variable')
858    if env['CLANG']:
859        swig_env.Append(CCFLAGS=['-Wno-unused-label', '-Wno-unused-value'])
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        if test.main:
910            test_objs += main_objs
911        testname = "unittest/%s.%s" % (test.target, label)
912        new_env.Program(testname, test_objs + static_objs)
913
914    progname = exename
915    if strip:
916        progname += '.unstripped'
917
918    targets = new_env.Program(progname, main_objs + static_objs)
919
920    if strip:
921        if sys.platform == 'sunos5':
922            cmd = 'cp $SOURCE $TARGET; strip $TARGET'
923        else:
924            cmd = 'strip $SOURCE -o $TARGET'
925        targets = new_env.Command(exename, progname,
926                    MakeAction(cmd, Transform("STRIP")))
927
928    new_env.Command(secondary_exename, exename,
929            MakeAction('ln $SOURCE $TARGET', Transform("HARDLINK")))
930
931    new_env.M5Binary = targets[0]
932    envList.append(new_env)
933
934# Debug binary
935ccflags = {}
936if env['GCC']:
937    if sys.platform == 'sunos5':
938        ccflags['debug'] = '-gstabs+'
939    else:
940        ccflags['debug'] = '-ggdb3'
941    ccflags['opt'] = '-g -O3'
942    ccflags['fast'] = '-O3'
943    ccflags['prof'] = '-O3 -g -pg'
944elif env['SUNCC']:
945    ccflags['debug'] = '-g0'
946    ccflags['opt'] = '-g -O'
947    ccflags['fast'] = '-fast'
948    ccflags['prof'] = '-fast -g -pg'
949elif env['ICC']:
950    ccflags['debug'] = '-g -O0'
951    ccflags['opt'] = '-g -O'
952    ccflags['fast'] = '-fast'
953    ccflags['prof'] = '-fast -g -pg'
954elif env['CLANG']:
955    ccflags['debug'] = '-g -O0'
956    ccflags['opt'] = '-g -O3'
957    ccflags['fast'] = '-O3'
958    ccflags['prof'] = '-O3 -g -pg'
959else:
960    print 'Unknown compiler, please fix compiler options'
961    Exit(1)
962
963
964# To speed things up, we only instantiate the build environments we
965# need.  We try to identify the needed environment for each target; if
966# we can't, we fall back on instantiating all the environments just to
967# be safe.
968target_types = ['debug', 'opt', 'fast', 'prof']
969obj2target = {'do': 'debug', 'o': 'opt', 'fo': 'fast', 'po': 'prof'}
970
971def identifyTarget(t):
972    ext = t.split('.')[-1]
973    if ext in target_types:
974        return ext
975    if obj2target.has_key(ext):
976        return obj2target[ext]
977    match = re.search(r'/tests/([^/]+)/', t)
978    if match and match.group(1) in target_types:
979        return match.group(1)
980    return 'all'
981
982needed_envs = [identifyTarget(target) for target in BUILD_TARGETS]
983if 'all' in needed_envs:
984    needed_envs += target_types
985
986# Debug binary
987if 'debug' in needed_envs:
988    makeEnv('debug', '.do',
989            CCFLAGS = Split(ccflags['debug']),
990            CPPDEFINES = ['DEBUG', 'TRACING_ON=1'])
991
992# Optimized binary
993if 'opt' in needed_envs:
994    makeEnv('opt', '.o',
995            CCFLAGS = Split(ccflags['opt']),
996            CPPDEFINES = ['TRACING_ON=1'])
997
998# "Fast" binary
999if 'fast' in needed_envs:
1000    makeEnv('fast', '.fo', strip = True,
1001            CCFLAGS = Split(ccflags['fast']),
1002            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'])
1003
1004# Profiled binary
1005if 'prof' in needed_envs:
1006    makeEnv('prof', '.po',
1007            CCFLAGS = Split(ccflags['prof']),
1008            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1009            LINKFLAGS = '-pg')
1010
1011Return('envList')
1012