SConscript revision 12223
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.
282665Ssaidi@eecs.umich.edu#
294762Snate@binkert.org# Authors: Nathan Binkert
30955SN/A
315522Snate@binkert.orgimport array
326143Snate@binkert.orgimport bisect
334762Snate@binkert.orgimport imp
345522Snate@binkert.orgimport marshal
35955SN/Aimport os
365522Snate@binkert.orgimport re
37955SN/Aimport subprocess
385522Snate@binkert.orgimport sys
394202Sbinkertn@umich.eduimport zlib
405742Snate@binkert.org
41955SN/Afrom os.path import basename, dirname, exists, isdir, isfile, join as joinpath
424381Sbinkertn@umich.edu
434381Sbinkertn@umich.eduimport SCons
44955SN/A
45955SN/A# This file defines how to build a particular configuration of gem5
46955SN/A# based on variable settings in the 'env' build environment.
474202Sbinkertn@umich.edu
48955SN/AImport('*')
494382Sbinkertn@umich.edu
504382Sbinkertn@umich.edu# Children need to see the environment
514382Sbinkertn@umich.eduExport('env')
526654Snate@binkert.org
535517Snate@binkert.orgbuild_env = [(opt, env[opt]) for opt in export_vars]
546143Snate@binkert.org
556143Snate@binkert.orgfrom m5.util import code_formatter, compareVersions
566143Snate@binkert.org
576143Snate@binkert.org########################################################################
586143Snate@binkert.org# Code for adding source files of various types
596143Snate@binkert.org#
606143Snate@binkert.org# When specifying a source file of some type, a set of guards can be
616143Snate@binkert.org# specified for that file.  When get() is used to find the files, if
626143Snate@binkert.org# get specifies a set of filters, only files that match those filters
636143Snate@binkert.org# will be accepted (unspecified filters on files are assumed to be
646143Snate@binkert.org# false).  Current filters are:
656143Snate@binkert.org#     main -- specifies the gem5 main() function
666143Snate@binkert.org#     skip_lib -- do not put this file into the gem5 library
676143Snate@binkert.org#     skip_no_python -- do not put this file into a no_python library
686143Snate@binkert.org#       as it embeds compiled Python
694762Snate@binkert.org#     <unittest> -- unit tests use filters based on the unit test name
706143Snate@binkert.org#
716143Snate@binkert.org# A parent can now be specified for a source file and default filter
726143Snate@binkert.org# values will be retrieved recursively from parents (children override
736143Snate@binkert.org# parents).
746143Snate@binkert.org#
756143Snate@binkert.orgdef guarded_source_iterator(sources, **guards):
766143Snate@binkert.org    '''Iterate over a set of sources, gated by a set of guards.'''
776143Snate@binkert.org    for src in sources:
786143Snate@binkert.org        for flag,value in guards.iteritems():
796143Snate@binkert.org            # if the flag is found and has a different value, skip
806143Snate@binkert.org            # this file
816143Snate@binkert.org            if src.all_guards.get(flag, False) != value:
826143Snate@binkert.org                break
836143Snate@binkert.org        else:
846143Snate@binkert.org            yield src
856143Snate@binkert.org
866143Snate@binkert.orgclass SourceMeta(type):
876143Snate@binkert.org    '''Meta class for source files that keeps track of all files of a
886143Snate@binkert.org    particular type and has a get function for finding all functions
896143Snate@binkert.org    of a certain type that match a set of guards'''
906143Snate@binkert.org    def __init__(cls, name, bases, dict):
916143Snate@binkert.org        super(SourceMeta, cls).__init__(name, bases, dict)
926143Snate@binkert.org        cls.all = []
936143Snate@binkert.org
946143Snate@binkert.org    def get(cls, **guards):
956143Snate@binkert.org        '''Find all files that match the specified guards.  If a source
966143Snate@binkert.org        file does not specify a flag, the default is False'''
976143Snate@binkert.org        for s in guarded_source_iterator(cls.all, **guards):
986143Snate@binkert.org            yield s
996143Snate@binkert.org
1006143Snate@binkert.orgclass SourceFile(object):
1016143Snate@binkert.org    '''Base object that encapsulates the notion of a source file.
1026143Snate@binkert.org    This includes, the source node, target node, various manipulations
1036143Snate@binkert.org    of those.  A source file also specifies a set of guards which
1046143Snate@binkert.org    describing which builds the source file applies to.  A parent can
1056143Snate@binkert.org    also be specified to get default guards from'''
1066143Snate@binkert.org    __metaclass__ = SourceMeta
1076143Snate@binkert.org    def __init__(self, source, parent=None, **guards):
1086143Snate@binkert.org        self.guards = guards
1096143Snate@binkert.org        self.parent = parent
1106143Snate@binkert.org
1116143Snate@binkert.org        tnode = source
1126143Snate@binkert.org        if not isinstance(source, SCons.Node.FS.File):
1135522Snate@binkert.org            tnode = File(source)
1146143Snate@binkert.org
1156143Snate@binkert.org        self.tnode = tnode
1166143Snate@binkert.org        self.snode = tnode.srcnode()
1176143Snate@binkert.org
1186143Snate@binkert.org        for base in type(self).__mro__:
1196143Snate@binkert.org            if issubclass(base, SourceFile):
1206143Snate@binkert.org                base.all.append(self)
1216143Snate@binkert.org
1226143Snate@binkert.org    @property
1236143Snate@binkert.org    def filename(self):
1245522Snate@binkert.org        return str(self.tnode)
1255522Snate@binkert.org
1265522Snate@binkert.org    @property
1275522Snate@binkert.org    def dirname(self):
1285604Snate@binkert.org        return dirname(self.filename)
1295604Snate@binkert.org
1306143Snate@binkert.org    @property
1316143Snate@binkert.org    def basename(self):
1324762Snate@binkert.org        return basename(self.filename)
1334762Snate@binkert.org
1346143Snate@binkert.org    @property
1356143Snate@binkert.org    def extname(self):
1366143Snate@binkert.org        index = self.basename.rfind('.')
1376143Snate@binkert.org        if index <= 0:
1384762Snate@binkert.org            # dot files aren't extensions
1396143Snate@binkert.org            return self.basename, None
1406143Snate@binkert.org
1416143Snate@binkert.org        return self.basename[:index], self.basename[index+1:]
1426143Snate@binkert.org
1436143Snate@binkert.org    @property
1446143Snate@binkert.org    def all_guards(self):
1456143Snate@binkert.org        '''find all guards for this object getting default values
1466143Snate@binkert.org        recursively from its parents'''
1475604Snate@binkert.org        guards = {}
1486143Snate@binkert.org        if self.parent:
1496143Snate@binkert.org            guards.update(self.parent.guards)
1506143Snate@binkert.org        guards.update(self.guards)
1514762Snate@binkert.org        return guards
1526143Snate@binkert.org
1534762Snate@binkert.org    def __lt__(self, other): return self.filename < other.filename
1544762Snate@binkert.org    def __le__(self, other): return self.filename <= other.filename
1554762Snate@binkert.org    def __gt__(self, other): return self.filename > other.filename
1566143Snate@binkert.org    def __ge__(self, other): return self.filename >= other.filename
1576143Snate@binkert.org    def __eq__(self, other): return self.filename == other.filename
1584762Snate@binkert.org    def __ne__(self, other): return self.filename != other.filename
1596143Snate@binkert.org
1606143Snate@binkert.org    @staticmethod
1616143Snate@binkert.org    def done():
1626143Snate@binkert.org        def disabled(cls, name, *ignored):
1634762Snate@binkert.org            raise RuntimeError("Additional SourceFile '%s'" % name,\
1646143Snate@binkert.org                  "declared, but targets deps are already fixed.")
1654762Snate@binkert.org        SourceFile.__init__ = disabled
1666143Snate@binkert.org
1674762Snate@binkert.org
1686143Snate@binkert.orgclass Source(SourceFile):
1696143Snate@binkert.org    current_group = None
1706143Snate@binkert.org    source_groups = { None : [] }
1716143Snate@binkert.org
1726143Snate@binkert.org    @classmethod
1736143Snate@binkert.org    def set_group(cls, group):
1746143Snate@binkert.org        if not group in Source.source_groups:
1756143Snate@binkert.org            Source.source_groups[group] = []
1766143Snate@binkert.org        Source.current_group = group
1776143Snate@binkert.org
1786143Snate@binkert.org    '''Add a c/c++ source file to the build'''
1796143Snate@binkert.org    def __init__(self, source, Werror=True, **guards):
1806143Snate@binkert.org        '''specify the source file, and any guards'''
181955SN/A        super(Source, self).__init__(source, **guards)
1825584Snate@binkert.org
1835584Snate@binkert.org        self.Werror = Werror
1845584Snate@binkert.org
1855584Snate@binkert.org        Source.source_groups[Source.current_group].append(self)
1866143Snate@binkert.org
1876143Snate@binkert.orgclass PySource(SourceFile):
1886143Snate@binkert.org    '''Add a python source file to the named package'''
1895584Snate@binkert.org    invalid_sym_char = re.compile('[^A-z0-9_]')
1904382Sbinkertn@umich.edu    modules = {}
1914202Sbinkertn@umich.edu    tnodes = {}
1924382Sbinkertn@umich.edu    symnames = {}
1934382Sbinkertn@umich.edu
1944382Sbinkertn@umich.edu    def __init__(self, package, source, **guards):
1955584Snate@binkert.org        '''specify the python package, the source file, and any guards'''
1964382Sbinkertn@umich.edu        super(PySource, self).__init__(source, **guards)
1974382Sbinkertn@umich.edu
1984382Sbinkertn@umich.edu        modname,ext = self.extname
1995192Ssaidi@eecs.umich.edu        assert ext == 'py'
2005192Ssaidi@eecs.umich.edu
2015799Snate@binkert.org        if package:
2025799Snate@binkert.org            path = package.split('.')
2035799Snate@binkert.org        else:
2045192Ssaidi@eecs.umich.edu            path = []
2055799Snate@binkert.org
2065192Ssaidi@eecs.umich.edu        modpath = path[:]
2075799Snate@binkert.org        if modname != '__init__':
2085799Snate@binkert.org            modpath += [ modname ]
2095192Ssaidi@eecs.umich.edu        modpath = '.'.join(modpath)
2105192Ssaidi@eecs.umich.edu
2115192Ssaidi@eecs.umich.edu        arcpath = path + [ self.basename ]
2125799Snate@binkert.org        abspath = self.snode.abspath
2135192Ssaidi@eecs.umich.edu        if not exists(abspath):
2145192Ssaidi@eecs.umich.edu            abspath = self.tnode.abspath
2155192Ssaidi@eecs.umich.edu
2165192Ssaidi@eecs.umich.edu        self.package = package
2175192Ssaidi@eecs.umich.edu        self.modname = modname
2185192Ssaidi@eecs.umich.edu        self.modpath = modpath
2194382Sbinkertn@umich.edu        self.arcname = joinpath(*arcpath)
2204382Sbinkertn@umich.edu        self.abspath = abspath
2214382Sbinkertn@umich.edu        self.compiled = File(self.filename + 'c')
2222667Sstever@eecs.umich.edu        self.cpp = File(self.filename + '.cc')
2232667Sstever@eecs.umich.edu        self.symname = PySource.invalid_sym_char.sub('_', modpath)
2242667Sstever@eecs.umich.edu
2252667Sstever@eecs.umich.edu        PySource.modules[modpath] = self
2262667Sstever@eecs.umich.edu        PySource.tnodes[self.tnode] = self
2272667Sstever@eecs.umich.edu        PySource.symnames[self.symname] = self
2285742Snate@binkert.org
2295742Snate@binkert.orgclass SimObject(PySource):
2305742Snate@binkert.org    '''Add a SimObject python file as a python source object and add
2312037SN/A    it to a list of sim object modules'''
2322037SN/A
2332037SN/A    fixed = False
2345793Snate@binkert.org    modnames = []
2355793Snate@binkert.org
2365793Snate@binkert.org    def __init__(self, source, **guards):
2375793Snate@binkert.org        '''Specify the source file and any guards (automatically in
2385793Snate@binkert.org        the m5.objects package)'''
2394382Sbinkertn@umich.edu        super(SimObject, self).__init__('m5.objects', source, **guards)
2404762Snate@binkert.org        if self.fixed:
2415344Sstever@gmail.com            raise AttributeError, "Too late to call SimObject now."
2424382Sbinkertn@umich.edu
2435341Sstever@gmail.com        bisect.insort_right(SimObject.modnames, self.modname)
2445742Snate@binkert.org
2455742Snate@binkert.orgclass ProtoBuf(SourceFile):
2465742Snate@binkert.org    '''Add a Protocol Buffer to build'''
2475742Snate@binkert.org
2485742Snate@binkert.org    def __init__(self, source, **guards):
2494762Snate@binkert.org        '''Specify the source file, and any guards'''
2505742Snate@binkert.org        super(ProtoBuf, self).__init__(source, **guards)
2515742Snate@binkert.org
2525742Snate@binkert.org        # Get the file name and the extension
2535742Snate@binkert.org        modname,ext = self.extname
2545742Snate@binkert.org        assert ext == 'proto'
2555742Snate@binkert.org
2565742Snate@binkert.org        # Currently, we stick to generating the C++ headers, so we
2575341Sstever@gmail.com        # only need to track the source and header.
2585742Snate@binkert.org        self.cc_file = File(modname + '.pb.cc')
2595341Sstever@gmail.com        self.hh_file = File(modname + '.pb.h')
2604773Snate@binkert.org
2616108Snate@binkert.orgclass UnitTest(object):
2621858SN/A    '''Create a UnitTest'''
2631085SN/A
2644382Sbinkertn@umich.edu    all = []
2654382Sbinkertn@umich.edu    def __init__(self, target, *sources, **kwargs):
2664762Snate@binkert.org        '''Specify the target name and any sources.  Sources that are
2674762Snate@binkert.org        not SourceFiles are evalued with Source().  All files are
2684762Snate@binkert.org        guarded with a guard of the same name as the UnitTest
2696654Snate@binkert.org        target.'''
2706654Snate@binkert.org
2715517Snate@binkert.org        srcs = []
2725517Snate@binkert.org        for src in sources:
2735517Snate@binkert.org            if not isinstance(src, SourceFile):
2745517Snate@binkert.org                src = Source(src, skip_lib=True)
2755517Snate@binkert.org            src.guards[target] = True
2765517Snate@binkert.org            srcs.append(src)
2775517Snate@binkert.org
2785517Snate@binkert.org        self.sources = srcs
2795517Snate@binkert.org        self.target = target
2805517Snate@binkert.org        self.main = kwargs.get('main', False)
2815517Snate@binkert.org        UnitTest.all.append(self)
2825517Snate@binkert.org
2835517Snate@binkert.org# Children should have access
2845517Snate@binkert.orgExport('Source')
2855517Snate@binkert.orgExport('PySource')
2865517Snate@binkert.orgExport('SimObject')
2875517Snate@binkert.orgExport('ProtoBuf')
2886654Snate@binkert.orgExport('UnitTest')
2895517Snate@binkert.org
2905517Snate@binkert.org########################################################################
2915517Snate@binkert.org#
2925517Snate@binkert.org# Debug Flags
2935517Snate@binkert.org#
2945517Snate@binkert.orgdebug_flags = {}
2955517Snate@binkert.orgdef DebugFlag(name, desc=None):
2965517Snate@binkert.org    if name in debug_flags:
2976143Snate@binkert.org        raise AttributeError, "Flag %s already specified" % name
2986654Snate@binkert.org    debug_flags[name] = (name, (), desc)
2995517Snate@binkert.org
3005517Snate@binkert.orgdef CompoundFlag(name, flags, desc=None):
3015517Snate@binkert.org    if name in debug_flags:
3025517Snate@binkert.org        raise AttributeError, "Flag %s already specified" % name
3035517Snate@binkert.org
3045517Snate@binkert.org    compound = tuple(flags)
3055517Snate@binkert.org    debug_flags[name] = (name, compound, desc)
3065517Snate@binkert.org
3075517Snate@binkert.orgExport('DebugFlag')
3085517Snate@binkert.orgExport('CompoundFlag')
3095517Snate@binkert.org
3105517Snate@binkert.org########################################################################
3115517Snate@binkert.org#
3125517Snate@binkert.org# Set some compiler variables
3136654Snate@binkert.org#
3146654Snate@binkert.org
3155517Snate@binkert.org# Include file paths are rooted in this directory.  SCons will
3165517Snate@binkert.org# automatically expand '.' to refer to both the source directory and
3176143Snate@binkert.org# the corresponding build directory to pick up generated include
3186143Snate@binkert.org# files.
3196143Snate@binkert.orgenv.Append(CPPPATH=Dir('.'))
3206143Snate@binkert.org
3215517Snate@binkert.orgfor extra_dir in extras_dir_list:
3226143Snate@binkert.org    env.Append(CPPPATH=Dir(extra_dir))
3235517Snate@binkert.org
3245517Snate@binkert.org# Workaround for bug in SCons version > 0.97d20071212
3255517Snate@binkert.org# Scons bug id: 2006 gem5 Bug id: 308
3266654Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
3276654Snate@binkert.org    Dir(root[len(base_dir) + 1:])
3286654Snate@binkert.org
3296654Snate@binkert.org########################################################################
3306654Snate@binkert.org#
3316654Snate@binkert.org# Walk the tree and execute all SConscripts in subdirectories
3325517Snate@binkert.org#
3335517Snate@binkert.org
3345517Snate@binkert.orghere = Dir('.').srcnode().abspath
3356143Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
3365517Snate@binkert.org    if root == here:
3374762Snate@binkert.org        # we don't want to recurse back into this SConscript
3385517Snate@binkert.org        continue
3395517Snate@binkert.org
3406143Snate@binkert.org    if 'SConscript' in files:
3416143Snate@binkert.org        build_dir = joinpath(env['BUILDDIR'], root[len(base_dir) + 1:])
3425517Snate@binkert.org        Source.set_group(build_dir)
3435517Snate@binkert.org        SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3445517Snate@binkert.org
3455517Snate@binkert.orgfor extra_dir in extras_dir_list:
3465517Snate@binkert.org    prefix_len = len(dirname(extra_dir)) + 1
3475517Snate@binkert.org
3485517Snate@binkert.org    # Also add the corresponding build directory to pick up generated
3495517Snate@binkert.org    # include files.
3505517Snate@binkert.org    env.Append(CPPPATH=Dir(joinpath(env['BUILDDIR'], extra_dir[prefix_len:])))
3515517Snate@binkert.org
3526143Snate@binkert.org    for root, dirs, files in os.walk(extra_dir, topdown=True):
3535517Snate@binkert.org        # if build lives in the extras directory, don't walk down it
3546654Snate@binkert.org        if 'build' in dirs:
3556654Snate@binkert.org            dirs.remove('build')
3566654Snate@binkert.org
3576654Snate@binkert.org        if 'SConscript' in files:
3586654Snate@binkert.org            build_dir = joinpath(env['BUILDDIR'], root[prefix_len:])
3596654Snate@binkert.org            SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3605517Snate@binkert.org
3615517Snate@binkert.orgfor opt in export_vars:
3625517Snate@binkert.org    env.ConfigFile(opt)
3635517Snate@binkert.org
3645517Snate@binkert.orgdef makeTheISA(source, target, env):
3654762Snate@binkert.org    isas = [ src.get_contents() for src in source ]
3664762Snate@binkert.org    target_isa = env['TARGET_ISA']
3674762Snate@binkert.org    def define(isa):
3684762Snate@binkert.org        return isa.upper() + '_ISA'
3694762Snate@binkert.org
3704762Snate@binkert.org    def namespace(isa):
3716143Snate@binkert.org        return isa[0].upper() + isa[1:].lower() + 'ISA'
3724762Snate@binkert.org
3734762Snate@binkert.org
3744762Snate@binkert.org    code = code_formatter()
3754762Snate@binkert.org    code('''\
3764382Sbinkertn@umich.edu#ifndef __CONFIG_THE_ISA_HH__
3774382Sbinkertn@umich.edu#define __CONFIG_THE_ISA_HH__
3785517Snate@binkert.org
3796654Snate@binkert.org''')
3805517Snate@binkert.org
3815798Snate@binkert.org    # create defines for the preprocessing and compile-time determination
3826654Snate@binkert.org    for i,isa in enumerate(isas):
3836654Snate@binkert.org        code('#define $0 $1', define(isa), i + 1)
3846654Snate@binkert.org    code()
3856654Snate@binkert.org
3866654Snate@binkert.org    # create an enum for any run-time determination of the ISA, we
3876654Snate@binkert.org    # reuse the same name as the namespaces
3886654Snate@binkert.org    code('enum class Arch {')
3896654Snate@binkert.org    for i,isa in enumerate(isas):
3906654Snate@binkert.org        if i + 1 == len(isas):
3916654Snate@binkert.org            code('  $0 = $1', namespace(isa), define(isa))
3926654Snate@binkert.org        else:
3936654Snate@binkert.org            code('  $0 = $1,', namespace(isa), define(isa))
3946654Snate@binkert.org    code('};')
3956654Snate@binkert.org
3966654Snate@binkert.org    code('''
3975517Snate@binkert.org
3985863Snate@binkert.org#define THE_ISA ${{define(target_isa)}}
3995798Snate@binkert.org#define TheISA ${{namespace(target_isa)}}
4005798Snate@binkert.org#define THE_ISA_STR "${{target_isa}}"
4015798Snate@binkert.org
4025798Snate@binkert.org#endif // __CONFIG_THE_ISA_HH__''')
4035517Snate@binkert.org
4045517Snate@binkert.org    code.write(str(target[0]))
4055517Snate@binkert.org
4065517Snate@binkert.orgenv.Command('config/the_isa.hh', map(Value, all_isa_list),
4075517Snate@binkert.org            MakeAction(makeTheISA, Transform("CFG ISA", 0)))
4085517Snate@binkert.org
4095517Snate@binkert.orgdef makeTheGPUISA(source, target, env):
4105517Snate@binkert.org    isas = [ src.get_contents() for src in source ]
4115798Snate@binkert.org    target_gpu_isa = env['TARGET_GPU_ISA']
4125798Snate@binkert.org    def define(isa):
4135798Snate@binkert.org        return isa.upper() + '_ISA'
4145798Snate@binkert.org
4155798Snate@binkert.org    def namespace(isa):
4165798Snate@binkert.org        return isa[0].upper() + isa[1:].lower() + 'ISA'
4175517Snate@binkert.org
4185517Snate@binkert.org
4195517Snate@binkert.org    code = code_formatter()
4205517Snate@binkert.org    code('''\
4215517Snate@binkert.org#ifndef __CONFIG_THE_GPU_ISA_HH__
4225517Snate@binkert.org#define __CONFIG_THE_GPU_ISA_HH__
4235517Snate@binkert.org
4245517Snate@binkert.org''')
4255517Snate@binkert.org
4264762Snate@binkert.org    # create defines for the preprocessing and compile-time determination
4274382Sbinkertn@umich.edu    for i,isa in enumerate(isas):
4286143Snate@binkert.org        code('#define $0 $1', define(isa), i + 1)
4295517Snate@binkert.org    code()
4304382Sbinkertn@umich.edu
4314382Sbinkertn@umich.edu    # create an enum for any run-time determination of the ISA, we
4324762Snate@binkert.org    # reuse the same name as the namespaces
4334762Snate@binkert.org    code('enum class GPUArch {')
4344762Snate@binkert.org    for i,isa in enumerate(isas):
4354762Snate@binkert.org        if i + 1 == len(isas):
4364762Snate@binkert.org            code('  $0 = $1', namespace(isa), define(isa))
4375517Snate@binkert.org        else:
4385517Snate@binkert.org            code('  $0 = $1,', namespace(isa), define(isa))
4395517Snate@binkert.org    code('};')
4405517Snate@binkert.org
4415517Snate@binkert.org    code('''
4425517Snate@binkert.org
4435517Snate@binkert.org#define THE_GPU_ISA ${{define(target_gpu_isa)}}
4445517Snate@binkert.org#define TheGpuISA ${{namespace(target_gpu_isa)}}
4456143Snate@binkert.org#define THE_GPU_ISA_STR "${{target_gpu_isa}}"
4465517Snate@binkert.org
4475517Snate@binkert.org#endif // __CONFIG_THE_GPU_ISA_HH__''')
4485517Snate@binkert.org
4495517Snate@binkert.org    code.write(str(target[0]))
4505517Snate@binkert.org
4515517Snate@binkert.orgenv.Command('config/the_gpu_isa.hh', map(Value, all_gpu_isa_list),
4525517Snate@binkert.org            MakeAction(makeTheGPUISA, Transform("CFG ISA", 0)))
4535517Snate@binkert.org
4545517Snate@binkert.org########################################################################
4555517Snate@binkert.org#
4566143Snate@binkert.org# Prevent any SimObjects from being added after this point, they
4575517Snate@binkert.org# should all have been added in the SConscripts above
4585517Snate@binkert.org#
4595517Snate@binkert.orgSimObject.fixed = True
4605517Snate@binkert.org
4615517Snate@binkert.orgclass DictImporter(object):
4625517Snate@binkert.org    '''This importer takes a dictionary of arbitrary module names that
4635517Snate@binkert.org    map to arbitrary filenames.'''
4645517Snate@binkert.org    def __init__(self, modules):
4655517Snate@binkert.org        self.modules = modules
4665517Snate@binkert.org        self.installed = set()
4675517Snate@binkert.org
4685517Snate@binkert.org    def __del__(self):
4695517Snate@binkert.org        self.unload()
4705517Snate@binkert.org
4715517Snate@binkert.org    def unload(self):
4725517Snate@binkert.org        import sys
4735517Snate@binkert.org        for module in self.installed:
4745517Snate@binkert.org            del sys.modules[module]
4755517Snate@binkert.org        self.installed = set()
4766143Snate@binkert.org
4775517Snate@binkert.org    def find_module(self, fullname, path):
4784762Snate@binkert.org        if fullname == 'm5.defines':
4794762Snate@binkert.org            return self
4806143Snate@binkert.org
4816143Snate@binkert.org        if fullname == 'm5.objects':
4826143Snate@binkert.org            return self
4834762Snate@binkert.org
4844762Snate@binkert.org        if fullname.startswith('_m5'):
4854762Snate@binkert.org            return None
4865517Snate@binkert.org
4874762Snate@binkert.org        source = self.modules.get(fullname, None)
4884762Snate@binkert.org        if source is not None and fullname.startswith('m5.objects'):
4894762Snate@binkert.org            return self
4905463Snate@binkert.org
4915517Snate@binkert.org        return None
4924762Snate@binkert.org
4934762Snate@binkert.org    def load_module(self, fullname):
4944762Snate@binkert.org        mod = imp.new_module(fullname)
4954762Snate@binkert.org        sys.modules[fullname] = mod
4964762Snate@binkert.org        self.installed.add(fullname)
4974762Snate@binkert.org
4985463Snate@binkert.org        mod.__loader__ = self
4995517Snate@binkert.org        if fullname == 'm5.objects':
5004762Snate@binkert.org            mod.__path__ = fullname.split('.')
5014762Snate@binkert.org            return mod
5024762Snate@binkert.org
5036143Snate@binkert.org        if fullname == 'm5.defines':
5046143Snate@binkert.org            mod.__dict__['buildEnv'] = m5.util.SmartDict(build_env)
5056143Snate@binkert.org            return mod
5064762Snate@binkert.org
5074762Snate@binkert.org        source = self.modules[fullname]
5085517Snate@binkert.org        if source.modname == '__init__':
5094762Snate@binkert.org            mod.__path__ = source.modpath
5104762Snate@binkert.org        mod.__file__ = source.abspath
5114762Snate@binkert.org
5124762Snate@binkert.org        exec file(source.abspath, 'r') in mod.__dict__
5135517Snate@binkert.org
5144762Snate@binkert.org        return mod
5154762Snate@binkert.org
5164762Snate@binkert.orgimport m5.SimObject
5174762Snate@binkert.orgimport m5.params
5185517Snate@binkert.orgfrom m5.util import code_formatter
5195517Snate@binkert.org
5205517Snate@binkert.orgm5.SimObject.clear()
5215517Snate@binkert.orgm5.params.clear()
5225517Snate@binkert.org
5235517Snate@binkert.org# install the python importer so we can grab stuff from the source
5245517Snate@binkert.org# tree itself.  We can't have SimObjects added after this point or
5255517Snate@binkert.org# else we won't know about them for the rest of the stuff.
5265517Snate@binkert.orgimporter = DictImporter(PySource.modules)
5275517Snate@binkert.orgsys.meta_path[0:0] = [ importer ]
5285517Snate@binkert.org
5295517Snate@binkert.org# import all sim objects so we can populate the all_objects list
5305517Snate@binkert.org# make sure that we're working with a list, then let's sort it
5315517Snate@binkert.orgfor modname in SimObject.modnames:
5325517Snate@binkert.org    exec('from m5.objects import %s' % modname)
5335517Snate@binkert.org
5345517Snate@binkert.org# we need to unload all of the currently imported modules so that they
5355517Snate@binkert.org# will be re-imported the next time the sconscript is run
5365517Snate@binkert.orgimporter.unload()
5375517Snate@binkert.orgsys.meta_path.remove(importer)
5385517Snate@binkert.org
5395517Snate@binkert.orgsim_objects = m5.SimObject.allClasses
5405517Snate@binkert.orgall_enums = m5.params.allEnums
5415517Snate@binkert.org
5425517Snate@binkert.orgfor name,obj in sorted(sim_objects.iteritems()):
5435517Snate@binkert.org    for param in obj._params.local.values():
5445517Snate@binkert.org        # load the ptype attribute now because it depends on the
5455517Snate@binkert.org        # current version of SimObject.allClasses, but when scons
5465517Snate@binkert.org        # actually uses the value, all versions of
5475517Snate@binkert.org        # SimObject.allClasses will have been loaded
5485517Snate@binkert.org        param.ptype
5495517Snate@binkert.org
5505517Snate@binkert.org########################################################################
5515517Snate@binkert.org#
5525517Snate@binkert.org# calculate extra dependencies
5535517Snate@binkert.org#
5545517Snate@binkert.orgmodule_depends = ["m5", "m5.SimObject", "m5.params"]
5555517Snate@binkert.orgdepends = [ PySource.modules[dep].snode for dep in module_depends ]
5565517Snate@binkert.orgdepends.sort(key = lambda x: x.name)
5575517Snate@binkert.org
5585517Snate@binkert.org########################################################################
5595517Snate@binkert.org#
5605517Snate@binkert.org# Commands for the basic automatically generated python files
5615517Snate@binkert.org#
5625517Snate@binkert.org
5635517Snate@binkert.org# Generate Python file containing a dict specifying the current
5645517Snate@binkert.org# buildEnv flags.
5655517Snate@binkert.orgdef makeDefinesPyFile(target, source, env):
5665517Snate@binkert.org    build_env = source[0].get_contents()
5675517Snate@binkert.org
5685517Snate@binkert.org    code = code_formatter()
5695517Snate@binkert.org    code("""
5705517Snate@binkert.orgimport _m5.core
5715517Snate@binkert.orgimport m5.util
5725517Snate@binkert.org
5735517Snate@binkert.orgbuildEnv = m5.util.SmartDict($build_env)
5745517Snate@binkert.org
5755517Snate@binkert.orgcompileDate = _m5.core.compileDate
5765517Snate@binkert.org_globals = globals()
5775517Snate@binkert.orgfor key,val in _m5.core.__dict__.iteritems():
5785517Snate@binkert.org    if key.startswith('flag_'):
5795517Snate@binkert.org        flag = key[5:]
5805517Snate@binkert.org        _globals[flag] = val
5815517Snate@binkert.orgdel _globals
5825517Snate@binkert.org""")
5835517Snate@binkert.org    code.write(target[0].abspath)
5845610Snate@binkert.org
5855623Snate@binkert.orgdefines_info = Value(build_env)
5865623Snate@binkert.org# Generate a file with all of the compile options in it
5875623Snate@binkert.orgenv.Command('python/m5/defines.py', defines_info,
5885610Snate@binkert.org            MakeAction(makeDefinesPyFile, Transform("DEFINES", 0)))
5895517Snate@binkert.orgPySource('m5', 'python/m5/defines.py')
5905623Snate@binkert.org
5915623Snate@binkert.org# Generate python file containing info about the M5 source code
5925623Snate@binkert.orgdef makeInfoPyFile(target, source, env):
5935623Snate@binkert.org    code = code_formatter()
5945623Snate@binkert.org    for src in source:
5955623Snate@binkert.org        data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
5965623Snate@binkert.org        code('$src = ${{repr(data)}}')
5975517Snate@binkert.org    code.write(str(target[0]))
5985610Snate@binkert.org
5995610Snate@binkert.org# Generate a file that wraps the basic top level files
6005610Snate@binkert.orgenv.Command('python/m5/info.py',
6015610Snate@binkert.org            [ '#/COPYING', '#/LICENSE', '#/README', ],
6025517Snate@binkert.org            MakeAction(makeInfoPyFile, Transform("INFO")))
6035517Snate@binkert.orgPySource('m5', 'python/m5/info.py')
6045610Snate@binkert.org
6055610Snate@binkert.org########################################################################
6065517Snate@binkert.org#
6075517Snate@binkert.org# Create all of the SimObject param headers and enum headers
6085517Snate@binkert.org#
6095517Snate@binkert.org
6105517Snate@binkert.orgdef createSimObjectParamStruct(target, source, env):
6115517Snate@binkert.org    assert len(target) == 1 and len(source) == 1
6125517Snate@binkert.org
6135517Snate@binkert.org    name = source[0].get_text_contents()
6145517Snate@binkert.org    obj = sim_objects[name]
6155517Snate@binkert.org
6164762Snate@binkert.org    code = code_formatter()
6176143Snate@binkert.org    obj.cxx_param_decl(code)
6186143Snate@binkert.org    code.write(target[0].abspath)
6195463Snate@binkert.org
6204762Snate@binkert.orgdef createSimObjectCxxConfig(is_header):
6214762Snate@binkert.org    def body(target, source, env):
6224762Snate@binkert.org        assert len(target) == 1 and len(source) == 1
6236143Snate@binkert.org
6246143Snate@binkert.org        name = str(source[0].get_contents())
6254382Sbinkertn@umich.edu        obj = sim_objects[name]
6264382Sbinkertn@umich.edu
6276143Snate@binkert.org        code = code_formatter()
6286143Snate@binkert.org        obj.cxx_config_param_file(code, is_header)
6294382Sbinkertn@umich.edu        code.write(target[0].abspath)
6304762Snate@binkert.org    return body
6315517Snate@binkert.org
6325517Snate@binkert.orgdef createEnumStrings(target, source, env):
6335517Snate@binkert.org    assert len(target) == 1 and len(source) == 2
6345517Snate@binkert.org
6355517Snate@binkert.org    name = source[0].get_text_contents()
6365517Snate@binkert.org    use_python = source[1].read()
6375522Snate@binkert.org    obj = all_enums[name]
6385517Snate@binkert.org
6395517Snate@binkert.org    code = code_formatter()
6405517Snate@binkert.org    obj.cxx_def(code)
6415517Snate@binkert.org    if use_python:
6425517Snate@binkert.org        obj.pybind_def(code)
6436143Snate@binkert.org    code.write(target[0].abspath)
6446143Snate@binkert.org
6456143Snate@binkert.orgdef createEnumDecls(target, source, env):
6465522Snate@binkert.org    assert len(target) == 1 and len(source) == 1
6474382Sbinkertn@umich.edu
6486229Snate@binkert.org    name = source[0].get_text_contents()
6496229Snate@binkert.org    obj = all_enums[name]
6506229Snate@binkert.org
6516229Snate@binkert.org    code = code_formatter()
6526229Snate@binkert.org    obj.cxx_decl(code)
6536229Snate@binkert.org    code.write(target[0].abspath)
6546229Snate@binkert.org
6556229Snate@binkert.orgdef createSimObjectPyBindWrapper(target, source, env):
6566229Snate@binkert.org    name = source[0].get_text_contents()
6576229Snate@binkert.org    obj = sim_objects[name]
6586229Snate@binkert.org
6596229Snate@binkert.org    code = code_formatter()
6606229Snate@binkert.org    obj.pybind_decl(code)
6616229Snate@binkert.org    code.write(target[0].abspath)
6626229Snate@binkert.org
6636229Snate@binkert.org# Generate all of the SimObject param C++ struct header files
6646229Snate@binkert.orgparams_hh_files = []
6656229Snate@binkert.orgfor name,simobj in sorted(sim_objects.iteritems()):
6666229Snate@binkert.org    py_source = PySource.modules[simobj.__module__]
6676229Snate@binkert.org    extra_deps = [ py_source.tnode ]
6686229Snate@binkert.org
6695192Ssaidi@eecs.umich.edu    hh_file = File('params/%s.hh' % name)
6705517Snate@binkert.org    params_hh_files.append(hh_file)
6715517Snate@binkert.org    env.Command(hh_file, Value(name),
6725517Snate@binkert.org                MakeAction(createSimObjectParamStruct, Transform("SO PARAM")))
6735517Snate@binkert.org    env.Depends(hh_file, depends + extra_deps)
6746229Snate@binkert.org
6756229Snate@binkert.org# C++ parameter description files
6765799Snate@binkert.orgif GetOption('with_cxx_config'):
6775799Snate@binkert.org    for name,simobj in sorted(sim_objects.iteritems()):
6785517Snate@binkert.org        py_source = PySource.modules[simobj.__module__]
6795517Snate@binkert.org        extra_deps = [ py_source.tnode ]
6805517Snate@binkert.org
6815517Snate@binkert.org        cxx_config_hh_file = File('cxx_config/%s.hh' % name)
6825517Snate@binkert.org        cxx_config_cc_file = File('cxx_config/%s.cc' % name)
6835517Snate@binkert.org        env.Command(cxx_config_hh_file, Value(name),
6845799Snate@binkert.org                    MakeAction(createSimObjectCxxConfig(True),
6855517Snate@binkert.org                    Transform("CXXCPRHH")))
6865517Snate@binkert.org        env.Command(cxx_config_cc_file, Value(name),
6875517Snate@binkert.org                    MakeAction(createSimObjectCxxConfig(False),
6885517Snate@binkert.org                    Transform("CXXCPRCC")))
6895517Snate@binkert.org        env.Depends(cxx_config_hh_file, depends + extra_deps +
6905517Snate@binkert.org                    [File('params/%s.hh' % name), File('sim/cxx_config.hh')])
6915517Snate@binkert.org        env.Depends(cxx_config_cc_file, depends + extra_deps +
6925799Snate@binkert.org                    [cxx_config_hh_file])
6935517Snate@binkert.org        Source(cxx_config_cc_file)
6945517Snate@binkert.org
6955799Snate@binkert.org    cxx_config_init_cc_file = File('cxx_config/init.cc')
6965517Snate@binkert.org
6975517Snate@binkert.org    def createCxxConfigInitCC(target, source, env):
6985517Snate@binkert.org        assert len(target) == 1 and len(source) == 1
6995517Snate@binkert.org
7005517Snate@binkert.org        code = code_formatter()
7015517Snate@binkert.org
7025517Snate@binkert.org        for name,simobj in sorted(sim_objects.iteritems()):
7035517Snate@binkert.org            if not hasattr(simobj, 'abstract') or not simobj.abstract:
7045799Snate@binkert.org                code('#include "cxx_config/${name}.hh"')
7055517Snate@binkert.org        code()
7065517Snate@binkert.org        code('void cxxConfigInit()')
7075517Snate@binkert.org        code('{')
7085517Snate@binkert.org        code.indent()
7095517Snate@binkert.org        for name,simobj in sorted(sim_objects.iteritems()):
7105517Snate@binkert.org            not_abstract = not hasattr(simobj, 'abstract') or \
7115517Snate@binkert.org                not simobj.abstract
7125517Snate@binkert.org            if not_abstract and 'type' in simobj.__dict__:
7135517Snate@binkert.org                code('cxx_config_directory["${name}"] = '
7145517Snate@binkert.org                     '${name}CxxConfigParams::makeDirectoryEntry();')
7155517Snate@binkert.org        code.dedent()
7165517Snate@binkert.org        code('}')
7176229Snate@binkert.org        code.write(target[0].abspath)
7185517Snate@binkert.org
7195517Snate@binkert.org    py_source = PySource.modules[simobj.__module__]
7205517Snate@binkert.org    extra_deps = [ py_source.tnode ]
7215517Snate@binkert.org    env.Command(cxx_config_init_cc_file, Value(name),
7225517Snate@binkert.org        MakeAction(createCxxConfigInitCC, Transform("CXXCINIT")))
7235517Snate@binkert.org    cxx_param_hh_files = ["cxx_config/%s.hh" % simobj
7245517Snate@binkert.org        for name,simobj in sorted(sim_objects.iteritems())
7255517Snate@binkert.org        if not hasattr(simobj, 'abstract') or not simobj.abstract]
7265517Snate@binkert.org    Depends(cxx_config_init_cc_file, cxx_param_hh_files +
7275517Snate@binkert.org            [File('sim/cxx_config.hh')])
7285517Snate@binkert.org    Source(cxx_config_init_cc_file)
7295517Snate@binkert.org
7305517Snate@binkert.org# Generate all enum header files
7315517Snate@binkert.orgfor name,enum in sorted(all_enums.iteritems()):
7325517Snate@binkert.org    py_source = PySource.modules[enum.__module__]
7335517Snate@binkert.org    extra_deps = [ py_source.tnode ]
7345517Snate@binkert.org
7355517Snate@binkert.org    cc_file = File('enums/%s.cc' % name)
7365517Snate@binkert.org    env.Command(cc_file, [Value(name), Value(env['USE_PYTHON'])],
7375517Snate@binkert.org                MakeAction(createEnumStrings, Transform("ENUM STR")))
7385517Snate@binkert.org    env.Depends(cc_file, depends + extra_deps)
7395517Snate@binkert.org    Source(cc_file)
7405517Snate@binkert.org
7415517Snate@binkert.org    hh_file = File('enums/%s.hh' % name)
7425517Snate@binkert.org    env.Command(hh_file, Value(name),
7435517Snate@binkert.org                MakeAction(createEnumDecls, Transform("ENUMDECL")))
7445517Snate@binkert.org    env.Depends(hh_file, depends + extra_deps)
7455517Snate@binkert.org
7465517Snate@binkert.org# Generate SimObject Python bindings wrapper files
7475517Snate@binkert.orgif env['USE_PYTHON']:
7485517Snate@binkert.org    for name,simobj in sorted(sim_objects.iteritems()):
7495517Snate@binkert.org        py_source = PySource.modules[simobj.__module__]
7505517Snate@binkert.org        extra_deps = [ py_source.tnode ]
7515517Snate@binkert.org        cc_file = File('python/_m5/param_%s.cc' % name)
7525517Snate@binkert.org        env.Command(cc_file, Value(name),
7535517Snate@binkert.org                    MakeAction(createSimObjectPyBindWrapper,
7545517Snate@binkert.org                               Transform("SO PyBind")))
7555517Snate@binkert.org        env.Depends(cc_file, depends + extra_deps)
7565517Snate@binkert.org        Source(cc_file)
7575517Snate@binkert.org
7585517Snate@binkert.org# Build all protocol buffers if we have got protoc and protobuf available
7595517Snate@binkert.orgif env['HAVE_PROTOBUF']:
7605517Snate@binkert.org    for proto in ProtoBuf.all:
7615517Snate@binkert.org        # Use both the source and header as the target, and the .proto
7625517Snate@binkert.org        # file as the source. When executing the protoc compiler, also
7635517Snate@binkert.org        # specify the proto_path to avoid having the generated files
7645517Snate@binkert.org        # include the path.
7655517Snate@binkert.org        env.Command([proto.cc_file, proto.hh_file], proto.tnode,
7665517Snate@binkert.org                    MakeAction('$PROTOC --cpp_out ${TARGET.dir} '
7675517Snate@binkert.org                               '--proto_path ${SOURCE.dir} $SOURCE',
7685517Snate@binkert.org                               Transform("PROTOC")))
7695517Snate@binkert.org
7705517Snate@binkert.org        # Add the C++ source file
7715517Snate@binkert.org        Source(proto.cc_file, **proto.guards)
7725517Snate@binkert.orgelif ProtoBuf.all:
7735517Snate@binkert.org    print 'Got protobuf to build, but lacks support!'
7745517Snate@binkert.org    Exit(1)
7755517Snate@binkert.org
7765517Snate@binkert.org#
7775517Snate@binkert.org# Handle debug flags
7785517Snate@binkert.org#
7795517Snate@binkert.orgdef makeDebugFlagCC(target, source, env):
7805517Snate@binkert.org    assert(len(target) == 1 and len(source) == 1)
7815517Snate@binkert.org
7825517Snate@binkert.org    code = code_formatter()
7835517Snate@binkert.org
7845517Snate@binkert.org    # delay definition of CompoundFlags until after all the definition
7855517Snate@binkert.org    # of all constituent SimpleFlags
7865517Snate@binkert.org    comp_code = code_formatter()
7875517Snate@binkert.org
7885517Snate@binkert.org    # file header
7895517Snate@binkert.org    code('''
7906229Snate@binkert.org/*
7915517Snate@binkert.org * DO NOT EDIT THIS FILE! Automatically generated by SCons.
7925517Snate@binkert.org */
7935517Snate@binkert.org
7945517Snate@binkert.org#include "base/debug.hh"
7955517Snate@binkert.org
7965517Snate@binkert.orgnamespace Debug {
7975517Snate@binkert.org
7985517Snate@binkert.org''')
7995517Snate@binkert.org
8005517Snate@binkert.org    for name, flag in sorted(source[0].read().iteritems()):
8015517Snate@binkert.org        n, compound, desc = flag
8025517Snate@binkert.org        assert n == name
8035517Snate@binkert.org
8045517Snate@binkert.org        if not compound:
8055517Snate@binkert.org            code('SimpleFlag $name("$name", "$desc");')
8065517Snate@binkert.org        else:
8075517Snate@binkert.org            comp_code('CompoundFlag $name("$name", "$desc",')
8085517Snate@binkert.org            comp_code.indent()
8095517Snate@binkert.org            last = len(compound) - 1
8105517Snate@binkert.org            for i,flag in enumerate(compound):
8115517Snate@binkert.org                if i != last:
8125517Snate@binkert.org                    comp_code('&$flag,')
8135517Snate@binkert.org                else:
8145517Snate@binkert.org                    comp_code('&$flag);')
8155517Snate@binkert.org            comp_code.dedent()
8165517Snate@binkert.org
8175517Snate@binkert.org    code.append(comp_code)
8185517Snate@binkert.org    code()
8195517Snate@binkert.org    code('} // namespace Debug')
8205517Snate@binkert.org
8215517Snate@binkert.org    code.write(str(target[0]))
8225517Snate@binkert.org
8235517Snate@binkert.orgdef makeDebugFlagHH(target, source, env):
8245517Snate@binkert.org    assert(len(target) == 1 and len(source) == 1)
8255517Snate@binkert.org
8265517Snate@binkert.org    val = eval(source[0].get_contents())
8275517Snate@binkert.org    name, compound, desc = val
8285517Snate@binkert.org
8295517Snate@binkert.org    code = code_formatter()
8305517Snate@binkert.org
8315517Snate@binkert.org    # file header boilerplate
8325517Snate@binkert.org    code('''\
8335517Snate@binkert.org/*
8345517Snate@binkert.org * DO NOT EDIT THIS FILE! Automatically generated by SCons.
8355517Snate@binkert.org */
8365517Snate@binkert.org
8375517Snate@binkert.org#ifndef __DEBUG_${name}_HH__
8385517Snate@binkert.org#define __DEBUG_${name}_HH__
8395517Snate@binkert.org
8405517Snate@binkert.orgnamespace Debug {
8415517Snate@binkert.org''')
8425517Snate@binkert.org
8435517Snate@binkert.org    if compound:
8445517Snate@binkert.org        code('class CompoundFlag;')
8455517Snate@binkert.org    code('class SimpleFlag;')
8465517Snate@binkert.org
8475517Snate@binkert.org    if compound:
8485517Snate@binkert.org        code('extern CompoundFlag $name;')
8495517Snate@binkert.org        for flag in compound:
8505517Snate@binkert.org            code('extern SimpleFlag $flag;')
8515517Snate@binkert.org    else:
8526143Snate@binkert.org        code('extern SimpleFlag $name;')
8535517Snate@binkert.org
8545192Ssaidi@eecs.umich.edu    code('''
8555192Ssaidi@eecs.umich.edu}
8565517Snate@binkert.org
8575517Snate@binkert.org#endif // __DEBUG_${name}_HH__
8585192Ssaidi@eecs.umich.edu''')
8595192Ssaidi@eecs.umich.edu
8605522Snate@binkert.org    code.write(str(target[0]))
8615522Snate@binkert.org
8625522Snate@binkert.orgfor name,flag in sorted(debug_flags.iteritems()):
8635522Snate@binkert.org    n, compound, desc = flag
8645522Snate@binkert.org    assert n == name
8655522Snate@binkert.org
8665522Snate@binkert.org    hh_file = 'debug/%s.hh' % name
8675522Snate@binkert.org    env.Command(hh_file, Value(flag),
8685522Snate@binkert.org                MakeAction(makeDebugFlagHH, Transform("TRACING", 0)))
8695522Snate@binkert.org
8705517Snate@binkert.orgenv.Command('debug/flags.cc', Value(debug_flags),
8715522Snate@binkert.org            MakeAction(makeDebugFlagCC, Transform("TRACING", 0)))
8725522Snate@binkert.orgSource('debug/flags.cc')
8735517Snate@binkert.org
8746143Snate@binkert.org# version tags
8755604Snate@binkert.orgtags = \
8765522Snate@binkert.orgenv.Command('sim/tags.cc', None,
8775522Snate@binkert.org            MakeAction('util/cpt_upgrader.py --get-cc-file > $TARGET',
8785522Snate@binkert.org                       Transform("VER TAGS")))
8795517Snate@binkert.orgenv.AlwaysBuild(tags)
8805522Snate@binkert.org
8815522Snate@binkert.org# Embed python files.  All .py files that have been indicated by a
8825522Snate@binkert.org# PySource() call in a SConscript need to be embedded into the M5
8835522Snate@binkert.org# library.  To do that, we compile the file to byte code, marshal the
8845522Snate@binkert.org# byte code, compress it, and then generate a c++ file that
8855522Snate@binkert.org# inserts the result into an array.
8865522Snate@binkert.orgdef embedPyFile(target, source, env):
8875522Snate@binkert.org    def c_str(string):
8885522Snate@binkert.org        if string is None:
8895522Snate@binkert.org            return "0"
8905522Snate@binkert.org        return '"%s"' % string
8915522Snate@binkert.org
8925522Snate@binkert.org    '''Action function to compile a .py into a code object, marshal
8935522Snate@binkert.org    it, compress it, and stick it into an asm file so the code appears
8945522Snate@binkert.org    as just bytes with a label in the data section'''
8955522Snate@binkert.org
8965522Snate@binkert.org    src = file(str(source[0]), 'r').read()
8975522Snate@binkert.org
8985522Snate@binkert.org    pysource = PySource.tnodes[source[0]]
8996143Snate@binkert.org    compiled = compile(src, pysource.abspath, 'exec')
9005522Snate@binkert.org    marshalled = marshal.dumps(compiled)
9015522Snate@binkert.org    compressed = zlib.compress(marshalled)
9024382Sbinkertn@umich.edu    data = compressed
9035522Snate@binkert.org    sym = pysource.symname
9045522Snate@binkert.org
9055522Snate@binkert.org    code = code_formatter()
9065522Snate@binkert.org    code('''\
9075522Snate@binkert.org#include "sim/init.hh"
9085522Snate@binkert.org
9095522Snate@binkert.orgnamespace {
9104382Sbinkertn@umich.edu
9115522Snate@binkert.orgconst uint8_t data_${sym}[] = {
9126143Snate@binkert.org''')
9135522Snate@binkert.org    code.indent()
9145522Snate@binkert.org    step = 16
9155522Snate@binkert.org    for i in xrange(0, len(data), step):
9165522Snate@binkert.org        x = array.array('B', data[i:i+step])
9175522Snate@binkert.org        code(''.join('%d,' % d for d in x))
9185522Snate@binkert.org    code.dedent()
9195522Snate@binkert.org
9205522Snate@binkert.org    code('''};
9215522Snate@binkert.org
9225522Snate@binkert.orgEmbeddedPython embedded_${sym}(
9235522Snate@binkert.org    ${{c_str(pysource.arcname)}},
9245522Snate@binkert.org    ${{c_str(pysource.abspath)}},
9255522Snate@binkert.org    ${{c_str(pysource.modpath)}},
9265522Snate@binkert.org    data_${sym},
9275522Snate@binkert.org    ${{len(data)}},
9285522Snate@binkert.org    ${{len(marshalled)}});
9295522Snate@binkert.org
9305522Snate@binkert.org} // anonymous namespace
9315522Snate@binkert.org''')
9325522Snate@binkert.org    code.write(str(target[0]))
9335522Snate@binkert.org
9345522Snate@binkert.orgfor source in PySource.all:
9355522Snate@binkert.org    env.Command(source.cpp, source.tnode,
9365522Snate@binkert.org                MakeAction(embedPyFile, Transform("EMBED PY")))
9375522Snate@binkert.org    Source(source.cpp, skip_no_python=True)
9385522Snate@binkert.org
9396143Snate@binkert.org########################################################################
9406143Snate@binkert.org#
9416143Snate@binkert.org# Define binaries.  Each different build type (debug, opt, etc.) gets
9426143Snate@binkert.org# a slightly different build environment.
9435522Snate@binkert.org#
9444382Sbinkertn@umich.edu
9454382Sbinkertn@umich.edu# List of constructed environments to pass back to SConstruct
9464382Sbinkertn@umich.edudate_source = Source('base/date.cc', skip_lib=True)
9474382Sbinkertn@umich.edu
9484382Sbinkertn@umich.edu# Function to create a new build environment as clone of current
9494382Sbinkertn@umich.edu# environment 'env' with modified object suffix and optional stripped
9504382Sbinkertn@umich.edu# binary.  Additional keyword arguments are appended to corresponding
9514382Sbinkertn@umich.edu# build environment vars.
9524382Sbinkertn@umich.edudef makeEnv(env, label, objsfx, strip=False, disable_partial=False, **kwargs):
9534382Sbinkertn@umich.edu    # SCons doesn't know to append a library suffix when there is a '.' in the
9546143Snate@binkert.org    # name.  Use '_' instead.
955955SN/A    libname = 'gem5_' + label
9562655Sstever@eecs.umich.edu    exename = 'gem5.' + label
9572655Sstever@eecs.umich.edu    secondary_exename = 'm5.' + label
9582655Sstever@eecs.umich.edu
9592655Sstever@eecs.umich.edu    new_env = env.Clone(OBJSUFFIX=objsfx, SHOBJSUFFIX=objsfx + 's')
9602655Sstever@eecs.umich.edu    new_env.Label = label
9615601Snate@binkert.org    new_env.Append(**kwargs)
9625601Snate@binkert.org
9635601Snate@binkert.org    if env['GCC']:
9645601Snate@binkert.org        # The address sanitizer is available for gcc >= 4.8
9655522Snate@binkert.org        if GetOption('with_asan'):
9665863Snate@binkert.org            if GetOption('with_ubsan') and \
9675601Snate@binkert.org                    compareVersions(env['GCC_VERSION'], '4.9') >= 0:
9685601Snate@binkert.org                new_env.Append(CCFLAGS=['-fsanitize=address,undefined',
9695601Snate@binkert.org                                        '-fno-omit-frame-pointer'])
9705863Snate@binkert.org                new_env.Append(LINKFLAGS='-fsanitize=address,undefined')
9716143Snate@binkert.org            else:
9725559Snate@binkert.org                new_env.Append(CCFLAGS=['-fsanitize=address',
9735559Snate@binkert.org                                        '-fno-omit-frame-pointer'])
9745559Snate@binkert.org                new_env.Append(LINKFLAGS='-fsanitize=address')
9755559Snate@binkert.org        # Only gcc >= 4.9 supports UBSan, so check both the version
9765601Snate@binkert.org        # and the command-line option before adding the compiler and
9776143Snate@binkert.org        # linker flags.
9786143Snate@binkert.org        elif GetOption('with_ubsan') and \
9796143Snate@binkert.org                compareVersions(env['GCC_VERSION'], '4.9') >= 0:
9806143Snate@binkert.org            new_env.Append(CCFLAGS='-fsanitize=undefined')
9816143Snate@binkert.org            new_env.Append(LINKFLAGS='-fsanitize=undefined')
9826143Snate@binkert.org
9836143Snate@binkert.org
9846143Snate@binkert.org    if env['CLANG']:
9856143Snate@binkert.org        # We require clang >= 3.1, so there is no need to check any
9866143Snate@binkert.org        # versions here.
9876143Snate@binkert.org        if GetOption('with_ubsan'):
9886143Snate@binkert.org            if GetOption('with_asan'):
9896143Snate@binkert.org                new_env.Append(CCFLAGS=['-fsanitize=address,undefined',
9906143Snate@binkert.org                                        '-fno-omit-frame-pointer'])
9916143Snate@binkert.org                new_env.Append(LINKFLAGS='-fsanitize=address,undefined')
9926143Snate@binkert.org            else:
9936143Snate@binkert.org                new_env.Append(CCFLAGS='-fsanitize=undefined')
9946143Snate@binkert.org                new_env.Append(LINKFLAGS='-fsanitize=undefined')
9956143Snate@binkert.org
9966143Snate@binkert.org        elif GetOption('with_asan'):
9976143Snate@binkert.org            new_env.Append(CCFLAGS=['-fsanitize=address',
9986143Snate@binkert.org                                    '-fno-omit-frame-pointer'])
9996143Snate@binkert.org            new_env.Append(LINKFLAGS='-fsanitize=address')
10006143Snate@binkert.org
10016143Snate@binkert.org    werror_env = new_env.Clone()
10026143Snate@binkert.org    # Treat warnings as errors but white list some warnings that we
10036143Snate@binkert.org    # want to allow (e.g., deprecation warnings).
10046143Snate@binkert.org    werror_env.Append(CCFLAGS=['-Werror',
10056143Snate@binkert.org                               '-Wno-error=deprecated-declarations',
10066143Snate@binkert.org                               '-Wno-error=deprecated',
10076143Snate@binkert.org                               ])
10086143Snate@binkert.org
10096240Snate@binkert.org    def make_obj(source, static, extra_deps = None):
10105554Snate@binkert.org        '''This function adds the specified source to the correct
10115522Snate@binkert.org        build environment, and returns the corresponding SCons Object
10125522Snate@binkert.org        nodes'''
10135797Snate@binkert.org
10145797Snate@binkert.org        if source.Werror:
10155522Snate@binkert.org            env = werror_env
10165584Snate@binkert.org        else:
10176143Snate@binkert.org            env = new_env
10185862Snate@binkert.org
10195584Snate@binkert.org        if static:
10205601Snate@binkert.org            obj = env.StaticObject(source.tnode)
10216143Snate@binkert.org        else:
10226143Snate@binkert.org            obj = env.SharedObject(source.tnode)
10232655Sstever@eecs.umich.edu
10246143Snate@binkert.org        if extra_deps:
10256143Snate@binkert.org            env.Depends(obj, extra_deps)
10266143Snate@binkert.org
10276143Snate@binkert.org        return obj
10286143Snate@binkert.org
10294007Ssaidi@eecs.umich.edu    lib_guards = {'main': False, 'skip_lib': False}
10304596Sbinkertn@umich.edu
10314007Ssaidi@eecs.umich.edu    # Without Python, leave out all Python content from the library
10324596Sbinkertn@umich.edu    # builds.  The option doesn't affect gem5 built as a program
10336143Snate@binkert.org    if GetOption('without_python'):
10345522Snate@binkert.org        lib_guards['skip_no_python'] = False
10355601Snate@binkert.org
10365601Snate@binkert.org    static_objs = []
10372655Sstever@eecs.umich.edu    shared_objs = []
1038955SN/A    for s in guarded_source_iterator(Source.source_groups[None], **lib_guards):
10393918Ssaidi@eecs.umich.edu        static_objs.append(make_obj(s, True))
10403918Ssaidi@eecs.umich.edu        shared_objs.append(make_obj(s, False))
10413918Ssaidi@eecs.umich.edu
10423918Ssaidi@eecs.umich.edu    partial_objs = []
10433918Ssaidi@eecs.umich.edu    for group, all_srcs in Source.source_groups.iteritems():
10443918Ssaidi@eecs.umich.edu        # If these are the ungrouped source files, skip them.
10453918Ssaidi@eecs.umich.edu        if not group:
10463918Ssaidi@eecs.umich.edu            continue
10473918Ssaidi@eecs.umich.edu
10483918Ssaidi@eecs.umich.edu        # Get a list of the source files compatible with the current guards.
10493918Ssaidi@eecs.umich.edu        srcs = [ s for s in guarded_source_iterator(all_srcs, **lib_guards) ]
10503918Ssaidi@eecs.umich.edu        # If there aren't any left, skip this group.
10513918Ssaidi@eecs.umich.edu        if not srcs:
10523918Ssaidi@eecs.umich.edu            continue
10533940Ssaidi@eecs.umich.edu
10543940Ssaidi@eecs.umich.edu        # If partial linking is disabled, add these sources to the build
10553940Ssaidi@eecs.umich.edu        # directly, and short circuit this loop.
10563942Ssaidi@eecs.umich.edu        if disable_partial:
10573940Ssaidi@eecs.umich.edu            for s in srcs:
10583515Ssaidi@eecs.umich.edu                static_objs.append(make_obj(s, True))
10593918Ssaidi@eecs.umich.edu                shared_objs.append(make_obj(s, False))
10604762Snate@binkert.org            continue
10613515Ssaidi@eecs.umich.edu
10622655Sstever@eecs.umich.edu        # Set up the static partially linked objects.
10633918Ssaidi@eecs.umich.edu        source_objs = [ make_obj(s, True) for s in srcs ]
10643619Sbinkertn@umich.edu        file_name = new_env.subst("${OBJPREFIX}lib${OBJSUFFIX}.partial")
1065955SN/A        target = File(joinpath(group, file_name))
1066955SN/A        partial = env.PartialStatic(target=target, source=source_objs)
10672655Sstever@eecs.umich.edu        static_objs.append(partial)
10683918Ssaidi@eecs.umich.edu
10693619Sbinkertn@umich.edu        # Set up the shared partially linked objects.
1070955SN/A        source_objs = [ make_obj(s, False) for s in srcs ]
1071955SN/A        file_name = new_env.subst("${SHOBJPREFIX}lib${SHOBJSUFFIX}.partial")
10722655Sstever@eecs.umich.edu        target = File(joinpath(group, file_name))
10733918Ssaidi@eecs.umich.edu        partial = env.PartialShared(target=target, source=source_objs)
10743619Sbinkertn@umich.edu        shared_objs.append(partial)
1075955SN/A
1076955SN/A    static_date = make_obj(date_source, static=True, extra_deps=static_objs)
10772655Sstever@eecs.umich.edu    static_objs.append(static_date)
10783918Ssaidi@eecs.umich.edu
10793683Sstever@eecs.umich.edu    shared_date = make_obj(date_source, static=False, extra_deps=shared_objs)
10802655Sstever@eecs.umich.edu    shared_objs.append(shared_date)
10811869SN/A
10821869SN/A    # First make a library of everything but main() so other programs can
1083    # link against m5.
1084    static_lib = new_env.StaticLibrary(libname, static_objs)
1085    shared_lib = new_env.SharedLibrary(libname, shared_objs)
1086
1087    # Now link a stub with main() and the static library.
1088    main_objs = [ make_obj(s, True) for s in Source.get(main=True) ]
1089
1090    for test in UnitTest.all:
1091        flags = { test.target : True }
1092        test_sources = Source.get(**flags)
1093        test_objs = [ make_obj(s, static=True) for s in test_sources ]
1094        if test.main:
1095            test_objs += main_objs
1096        path = 'unittest/%s.%s' % (test.target, label)
1097        new_env.Program(path, test_objs + static_objs)
1098
1099    progname = exename
1100    if strip:
1101        progname += '.unstripped'
1102
1103    targets = new_env.Program(progname, main_objs + static_objs)
1104
1105    if strip:
1106        if sys.platform == 'sunos5':
1107            cmd = 'cp $SOURCE $TARGET; strip $TARGET'
1108        else:
1109            cmd = 'strip $SOURCE -o $TARGET'
1110        targets = new_env.Command(exename, progname,
1111                    MakeAction(cmd, Transform("STRIP")))
1112
1113    new_env.Command(secondary_exename, exename,
1114            MakeAction('ln $SOURCE $TARGET', Transform("HARDLINK")))
1115
1116    new_env.M5Binary = targets[0]
1117
1118    # Set up regression tests.
1119    SConscript(os.path.join(env.root.abspath, 'tests', 'SConscript'),
1120               variant_dir=Dir('tests').Dir(new_env.Label),
1121               exports={ 'env' : new_env }, duplicate=False)
1122
1123# Start out with the compiler flags common to all compilers,
1124# i.e. they all use -g for opt and -g -pg for prof
1125ccflags = {'debug' : [], 'opt' : ['-g'], 'fast' : [], 'prof' : ['-g', '-pg'],
1126           'perf' : ['-g']}
1127
1128# Start out with the linker flags common to all linkers, i.e. -pg for
1129# prof, and -lprofiler for perf. The -lprofile flag is surrounded by
1130# no-as-needed and as-needed as the binutils linker is too clever and
1131# simply doesn't link to the library otherwise.
1132ldflags = {'debug' : [], 'opt' : [], 'fast' : [], 'prof' : ['-pg'],
1133           'perf' : ['-Wl,--no-as-needed', '-lprofiler', '-Wl,--as-needed']}
1134
1135# For Link Time Optimization, the optimisation flags used to compile
1136# individual files are decoupled from those used at link time
1137# (i.e. you can compile with -O3 and perform LTO with -O0), so we need
1138# to also update the linker flags based on the target.
1139if env['GCC']:
1140    if sys.platform == 'sunos5':
1141        ccflags['debug'] += ['-gstabs+']
1142    else:
1143        ccflags['debug'] += ['-ggdb3']
1144    ldflags['debug'] += ['-O0']
1145    # opt, fast, prof and perf all share the same cc flags, also add
1146    # the optimization to the ldflags as LTO defers the optimization
1147    # to link time
1148    for target in ['opt', 'fast', 'prof', 'perf']:
1149        ccflags[target] += ['-O3']
1150        ldflags[target] += ['-O3']
1151
1152    ccflags['fast'] += env['LTO_CCFLAGS']
1153    ldflags['fast'] += env['LTO_LDFLAGS']
1154elif env['CLANG']:
1155    ccflags['debug'] += ['-g', '-O0']
1156    # opt, fast, prof and perf all share the same cc flags
1157    for target in ['opt', 'fast', 'prof', 'perf']:
1158        ccflags[target] += ['-O3']
1159else:
1160    print 'Unknown compiler, please fix compiler options'
1161    Exit(1)
1162
1163
1164# To speed things up, we only instantiate the build environments we
1165# need.  We try to identify the needed environment for each target; if
1166# we can't, we fall back on instantiating all the environments just to
1167# be safe.
1168target_types = ['debug', 'opt', 'fast', 'prof', 'perf']
1169obj2target = {'do': 'debug', 'o': 'opt', 'fo': 'fast', 'po': 'prof',
1170              'gpo' : 'perf'}
1171
1172def identifyTarget(t):
1173    ext = t.split('.')[-1]
1174    if ext in target_types:
1175        return ext
1176    if obj2target.has_key(ext):
1177        return obj2target[ext]
1178    match = re.search(r'/tests/([^/]+)/', t)
1179    if match and match.group(1) in target_types:
1180        return match.group(1)
1181    return 'all'
1182
1183needed_envs = [identifyTarget(target) for target in BUILD_TARGETS]
1184if 'all' in needed_envs:
1185    needed_envs += target_types
1186
1187# Debug binary
1188if 'debug' in needed_envs:
1189    makeEnv(env, 'debug', '.do',
1190            CCFLAGS = Split(ccflags['debug']),
1191            CPPDEFINES = ['DEBUG', 'TRACING_ON=1'],
1192            LINKFLAGS = Split(ldflags['debug']))
1193
1194# Optimized binary
1195if 'opt' in needed_envs:
1196    makeEnv(env, 'opt', '.o',
1197            CCFLAGS = Split(ccflags['opt']),
1198            CPPDEFINES = ['TRACING_ON=1'],
1199            LINKFLAGS = Split(ldflags['opt']))
1200
1201# "Fast" binary
1202if 'fast' in needed_envs:
1203    disable_partial = \
1204            env.get('BROKEN_INCREMENTAL_LTO', False) and \
1205            GetOption('force_lto')
1206    makeEnv(env, 'fast', '.fo', strip = True,
1207            CCFLAGS = Split(ccflags['fast']),
1208            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1209            LINKFLAGS = Split(ldflags['fast']),
1210            disable_partial=disable_partial)
1211
1212# Profiled binary using gprof
1213if 'prof' in needed_envs:
1214    makeEnv(env, 'prof', '.po',
1215            CCFLAGS = Split(ccflags['prof']),
1216            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1217            LINKFLAGS = Split(ldflags['prof']))
1218
1219# Profiled binary using google-pprof
1220if 'perf' in needed_envs:
1221    makeEnv(env, 'perf', '.gpo',
1222            CCFLAGS = Split(ccflags['perf']),
1223            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1224            LINKFLAGS = Split(ldflags['perf']))
1225