SConscript revision 11294:a368064a2ab5
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#
292665Ssaidi@eecs.umich.edu# Authors: Nathan Binkert
30955SN/A
31955SN/Aimport array
32955SN/Aimport bisect
33955SN/Aimport imp
34955SN/Aimport marshal
352632Sstever@eecs.umich.eduimport os
362632Sstever@eecs.umich.eduimport re
372632Sstever@eecs.umich.eduimport sys
382632Sstever@eecs.umich.eduimport zlib
39955SN/A
402632Sstever@eecs.umich.edufrom os.path import basename, dirname, exists, isdir, isfile, join as joinpath
412632Sstever@eecs.umich.edu
422761Sstever@eecs.umich.eduimport SCons
432632Sstever@eecs.umich.edu
442632Sstever@eecs.umich.edu# This file defines how to build a particular configuration of gem5
452632Sstever@eecs.umich.edu# based on variable settings in the 'env' build environment.
462761Sstever@eecs.umich.edu
472761Sstever@eecs.umich.eduImport('*')
482761Sstever@eecs.umich.edu
492632Sstever@eecs.umich.edu# Children need to see the environment
502632Sstever@eecs.umich.eduExport('env')
512761Sstever@eecs.umich.edu
522761Sstever@eecs.umich.edubuild_env = [(opt, env[opt]) for opt in export_vars]
532761Sstever@eecs.umich.edu
542761Sstever@eecs.umich.edufrom m5.util import code_formatter, compareVersions
552761Sstever@eecs.umich.edu
562632Sstever@eecs.umich.edu########################################################################
572632Sstever@eecs.umich.edu# Code for adding source files of various types
582632Sstever@eecs.umich.edu#
592632Sstever@eecs.umich.edu# When specifying a source file of some type, a set of guards can be
602632Sstever@eecs.umich.edu# specified for that file.  When get() is used to find the files, if
612632Sstever@eecs.umich.edu# get specifies a set of filters, only files that match those filters
622632Sstever@eecs.umich.edu# will be accepted (unspecified filters on files are assumed to be
63955SN/A# false).  Current filters are:
64955SN/A#     main -- specifies the gem5 main() function
65955SN/A#     skip_lib -- do not put this file into the gem5 library
66955SN/A#     skip_no_python -- do not put this file into a no_python library
67955SN/A#       as it embeds compiled Python
68955SN/A#     <unittest> -- unit tests use filters based on the unit test name
69955SN/A#
702656Sstever@eecs.umich.edu# A parent can now be specified for a source file and default filter
712656Sstever@eecs.umich.edu# values will be retrieved recursively from parents (children override
722656Sstever@eecs.umich.edu# parents).
732656Sstever@eecs.umich.edu#
742656Sstever@eecs.umich.educlass SourceMeta(type):
752656Sstever@eecs.umich.edu    '''Meta class for source files that keeps track of all files of a
762656Sstever@eecs.umich.edu    particular type and has a get function for finding all functions
772653Sstever@eecs.umich.edu    of a certain type that match a set of guards'''
782653Sstever@eecs.umich.edu    def __init__(cls, name, bases, dict):
792653Sstever@eecs.umich.edu        super(SourceMeta, cls).__init__(name, bases, dict)
802653Sstever@eecs.umich.edu        cls.all = []
812653Sstever@eecs.umich.edu        
822653Sstever@eecs.umich.edu    def get(cls, **guards):
832653Sstever@eecs.umich.edu        '''Find all files that match the specified guards.  If a source
842653Sstever@eecs.umich.edu        file does not specify a flag, the default is False'''
852653Sstever@eecs.umich.edu        for src in cls.all:
862653Sstever@eecs.umich.edu            for flag,value in guards.iteritems():
872653Sstever@eecs.umich.edu                # if the flag is found and has a different value, skip
881852SN/A                # this file
89955SN/A                if src.all_guards.get(flag, False) != value:
90955SN/A                    break
91955SN/A            else:
922632Sstever@eecs.umich.edu                yield src
932632Sstever@eecs.umich.edu
94955SN/Aclass SourceFile(object):
951533SN/A    '''Base object that encapsulates the notion of a source file.
962632Sstever@eecs.umich.edu    This includes, the source node, target node, various manipulations
971533SN/A    of those.  A source file also specifies a set of guards which
98955SN/A    describing which builds the source file applies to.  A parent can
99955SN/A    also be specified to get default guards from'''
1002632Sstever@eecs.umich.edu    __metaclass__ = SourceMeta
1012632Sstever@eecs.umich.edu    def __init__(self, source, parent=None, **guards):
102955SN/A        self.guards = guards
103955SN/A        self.parent = parent
104955SN/A
105955SN/A        tnode = source
1062632Sstever@eecs.umich.edu        if not isinstance(source, SCons.Node.FS.File):
107955SN/A            tnode = File(source)
1082632Sstever@eecs.umich.edu
109955SN/A        self.tnode = tnode
110955SN/A        self.snode = tnode.srcnode()
1112632Sstever@eecs.umich.edu
1122632Sstever@eecs.umich.edu        for base in type(self).__mro__:
1132632Sstever@eecs.umich.edu            if issubclass(base, SourceFile):
1142632Sstever@eecs.umich.edu                base.all.append(self)
1152632Sstever@eecs.umich.edu
1162632Sstever@eecs.umich.edu    @property
1172632Sstever@eecs.umich.edu    def filename(self):
1182632Sstever@eecs.umich.edu        return str(self.tnode)
1192632Sstever@eecs.umich.edu
1202632Sstever@eecs.umich.edu    @property
1212632Sstever@eecs.umich.edu    def dirname(self):
1223053Sstever@eecs.umich.edu        return dirname(self.filename)
1233053Sstever@eecs.umich.edu
1243053Sstever@eecs.umich.edu    @property
1253053Sstever@eecs.umich.edu    def basename(self):
1263053Sstever@eecs.umich.edu        return basename(self.filename)
1273053Sstever@eecs.umich.edu
1283053Sstever@eecs.umich.edu    @property
1293053Sstever@eecs.umich.edu    def extname(self):
1303053Sstever@eecs.umich.edu        index = self.basename.rfind('.')
1313053Sstever@eecs.umich.edu        if index <= 0:
1323053Sstever@eecs.umich.edu            # dot files aren't extensions
1333053Sstever@eecs.umich.edu            return self.basename, None
1343053Sstever@eecs.umich.edu
1353053Sstever@eecs.umich.edu        return self.basename[:index], self.basename[index+1:]
1363053Sstever@eecs.umich.edu
1373053Sstever@eecs.umich.edu    @property
1382632Sstever@eecs.umich.edu    def all_guards(self):
1392632Sstever@eecs.umich.edu        '''find all guards for this object getting default values
1402632Sstever@eecs.umich.edu        recursively from its parents'''
1412632Sstever@eecs.umich.edu        guards = {}
1422632Sstever@eecs.umich.edu        if self.parent:
1432632Sstever@eecs.umich.edu            guards.update(self.parent.guards)
1442634Sstever@eecs.umich.edu        guards.update(self.guards)
1452634Sstever@eecs.umich.edu        return guards
1462632Sstever@eecs.umich.edu
1472638Sstever@eecs.umich.edu    def __lt__(self, other): return self.filename < other.filename
1482632Sstever@eecs.umich.edu    def __le__(self, other): return self.filename <= other.filename
1492632Sstever@eecs.umich.edu    def __gt__(self, other): return self.filename > other.filename
1502632Sstever@eecs.umich.edu    def __ge__(self, other): return self.filename >= other.filename
1512632Sstever@eecs.umich.edu    def __eq__(self, other): return self.filename == other.filename
1522632Sstever@eecs.umich.edu    def __ne__(self, other): return self.filename != other.filename
1532632Sstever@eecs.umich.edu
1541858SN/A    @staticmethod
1552638Sstever@eecs.umich.edu    def done():
1562638Sstever@eecs.umich.edu        def disabled(cls, name, *ignored):
1572638Sstever@eecs.umich.edu            raise RuntimeError("Additional SourceFile '%s'" % name,\
1582638Sstever@eecs.umich.edu                  "declared, but targets deps are already fixed.")
1592638Sstever@eecs.umich.edu        SourceFile.__init__ = disabled
1602638Sstever@eecs.umich.edu
1612638Sstever@eecs.umich.edu
1622638Sstever@eecs.umich.educlass Source(SourceFile):
1632634Sstever@eecs.umich.edu    '''Add a c/c++ source file to the build'''
1642634Sstever@eecs.umich.edu    def __init__(self, source, Werror=True, swig=False, **guards):
1652634Sstever@eecs.umich.edu        '''specify the source file, and any guards'''
166955SN/A        super(Source, self).__init__(source, **guards)
167955SN/A
168955SN/A        self.Werror = Werror
169955SN/A        self.swig = swig
170955SN/A
171955SN/Aclass PySource(SourceFile):
172955SN/A    '''Add a python source file to the named package'''
173955SN/A    invalid_sym_char = re.compile('[^A-z0-9_]')
1741858SN/A    modules = {}
1751858SN/A    tnodes = {}
1762632Sstever@eecs.umich.edu    symnames = {}
177955SN/A
1782776Sstever@eecs.umich.edu    def __init__(self, package, source, **guards):
1791105SN/A        '''specify the python package, the source file, and any guards'''
1802667Sstever@eecs.umich.edu        super(PySource, self).__init__(source, **guards)
1812667Sstever@eecs.umich.edu
1822667Sstever@eecs.umich.edu        modname,ext = self.extname
1832667Sstever@eecs.umich.edu        assert ext == 'py'
1842667Sstever@eecs.umich.edu
1852667Sstever@eecs.umich.edu        if package:
1861869SN/A            path = package.split('.')
1871869SN/A        else:
1881869SN/A            path = []
1891869SN/A
1901869SN/A        modpath = path[:]
1911065SN/A        if modname != '__init__':
1922632Sstever@eecs.umich.edu            modpath += [ modname ]
1932632Sstever@eecs.umich.edu        modpath = '.'.join(modpath)
194955SN/A
1951858SN/A        arcpath = path + [ self.basename ]
1961858SN/A        abspath = self.snode.abspath
1971858SN/A        if not exists(abspath):
1981858SN/A            abspath = self.tnode.abspath
1991851SN/A
2001851SN/A        self.package = package
2011858SN/A        self.modname = modname
2022632Sstever@eecs.umich.edu        self.modpath = modpath
203955SN/A        self.arcname = joinpath(*arcpath)
2043053Sstever@eecs.umich.edu        self.abspath = abspath
2053053Sstever@eecs.umich.edu        self.compiled = File(self.filename + 'c')
2063053Sstever@eecs.umich.edu        self.cpp = File(self.filename + '.cc')
2073053Sstever@eecs.umich.edu        self.symname = PySource.invalid_sym_char.sub('_', modpath)
2083053Sstever@eecs.umich.edu
2093053Sstever@eecs.umich.edu        PySource.modules[modpath] = self
2103053Sstever@eecs.umich.edu        PySource.tnodes[self.tnode] = self
2113053Sstever@eecs.umich.edu        PySource.symnames[self.symname] = self
2123053Sstever@eecs.umich.edu
2133053Sstever@eecs.umich.educlass SimObject(PySource):
2143053Sstever@eecs.umich.edu    '''Add a SimObject python file as a python source object and add
2153053Sstever@eecs.umich.edu    it to a list of sim object modules'''
2163053Sstever@eecs.umich.edu
2173053Sstever@eecs.umich.edu    fixed = False
2183053Sstever@eecs.umich.edu    modnames = []
2193053Sstever@eecs.umich.edu
2203053Sstever@eecs.umich.edu    def __init__(self, source, **guards):
2213053Sstever@eecs.umich.edu        '''Specify the source file and any guards (automatically in
2223053Sstever@eecs.umich.edu        the m5.objects package)'''
2232667Sstever@eecs.umich.edu        super(SimObject, self).__init__('m5.objects', source, **guards)
2242667Sstever@eecs.umich.edu        if self.fixed:
2252667Sstever@eecs.umich.edu            raise AttributeError, "Too late to call SimObject now."
2262667Sstever@eecs.umich.edu
2272667Sstever@eecs.umich.edu        bisect.insort_right(SimObject.modnames, self.modname)
2282667Sstever@eecs.umich.edu
2292667Sstever@eecs.umich.educlass SwigSource(SourceFile):
2302667Sstever@eecs.umich.edu    '''Add a swig file to build'''
2312667Sstever@eecs.umich.edu
2322667Sstever@eecs.umich.edu    def __init__(self, package, source, **guards):
2332667Sstever@eecs.umich.edu        '''Specify the python package, the source file, and any guards'''
2342667Sstever@eecs.umich.edu        super(SwigSource, self).__init__(source, skip_no_python=True, **guards)
2352638Sstever@eecs.umich.edu
2362638Sstever@eecs.umich.edu        modname,ext = self.extname
2372638Sstever@eecs.umich.edu        assert ext == 'i'
2382638Sstever@eecs.umich.edu
2392638Sstever@eecs.umich.edu        self.module = modname
2401858SN/A        cc_file = joinpath(self.dirname, modname + '_wrap.cc')
2413118Sstever@eecs.umich.edu        py_file = joinpath(self.dirname, modname + '.py')
2423118Sstever@eecs.umich.edu
2433118Sstever@eecs.umich.edu        self.cc_source = Source(cc_file, swig=True, parent=self, **guards)
2443118Sstever@eecs.umich.edu        self.py_source = PySource(package, py_file, parent=self, **guards)
2453118Sstever@eecs.umich.edu
2463118Sstever@eecs.umich.educlass ProtoBuf(SourceFile):
2473118Sstever@eecs.umich.edu    '''Add a Protocol Buffer to build'''
2483118Sstever@eecs.umich.edu
2493118Sstever@eecs.umich.edu    def __init__(self, source, **guards):
2503118Sstever@eecs.umich.edu        '''Specify the source file, and any guards'''
2513118Sstever@eecs.umich.edu        super(ProtoBuf, self).__init__(source, **guards)
2523118Sstever@eecs.umich.edu
2533118Sstever@eecs.umich.edu        # Get the file name and the extension
2543118Sstever@eecs.umich.edu        modname,ext = self.extname
2553118Sstever@eecs.umich.edu        assert ext == 'proto'
2563118Sstever@eecs.umich.edu
2573118Sstever@eecs.umich.edu        # Currently, we stick to generating the C++ headers, so we
2583118Sstever@eecs.umich.edu        # only need to track the source and header.
2593118Sstever@eecs.umich.edu        self.cc_file = File(modname + '.pb.cc')
2603118Sstever@eecs.umich.edu        self.hh_file = File(modname + '.pb.h')
2613118Sstever@eecs.umich.edu
2623118Sstever@eecs.umich.educlass UnitTest(object):
2633118Sstever@eecs.umich.edu    '''Create a UnitTest'''
2643118Sstever@eecs.umich.edu
2653118Sstever@eecs.umich.edu    all = []
2663118Sstever@eecs.umich.edu    def __init__(self, target, *sources, **kwargs):
2673118Sstever@eecs.umich.edu        '''Specify the target name and any sources.  Sources that are
2683118Sstever@eecs.umich.edu        not SourceFiles are evalued with Source().  All files are
2693118Sstever@eecs.umich.edu        guarded with a guard of the same name as the UnitTest
2703118Sstever@eecs.umich.edu        target.'''
2713118Sstever@eecs.umich.edu
2723118Sstever@eecs.umich.edu        srcs = []
2733053Sstever@eecs.umich.edu        for src in sources:
2743053Sstever@eecs.umich.edu            if not isinstance(src, SourceFile):
2753053Sstever@eecs.umich.edu                src = Source(src, skip_lib=True)
2763053Sstever@eecs.umich.edu            src.guards[target] = True
2773053Sstever@eecs.umich.edu            srcs.append(src)
2783053Sstever@eecs.umich.edu
2793053Sstever@eecs.umich.edu        self.sources = srcs
2803053Sstever@eecs.umich.edu        self.target = target
2811858SN/A        self.main = kwargs.get('main', False)
2821858SN/A        UnitTest.all.append(self)
2831858SN/A
2841858SN/A# Children should have access
2851858SN/AExport('Source')
2861858SN/AExport('PySource')
2871859SN/AExport('SimObject')
2881858SN/AExport('SwigSource')
2891858SN/AExport('ProtoBuf')
2901858SN/AExport('UnitTest')
2911859SN/A
2921859SN/A########################################################################
2931862SN/A#
2943053Sstever@eecs.umich.edu# Debug Flags
2953053Sstever@eecs.umich.edu#
2963053Sstever@eecs.umich.edudebug_flags = {}
2973053Sstever@eecs.umich.edudef DebugFlag(name, desc=None):
2981859SN/A    if name in debug_flags:
2991859SN/A        raise AttributeError, "Flag %s already specified" % name
3001859SN/A    debug_flags[name] = (name, (), desc)
3011859SN/A
3021859SN/Adef CompoundFlag(name, flags, desc=None):
3031859SN/A    if name in debug_flags:
3041859SN/A        raise AttributeError, "Flag %s already specified" % name
3051859SN/A
3061862SN/A    compound = tuple(flags)
3071859SN/A    debug_flags[name] = (name, compound, desc)
3081859SN/A
3091859SN/AExport('DebugFlag')
3101858SN/AExport('CompoundFlag')
3111858SN/A
3122139SN/A########################################################################
3132139SN/A#
3142139SN/A# Set some compiler variables
3152155SN/A#
3162623SN/A
3172817Sksewell@umich.edu# Include file paths are rooted in this directory.  SCons will
3182792Sktlim@umich.edu# automatically expand '.' to refer to both the source directory and
3192155SN/A# the corresponding build directory to pick up generated include
3201869SN/A# files.
3211869SN/Aenv.Append(CPPPATH=Dir('.'))
3221869SN/A
3231869SN/Afor extra_dir in extras_dir_list:
3241869SN/A    env.Append(CPPPATH=Dir(extra_dir))
3252139SN/A
3261869SN/A# Workaround for bug in SCons version > 0.97d20071212
3272508SN/A# Scons bug id: 2006 gem5 Bug id: 308
3282508SN/Afor root, dirs, files in os.walk(base_dir, topdown=True):
3292508SN/A    Dir(root[len(base_dir) + 1:])
3302508SN/A
3312635Sstever@eecs.umich.edu########################################################################
3322635Sstever@eecs.umich.edu#
3331869SN/A# Walk the tree and execute all SConscripts in subdirectories
3341869SN/A#
3351869SN/A
3361869SN/Ahere = Dir('.').srcnode().abspath
3371869SN/Afor root, dirs, files in os.walk(base_dir, topdown=True):
3381869SN/A    if root == here:
3391869SN/A        # we don't want to recurse back into this SConscript
3401869SN/A        continue
3411965SN/A
3421965SN/A    if 'SConscript' in files:
3431965SN/A        build_dir = joinpath(env['BUILDDIR'], root[len(base_dir) + 1:])
3441869SN/A        SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3451869SN/A
3462733Sktlim@umich.edufor extra_dir in extras_dir_list:
3471869SN/A    prefix_len = len(dirname(extra_dir)) + 1
3481884SN/A
3491884SN/A    # Also add the corresponding build directory to pick up generated
3501884SN/A    # include files.
3511869SN/A    env.Append(CPPPATH=Dir(joinpath(env['BUILDDIR'], extra_dir[prefix_len:])))
3521858SN/A
3531869SN/A    for root, dirs, files in os.walk(extra_dir, topdown=True):
3541869SN/A        # if build lives in the extras directory, don't walk down it
3551869SN/A        if 'build' in dirs:
3561869SN/A            dirs.remove('build')
3571869SN/A
3581858SN/A        if 'SConscript' in files:
3592761Sstever@eecs.umich.edu            build_dir = joinpath(env['BUILDDIR'], root[prefix_len:])
3601869SN/A            SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3612733Sktlim@umich.edu
3622733Sktlim@umich.edufor opt in export_vars:
3631869SN/A    env.ConfigFile(opt)
3641869SN/A
3651869SN/Adef makeTheISA(source, target, env):
3661869SN/A    isas = [ src.get_contents() for src in source ]
3671869SN/A    target_isa = env['TARGET_ISA']
3681869SN/A    def define(isa):
3691858SN/A        return isa.upper() + '_ISA'
370955SN/A    
371955SN/A    def namespace(isa):
3721869SN/A        return isa[0].upper() + isa[1:].lower() + 'ISA' 
3731869SN/A
3741869SN/A
3751869SN/A    code = code_formatter()
3761869SN/A    code('''\
3771869SN/A#ifndef __CONFIG_THE_ISA_HH__
3781869SN/A#define __CONFIG_THE_ISA_HH__
3791869SN/A
3801869SN/A''')
3811869SN/A
3821869SN/A    # create defines for the preprocessing and compile-time determination
3831869SN/A    for i,isa in enumerate(isas):
3841869SN/A        code('#define $0 $1', define(isa), i + 1)
3851869SN/A    code()
3861869SN/A
3871869SN/A    # create an enum for any run-time determination of the ISA, we
3881869SN/A    # reuse the same name as the namespaces
3891869SN/A    code('enum class Arch {')
3901869SN/A    for i,isa in enumerate(isas):
3911869SN/A        if i + 1 == len(isas):
3921869SN/A            code('  $0 = $1', namespace(isa), define(isa))
3931869SN/A        else:
3941869SN/A            code('  $0 = $1,', namespace(isa), define(isa))
3951869SN/A    code('};')
3961869SN/A
3971869SN/A    code('''
3981869SN/A
3991869SN/A#define THE_ISA ${{define(target_isa)}}
4001869SN/A#define TheISA ${{namespace(target_isa)}}
4011869SN/A#define THE_ISA_STR "${{target_isa}}"
4021869SN/A
4031869SN/A#endif // __CONFIG_THE_ISA_HH__''')
4041869SN/A
4051869SN/A    code.write(str(target[0]))
4061869SN/A
4071869SN/Aenv.Command('config/the_isa.hh', map(Value, all_isa_list),
4081869SN/A            MakeAction(makeTheISA, Transform("CFG ISA", 0)))
4091869SN/A
4101869SN/A########################################################################
4112655Sstever@eecs.umich.edu#
4122655Sstever@eecs.umich.edu# Prevent any SimObjects from being added after this point, they
4132655Sstever@eecs.umich.edu# should all have been added in the SConscripts above
4142655Sstever@eecs.umich.edu#
4152655Sstever@eecs.umich.eduSimObject.fixed = True
4162655Sstever@eecs.umich.edu
4172655Sstever@eecs.umich.educlass DictImporter(object):
4182655Sstever@eecs.umich.edu    '''This importer takes a dictionary of arbitrary module names that
4192655Sstever@eecs.umich.edu    map to arbitrary filenames.'''
4202655Sstever@eecs.umich.edu    def __init__(self, modules):
4212655Sstever@eecs.umich.edu        self.modules = modules
4222655Sstever@eecs.umich.edu        self.installed = set()
4232655Sstever@eecs.umich.edu
4242655Sstever@eecs.umich.edu    def __del__(self):
4252655Sstever@eecs.umich.edu        self.unload()
4262655Sstever@eecs.umich.edu
4272655Sstever@eecs.umich.edu    def unload(self):
4282655Sstever@eecs.umich.edu        import sys
4292655Sstever@eecs.umich.edu        for module in self.installed:
4302655Sstever@eecs.umich.edu            del sys.modules[module]
4312655Sstever@eecs.umich.edu        self.installed = set()
4322655Sstever@eecs.umich.edu
4332655Sstever@eecs.umich.edu    def find_module(self, fullname, path):
4342655Sstever@eecs.umich.edu        if fullname == 'm5.defines':
4352655Sstever@eecs.umich.edu            return self
4362655Sstever@eecs.umich.edu
4372634Sstever@eecs.umich.edu        if fullname == 'm5.objects':
4382634Sstever@eecs.umich.edu            return self
4392634Sstever@eecs.umich.edu
4402634Sstever@eecs.umich.edu        if fullname.startswith('m5.internal'):
4412634Sstever@eecs.umich.edu            return None
4422634Sstever@eecs.umich.edu
4432638Sstever@eecs.umich.edu        source = self.modules.get(fullname, None)
4442638Sstever@eecs.umich.edu        if source is not None and fullname.startswith('m5.objects'):
4452638Sstever@eecs.umich.edu            return self
4462638Sstever@eecs.umich.edu
4472638Sstever@eecs.umich.edu        return None
4481869SN/A
4491869SN/A    def load_module(self, fullname):
450955SN/A        mod = imp.new_module(fullname)
451955SN/A        sys.modules[fullname] = mod
452955SN/A        self.installed.add(fullname)
453955SN/A
4541858SN/A        mod.__loader__ = self
4551858SN/A        if fullname == 'm5.objects':
4561858SN/A            mod.__path__ = fullname.split('.')
4572632Sstever@eecs.umich.edu            return mod
4582632Sstever@eecs.umich.edu
4592632Sstever@eecs.umich.edu        if fullname == 'm5.defines':
4602632Sstever@eecs.umich.edu            mod.__dict__['buildEnv'] = m5.util.SmartDict(build_env)
4612632Sstever@eecs.umich.edu            return mod
4622634Sstever@eecs.umich.edu
4632638Sstever@eecs.umich.edu        source = self.modules[fullname]
4642023SN/A        if source.modname == '__init__':
4652632Sstever@eecs.umich.edu            mod.__path__ = source.modpath
4662632Sstever@eecs.umich.edu        mod.__file__ = source.abspath
4672632Sstever@eecs.umich.edu
4682632Sstever@eecs.umich.edu        exec file(source.abspath, 'r') in mod.__dict__
4692632Sstever@eecs.umich.edu
4702632Sstever@eecs.umich.edu        return mod
4712632Sstever@eecs.umich.edu
4722632Sstever@eecs.umich.eduimport m5.SimObject
4732632Sstever@eecs.umich.eduimport m5.params
4742632Sstever@eecs.umich.edufrom m5.util import code_formatter
4752632Sstever@eecs.umich.edu
4762023SN/Am5.SimObject.clear()
4772632Sstever@eecs.umich.edum5.params.clear()
4782632Sstever@eecs.umich.edu
4791889SN/A# install the python importer so we can grab stuff from the source
4801889SN/A# tree itself.  We can't have SimObjects added after this point or
4812632Sstever@eecs.umich.edu# else we won't know about them for the rest of the stuff.
4822632Sstever@eecs.umich.eduimporter = DictImporter(PySource.modules)
4832632Sstever@eecs.umich.edusys.meta_path[0:0] = [ importer ]
4842632Sstever@eecs.umich.edu
4852632Sstever@eecs.umich.edu# import all sim objects so we can populate the all_objects list
4862632Sstever@eecs.umich.edu# make sure that we're working with a list, then let's sort it
4872632Sstever@eecs.umich.edufor modname in SimObject.modnames:
4882632Sstever@eecs.umich.edu    exec('from m5.objects import %s' % modname)
4892632Sstever@eecs.umich.edu
4902632Sstever@eecs.umich.edu# we need to unload all of the currently imported modules so that they
4912632Sstever@eecs.umich.edu# will be re-imported the next time the sconscript is run
4922632Sstever@eecs.umich.eduimporter.unload()
4932632Sstever@eecs.umich.edusys.meta_path.remove(importer)
4942632Sstever@eecs.umich.edu
4951888SN/Asim_objects = m5.SimObject.allClasses
4961888SN/Aall_enums = m5.params.allEnums
4971869SN/A
4981869SN/Aif m5.SimObject.noCxxHeader:
4991858SN/A    print >> sys.stderr, \
5002598SN/A        "warning: At least one SimObject lacks a header specification. " \
5012598SN/A        "This can cause unexpected results in the generated SWIG " \
5022598SN/A        "wrappers."
5032598SN/A
5042598SN/A# Find param types that need to be explicitly wrapped with swig.
5051858SN/A# These will be recognized because the ParamDesc will have a
5061858SN/A# swig_decl() method.  Most param types are based on types that don't
5071858SN/A# need this, either because they're based on native types (like Int)
5081858SN/A# or because they're SimObjects (which get swigged independently).
5091858SN/A# For now the only things handled here are VectorParam types.
5101858SN/Aparams_to_swig = {}
5111858SN/Afor name,obj in sorted(sim_objects.iteritems()):
5121858SN/A    for param in obj._params.local.values():
5131858SN/A        # load the ptype attribute now because it depends on the
5141871SN/A        # current version of SimObject.allClasses, but when scons
5151858SN/A        # actually uses the value, all versions of
5161858SN/A        # SimObject.allClasses will have been loaded
5171858SN/A        param.ptype
5181858SN/A
5191858SN/A        if not hasattr(param, 'swig_decl'):
5201858SN/A            continue
5211858SN/A        pname = param.ptype_str
5221858SN/A        if pname not in params_to_swig:
5231858SN/A            params_to_swig[pname] = param
5241858SN/A
5251858SN/A########################################################################
5261859SN/A#
5271859SN/A# calculate extra dependencies
5281869SN/A#
5291888SN/Amodule_depends = ["m5", "m5.SimObject", "m5.params"]
5302632Sstever@eecs.umich.edudepends = [ PySource.modules[dep].snode for dep in module_depends ]
5311869SN/Adepends.sort(key = lambda x: x.name)
5321884SN/A
5331884SN/A########################################################################
5341884SN/A#
5351884SN/A# Commands for the basic automatically generated python files
5361884SN/A#
5371884SN/A
5381965SN/A# Generate Python file containing a dict specifying the current
5391965SN/A# buildEnv flags.
5401965SN/Adef makeDefinesPyFile(target, source, env):
5412761Sstever@eecs.umich.edu    build_env = source[0].get_contents()
5421869SN/A
5431869SN/A    code = code_formatter()
5442632Sstever@eecs.umich.edu    code("""
5452667Sstever@eecs.umich.eduimport m5.internal
5461869SN/Aimport m5.util
5471869SN/A
5482929Sktlim@umich.edubuildEnv = m5.util.SmartDict($build_env)
5492929Sktlim@umich.edu
5503036Sstever@eecs.umich.educompileDate = m5.internal.core.compileDate
5512929Sktlim@umich.edu_globals = globals()
552955SN/Afor key,val in m5.internal.core.__dict__.iteritems():
5532598SN/A    if key.startswith('flag_'):
5542598SN/A        flag = key[5:]
555955SN/A        _globals[flag] = val
556955SN/Adel _globals
557955SN/A""")
5581530SN/A    code.write(target[0].abspath)
559955SN/A
560955SN/Adefines_info = Value(build_env)
561955SN/A# Generate a file with all of the compile options in it
562env.Command('python/m5/defines.py', defines_info,
563            MakeAction(makeDefinesPyFile, Transform("DEFINES", 0)))
564PySource('m5', 'python/m5/defines.py')
565
566# Generate python file containing info about the M5 source code
567def makeInfoPyFile(target, source, env):
568    code = code_formatter()
569    for src in source:
570        data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
571        code('$src = ${{repr(data)}}')
572    code.write(str(target[0]))
573
574# Generate a file that wraps the basic top level files
575env.Command('python/m5/info.py',
576            [ '#/COPYING', '#/LICENSE', '#/README', ],
577            MakeAction(makeInfoPyFile, Transform("INFO")))
578PySource('m5', 'python/m5/info.py')
579
580########################################################################
581#
582# Create all of the SimObject param headers and enum headers
583#
584
585def createSimObjectParamStruct(target, source, env):
586    assert len(target) == 1 and len(source) == 1
587
588    name = str(source[0].get_contents())
589    obj = sim_objects[name]
590
591    code = code_formatter()
592    obj.cxx_param_decl(code)
593    code.write(target[0].abspath)
594
595def createSimObjectCxxConfig(is_header):
596    def body(target, source, env):
597        assert len(target) == 1 and len(source) == 1
598
599        name = str(source[0].get_contents())
600        obj = sim_objects[name]
601
602        code = code_formatter()
603        obj.cxx_config_param_file(code, is_header)
604        code.write(target[0].abspath)
605    return body
606
607def createParamSwigWrapper(target, source, env):
608    assert len(target) == 1 and len(source) == 1
609
610    name = str(source[0].get_contents())
611    param = params_to_swig[name]
612
613    code = code_formatter()
614    param.swig_decl(code)
615    code.write(target[0].abspath)
616
617def createEnumStrings(target, source, env):
618    assert len(target) == 1 and len(source) == 1
619
620    name = str(source[0].get_contents())
621    obj = all_enums[name]
622
623    code = code_formatter()
624    obj.cxx_def(code)
625    code.write(target[0].abspath)
626
627def createEnumDecls(target, source, env):
628    assert len(target) == 1 and len(source) == 1
629
630    name = str(source[0].get_contents())
631    obj = all_enums[name]
632
633    code = code_formatter()
634    obj.cxx_decl(code)
635    code.write(target[0].abspath)
636
637def createEnumSwigWrapper(target, source, env):
638    assert len(target) == 1 and len(source) == 1
639
640    name = str(source[0].get_contents())
641    obj = all_enums[name]
642
643    code = code_formatter()
644    obj.swig_decl(code)
645    code.write(target[0].abspath)
646
647def createSimObjectSwigWrapper(target, source, env):
648    name = source[0].get_contents()
649    obj = sim_objects[name]
650
651    code = code_formatter()
652    obj.swig_decl(code)
653    code.write(target[0].abspath)
654
655# dummy target for generated code
656# we start out with all the Source files so they get copied to build/*/ also.
657SWIG = env.Dummy('swig', [s.tnode for s in Source.get()])
658
659# Generate all of the SimObject param C++ struct header files
660params_hh_files = []
661for name,simobj in sorted(sim_objects.iteritems()):
662    py_source = PySource.modules[simobj.__module__]
663    extra_deps = [ py_source.tnode ]
664
665    hh_file = File('params/%s.hh' % name)
666    params_hh_files.append(hh_file)
667    env.Command(hh_file, Value(name),
668                MakeAction(createSimObjectParamStruct, Transform("SO PARAM")))
669    env.Depends(hh_file, depends + extra_deps)
670    env.Depends(SWIG, hh_file)
671
672# C++ parameter description files
673if GetOption('with_cxx_config'):
674    for name,simobj in sorted(sim_objects.iteritems()):
675        py_source = PySource.modules[simobj.__module__]
676        extra_deps = [ py_source.tnode ]
677
678        cxx_config_hh_file = File('cxx_config/%s.hh' % name)
679        cxx_config_cc_file = File('cxx_config/%s.cc' % name)
680        env.Command(cxx_config_hh_file, Value(name),
681                    MakeAction(createSimObjectCxxConfig(True),
682                    Transform("CXXCPRHH")))
683        env.Command(cxx_config_cc_file, Value(name),
684                    MakeAction(createSimObjectCxxConfig(False),
685                    Transform("CXXCPRCC")))
686        env.Depends(cxx_config_hh_file, depends + extra_deps +
687                    [File('params/%s.hh' % name), File('sim/cxx_config.hh')])
688        env.Depends(cxx_config_cc_file, depends + extra_deps +
689                    [cxx_config_hh_file])
690        Source(cxx_config_cc_file)
691
692    cxx_config_init_cc_file = File('cxx_config/init.cc')
693
694    def createCxxConfigInitCC(target, source, env):
695        assert len(target) == 1 and len(source) == 1
696
697        code = code_formatter()
698
699        for name,simobj in sorted(sim_objects.iteritems()):
700            if not hasattr(simobj, 'abstract') or not simobj.abstract:
701                code('#include "cxx_config/${name}.hh"')
702        code()
703        code('void cxxConfigInit()')
704        code('{')
705        code.indent()
706        for name,simobj in sorted(sim_objects.iteritems()):
707            not_abstract = not hasattr(simobj, 'abstract') or \
708                not simobj.abstract
709            if not_abstract and 'type' in simobj.__dict__:
710                code('cxx_config_directory["${name}"] = '
711                     '${name}CxxConfigParams::makeDirectoryEntry();')
712        code.dedent()
713        code('}')
714        code.write(target[0].abspath)
715
716    py_source = PySource.modules[simobj.__module__]
717    extra_deps = [ py_source.tnode ]
718    env.Command(cxx_config_init_cc_file, Value(name),
719        MakeAction(createCxxConfigInitCC, Transform("CXXCINIT")))
720    cxx_param_hh_files = ["cxx_config/%s.hh" % simobj
721        for name,simobj in sorted(sim_objects.iteritems())
722        if not hasattr(simobj, 'abstract') or not simobj.abstract]
723    Depends(cxx_config_init_cc_file, cxx_param_hh_files +
724            [File('sim/cxx_config.hh')])
725    Source(cxx_config_init_cc_file)
726
727# Generate any needed param SWIG wrapper files
728params_i_files = []
729for name,param in sorted(params_to_swig.iteritems()):
730    i_file = File('python/m5/internal/%s.i' % (param.swig_module_name()))
731    params_i_files.append(i_file)
732    env.Command(i_file, Value(name),
733                MakeAction(createParamSwigWrapper, Transform("SW PARAM")))
734    env.Depends(i_file, depends)
735    env.Depends(SWIG, i_file)
736    SwigSource('m5.internal', i_file)
737
738# Generate all enum header files
739for name,enum in sorted(all_enums.iteritems()):
740    py_source = PySource.modules[enum.__module__]
741    extra_deps = [ py_source.tnode ]
742
743    cc_file = File('enums/%s.cc' % name)
744    env.Command(cc_file, Value(name),
745                MakeAction(createEnumStrings, Transform("ENUM STR")))
746    env.Depends(cc_file, depends + extra_deps)
747    env.Depends(SWIG, cc_file)
748    Source(cc_file)
749
750    hh_file = File('enums/%s.hh' % name)
751    env.Command(hh_file, Value(name),
752                MakeAction(createEnumDecls, Transform("ENUMDECL")))
753    env.Depends(hh_file, depends + extra_deps)
754    env.Depends(SWIG, hh_file)
755
756    i_file = File('python/m5/internal/enum_%s.i' % name)
757    env.Command(i_file, Value(name),
758                MakeAction(createEnumSwigWrapper, Transform("ENUMSWIG")))
759    env.Depends(i_file, depends + extra_deps)
760    env.Depends(SWIG, i_file)
761    SwigSource('m5.internal', i_file)
762
763# Generate SimObject SWIG wrapper files
764for name,simobj in sorted(sim_objects.iteritems()):
765    py_source = PySource.modules[simobj.__module__]
766    extra_deps = [ py_source.tnode ]
767    i_file = File('python/m5/internal/param_%s.i' % name)
768    env.Command(i_file, Value(name),
769                MakeAction(createSimObjectSwigWrapper, Transform("SO SWIG")))
770    env.Depends(i_file, depends + extra_deps)
771    SwigSource('m5.internal', i_file)
772
773# Generate the main swig init file
774def makeEmbeddedSwigInit(target, source, env):
775    code = code_formatter()
776    module = source[0].get_contents()
777    code('''\
778#include "sim/init.hh"
779
780extern "C" {
781    void init_${module}();
782}
783
784EmbeddedSwig embed_swig_${module}(init_${module});
785''')
786    code.write(str(target[0]))
787    
788# Build all swig modules
789for swig in SwigSource.all:
790    env.Command([swig.cc_source.tnode, swig.py_source.tnode], swig.tnode,
791                MakeAction('$SWIG $SWIGFLAGS -outdir ${TARGETS[1].dir} '
792                '-o ${TARGETS[0]} $SOURCES', Transform("SWIG")))
793    cc_file = str(swig.tnode)
794    init_file = '%s/%s_init.cc' % (dirname(cc_file), basename(cc_file))
795    env.Command(init_file, Value(swig.module),
796                MakeAction(makeEmbeddedSwigInit, Transform("EMBED SW")))
797    env.Depends(SWIG, init_file)
798    Source(init_file, **swig.guards)
799
800# Build all protocol buffers if we have got protoc and protobuf available
801if env['HAVE_PROTOBUF']:
802    for proto in ProtoBuf.all:
803        # Use both the source and header as the target, and the .proto
804        # file as the source. When executing the protoc compiler, also
805        # specify the proto_path to avoid having the generated files
806        # include the path.
807        env.Command([proto.cc_file, proto.hh_file], proto.tnode,
808                    MakeAction('$PROTOC --cpp_out ${TARGET.dir} '
809                               '--proto_path ${SOURCE.dir} $SOURCE',
810                               Transform("PROTOC")))
811
812        env.Depends(SWIG, [proto.cc_file, proto.hh_file])
813        # Add the C++ source file
814        Source(proto.cc_file, **proto.guards)
815elif ProtoBuf.all:
816    print 'Got protobuf to build, but lacks support!'
817    Exit(1)
818
819#
820# Handle debug flags
821#
822def makeDebugFlagCC(target, source, env):
823    assert(len(target) == 1 and len(source) == 1)
824
825    code = code_formatter()
826
827    # delay definition of CompoundFlags until after all the definition
828    # of all constituent SimpleFlags
829    comp_code = code_formatter()
830
831    # file header
832    code('''
833/*
834 * DO NOT EDIT THIS FILE! Automatically generated by SCons.
835 */
836
837#include "base/debug.hh"
838
839namespace Debug {
840
841''')
842
843    for name, flag in sorted(source[0].read().iteritems()):
844        n, compound, desc = flag
845        assert n == name
846
847        if not compound:
848            code('SimpleFlag $name("$name", "$desc");')
849        else:
850            comp_code('CompoundFlag $name("$name", "$desc",')
851            comp_code.indent()
852            last = len(compound) - 1
853            for i,flag in enumerate(compound):
854                if i != last:
855                    comp_code('&$flag,')
856                else:
857                    comp_code('&$flag);')
858            comp_code.dedent()
859
860    code.append(comp_code)
861    code()
862    code('} // namespace Debug')
863
864    code.write(str(target[0]))
865
866def makeDebugFlagHH(target, source, env):
867    assert(len(target) == 1 and len(source) == 1)
868
869    val = eval(source[0].get_contents())
870    name, compound, desc = val
871
872    code = code_formatter()
873
874    # file header boilerplate
875    code('''\
876/*
877 * DO NOT EDIT THIS FILE! Automatically generated by SCons.
878 */
879
880#ifndef __DEBUG_${name}_HH__
881#define __DEBUG_${name}_HH__
882
883namespace Debug {
884''')
885
886    if compound:
887        code('class CompoundFlag;')
888    code('class SimpleFlag;')
889
890    if compound:
891        code('extern CompoundFlag $name;')
892        for flag in compound:
893            code('extern SimpleFlag $flag;')
894    else:
895        code('extern SimpleFlag $name;')
896
897    code('''
898}
899
900#endif // __DEBUG_${name}_HH__
901''')
902
903    code.write(str(target[0]))
904
905for name,flag in sorted(debug_flags.iteritems()):
906    n, compound, desc = flag
907    assert n == name
908
909    hh_file = 'debug/%s.hh' % name
910    env.Command(hh_file, Value(flag),
911                MakeAction(makeDebugFlagHH, Transform("TRACING", 0)))
912    env.Depends(SWIG, hh_file)
913
914env.Command('debug/flags.cc', Value(debug_flags),
915            MakeAction(makeDebugFlagCC, Transform("TRACING", 0)))
916env.Depends(SWIG, 'debug/flags.cc')
917Source('debug/flags.cc')
918
919# version tags
920env.Command('sim/tags.cc', None,
921            MakeAction('util/cpt_upgrader.py --get-cc-file > $TARGET',
922                       Transform("VER TAGS")))
923
924# Embed python files.  All .py files that have been indicated by a
925# PySource() call in a SConscript need to be embedded into the M5
926# library.  To do that, we compile the file to byte code, marshal the
927# byte code, compress it, and then generate a c++ file that
928# inserts the result into an array.
929def embedPyFile(target, source, env):
930    def c_str(string):
931        if string is None:
932            return "0"
933        return '"%s"' % string
934
935    '''Action function to compile a .py into a code object, marshal
936    it, compress it, and stick it into an asm file so the code appears
937    as just bytes with a label in the data section'''
938
939    src = file(str(source[0]), 'r').read()
940
941    pysource = PySource.tnodes[source[0]]
942    compiled = compile(src, pysource.abspath, 'exec')
943    marshalled = marshal.dumps(compiled)
944    compressed = zlib.compress(marshalled)
945    data = compressed
946    sym = pysource.symname
947
948    code = code_formatter()
949    code('''\
950#include "sim/init.hh"
951
952namespace {
953
954const uint8_t data_${sym}[] = {
955''')
956    code.indent()
957    step = 16
958    for i in xrange(0, len(data), step):
959        x = array.array('B', data[i:i+step])
960        code(''.join('%d,' % d for d in x))
961    code.dedent()
962    
963    code('''};
964
965EmbeddedPython embedded_${sym}(
966    ${{c_str(pysource.arcname)}},
967    ${{c_str(pysource.abspath)}},
968    ${{c_str(pysource.modpath)}},
969    data_${sym},
970    ${{len(data)}},
971    ${{len(marshalled)}});
972
973} // anonymous namespace
974''')
975    code.write(str(target[0]))
976
977for source in PySource.all:
978    env.Command(source.cpp, source.tnode,
979                MakeAction(embedPyFile, Transform("EMBED PY")))
980    env.Depends(SWIG, source.cpp)
981    Source(source.cpp, skip_no_python=True)
982
983########################################################################
984#
985# Define binaries.  Each different build type (debug, opt, etc.) gets
986# a slightly different build environment.
987#
988
989# List of constructed environments to pass back to SConstruct
990date_source = Source('base/date.cc', skip_lib=True)
991
992# Capture this directory for the closure makeEnv, otherwise when it is
993# called, it won't know what directory it should use.
994variant_dir = Dir('.').path
995def variant(*path):
996    return os.path.join(variant_dir, *path)
997def variantd(*path):
998    return variant(*path)+'/'
999
1000# Function to create a new build environment as clone of current
1001# environment 'env' with modified object suffix and optional stripped
1002# binary.  Additional keyword arguments are appended to corresponding
1003# build environment vars.
1004def makeEnv(env, label, objsfx, strip = False, **kwargs):
1005    # SCons doesn't know to append a library suffix when there is a '.' in the
1006    # name.  Use '_' instead.
1007    libname = variant('gem5_' + label)
1008    exename = variant('gem5.' + label)
1009    secondary_exename = variant('m5.' + label)
1010
1011    new_env = env.Clone(OBJSUFFIX=objsfx, SHOBJSUFFIX=objsfx + 's')
1012    new_env.Label = label
1013    new_env.Append(**kwargs)
1014
1015    swig_env = new_env.Clone()
1016
1017    # Both gcc and clang have issues with unused labels and values in
1018    # the SWIG generated code
1019    swig_env.Append(CCFLAGS=['-Wno-unused-label', '-Wno-unused-value'])
1020
1021    if env['GCC']:
1022        # Depending on the SWIG version, we also need to supress
1023        # warnings about uninitialized variables and missing field
1024        # initializers.
1025        swig_env.Append(CCFLAGS=['-Wno-uninitialized',
1026                                 '-Wno-missing-field-initializers',
1027                                 '-Wno-unused-but-set-variable',
1028                                 '-Wno-maybe-uninitialized',
1029                                 '-Wno-type-limits'])
1030
1031        # Only gcc >= 4.9 supports UBSan, so check both the version
1032        # and the command-line option before adding the compiler and
1033        # linker flags.
1034        if GetOption('with_ubsan') and \
1035                compareVersions(env['GCC_VERSION'], '4.9') >= 0:
1036            new_env.Append(CCFLAGS='-fsanitize=undefined')
1037            new_env.Append(LINKFLAGS='-fsanitize=undefined')
1038
1039    if env['CLANG']:
1040        swig_env.Append(CCFLAGS=['-Wno-sometimes-uninitialized',
1041                                 '-Wno-deprecated-register',
1042                                 '-Wno-tautological-compare'])
1043
1044        # All supported clang versions have support for UBSan, so if
1045        # asked to use it, append the compiler and linker flags.
1046        if GetOption('with_ubsan'):
1047            new_env.Append(CCFLAGS='-fsanitize=undefined')
1048            new_env.Append(LINKFLAGS='-fsanitize=undefined')
1049
1050    werror_env = new_env.Clone()
1051    # Treat warnings as errors but white list some warnings that we
1052    # want to allow (e.g., deprecation warnings).
1053    werror_env.Append(CCFLAGS=['-Werror',
1054                               '-Wno-error=deprecated-declarations',
1055                               '-Wno-error=deprecated',
1056                               ])
1057
1058    def make_obj(source, static, extra_deps = None):
1059        '''This function adds the specified source to the correct
1060        build environment, and returns the corresponding SCons Object
1061        nodes'''
1062
1063        if source.swig:
1064            env = swig_env
1065        elif source.Werror:
1066            env = werror_env
1067        else:
1068            env = new_env
1069
1070        if static:
1071            obj = env.StaticObject(source.tnode)
1072        else:
1073            obj = env.SharedObject(source.tnode)
1074
1075        if extra_deps:
1076            env.Depends(obj, extra_deps)
1077
1078        return obj
1079
1080    lib_guards = {'main': False, 'skip_lib': False}
1081
1082    # Without Python, leave out all SWIG and Python content from the
1083    # library builds.  The option doesn't affect gem5 built as a program
1084    if GetOption('without_python'):
1085        lib_guards['skip_no_python'] = False
1086
1087    static_objs = [ make_obj(s, True) for s in Source.get(**lib_guards) ]
1088    shared_objs = [ make_obj(s, False) for s in Source.get(**lib_guards) ]
1089
1090    static_date = make_obj(date_source, static=True, extra_deps=static_objs)
1091    static_objs.append(static_date)
1092
1093    shared_date = make_obj(date_source, static=False, extra_deps=shared_objs)
1094    shared_objs.append(shared_date)
1095
1096    # First make a library of everything but main() so other programs can
1097    # link against m5.
1098    static_lib = new_env.StaticLibrary(libname, static_objs)
1099    shared_lib = new_env.SharedLibrary(libname, shared_objs)
1100
1101    # Now link a stub with main() and the static library.
1102    main_objs = [ make_obj(s, True) for s in Source.get(main=True) ]
1103
1104    for test in UnitTest.all:
1105        flags = { test.target : True }
1106        test_sources = Source.get(**flags)
1107        test_objs = [ make_obj(s, static=True) for s in test_sources ]
1108        if test.main:
1109            test_objs += main_objs
1110        path = variant('unittest/%s.%s' % (test.target, label))
1111        new_env.Program(path, test_objs + static_objs)
1112
1113    progname = exename
1114    if strip:
1115        progname += '.unstripped'
1116
1117    targets = new_env.Program(progname, main_objs + static_objs)
1118
1119    if strip:
1120        if sys.platform == 'sunos5':
1121            cmd = 'cp $SOURCE $TARGET; strip $TARGET'
1122        else:
1123            cmd = 'strip $SOURCE -o $TARGET'
1124        targets = new_env.Command(exename, progname,
1125                    MakeAction(cmd, Transform("STRIP")))
1126
1127    new_env.Command(secondary_exename, exename,
1128            MakeAction('ln $SOURCE $TARGET', Transform("HARDLINK")))
1129
1130    new_env.M5Binary = targets[0]
1131    return new_env
1132
1133# Start out with the compiler flags common to all compilers,
1134# i.e. they all use -g for opt and -g -pg for prof
1135ccflags = {'debug' : [], 'opt' : ['-g'], 'fast' : [], 'prof' : ['-g', '-pg'],
1136           'perf' : ['-g']}
1137
1138# Start out with the linker flags common to all linkers, i.e. -pg for
1139# prof, and -lprofiler for perf. The -lprofile flag is surrounded by
1140# no-as-needed and as-needed as the binutils linker is too clever and
1141# simply doesn't link to the library otherwise.
1142ldflags = {'debug' : [], 'opt' : [], 'fast' : [], 'prof' : ['-pg'],
1143           'perf' : ['-Wl,--no-as-needed', '-lprofiler', '-Wl,--as-needed']}
1144
1145# For Link Time Optimization, the optimisation flags used to compile
1146# individual files are decoupled from those used at link time
1147# (i.e. you can compile with -O3 and perform LTO with -O0), so we need
1148# to also update the linker flags based on the target.
1149if env['GCC']:
1150    if sys.platform == 'sunos5':
1151        ccflags['debug'] += ['-gstabs+']
1152    else:
1153        ccflags['debug'] += ['-ggdb3']
1154    ldflags['debug'] += ['-O0']
1155    # opt, fast, prof and perf all share the same cc flags, also add
1156    # the optimization to the ldflags as LTO defers the optimization
1157    # to link time
1158    for target in ['opt', 'fast', 'prof', 'perf']:
1159        ccflags[target] += ['-O3']
1160        ldflags[target] += ['-O3']
1161
1162    ccflags['fast'] += env['LTO_CCFLAGS']
1163    ldflags['fast'] += env['LTO_LDFLAGS']
1164elif env['CLANG']:
1165    ccflags['debug'] += ['-g', '-O0']
1166    # opt, fast, prof and perf all share the same cc flags
1167    for target in ['opt', 'fast', 'prof', 'perf']:
1168        ccflags[target] += ['-O3']
1169else:
1170    print 'Unknown compiler, please fix compiler options'
1171    Exit(1)
1172
1173
1174# To speed things up, we only instantiate the build environments we
1175# need.  We try to identify the needed environment for each target; if
1176# we can't, we fall back on instantiating all the environments just to
1177# be safe.
1178target_types = ['debug', 'opt', 'fast', 'prof', 'perf']
1179obj2target = {'do': 'debug', 'o': 'opt', 'fo': 'fast', 'po': 'prof',
1180              'gpo' : 'perf'}
1181
1182def identifyTarget(t):
1183    ext = t.split('.')[-1]
1184    if ext in target_types:
1185        return ext
1186    if obj2target.has_key(ext):
1187        return obj2target[ext]
1188    match = re.search(r'/tests/([^/]+)/', t)
1189    if match and match.group(1) in target_types:
1190        return match.group(1)
1191    return 'all'
1192
1193needed_envs = [identifyTarget(target) for target in BUILD_TARGETS]
1194if 'all' in needed_envs:
1195    needed_envs += target_types
1196
1197gem5_root = Dir('.').up().up().abspath
1198def makeEnvirons(target, source, env):
1199    # cause any later Source() calls to be fatal, as a diagnostic.
1200    Source.done()
1201
1202    envList = []
1203
1204    # Debug binary
1205    if 'debug' in needed_envs:
1206        envList.append(
1207            makeEnv(env, 'debug', '.do',
1208                    CCFLAGS = Split(ccflags['debug']),
1209                    CPPDEFINES = ['DEBUG', 'TRACING_ON=1'],
1210                    LINKFLAGS = Split(ldflags['debug'])))
1211
1212    # Optimized binary
1213    if 'opt' in needed_envs:
1214        envList.append(
1215            makeEnv(env, 'opt', '.o',
1216                    CCFLAGS = Split(ccflags['opt']),
1217                    CPPDEFINES = ['TRACING_ON=1'],
1218                    LINKFLAGS = Split(ldflags['opt'])))
1219
1220    # "Fast" binary
1221    if 'fast' in needed_envs:
1222        envList.append(
1223            makeEnv(env, 'fast', '.fo', strip = True,
1224                    CCFLAGS = Split(ccflags['fast']),
1225                    CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1226                    LINKFLAGS = Split(ldflags['fast'])))
1227
1228    # Profiled binary using gprof
1229    if 'prof' in needed_envs:
1230        envList.append(
1231            makeEnv(env, 'prof', '.po',
1232                    CCFLAGS = Split(ccflags['prof']),
1233                    CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1234                    LINKFLAGS = Split(ldflags['prof'])))
1235
1236    # Profiled binary using google-pprof
1237    if 'perf' in needed_envs:
1238        envList.append(
1239            makeEnv(env, 'perf', '.gpo',
1240                    CCFLAGS = Split(ccflags['perf']),
1241                    CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1242                    LINKFLAGS = Split(ldflags['perf'])))
1243
1244    # Set up the regression tests for each build.
1245    for e in envList:
1246        SConscript(os.path.join(gem5_root, 'tests', 'SConscript'),
1247                   variant_dir = variantd('tests', e.Label),
1248                   exports = { 'env' : e }, duplicate = False)
1249
1250# The MakeEnvirons Builder defers the full dependency collection until
1251# after processing the ISA definition (due to dynamically generated
1252# source files).  Add this dependency to all targets so they will wait
1253# until the environments are completely set up.  Otherwise, a second
1254# process (e.g. -j2 or higher) will try to compile the requested target,
1255# not know how, and fail.
1256env.Append(BUILDERS = {'MakeEnvirons' :
1257                        Builder(action=MakeAction(makeEnvirons,
1258                                                  Transform("ENVIRONS", 1)))})
1259
1260isa_target = env['PHONY_BASE'] + '-deps'
1261environs   = env['PHONY_BASE'] + '-environs'
1262env.Depends('#all-deps',     isa_target)
1263env.Depends('#all-environs', environs)
1264env.ScanISA(isa_target, File('arch/%s/generated/inc.d' % env['TARGET_ISA']))
1265envSetup = env.MakeEnvirons(environs, isa_target)
1266
1267# make sure no -deps targets occur before all ISAs are complete
1268env.Depends(isa_target, '#all-isas')
1269# likewise for -environs targets and all the -deps targets
1270env.Depends(environs, '#all-deps')
1271