SConscript revision 11370
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
314762Snate@binkert.orgimport array
32955SN/Aimport bisect
33955SN/Aimport imp
344202Sbinkertn@umich.eduimport marshal
355342Sstever@gmail.comimport os
36955SN/Aimport re
374381Sbinkertn@umich.eduimport sys
384381Sbinkertn@umich.eduimport zlib
39955SN/A
40955SN/Afrom os.path import basename, dirname, exists, isdir, isfile, join as joinpath
41955SN/A
424202Sbinkertn@umich.eduimport SCons
43955SN/A
444382Sbinkertn@umich.edu# This file defines how to build a particular configuration of gem5
454382Sbinkertn@umich.edu# based on variable settings in the 'env' build environment.
464382Sbinkertn@umich.edu
474762Snate@binkert.orgImport('*')
484762Snate@binkert.org
494762Snate@binkert.org# Children need to see the environment
504762Snate@binkert.orgExport('env')
514762Snate@binkert.org
524762Snate@binkert.orgbuild_env = [(opt, env[opt]) for opt in export_vars]
534762Snate@binkert.org
544762Snate@binkert.orgfrom m5.util import code_formatter, compareVersions
554762Snate@binkert.org
564762Snate@binkert.org########################################################################
574762Snate@binkert.org# Code for adding source files of various types
584762Snate@binkert.org#
594762Snate@binkert.org# When specifying a source file of some type, a set of guards can be
604762Snate@binkert.org# specified for that file.  When get() is used to find the files, if
614762Snate@binkert.org# get specifies a set of filters, only files that match those filters
624762Snate@binkert.org# will be accepted (unspecified filters on files are assumed to be
634762Snate@binkert.org# false).  Current filters are:
644762Snate@binkert.org#     main -- specifies the gem5 main() function
654762Snate@binkert.org#     skip_lib -- do not put this file into the gem5 library
664762Snate@binkert.org#     skip_no_python -- do not put this file into a no_python library
674762Snate@binkert.org#       as it embeds compiled Python
684762Snate@binkert.org#     <unittest> -- unit tests use filters based on the unit test name
694762Snate@binkert.org#
704762Snate@binkert.org# A parent can now be specified for a source file and default filter
714762Snate@binkert.org# values will be retrieved recursively from parents (children override
724762Snate@binkert.org# parents).
734762Snate@binkert.org#
744762Snate@binkert.orgclass SourceMeta(type):
754762Snate@binkert.org    '''Meta class for source files that keeps track of all files of a
764762Snate@binkert.org    particular type and has a get function for finding all functions
774762Snate@binkert.org    of a certain type that match a set of guards'''
784762Snate@binkert.org    def __init__(cls, name, bases, dict):
794762Snate@binkert.org        super(SourceMeta, cls).__init__(name, bases, dict)
804382Sbinkertn@umich.edu        cls.all = []
814762Snate@binkert.org
824382Sbinkertn@umich.edu    def get(cls, **guards):
834762Snate@binkert.org        '''Find all files that match the specified guards.  If a source
844381Sbinkertn@umich.edu        file does not specify a flag, the default is False'''
854762Snate@binkert.org        for src in cls.all:
864762Snate@binkert.org            for flag,value in guards.iteritems():
874762Snate@binkert.org                # if the flag is found and has a different value, skip
884762Snate@binkert.org                # this file
894762Snate@binkert.org                if src.all_guards.get(flag, False) != value:
904762Snate@binkert.org                    break
914762Snate@binkert.org            else:
924762Snate@binkert.org                yield src
934762Snate@binkert.org
944762Snate@binkert.orgclass SourceFile(object):
954762Snate@binkert.org    '''Base object that encapsulates the notion of a source file.
964762Snate@binkert.org    This includes, the source node, target node, various manipulations
974762Snate@binkert.org    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
994762Snate@binkert.org    also be specified to get default guards from'''
1004762Snate@binkert.org    __metaclass__ = SourceMeta
1014762Snate@binkert.org    def __init__(self, source, parent=None, **guards):
1024762Snate@binkert.org        self.guards = guards
1034762Snate@binkert.org        self.parent = parent
1044762Snate@binkert.org
1054762Snate@binkert.org        tnode = source
1064762Snate@binkert.org        if not isinstance(source, SCons.Node.FS.File):
1074762Snate@binkert.org            tnode = File(source)
1084762Snate@binkert.org
1094762Snate@binkert.org        self.tnode = tnode
1104762Snate@binkert.org        self.snode = tnode.srcnode()
1114762Snate@binkert.org
1124762Snate@binkert.org        for base in type(self).__mro__:
1134762Snate@binkert.org            if issubclass(base, SourceFile):
1144762Snate@binkert.org                base.all.append(self)
1154762Snate@binkert.org
1164762Snate@binkert.org    @property
1174762Snate@binkert.org    def filename(self):
1184762Snate@binkert.org        return str(self.tnode)
1194762Snate@binkert.org
1204762Snate@binkert.org    @property
1214762Snate@binkert.org    def dirname(self):
1224762Snate@binkert.org        return dirname(self.filename)
1234762Snate@binkert.org
1244762Snate@binkert.org    @property
125955SN/A    def basename(self):
1264382Sbinkertn@umich.edu        return basename(self.filename)
1274202Sbinkertn@umich.edu
1284382Sbinkertn@umich.edu    @property
1294382Sbinkertn@umich.edu    def extname(self):
1304382Sbinkertn@umich.edu        index = self.basename.rfind('.')
1314382Sbinkertn@umich.edu        if index <= 0:
1324382Sbinkertn@umich.edu            # dot files aren't extensions
1334382Sbinkertn@umich.edu            return self.basename, None
1345192Ssaidi@eecs.umich.edu
1355192Ssaidi@eecs.umich.edu        return self.basename[:index], self.basename[index+1:]
1365192Ssaidi@eecs.umich.edu
1375192Ssaidi@eecs.umich.edu    @property
1385192Ssaidi@eecs.umich.edu    def all_guards(self):
1395192Ssaidi@eecs.umich.edu        '''find all guards for this object getting default values
1405192Ssaidi@eecs.umich.edu        recursively from its parents'''
1415192Ssaidi@eecs.umich.edu        guards = {}
1425192Ssaidi@eecs.umich.edu        if self.parent:
1435192Ssaidi@eecs.umich.edu            guards.update(self.parent.guards)
1445192Ssaidi@eecs.umich.edu        guards.update(self.guards)
1455192Ssaidi@eecs.umich.edu        return guards
1465192Ssaidi@eecs.umich.edu
1475192Ssaidi@eecs.umich.edu    def __lt__(self, other): return self.filename < other.filename
1485192Ssaidi@eecs.umich.edu    def __le__(self, other): return self.filename <= other.filename
1495192Ssaidi@eecs.umich.edu    def __gt__(self, other): return self.filename > other.filename
1505192Ssaidi@eecs.umich.edu    def __ge__(self, other): return self.filename >= other.filename
1515192Ssaidi@eecs.umich.edu    def __eq__(self, other): return self.filename == other.filename
1525192Ssaidi@eecs.umich.edu    def __ne__(self, other): return self.filename != other.filename
1535192Ssaidi@eecs.umich.edu
1545192Ssaidi@eecs.umich.edu    @staticmethod
1555192Ssaidi@eecs.umich.edu    def done():
1565192Ssaidi@eecs.umich.edu        def disabled(cls, name, *ignored):
1575192Ssaidi@eecs.umich.edu            raise RuntimeError("Additional SourceFile '%s'" % name,\
1585192Ssaidi@eecs.umich.edu                  "declared, but targets deps are already fixed.")
1595192Ssaidi@eecs.umich.edu        SourceFile.__init__ = disabled
1605192Ssaidi@eecs.umich.edu
1615192Ssaidi@eecs.umich.edu
1625192Ssaidi@eecs.umich.educlass Source(SourceFile):
1635192Ssaidi@eecs.umich.edu    '''Add a c/c++ source file to the build'''
1645192Ssaidi@eecs.umich.edu    def __init__(self, source, Werror=True, swig=False, **guards):
1655192Ssaidi@eecs.umich.edu        '''specify the source file, and any guards'''
1664382Sbinkertn@umich.edu        super(Source, self).__init__(source, **guards)
1674382Sbinkertn@umich.edu
1684382Sbinkertn@umich.edu        self.Werror = Werror
1692667Sstever@eecs.umich.edu        self.swig = swig
1702667Sstever@eecs.umich.edu
1712667Sstever@eecs.umich.educlass PySource(SourceFile):
1722667Sstever@eecs.umich.edu    '''Add a python source file to the named package'''
1732667Sstever@eecs.umich.edu    invalid_sym_char = re.compile('[^A-z0-9_]')
1742667Sstever@eecs.umich.edu    modules = {}
1752037SN/A    tnodes = {}
1762037SN/A    symnames = {}
1772037SN/A
1784382Sbinkertn@umich.edu    def __init__(self, package, source, **guards):
1794762Snate@binkert.org        '''specify the python package, the source file, and any guards'''
1805341Sstever@gmail.com        super(PySource, self).__init__(source, **guards)
1814382Sbinkertn@umich.edu
1825341Sstever@gmail.com        modname,ext = self.extname
1835341Sstever@gmail.com        assert ext == 'py'
1845341Sstever@gmail.com
1855341Sstever@gmail.com        if package:
1864202Sbinkertn@umich.edu            path = package.split('.')
1875341Sstever@gmail.com        else:
1885341Sstever@gmail.com            path = []
1895341Sstever@gmail.com
1905341Sstever@gmail.com        modpath = path[:]
1915341Sstever@gmail.com        if modname != '__init__':
1924762Snate@binkert.org            modpath += [ modname ]
1935341Sstever@gmail.com        modpath = '.'.join(modpath)
1945341Sstever@gmail.com
1955341Sstever@gmail.com        arcpath = path + [ self.basename ]
1964773Snate@binkert.org        abspath = self.snode.abspath
1971858SN/A        if not exists(abspath):
1981858SN/A            abspath = self.tnode.abspath
1991085SN/A
2004382Sbinkertn@umich.edu        self.package = package
2014382Sbinkertn@umich.edu        self.modname = modname
2024762Snate@binkert.org        self.modpath = modpath
2034762Snate@binkert.org        self.arcname = joinpath(*arcpath)
2044762Snate@binkert.org        self.abspath = abspath
2054762Snate@binkert.org        self.compiled = File(self.filename + 'c')
2064762Snate@binkert.org        self.cpp = File(self.filename + '.cc')
2074762Snate@binkert.org        self.symname = PySource.invalid_sym_char.sub('_', modpath)
2084762Snate@binkert.org
2094762Snate@binkert.org        PySource.modules[modpath] = self
2104762Snate@binkert.org        PySource.tnodes[self.tnode] = self
2114762Snate@binkert.org        PySource.symnames[self.symname] = self
2124762Snate@binkert.org
2134762Snate@binkert.orgclass SimObject(PySource):
2144762Snate@binkert.org    '''Add a SimObject python file as a python source object and add
2154762Snate@binkert.org    it to a list of sim object modules'''
2164762Snate@binkert.org
2174762Snate@binkert.org    fixed = False
2184762Snate@binkert.org    modnames = []
2194762Snate@binkert.org
2204762Snate@binkert.org    def __init__(self, source, **guards):
2214762Snate@binkert.org        '''Specify the source file and any guards (automatically in
2224762Snate@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."
2264762Snate@binkert.org
2274762Snate@binkert.org        bisect.insort_right(SimObject.modnames, self.modname)
2284762Snate@binkert.org
2294762Snate@binkert.orgclass SwigSource(SourceFile):
2304762Snate@binkert.org    '''Add a swig file to build'''
2314762Snate@binkert.org
2324762Snate@binkert.org    def __init__(self, package, source, **guards):
2334762Snate@binkert.org        '''Specify the python package, the source file, and any guards'''
2344762Snate@binkert.org        super(SwigSource, self).__init__(source, skip_no_python=True, **guards)
2354762Snate@binkert.org
2364762Snate@binkert.org        modname,ext = self.extname
2374382Sbinkertn@umich.edu        assert ext == 'i'
2384382Sbinkertn@umich.edu
2394762Snate@binkert.org        self.module = modname
2404762Snate@binkert.org        cc_file = joinpath(self.dirname, modname + '_wrap.cc')
2414762Snate@binkert.org        py_file = joinpath(self.dirname, modname + '.py')
2424382Sbinkertn@umich.edu
2434382Sbinkertn@umich.edu        self.cc_source = Source(cc_file, swig=True, parent=self, **guards)
2444762Snate@binkert.org        self.py_source = PySource(package, py_file, parent=self, **guards)
2454382Sbinkertn@umich.edu
2464382Sbinkertn@umich.educlass ProtoBuf(SourceFile):
2474762Snate@binkert.org    '''Add a Protocol Buffer to build'''
2484382Sbinkertn@umich.edu
2494382Sbinkertn@umich.edu    def __init__(self, source, **guards):
2504762Snate@binkert.org        '''Specify the source file, and any guards'''
2514382Sbinkertn@umich.edu        super(ProtoBuf, self).__init__(source, **guards)
2524762Snate@binkert.org
2534762Snate@binkert.org        # Get the file name and the extension
2544382Sbinkertn@umich.edu        modname,ext = self.extname
2554382Sbinkertn@umich.edu        assert ext == 'proto'
2564762Snate@binkert.org
2574762Snate@binkert.org        # Currently, we stick to generating the C++ headers, so we
2584762Snate@binkert.org        # only need to track the source and header.
2594762Snate@binkert.org        self.cc_file = File(modname + '.pb.cc')
2604762Snate@binkert.org        self.hh_file = File(modname + '.pb.h')
2614762Snate@binkert.org
2624762Snate@binkert.orgclass UnitTest(object):
2634762Snate@binkert.org    '''Create a UnitTest'''
2644762Snate@binkert.org
2654762Snate@binkert.org    all = []
2664762Snate@binkert.org    def __init__(self, target, *sources, **kwargs):
2674762Snate@binkert.org        '''Specify the target name and any sources.  Sources that are
2684762Snate@binkert.org        not SourceFiles are evalued with Source().  All files are
2694762Snate@binkert.org        guarded with a guard of the same name as the UnitTest
2704762Snate@binkert.org        target.'''
2714762Snate@binkert.org
2724762Snate@binkert.org        srcs = []
2734762Snate@binkert.org        for src in sources:
2744762Snate@binkert.org            if not isinstance(src, SourceFile):
2754762Snate@binkert.org                src = Source(src, skip_lib=True)
2764762Snate@binkert.org            src.guards[target] = True
2774762Snate@binkert.org            srcs.append(src)
2784762Snate@binkert.org
2794762Snate@binkert.org        self.sources = srcs
2804762Snate@binkert.org        self.target = target
2814762Snate@binkert.org        self.main = kwargs.get('main', False)
2824762Snate@binkert.org        UnitTest.all.append(self)
2834762Snate@binkert.org
2844762Snate@binkert.org# Children should have access
2854762Snate@binkert.orgExport('Source')
2864762Snate@binkert.orgExport('PySource')
2874762Snate@binkert.orgExport('SimObject')
2884762Snate@binkert.orgExport('SwigSource')
2894762Snate@binkert.orgExport('ProtoBuf')
2904762Snate@binkert.orgExport('UnitTest')
2914762Snate@binkert.org
2924762Snate@binkert.org########################################################################
2934762Snate@binkert.org#
2944762Snate@binkert.org# Debug Flags
2954762Snate@binkert.org#
2964762Snate@binkert.orgdebug_flags = {}
2974762Snate@binkert.orgdef DebugFlag(name, desc=None):
2984762Snate@binkert.org    if name in debug_flags:
2994762Snate@binkert.org        raise AttributeError, "Flag %s already specified" % name
3004762Snate@binkert.org    debug_flags[name] = (name, (), desc)
3014762Snate@binkert.org
3024762Snate@binkert.orgdef CompoundFlag(name, flags, desc=None):
3034762Snate@binkert.org    if name in debug_flags:
3044762Snate@binkert.org        raise AttributeError, "Flag %s already specified" % name
3054382Sbinkertn@umich.edu
3064762Snate@binkert.org    compound = tuple(flags)
3074382Sbinkertn@umich.edu    debug_flags[name] = (name, compound, desc)
3084762Snate@binkert.org
3094382Sbinkertn@umich.eduExport('DebugFlag')
3104762Snate@binkert.orgExport('CompoundFlag')
3114762Snate@binkert.org
3124762Snate@binkert.org########################################################################
3134762Snate@binkert.org#
3144382Sbinkertn@umich.edu# Set some compiler variables
3154382Sbinkertn@umich.edu#
3164382Sbinkertn@umich.edu
3174382Sbinkertn@umich.edu# Include file paths are rooted in this directory.  SCons will
3184382Sbinkertn@umich.edu# automatically expand '.' to refer to both the source directory and
3194382Sbinkertn@umich.edu# the corresponding build directory to pick up generated include
3204762Snate@binkert.org# files.
3214382Sbinkertn@umich.eduenv.Append(CPPPATH=Dir('.'))
3224382Sbinkertn@umich.edu
3234382Sbinkertn@umich.edufor extra_dir in extras_dir_list:
3244382Sbinkertn@umich.edu    env.Append(CPPPATH=Dir(extra_dir))
3254762Snate@binkert.org
3264762Snate@binkert.org# Workaround for bug in SCons version > 0.97d20071212
3274762Snate@binkert.org# Scons bug id: 2006 gem5 Bug id: 308
3284382Sbinkertn@umich.edufor root, dirs, files in os.walk(base_dir, topdown=True):
3295192Ssaidi@eecs.umich.edu    Dir(root[len(base_dir) + 1:])
3305192Ssaidi@eecs.umich.edu
3315192Ssaidi@eecs.umich.edu########################################################################
3325192Ssaidi@eecs.umich.edu#
3335192Ssaidi@eecs.umich.edu# Walk the tree and execute all SConscripts in subdirectories
3345192Ssaidi@eecs.umich.edu#
3355192Ssaidi@eecs.umich.edu
3365192Ssaidi@eecs.umich.eduhere = Dir('.').srcnode().abspath
3375192Ssaidi@eecs.umich.edufor root, dirs, files in os.walk(base_dir, topdown=True):
3384762Snate@binkert.org    if root == here:
3394382Sbinkertn@umich.edu        # we don't want to recurse back into this SConscript
3404382Sbinkertn@umich.edu        continue
3414382Sbinkertn@umich.edu
3424762Snate@binkert.org    if 'SConscript' in files:
3434762Snate@binkert.org        build_dir = joinpath(env['BUILDDIR'], root[len(base_dir) + 1:])
3444382Sbinkertn@umich.edu        SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3454382Sbinkertn@umich.edu
3464382Sbinkertn@umich.edufor extra_dir in extras_dir_list:
3474762Snate@binkert.org    prefix_len = len(dirname(extra_dir)) + 1
3484382Sbinkertn@umich.edu
3494382Sbinkertn@umich.edu    # Also add the corresponding build directory to pick up generated
3504762Snate@binkert.org    # include files.
3514762Snate@binkert.org    env.Append(CPPPATH=Dir(joinpath(env['BUILDDIR'], extra_dir[prefix_len:])))
3524762Snate@binkert.org
3534382Sbinkertn@umich.edu    for root, dirs, files in os.walk(extra_dir, topdown=True):
3544382Sbinkertn@umich.edu        # if build lives in the extras directory, don't walk down it
3554382Sbinkertn@umich.edu        if 'build' in dirs:
3564382Sbinkertn@umich.edu            dirs.remove('build')
3574382Sbinkertn@umich.edu
3584382Sbinkertn@umich.edu        if 'SConscript' in files:
3594382Sbinkertn@umich.edu            build_dir = joinpath(env['BUILDDIR'], root[prefix_len:])
3604382Sbinkertn@umich.edu            SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3614382Sbinkertn@umich.edu
3624382Sbinkertn@umich.edufor opt in export_vars:
363955SN/A    env.ConfigFile(opt)
364955SN/A
365955SN/Adef makeTheISA(source, target, env):
366955SN/A    isas = [ src.get_contents() for src in source ]
3671108SN/A    target_isa = env['TARGET_ISA']
368955SN/A    def define(isa):
369955SN/A        return isa.upper() + '_ISA'
370955SN/A
371955SN/A    def namespace(isa):
372955SN/A        return isa[0].upper() + isa[1:].lower() + 'ISA'
373955SN/A
374955SN/A
375955SN/A    code = code_formatter()
376955SN/A    code('''\
3772655Sstever@eecs.umich.edu#ifndef __CONFIG_THE_ISA_HH__
3782655Sstever@eecs.umich.edu#define __CONFIG_THE_ISA_HH__
3792655Sstever@eecs.umich.edu
3802655Sstever@eecs.umich.edu''')
3812655Sstever@eecs.umich.edu
3822655Sstever@eecs.umich.edu    # create defines for the preprocessing and compile-time determination
3832655Sstever@eecs.umich.edu    for i,isa in enumerate(isas):
3842655Sstever@eecs.umich.edu        code('#define $0 $1', define(isa), i + 1)
3852655Sstever@eecs.umich.edu    code()
3862655Sstever@eecs.umich.edu
3874762Snate@binkert.org    # create an enum for any run-time determination of the ISA, we
3882655Sstever@eecs.umich.edu    # reuse the same name as the namespaces
3892655Sstever@eecs.umich.edu    code('enum class Arch {')
3904007Ssaidi@eecs.umich.edu    for i,isa in enumerate(isas):
3914596Sbinkertn@umich.edu        if i + 1 == len(isas):
3924007Ssaidi@eecs.umich.edu            code('  $0 = $1', namespace(isa), define(isa))
3934596Sbinkertn@umich.edu        else:
3944596Sbinkertn@umich.edu            code('  $0 = $1,', namespace(isa), define(isa))
3952655Sstever@eecs.umich.edu    code('};')
3964382Sbinkertn@umich.edu
3972655Sstever@eecs.umich.edu    code('''
3982655Sstever@eecs.umich.edu
3992655Sstever@eecs.umich.edu#define THE_ISA ${{define(target_isa)}}
400955SN/A#define TheISA ${{namespace(target_isa)}}
4013918Ssaidi@eecs.umich.edu#define THE_ISA_STR "${{target_isa}}"
4023918Ssaidi@eecs.umich.edu
4033918Ssaidi@eecs.umich.edu#endif // __CONFIG_THE_ISA_HH__''')
4043918Ssaidi@eecs.umich.edu
4053918Ssaidi@eecs.umich.edu    code.write(str(target[0]))
4063918Ssaidi@eecs.umich.edu
4073918Ssaidi@eecs.umich.eduenv.Command('config/the_isa.hh', map(Value, all_isa_list),
4083918Ssaidi@eecs.umich.edu            MakeAction(makeTheISA, Transform("CFG ISA", 0)))
4093918Ssaidi@eecs.umich.edu
4103918Ssaidi@eecs.umich.edudef makeTheGPUISA(source, target, env):
4113918Ssaidi@eecs.umich.edu    isas = [ src.get_contents() for src in source ]
4123918Ssaidi@eecs.umich.edu    target_gpu_isa = env['TARGET_GPU_ISA']
4133918Ssaidi@eecs.umich.edu    def define(isa):
4143918Ssaidi@eecs.umich.edu        return isa.upper() + '_ISA'
4153940Ssaidi@eecs.umich.edu
4163940Ssaidi@eecs.umich.edu    def namespace(isa):
4173940Ssaidi@eecs.umich.edu        return isa[0].upper() + isa[1:].lower() + 'ISA'
4183942Ssaidi@eecs.umich.edu
4193940Ssaidi@eecs.umich.edu
4203515Ssaidi@eecs.umich.edu    code = code_formatter()
4213918Ssaidi@eecs.umich.edu    code('''\
4224762Snate@binkert.org#ifndef __CONFIG_THE_GPU_ISA_HH__
4233515Ssaidi@eecs.umich.edu#define __CONFIG_THE_GPU_ISA_HH__
4242655Sstever@eecs.umich.edu
4253918Ssaidi@eecs.umich.edu''')
4263619Sbinkertn@umich.edu
427955SN/A    # create defines for the preprocessing and compile-time determination
428955SN/A    for i,isa in enumerate(isas):
4292655Sstever@eecs.umich.edu        code('#define $0 $1', define(isa), i + 1)
4303918Ssaidi@eecs.umich.edu    code()
4313619Sbinkertn@umich.edu
432955SN/A    # create an enum for any run-time determination of the ISA, we
433955SN/A    # reuse the same name as the namespaces
4342655Sstever@eecs.umich.edu    code('enum class GPUArch {')
4353918Ssaidi@eecs.umich.edu    for i,isa in enumerate(isas):
4363619Sbinkertn@umich.edu        if i + 1 == len(isas):
437955SN/A            code('  $0 = $1', namespace(isa), define(isa))
438955SN/A        else:
4392655Sstever@eecs.umich.edu            code('  $0 = $1,', namespace(isa), define(isa))
4403918Ssaidi@eecs.umich.edu    code('};')
4413683Sstever@eecs.umich.edu
4422655Sstever@eecs.umich.edu    code('''
4431869SN/A
4441869SN/A#define THE_GPU_ISA ${{define(target_gpu_isa)}}
445#define TheGpuISA ${{namespace(target_gpu_isa)}}
446#define THE_GPU_ISA_STR "${{target_gpu_isa}}"
447
448#endif // __CONFIG_THE_GPU_ISA_HH__''')
449
450    code.write(str(target[0]))
451
452env.Command('config/the_gpu_isa.hh', map(Value, all_gpu_isa_list),
453            MakeAction(makeTheGPUISA, Transform("CFG ISA", 0)))
454
455########################################################################
456#
457# Prevent any SimObjects from being added after this point, they
458# should all have been added in the SConscripts above
459#
460SimObject.fixed = True
461
462class DictImporter(object):
463    '''This importer takes a dictionary of arbitrary module names that
464    map to arbitrary filenames.'''
465    def __init__(self, modules):
466        self.modules = modules
467        self.installed = set()
468
469    def __del__(self):
470        self.unload()
471
472    def unload(self):
473        import sys
474        for module in self.installed:
475            del sys.modules[module]
476        self.installed = set()
477
478    def find_module(self, fullname, path):
479        if fullname == 'm5.defines':
480            return self
481
482        if fullname == 'm5.objects':
483            return self
484
485        if fullname.startswith('m5.internal'):
486            return None
487
488        source = self.modules.get(fullname, None)
489        if source is not None and fullname.startswith('m5.objects'):
490            return self
491
492        return None
493
494    def load_module(self, fullname):
495        mod = imp.new_module(fullname)
496        sys.modules[fullname] = mod
497        self.installed.add(fullname)
498
499        mod.__loader__ = self
500        if fullname == 'm5.objects':
501            mod.__path__ = fullname.split('.')
502            return mod
503
504        if fullname == 'm5.defines':
505            mod.__dict__['buildEnv'] = m5.util.SmartDict(build_env)
506            return mod
507
508        source = self.modules[fullname]
509        if source.modname == '__init__':
510            mod.__path__ = source.modpath
511        mod.__file__ = source.abspath
512
513        exec file(source.abspath, 'r') in mod.__dict__
514
515        return mod
516
517import m5.SimObject
518import m5.params
519from m5.util import code_formatter
520
521m5.SimObject.clear()
522m5.params.clear()
523
524# install the python importer so we can grab stuff from the source
525# tree itself.  We can't have SimObjects added after this point or
526# else we won't know about them for the rest of the stuff.
527importer = DictImporter(PySource.modules)
528sys.meta_path[0:0] = [ importer ]
529
530# import all sim objects so we can populate the all_objects list
531# make sure that we're working with a list, then let's sort it
532for modname in SimObject.modnames:
533    exec('from m5.objects import %s' % modname)
534
535# we need to unload all of the currently imported modules so that they
536# will be re-imported the next time the sconscript is run
537importer.unload()
538sys.meta_path.remove(importer)
539
540sim_objects = m5.SimObject.allClasses
541all_enums = m5.params.allEnums
542
543if m5.SimObject.noCxxHeader:
544    print >> sys.stderr, \
545        "warning: At least one SimObject lacks a header specification. " \
546        "This can cause unexpected results in the generated SWIG " \
547        "wrappers."
548
549# Find param types that need to be explicitly wrapped with swig.
550# These will be recognized because the ParamDesc will have a
551# swig_decl() method.  Most param types are based on types that don't
552# need this, either because they're based on native types (like Int)
553# or because they're SimObjects (which get swigged independently).
554# For now the only things handled here are VectorParam types.
555params_to_swig = {}
556for name,obj in sorted(sim_objects.iteritems()):
557    for param in obj._params.local.values():
558        # load the ptype attribute now because it depends on the
559        # current version of SimObject.allClasses, but when scons
560        # actually uses the value, all versions of
561        # SimObject.allClasses will have been loaded
562        param.ptype
563
564        if not hasattr(param, 'swig_decl'):
565            continue
566        pname = param.ptype_str
567        if pname not in params_to_swig:
568            params_to_swig[pname] = param
569
570########################################################################
571#
572# calculate extra dependencies
573#
574module_depends = ["m5", "m5.SimObject", "m5.params"]
575depends = [ PySource.modules[dep].snode for dep in module_depends ]
576depends.sort(key = lambda x: x.name)
577
578########################################################################
579#
580# Commands for the basic automatically generated python files
581#
582
583# Generate Python file containing a dict specifying the current
584# buildEnv flags.
585def makeDefinesPyFile(target, source, env):
586    build_env = source[0].get_contents()
587
588    code = code_formatter()
589    code("""
590import m5.internal
591import m5.util
592
593buildEnv = m5.util.SmartDict($build_env)
594
595compileDate = m5.internal.core.compileDate
596_globals = globals()
597for key,val in m5.internal.core.__dict__.iteritems():
598    if key.startswith('flag_'):
599        flag = key[5:]
600        _globals[flag] = val
601del _globals
602""")
603    code.write(target[0].abspath)
604
605defines_info = Value(build_env)
606# Generate a file with all of the compile options in it
607env.Command('python/m5/defines.py', defines_info,
608            MakeAction(makeDefinesPyFile, Transform("DEFINES", 0)))
609PySource('m5', 'python/m5/defines.py')
610
611# Generate python file containing info about the M5 source code
612def makeInfoPyFile(target, source, env):
613    code = code_formatter()
614    for src in source:
615        data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
616        code('$src = ${{repr(data)}}')
617    code.write(str(target[0]))
618
619# Generate a file that wraps the basic top level files
620env.Command('python/m5/info.py',
621            [ '#/COPYING', '#/LICENSE', '#/README', ],
622            MakeAction(makeInfoPyFile, Transform("INFO")))
623PySource('m5', 'python/m5/info.py')
624
625########################################################################
626#
627# Create all of the SimObject param headers and enum headers
628#
629
630def createSimObjectParamStruct(target, source, env):
631    assert len(target) == 1 and len(source) == 1
632
633    name = str(source[0].get_contents())
634    obj = sim_objects[name]
635
636    code = code_formatter()
637    obj.cxx_param_decl(code)
638    code.write(target[0].abspath)
639
640def createSimObjectCxxConfig(is_header):
641    def body(target, source, env):
642        assert len(target) == 1 and len(source) == 1
643
644        name = str(source[0].get_contents())
645        obj = sim_objects[name]
646
647        code = code_formatter()
648        obj.cxx_config_param_file(code, is_header)
649        code.write(target[0].abspath)
650    return body
651
652def createParamSwigWrapper(target, source, env):
653    assert len(target) == 1 and len(source) == 1
654
655    name = str(source[0].get_contents())
656    param = params_to_swig[name]
657
658    code = code_formatter()
659    param.swig_decl(code)
660    code.write(target[0].abspath)
661
662def createEnumStrings(target, source, env):
663    assert len(target) == 1 and len(source) == 1
664
665    name = str(source[0].get_contents())
666    obj = all_enums[name]
667
668    code = code_formatter()
669    obj.cxx_def(code)
670    code.write(target[0].abspath)
671
672def createEnumDecls(target, source, env):
673    assert len(target) == 1 and len(source) == 1
674
675    name = str(source[0].get_contents())
676    obj = all_enums[name]
677
678    code = code_formatter()
679    obj.cxx_decl(code)
680    code.write(target[0].abspath)
681
682def createEnumSwigWrapper(target, source, env):
683    assert len(target) == 1 and len(source) == 1
684
685    name = str(source[0].get_contents())
686    obj = all_enums[name]
687
688    code = code_formatter()
689    obj.swig_decl(code)
690    code.write(target[0].abspath)
691
692def createSimObjectSwigWrapper(target, source, env):
693    name = source[0].get_contents()
694    obj = sim_objects[name]
695
696    code = code_formatter()
697    obj.swig_decl(code)
698    code.write(target[0].abspath)
699
700# dummy target for generated code
701# we start out with all the Source files so they get copied to build/*/ also.
702SWIG = env.Dummy('swig', [s.tnode for s in Source.get()])
703
704# Generate all of the SimObject param C++ struct header files
705params_hh_files = []
706for name,simobj in sorted(sim_objects.iteritems()):
707    py_source = PySource.modules[simobj.__module__]
708    extra_deps = [ py_source.tnode ]
709
710    hh_file = File('params/%s.hh' % name)
711    params_hh_files.append(hh_file)
712    env.Command(hh_file, Value(name),
713                MakeAction(createSimObjectParamStruct, Transform("SO PARAM")))
714    env.Depends(hh_file, depends + extra_deps)
715    env.Depends(SWIG, hh_file)
716
717# C++ parameter description files
718if GetOption('with_cxx_config'):
719    for name,simobj in sorted(sim_objects.iteritems()):
720        py_source = PySource.modules[simobj.__module__]
721        extra_deps = [ py_source.tnode ]
722
723        cxx_config_hh_file = File('cxx_config/%s.hh' % name)
724        cxx_config_cc_file = File('cxx_config/%s.cc' % name)
725        env.Command(cxx_config_hh_file, Value(name),
726                    MakeAction(createSimObjectCxxConfig(True),
727                    Transform("CXXCPRHH")))
728        env.Command(cxx_config_cc_file, Value(name),
729                    MakeAction(createSimObjectCxxConfig(False),
730                    Transform("CXXCPRCC")))
731        env.Depends(cxx_config_hh_file, depends + extra_deps +
732                    [File('params/%s.hh' % name), File('sim/cxx_config.hh')])
733        env.Depends(cxx_config_cc_file, depends + extra_deps +
734                    [cxx_config_hh_file])
735        Source(cxx_config_cc_file)
736
737    cxx_config_init_cc_file = File('cxx_config/init.cc')
738
739    def createCxxConfigInitCC(target, source, env):
740        assert len(target) == 1 and len(source) == 1
741
742        code = code_formatter()
743
744        for name,simobj in sorted(sim_objects.iteritems()):
745            if not hasattr(simobj, 'abstract') or not simobj.abstract:
746                code('#include "cxx_config/${name}.hh"')
747        code()
748        code('void cxxConfigInit()')
749        code('{')
750        code.indent()
751        for name,simobj in sorted(sim_objects.iteritems()):
752            not_abstract = not hasattr(simobj, 'abstract') or \
753                not simobj.abstract
754            if not_abstract and 'type' in simobj.__dict__:
755                code('cxx_config_directory["${name}"] = '
756                     '${name}CxxConfigParams::makeDirectoryEntry();')
757        code.dedent()
758        code('}')
759        code.write(target[0].abspath)
760
761    py_source = PySource.modules[simobj.__module__]
762    extra_deps = [ py_source.tnode ]
763    env.Command(cxx_config_init_cc_file, Value(name),
764        MakeAction(createCxxConfigInitCC, Transform("CXXCINIT")))
765    cxx_param_hh_files = ["cxx_config/%s.hh" % simobj
766        for name,simobj in sorted(sim_objects.iteritems())
767        if not hasattr(simobj, 'abstract') or not simobj.abstract]
768    Depends(cxx_config_init_cc_file, cxx_param_hh_files +
769            [File('sim/cxx_config.hh')])
770    Source(cxx_config_init_cc_file)
771
772# Generate any needed param SWIG wrapper files
773params_i_files = []
774for name,param in sorted(params_to_swig.iteritems()):
775    i_file = File('python/m5/internal/%s.i' % (param.swig_module_name()))
776    params_i_files.append(i_file)
777    env.Command(i_file, Value(name),
778                MakeAction(createParamSwigWrapper, Transform("SW PARAM")))
779    env.Depends(i_file, depends)
780    env.Depends(SWIG, i_file)
781    SwigSource('m5.internal', i_file)
782
783# Generate all enum header files
784for name,enum in sorted(all_enums.iteritems()):
785    py_source = PySource.modules[enum.__module__]
786    extra_deps = [ py_source.tnode ]
787
788    cc_file = File('enums/%s.cc' % name)
789    env.Command(cc_file, Value(name),
790                MakeAction(createEnumStrings, Transform("ENUM STR")))
791    env.Depends(cc_file, depends + extra_deps)
792    env.Depends(SWIG, cc_file)
793    Source(cc_file)
794
795    hh_file = File('enums/%s.hh' % name)
796    env.Command(hh_file, Value(name),
797                MakeAction(createEnumDecls, Transform("ENUMDECL")))
798    env.Depends(hh_file, depends + extra_deps)
799    env.Depends(SWIG, hh_file)
800
801    i_file = File('python/m5/internal/enum_%s.i' % name)
802    env.Command(i_file, Value(name),
803                MakeAction(createEnumSwigWrapper, Transform("ENUMSWIG")))
804    env.Depends(i_file, depends + extra_deps)
805    env.Depends(SWIG, i_file)
806    SwigSource('m5.internal', i_file)
807
808# Generate SimObject SWIG wrapper files
809for name,simobj in sorted(sim_objects.iteritems()):
810    py_source = PySource.modules[simobj.__module__]
811    extra_deps = [ py_source.tnode ]
812    i_file = File('python/m5/internal/param_%s.i' % name)
813    env.Command(i_file, Value(name),
814                MakeAction(createSimObjectSwigWrapper, Transform("SO SWIG")))
815    env.Depends(i_file, depends + extra_deps)
816    SwigSource('m5.internal', i_file)
817
818# Generate the main swig init file
819def makeEmbeddedSwigInit(target, source, env):
820    code = code_formatter()
821    module = source[0].get_contents()
822    code('''\
823#include "sim/init.hh"
824
825extern "C" {
826    void init_${module}();
827}
828
829EmbeddedSwig embed_swig_${module}(init_${module});
830''')
831    code.write(str(target[0]))
832
833# Build all swig modules
834for swig in SwigSource.all:
835    env.Command([swig.cc_source.tnode, swig.py_source.tnode], swig.tnode,
836                MakeAction('$SWIG $SWIGFLAGS -outdir ${TARGETS[1].dir} '
837                '-o ${TARGETS[0]} $SOURCES', Transform("SWIG")))
838    cc_file = str(swig.tnode)
839    init_file = '%s/%s_init.cc' % (dirname(cc_file), basename(cc_file))
840    env.Command(init_file, Value(swig.module),
841                MakeAction(makeEmbeddedSwigInit, Transform("EMBED SW")))
842    env.Depends(SWIG, init_file)
843    Source(init_file, **swig.guards)
844
845# Build all protocol buffers if we have got protoc and protobuf available
846if env['HAVE_PROTOBUF']:
847    for proto in ProtoBuf.all:
848        # Use both the source and header as the target, and the .proto
849        # file as the source. When executing the protoc compiler, also
850        # specify the proto_path to avoid having the generated files
851        # include the path.
852        env.Command([proto.cc_file, proto.hh_file], proto.tnode,
853                    MakeAction('$PROTOC --cpp_out ${TARGET.dir} '
854                               '--proto_path ${SOURCE.dir} $SOURCE',
855                               Transform("PROTOC")))
856
857        env.Depends(SWIG, [proto.cc_file, proto.hh_file])
858        # Add the C++ source file
859        Source(proto.cc_file, **proto.guards)
860elif ProtoBuf.all:
861    print 'Got protobuf to build, but lacks support!'
862    Exit(1)
863
864#
865# Handle debug flags
866#
867def makeDebugFlagCC(target, source, env):
868    assert(len(target) == 1 and len(source) == 1)
869
870    code = code_formatter()
871
872    # delay definition of CompoundFlags until after all the definition
873    # of all constituent SimpleFlags
874    comp_code = code_formatter()
875
876    # file header
877    code('''
878/*
879 * DO NOT EDIT THIS FILE! Automatically generated by SCons.
880 */
881
882#include "base/debug.hh"
883
884namespace Debug {
885
886''')
887
888    for name, flag in sorted(source[0].read().iteritems()):
889        n, compound, desc = flag
890        assert n == name
891
892        if not compound:
893            code('SimpleFlag $name("$name", "$desc");')
894        else:
895            comp_code('CompoundFlag $name("$name", "$desc",')
896            comp_code.indent()
897            last = len(compound) - 1
898            for i,flag in enumerate(compound):
899                if i != last:
900                    comp_code('&$flag,')
901                else:
902                    comp_code('&$flag);')
903            comp_code.dedent()
904
905    code.append(comp_code)
906    code()
907    code('} // namespace Debug')
908
909    code.write(str(target[0]))
910
911def makeDebugFlagHH(target, source, env):
912    assert(len(target) == 1 and len(source) == 1)
913
914    val = eval(source[0].get_contents())
915    name, compound, desc = val
916
917    code = code_formatter()
918
919    # file header boilerplate
920    code('''\
921/*
922 * DO NOT EDIT THIS FILE! Automatically generated by SCons.
923 */
924
925#ifndef __DEBUG_${name}_HH__
926#define __DEBUG_${name}_HH__
927
928namespace Debug {
929''')
930
931    if compound:
932        code('class CompoundFlag;')
933    code('class SimpleFlag;')
934
935    if compound:
936        code('extern CompoundFlag $name;')
937        for flag in compound:
938            code('extern SimpleFlag $flag;')
939    else:
940        code('extern SimpleFlag $name;')
941
942    code('''
943}
944
945#endif // __DEBUG_${name}_HH__
946''')
947
948    code.write(str(target[0]))
949
950for name,flag in sorted(debug_flags.iteritems()):
951    n, compound, desc = flag
952    assert n == name
953
954    hh_file = 'debug/%s.hh' % name
955    env.Command(hh_file, Value(flag),
956                MakeAction(makeDebugFlagHH, Transform("TRACING", 0)))
957    env.Depends(SWIG, hh_file)
958
959env.Command('debug/flags.cc', Value(debug_flags),
960            MakeAction(makeDebugFlagCC, Transform("TRACING", 0)))
961env.Depends(SWIG, 'debug/flags.cc')
962Source('debug/flags.cc')
963
964# version tags
965tags = \
966env.Command('sim/tags.cc', None,
967            MakeAction('util/cpt_upgrader.py --get-cc-file > $TARGET',
968                       Transform("VER TAGS")))
969env.AlwaysBuild(tags)
970
971# Embed python files.  All .py files that have been indicated by a
972# PySource() call in a SConscript need to be embedded into the M5
973# library.  To do that, we compile the file to byte code, marshal the
974# byte code, compress it, and then generate a c++ file that
975# inserts the result into an array.
976def embedPyFile(target, source, env):
977    def c_str(string):
978        if string is None:
979            return "0"
980        return '"%s"' % string
981
982    '''Action function to compile a .py into a code object, marshal
983    it, compress it, and stick it into an asm file so the code appears
984    as just bytes with a label in the data section'''
985
986    src = file(str(source[0]), 'r').read()
987
988    pysource = PySource.tnodes[source[0]]
989    compiled = compile(src, pysource.abspath, 'exec')
990    marshalled = marshal.dumps(compiled)
991    compressed = zlib.compress(marshalled)
992    data = compressed
993    sym = pysource.symname
994
995    code = code_formatter()
996    code('''\
997#include "sim/init.hh"
998
999namespace {
1000
1001const uint8_t data_${sym}[] = {
1002''')
1003    code.indent()
1004    step = 16
1005    for i in xrange(0, len(data), step):
1006        x = array.array('B', data[i:i+step])
1007        code(''.join('%d,' % d for d in x))
1008    code.dedent()
1009
1010    code('''};
1011
1012EmbeddedPython embedded_${sym}(
1013    ${{c_str(pysource.arcname)}},
1014    ${{c_str(pysource.abspath)}},
1015    ${{c_str(pysource.modpath)}},
1016    data_${sym},
1017    ${{len(data)}},
1018    ${{len(marshalled)}});
1019
1020} // anonymous namespace
1021''')
1022    code.write(str(target[0]))
1023
1024for source in PySource.all:
1025    env.Command(source.cpp, source.tnode,
1026                MakeAction(embedPyFile, Transform("EMBED PY")))
1027    env.Depends(SWIG, source.cpp)
1028    Source(source.cpp, skip_no_python=True)
1029
1030########################################################################
1031#
1032# Define binaries.  Each different build type (debug, opt, etc.) gets
1033# a slightly different build environment.
1034#
1035
1036# List of constructed environments to pass back to SConstruct
1037date_source = Source('base/date.cc', skip_lib=True)
1038
1039# Capture this directory for the closure makeEnv, otherwise when it is
1040# called, it won't know what directory it should use.
1041variant_dir = Dir('.').path
1042def variant(*path):
1043    return os.path.join(variant_dir, *path)
1044def variantd(*path):
1045    return variant(*path)+'/'
1046
1047# Function to create a new build environment as clone of current
1048# environment 'env' with modified object suffix and optional stripped
1049# binary.  Additional keyword arguments are appended to corresponding
1050# build environment vars.
1051def makeEnv(env, label, objsfx, strip = False, **kwargs):
1052    # SCons doesn't know to append a library suffix when there is a '.' in the
1053    # name.  Use '_' instead.
1054    libname = variant('gem5_' + label)
1055    exename = variant('gem5.' + label)
1056    secondary_exename = variant('m5.' + label)
1057
1058    new_env = env.Clone(OBJSUFFIX=objsfx, SHOBJSUFFIX=objsfx + 's')
1059    new_env.Label = label
1060    new_env.Append(**kwargs)
1061
1062    swig_env = new_env.Clone()
1063
1064    # Both gcc and clang have issues with unused labels and values in
1065    # the SWIG generated code
1066    swig_env.Append(CCFLAGS=['-Wno-unused-label', '-Wno-unused-value'])
1067
1068    if env['GCC']:
1069        # Depending on the SWIG version, we also need to supress
1070        # warnings about uninitialized variables and missing field
1071        # initializers.
1072        swig_env.Append(CCFLAGS=['-Wno-uninitialized',
1073                                 '-Wno-missing-field-initializers',
1074                                 '-Wno-unused-but-set-variable',
1075                                 '-Wno-maybe-uninitialized',
1076                                 '-Wno-type-limits'])
1077
1078        # Only gcc >= 4.9 supports UBSan, so check both the version
1079        # and the command-line option before adding the compiler and
1080        # linker flags.
1081        if GetOption('with_ubsan') and \
1082                compareVersions(env['GCC_VERSION'], '4.9') >= 0:
1083            new_env.Append(CCFLAGS='-fsanitize=undefined')
1084            new_env.Append(LINKFLAGS='-fsanitize=undefined')
1085
1086        # The address sanitizer is available for gcc >= 4.8
1087        if GetOption('with_asan')  and \
1088                compareVersions(env['GCC_VERSION'], '4.8') >= 0:
1089            new_env.Append(CCFLAGS='-fsanitize=address')
1090            new_env.Append(LINKFLAGS='-fsanitize=address')
1091
1092    if env['CLANG']:
1093        swig_env.Append(CCFLAGS=['-Wno-sometimes-uninitialized',
1094                                 '-Wno-deprecated-register',
1095                                 '-Wno-tautological-compare'])
1096
1097        # We require clang >= 3.1, so there is no need to check any
1098        # versions here.
1099        if GetOption('with_ubsan'):
1100            new_env.Append(CCFLAGS='-fsanitize=undefined')
1101            new_env.Append(LINKFLAGS='-fsanitize=undefined')
1102
1103        if GetOption('with_asan'):
1104            new_env.Append(CCFLAGS='-fsanitize=address')
1105            new_env.Append(LINKFLAGS='-fsanitize=address')
1106
1107    werror_env = new_env.Clone()
1108    # Treat warnings as errors but white list some warnings that we
1109    # want to allow (e.g., deprecation warnings).
1110    werror_env.Append(CCFLAGS=['-Werror',
1111                               '-Wno-error=deprecated-declarations',
1112                               '-Wno-error=deprecated',
1113                               ])
1114
1115    def make_obj(source, static, extra_deps = None):
1116        '''This function adds the specified source to the correct
1117        build environment, and returns the corresponding SCons Object
1118        nodes'''
1119
1120        if source.swig:
1121            env = swig_env
1122        elif source.Werror:
1123            env = werror_env
1124        else:
1125            env = new_env
1126
1127        if static:
1128            obj = env.StaticObject(source.tnode)
1129        else:
1130            obj = env.SharedObject(source.tnode)
1131
1132        if extra_deps:
1133            env.Depends(obj, extra_deps)
1134
1135        return obj
1136
1137    lib_guards = {'main': False, 'skip_lib': False}
1138
1139    # Without Python, leave out all SWIG and Python content from the
1140    # library builds.  The option doesn't affect gem5 built as a program
1141    if GetOption('without_python'):
1142        lib_guards['skip_no_python'] = False
1143
1144    static_objs = [ make_obj(s, True) for s in Source.get(**lib_guards) ]
1145    shared_objs = [ make_obj(s, False) for s in Source.get(**lib_guards) ]
1146
1147    static_date = make_obj(date_source, static=True, extra_deps=static_objs)
1148    static_objs.append(static_date)
1149
1150    shared_date = make_obj(date_source, static=False, extra_deps=shared_objs)
1151    shared_objs.append(shared_date)
1152
1153    # First make a library of everything but main() so other programs can
1154    # link against m5.
1155    static_lib = new_env.StaticLibrary(libname, static_objs)
1156    shared_lib = new_env.SharedLibrary(libname, shared_objs)
1157
1158    # Now link a stub with main() and the static library.
1159    main_objs = [ make_obj(s, True) for s in Source.get(main=True) ]
1160
1161    for test in UnitTest.all:
1162        flags = { test.target : True }
1163        test_sources = Source.get(**flags)
1164        test_objs = [ make_obj(s, static=True) for s in test_sources ]
1165        if test.main:
1166            test_objs += main_objs
1167        path = variant('unittest/%s.%s' % (test.target, label))
1168        new_env.Program(path, test_objs + static_objs)
1169
1170    progname = exename
1171    if strip:
1172        progname += '.unstripped'
1173
1174    targets = new_env.Program(progname, main_objs + static_objs)
1175
1176    if strip:
1177        if sys.platform == 'sunos5':
1178            cmd = 'cp $SOURCE $TARGET; strip $TARGET'
1179        else:
1180            cmd = 'strip $SOURCE -o $TARGET'
1181        targets = new_env.Command(exename, progname,
1182                    MakeAction(cmd, Transform("STRIP")))
1183
1184    new_env.Command(secondary_exename, exename,
1185            MakeAction('ln $SOURCE $TARGET', Transform("HARDLINK")))
1186
1187    new_env.M5Binary = targets[0]
1188    return new_env
1189
1190# Start out with the compiler flags common to all compilers,
1191# i.e. they all use -g for opt and -g -pg for prof
1192ccflags = {'debug' : [], 'opt' : ['-g'], 'fast' : [], 'prof' : ['-g', '-pg'],
1193           'perf' : ['-g']}
1194
1195# Start out with the linker flags common to all linkers, i.e. -pg for
1196# prof, and -lprofiler for perf. The -lprofile flag is surrounded by
1197# no-as-needed and as-needed as the binutils linker is too clever and
1198# simply doesn't link to the library otherwise.
1199ldflags = {'debug' : [], 'opt' : [], 'fast' : [], 'prof' : ['-pg'],
1200           'perf' : ['-Wl,--no-as-needed', '-lprofiler', '-Wl,--as-needed']}
1201
1202# For Link Time Optimization, the optimisation flags used to compile
1203# individual files are decoupled from those used at link time
1204# (i.e. you can compile with -O3 and perform LTO with -O0), so we need
1205# to also update the linker flags based on the target.
1206if env['GCC']:
1207    if sys.platform == 'sunos5':
1208        ccflags['debug'] += ['-gstabs+']
1209    else:
1210        ccflags['debug'] += ['-ggdb3']
1211    ldflags['debug'] += ['-O0']
1212    # opt, fast, prof and perf all share the same cc flags, also add
1213    # the optimization to the ldflags as LTO defers the optimization
1214    # to link time
1215    for target in ['opt', 'fast', 'prof', 'perf']:
1216        ccflags[target] += ['-O3']
1217        ldflags[target] += ['-O3']
1218
1219    ccflags['fast'] += env['LTO_CCFLAGS']
1220    ldflags['fast'] += env['LTO_LDFLAGS']
1221elif env['CLANG']:
1222    ccflags['debug'] += ['-g', '-O0']
1223    # opt, fast, prof and perf all share the same cc flags
1224    for target in ['opt', 'fast', 'prof', 'perf']:
1225        ccflags[target] += ['-O3']
1226else:
1227    print 'Unknown compiler, please fix compiler options'
1228    Exit(1)
1229
1230
1231# To speed things up, we only instantiate the build environments we
1232# need.  We try to identify the needed environment for each target; if
1233# we can't, we fall back on instantiating all the environments just to
1234# be safe.
1235target_types = ['debug', 'opt', 'fast', 'prof', 'perf']
1236obj2target = {'do': 'debug', 'o': 'opt', 'fo': 'fast', 'po': 'prof',
1237              'gpo' : 'perf'}
1238
1239def identifyTarget(t):
1240    ext = t.split('.')[-1]
1241    if ext in target_types:
1242        return ext
1243    if obj2target.has_key(ext):
1244        return obj2target[ext]
1245    match = re.search(r'/tests/([^/]+)/', t)
1246    if match and match.group(1) in target_types:
1247        return match.group(1)
1248    return 'all'
1249
1250needed_envs = [identifyTarget(target) for target in BUILD_TARGETS]
1251if 'all' in needed_envs:
1252    needed_envs += target_types
1253
1254def makeEnvirons(target, source, env):
1255    # cause any later Source() calls to be fatal, as a diagnostic.
1256    Source.done()
1257
1258    envList = []
1259
1260    # Debug binary
1261    if 'debug' in needed_envs:
1262        envList.append(
1263            makeEnv(env, 'debug', '.do',
1264                    CCFLAGS = Split(ccflags['debug']),
1265                    CPPDEFINES = ['DEBUG', 'TRACING_ON=1'],
1266                    LINKFLAGS = Split(ldflags['debug'])))
1267
1268    # Optimized binary
1269    if 'opt' in needed_envs:
1270        envList.append(
1271            makeEnv(env, 'opt', '.o',
1272                    CCFLAGS = Split(ccflags['opt']),
1273                    CPPDEFINES = ['TRACING_ON=1'],
1274                    LINKFLAGS = Split(ldflags['opt'])))
1275
1276    # "Fast" binary
1277    if 'fast' in needed_envs:
1278        envList.append(
1279            makeEnv(env, 'fast', '.fo', strip = True,
1280                    CCFLAGS = Split(ccflags['fast']),
1281                    CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1282                    LINKFLAGS = Split(ldflags['fast'])))
1283
1284    # Profiled binary using gprof
1285    if 'prof' in needed_envs:
1286        envList.append(
1287            makeEnv(env, 'prof', '.po',
1288                    CCFLAGS = Split(ccflags['prof']),
1289                    CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1290                    LINKFLAGS = Split(ldflags['prof'])))
1291
1292    # Profiled binary using google-pprof
1293    if 'perf' in needed_envs:
1294        envList.append(
1295            makeEnv(env, 'perf', '.gpo',
1296                    CCFLAGS = Split(ccflags['perf']),
1297                    CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1298                    LINKFLAGS = Split(ldflags['perf'])))
1299
1300    # Set up the regression tests for each build.
1301    for e in envList:
1302        SConscript(os.path.join(env.root.abspath, 'tests', 'SConscript'),
1303                   variant_dir = variantd('tests', e.Label),
1304                   exports = { 'env' : e }, duplicate = False)
1305
1306# The MakeEnvirons Builder defers the full dependency collection until
1307# after processing the ISA definition (due to dynamically generated
1308# source files).  Add this dependency to all targets so they will wait
1309# until the environments are completely set up.  Otherwise, a second
1310# process (e.g. -j2 or higher) will try to compile the requested target,
1311# not know how, and fail.
1312env.Append(BUILDERS = {'MakeEnvirons' :
1313                        Builder(action=MakeAction(makeEnvirons,
1314                                                  Transform("ENVIRONS", 1)))})
1315
1316isa_target = env['PHONY_BASE'] + '-deps'
1317environs   = env['PHONY_BASE'] + '-environs'
1318env.Depends('#all-deps',     isa_target)
1319env.Depends('#all-environs', environs)
1320env.ScanISA(isa_target, File('arch/%s/generated/inc.d' % env['TARGET_ISA']))
1321envSetup = env.MakeEnvirons(environs, isa_target)
1322
1323# make sure no -deps targets occur before all ISAs are complete
1324env.Depends(isa_target, '#all-isas')
1325# likewise for -environs targets and all the -deps targets
1326env.Depends(environs, '#all-deps')
1327