SConscript revision 11985
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 subprocess
38955SN/Aimport sys
395522Snate@binkert.orgimport zlib
404202Sbinkertn@umich.edu
415742Snate@binkert.orgfrom os.path import basename, dirname, exists, isdir, isfile, join as joinpath
42955SN/A
434381Sbinkertn@umich.eduimport SCons
444381Sbinkertn@umich.edu
458334Snate@binkert.org# This file defines how to build a particular configuration of gem5
46955SN/A# based on variable settings in the 'env' build environment.
47955SN/A
484202Sbinkertn@umich.eduImport('*')
49955SN/A
504382Sbinkertn@umich.edu# Children need to see the environment
514382Sbinkertn@umich.eduExport('env')
524382Sbinkertn@umich.edu
536654Snate@binkert.orgbuild_env = [(opt, env[opt]) for opt in export_vars]
545517Snate@binkert.org
558614Sgblack@eecs.umich.edufrom m5.util import code_formatter, compareVersions
567674Snate@binkert.org
576143Snate@binkert.org########################################################################
586143Snate@binkert.org# Code for adding source files of various types
596143Snate@binkert.org#
608233Snate@binkert.org# When specifying a source file of some type, a set of guards can be
618233Snate@binkert.org# specified for that file.  When get() is used to find the files, if
628233Snate@binkert.org# get specifies a set of filters, only files that match those filters
638233Snate@binkert.org# will be accepted (unspecified filters on files are assumed to be
648233Snate@binkert.org# false).  Current filters are:
658334Snate@binkert.org#     main -- specifies the gem5 main() function
668334Snate@binkert.org#     skip_lib -- do not put this file into the gem5 library
6710453SAndrew.Bardsley@arm.com#     skip_no_python -- do not put this file into a no_python library
6810453SAndrew.Bardsley@arm.com#       as it embeds compiled Python
698233Snate@binkert.org#     <unittest> -- unit tests use filters based on the unit test name
708233Snate@binkert.org#
718233Snate@binkert.org# A parent can now be specified for a source file and default filter
728233Snate@binkert.org# values will be retrieved recursively from parents (children override
738233Snate@binkert.org# parents).
748233Snate@binkert.org#
7511983Sgabeblack@google.comdef guarded_source_iterator(sources, **guards):
7611983Sgabeblack@google.com    '''Iterate over a set of sources, gated by a set of guards.'''
7711983Sgabeblack@google.com    for src in sources:
7811983Sgabeblack@google.com        for flag,value in guards.iteritems():
7911983Sgabeblack@google.com            # if the flag is found and has a different value, skip
8011983Sgabeblack@google.com            # this file
8111983Sgabeblack@google.com            if src.all_guards.get(flag, False) != value:
8211983Sgabeblack@google.com                break
8311983Sgabeblack@google.com        else:
8411983Sgabeblack@google.com            yield src
8511983Sgabeblack@google.com
866143Snate@binkert.orgclass SourceMeta(type):
878233Snate@binkert.org    '''Meta class for source files that keeps track of all files of a
888233Snate@binkert.org    particular type and has a get function for finding all functions
898233Snate@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 = []
9311308Santhony.gutierrez@amd.com
948233Snate@binkert.org    def get(cls, **guards):
958233Snate@binkert.org        '''Find all files that match the specified guards.  If a source
968233Snate@binkert.org        file does not specify a flag, the default is False'''
9711983Sgabeblack@google.com        for s in guarded_source_iterator(cls.all, **guards):
9811983Sgabeblack@google.com            yield s
994762Snate@binkert.org
1006143Snate@binkert.orgclass SourceFile(object):
1018233Snate@binkert.org    '''Base object that encapsulates the notion of a source file.
1028233Snate@binkert.org    This includes, the source node, target node, various manipulations
1038233Snate@binkert.org    of those.  A source file also specifies a set of guards which
1048233Snate@binkert.org    describing which builds the source file applies to.  A parent can
1058233Snate@binkert.org    also be specified to get default guards from'''
1066143Snate@binkert.org    __metaclass__ = SourceMeta
1078233Snate@binkert.org    def __init__(self, source, parent=None, **guards):
1088233Snate@binkert.org        self.guards = guards
1098233Snate@binkert.org        self.parent = parent
1108233Snate@binkert.org
1116143Snate@binkert.org        tnode = source
1126143Snate@binkert.org        if not isinstance(source, SCons.Node.FS.File):
1136143Snate@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):
1207065Snate@binkert.org                base.all.append(self)
1216143Snate@binkert.org
1228233Snate@binkert.org    @property
1238233Snate@binkert.org    def filename(self):
1248233Snate@binkert.org        return str(self.tnode)
1258233Snate@binkert.org
1268233Snate@binkert.org    @property
1278233Snate@binkert.org    def dirname(self):
1288233Snate@binkert.org        return dirname(self.filename)
1298233Snate@binkert.org
1308233Snate@binkert.org    @property
1318233Snate@binkert.org    def basename(self):
1328233Snate@binkert.org        return basename(self.filename)
1338233Snate@binkert.org
1348233Snate@binkert.org    @property
1358233Snate@binkert.org    def extname(self):
1368233Snate@binkert.org        index = self.basename.rfind('.')
1378233Snate@binkert.org        if index <= 0:
1388233Snate@binkert.org            # dot files aren't extensions
1398233Snate@binkert.org            return self.basename, None
1408233Snate@binkert.org
1418233Snate@binkert.org        return self.basename[:index], self.basename[index+1:]
1428233Snate@binkert.org
1438233Snate@binkert.org    @property
1448233Snate@binkert.org    def all_guards(self):
1458233Snate@binkert.org        '''find all guards for this object getting default values
1468233Snate@binkert.org        recursively from its parents'''
1478233Snate@binkert.org        guards = {}
1488233Snate@binkert.org        if self.parent:
1498233Snate@binkert.org            guards.update(self.parent.guards)
1508233Snate@binkert.org        guards.update(self.guards)
1518233Snate@binkert.org        return guards
1528233Snate@binkert.org
1536143Snate@binkert.org    def __lt__(self, other): return self.filename < other.filename
1546143Snate@binkert.org    def __le__(self, other): return self.filename <= other.filename
1556143Snate@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
1586143Snate@binkert.org    def __ne__(self, other): return self.filename != other.filename
1599982Satgutier@umich.edu
16010196SCurtis.Dunham@arm.com    @staticmethod
16110196SCurtis.Dunham@arm.com    def done():
16210196SCurtis.Dunham@arm.com        def disabled(cls, name, *ignored):
16310196SCurtis.Dunham@arm.com            raise RuntimeError("Additional SourceFile '%s'" % name,\
16410196SCurtis.Dunham@arm.com                  "declared, but targets deps are already fixed.")
16510196SCurtis.Dunham@arm.com        SourceFile.__init__ = disabled
16610196SCurtis.Dunham@arm.com
16710196SCurtis.Dunham@arm.com
1686143Snate@binkert.orgclass Source(SourceFile):
16911983Sgabeblack@google.com    current_group = None
17011983Sgabeblack@google.com    source_groups = { None : [] }
17111983Sgabeblack@google.com
17211983Sgabeblack@google.com    @classmethod
17311983Sgabeblack@google.com    def set_group(cls, group):
17411983Sgabeblack@google.com        if not group in Source.source_groups:
17511983Sgabeblack@google.com            Source.source_groups[group] = []
17611983Sgabeblack@google.com        Source.current_group = group
17711983Sgabeblack@google.com
1786143Snate@binkert.org    '''Add a c/c++ source file to the build'''
1798945Ssteve.reinhardt@amd.com    def __init__(self, source, Werror=True, swig=False, **guards):
1808233Snate@binkert.org        '''specify the source file, and any guards'''
1818233Snate@binkert.org        super(Source, self).__init__(source, **guards)
1826143Snate@binkert.org
1838945Ssteve.reinhardt@amd.com        self.Werror = Werror
1846143Snate@binkert.org        self.swig = swig
1856143Snate@binkert.org
18611983Sgabeblack@google.com        Source.source_groups[Source.current_group].append(self)
18711983Sgabeblack@google.com
1886143Snate@binkert.orgclass PySource(SourceFile):
1896143Snate@binkert.org    '''Add a python source file to the named package'''
1905522Snate@binkert.org    invalid_sym_char = re.compile('[^A-z0-9_]')
1916143Snate@binkert.org    modules = {}
1926143Snate@binkert.org    tnodes = {}
1936143Snate@binkert.org    symnames = {}
1949982Satgutier@umich.edu
1958233Snate@binkert.org    def __init__(self, package, source, **guards):
1968233Snate@binkert.org        '''specify the python package, the source file, and any guards'''
1978233Snate@binkert.org        super(PySource, self).__init__(source, **guards)
1986143Snate@binkert.org
1996143Snate@binkert.org        modname,ext = self.extname
2006143Snate@binkert.org        assert ext == 'py'
2016143Snate@binkert.org
2025522Snate@binkert.org        if package:
2035522Snate@binkert.org            path = package.split('.')
2045522Snate@binkert.org        else:
2055522Snate@binkert.org            path = []
2065604Snate@binkert.org
2075604Snate@binkert.org        modpath = path[:]
2086143Snate@binkert.org        if modname != '__init__':
2096143Snate@binkert.org            modpath += [ modname ]
2104762Snate@binkert.org        modpath = '.'.join(modpath)
2114762Snate@binkert.org
2126143Snate@binkert.org        arcpath = path + [ self.basename ]
2136727Ssteve.reinhardt@amd.com        abspath = self.snode.abspath
2146727Ssteve.reinhardt@amd.com        if not exists(abspath):
2156727Ssteve.reinhardt@amd.com            abspath = self.tnode.abspath
2164762Snate@binkert.org
2176143Snate@binkert.org        self.package = package
2186143Snate@binkert.org        self.modname = modname
2196143Snate@binkert.org        self.modpath = modpath
2206143Snate@binkert.org        self.arcname = joinpath(*arcpath)
2216727Ssteve.reinhardt@amd.com        self.abspath = abspath
2226143Snate@binkert.org        self.compiled = File(self.filename + 'c')
2237674Snate@binkert.org        self.cpp = File(self.filename + '.cc')
2247674Snate@binkert.org        self.symname = PySource.invalid_sym_char.sub('_', modpath)
2255604Snate@binkert.org
2266143Snate@binkert.org        PySource.modules[modpath] = self
2276143Snate@binkert.org        PySource.tnodes[self.tnode] = self
2286143Snate@binkert.org        PySource.symnames[self.symname] = self
2294762Snate@binkert.org
2306143Snate@binkert.orgclass SimObject(PySource):
2314762Snate@binkert.org    '''Add a SimObject python file as a python source object and add
2324762Snate@binkert.org    it to a list of sim object modules'''
2334762Snate@binkert.org
2346143Snate@binkert.org    fixed = False
2356143Snate@binkert.org    modnames = []
2364762Snate@binkert.org
2378233Snate@binkert.org    def __init__(self, source, **guards):
2388233Snate@binkert.org        '''Specify the source file and any guards (automatically in
2398233Snate@binkert.org        the m5.objects package)'''
2408233Snate@binkert.org        super(SimObject, self).__init__('m5.objects', source, **guards)
2416143Snate@binkert.org        if self.fixed:
2426143Snate@binkert.org            raise AttributeError, "Too late to call SimObject now."
2434762Snate@binkert.org
2446143Snate@binkert.org        bisect.insort_right(SimObject.modnames, self.modname)
2454762Snate@binkert.org
2466143Snate@binkert.orgclass SwigSource(SourceFile):
2474762Snate@binkert.org    '''Add a swig file to build'''
2486143Snate@binkert.org
2498233Snate@binkert.org    def __init__(self, package, source, **guards):
2508233Snate@binkert.org        '''Specify the python package, the source file, and any guards'''
25110453SAndrew.Bardsley@arm.com        super(SwigSource, self).__init__(source, skip_no_python=True, **guards)
2526143Snate@binkert.org
2536143Snate@binkert.org        modname,ext = self.extname
2546143Snate@binkert.org        assert ext == 'i'
2556143Snate@binkert.org
25611548Sandreas.hansson@arm.com        self.package = package
2576143Snate@binkert.org        self.module = modname
2586143Snate@binkert.org        cc_file = joinpath(self.dirname, modname + '_wrap.cc')
2596143Snate@binkert.org        py_file = joinpath(self.dirname, modname + '.py')
2606143Snate@binkert.org
26110453SAndrew.Bardsley@arm.com        self.cc_source = Source(cc_file, swig=True, parent=self, **guards)
26210453SAndrew.Bardsley@arm.com        self.py_source = PySource(package, py_file, parent=self, **guards)
263955SN/A
2649396Sandreas.hansson@arm.comclass ProtoBuf(SourceFile):
2659396Sandreas.hansson@arm.com    '''Add a Protocol Buffer to build'''
2669396Sandreas.hansson@arm.com
2679396Sandreas.hansson@arm.com    def __init__(self, source, **guards):
2689396Sandreas.hansson@arm.com        '''Specify the source file, and any guards'''
2699396Sandreas.hansson@arm.com        super(ProtoBuf, self).__init__(source, **guards)
2709396Sandreas.hansson@arm.com
2719396Sandreas.hansson@arm.com        # Get the file name and the extension
2729396Sandreas.hansson@arm.com        modname,ext = self.extname
2739396Sandreas.hansson@arm.com        assert ext == 'proto'
2749396Sandreas.hansson@arm.com
2759396Sandreas.hansson@arm.com        # Currently, we stick to generating the C++ headers, so we
2769396Sandreas.hansson@arm.com        # only need to track the source and header.
2779930Sandreas.hansson@arm.com        self.cc_file = File(modname + '.pb.cc')
2789930Sandreas.hansson@arm.com        self.hh_file = File(modname + '.pb.h')
2799396Sandreas.hansson@arm.com
2808235Snate@binkert.orgclass UnitTest(object):
2818235Snate@binkert.org    '''Create a UnitTest'''
2826143Snate@binkert.org
2838235Snate@binkert.org    all = []
2849003SAli.Saidi@ARM.com    def __init__(self, target, *sources, **kwargs):
2858235Snate@binkert.org        '''Specify the target name and any sources.  Sources that are
2868235Snate@binkert.org        not SourceFiles are evalued with Source().  All files are
2878235Snate@binkert.org        guarded with a guard of the same name as the UnitTest
2888235Snate@binkert.org        target.'''
2898235Snate@binkert.org
2908235Snate@binkert.org        srcs = []
2918235Snate@binkert.org        for src in sources:
2928235Snate@binkert.org            if not isinstance(src, SourceFile):
2938235Snate@binkert.org                src = Source(src, skip_lib=True)
2948235Snate@binkert.org            src.guards[target] = True
2958235Snate@binkert.org            srcs.append(src)
2968235Snate@binkert.org
2978235Snate@binkert.org        self.sources = srcs
2988235Snate@binkert.org        self.target = target
2999003SAli.Saidi@ARM.com        self.main = kwargs.get('main', False)
3008235Snate@binkert.org        UnitTest.all.append(self)
3015584Snate@binkert.org
3024382Sbinkertn@umich.edu# Children should have access
3034202Sbinkertn@umich.eduExport('Source')
3044382Sbinkertn@umich.eduExport('PySource')
3054382Sbinkertn@umich.eduExport('SimObject')
3064382Sbinkertn@umich.eduExport('SwigSource')
3079396Sandreas.hansson@arm.comExport('ProtoBuf')
3085584Snate@binkert.orgExport('UnitTest')
3094382Sbinkertn@umich.edu
3104382Sbinkertn@umich.edu########################################################################
3114382Sbinkertn@umich.edu#
3128232Snate@binkert.org# Debug Flags
3135192Ssaidi@eecs.umich.edu#
3148232Snate@binkert.orgdebug_flags = {}
3158232Snate@binkert.orgdef DebugFlag(name, desc=None):
3168232Snate@binkert.org    if name in debug_flags:
3175192Ssaidi@eecs.umich.edu        raise AttributeError, "Flag %s already specified" % name
3188232Snate@binkert.org    debug_flags[name] = (name, (), desc)
3195192Ssaidi@eecs.umich.edu
3205799Snate@binkert.orgdef CompoundFlag(name, flags, desc=None):
3218232Snate@binkert.org    if name in debug_flags:
3225192Ssaidi@eecs.umich.edu        raise AttributeError, "Flag %s already specified" % name
3235192Ssaidi@eecs.umich.edu
3245192Ssaidi@eecs.umich.edu    compound = tuple(flags)
3258232Snate@binkert.org    debug_flags[name] = (name, compound, desc)
3265192Ssaidi@eecs.umich.edu
3278232Snate@binkert.orgExport('DebugFlag')
3285192Ssaidi@eecs.umich.eduExport('CompoundFlag')
3295192Ssaidi@eecs.umich.edu
3305192Ssaidi@eecs.umich.edu########################################################################
3315192Ssaidi@eecs.umich.edu#
3324382Sbinkertn@umich.edu# Set some compiler variables
3334382Sbinkertn@umich.edu#
3344382Sbinkertn@umich.edu
3352667Sstever@eecs.umich.edu# Include file paths are rooted in this directory.  SCons will
3362667Sstever@eecs.umich.edu# automatically expand '.' to refer to both the source directory and
3372667Sstever@eecs.umich.edu# the corresponding build directory to pick up generated include
3382667Sstever@eecs.umich.edu# files.
3392667Sstever@eecs.umich.eduenv.Append(CPPPATH=Dir('.'))
3402667Sstever@eecs.umich.edu
3415742Snate@binkert.orgfor extra_dir in extras_dir_list:
3425742Snate@binkert.org    env.Append(CPPPATH=Dir(extra_dir))
3435742Snate@binkert.org
3445793Snate@binkert.org# Workaround for bug in SCons version > 0.97d20071212
3458334Snate@binkert.org# Scons bug id: 2006 gem5 Bug id: 308
3465793Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
3475793Snate@binkert.org    Dir(root[len(base_dir) + 1:])
3485793Snate@binkert.org
3494382Sbinkertn@umich.edu########################################################################
3504762Snate@binkert.org#
3515344Sstever@gmail.com# Walk the tree and execute all SConscripts in subdirectories
3524382Sbinkertn@umich.edu#
3535341Sstever@gmail.com
3545742Snate@binkert.orghere = Dir('.').srcnode().abspath
3555742Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
3565742Snate@binkert.org    if root == here:
3575742Snate@binkert.org        # we don't want to recurse back into this SConscript
3585742Snate@binkert.org        continue
3594762Snate@binkert.org
3605742Snate@binkert.org    if 'SConscript' in files:
3615742Snate@binkert.org        build_dir = joinpath(env['BUILDDIR'], root[len(base_dir) + 1:])
36211984Sgabeblack@google.com        Source.set_group(build_dir)
3637722Sgblack@eecs.umich.edu        SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3645742Snate@binkert.org
3655742Snate@binkert.orgfor extra_dir in extras_dir_list:
3665742Snate@binkert.org    prefix_len = len(dirname(extra_dir)) + 1
3679930Sandreas.hansson@arm.com
3689930Sandreas.hansson@arm.com    # Also add the corresponding build directory to pick up generated
3699930Sandreas.hansson@arm.com    # include files.
3709930Sandreas.hansson@arm.com    env.Append(CPPPATH=Dir(joinpath(env['BUILDDIR'], extra_dir[prefix_len:])))
3719930Sandreas.hansson@arm.com
3725742Snate@binkert.org    for root, dirs, files in os.walk(extra_dir, topdown=True):
3738242Sbradley.danofsky@amd.com        # if build lives in the extras directory, don't walk down it
3748242Sbradley.danofsky@amd.com        if 'build' in dirs:
3758242Sbradley.danofsky@amd.com            dirs.remove('build')
3768242Sbradley.danofsky@amd.com
3775341Sstever@gmail.com        if 'SConscript' in files:
3785742Snate@binkert.org            build_dir = joinpath(env['BUILDDIR'], root[prefix_len:])
3797722Sgblack@eecs.umich.edu            SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3804773Snate@binkert.org
3816108Snate@binkert.orgfor opt in export_vars:
3821858SN/A    env.ConfigFile(opt)
3831085SN/A
3846658Snate@binkert.orgdef makeTheISA(source, target, env):
3856658Snate@binkert.org    isas = [ src.get_contents() for src in source ]
3867673Snate@binkert.org    target_isa = env['TARGET_ISA']
3876658Snate@binkert.org    def define(isa):
3886658Snate@binkert.org        return isa.upper() + '_ISA'
38911308Santhony.gutierrez@amd.com
3906658Snate@binkert.org    def namespace(isa):
39111308Santhony.gutierrez@amd.com        return isa[0].upper() + isa[1:].lower() + 'ISA'
3926658Snate@binkert.org
3936658Snate@binkert.org
3947673Snate@binkert.org    code = code_formatter()
3957673Snate@binkert.org    code('''\
3967673Snate@binkert.org#ifndef __CONFIG_THE_ISA_HH__
3977673Snate@binkert.org#define __CONFIG_THE_ISA_HH__
3987673Snate@binkert.org
3997673Snate@binkert.org''')
4007673Snate@binkert.org
40110467Sandreas.hansson@arm.com    # create defines for the preprocessing and compile-time determination
4026658Snate@binkert.org    for i,isa in enumerate(isas):
4037673Snate@binkert.org        code('#define $0 $1', define(isa), i + 1)
40410467Sandreas.hansson@arm.com    code()
40510467Sandreas.hansson@arm.com
40610467Sandreas.hansson@arm.com    # create an enum for any run-time determination of the ISA, we
40710467Sandreas.hansson@arm.com    # reuse the same name as the namespaces
40810467Sandreas.hansson@arm.com    code('enum class Arch {')
40910467Sandreas.hansson@arm.com    for i,isa in enumerate(isas):
41010467Sandreas.hansson@arm.com        if i + 1 == len(isas):
41110467Sandreas.hansson@arm.com            code('  $0 = $1', namespace(isa), define(isa))
41210467Sandreas.hansson@arm.com        else:
41310467Sandreas.hansson@arm.com            code('  $0 = $1,', namespace(isa), define(isa))
41410467Sandreas.hansson@arm.com    code('};')
4157673Snate@binkert.org
4167673Snate@binkert.org    code('''
4177673Snate@binkert.org
4187673Snate@binkert.org#define THE_ISA ${{define(target_isa)}}
4197673Snate@binkert.org#define TheISA ${{namespace(target_isa)}}
4209048SAli.Saidi@ARM.com#define THE_ISA_STR "${{target_isa}}"
4217673Snate@binkert.org
4227673Snate@binkert.org#endif // __CONFIG_THE_ISA_HH__''')
4237673Snate@binkert.org
4247673Snate@binkert.org    code.write(str(target[0]))
4256658Snate@binkert.org
4267756SAli.Saidi@ARM.comenv.Command('config/the_isa.hh', map(Value, all_isa_list),
4277816Ssteve.reinhardt@amd.com            MakeAction(makeTheISA, Transform("CFG ISA", 0)))
4286658Snate@binkert.org
42911308Santhony.gutierrez@amd.comdef makeTheGPUISA(source, target, env):
43011308Santhony.gutierrez@amd.com    isas = [ src.get_contents() for src in source ]
43111308Santhony.gutierrez@amd.com    target_gpu_isa = env['TARGET_GPU_ISA']
43211308Santhony.gutierrez@amd.com    def define(isa):
43311308Santhony.gutierrez@amd.com        return isa.upper() + '_ISA'
43411308Santhony.gutierrez@amd.com
43511308Santhony.gutierrez@amd.com    def namespace(isa):
43611308Santhony.gutierrez@amd.com        return isa[0].upper() + isa[1:].lower() + 'ISA'
43711308Santhony.gutierrez@amd.com
43811308Santhony.gutierrez@amd.com
43911308Santhony.gutierrez@amd.com    code = code_formatter()
44011308Santhony.gutierrez@amd.com    code('''\
44111308Santhony.gutierrez@amd.com#ifndef __CONFIG_THE_GPU_ISA_HH__
44211308Santhony.gutierrez@amd.com#define __CONFIG_THE_GPU_ISA_HH__
44311308Santhony.gutierrez@amd.com
44411308Santhony.gutierrez@amd.com''')
44511308Santhony.gutierrez@amd.com
44611308Santhony.gutierrez@amd.com    # create defines for the preprocessing and compile-time determination
44711308Santhony.gutierrez@amd.com    for i,isa in enumerate(isas):
44811308Santhony.gutierrez@amd.com        code('#define $0 $1', define(isa), i + 1)
44911308Santhony.gutierrez@amd.com    code()
45011308Santhony.gutierrez@amd.com
45111308Santhony.gutierrez@amd.com    # create an enum for any run-time determination of the ISA, we
45211308Santhony.gutierrez@amd.com    # reuse the same name as the namespaces
45311308Santhony.gutierrez@amd.com    code('enum class GPUArch {')
45411308Santhony.gutierrez@amd.com    for i,isa in enumerate(isas):
45511308Santhony.gutierrez@amd.com        if i + 1 == len(isas):
45611308Santhony.gutierrez@amd.com            code('  $0 = $1', namespace(isa), define(isa))
45711308Santhony.gutierrez@amd.com        else:
45811308Santhony.gutierrez@amd.com            code('  $0 = $1,', namespace(isa), define(isa))
45911308Santhony.gutierrez@amd.com    code('};')
46011308Santhony.gutierrez@amd.com
46111308Santhony.gutierrez@amd.com    code('''
46211308Santhony.gutierrez@amd.com
46311308Santhony.gutierrez@amd.com#define THE_GPU_ISA ${{define(target_gpu_isa)}}
46411308Santhony.gutierrez@amd.com#define TheGpuISA ${{namespace(target_gpu_isa)}}
46511308Santhony.gutierrez@amd.com#define THE_GPU_ISA_STR "${{target_gpu_isa}}"
46611308Santhony.gutierrez@amd.com
46711308Santhony.gutierrez@amd.com#endif // __CONFIG_THE_GPU_ISA_HH__''')
46811308Santhony.gutierrez@amd.com
46911308Santhony.gutierrez@amd.com    code.write(str(target[0]))
47011308Santhony.gutierrez@amd.com
47111308Santhony.gutierrez@amd.comenv.Command('config/the_gpu_isa.hh', map(Value, all_gpu_isa_list),
47211308Santhony.gutierrez@amd.com            MakeAction(makeTheGPUISA, Transform("CFG ISA", 0)))
47311308Santhony.gutierrez@amd.com
4744382Sbinkertn@umich.edu########################################################################
4754382Sbinkertn@umich.edu#
4764762Snate@binkert.org# Prevent any SimObjects from being added after this point, they
4774762Snate@binkert.org# should all have been added in the SConscripts above
4784762Snate@binkert.org#
4796654Snate@binkert.orgSimObject.fixed = True
4806654Snate@binkert.org
4815517Snate@binkert.orgclass DictImporter(object):
4825517Snate@binkert.org    '''This importer takes a dictionary of arbitrary module names that
4835517Snate@binkert.org    map to arbitrary filenames.'''
4845517Snate@binkert.org    def __init__(self, modules):
4855517Snate@binkert.org        self.modules = modules
4865517Snate@binkert.org        self.installed = set()
4875517Snate@binkert.org
4885517Snate@binkert.org    def __del__(self):
4895517Snate@binkert.org        self.unload()
4905517Snate@binkert.org
4915517Snate@binkert.org    def unload(self):
4925517Snate@binkert.org        import sys
4935517Snate@binkert.org        for module in self.installed:
4945517Snate@binkert.org            del sys.modules[module]
4955517Snate@binkert.org        self.installed = set()
4965517Snate@binkert.org
4975517Snate@binkert.org    def find_module(self, fullname, path):
4986654Snate@binkert.org        if fullname == 'm5.defines':
4995517Snate@binkert.org            return self
5005517Snate@binkert.org
5015517Snate@binkert.org        if fullname == 'm5.objects':
5025517Snate@binkert.org            return self
5035517Snate@binkert.org
50411802Sandreas.sandberg@arm.com        if fullname.startswith('_m5'):
5055517Snate@binkert.org            return None
5065517Snate@binkert.org
5076143Snate@binkert.org        source = self.modules.get(fullname, None)
5086654Snate@binkert.org        if source is not None and fullname.startswith('m5.objects'):
5095517Snate@binkert.org            return self
5105517Snate@binkert.org
5115517Snate@binkert.org        return None
5125517Snate@binkert.org
5135517Snate@binkert.org    def load_module(self, fullname):
5145517Snate@binkert.org        mod = imp.new_module(fullname)
5155517Snate@binkert.org        sys.modules[fullname] = mod
5165517Snate@binkert.org        self.installed.add(fullname)
5175517Snate@binkert.org
5185517Snate@binkert.org        mod.__loader__ = self
5195517Snate@binkert.org        if fullname == 'm5.objects':
5205517Snate@binkert.org            mod.__path__ = fullname.split('.')
5215517Snate@binkert.org            return mod
5225517Snate@binkert.org
5236654Snate@binkert.org        if fullname == 'm5.defines':
5246654Snate@binkert.org            mod.__dict__['buildEnv'] = m5.util.SmartDict(build_env)
5255517Snate@binkert.org            return mod
5265517Snate@binkert.org
5276143Snate@binkert.org        source = self.modules[fullname]
5286143Snate@binkert.org        if source.modname == '__init__':
5296143Snate@binkert.org            mod.__path__ = source.modpath
5306727Ssteve.reinhardt@amd.com        mod.__file__ = source.abspath
5315517Snate@binkert.org
5326727Ssteve.reinhardt@amd.com        exec file(source.abspath, 'r') in mod.__dict__
5335517Snate@binkert.org
5345517Snate@binkert.org        return mod
5355517Snate@binkert.org
5366654Snate@binkert.orgimport m5.SimObject
5376654Snate@binkert.orgimport m5.params
5387673Snate@binkert.orgfrom m5.util import code_formatter
5396654Snate@binkert.org
5406654Snate@binkert.orgm5.SimObject.clear()
5416654Snate@binkert.orgm5.params.clear()
5426654Snate@binkert.org
5435517Snate@binkert.org# install the python importer so we can grab stuff from the source
5445517Snate@binkert.org# tree itself.  We can't have SimObjects added after this point or
5455517Snate@binkert.org# else we won't know about them for the rest of the stuff.
5466143Snate@binkert.orgimporter = DictImporter(PySource.modules)
5475517Snate@binkert.orgsys.meta_path[0:0] = [ importer ]
5484762Snate@binkert.org
5495517Snate@binkert.org# import all sim objects so we can populate the all_objects list
5505517Snate@binkert.org# make sure that we're working with a list, then let's sort it
5516143Snate@binkert.orgfor modname in SimObject.modnames:
5526143Snate@binkert.org    exec('from m5.objects import %s' % modname)
5535517Snate@binkert.org
5545517Snate@binkert.org# we need to unload all of the currently imported modules so that they
5555517Snate@binkert.org# will be re-imported the next time the sconscript is run
5565517Snate@binkert.orgimporter.unload()
5575517Snate@binkert.orgsys.meta_path.remove(importer)
5585517Snate@binkert.org
5595517Snate@binkert.orgsim_objects = m5.SimObject.allClasses
5605517Snate@binkert.orgall_enums = m5.params.allEnums
5615517Snate@binkert.org
5629338SAndreas.Sandberg@arm.comif m5.SimObject.noCxxHeader:
5639338SAndreas.Sandberg@arm.com    print >> sys.stderr, \
5649338SAndreas.Sandberg@arm.com        "warning: At least one SimObject lacks a header specification. " \
5659338SAndreas.Sandberg@arm.com        "This can cause unexpected results in the generated SWIG " \
5669338SAndreas.Sandberg@arm.com        "wrappers."
5679338SAndreas.Sandberg@arm.com
5688596Ssteve.reinhardt@amd.com# Find param types that need to be explicitly wrapped with swig.
5698596Ssteve.reinhardt@amd.com# These will be recognized because the ParamDesc will have a
5708596Ssteve.reinhardt@amd.com# swig_decl() method.  Most param types are based on types that don't
5718596Ssteve.reinhardt@amd.com# need this, either because they're based on native types (like Int)
5728596Ssteve.reinhardt@amd.com# or because they're SimObjects (which get swigged independently).
5738596Ssteve.reinhardt@amd.com# For now the only things handled here are VectorParam types.
5748596Ssteve.reinhardt@amd.comparams_to_swig = {}
5756143Snate@binkert.orgfor name,obj in sorted(sim_objects.iteritems()):
5765517Snate@binkert.org    for param in obj._params.local.values():
5776654Snate@binkert.org        # load the ptype attribute now because it depends on the
5786654Snate@binkert.org        # current version of SimObject.allClasses, but when scons
5796654Snate@binkert.org        # actually uses the value, all versions of
5806654Snate@binkert.org        # SimObject.allClasses will have been loaded
5816654Snate@binkert.org        param.ptype
5826654Snate@binkert.org
5835517Snate@binkert.org        if not hasattr(param, 'swig_decl'):
5845517Snate@binkert.org            continue
5855517Snate@binkert.org        pname = param.ptype_str
5868596Ssteve.reinhardt@amd.com        if pname not in params_to_swig:
5878596Ssteve.reinhardt@amd.com            params_to_swig[pname] = param
5884762Snate@binkert.org
5894762Snate@binkert.org########################################################################
5904762Snate@binkert.org#
5914762Snate@binkert.org# calculate extra dependencies
5924762Snate@binkert.org#
5934762Snate@binkert.orgmodule_depends = ["m5", "m5.SimObject", "m5.params"]
5947675Snate@binkert.orgdepends = [ PySource.modules[dep].snode for dep in module_depends ]
59510584Sandreas.hansson@arm.comdepends.sort(key = lambda x: x.name)
5964762Snate@binkert.org
5974762Snate@binkert.org########################################################################
5984762Snate@binkert.org#
5994762Snate@binkert.org# Commands for the basic automatically generated python files
6004382Sbinkertn@umich.edu#
6014382Sbinkertn@umich.edu
6025517Snate@binkert.org# Generate Python file containing a dict specifying the current
6036654Snate@binkert.org# buildEnv flags.
6045517Snate@binkert.orgdef makeDefinesPyFile(target, source, env):
6058126Sgblack@eecs.umich.edu    build_env = source[0].get_contents()
6066654Snate@binkert.org
6077673Snate@binkert.org    code = code_formatter()
6086654Snate@binkert.org    code("""
60911802Sandreas.sandberg@arm.comimport _m5.core
6106654Snate@binkert.orgimport m5.util
6116654Snate@binkert.org
6126654Snate@binkert.orgbuildEnv = m5.util.SmartDict($build_env)
6136654Snate@binkert.org
61411802Sandreas.sandberg@arm.comcompileDate = _m5.core.compileDate
6156669Snate@binkert.org_globals = globals()
61611802Sandreas.sandberg@arm.comfor key,val in _m5.core.__dict__.iteritems():
6176669Snate@binkert.org    if key.startswith('flag_'):
6186669Snate@binkert.org        flag = key[5:]
6196669Snate@binkert.org        _globals[flag] = val
6206669Snate@binkert.orgdel _globals
6216654Snate@binkert.org""")
6227673Snate@binkert.org    code.write(target[0].abspath)
6235517Snate@binkert.org
6248126Sgblack@eecs.umich.edudefines_info = Value(build_env)
6255798Snate@binkert.org# Generate a file with all of the compile options in it
6267756SAli.Saidi@ARM.comenv.Command('python/m5/defines.py', defines_info,
6277816Ssteve.reinhardt@amd.com            MakeAction(makeDefinesPyFile, Transform("DEFINES", 0)))
6285798Snate@binkert.orgPySource('m5', 'python/m5/defines.py')
6295798Snate@binkert.org
6305517Snate@binkert.org# Generate python file containing info about the M5 source code
6315517Snate@binkert.orgdef makeInfoPyFile(target, source, env):
6327673Snate@binkert.org    code = code_formatter()
6335517Snate@binkert.org    for src in source:
6345517Snate@binkert.org        data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
6357673Snate@binkert.org        code('$src = ${{repr(data)}}')
6367673Snate@binkert.org    code.write(str(target[0]))
6375517Snate@binkert.org
6385798Snate@binkert.org# Generate a file that wraps the basic top level files
6395798Snate@binkert.orgenv.Command('python/m5/info.py',
6408333Snate@binkert.org            [ '#/COPYING', '#/LICENSE', '#/README', ],
6417816Ssteve.reinhardt@amd.com            MakeAction(makeInfoPyFile, Transform("INFO")))
6425798Snate@binkert.orgPySource('m5', 'python/m5/info.py')
6435798Snate@binkert.org
6444762Snate@binkert.org########################################################################
6454762Snate@binkert.org#
6464762Snate@binkert.org# Create all of the SimObject param headers and enum headers
6474762Snate@binkert.org#
6484762Snate@binkert.org
6498596Ssteve.reinhardt@amd.comdef createSimObjectParamStruct(target, source, env):
6505517Snate@binkert.org    assert len(target) == 1 and len(source) == 1
6515517Snate@binkert.org
6525517Snate@binkert.org    name = str(source[0].get_contents())
6535517Snate@binkert.org    obj = sim_objects[name]
6545517Snate@binkert.org
6557673Snate@binkert.org    code = code_formatter()
6568596Ssteve.reinhardt@amd.com    obj.cxx_param_decl(code)
6577673Snate@binkert.org    code.write(target[0].abspath)
6585517Snate@binkert.org
65910458Sandreas.hansson@arm.comdef createSimObjectCxxConfig(is_header):
66010458Sandreas.hansson@arm.com    def body(target, source, env):
66110458Sandreas.hansson@arm.com        assert len(target) == 1 and len(source) == 1
66210458Sandreas.hansson@arm.com
66310458Sandreas.hansson@arm.com        name = str(source[0].get_contents())
66410458Sandreas.hansson@arm.com        obj = sim_objects[name]
66510458Sandreas.hansson@arm.com
66610458Sandreas.hansson@arm.com        code = code_formatter()
66710458Sandreas.hansson@arm.com        obj.cxx_config_param_file(code, is_header)
66810458Sandreas.hansson@arm.com        code.write(target[0].abspath)
66910458Sandreas.hansson@arm.com    return body
67010458Sandreas.hansson@arm.com
6718596Ssteve.reinhardt@amd.comdef createParamSwigWrapper(target, source, env):
6725517Snate@binkert.org    assert len(target) == 1 and len(source) == 1
6735517Snate@binkert.org
6745517Snate@binkert.org    name = str(source[0].get_contents())
6758596Ssteve.reinhardt@amd.com    param = params_to_swig[name]
6765517Snate@binkert.org
6777673Snate@binkert.org    code = code_formatter()
6787673Snate@binkert.org    param.swig_decl(code)
6797673Snate@binkert.org    code.write(target[0].abspath)
6805517Snate@binkert.org
6815517Snate@binkert.orgdef createEnumStrings(target, source, env):
6825517Snate@binkert.org    assert len(target) == 1 and len(source) == 1
6835517Snate@binkert.org
6845517Snate@binkert.org    name = str(source[0].get_contents())
6855517Snate@binkert.org    obj = all_enums[name]
6865517Snate@binkert.org
6877673Snate@binkert.org    code = code_formatter()
6887673Snate@binkert.org    obj.cxx_def(code)
6897673Snate@binkert.org    code.write(target[0].abspath)
6905517Snate@binkert.org
6918596Ssteve.reinhardt@amd.comdef createEnumDecls(target, source, env):
6925517Snate@binkert.org    assert len(target) == 1 and len(source) == 1
6935517Snate@binkert.org
6945517Snate@binkert.org    name = str(source[0].get_contents())
6955517Snate@binkert.org    obj = all_enums[name]
6965517Snate@binkert.org
6977673Snate@binkert.org    code = code_formatter()
6987673Snate@binkert.org    obj.cxx_decl(code)
6997673Snate@binkert.org    code.write(target[0].abspath)
7005517Snate@binkert.org
7018596Ssteve.reinhardt@amd.comdef createEnumSwigWrapper(target, source, env):
7027675Snate@binkert.org    assert len(target) == 1 and len(source) == 1
7037675Snate@binkert.org
7047675Snate@binkert.org    name = str(source[0].get_contents())
7057675Snate@binkert.org    obj = all_enums[name]
7067675Snate@binkert.org
7077675Snate@binkert.org    code = code_formatter()
7088596Ssteve.reinhardt@amd.com    obj.swig_decl(code)
7097675Snate@binkert.org    code.write(target[0].abspath)
7107675Snate@binkert.org
7118596Ssteve.reinhardt@amd.comdef createSimObjectSwigWrapper(target, source, env):
7128596Ssteve.reinhardt@amd.com    name = source[0].get_contents()
7138596Ssteve.reinhardt@amd.com    obj = sim_objects[name]
7148596Ssteve.reinhardt@amd.com
7158596Ssteve.reinhardt@amd.com    code = code_formatter()
7168596Ssteve.reinhardt@amd.com    obj.swig_decl(code)
7178596Ssteve.reinhardt@amd.com    code.write(target[0].abspath)
7188596Ssteve.reinhardt@amd.com
71910454SCurtis.Dunham@arm.com# dummy target for generated code
72010454SCurtis.Dunham@arm.com# we start out with all the Source files so they get copied to build/*/ also.
72110454SCurtis.Dunham@arm.comSWIG = env.Dummy('swig', [s.tnode for s in Source.get()])
72210454SCurtis.Dunham@arm.com
7238596Ssteve.reinhardt@amd.com# Generate all of the SimObject param C++ struct header files
7244762Snate@binkert.orgparams_hh_files = []
7256143Snate@binkert.orgfor name,simobj in sorted(sim_objects.iteritems()):
7266143Snate@binkert.org    py_source = PySource.modules[simobj.__module__]
7276143Snate@binkert.org    extra_deps = [ py_source.tnode ]
7284762Snate@binkert.org
7294762Snate@binkert.org    hh_file = File('params/%s.hh' % name)
7304762Snate@binkert.org    params_hh_files.append(hh_file)
7317756SAli.Saidi@ARM.com    env.Command(hh_file, Value(name),
7328596Ssteve.reinhardt@amd.com                MakeAction(createSimObjectParamStruct, Transform("SO PARAM")))
7334762Snate@binkert.org    env.Depends(hh_file, depends + extra_deps)
73410454SCurtis.Dunham@arm.com    env.Depends(SWIG, hh_file)
7354762Snate@binkert.org
73610458Sandreas.hansson@arm.com# C++ parameter description files
73710458Sandreas.hansson@arm.comif GetOption('with_cxx_config'):
73810458Sandreas.hansson@arm.com    for name,simobj in sorted(sim_objects.iteritems()):
73910458Sandreas.hansson@arm.com        py_source = PySource.modules[simobj.__module__]
74010458Sandreas.hansson@arm.com        extra_deps = [ py_source.tnode ]
74110458Sandreas.hansson@arm.com
74210458Sandreas.hansson@arm.com        cxx_config_hh_file = File('cxx_config/%s.hh' % name)
74310458Sandreas.hansson@arm.com        cxx_config_cc_file = File('cxx_config/%s.cc' % name)
74410458Sandreas.hansson@arm.com        env.Command(cxx_config_hh_file, Value(name),
74510458Sandreas.hansson@arm.com                    MakeAction(createSimObjectCxxConfig(True),
74610458Sandreas.hansson@arm.com                    Transform("CXXCPRHH")))
74710458Sandreas.hansson@arm.com        env.Command(cxx_config_cc_file, Value(name),
74810458Sandreas.hansson@arm.com                    MakeAction(createSimObjectCxxConfig(False),
74910458Sandreas.hansson@arm.com                    Transform("CXXCPRCC")))
75010458Sandreas.hansson@arm.com        env.Depends(cxx_config_hh_file, depends + extra_deps +
75110458Sandreas.hansson@arm.com                    [File('params/%s.hh' % name), File('sim/cxx_config.hh')])
75210458Sandreas.hansson@arm.com        env.Depends(cxx_config_cc_file, depends + extra_deps +
75310458Sandreas.hansson@arm.com                    [cxx_config_hh_file])
75410458Sandreas.hansson@arm.com        Source(cxx_config_cc_file)
75510458Sandreas.hansson@arm.com
75610458Sandreas.hansson@arm.com    cxx_config_init_cc_file = File('cxx_config/init.cc')
75710458Sandreas.hansson@arm.com
75810458Sandreas.hansson@arm.com    def createCxxConfigInitCC(target, source, env):
75910458Sandreas.hansson@arm.com        assert len(target) == 1 and len(source) == 1
76010458Sandreas.hansson@arm.com
76110458Sandreas.hansson@arm.com        code = code_formatter()
76210458Sandreas.hansson@arm.com
76310458Sandreas.hansson@arm.com        for name,simobj in sorted(sim_objects.iteritems()):
76410458Sandreas.hansson@arm.com            if not hasattr(simobj, 'abstract') or not simobj.abstract:
76510458Sandreas.hansson@arm.com                code('#include "cxx_config/${name}.hh"')
76610458Sandreas.hansson@arm.com        code()
76710458Sandreas.hansson@arm.com        code('void cxxConfigInit()')
76810458Sandreas.hansson@arm.com        code('{')
76910458Sandreas.hansson@arm.com        code.indent()
77010458Sandreas.hansson@arm.com        for name,simobj in sorted(sim_objects.iteritems()):
77110458Sandreas.hansson@arm.com            not_abstract = not hasattr(simobj, 'abstract') or \
77210458Sandreas.hansson@arm.com                not simobj.abstract
77310458Sandreas.hansson@arm.com            if not_abstract and 'type' in simobj.__dict__:
77410458Sandreas.hansson@arm.com                code('cxx_config_directory["${name}"] = '
77510458Sandreas.hansson@arm.com                     '${name}CxxConfigParams::makeDirectoryEntry();')
77610458Sandreas.hansson@arm.com        code.dedent()
77710458Sandreas.hansson@arm.com        code('}')
77810458Sandreas.hansson@arm.com        code.write(target[0].abspath)
77910458Sandreas.hansson@arm.com
78010458Sandreas.hansson@arm.com    py_source = PySource.modules[simobj.__module__]
78110458Sandreas.hansson@arm.com    extra_deps = [ py_source.tnode ]
78210458Sandreas.hansson@arm.com    env.Command(cxx_config_init_cc_file, Value(name),
78310458Sandreas.hansson@arm.com        MakeAction(createCxxConfigInitCC, Transform("CXXCINIT")))
78410458Sandreas.hansson@arm.com    cxx_param_hh_files = ["cxx_config/%s.hh" % simobj
78510584Sandreas.hansson@arm.com        for name,simobj in sorted(sim_objects.iteritems())
78610458Sandreas.hansson@arm.com        if not hasattr(simobj, 'abstract') or not simobj.abstract]
78710458Sandreas.hansson@arm.com    Depends(cxx_config_init_cc_file, cxx_param_hh_files +
78810458Sandreas.hansson@arm.com            [File('sim/cxx_config.hh')])
78910458Sandreas.hansson@arm.com    Source(cxx_config_init_cc_file)
79010458Sandreas.hansson@arm.com
7918596Ssteve.reinhardt@amd.com# Generate any needed param SWIG wrapper files
7925463Snate@binkert.orgparams_i_files = []
79310584Sandreas.hansson@arm.comfor name,param in sorted(params_to_swig.iteritems()):
79411802Sandreas.sandberg@arm.com    i_file = File('python/_m5/%s.i' % (param.swig_module_name()))
7955463Snate@binkert.org    params_i_files.append(i_file)
7967756SAli.Saidi@ARM.com    env.Command(i_file, Value(name),
7978596Ssteve.reinhardt@amd.com                MakeAction(createParamSwigWrapper, Transform("SW PARAM")))
7984762Snate@binkert.org    env.Depends(i_file, depends)
79910454SCurtis.Dunham@arm.com    env.Depends(SWIG, i_file)
80011802Sandreas.sandberg@arm.com    SwigSource('_m5', i_file)
8014762Snate@binkert.org
8024762Snate@binkert.org# Generate all enum header files
8036143Snate@binkert.orgfor name,enum in sorted(all_enums.iteritems()):
8046143Snate@binkert.org    py_source = PySource.modules[enum.__module__]
8056143Snate@binkert.org    extra_deps = [ py_source.tnode ]
8064762Snate@binkert.org
8074762Snate@binkert.org    cc_file = File('enums/%s.cc' % name)
8087756SAli.Saidi@ARM.com    env.Command(cc_file, Value(name),
8097816Ssteve.reinhardt@amd.com                MakeAction(createEnumStrings, Transform("ENUM STR")))
8104762Snate@binkert.org    env.Depends(cc_file, depends + extra_deps)
81110454SCurtis.Dunham@arm.com    env.Depends(SWIG, cc_file)
8124762Snate@binkert.org    Source(cc_file)
8134762Snate@binkert.org
8144762Snate@binkert.org    hh_file = File('enums/%s.hh' % name)
8157756SAli.Saidi@ARM.com    env.Command(hh_file, Value(name),
8168596Ssteve.reinhardt@amd.com                MakeAction(createEnumDecls, Transform("ENUMDECL")))
8174762Snate@binkert.org    env.Depends(hh_file, depends + extra_deps)
81810454SCurtis.Dunham@arm.com    env.Depends(SWIG, hh_file)
8194762Snate@binkert.org
82011802Sandreas.sandberg@arm.com    i_file = File('python/_m5/enum_%s.i' % name)
8217756SAli.Saidi@ARM.com    env.Command(i_file, Value(name),
8228596Ssteve.reinhardt@amd.com                MakeAction(createEnumSwigWrapper, Transform("ENUMSWIG")))
8237675Snate@binkert.org    env.Depends(i_file, depends + extra_deps)
82410454SCurtis.Dunham@arm.com    env.Depends(SWIG, i_file)
82511802Sandreas.sandberg@arm.com    SwigSource('_m5', i_file)
8265517Snate@binkert.org
8278596Ssteve.reinhardt@amd.com# Generate SimObject SWIG wrapper files
82810584Sandreas.hansson@arm.comfor name,simobj in sorted(sim_objects.iteritems()):
8299248SAndreas.Sandberg@arm.com    py_source = PySource.modules[simobj.__module__]
8309248SAndreas.Sandberg@arm.com    extra_deps = [ py_source.tnode ]
83111802Sandreas.sandberg@arm.com    i_file = File('python/_m5/param_%s.i' % name)
8328596Ssteve.reinhardt@amd.com    env.Command(i_file, Value(name),
8338596Ssteve.reinhardt@amd.com                MakeAction(createSimObjectSwigWrapper, Transform("SO SWIG")))
8349248SAndreas.Sandberg@arm.com    env.Depends(i_file, depends + extra_deps)
83511802Sandreas.sandberg@arm.com    SwigSource('_m5', i_file)
8364762Snate@binkert.org
8377674Snate@binkert.org# Generate the main swig init file
83811548Sandreas.hansson@arm.comdef makeEmbeddedSwigInit(package):
83911548Sandreas.hansson@arm.com    def body(target, source, env):
84011548Sandreas.hansson@arm.com        assert len(target) == 1 and len(source) == 1
8417674Snate@binkert.org
84211548Sandreas.hansson@arm.com        code = code_formatter()
84311548Sandreas.hansson@arm.com        module = source[0].get_contents()
84411548Sandreas.hansson@arm.com        # Provide the full context so that the swig-generated call to
84511548Sandreas.hansson@arm.com        # Py_InitModule ends up placing the embedded module in the
84611548Sandreas.hansson@arm.com        # right package.
84711548Sandreas.hansson@arm.com        context = str(package) + "._" + str(module)
84811548Sandreas.hansson@arm.com        code('''\
84911548Sandreas.hansson@arm.com        #include "sim/init.hh"
8507674Snate@binkert.org
85111548Sandreas.hansson@arm.com        extern "C" {
85211548Sandreas.hansson@arm.com            void init_${module}();
85311548Sandreas.hansson@arm.com        }
85411548Sandreas.hansson@arm.com
85511548Sandreas.hansson@arm.com        EmbeddedSwig embed_swig_${module}(init_${module}, "${context}");
85611548Sandreas.hansson@arm.com        ''')
85711548Sandreas.hansson@arm.com        code.write(str(target[0]))
85811548Sandreas.hansson@arm.com    return body
85911308Santhony.gutierrez@amd.com
8604762Snate@binkert.org# Build all swig modules
8616143Snate@binkert.orgfor swig in SwigSource.all:
8626143Snate@binkert.org    env.Command([swig.cc_source.tnode, swig.py_source.tnode], swig.tnode,
8637756SAli.Saidi@ARM.com                MakeAction('$SWIG $SWIGFLAGS -outdir ${TARGETS[1].dir} '
8647816Ssteve.reinhardt@amd.com                '-o ${TARGETS[0]} $SOURCES', Transform("SWIG")))
8658235Snate@binkert.org    cc_file = str(swig.tnode)
8668596Ssteve.reinhardt@amd.com    init_file = '%s/%s_init.cc' % (dirname(cc_file), basename(cc_file))
8677756SAli.Saidi@ARM.com    env.Command(init_file, Value(swig.module),
86811548Sandreas.hansson@arm.com                MakeAction(makeEmbeddedSwigInit(swig.package),
86911548Sandreas.hansson@arm.com                           Transform("EMBED SW")))
87010454SCurtis.Dunham@arm.com    env.Depends(SWIG, init_file)
8718235Snate@binkert.org    Source(init_file, **swig.guards)
8724382Sbinkertn@umich.edu
8739396Sandreas.hansson@arm.com# Build all protocol buffers if we have got protoc and protobuf available
8749396Sandreas.hansson@arm.comif env['HAVE_PROTOBUF']:
8759396Sandreas.hansson@arm.com    for proto in ProtoBuf.all:
8769396Sandreas.hansson@arm.com        # Use both the source and header as the target, and the .proto
8779396Sandreas.hansson@arm.com        # file as the source. When executing the protoc compiler, also
8789396Sandreas.hansson@arm.com        # specify the proto_path to avoid having the generated files
8799396Sandreas.hansson@arm.com        # include the path.
8809396Sandreas.hansson@arm.com        env.Command([proto.cc_file, proto.hh_file], proto.tnode,
8819396Sandreas.hansson@arm.com                    MakeAction('$PROTOC --cpp_out ${TARGET.dir} '
8829396Sandreas.hansson@arm.com                               '--proto_path ${SOURCE.dir} $SOURCE',
8839396Sandreas.hansson@arm.com                               Transform("PROTOC")))
8849396Sandreas.hansson@arm.com
88510454SCurtis.Dunham@arm.com        env.Depends(SWIG, [proto.cc_file, proto.hh_file])
8869396Sandreas.hansson@arm.com        # Add the C++ source file
8879396Sandreas.hansson@arm.com        Source(proto.cc_file, **proto.guards)
8889396Sandreas.hansson@arm.comelif ProtoBuf.all:
8899396Sandreas.hansson@arm.com    print 'Got protobuf to build, but lacks support!'
8909396Sandreas.hansson@arm.com    Exit(1)
8919396Sandreas.hansson@arm.com
8928232Snate@binkert.org#
8938232Snate@binkert.org# Handle debug flags
8948232Snate@binkert.org#
8958232Snate@binkert.orgdef makeDebugFlagCC(target, source, env):
8968232Snate@binkert.org    assert(len(target) == 1 and len(source) == 1)
8976229Snate@binkert.org
89810455SCurtis.Dunham@arm.com    code = code_formatter()
8996229Snate@binkert.org
90010455SCurtis.Dunham@arm.com    # delay definition of CompoundFlags until after all the definition
90110455SCurtis.Dunham@arm.com    # of all constituent SimpleFlags
90210455SCurtis.Dunham@arm.com    comp_code = code_formatter()
9035517Snate@binkert.org
9045517Snate@binkert.org    # file header
9057673Snate@binkert.org    code('''
9065517Snate@binkert.org/*
90710455SCurtis.Dunham@arm.com * DO NOT EDIT THIS FILE! Automatically generated by SCons.
9085517Snate@binkert.org */
9095517Snate@binkert.org
9108232Snate@binkert.org#include "base/debug.hh"
91110455SCurtis.Dunham@arm.com
91210455SCurtis.Dunham@arm.comnamespace Debug {
91310455SCurtis.Dunham@arm.com
9147673Snate@binkert.org''')
9157673Snate@binkert.org
91610455SCurtis.Dunham@arm.com    for name, flag in sorted(source[0].read().iteritems()):
91710455SCurtis.Dunham@arm.com        n, compound, desc = flag
91810455SCurtis.Dunham@arm.com        assert n == name
9195517Snate@binkert.org
92010455SCurtis.Dunham@arm.com        if not compound:
92110455SCurtis.Dunham@arm.com            code('SimpleFlag $name("$name", "$desc");')
92210455SCurtis.Dunham@arm.com        else:
92310455SCurtis.Dunham@arm.com            comp_code('CompoundFlag $name("$name", "$desc",')
92410455SCurtis.Dunham@arm.com            comp_code.indent()
92510455SCurtis.Dunham@arm.com            last = len(compound) - 1
92610455SCurtis.Dunham@arm.com            for i,flag in enumerate(compound):
92710455SCurtis.Dunham@arm.com                if i != last:
92810685Sandreas.hansson@arm.com                    comp_code('&$flag,')
92910455SCurtis.Dunham@arm.com                else:
93010685Sandreas.hansson@arm.com                    comp_code('&$flag);')
93110455SCurtis.Dunham@arm.com            comp_code.dedent()
9325517Snate@binkert.org
93310455SCurtis.Dunham@arm.com    code.append(comp_code)
9348232Snate@binkert.org    code()
9358232Snate@binkert.org    code('} // namespace Debug')
9365517Snate@binkert.org
9377673Snate@binkert.org    code.write(str(target[0]))
9385517Snate@binkert.org
9398232Snate@binkert.orgdef makeDebugFlagHH(target, source, env):
9408232Snate@binkert.org    assert(len(target) == 1 and len(source) == 1)
9415517Snate@binkert.org
9428232Snate@binkert.org    val = eval(source[0].get_contents())
9438232Snate@binkert.org    name, compound, desc = val
9448232Snate@binkert.org
9457673Snate@binkert.org    code = code_formatter()
9465517Snate@binkert.org
9475517Snate@binkert.org    # file header boilerplate
9487673Snate@binkert.org    code('''\
9495517Snate@binkert.org/*
95010455SCurtis.Dunham@arm.com * DO NOT EDIT THIS FILE! Automatically generated by SCons.
9515517Snate@binkert.org */
9525517Snate@binkert.org
9538232Snate@binkert.org#ifndef __DEBUG_${name}_HH__
9548232Snate@binkert.org#define __DEBUG_${name}_HH__
9555517Snate@binkert.org
9568232Snate@binkert.orgnamespace Debug {
9578232Snate@binkert.org''')
9585517Snate@binkert.org
9598232Snate@binkert.org    if compound:
9608232Snate@binkert.org        code('class CompoundFlag;')
9618232Snate@binkert.org    code('class SimpleFlag;')
9625517Snate@binkert.org
9638232Snate@binkert.org    if compound:
9648232Snate@binkert.org        code('extern CompoundFlag $name;')
9658232Snate@binkert.org        for flag in compound:
9668232Snate@binkert.org            code('extern SimpleFlag $flag;')
9678232Snate@binkert.org    else:
9688232Snate@binkert.org        code('extern SimpleFlag $name;')
9695517Snate@binkert.org
9708232Snate@binkert.org    code('''
9718232Snate@binkert.org}
9725517Snate@binkert.org
9738232Snate@binkert.org#endif // __DEBUG_${name}_HH__
9747673Snate@binkert.org''')
9755517Snate@binkert.org
9767673Snate@binkert.org    code.write(str(target[0]))
9775517Snate@binkert.org
9788232Snate@binkert.orgfor name,flag in sorted(debug_flags.iteritems()):
9798232Snate@binkert.org    n, compound, desc = flag
9808232Snate@binkert.org    assert n == name
9815192Ssaidi@eecs.umich.edu
98210454SCurtis.Dunham@arm.com    hh_file = 'debug/%s.hh' % name
98310454SCurtis.Dunham@arm.com    env.Command(hh_file, Value(flag),
9848232Snate@binkert.org                MakeAction(makeDebugFlagHH, Transform("TRACING", 0)))
98510455SCurtis.Dunham@arm.com    env.Depends(SWIG, hh_file)
98610455SCurtis.Dunham@arm.com
98710455SCurtis.Dunham@arm.comenv.Command('debug/flags.cc', Value(debug_flags),
98810455SCurtis.Dunham@arm.com            MakeAction(makeDebugFlagCC, Transform("TRACING", 0)))
98910455SCurtis.Dunham@arm.comenv.Depends(SWIG, 'debug/flags.cc')
99010455SCurtis.Dunham@arm.comSource('debug/flags.cc')
9915192Ssaidi@eecs.umich.edu
99211077SCurtis.Dunham@arm.com# version tags
99311330SCurtis.Dunham@arm.comtags = \
99411077SCurtis.Dunham@arm.comenv.Command('sim/tags.cc', None,
99511077SCurtis.Dunham@arm.com            MakeAction('util/cpt_upgrader.py --get-cc-file > $TARGET',
99611077SCurtis.Dunham@arm.com                       Transform("VER TAGS")))
99711330SCurtis.Dunham@arm.comenv.AlwaysBuild(tags)
99811077SCurtis.Dunham@arm.com
9997674Snate@binkert.org# Embed python files.  All .py files that have been indicated by a
10005522Snate@binkert.org# PySource() call in a SConscript need to be embedded into the M5
10015522Snate@binkert.org# library.  To do that, we compile the file to byte code, marshal the
10027674Snate@binkert.org# byte code, compress it, and then generate a c++ file that
10037674Snate@binkert.org# inserts the result into an array.
10047674Snate@binkert.orgdef embedPyFile(target, source, env):
10057674Snate@binkert.org    def c_str(string):
10067674Snate@binkert.org        if string is None:
10077674Snate@binkert.org            return "0"
10087674Snate@binkert.org        return '"%s"' % string
10097674Snate@binkert.org
10105522Snate@binkert.org    '''Action function to compile a .py into a code object, marshal
10115522Snate@binkert.org    it, compress it, and stick it into an asm file so the code appears
10125522Snate@binkert.org    as just bytes with a label in the data section'''
10135517Snate@binkert.org
10145522Snate@binkert.org    src = file(str(source[0]), 'r').read()
10155517Snate@binkert.org
10166143Snate@binkert.org    pysource = PySource.tnodes[source[0]]
10176727Ssteve.reinhardt@amd.com    compiled = compile(src, pysource.abspath, 'exec')
10185522Snate@binkert.org    marshalled = marshal.dumps(compiled)
10195522Snate@binkert.org    compressed = zlib.compress(marshalled)
10205522Snate@binkert.org    data = compressed
10217674Snate@binkert.org    sym = pysource.symname
10225517Snate@binkert.org
10237673Snate@binkert.org    code = code_formatter()
10247673Snate@binkert.org    code('''\
10257674Snate@binkert.org#include "sim/init.hh"
10267673Snate@binkert.org
10277674Snate@binkert.orgnamespace {
10287674Snate@binkert.org
10298946Sandreas.hansson@arm.comconst uint8_t data_${sym}[] = {
10307674Snate@binkert.org''')
10317674Snate@binkert.org    code.indent()
10327674Snate@binkert.org    step = 16
10335522Snate@binkert.org    for i in xrange(0, len(data), step):
10345522Snate@binkert.org        x = array.array('B', data[i:i+step])
10357674Snate@binkert.org        code(''.join('%d,' % d for d in x))
10367674Snate@binkert.org    code.dedent()
103711308Santhony.gutierrez@amd.com
10387674Snate@binkert.org    code('''};
10397673Snate@binkert.org
10407674Snate@binkert.orgEmbeddedPython embedded_${sym}(
10417674Snate@binkert.org    ${{c_str(pysource.arcname)}},
10427674Snate@binkert.org    ${{c_str(pysource.abspath)}},
10437674Snate@binkert.org    ${{c_str(pysource.modpath)}},
10447674Snate@binkert.org    data_${sym},
10457674Snate@binkert.org    ${{len(data)}},
10467674Snate@binkert.org    ${{len(marshalled)}});
10477674Snate@binkert.org
10487811Ssteve.reinhardt@amd.com} // anonymous namespace
10497674Snate@binkert.org''')
10507673Snate@binkert.org    code.write(str(target[0]))
10515522Snate@binkert.org
10526143Snate@binkert.orgfor source in PySource.all:
105310453SAndrew.Bardsley@arm.com    env.Command(source.cpp, source.tnode,
10547816Ssteve.reinhardt@amd.com                MakeAction(embedPyFile, Transform("EMBED PY")))
105510454SCurtis.Dunham@arm.com    env.Depends(SWIG, source.cpp)
105610453SAndrew.Bardsley@arm.com    Source(source.cpp, skip_no_python=True)
10574382Sbinkertn@umich.edu
10584382Sbinkertn@umich.edu########################################################################
10594382Sbinkertn@umich.edu#
10604382Sbinkertn@umich.edu# Define binaries.  Each different build type (debug, opt, etc.) gets
10614382Sbinkertn@umich.edu# a slightly different build environment.
10624382Sbinkertn@umich.edu#
10634382Sbinkertn@umich.edu
10644382Sbinkertn@umich.edu# List of constructed environments to pass back to SConstruct
106510196SCurtis.Dunham@arm.comdate_source = Source('base/date.cc', skip_lib=True)
10664382Sbinkertn@umich.edu
106710196SCurtis.Dunham@arm.com# Capture this directory for the closure makeEnv, otherwise when it is
106810196SCurtis.Dunham@arm.com# called, it won't know what directory it should use.
106910196SCurtis.Dunham@arm.comvariant_dir = Dir('.').path
107010196SCurtis.Dunham@arm.comdef variant(*path):
107110196SCurtis.Dunham@arm.com    return os.path.join(variant_dir, *path)
107210196SCurtis.Dunham@arm.comdef variantd(*path):
107310196SCurtis.Dunham@arm.com    return variant(*path)+'/'
1074955SN/A
10752655Sstever@eecs.umich.edu# Function to create a new build environment as clone of current
10762655Sstever@eecs.umich.edu# environment 'env' with modified object suffix and optional stripped
10772655Sstever@eecs.umich.edu# binary.  Additional keyword arguments are appended to corresponding
10782655Sstever@eecs.umich.edu# build environment vars.
107910196SCurtis.Dunham@arm.comdef makeEnv(env, label, objsfx, strip = False, **kwargs):
10805601Snate@binkert.org    # SCons doesn't know to append a library suffix when there is a '.' in the
10815601Snate@binkert.org    # name.  Use '_' instead.
108210196SCurtis.Dunham@arm.com    libname = variant('gem5_' + label)
108310196SCurtis.Dunham@arm.com    exename = variant('gem5.' + label)
108410196SCurtis.Dunham@arm.com    secondary_exename = variant('m5.' + label)
10855522Snate@binkert.org
10865863Snate@binkert.org    new_env = env.Clone(OBJSUFFIX=objsfx, SHOBJSUFFIX=objsfx + 's')
10875601Snate@binkert.org    new_env.Label = label
10885601Snate@binkert.org    new_env.Append(**kwargs)
10895601Snate@binkert.org
10905863Snate@binkert.org    swig_env = new_env.Clone()
10919556Sandreas.hansson@arm.com
10929556Sandreas.hansson@arm.com    # Both gcc and clang have issues with unused labels and values in
10939556Sandreas.hansson@arm.com    # the SWIG generated code
10949556Sandreas.hansson@arm.com    swig_env.Append(CCFLAGS=['-Wno-unused-label', '-Wno-unused-value'])
10959556Sandreas.hansson@arm.com
10965559Snate@binkert.org    if env['GCC']:
10979556Sandreas.hansson@arm.com        # Depending on the SWIG version, we also need to supress
10989618Ssteve.reinhardt@amd.com        # warnings about uninitialized variables and missing field
10999618Ssteve.reinhardt@amd.com        # initializers.
11009618Ssteve.reinhardt@amd.com        swig_env.Append(CCFLAGS=['-Wno-uninitialized',
110110238Sandreas.hansson@arm.com                                 '-Wno-missing-field-initializers',
110210878Sandreas.hansson@arm.com                                 '-Wno-unused-but-set-variable',
110311294Sandreas.hansson@arm.com                                 '-Wno-maybe-uninitialized',
110411294Sandreas.hansson@arm.com                                 '-Wno-type-limits'])
110510457Sandreas.hansson@arm.com
110611718Sjoseph.gross@amd.com
110711718Sjoseph.gross@amd.com        # The address sanitizer is available for gcc >= 4.8
110811718Sjoseph.gross@amd.com        if GetOption('with_asan'):
110911718Sjoseph.gross@amd.com            if GetOption('with_ubsan') and \
111011718Sjoseph.gross@amd.com                    compareVersions(env['GCC_VERSION'], '4.9') >= 0:
111111718Sjoseph.gross@amd.com                new_env.Append(CCFLAGS=['-fsanitize=address,undefined',
111211718Sjoseph.gross@amd.com                                        '-fno-omit-frame-pointer'])
111311718Sjoseph.gross@amd.com                new_env.Append(LINKFLAGS='-fsanitize=address,undefined')
111411718Sjoseph.gross@amd.com            else:
111511718Sjoseph.gross@amd.com                new_env.Append(CCFLAGS=['-fsanitize=address',
111611718Sjoseph.gross@amd.com                                        '-fno-omit-frame-pointer'])
111711718Sjoseph.gross@amd.com                new_env.Append(LINKFLAGS='-fsanitize=address')
111810457Sandreas.hansson@arm.com        # Only gcc >= 4.9 supports UBSan, so check both the version
111910457Sandreas.hansson@arm.com        # and the command-line option before adding the compiler and
112010457Sandreas.hansson@arm.com        # linker flags.
112111718Sjoseph.gross@amd.com        elif GetOption('with_ubsan') and \
112210457Sandreas.hansson@arm.com                compareVersions(env['GCC_VERSION'], '4.9') >= 0:
112310457Sandreas.hansson@arm.com            new_env.Append(CCFLAGS='-fsanitize=undefined')
112410457Sandreas.hansson@arm.com            new_env.Append(LINKFLAGS='-fsanitize=undefined')
112510457Sandreas.hansson@arm.com
112611342Sandreas.hansson@arm.com
11278737Skoansin.tan@gmail.com    if env['CLANG']:
112811294Sandreas.hansson@arm.com        swig_env.Append(CCFLAGS=['-Wno-sometimes-uninitialized',
112911294Sandreas.hansson@arm.com                                 '-Wno-deprecated-register',
113011294Sandreas.hansson@arm.com                                 '-Wno-tautological-compare'])
113110278SAndreas.Sandberg@ARM.com
113211342Sandreas.hansson@arm.com        # We require clang >= 3.1, so there is no need to check any
113311342Sandreas.hansson@arm.com        # versions here.
113410457Sandreas.hansson@arm.com        if GetOption('with_ubsan'):
113511718Sjoseph.gross@amd.com            if GetOption('with_asan'):
113611718Sjoseph.gross@amd.com                new_env.Append(CCFLAGS=['-fsanitize=address,undefined',
113711718Sjoseph.gross@amd.com                                        '-fno-omit-frame-pointer'])
113811718Sjoseph.gross@amd.com                new_env.Append(LINKFLAGS='-fsanitize=address,undefined')
113911718Sjoseph.gross@amd.com            else:
114011718Sjoseph.gross@amd.com                new_env.Append(CCFLAGS='-fsanitize=undefined')
114111718Sjoseph.gross@amd.com                new_env.Append(LINKFLAGS='-fsanitize=undefined')
114210457Sandreas.hansson@arm.com
114311718Sjoseph.gross@amd.com        elif GetOption('with_asan'):
114411500Sandreas.hansson@arm.com            new_env.Append(CCFLAGS=['-fsanitize=address',
114511500Sandreas.hansson@arm.com                                    '-fno-omit-frame-pointer'])
114611342Sandreas.hansson@arm.com            new_env.Append(LINKFLAGS='-fsanitize=address')
114711342Sandreas.hansson@arm.com
11488945Ssteve.reinhardt@amd.com    werror_env = new_env.Clone()
114910686SAndreas.Sandberg@ARM.com    # Treat warnings as errors but white list some warnings that we
115010686SAndreas.Sandberg@ARM.com    # want to allow (e.g., deprecation warnings).
115110686SAndreas.Sandberg@ARM.com    werror_env.Append(CCFLAGS=['-Werror',
115210686SAndreas.Sandberg@ARM.com                               '-Wno-error=deprecated-declarations',
115310686SAndreas.Sandberg@ARM.com                               '-Wno-error=deprecated',
115410686SAndreas.Sandberg@ARM.com                               ])
11558945Ssteve.reinhardt@amd.com
11566143Snate@binkert.org    def make_obj(source, static, extra_deps = None):
11576143Snate@binkert.org        '''This function adds the specified source to the correct
11586143Snate@binkert.org        build environment, and returns the corresponding SCons Object
11596143Snate@binkert.org        nodes'''
11606143Snate@binkert.org
11616143Snate@binkert.org        if source.swig:
11626143Snate@binkert.org            env = swig_env
11638945Ssteve.reinhardt@amd.com        elif source.Werror:
11648945Ssteve.reinhardt@amd.com            env = werror_env
11656143Snate@binkert.org        else:
11666143Snate@binkert.org            env = new_env
11676143Snate@binkert.org
11686143Snate@binkert.org        if static:
11696143Snate@binkert.org            obj = env.StaticObject(source.tnode)
11706143Snate@binkert.org        else:
11716143Snate@binkert.org            obj = env.SharedObject(source.tnode)
11726143Snate@binkert.org
11736143Snate@binkert.org        if extra_deps:
11746143Snate@binkert.org            env.Depends(obj, extra_deps)
11756143Snate@binkert.org
11766143Snate@binkert.org        return obj
11776143Snate@binkert.org
117810453SAndrew.Bardsley@arm.com    lib_guards = {'main': False, 'skip_lib': False}
117910453SAndrew.Bardsley@arm.com
118010453SAndrew.Bardsley@arm.com    # Without Python, leave out all SWIG and Python content from the
118110453SAndrew.Bardsley@arm.com    # library builds.  The option doesn't affect gem5 built as a program
118210453SAndrew.Bardsley@arm.com    if GetOption('without_python'):
118310453SAndrew.Bardsley@arm.com        lib_guards['skip_no_python'] = False
118410453SAndrew.Bardsley@arm.com
118511983Sgabeblack@google.com    static_objs = []
118611983Sgabeblack@google.com    shared_objs = []
118711983Sgabeblack@google.com    for s in guarded_source_iterator(Source.source_groups[None], **lib_guards):
118811983Sgabeblack@google.com        static_objs.append(make_obj(s, True))
118911983Sgabeblack@google.com        shared_objs.append(make_obj(s, False))
119011983Sgabeblack@google.com
119111983Sgabeblack@google.com    partial_objs = []
119211983Sgabeblack@google.com    for group, all_srcs in Source.source_groups.iteritems():
119311983Sgabeblack@google.com        # If these are the ungrouped source files, skip them.
119411983Sgabeblack@google.com        if not group:
119511983Sgabeblack@google.com            continue
119611983Sgabeblack@google.com
119711983Sgabeblack@google.com        # Get a list of the source files compatible with the current guards.
119811983Sgabeblack@google.com        srcs = [ s for s in guarded_source_iterator(all_srcs, **lib_guards) ]
119911983Sgabeblack@google.com        # If there aren't any left, skip this group.
120011983Sgabeblack@google.com        if not srcs:
120111983Sgabeblack@google.com            continue
120211983Sgabeblack@google.com
120311983Sgabeblack@google.com        # Set up the static partially linked objects.
120411983Sgabeblack@google.com        source_objs = [ make_obj(s, True) for s in srcs ]
120511983Sgabeblack@google.com        file_name = new_env.subst("${OBJPREFIX}lib${OBJSUFFIX}.partial")
120611983Sgabeblack@google.com        target = File(joinpath(group, file_name))
120711983Sgabeblack@google.com        partial = env.PartialStatic(target=target, source=source_objs)
120811983Sgabeblack@google.com        static_objs.append(partial)
120911983Sgabeblack@google.com
121011983Sgabeblack@google.com        # Set up the shared partially linked objects.
121111983Sgabeblack@google.com        source_objs = [ make_obj(s, False) for s in srcs ]
121211983Sgabeblack@google.com        file_name = new_env.subst("${SHOBJPREFIX}lib${SHOBJSUFFIX}.partial")
121311983Sgabeblack@google.com        target = File(joinpath(group, file_name))
121411983Sgabeblack@google.com        partial = env.PartialShared(target=target, source=source_objs)
121511983Sgabeblack@google.com        shared_objs.append(partial)
12166143Snate@binkert.org
12176143Snate@binkert.org    static_date = make_obj(date_source, static=True, extra_deps=static_objs)
12186143Snate@binkert.org    static_objs.append(static_date)
121910453SAndrew.Bardsley@arm.com
12206143Snate@binkert.org    shared_date = make_obj(date_source, static=False, extra_deps=shared_objs)
12216240Snate@binkert.org    shared_objs.append(shared_date)
12225554Snate@binkert.org
12235522Snate@binkert.org    # First make a library of everything but main() so other programs can
12245522Snate@binkert.org    # link against m5.
12255797Snate@binkert.org    static_lib = new_env.StaticLibrary(libname, static_objs)
12265797Snate@binkert.org    shared_lib = new_env.SharedLibrary(libname, shared_objs)
12275522Snate@binkert.org
12285601Snate@binkert.org    # Now link a stub with main() and the static library.
12298233Snate@binkert.org    main_objs = [ make_obj(s, True) for s in Source.get(main=True) ]
12308233Snate@binkert.org
12318235Snate@binkert.org    for test in UnitTest.all:
12328235Snate@binkert.org        flags = { test.target : True }
12338235Snate@binkert.org        test_sources = Source.get(**flags)
12348235Snate@binkert.org        test_objs = [ make_obj(s, static=True) for s in test_sources ]
12359003SAli.Saidi@ARM.com        if test.main:
12369003SAli.Saidi@ARM.com            test_objs += main_objs
123710196SCurtis.Dunham@arm.com        path = variant('unittest/%s.%s' % (test.target, label))
123810196SCurtis.Dunham@arm.com        new_env.Program(path, test_objs + static_objs)
12398235Snate@binkert.org
12406143Snate@binkert.org    progname = exename
12412655Sstever@eecs.umich.edu    if strip:
12426143Snate@binkert.org        progname += '.unstripped'
12436143Snate@binkert.org
124411985Sgabeblack@google.com    targets = new_env.Program(progname, main_objs + static_objs)
12456143Snate@binkert.org
12466143Snate@binkert.org    if strip:
12474007Ssaidi@eecs.umich.edu        if sys.platform == 'sunos5':
12484596Sbinkertn@umich.edu            cmd = 'cp $SOURCE $TARGET; strip $TARGET'
12494007Ssaidi@eecs.umich.edu        else:
12504596Sbinkertn@umich.edu            cmd = 'strip $SOURCE -o $TARGET'
12517756SAli.Saidi@ARM.com        targets = new_env.Command(exename, progname,
12527816Ssteve.reinhardt@amd.com                    MakeAction(cmd, Transform("STRIP")))
12538334Snate@binkert.org
12548334Snate@binkert.org    new_env.Command(secondary_exename, exename,
12558334Snate@binkert.org            MakeAction('ln $SOURCE $TARGET', Transform("HARDLINK")))
12568334Snate@binkert.org
12575601Snate@binkert.org    new_env.M5Binary = targets[0]
125810196SCurtis.Dunham@arm.com    return new_env
12592655Sstever@eecs.umich.edu
12609225Sandreas.hansson@arm.com# Start out with the compiler flags common to all compilers,
12619225Sandreas.hansson@arm.com# i.e. they all use -g for opt and -g -pg for prof
12629226Sandreas.hansson@arm.comccflags = {'debug' : [], 'opt' : ['-g'], 'fast' : [], 'prof' : ['-g', '-pg'],
12639226Sandreas.hansson@arm.com           'perf' : ['-g']}
12649225Sandreas.hansson@arm.com
12659226Sandreas.hansson@arm.com# Start out with the linker flags common to all linkers, i.e. -pg for
12669226Sandreas.hansson@arm.com# prof, and -lprofiler for perf. The -lprofile flag is surrounded by
12679226Sandreas.hansson@arm.com# no-as-needed and as-needed as the binutils linker is too clever and
12689226Sandreas.hansson@arm.com# simply doesn't link to the library otherwise.
12699226Sandreas.hansson@arm.comldflags = {'debug' : [], 'opt' : [], 'fast' : [], 'prof' : ['-pg'],
12709226Sandreas.hansson@arm.com           'perf' : ['-Wl,--no-as-needed', '-lprofiler', '-Wl,--as-needed']}
12719225Sandreas.hansson@arm.com
12729227Sandreas.hansson@arm.com# For Link Time Optimization, the optimisation flags used to compile
12739227Sandreas.hansson@arm.com# individual files are decoupled from those used at link time
12749227Sandreas.hansson@arm.com# (i.e. you can compile with -O3 and perform LTO with -O0), so we need
12759227Sandreas.hansson@arm.com# to also update the linker flags based on the target.
12768946Sandreas.hansson@arm.comif env['GCC']:
12773918Ssaidi@eecs.umich.edu    if sys.platform == 'sunos5':
12789225Sandreas.hansson@arm.com        ccflags['debug'] += ['-gstabs+']
12793918Ssaidi@eecs.umich.edu    else:
12809225Sandreas.hansson@arm.com        ccflags['debug'] += ['-ggdb3']
12819225Sandreas.hansson@arm.com    ldflags['debug'] += ['-O0']
12829227Sandreas.hansson@arm.com    # opt, fast, prof and perf all share the same cc flags, also add
12839227Sandreas.hansson@arm.com    # the optimization to the ldflags as LTO defers the optimization
12849227Sandreas.hansson@arm.com    # to link time
12859226Sandreas.hansson@arm.com    for target in ['opt', 'fast', 'prof', 'perf']:
12869225Sandreas.hansson@arm.com        ccflags[target] += ['-O3']
12879227Sandreas.hansson@arm.com        ldflags[target] += ['-O3']
12889227Sandreas.hansson@arm.com
12899227Sandreas.hansson@arm.com    ccflags['fast'] += env['LTO_CCFLAGS']
12909227Sandreas.hansson@arm.com    ldflags['fast'] += env['LTO_LDFLAGS']
12918946Sandreas.hansson@arm.comelif env['CLANG']:
12929225Sandreas.hansson@arm.com    ccflags['debug'] += ['-g', '-O0']
12939226Sandreas.hansson@arm.com    # opt, fast, prof and perf all share the same cc flags
12949226Sandreas.hansson@arm.com    for target in ['opt', 'fast', 'prof', 'perf']:
12959226Sandreas.hansson@arm.com        ccflags[target] += ['-O3']
12963515Ssaidi@eecs.umich.eduelse:
12973918Ssaidi@eecs.umich.edu    print 'Unknown compiler, please fix compiler options'
12984762Snate@binkert.org    Exit(1)
12993515Ssaidi@eecs.umich.edu
13008881Smarc.orr@gmail.com
13018881Smarc.orr@gmail.com# To speed things up, we only instantiate the build environments we
13028881Smarc.orr@gmail.com# need.  We try to identify the needed environment for each target; if
13038881Smarc.orr@gmail.com# we can't, we fall back on instantiating all the environments just to
13048881Smarc.orr@gmail.com# be safe.
13059226Sandreas.hansson@arm.comtarget_types = ['debug', 'opt', 'fast', 'prof', 'perf']
13069226Sandreas.hansson@arm.comobj2target = {'do': 'debug', 'o': 'opt', 'fo': 'fast', 'po': 'prof',
13079226Sandreas.hansson@arm.com              'gpo' : 'perf'}
13088881Smarc.orr@gmail.com
13098881Smarc.orr@gmail.comdef identifyTarget(t):
13108881Smarc.orr@gmail.com    ext = t.split('.')[-1]
13118881Smarc.orr@gmail.com    if ext in target_types:
13128881Smarc.orr@gmail.com        return ext
13138881Smarc.orr@gmail.com    if obj2target.has_key(ext):
13148881Smarc.orr@gmail.com        return obj2target[ext]
13158881Smarc.orr@gmail.com    match = re.search(r'/tests/([^/]+)/', t)
13168881Smarc.orr@gmail.com    if match and match.group(1) in target_types:
13178881Smarc.orr@gmail.com        return match.group(1)
13188881Smarc.orr@gmail.com    return 'all'
13198881Smarc.orr@gmail.com
13208881Smarc.orr@gmail.comneeded_envs = [identifyTarget(target) for target in BUILD_TARGETS]
13218881Smarc.orr@gmail.comif 'all' in needed_envs:
13228881Smarc.orr@gmail.com    needed_envs += target_types
13238881Smarc.orr@gmail.com
132410196SCurtis.Dunham@arm.comdef makeEnvirons(target, source, env):
132510196SCurtis.Dunham@arm.com    # cause any later Source() calls to be fatal, as a diagnostic.
132610196SCurtis.Dunham@arm.com    Source.done()
1327955SN/A
132810196SCurtis.Dunham@arm.com    envList = []
1329955SN/A
133010196SCurtis.Dunham@arm.com    # Debug binary
133110196SCurtis.Dunham@arm.com    if 'debug' in needed_envs:
133210196SCurtis.Dunham@arm.com        envList.append(
133310196SCurtis.Dunham@arm.com            makeEnv(env, 'debug', '.do',
133410196SCurtis.Dunham@arm.com                    CCFLAGS = Split(ccflags['debug']),
133510196SCurtis.Dunham@arm.com                    CPPDEFINES = ['DEBUG', 'TRACING_ON=1'],
133610196SCurtis.Dunham@arm.com                    LINKFLAGS = Split(ldflags['debug'])))
1337955SN/A
133810196SCurtis.Dunham@arm.com    # Optimized binary
133910196SCurtis.Dunham@arm.com    if 'opt' in needed_envs:
134010196SCurtis.Dunham@arm.com        envList.append(
134110196SCurtis.Dunham@arm.com            makeEnv(env, 'opt', '.o',
134210196SCurtis.Dunham@arm.com                    CCFLAGS = Split(ccflags['opt']),
134310196SCurtis.Dunham@arm.com                    CPPDEFINES = ['TRACING_ON=1'],
134410196SCurtis.Dunham@arm.com                    LINKFLAGS = Split(ldflags['opt'])))
13451869SN/A
134610196SCurtis.Dunham@arm.com    # "Fast" binary
134710196SCurtis.Dunham@arm.com    if 'fast' in needed_envs:
134810196SCurtis.Dunham@arm.com        envList.append(
134910196SCurtis.Dunham@arm.com            makeEnv(env, 'fast', '.fo', strip = True,
135010196SCurtis.Dunham@arm.com                    CCFLAGS = Split(ccflags['fast']),
135110196SCurtis.Dunham@arm.com                    CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
135210196SCurtis.Dunham@arm.com                    LINKFLAGS = Split(ldflags['fast'])))
13539226Sandreas.hansson@arm.com
135410196SCurtis.Dunham@arm.com    # Profiled binary using gprof
135510196SCurtis.Dunham@arm.com    if 'prof' in needed_envs:
135610196SCurtis.Dunham@arm.com        envList.append(
135710196SCurtis.Dunham@arm.com            makeEnv(env, 'prof', '.po',
135810196SCurtis.Dunham@arm.com                    CCFLAGS = Split(ccflags['prof']),
135910196SCurtis.Dunham@arm.com                    CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
136010196SCurtis.Dunham@arm.com                    LINKFLAGS = Split(ldflags['prof'])))
136110196SCurtis.Dunham@arm.com
136210196SCurtis.Dunham@arm.com    # Profiled binary using google-pprof
136310196SCurtis.Dunham@arm.com    if 'perf' in needed_envs:
136410196SCurtis.Dunham@arm.com        envList.append(
136510196SCurtis.Dunham@arm.com            makeEnv(env, 'perf', '.gpo',
136610196SCurtis.Dunham@arm.com                    CCFLAGS = Split(ccflags['perf']),
136710196SCurtis.Dunham@arm.com                    CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
136810196SCurtis.Dunham@arm.com                    LINKFLAGS = Split(ldflags['perf'])))
136910196SCurtis.Dunham@arm.com
137010196SCurtis.Dunham@arm.com    # Set up the regression tests for each build.
137110196SCurtis.Dunham@arm.com    for e in envList:
137211370Ssteve.reinhardt@amd.com        SConscript(os.path.join(env.root.abspath, 'tests', 'SConscript'),
137310196SCurtis.Dunham@arm.com                   variant_dir = variantd('tests', e.Label),
137410196SCurtis.Dunham@arm.com                   exports = { 'env' : e }, duplicate = False)
137510196SCurtis.Dunham@arm.com
137610196SCurtis.Dunham@arm.com# The MakeEnvirons Builder defers the full dependency collection until
137710196SCurtis.Dunham@arm.com# after processing the ISA definition (due to dynamically generated
137810196SCurtis.Dunham@arm.com# source files).  Add this dependency to all targets so they will wait
137910196SCurtis.Dunham@arm.com# until the environments are completely set up.  Otherwise, a second
138010196SCurtis.Dunham@arm.com# process (e.g. -j2 or higher) will try to compile the requested target,
138110196SCurtis.Dunham@arm.com# not know how, and fail.
138210196SCurtis.Dunham@arm.comenv.Append(BUILDERS = {'MakeEnvirons' :
138310196SCurtis.Dunham@arm.com                        Builder(action=MakeAction(makeEnvirons,
138410196SCurtis.Dunham@arm.com                                                  Transform("ENVIRONS", 1)))})
138510196SCurtis.Dunham@arm.com
138610196SCurtis.Dunham@arm.comisa_target = env['PHONY_BASE'] + '-deps'
138710196SCurtis.Dunham@arm.comenvirons   = env['PHONY_BASE'] + '-environs'
138810196SCurtis.Dunham@arm.comenv.Depends('#all-deps',     isa_target)
138910196SCurtis.Dunham@arm.comenv.Depends('#all-environs', environs)
139010196SCurtis.Dunham@arm.comenv.ScanISA(isa_target, File('arch/%s/generated/inc.d' % env['TARGET_ISA']))
139110196SCurtis.Dunham@arm.comenvSetup = env.MakeEnvirons(environs, isa_target)
139210196SCurtis.Dunham@arm.com
139310196SCurtis.Dunham@arm.com# make sure no -deps targets occur before all ISAs are complete
139410196SCurtis.Dunham@arm.comenv.Depends(isa_target, '#all-isas')
139510196SCurtis.Dunham@arm.com# likewise for -environs targets and all the -deps targets
139610196SCurtis.Dunham@arm.comenv.Depends(environs, '#all-deps')
1397