SConscript revision 11802
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
3711974Sgabeblack@google.comimport sys
38955SN/Aimport zlib
395522Snate@binkert.org
404202Sbinkertn@umich.edufrom os.path import basename, dirname, exists, isdir, isfile, join as joinpath
415742Snate@binkert.org
42955SN/Aimport SCons
434381Sbinkertn@umich.edu
444381Sbinkertn@umich.edu# This file defines how to build a particular configuration of gem5
4512246Sgabeblack@google.com# based on variable settings in the 'env' build environment.
4612246Sgabeblack@google.com
478334Snate@binkert.orgImport('*')
48955SN/A
49955SN/A# Children need to see the environment
504202Sbinkertn@umich.eduExport('env')
51955SN/A
524382Sbinkertn@umich.edubuild_env = [(opt, env[opt]) for opt in export_vars]
534382Sbinkertn@umich.edu
544382Sbinkertn@umich.edufrom m5.util import code_formatter, compareVersions
556654Snate@binkert.org
565517Snate@binkert.org########################################################################
578614Sgblack@eecs.umich.edu# Code for adding source files of various types
587674Snate@binkert.org#
596143Snate@binkert.org# When specifying a source file of some type, a set of guards can be
606143Snate@binkert.org# specified for that file.  When get() is used to find the files, if
616143Snate@binkert.org# get specifies a set of filters, only files that match those filters
6212302Sgabeblack@google.com# will be accepted (unspecified filters on files are assumed to be
6312302Sgabeblack@google.com# false).  Current filters are:
6412302Sgabeblack@google.com#     main -- specifies the gem5 main() function
6512302Sgabeblack@google.com#     skip_lib -- do not put this file into the gem5 library
6612302Sgabeblack@google.com#     skip_no_python -- do not put this file into a no_python library
6712302Sgabeblack@google.com#       as it embeds compiled Python
6812302Sgabeblack@google.com#     <unittest> -- unit tests use filters based on the unit test name
6912302Sgabeblack@google.com#
7012302Sgabeblack@google.com# A parent can now be specified for a source file and default filter
7112302Sgabeblack@google.com# values will be retrieved recursively from parents (children override
7212302Sgabeblack@google.com# parents).
7312302Sgabeblack@google.com#
7412302Sgabeblack@google.comclass SourceMeta(type):
7512302Sgabeblack@google.com    '''Meta class for source files that keeps track of all files of a
7612302Sgabeblack@google.com    particular type and has a get function for finding all functions
7712302Sgabeblack@google.com    of a certain type that match a set of guards'''
7812302Sgabeblack@google.com    def __init__(cls, name, bases, dict):
7912302Sgabeblack@google.com        super(SourceMeta, cls).__init__(name, bases, dict)
8012302Sgabeblack@google.com        cls.all = []
8112302Sgabeblack@google.com
8212302Sgabeblack@google.com    def get(cls, **guards):
8312302Sgabeblack@google.com        '''Find all files that match the specified guards.  If a source
8412302Sgabeblack@google.com        file does not specify a flag, the default is False'''
8512302Sgabeblack@google.com        for src in cls.all:
8612302Sgabeblack@google.com            for flag,value in guards.iteritems():
8712302Sgabeblack@google.com                # if the flag is found and has a different value, skip
8812302Sgabeblack@google.com                # this file
8912302Sgabeblack@google.com                if src.all_guards.get(flag, False) != value:
9012302Sgabeblack@google.com                    break
9111983Sgabeblack@google.com            else:
926143Snate@binkert.org                yield src
938233Snate@binkert.org
9412302Sgabeblack@google.comclass SourceFile(object):
956143Snate@binkert.org    '''Base object that encapsulates the notion of a source file.
966143Snate@binkert.org    This includes, the source node, target node, various manipulations
9712302Sgabeblack@google.com    of those.  A source file also specifies a set of guards which
984762Snate@binkert.org    describing which builds the source file applies to.  A parent can
996143Snate@binkert.org    also be specified to get default guards from'''
1008233Snate@binkert.org    __metaclass__ = SourceMeta
1018233Snate@binkert.org    def __init__(self, source, parent=None, **guards):
10212302Sgabeblack@google.com        self.guards = guards
10312302Sgabeblack@google.com        self.parent = parent
1046143Snate@binkert.org
10512302Sgabeblack@google.com        tnode = source
10612302Sgabeblack@google.com        if not isinstance(source, SCons.Node.FS.File):
10712302Sgabeblack@google.com            tnode = File(source)
10812302Sgabeblack@google.com
10912302Sgabeblack@google.com        self.tnode = tnode
11012302Sgabeblack@google.com        self.snode = tnode.srcnode()
11112302Sgabeblack@google.com
11212302Sgabeblack@google.com        for base in type(self).__mro__:
11312302Sgabeblack@google.com            if issubclass(base, SourceFile):
11412302Sgabeblack@google.com                base.all.append(self)
1158233Snate@binkert.org
1166143Snate@binkert.org    @property
1176143Snate@binkert.org    def filename(self):
1186143Snate@binkert.org        return str(self.tnode)
1196143Snate@binkert.org
1206143Snate@binkert.org    @property
1216143Snate@binkert.org    def dirname(self):
1226143Snate@binkert.org        return dirname(self.filename)
1236143Snate@binkert.org
1246143Snate@binkert.org    @property
1257065Snate@binkert.org    def basename(self):
1266143Snate@binkert.org        return basename(self.filename)
1278233Snate@binkert.org
1288233Snate@binkert.org    @property
1298233Snate@binkert.org    def extname(self):
1308233Snate@binkert.org        index = self.basename.rfind('.')
1318233Snate@binkert.org        if index <= 0:
1328233Snate@binkert.org            # dot files aren't extensions
1338233Snate@binkert.org            return self.basename, None
1348233Snate@binkert.org
1358233Snate@binkert.org        return self.basename[:index], self.basename[index+1:]
1368233Snate@binkert.org
1378233Snate@binkert.org    @property
1388233Snate@binkert.org    def all_guards(self):
1398233Snate@binkert.org        '''find all guards for this object getting default values
1408233Snate@binkert.org        recursively from its parents'''
1418233Snate@binkert.org        guards = {}
1428233Snate@binkert.org        if self.parent:
1438233Snate@binkert.org            guards.update(self.parent.guards)
1448233Snate@binkert.org        guards.update(self.guards)
1458233Snate@binkert.org        return guards
1468233Snate@binkert.org
1478233Snate@binkert.org    def __lt__(self, other): return self.filename < other.filename
1486143Snate@binkert.org    def __le__(self, other): return self.filename <= other.filename
1496143Snate@binkert.org    def __gt__(self, other): return self.filename > other.filename
1506143Snate@binkert.org    def __ge__(self, other): return self.filename >= other.filename
1516143Snate@binkert.org    def __eq__(self, other): return self.filename == other.filename
1526143Snate@binkert.org    def __ne__(self, other): return self.filename != other.filename
1536143Snate@binkert.org
1549982Satgutier@umich.edu    @staticmethod
1556143Snate@binkert.org    def done():
15612302Sgabeblack@google.com        def disabled(cls, name, *ignored):
15712302Sgabeblack@google.com            raise RuntimeError("Additional SourceFile '%s'" % name,\
15812302Sgabeblack@google.com                  "declared, but targets deps are already fixed.")
15912302Sgabeblack@google.com        SourceFile.__init__ = disabled
16012302Sgabeblack@google.com
16112302Sgabeblack@google.com
16212302Sgabeblack@google.comclass Source(SourceFile):
16312302Sgabeblack@google.com    '''Add a c/c++ source file to the build'''
16411983Sgabeblack@google.com    def __init__(self, source, Werror=True, swig=False, **guards):
16511983Sgabeblack@google.com        '''specify the source file, and any guards'''
16611983Sgabeblack@google.com        super(Source, self).__init__(source, **guards)
16712302Sgabeblack@google.com
16812302Sgabeblack@google.com        self.Werror = Werror
16912302Sgabeblack@google.com        self.swig = swig
17012302Sgabeblack@google.com
17112302Sgabeblack@google.comclass PySource(SourceFile):
17212302Sgabeblack@google.com    '''Add a python source file to the named package'''
17311983Sgabeblack@google.com    invalid_sym_char = re.compile('[^A-z0-9_]')
1746143Snate@binkert.org    modules = {}
17512305Sgabeblack@google.com    tnodes = {}
17612302Sgabeblack@google.com    symnames = {}
17712302Sgabeblack@google.com
17812302Sgabeblack@google.com    def __init__(self, package, source, **guards):
1796143Snate@binkert.org        '''specify the python package, the source file, and any guards'''
1806143Snate@binkert.org        super(PySource, self).__init__(source, **guards)
1816143Snate@binkert.org
1825522Snate@binkert.org        modname,ext = self.extname
1836143Snate@binkert.org        assert ext == 'py'
1846143Snate@binkert.org
1856143Snate@binkert.org        if package:
1869982Satgutier@umich.edu            path = package.split('.')
18712302Sgabeblack@google.com        else:
18812302Sgabeblack@google.com            path = []
18912302Sgabeblack@google.com
1906143Snate@binkert.org        modpath = path[:]
1916143Snate@binkert.org        if modname != '__init__':
1926143Snate@binkert.org            modpath += [ modname ]
1936143Snate@binkert.org        modpath = '.'.join(modpath)
1945522Snate@binkert.org
1955522Snate@binkert.org        arcpath = path + [ self.basename ]
1965522Snate@binkert.org        abspath = self.snode.abspath
1975522Snate@binkert.org        if not exists(abspath):
1985604Snate@binkert.org            abspath = self.tnode.abspath
1995604Snate@binkert.org
2006143Snate@binkert.org        self.package = package
2016143Snate@binkert.org        self.modname = modname
2024762Snate@binkert.org        self.modpath = modpath
2034762Snate@binkert.org        self.arcname = joinpath(*arcpath)
2046143Snate@binkert.org        self.abspath = abspath
2056727Ssteve.reinhardt@amd.com        self.compiled = File(self.filename + 'c')
2066727Ssteve.reinhardt@amd.com        self.cpp = File(self.filename + '.cc')
2076727Ssteve.reinhardt@amd.com        self.symname = PySource.invalid_sym_char.sub('_', modpath)
2084762Snate@binkert.org
2096143Snate@binkert.org        PySource.modules[modpath] = self
2106143Snate@binkert.org        PySource.tnodes[self.tnode] = self
2116143Snate@binkert.org        PySource.symnames[self.symname] = self
2126143Snate@binkert.org
2136727Ssteve.reinhardt@amd.comclass SimObject(PySource):
2146143Snate@binkert.org    '''Add a SimObject python file as a python source object and add
2157674Snate@binkert.org    it to a list of sim object modules'''
2167674Snate@binkert.org
2175604Snate@binkert.org    fixed = False
2186143Snate@binkert.org    modnames = []
2196143Snate@binkert.org
2206143Snate@binkert.org    def __init__(self, source, **guards):
2214762Snate@binkert.org        '''Specify the source file and any guards (automatically in
2226143Snate@binkert.org        the m5.objects package)'''
2234762Snate@binkert.org        super(SimObject, self).__init__('m5.objects', source, **guards)
2244762Snate@binkert.org        if self.fixed:
2254762Snate@binkert.org            raise AttributeError, "Too late to call SimObject now."
2266143Snate@binkert.org
2276143Snate@binkert.org        bisect.insort_right(SimObject.modnames, self.modname)
2284762Snate@binkert.org
22912302Sgabeblack@google.comclass SwigSource(SourceFile):
23012302Sgabeblack@google.com    '''Add a swig file to build'''
2318233Snate@binkert.org
23212302Sgabeblack@google.com    def __init__(self, package, source, **guards):
2336143Snate@binkert.org        '''Specify the python package, the source file, and any guards'''
2346143Snate@binkert.org        super(SwigSource, self).__init__(source, skip_no_python=True, **guards)
2354762Snate@binkert.org
2366143Snate@binkert.org        modname,ext = self.extname
2374762Snate@binkert.org        assert ext == 'i'
2389396Sandreas.hansson@arm.com
2399396Sandreas.hansson@arm.com        self.package = package
2409396Sandreas.hansson@arm.com        self.module = modname
24112302Sgabeblack@google.com        cc_file = joinpath(self.dirname, modname + '_wrap.cc')
24212302Sgabeblack@google.com        py_file = joinpath(self.dirname, modname + '.py')
24312302Sgabeblack@google.com
2449396Sandreas.hansson@arm.com        self.cc_source = Source(cc_file, swig=True, parent=self, **guards)
2459396Sandreas.hansson@arm.com        self.py_source = PySource(package, py_file, parent=self, **guards)
2469396Sandreas.hansson@arm.com
2479396Sandreas.hansson@arm.comclass ProtoBuf(SourceFile):
2489396Sandreas.hansson@arm.com    '''Add a Protocol Buffer to build'''
2499396Sandreas.hansson@arm.com
2509396Sandreas.hansson@arm.com    def __init__(self, source, **guards):
2519930Sandreas.hansson@arm.com        '''Specify the source file, and any guards'''
2529930Sandreas.hansson@arm.com        super(ProtoBuf, self).__init__(source, **guards)
2539396Sandreas.hansson@arm.com
2548235Snate@binkert.org        # Get the file name and the extension
2558235Snate@binkert.org        modname,ext = self.extname
2566143Snate@binkert.org        assert ext == 'proto'
2578235Snate@binkert.org
2589003SAli.Saidi@ARM.com        # Currently, we stick to generating the C++ headers, so we
2598235Snate@binkert.org        # only need to track the source and header.
2608235Snate@binkert.org        self.cc_file = File(modname + '.pb.cc')
26112302Sgabeblack@google.com        self.hh_file = File(modname + '.pb.h')
2628235Snate@binkert.org
26312302Sgabeblack@google.comclass UnitTest(object):
2648235Snate@binkert.org    '''Create a UnitTest'''
2658235Snate@binkert.org
26612302Sgabeblack@google.com    all = []
2678235Snate@binkert.org    def __init__(self, target, *sources, **kwargs):
2688235Snate@binkert.org        '''Specify the target name and any sources.  Sources that are
2698235Snate@binkert.org        not SourceFiles are evalued with Source().  All files are
2708235Snate@binkert.org        guarded with a guard of the same name as the UnitTest
2719003SAli.Saidi@ARM.com        target.'''
2728235Snate@binkert.org
2735584Snate@binkert.org        srcs = []
2744382Sbinkertn@umich.edu        for src in sources:
2754202Sbinkertn@umich.edu            if not isinstance(src, SourceFile):
2764382Sbinkertn@umich.edu                src = Source(src, skip_lib=True)
2774382Sbinkertn@umich.edu            src.guards[target] = True
2789396Sandreas.hansson@arm.com            srcs.append(src)
2795584Snate@binkert.org
2804382Sbinkertn@umich.edu        self.sources = srcs
2814382Sbinkertn@umich.edu        self.target = target
2824382Sbinkertn@umich.edu        self.main = kwargs.get('main', False)
2838232Snate@binkert.org        UnitTest.all.append(self)
2845192Ssaidi@eecs.umich.edu
2858232Snate@binkert.org# Children should have access
2868232Snate@binkert.orgExport('Source')
2878232Snate@binkert.orgExport('PySource')
2885192Ssaidi@eecs.umich.eduExport('SimObject')
2898232Snate@binkert.orgExport('SwigSource')
2905192Ssaidi@eecs.umich.eduExport('ProtoBuf')
2915799Snate@binkert.orgExport('UnitTest')
2928232Snate@binkert.org
2935192Ssaidi@eecs.umich.edu########################################################################
2945192Ssaidi@eecs.umich.edu#
2955192Ssaidi@eecs.umich.edu# Debug Flags
2968232Snate@binkert.org#
2975192Ssaidi@eecs.umich.edudebug_flags = {}
2988232Snate@binkert.orgdef DebugFlag(name, desc=None):
2995192Ssaidi@eecs.umich.edu    if name in debug_flags:
3005192Ssaidi@eecs.umich.edu        raise AttributeError, "Flag %s already specified" % name
3015192Ssaidi@eecs.umich.edu    debug_flags[name] = (name, (), desc)
3025192Ssaidi@eecs.umich.edu
3034382Sbinkertn@umich.edudef CompoundFlag(name, flags, desc=None):
3044382Sbinkertn@umich.edu    if name in debug_flags:
3054382Sbinkertn@umich.edu        raise AttributeError, "Flag %s already specified" % name
3062667Sstever@eecs.umich.edu
3072667Sstever@eecs.umich.edu    compound = tuple(flags)
3082667Sstever@eecs.umich.edu    debug_flags[name] = (name, compound, desc)
3092667Sstever@eecs.umich.edu
3102667Sstever@eecs.umich.eduExport('DebugFlag')
3112667Sstever@eecs.umich.eduExport('CompoundFlag')
3125742Snate@binkert.org
3135742Snate@binkert.org########################################################################
3145742Snate@binkert.org#
3155793Snate@binkert.org# Set some compiler variables
3168334Snate@binkert.org#
3175793Snate@binkert.org
3185793Snate@binkert.org# Include file paths are rooted in this directory.  SCons will
3195793Snate@binkert.org# automatically expand '.' to refer to both the source directory and
3204382Sbinkertn@umich.edu# the corresponding build directory to pick up generated include
3214762Snate@binkert.org# files.
3225344Sstever@gmail.comenv.Append(CPPPATH=Dir('.'))
3234382Sbinkertn@umich.edu
3245341Sstever@gmail.comfor extra_dir in extras_dir_list:
3255742Snate@binkert.org    env.Append(CPPPATH=Dir(extra_dir))
3265742Snate@binkert.org
3275742Snate@binkert.org# Workaround for bug in SCons version > 0.97d20071212
3285742Snate@binkert.org# Scons bug id: 2006 gem5 Bug id: 308
3295742Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
3304762Snate@binkert.org    Dir(root[len(base_dir) + 1:])
3315742Snate@binkert.org
3325742Snate@binkert.org########################################################################
33311984Sgabeblack@google.com#
3347722Sgblack@eecs.umich.edu# Walk the tree and execute all SConscripts in subdirectories
3355742Snate@binkert.org#
3365742Snate@binkert.org
3375742Snate@binkert.orghere = Dir('.').srcnode().abspath
3389930Sandreas.hansson@arm.comfor root, dirs, files in os.walk(base_dir, topdown=True):
3399930Sandreas.hansson@arm.com    if root == here:
3409930Sandreas.hansson@arm.com        # we don't want to recurse back into this SConscript
3419930Sandreas.hansson@arm.com        continue
3429930Sandreas.hansson@arm.com
3435742Snate@binkert.org    if 'SConscript' in files:
3448242Sbradley.danofsky@amd.com        build_dir = joinpath(env['BUILDDIR'], root[len(base_dir) + 1:])
3458242Sbradley.danofsky@amd.com        SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3468242Sbradley.danofsky@amd.com
3478242Sbradley.danofsky@amd.comfor extra_dir in extras_dir_list:
3485341Sstever@gmail.com    prefix_len = len(dirname(extra_dir)) + 1
3495742Snate@binkert.org
3507722Sgblack@eecs.umich.edu    # Also add the corresponding build directory to pick up generated
3514773Snate@binkert.org    # include files.
3526108Snate@binkert.org    env.Append(CPPPATH=Dir(joinpath(env['BUILDDIR'], extra_dir[prefix_len:])))
3531858SN/A
3541085SN/A    for root, dirs, files in os.walk(extra_dir, topdown=True):
3556658Snate@binkert.org        # if build lives in the extras directory, don't walk down it
3566658Snate@binkert.org        if 'build' in dirs:
3577673Snate@binkert.org            dirs.remove('build')
3586658Snate@binkert.org
3596658Snate@binkert.org        if 'SConscript' in files:
36011308Santhony.gutierrez@amd.com            build_dir = joinpath(env['BUILDDIR'], root[prefix_len:])
3616658Snate@binkert.org            SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
36211308Santhony.gutierrez@amd.com
3636658Snate@binkert.orgfor opt in export_vars:
3646658Snate@binkert.org    env.ConfigFile(opt)
3657673Snate@binkert.org
3667673Snate@binkert.orgdef makeTheISA(source, target, env):
3677673Snate@binkert.org    isas = [ src.get_contents() for src in source ]
3687673Snate@binkert.org    target_isa = env['TARGET_ISA']
3697673Snate@binkert.org    def define(isa):
3707673Snate@binkert.org        return isa.upper() + '_ISA'
3717673Snate@binkert.org
37210467Sandreas.hansson@arm.com    def namespace(isa):
3736658Snate@binkert.org        return isa[0].upper() + isa[1:].lower() + 'ISA'
3747673Snate@binkert.org
37510467Sandreas.hansson@arm.com
37610467Sandreas.hansson@arm.com    code = code_formatter()
37710467Sandreas.hansson@arm.com    code('''\
37810467Sandreas.hansson@arm.com#ifndef __CONFIG_THE_ISA_HH__
37910467Sandreas.hansson@arm.com#define __CONFIG_THE_ISA_HH__
38010467Sandreas.hansson@arm.com
38110467Sandreas.hansson@arm.com''')
38210467Sandreas.hansson@arm.com
38310467Sandreas.hansson@arm.com    # create defines for the preprocessing and compile-time determination
38410467Sandreas.hansson@arm.com    for i,isa in enumerate(isas):
38510467Sandreas.hansson@arm.com        code('#define $0 $1', define(isa), i + 1)
3867673Snate@binkert.org    code()
3877673Snate@binkert.org
3887673Snate@binkert.org    # create an enum for any run-time determination of the ISA, we
3897673Snate@binkert.org    # reuse the same name as the namespaces
3907673Snate@binkert.org    code('enum class Arch {')
3919048SAli.Saidi@ARM.com    for i,isa in enumerate(isas):
3927673Snate@binkert.org        if i + 1 == len(isas):
3937673Snate@binkert.org            code('  $0 = $1', namespace(isa), define(isa))
3947673Snate@binkert.org        else:
3957673Snate@binkert.org            code('  $0 = $1,', namespace(isa), define(isa))
3966658Snate@binkert.org    code('};')
3977756SAli.Saidi@ARM.com
3987816Ssteve.reinhardt@amd.com    code('''
3996658Snate@binkert.org
40011308Santhony.gutierrez@amd.com#define THE_ISA ${{define(target_isa)}}
40111308Santhony.gutierrez@amd.com#define TheISA ${{namespace(target_isa)}}
40211308Santhony.gutierrez@amd.com#define THE_ISA_STR "${{target_isa}}"
40311308Santhony.gutierrez@amd.com
40411308Santhony.gutierrez@amd.com#endif // __CONFIG_THE_ISA_HH__''')
40511308Santhony.gutierrez@amd.com
40611308Santhony.gutierrez@amd.com    code.write(str(target[0]))
40711308Santhony.gutierrez@amd.com
40811308Santhony.gutierrez@amd.comenv.Command('config/the_isa.hh', map(Value, all_isa_list),
40911308Santhony.gutierrez@amd.com            MakeAction(makeTheISA, Transform("CFG ISA", 0)))
41011308Santhony.gutierrez@amd.com
41111308Santhony.gutierrez@amd.comdef makeTheGPUISA(source, target, env):
41211308Santhony.gutierrez@amd.com    isas = [ src.get_contents() for src in source ]
41311308Santhony.gutierrez@amd.com    target_gpu_isa = env['TARGET_GPU_ISA']
41411308Santhony.gutierrez@amd.com    def define(isa):
41511308Santhony.gutierrez@amd.com        return isa.upper() + '_ISA'
41611308Santhony.gutierrez@amd.com
41711308Santhony.gutierrez@amd.com    def namespace(isa):
41811308Santhony.gutierrez@amd.com        return isa[0].upper() + isa[1:].lower() + 'ISA'
41911308Santhony.gutierrez@amd.com
42011308Santhony.gutierrez@amd.com
42111308Santhony.gutierrez@amd.com    code = code_formatter()
42211308Santhony.gutierrez@amd.com    code('''\
42311308Santhony.gutierrez@amd.com#ifndef __CONFIG_THE_GPU_ISA_HH__
42411308Santhony.gutierrez@amd.com#define __CONFIG_THE_GPU_ISA_HH__
42511308Santhony.gutierrez@amd.com
42611308Santhony.gutierrez@amd.com''')
42711308Santhony.gutierrez@amd.com
42811308Santhony.gutierrez@amd.com    # create defines for the preprocessing and compile-time determination
42911308Santhony.gutierrez@amd.com    for i,isa in enumerate(isas):
43011308Santhony.gutierrez@amd.com        code('#define $0 $1', define(isa), i + 1)
43111308Santhony.gutierrez@amd.com    code()
43211308Santhony.gutierrez@amd.com
43311308Santhony.gutierrez@amd.com    # create an enum for any run-time determination of the ISA, we
43411308Santhony.gutierrez@amd.com    # reuse the same name as the namespaces
43511308Santhony.gutierrez@amd.com    code('enum class GPUArch {')
43611308Santhony.gutierrez@amd.com    for i,isa in enumerate(isas):
43711308Santhony.gutierrez@amd.com        if i + 1 == len(isas):
43811308Santhony.gutierrez@amd.com            code('  $0 = $1', namespace(isa), define(isa))
43911308Santhony.gutierrez@amd.com        else:
44011308Santhony.gutierrez@amd.com            code('  $0 = $1,', namespace(isa), define(isa))
44111308Santhony.gutierrez@amd.com    code('};')
44211308Santhony.gutierrez@amd.com
44311308Santhony.gutierrez@amd.com    code('''
44411308Santhony.gutierrez@amd.com
4454382Sbinkertn@umich.edu#define THE_GPU_ISA ${{define(target_gpu_isa)}}
4464382Sbinkertn@umich.edu#define TheGpuISA ${{namespace(target_gpu_isa)}}
4474762Snate@binkert.org#define THE_GPU_ISA_STR "${{target_gpu_isa}}"
4484762Snate@binkert.org
4494762Snate@binkert.org#endif // __CONFIG_THE_GPU_ISA_HH__''')
4506654Snate@binkert.org
4516654Snate@binkert.org    code.write(str(target[0]))
4525517Snate@binkert.org
4535517Snate@binkert.orgenv.Command('config/the_gpu_isa.hh', map(Value, all_gpu_isa_list),
4545517Snate@binkert.org            MakeAction(makeTheGPUISA, Transform("CFG ISA", 0)))
4555517Snate@binkert.org
4565517Snate@binkert.org########################################################################
4575517Snate@binkert.org#
4585517Snate@binkert.org# Prevent any SimObjects from being added after this point, they
4595517Snate@binkert.org# should all have been added in the SConscripts above
4605517Snate@binkert.org#
4615517Snate@binkert.orgSimObject.fixed = True
4625517Snate@binkert.org
4635517Snate@binkert.orgclass DictImporter(object):
4645517Snate@binkert.org    '''This importer takes a dictionary of arbitrary module names that
4655517Snate@binkert.org    map to arbitrary filenames.'''
4665517Snate@binkert.org    def __init__(self, modules):
4675517Snate@binkert.org        self.modules = modules
4685517Snate@binkert.org        self.installed = set()
4696654Snate@binkert.org
4705517Snate@binkert.org    def __del__(self):
4715517Snate@binkert.org        self.unload()
4725517Snate@binkert.org
4735517Snate@binkert.org    def unload(self):
4745517Snate@binkert.org        import sys
47511802Sandreas.sandberg@arm.com        for module in self.installed:
4765517Snate@binkert.org            del sys.modules[module]
4775517Snate@binkert.org        self.installed = set()
4786143Snate@binkert.org
4796654Snate@binkert.org    def find_module(self, fullname, path):
4805517Snate@binkert.org        if fullname == 'm5.defines':
4815517Snate@binkert.org            return self
4825517Snate@binkert.org
4835517Snate@binkert.org        if fullname == 'm5.objects':
4845517Snate@binkert.org            return self
4855517Snate@binkert.org
4865517Snate@binkert.org        if fullname.startswith('_m5'):
4875517Snate@binkert.org            return None
4885517Snate@binkert.org
4895517Snate@binkert.org        source = self.modules.get(fullname, None)
4905517Snate@binkert.org        if source is not None and fullname.startswith('m5.objects'):
4915517Snate@binkert.org            return self
4925517Snate@binkert.org
4935517Snate@binkert.org        return None
4946654Snate@binkert.org
4956654Snate@binkert.org    def load_module(self, fullname):
4965517Snate@binkert.org        mod = imp.new_module(fullname)
4975517Snate@binkert.org        sys.modules[fullname] = mod
4986143Snate@binkert.org        self.installed.add(fullname)
4996143Snate@binkert.org
5006143Snate@binkert.org        mod.__loader__ = self
5016727Ssteve.reinhardt@amd.com        if fullname == 'm5.objects':
5025517Snate@binkert.org            mod.__path__ = fullname.split('.')
5036727Ssteve.reinhardt@amd.com            return mod
5045517Snate@binkert.org
5055517Snate@binkert.org        if fullname == 'm5.defines':
5065517Snate@binkert.org            mod.__dict__['buildEnv'] = m5.util.SmartDict(build_env)
5076654Snate@binkert.org            return mod
5086654Snate@binkert.org
5097673Snate@binkert.org        source = self.modules[fullname]
5106654Snate@binkert.org        if source.modname == '__init__':
5116654Snate@binkert.org            mod.__path__ = source.modpath
5126654Snate@binkert.org        mod.__file__ = source.abspath
5136654Snate@binkert.org
5145517Snate@binkert.org        exec file(source.abspath, 'r') in mod.__dict__
5155517Snate@binkert.org
5165517Snate@binkert.org        return mod
5176143Snate@binkert.org
5185517Snate@binkert.orgimport m5.SimObject
5194762Snate@binkert.orgimport m5.params
5205517Snate@binkert.orgfrom m5.util import code_formatter
5215517Snate@binkert.org
5226143Snate@binkert.orgm5.SimObject.clear()
5236143Snate@binkert.orgm5.params.clear()
5245517Snate@binkert.org
5255517Snate@binkert.org# install the python importer so we can grab stuff from the source
5265517Snate@binkert.org# tree itself.  We can't have SimObjects added after this point or
5275517Snate@binkert.org# else we won't know about them for the rest of the stuff.
5285517Snate@binkert.orgimporter = DictImporter(PySource.modules)
5295517Snate@binkert.orgsys.meta_path[0:0] = [ importer ]
5305517Snate@binkert.org
5315517Snate@binkert.org# import all sim objects so we can populate the all_objects list
5325517Snate@binkert.org# make sure that we're working with a list, then let's sort it
5336143Snate@binkert.orgfor modname in SimObject.modnames:
5345517Snate@binkert.org    exec('from m5.objects import %s' % modname)
5356654Snate@binkert.org
5366654Snate@binkert.org# we need to unload all of the currently imported modules so that they
5376654Snate@binkert.org# will be re-imported the next time the sconscript is run
5386654Snate@binkert.orgimporter.unload()
5396654Snate@binkert.orgsys.meta_path.remove(importer)
5406654Snate@binkert.org
5414762Snate@binkert.orgsim_objects = m5.SimObject.allClasses
5424762Snate@binkert.orgall_enums = m5.params.allEnums
5434762Snate@binkert.org
5444762Snate@binkert.orgif m5.SimObject.noCxxHeader:
5454762Snate@binkert.org    print >> sys.stderr, \
5467675Snate@binkert.org        "warning: At least one SimObject lacks a header specification. " \
54710584Sandreas.hansson@arm.com        "This can cause unexpected results in the generated SWIG " \
5484762Snate@binkert.org        "wrappers."
5494762Snate@binkert.org
5504762Snate@binkert.org# Find param types that need to be explicitly wrapped with swig.
5514762Snate@binkert.org# These will be recognized because the ParamDesc will have a
5524382Sbinkertn@umich.edu# swig_decl() method.  Most param types are based on types that don't
5534382Sbinkertn@umich.edu# need this, either because they're based on native types (like Int)
5545517Snate@binkert.org# or because they're SimObjects (which get swigged independently).
5556654Snate@binkert.org# For now the only things handled here are VectorParam types.
5565517Snate@binkert.orgparams_to_swig = {}
5578126Sgblack@eecs.umich.edufor name,obj in sorted(sim_objects.iteritems()):
5586654Snate@binkert.org    for param in obj._params.local.values():
5597673Snate@binkert.org        # load the ptype attribute now because it depends on the
5606654Snate@binkert.org        # current version of SimObject.allClasses, but when scons
56111802Sandreas.sandberg@arm.com        # actually uses the value, all versions of
5626654Snate@binkert.org        # SimObject.allClasses will have been loaded
5636654Snate@binkert.org        param.ptype
5646654Snate@binkert.org
5656654Snate@binkert.org        if not hasattr(param, 'swig_decl'):
56611802Sandreas.sandberg@arm.com            continue
5676669Snate@binkert.org        pname = param.ptype_str
56811802Sandreas.sandberg@arm.com        if pname not in params_to_swig:
5696669Snate@binkert.org            params_to_swig[pname] = param
5706669Snate@binkert.org
5716669Snate@binkert.org########################################################################
5726669Snate@binkert.org#
5736654Snate@binkert.org# calculate extra dependencies
5747673Snate@binkert.org#
5755517Snate@binkert.orgmodule_depends = ["m5", "m5.SimObject", "m5.params"]
5768126Sgblack@eecs.umich.edudepends = [ PySource.modules[dep].snode for dep in module_depends ]
5775798Snate@binkert.orgdepends.sort(key = lambda x: x.name)
5787756SAli.Saidi@ARM.com
5797816Ssteve.reinhardt@amd.com########################################################################
5805798Snate@binkert.org#
5815798Snate@binkert.org# Commands for the basic automatically generated python files
5825517Snate@binkert.org#
5835517Snate@binkert.org
5847673Snate@binkert.org# Generate Python file containing a dict specifying the current
5855517Snate@binkert.org# buildEnv flags.
5865517Snate@binkert.orgdef makeDefinesPyFile(target, source, env):
5877673Snate@binkert.org    build_env = source[0].get_contents()
5887673Snate@binkert.org
5895517Snate@binkert.org    code = code_formatter()
5905798Snate@binkert.org    code("""
5915798Snate@binkert.orgimport _m5.core
5928333Snate@binkert.orgimport m5.util
5937816Ssteve.reinhardt@amd.com
5945798Snate@binkert.orgbuildEnv = m5.util.SmartDict($build_env)
5955798Snate@binkert.org
5964762Snate@binkert.orgcompileDate = _m5.core.compileDate
5974762Snate@binkert.org_globals = globals()
5984762Snate@binkert.orgfor key,val in _m5.core.__dict__.iteritems():
5994762Snate@binkert.org    if key.startswith('flag_'):
6004762Snate@binkert.org        flag = key[5:]
6018596Ssteve.reinhardt@amd.com        _globals[flag] = val
6025517Snate@binkert.orgdel _globals
6035517Snate@binkert.org""")
60411997Sgabeblack@google.com    code.write(target[0].abspath)
6055517Snate@binkert.org
6065517Snate@binkert.orgdefines_info = Value(build_env)
6077673Snate@binkert.org# Generate a file with all of the compile options in it
6088596Ssteve.reinhardt@amd.comenv.Command('python/m5/defines.py', defines_info,
6097673Snate@binkert.org            MakeAction(makeDefinesPyFile, Transform("DEFINES", 0)))
6105517Snate@binkert.orgPySource('m5', 'python/m5/defines.py')
61110458Sandreas.hansson@arm.com
61210458Sandreas.hansson@arm.com# Generate python file containing info about the M5 source code
61310458Sandreas.hansson@arm.comdef makeInfoPyFile(target, source, env):
61410458Sandreas.hansson@arm.com    code = code_formatter()
61510458Sandreas.hansson@arm.com    for src in source:
61610458Sandreas.hansson@arm.com        data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
61710458Sandreas.hansson@arm.com        code('$src = ${{repr(data)}}')
61810458Sandreas.hansson@arm.com    code.write(str(target[0]))
61910458Sandreas.hansson@arm.com
62010458Sandreas.hansson@arm.com# Generate a file that wraps the basic top level files
62110458Sandreas.hansson@arm.comenv.Command('python/m5/info.py',
62210458Sandreas.hansson@arm.com            [ '#/COPYING', '#/LICENSE', '#/README', ],
6235517Snate@binkert.org            MakeAction(makeInfoPyFile, Transform("INFO")))
62411996Sgabeblack@google.comPySource('m5', 'python/m5/info.py')
6255517Snate@binkert.org
62611997Sgabeblack@google.com########################################################################
62711996Sgabeblack@google.com#
6285517Snate@binkert.org# Create all of the SimObject param headers and enum headers
6295517Snate@binkert.org#
6307673Snate@binkert.org
6317673Snate@binkert.orgdef createSimObjectParamStruct(target, source, env):
63211996Sgabeblack@google.com    assert len(target) == 1 and len(source) == 1
63311988Sandreas.sandberg@arm.com
6347673Snate@binkert.org    name = str(source[0].get_contents())
6355517Snate@binkert.org    obj = sim_objects[name]
6368596Ssteve.reinhardt@amd.com
6375517Snate@binkert.org    code = code_formatter()
6385517Snate@binkert.org    obj.cxx_param_decl(code)
63911997Sgabeblack@google.com    code.write(target[0].abspath)
6405517Snate@binkert.org
6415517Snate@binkert.orgdef createSimObjectCxxConfig(is_header):
6427673Snate@binkert.org    def body(target, source, env):
6437673Snate@binkert.org        assert len(target) == 1 and len(source) == 1
6447673Snate@binkert.org
6455517Snate@binkert.org        name = str(source[0].get_contents())
64611988Sandreas.sandberg@arm.com        obj = sim_objects[name]
64711997Sgabeblack@google.com
6488596Ssteve.reinhardt@amd.com        code = code_formatter()
6498596Ssteve.reinhardt@amd.com        obj.cxx_config_param_file(code, is_header)
6508596Ssteve.reinhardt@amd.com        code.write(target[0].abspath)
65111988Sandreas.sandberg@arm.com    return body
6528596Ssteve.reinhardt@amd.com
6538596Ssteve.reinhardt@amd.comdef createParamSwigWrapper(target, source, env):
6548596Ssteve.reinhardt@amd.com    assert len(target) == 1 and len(source) == 1
6554762Snate@binkert.org
6566143Snate@binkert.org    name = str(source[0].get_contents())
6576143Snate@binkert.org    param = params_to_swig[name]
6586143Snate@binkert.org
6594762Snate@binkert.org    code = code_formatter()
6604762Snate@binkert.org    param.swig_decl(code)
6614762Snate@binkert.org    code.write(target[0].abspath)
6627756SAli.Saidi@ARM.com
6638596Ssteve.reinhardt@amd.comdef createEnumStrings(target, source, env):
6644762Snate@binkert.org    assert len(target) == 1 and len(source) == 1
6654762Snate@binkert.org
66610458Sandreas.hansson@arm.com    name = str(source[0].get_contents())
66710458Sandreas.hansson@arm.com    obj = all_enums[name]
66810458Sandreas.hansson@arm.com
66910458Sandreas.hansson@arm.com    code = code_formatter()
67010458Sandreas.hansson@arm.com    obj.cxx_def(code)
67110458Sandreas.hansson@arm.com    code.write(target[0].abspath)
67210458Sandreas.hansson@arm.com
67310458Sandreas.hansson@arm.comdef createEnumDecls(target, source, env):
67410458Sandreas.hansson@arm.com    assert len(target) == 1 and len(source) == 1
67510458Sandreas.hansson@arm.com
67610458Sandreas.hansson@arm.com    name = str(source[0].get_contents())
67710458Sandreas.hansson@arm.com    obj = all_enums[name]
67810458Sandreas.hansson@arm.com
67910458Sandreas.hansson@arm.com    code = code_formatter()
68010458Sandreas.hansson@arm.com    obj.cxx_decl(code)
68110458Sandreas.hansson@arm.com    code.write(target[0].abspath)
68210458Sandreas.hansson@arm.com
68310458Sandreas.hansson@arm.comdef createEnumSwigWrapper(target, source, env):
68410458Sandreas.hansson@arm.com    assert len(target) == 1 and len(source) == 1
68510458Sandreas.hansson@arm.com
68610458Sandreas.hansson@arm.com    name = str(source[0].get_contents())
68710458Sandreas.hansson@arm.com    obj = all_enums[name]
68810458Sandreas.hansson@arm.com
68910458Sandreas.hansson@arm.com    code = code_formatter()
69010458Sandreas.hansson@arm.com    obj.swig_decl(code)
69110458Sandreas.hansson@arm.com    code.write(target[0].abspath)
69210458Sandreas.hansson@arm.com
69310458Sandreas.hansson@arm.comdef createSimObjectSwigWrapper(target, source, env):
69410458Sandreas.hansson@arm.com    name = source[0].get_contents()
69510458Sandreas.hansson@arm.com    obj = sim_objects[name]
69610458Sandreas.hansson@arm.com
69710458Sandreas.hansson@arm.com    code = code_formatter()
69810458Sandreas.hansson@arm.com    obj.swig_decl(code)
69910458Sandreas.hansson@arm.com    code.write(target[0].abspath)
70010458Sandreas.hansson@arm.com
70110458Sandreas.hansson@arm.com# dummy target for generated code
70210458Sandreas.hansson@arm.com# we start out with all the Source files so they get copied to build/*/ also.
70310458Sandreas.hansson@arm.comSWIG = env.Dummy('swig', [s.tnode for s in Source.get()])
70410458Sandreas.hansson@arm.com
70510458Sandreas.hansson@arm.com# Generate all of the SimObject param C++ struct header files
70610458Sandreas.hansson@arm.comparams_hh_files = []
70710458Sandreas.hansson@arm.comfor name,simobj in sorted(sim_objects.iteritems()):
70810458Sandreas.hansson@arm.com    py_source = PySource.modules[simobj.__module__]
70910458Sandreas.hansson@arm.com    extra_deps = [ py_source.tnode ]
71010458Sandreas.hansson@arm.com
71110458Sandreas.hansson@arm.com    hh_file = File('params/%s.hh' % name)
71210458Sandreas.hansson@arm.com    params_hh_files.append(hh_file)
71310458Sandreas.hansson@arm.com    env.Command(hh_file, Value(name),
71410458Sandreas.hansson@arm.com                MakeAction(createSimObjectParamStruct, Transform("SO PARAM")))
71510584Sandreas.hansson@arm.com    env.Depends(hh_file, depends + extra_deps)
71610458Sandreas.hansson@arm.com    env.Depends(SWIG, hh_file)
71710458Sandreas.hansson@arm.com
71810458Sandreas.hansson@arm.com# C++ parameter description files
71910458Sandreas.hansson@arm.comif GetOption('with_cxx_config'):
72010458Sandreas.hansson@arm.com    for name,simobj in sorted(sim_objects.iteritems()):
7214762Snate@binkert.org        py_source = PySource.modules[simobj.__module__]
7226143Snate@binkert.org        extra_deps = [ py_source.tnode ]
7236143Snate@binkert.org
7246143Snate@binkert.org        cxx_config_hh_file = File('cxx_config/%s.hh' % name)
7254762Snate@binkert.org        cxx_config_cc_file = File('cxx_config/%s.cc' % name)
7264762Snate@binkert.org        env.Command(cxx_config_hh_file, Value(name),
72711996Sgabeblack@google.com                    MakeAction(createSimObjectCxxConfig(True),
7287816Ssteve.reinhardt@amd.com                    Transform("CXXCPRHH")))
7294762Snate@binkert.org        env.Command(cxx_config_cc_file, Value(name),
7304762Snate@binkert.org                    MakeAction(createSimObjectCxxConfig(False),
7314762Snate@binkert.org                    Transform("CXXCPRCC")))
7324762Snate@binkert.org        env.Depends(cxx_config_hh_file, depends + extra_deps +
7337756SAli.Saidi@ARM.com                    [File('params/%s.hh' % name), File('sim/cxx_config.hh')])
7348596Ssteve.reinhardt@amd.com        env.Depends(cxx_config_cc_file, depends + extra_deps +
7354762Snate@binkert.org                    [cxx_config_hh_file])
7364762Snate@binkert.org        Source(cxx_config_cc_file)
73711988Sandreas.sandberg@arm.com
73811988Sandreas.sandberg@arm.com    cxx_config_init_cc_file = File('cxx_config/init.cc')
73911988Sandreas.sandberg@arm.com
74011988Sandreas.sandberg@arm.com    def createCxxConfigInitCC(target, source, env):
74111988Sandreas.sandberg@arm.com        assert len(target) == 1 and len(source) == 1
74211988Sandreas.sandberg@arm.com
74311988Sandreas.sandberg@arm.com        code = code_formatter()
74411988Sandreas.sandberg@arm.com
74511988Sandreas.sandberg@arm.com        for name,simobj in sorted(sim_objects.iteritems()):
74611988Sandreas.sandberg@arm.com            if not hasattr(simobj, 'abstract') or not simobj.abstract:
74711988Sandreas.sandberg@arm.com                code('#include "cxx_config/${name}.hh"')
7484382Sbinkertn@umich.edu        code()
7499396Sandreas.hansson@arm.com        code('void cxxConfigInit()')
7509396Sandreas.hansson@arm.com        code('{')
7519396Sandreas.hansson@arm.com        code.indent()
7529396Sandreas.hansson@arm.com        for name,simobj in sorted(sim_objects.iteritems()):
7539396Sandreas.hansson@arm.com            not_abstract = not hasattr(simobj, 'abstract') or \
7549396Sandreas.hansson@arm.com                not simobj.abstract
7559396Sandreas.hansson@arm.com            if not_abstract and 'type' in simobj.__dict__:
7569396Sandreas.hansson@arm.com                code('cxx_config_directory["${name}"] = '
7579396Sandreas.hansson@arm.com                     '${name}CxxConfigParams::makeDirectoryEntry();')
7589396Sandreas.hansson@arm.com        code.dedent()
7599396Sandreas.hansson@arm.com        code('}')
7609396Sandreas.hansson@arm.com        code.write(target[0].abspath)
7619396Sandreas.hansson@arm.com
76212302Sgabeblack@google.com    py_source = PySource.modules[simobj.__module__]
7639396Sandreas.hansson@arm.com    extra_deps = [ py_source.tnode ]
7649396Sandreas.hansson@arm.com    env.Command(cxx_config_init_cc_file, Value(name),
7659396Sandreas.hansson@arm.com        MakeAction(createCxxConfigInitCC, Transform("CXXCINIT")))
7669396Sandreas.hansson@arm.com    cxx_param_hh_files = ["cxx_config/%s.hh" % simobj
7678232Snate@binkert.org        for name,simobj in sorted(sim_objects.iteritems())
7688232Snate@binkert.org        if not hasattr(simobj, 'abstract') or not simobj.abstract]
7698232Snate@binkert.org    Depends(cxx_config_init_cc_file, cxx_param_hh_files +
7708232Snate@binkert.org            [File('sim/cxx_config.hh')])
7718232Snate@binkert.org    Source(cxx_config_init_cc_file)
7726229Snate@binkert.org
77310455SCurtis.Dunham@arm.com# Generate any needed param SWIG wrapper files
7746229Snate@binkert.orgparams_i_files = []
77510455SCurtis.Dunham@arm.comfor name,param in sorted(params_to_swig.iteritems()):
77610455SCurtis.Dunham@arm.com    i_file = File('python/_m5/%s.i' % (param.swig_module_name()))
77710455SCurtis.Dunham@arm.com    params_i_files.append(i_file)
7785517Snate@binkert.org    env.Command(i_file, Value(name),
7795517Snate@binkert.org                MakeAction(createParamSwigWrapper, Transform("SW PARAM")))
7807673Snate@binkert.org    env.Depends(i_file, depends)
7815517Snate@binkert.org    env.Depends(SWIG, i_file)
78210455SCurtis.Dunham@arm.com    SwigSource('_m5', i_file)
7835517Snate@binkert.org
7845517Snate@binkert.org# Generate all enum header files
7858232Snate@binkert.orgfor name,enum in sorted(all_enums.iteritems()):
78610455SCurtis.Dunham@arm.com    py_source = PySource.modules[enum.__module__]
78710455SCurtis.Dunham@arm.com    extra_deps = [ py_source.tnode ]
78810455SCurtis.Dunham@arm.com
7897673Snate@binkert.org    cc_file = File('enums/%s.cc' % name)
7907673Snate@binkert.org    env.Command(cc_file, Value(name),
79110455SCurtis.Dunham@arm.com                MakeAction(createEnumStrings, Transform("ENUM STR")))
79210455SCurtis.Dunham@arm.com    env.Depends(cc_file, depends + extra_deps)
79310455SCurtis.Dunham@arm.com    env.Depends(SWIG, cc_file)
7945517Snate@binkert.org    Source(cc_file)
79510455SCurtis.Dunham@arm.com
79610455SCurtis.Dunham@arm.com    hh_file = File('enums/%s.hh' % name)
79710455SCurtis.Dunham@arm.com    env.Command(hh_file, Value(name),
79810455SCurtis.Dunham@arm.com                MakeAction(createEnumDecls, Transform("ENUMDECL")))
79910455SCurtis.Dunham@arm.com    env.Depends(hh_file, depends + extra_deps)
80010455SCurtis.Dunham@arm.com    env.Depends(SWIG, hh_file)
80110455SCurtis.Dunham@arm.com
80210455SCurtis.Dunham@arm.com    i_file = File('python/_m5/enum_%s.i' % name)
80310685Sandreas.hansson@arm.com    env.Command(i_file, Value(name),
80410455SCurtis.Dunham@arm.com                MakeAction(createEnumSwigWrapper, Transform("ENUMSWIG")))
80510685Sandreas.hansson@arm.com    env.Depends(i_file, depends + extra_deps)
80610455SCurtis.Dunham@arm.com    env.Depends(SWIG, i_file)
8075517Snate@binkert.org    SwigSource('_m5', i_file)
80810455SCurtis.Dunham@arm.com
8098232Snate@binkert.org# Generate SimObject SWIG wrapper files
8108232Snate@binkert.orgfor name,simobj in sorted(sim_objects.iteritems()):
8115517Snate@binkert.org    py_source = PySource.modules[simobj.__module__]
8127673Snate@binkert.org    extra_deps = [ py_source.tnode ]
8135517Snate@binkert.org    i_file = File('python/_m5/param_%s.i' % name)
8148232Snate@binkert.org    env.Command(i_file, Value(name),
8158232Snate@binkert.org                MakeAction(createSimObjectSwigWrapper, Transform("SO SWIG")))
8165517Snate@binkert.org    env.Depends(i_file, depends + extra_deps)
8178232Snate@binkert.org    SwigSource('_m5', i_file)
8188232Snate@binkert.org
8198232Snate@binkert.org# Generate the main swig init file
8207673Snate@binkert.orgdef makeEmbeddedSwigInit(package):
8215517Snate@binkert.org    def body(target, source, env):
8225517Snate@binkert.org        assert len(target) == 1 and len(source) == 1
8237673Snate@binkert.org
8245517Snate@binkert.org        code = code_formatter()
82510455SCurtis.Dunham@arm.com        module = source[0].get_contents()
8265517Snate@binkert.org        # Provide the full context so that the swig-generated call to
8275517Snate@binkert.org        # Py_InitModule ends up placing the embedded module in the
8288232Snate@binkert.org        # right package.
8298232Snate@binkert.org        context = str(package) + "._" + str(module)
8305517Snate@binkert.org        code('''\
8318232Snate@binkert.org        #include "sim/init.hh"
8328232Snate@binkert.org
8335517Snate@binkert.org        extern "C" {
8348232Snate@binkert.org            void init_${module}();
8358232Snate@binkert.org        }
8368232Snate@binkert.org
8375517Snate@binkert.org        EmbeddedSwig embed_swig_${module}(init_${module}, "${context}");
8388232Snate@binkert.org        ''')
8398232Snate@binkert.org        code.write(str(target[0]))
8408232Snate@binkert.org    return body
8418232Snate@binkert.org
8428232Snate@binkert.org# Build all swig modules
8438232Snate@binkert.orgfor swig in SwigSource.all:
8445517Snate@binkert.org    env.Command([swig.cc_source.tnode, swig.py_source.tnode], swig.tnode,
8458232Snate@binkert.org                MakeAction('$SWIG $SWIGFLAGS -outdir ${TARGETS[1].dir} '
8468232Snate@binkert.org                '-o ${TARGETS[0]} $SOURCES', Transform("SWIG")))
8475517Snate@binkert.org    cc_file = str(swig.tnode)
8488232Snate@binkert.org    init_file = '%s/%s_init.cc' % (dirname(cc_file), basename(cc_file))
8497673Snate@binkert.org    env.Command(init_file, Value(swig.module),
8505517Snate@binkert.org                MakeAction(makeEmbeddedSwigInit(swig.package),
8517673Snate@binkert.org                           Transform("EMBED SW")))
8525517Snate@binkert.org    env.Depends(SWIG, init_file)
8538232Snate@binkert.org    Source(init_file, **swig.guards)
8548232Snate@binkert.org
8558232Snate@binkert.org# Build all protocol buffers if we have got protoc and protobuf available
8565192Ssaidi@eecs.umich.eduif env['HAVE_PROTOBUF']:
85710454SCurtis.Dunham@arm.com    for proto in ProtoBuf.all:
85810454SCurtis.Dunham@arm.com        # Use both the source and header as the target, and the .proto
8598232Snate@binkert.org        # file as the source. When executing the protoc compiler, also
86010455SCurtis.Dunham@arm.com        # specify the proto_path to avoid having the generated files
86110455SCurtis.Dunham@arm.com        # include the path.
86210455SCurtis.Dunham@arm.com        env.Command([proto.cc_file, proto.hh_file], proto.tnode,
86310455SCurtis.Dunham@arm.com                    MakeAction('$PROTOC --cpp_out ${TARGET.dir} '
8645192Ssaidi@eecs.umich.edu                               '--proto_path ${SOURCE.dir} $SOURCE',
86511077SCurtis.Dunham@arm.com                               Transform("PROTOC")))
86611330SCurtis.Dunham@arm.com
86711077SCurtis.Dunham@arm.com        env.Depends(SWIG, [proto.cc_file, proto.hh_file])
86811077SCurtis.Dunham@arm.com        # Add the C++ source file
86911077SCurtis.Dunham@arm.com        Source(proto.cc_file, **proto.guards)
87011330SCurtis.Dunham@arm.comelif ProtoBuf.all:
87111077SCurtis.Dunham@arm.com    print 'Got protobuf to build, but lacks support!'
8727674Snate@binkert.org    Exit(1)
8735522Snate@binkert.org
8745522Snate@binkert.org#
8757674Snate@binkert.org# Handle debug flags
8767674Snate@binkert.org#
8777674Snate@binkert.orgdef makeDebugFlagCC(target, source, env):
8787674Snate@binkert.org    assert(len(target) == 1 and len(source) == 1)
8797674Snate@binkert.org
8807674Snate@binkert.org    code = code_formatter()
8817674Snate@binkert.org
8827674Snate@binkert.org    # delay definition of CompoundFlags until after all the definition
8835522Snate@binkert.org    # of all constituent SimpleFlags
8845522Snate@binkert.org    comp_code = code_formatter()
8855522Snate@binkert.org
8865517Snate@binkert.org    # file header
8875522Snate@binkert.org    code('''
8885517Snate@binkert.org/*
8896143Snate@binkert.org * DO NOT EDIT THIS FILE! Automatically generated by SCons.
8906727Ssteve.reinhardt@amd.com */
8915522Snate@binkert.org
8925522Snate@binkert.org#include "base/debug.hh"
8935522Snate@binkert.org
8947674Snate@binkert.orgnamespace Debug {
8955517Snate@binkert.org
8967673Snate@binkert.org''')
8977673Snate@binkert.org
8987674Snate@binkert.org    for name, flag in sorted(source[0].read().iteritems()):
8997673Snate@binkert.org        n, compound, desc = flag
9007674Snate@binkert.org        assert n == name
9017674Snate@binkert.org
9028946Sandreas.hansson@arm.com        if not compound:
9037674Snate@binkert.org            code('SimpleFlag $name("$name", "$desc");')
9047674Snate@binkert.org        else:
9057674Snate@binkert.org            comp_code('CompoundFlag $name("$name", "$desc",')
9065522Snate@binkert.org            comp_code.indent()
9075522Snate@binkert.org            last = len(compound) - 1
9087674Snate@binkert.org            for i,flag in enumerate(compound):
9097674Snate@binkert.org                if i != last:
91011308Santhony.gutierrez@amd.com                    comp_code('&$flag,')
9117674Snate@binkert.org                else:
9127673Snate@binkert.org                    comp_code('&$flag);')
9137674Snate@binkert.org            comp_code.dedent()
9147674Snate@binkert.org
9157674Snate@binkert.org    code.append(comp_code)
9167674Snate@binkert.org    code()
9177674Snate@binkert.org    code('} // namespace Debug')
9187674Snate@binkert.org
9197674Snate@binkert.org    code.write(str(target[0]))
9207674Snate@binkert.org
9217811Ssteve.reinhardt@amd.comdef makeDebugFlagHH(target, source, env):
9227674Snate@binkert.org    assert(len(target) == 1 and len(source) == 1)
9237673Snate@binkert.org
9245522Snate@binkert.org    val = eval(source[0].get_contents())
9256143Snate@binkert.org    name, compound, desc = val
92610453SAndrew.Bardsley@arm.com
9277816Ssteve.reinhardt@amd.com    code = code_formatter()
92812302Sgabeblack@google.com
9294382Sbinkertn@umich.edu    # file header boilerplate
9304382Sbinkertn@umich.edu    code('''\
9314382Sbinkertn@umich.edu/*
9324382Sbinkertn@umich.edu * DO NOT EDIT THIS FILE! Automatically generated by SCons.
9334382Sbinkertn@umich.edu */
9344382Sbinkertn@umich.edu
9354382Sbinkertn@umich.edu#ifndef __DEBUG_${name}_HH__
9364382Sbinkertn@umich.edu#define __DEBUG_${name}_HH__
93712302Sgabeblack@google.com
9384382Sbinkertn@umich.edunamespace Debug {
9392655Sstever@eecs.umich.edu''')
9402655Sstever@eecs.umich.edu
9412655Sstever@eecs.umich.edu    if compound:
9422655Sstever@eecs.umich.edu        code('class CompoundFlag;')
94312063Sgabeblack@google.com    code('class SimpleFlag;')
9445601Snate@binkert.org
9455601Snate@binkert.org    if compound:
94612222Sgabeblack@google.com        code('extern CompoundFlag $name;')
94712222Sgabeblack@google.com        for flag in compound:
94812222Sgabeblack@google.com            code('extern SimpleFlag $flag;')
9495522Snate@binkert.org    else:
9505863Snate@binkert.org        code('extern SimpleFlag $name;')
9515601Snate@binkert.org
9525601Snate@binkert.org    code('''
9535601Snate@binkert.org}
95412307Sgabeblack@google.com
95512307Sgabeblack@google.com#endif // __DEBUG_${name}_HH__
9566143Snate@binkert.org''')
95712302Sgabeblack@google.com
95810453SAndrew.Bardsley@arm.com    code.write(str(target[0]))
95911988Sandreas.sandberg@arm.com
96011988Sandreas.sandberg@arm.comfor name,flag in sorted(debug_flags.iteritems()):
96110453SAndrew.Bardsley@arm.com    n, compound, desc = flag
96212302Sgabeblack@google.com    assert n == name
96310453SAndrew.Bardsley@arm.com
96411983Sgabeblack@google.com    hh_file = 'debug/%s.hh' % name
96511983Sgabeblack@google.com    env.Command(hh_file, Value(flag),
96612302Sgabeblack@google.com                MakeAction(makeDebugFlagHH, Transform("TRACING", 0)))
96712302Sgabeblack@google.com    env.Depends(SWIG, hh_file)
96812307Sgabeblack@google.com
96912307Sgabeblack@google.comenv.Command('debug/flags.cc', Value(debug_flags),
97011983Sgabeblack@google.com            MakeAction(makeDebugFlagCC, Transform("TRACING", 0)))
97112302Sgabeblack@google.comenv.Depends(SWIG, 'debug/flags.cc')
97212302Sgabeblack@google.comSource('debug/flags.cc')
97311983Sgabeblack@google.com
97411983Sgabeblack@google.com# version tags
97511983Sgabeblack@google.comtags = \
97612310Sgabeblack@google.comenv.Command('sim/tags.cc', None,
97712310Sgabeblack@google.com            MakeAction('util/cpt_upgrader.py --get-cc-file > $TARGET',
97812310Sgabeblack@google.com                       Transform("VER TAGS")))
97912063Sgabeblack@google.comenv.AlwaysBuild(tags)
98012063Sgabeblack@google.com
98112063Sgabeblack@google.com# Embed python files.  All .py files that have been indicated by a
98212310Sgabeblack@google.com# PySource() call in a SConscript need to be embedded into the M5
98312310Sgabeblack@google.com# library.  To do that, we compile the file to byte code, marshal the
98412063Sgabeblack@google.com# byte code, compress it, and then generate a c++ file that
98512063Sgabeblack@google.com# inserts the result into an array.
98611983Sgabeblack@google.comdef embedPyFile(target, source, env):
98711983Sgabeblack@google.com    def c_str(string):
98811983Sgabeblack@google.com        if string is None:
98912310Sgabeblack@google.com            return "0"
99012310Sgabeblack@google.com        return '"%s"' % string
99111983Sgabeblack@google.com
99211983Sgabeblack@google.com    '''Action function to compile a .py into a code object, marshal
99311983Sgabeblack@google.com    it, compress it, and stick it into an asm file so the code appears
99411983Sgabeblack@google.com    as just bytes with a label in the data section'''
99512310Sgabeblack@google.com
99612310Sgabeblack@google.com    src = file(str(source[0]), 'r').read()
9976143Snate@binkert.org
99812307Sgabeblack@google.com    pysource = PySource.tnodes[source[0]]
99912306Sgabeblack@google.com    compiled = compile(src, pysource.abspath, 'exec')
100012310Sgabeblack@google.com    marshalled = marshal.dumps(compiled)
100110453SAndrew.Bardsley@arm.com    compressed = zlib.compress(marshalled)
100212307Sgabeblack@google.com    data = compressed
100312306Sgabeblack@google.com    sym = pysource.symname
100412310Sgabeblack@google.com
10055554Snate@binkert.org    code = code_formatter()
10065522Snate@binkert.org    code('''\
10075522Snate@binkert.org#include "sim/init.hh"
10085797Snate@binkert.org
10095797Snate@binkert.orgnamespace {
10105522Snate@binkert.org
10115601Snate@binkert.orgconst uint8_t data_${sym}[] = {
101212307Sgabeblack@google.com''')
10138233Snate@binkert.org    code.indent()
10148235Snate@binkert.org    step = 16
101512302Sgabeblack@google.com    for i in xrange(0, len(data), step):
101612307Sgabeblack@google.com        x = array.array('B', data[i:i+step])
10179003SAli.Saidi@ARM.com        code(''.join('%d,' % d for d in x))
10189003SAli.Saidi@ARM.com    code.dedent()
101912222Sgabeblack@google.com
102010196SCurtis.Dunham@arm.com    code('''};
10218235Snate@binkert.org
10226143Snate@binkert.orgEmbeddedPython embedded_${sym}(
10232655Sstever@eecs.umich.edu    ${{c_str(pysource.arcname)}},
10246143Snate@binkert.org    ${{c_str(pysource.abspath)}},
10256143Snate@binkert.org    ${{c_str(pysource.modpath)}},
102611985Sgabeblack@google.com    data_${sym},
10276143Snate@binkert.org    ${{len(data)}},
10286143Snate@binkert.org    ${{len(marshalled)}});
10294007Ssaidi@eecs.umich.edu
10304596Sbinkertn@umich.edu} // anonymous namespace
10314007Ssaidi@eecs.umich.edu''')
10324596Sbinkertn@umich.edu    code.write(str(target[0]))
10337756SAli.Saidi@ARM.com
10347816Ssteve.reinhardt@amd.comfor source in PySource.all:
10358334Snate@binkert.org    env.Command(source.cpp, source.tnode,
10368334Snate@binkert.org                MakeAction(embedPyFile, Transform("EMBED PY")))
10378334Snate@binkert.org    env.Depends(SWIG, source.cpp)
10388334Snate@binkert.org    Source(source.cpp, skip_no_python=True)
10395601Snate@binkert.org
104011993Sgabeblack@google.com########################################################################
104111993Sgabeblack@google.com#
104211993Sgabeblack@google.com# Define binaries.  Each different build type (debug, opt, etc.) gets
104312223Sgabeblack@google.com# a slightly different build environment.
104411993Sgabeblack@google.com#
10452655Sstever@eecs.umich.edu
10469225Sandreas.hansson@arm.com# List of constructed environments to pass back to SConstruct
10479225Sandreas.hansson@arm.comdate_source = Source('base/date.cc', skip_lib=True)
10489226Sandreas.hansson@arm.com
10499226Sandreas.hansson@arm.com# Capture this directory for the closure makeEnv, otherwise when it is
10509225Sandreas.hansson@arm.com# called, it won't know what directory it should use.
10519226Sandreas.hansson@arm.comvariant_dir = Dir('.').path
10529226Sandreas.hansson@arm.comdef variant(*path):
10539226Sandreas.hansson@arm.com    return os.path.join(variant_dir, *path)
10549226Sandreas.hansson@arm.comdef variantd(*path):
10559226Sandreas.hansson@arm.com    return variant(*path)+'/'
10569226Sandreas.hansson@arm.com
10579225Sandreas.hansson@arm.com# Function to create a new build environment as clone of current
10589227Sandreas.hansson@arm.com# environment 'env' with modified object suffix and optional stripped
10599227Sandreas.hansson@arm.com# binary.  Additional keyword arguments are appended to corresponding
10609227Sandreas.hansson@arm.com# build environment vars.
10619227Sandreas.hansson@arm.comdef makeEnv(env, label, objsfx, strip = False, **kwargs):
10628946Sandreas.hansson@arm.com    # SCons doesn't know to append a library suffix when there is a '.' in the
10633918Ssaidi@eecs.umich.edu    # name.  Use '_' instead.
10649225Sandreas.hansson@arm.com    libname = variant('gem5_' + label)
10653918Ssaidi@eecs.umich.edu    exename = variant('gem5.' + label)
10669225Sandreas.hansson@arm.com    secondary_exename = variant('m5.' + label)
10679225Sandreas.hansson@arm.com
10689227Sandreas.hansson@arm.com    new_env = env.Clone(OBJSUFFIX=objsfx, SHOBJSUFFIX=objsfx + 's')
10699227Sandreas.hansson@arm.com    new_env.Label = label
10709227Sandreas.hansson@arm.com    new_env.Append(**kwargs)
10719226Sandreas.hansson@arm.com
10729225Sandreas.hansson@arm.com    swig_env = new_env.Clone()
10739227Sandreas.hansson@arm.com
10749227Sandreas.hansson@arm.com    # Both gcc and clang have issues with unused labels and values in
10759227Sandreas.hansson@arm.com    # the SWIG generated code
10769227Sandreas.hansson@arm.com    swig_env.Append(CCFLAGS=['-Wno-unused-label', '-Wno-unused-value'])
10778946Sandreas.hansson@arm.com
10789225Sandreas.hansson@arm.com    if env['GCC']:
10799226Sandreas.hansson@arm.com        # Depending on the SWIG version, we also need to supress
10809226Sandreas.hansson@arm.com        # warnings about uninitialized variables and missing field
10819226Sandreas.hansson@arm.com        # initializers.
10823515Ssaidi@eecs.umich.edu        swig_env.Append(CCFLAGS=['-Wno-uninitialized',
10833918Ssaidi@eecs.umich.edu                                 '-Wno-missing-field-initializers',
10844762Snate@binkert.org                                 '-Wno-unused-but-set-variable',
10853515Ssaidi@eecs.umich.edu                                 '-Wno-maybe-uninitialized',
10868881Smarc.orr@gmail.com                                 '-Wno-type-limits'])
10878881Smarc.orr@gmail.com
10888881Smarc.orr@gmail.com
10898881Smarc.orr@gmail.com        # The address sanitizer is available for gcc >= 4.8
10908881Smarc.orr@gmail.com        if GetOption('with_asan'):
10919226Sandreas.hansson@arm.com            if GetOption('with_ubsan') and \
10929226Sandreas.hansson@arm.com                    compareVersions(env['GCC_VERSION'], '4.9') >= 0:
10939226Sandreas.hansson@arm.com                new_env.Append(CCFLAGS=['-fsanitize=address,undefined',
10948881Smarc.orr@gmail.com                                        '-fno-omit-frame-pointer'])
10958881Smarc.orr@gmail.com                new_env.Append(LINKFLAGS='-fsanitize=address,undefined')
10968881Smarc.orr@gmail.com            else:
10978881Smarc.orr@gmail.com                new_env.Append(CCFLAGS=['-fsanitize=address',
10988881Smarc.orr@gmail.com                                        '-fno-omit-frame-pointer'])
10998881Smarc.orr@gmail.com                new_env.Append(LINKFLAGS='-fsanitize=address')
11008881Smarc.orr@gmail.com        # Only gcc >= 4.9 supports UBSan, so check both the version
11018881Smarc.orr@gmail.com        # and the command-line option before adding the compiler and
11028881Smarc.orr@gmail.com        # linker flags.
11038881Smarc.orr@gmail.com        elif GetOption('with_ubsan') and \
11048881Smarc.orr@gmail.com                compareVersions(env['GCC_VERSION'], '4.9') >= 0:
11058881Smarc.orr@gmail.com            new_env.Append(CCFLAGS='-fsanitize=undefined')
11068881Smarc.orr@gmail.com            new_env.Append(LINKFLAGS='-fsanitize=undefined')
11078881Smarc.orr@gmail.com
11088881Smarc.orr@gmail.com
11098881Smarc.orr@gmail.com    if env['CLANG']:
111012222Sgabeblack@google.com        swig_env.Append(CCFLAGS=['-Wno-sometimes-uninitialized',
111112222Sgabeblack@google.com                                 '-Wno-deprecated-register',
111212222Sgabeblack@google.com                                 '-Wno-tautological-compare'])
111312222Sgabeblack@google.com
111412222Sgabeblack@google.com        # We require clang >= 3.1, so there is no need to check any
111512222Sgabeblack@google.com        # versions here.
1116955SN/A        if GetOption('with_ubsan'):
111712222Sgabeblack@google.com            if GetOption('with_asan'):
111812222Sgabeblack@google.com                new_env.Append(CCFLAGS=['-fsanitize=address,undefined',
111912222Sgabeblack@google.com                                        '-fno-omit-frame-pointer'])
112012222Sgabeblack@google.com                new_env.Append(LINKFLAGS='-fsanitize=address,undefined')
112112222Sgabeblack@google.com            else:
112212222Sgabeblack@google.com                new_env.Append(CCFLAGS='-fsanitize=undefined')
1123955SN/A                new_env.Append(LINKFLAGS='-fsanitize=undefined')
112412222Sgabeblack@google.com
112512222Sgabeblack@google.com        elif GetOption('with_asan'):
112612222Sgabeblack@google.com            new_env.Append(CCFLAGS=['-fsanitize=address',
112712222Sgabeblack@google.com                                    '-fno-omit-frame-pointer'])
112812222Sgabeblack@google.com            new_env.Append(LINKFLAGS='-fsanitize=address')
112912222Sgabeblack@google.com
113012222Sgabeblack@google.com    werror_env = new_env.Clone()
113112222Sgabeblack@google.com    # Treat warnings as errors but white list some warnings that we
113212222Sgabeblack@google.com    # want to allow (e.g., deprecation warnings).
113312222Sgabeblack@google.com    werror_env.Append(CCFLAGS=['-Werror',
11341869SN/A                               '-Wno-error=deprecated-declarations',
113512222Sgabeblack@google.com                               '-Wno-error=deprecated',
113612222Sgabeblack@google.com                               ])
113712222Sgabeblack@google.com
113812222Sgabeblack@google.com    def make_obj(source, static, extra_deps = None):
113912222Sgabeblack@google.com        '''This function adds the specified source to the correct
114012222Sgabeblack@google.com        build environment, and returns the corresponding SCons Object
11419226Sandreas.hansson@arm.com        nodes'''
114212222Sgabeblack@google.com
114312222Sgabeblack@google.com        if source.swig:
114412222Sgabeblack@google.com            env = swig_env
114512222Sgabeblack@google.com        elif source.Werror:
114612222Sgabeblack@google.com            env = werror_env
114712222Sgabeblack@google.com        else:
1148            env = new_env
1149
1150        if static:
1151            obj = env.StaticObject(source.tnode)
1152        else:
1153            obj = env.SharedObject(source.tnode)
1154
1155        if extra_deps:
1156            env.Depends(obj, extra_deps)
1157
1158        return obj
1159
1160    lib_guards = {'main': False, 'skip_lib': False}
1161
1162    # Without Python, leave out all SWIG and Python content from the
1163    # library builds.  The option doesn't affect gem5 built as a program
1164    if GetOption('without_python'):
1165        lib_guards['skip_no_python'] = False
1166
1167    static_objs = [ make_obj(s, True) for s in Source.get(**lib_guards) ]
1168    shared_objs = [ make_obj(s, False) for s in Source.get(**lib_guards) ]
1169
1170    static_date = make_obj(date_source, static=True, extra_deps=static_objs)
1171    static_objs.append(static_date)
1172
1173    shared_date = make_obj(date_source, static=False, extra_deps=shared_objs)
1174    shared_objs.append(shared_date)
1175
1176    # First make a library of everything but main() so other programs can
1177    # link against m5.
1178    static_lib = new_env.StaticLibrary(libname, static_objs)
1179    shared_lib = new_env.SharedLibrary(libname, shared_objs)
1180
1181    # Now link a stub with main() and the static library.
1182    main_objs = [ make_obj(s, True) for s in Source.get(main=True) ]
1183
1184    for test in UnitTest.all:
1185        flags = { test.target : True }
1186        test_sources = Source.get(**flags)
1187        test_objs = [ make_obj(s, static=True) for s in test_sources ]
1188        if test.main:
1189            test_objs += main_objs
1190        path = variant('unittest/%s.%s' % (test.target, label))
1191        new_env.Program(path, test_objs + static_objs)
1192
1193    progname = exename
1194    if strip:
1195        progname += '.unstripped'
1196
1197    targets = new_env.Program(progname, main_objs + static_objs)
1198
1199    if strip:
1200        if sys.platform == 'sunos5':
1201            cmd = 'cp $SOURCE $TARGET; strip $TARGET'
1202        else:
1203            cmd = 'strip $SOURCE -o $TARGET'
1204        targets = new_env.Command(exename, progname,
1205                    MakeAction(cmd, Transform("STRIP")))
1206
1207    new_env.Command(secondary_exename, exename,
1208            MakeAction('ln $SOURCE $TARGET', Transform("HARDLINK")))
1209
1210    new_env.M5Binary = targets[0]
1211    return new_env
1212
1213# Start out with the compiler flags common to all compilers,
1214# i.e. they all use -g for opt and -g -pg for prof
1215ccflags = {'debug' : [], 'opt' : ['-g'], 'fast' : [], 'prof' : ['-g', '-pg'],
1216           'perf' : ['-g']}
1217
1218# Start out with the linker flags common to all linkers, i.e. -pg for
1219# prof, and -lprofiler for perf. The -lprofile flag is surrounded by
1220# no-as-needed and as-needed as the binutils linker is too clever and
1221# simply doesn't link to the library otherwise.
1222ldflags = {'debug' : [], 'opt' : [], 'fast' : [], 'prof' : ['-pg'],
1223           'perf' : ['-Wl,--no-as-needed', '-lprofiler', '-Wl,--as-needed']}
1224
1225# For Link Time Optimization, the optimisation flags used to compile
1226# individual files are decoupled from those used at link time
1227# (i.e. you can compile with -O3 and perform LTO with -O0), so we need
1228# to also update the linker flags based on the target.
1229if env['GCC']:
1230    if sys.platform == 'sunos5':
1231        ccflags['debug'] += ['-gstabs+']
1232    else:
1233        ccflags['debug'] += ['-ggdb3']
1234    ldflags['debug'] += ['-O0']
1235    # opt, fast, prof and perf all share the same cc flags, also add
1236    # the optimization to the ldflags as LTO defers the optimization
1237    # to link time
1238    for target in ['opt', 'fast', 'prof', 'perf']:
1239        ccflags[target] += ['-O3']
1240        ldflags[target] += ['-O3']
1241
1242    ccflags['fast'] += env['LTO_CCFLAGS']
1243    ldflags['fast'] += env['LTO_LDFLAGS']
1244elif env['CLANG']:
1245    ccflags['debug'] += ['-g', '-O0']
1246    # opt, fast, prof and perf all share the same cc flags
1247    for target in ['opt', 'fast', 'prof', 'perf']:
1248        ccflags[target] += ['-O3']
1249else:
1250    print 'Unknown compiler, please fix compiler options'
1251    Exit(1)
1252
1253
1254# To speed things up, we only instantiate the build environments we
1255# need.  We try to identify the needed environment for each target; if
1256# we can't, we fall back on instantiating all the environments just to
1257# be safe.
1258target_types = ['debug', 'opt', 'fast', 'prof', 'perf']
1259obj2target = {'do': 'debug', 'o': 'opt', 'fo': 'fast', 'po': 'prof',
1260              'gpo' : 'perf'}
1261
1262def identifyTarget(t):
1263    ext = t.split('.')[-1]
1264    if ext in target_types:
1265        return ext
1266    if obj2target.has_key(ext):
1267        return obj2target[ext]
1268    match = re.search(r'/tests/([^/]+)/', t)
1269    if match and match.group(1) in target_types:
1270        return match.group(1)
1271    return 'all'
1272
1273needed_envs = [identifyTarget(target) for target in BUILD_TARGETS]
1274if 'all' in needed_envs:
1275    needed_envs += target_types
1276
1277def makeEnvirons(target, source, env):
1278    # cause any later Source() calls to be fatal, as a diagnostic.
1279    Source.done()
1280
1281    envList = []
1282
1283    # Debug binary
1284    if 'debug' in needed_envs:
1285        envList.append(
1286            makeEnv(env, 'debug', '.do',
1287                    CCFLAGS = Split(ccflags['debug']),
1288                    CPPDEFINES = ['DEBUG', 'TRACING_ON=1'],
1289                    LINKFLAGS = Split(ldflags['debug'])))
1290
1291    # Optimized binary
1292    if 'opt' in needed_envs:
1293        envList.append(
1294            makeEnv(env, 'opt', '.o',
1295                    CCFLAGS = Split(ccflags['opt']),
1296                    CPPDEFINES = ['TRACING_ON=1'],
1297                    LINKFLAGS = Split(ldflags['opt'])))
1298
1299    # "Fast" binary
1300    if 'fast' in needed_envs:
1301        envList.append(
1302            makeEnv(env, 'fast', '.fo', strip = True,
1303                    CCFLAGS = Split(ccflags['fast']),
1304                    CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1305                    LINKFLAGS = Split(ldflags['fast'])))
1306
1307    # Profiled binary using gprof
1308    if 'prof' in needed_envs:
1309        envList.append(
1310            makeEnv(env, 'prof', '.po',
1311                    CCFLAGS = Split(ccflags['prof']),
1312                    CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1313                    LINKFLAGS = Split(ldflags['prof'])))
1314
1315    # Profiled binary using google-pprof
1316    if 'perf' in needed_envs:
1317        envList.append(
1318            makeEnv(env, 'perf', '.gpo',
1319                    CCFLAGS = Split(ccflags['perf']),
1320                    CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1321                    LINKFLAGS = Split(ldflags['perf'])))
1322
1323    # Set up the regression tests for each build.
1324    for e in envList:
1325        SConscript(os.path.join(env.root.abspath, 'tests', 'SConscript'),
1326                   variant_dir = variantd('tests', e.Label),
1327                   exports = { 'env' : e }, duplicate = False)
1328
1329# The MakeEnvirons Builder defers the full dependency collection until
1330# after processing the ISA definition (due to dynamically generated
1331# source files).  Add this dependency to all targets so they will wait
1332# until the environments are completely set up.  Otherwise, a second
1333# process (e.g. -j2 or higher) will try to compile the requested target,
1334# not know how, and fail.
1335env.Append(BUILDERS = {'MakeEnvirons' :
1336                        Builder(action=MakeAction(makeEnvirons,
1337                                                  Transform("ENVIRONS", 1)))})
1338
1339isa_target = env['PHONY_BASE'] + '-deps'
1340environs   = env['PHONY_BASE'] + '-environs'
1341env.Depends('#all-deps',     isa_target)
1342env.Depends('#all-environs', environs)
1343env.ScanISA(isa_target, File('arch/%s/generated/inc.d' % env['TARGET_ISA']))
1344envSetup = env.MakeEnvirons(environs, isa_target)
1345
1346# make sure no -deps targets occur before all ISAs are complete
1347env.Depends(isa_target, '#all-isas')
1348# likewise for -environs targets and all the -deps targets
1349env.Depends(environs, '#all-deps')
1350