SConscript revision 8881:042d509574c1
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#     <unittest> -- unit tests use filters based on the unit test name
67955SN/A#
68955SN/A# A parent can now be specified for a source file and default filter
693918Ssaidi@eecs.umich.edu# values will be retrieved recursively from parents (children override
703716Sstever@eecs.umich.edu# parents).
71955SN/A#
722656Sstever@eecs.umich.educlass SourceMeta(type):
732656Sstever@eecs.umich.edu    '''Meta class for source files that keeps track of all files of a
742656Sstever@eecs.umich.edu    particular type and has a get function for finding all functions
752656Sstever@eecs.umich.edu    of a certain type that match a set of guards'''
762656Sstever@eecs.umich.edu    def __init__(cls, name, bases, dict):
772656Sstever@eecs.umich.edu        super(SourceMeta, cls).__init__(name, bases, dict)
782656Sstever@eecs.umich.edu        cls.all = []
792653Sstever@eecs.umich.edu        
802653Sstever@eecs.umich.edu    def get(cls, **guards):
812653Sstever@eecs.umich.edu        '''Find all files that match the specified guards.  If a source
822653Sstever@eecs.umich.edu        file does not specify a flag, the default is False'''
832653Sstever@eecs.umich.edu        for src in cls.all:
842653Sstever@eecs.umich.edu            for flag,value in guards.iteritems():
852653Sstever@eecs.umich.edu                # if the flag is found and has a different value, skip
862653Sstever@eecs.umich.edu                # this file
872653Sstever@eecs.umich.edu                if src.all_guards.get(flag, False) != value:
882653Sstever@eecs.umich.edu                    break
892653Sstever@eecs.umich.edu            else:
901852SN/A                yield src
91955SN/A
92955SN/Aclass SourceFile(object):
93955SN/A    '''Base object that encapsulates the notion of a source file.
943717Sstever@eecs.umich.edu    This includes, the source node, target node, various manipulations
953716Sstever@eecs.umich.edu    of those.  A source file also specifies a set of guards which
96955SN/A    describing which builds the source file applies to.  A parent can
971533SN/A    also be specified to get default guards from'''
983716Sstever@eecs.umich.edu    __metaclass__ = SourceMeta
991533SN/A    def __init__(self, source, parent=None, **guards):
100955SN/A        self.guards = guards
101955SN/A        self.parent = parent
1022632Sstever@eecs.umich.edu
1032632Sstever@eecs.umich.edu        tnode = source
104955SN/A        if not isinstance(source, SCons.Node.FS.File):
105955SN/A            tnode = File(source)
106955SN/A
107955SN/A        self.tnode = tnode
1082632Sstever@eecs.umich.edu        self.snode = tnode.srcnode()
109955SN/A
1102632Sstever@eecs.umich.edu        for base in type(self).__mro__:
1112632Sstever@eecs.umich.edu            if issubclass(base, SourceFile):
1122632Sstever@eecs.umich.edu                base.all.append(self)
1132632Sstever@eecs.umich.edu
1142632Sstever@eecs.umich.edu    @property
1152632Sstever@eecs.umich.edu    def filename(self):
1162632Sstever@eecs.umich.edu        return str(self.tnode)
1173053Sstever@eecs.umich.edu
1183053Sstever@eecs.umich.edu    @property
1193053Sstever@eecs.umich.edu    def dirname(self):
1203053Sstever@eecs.umich.edu        return dirname(self.filename)
1213053Sstever@eecs.umich.edu
1223053Sstever@eecs.umich.edu    @property
1233053Sstever@eecs.umich.edu    def basename(self):
1243053Sstever@eecs.umich.edu        return basename(self.filename)
1253053Sstever@eecs.umich.edu
1263053Sstever@eecs.umich.edu    @property
1273053Sstever@eecs.umich.edu    def extname(self):
1283053Sstever@eecs.umich.edu        index = self.basename.rfind('.')
1293053Sstever@eecs.umich.edu        if index <= 0:
1303053Sstever@eecs.umich.edu            # dot files aren't extensions
1313053Sstever@eecs.umich.edu            return self.basename, None
1323053Sstever@eecs.umich.edu
1332632Sstever@eecs.umich.edu        return self.basename[:index], self.basename[index+1:]
1342632Sstever@eecs.umich.edu
1352632Sstever@eecs.umich.edu    @property
1362632Sstever@eecs.umich.edu    def all_guards(self):
1372632Sstever@eecs.umich.edu        '''find all guards for this object getting default values
1382632Sstever@eecs.umich.edu        recursively from its parents'''
1393718Sstever@eecs.umich.edu        guards = {}
1403718Sstever@eecs.umich.edu        if self.parent:
1413718Sstever@eecs.umich.edu            guards.update(self.parent.guards)
1423718Sstever@eecs.umich.edu        guards.update(self.guards)
1433718Sstever@eecs.umich.edu        return guards
1443718Sstever@eecs.umich.edu
1453718Sstever@eecs.umich.edu    def __lt__(self, other): return self.filename < other.filename
1463718Sstever@eecs.umich.edu    def __le__(self, other): return self.filename <= other.filename
1473718Sstever@eecs.umich.edu    def __gt__(self, other): return self.filename > other.filename
1483718Sstever@eecs.umich.edu    def __ge__(self, other): return self.filename >= other.filename
1493718Sstever@eecs.umich.edu    def __eq__(self, other): return self.filename == other.filename
1503718Sstever@eecs.umich.edu    def __ne__(self, other): return self.filename != other.filename
1513718Sstever@eecs.umich.edu        
1522634Sstever@eecs.umich.educlass Source(SourceFile):
1532634Sstever@eecs.umich.edu    '''Add a c/c++ source file to the build'''
1542632Sstever@eecs.umich.edu    def __init__(self, source, Werror=True, swig=False, **guards):
1552638Sstever@eecs.umich.edu        '''specify the source file, and any guards'''
1562632Sstever@eecs.umich.edu        super(Source, self).__init__(source, **guards)
1572632Sstever@eecs.umich.edu
1582632Sstever@eecs.umich.edu        self.Werror = Werror
1592632Sstever@eecs.umich.edu        self.swig = swig
1602632Sstever@eecs.umich.edu
1612632Sstever@eecs.umich.educlass PySource(SourceFile):
1621858SN/A    '''Add a python source file to the named package'''
1633716Sstever@eecs.umich.edu    invalid_sym_char = re.compile('[^A-z0-9_]')
1642638Sstever@eecs.umich.edu    modules = {}
1652638Sstever@eecs.umich.edu    tnodes = {}
1662638Sstever@eecs.umich.edu    symnames = {}
1672638Sstever@eecs.umich.edu    
1682638Sstever@eecs.umich.edu    def __init__(self, package, source, **guards):
1692638Sstever@eecs.umich.edu        '''specify the python package, the source file, and any guards'''
1702638Sstever@eecs.umich.edu        super(PySource, self).__init__(source, **guards)
1713716Sstever@eecs.umich.edu
1722634Sstever@eecs.umich.edu        modname,ext = self.extname
1732634Sstever@eecs.umich.edu        assert ext == 'py'
174955SN/A
175955SN/A        if package:
176955SN/A            path = package.split('.')
177955SN/A        else:
178955SN/A            path = []
179955SN/A
180955SN/A        modpath = path[:]
181955SN/A        if modname != '__init__':
1821858SN/A            modpath += [ modname ]
1831858SN/A        modpath = '.'.join(modpath)
1842632Sstever@eecs.umich.edu
185955SN/A        arcpath = path + [ self.basename ]
1863643Ssaidi@eecs.umich.edu        abspath = self.snode.abspath
1873643Ssaidi@eecs.umich.edu        if not exists(abspath):
1883643Ssaidi@eecs.umich.edu            abspath = self.tnode.abspath
1893643Ssaidi@eecs.umich.edu
1903643Ssaidi@eecs.umich.edu        self.package = package
1913643Ssaidi@eecs.umich.edu        self.modname = modname
1923643Ssaidi@eecs.umich.edu        self.modpath = modpath
1933643Ssaidi@eecs.umich.edu        self.arcname = joinpath(*arcpath)
1943716Sstever@eecs.umich.edu        self.abspath = abspath
1951105SN/A        self.compiled = File(self.filename + 'c')
1962667Sstever@eecs.umich.edu        self.cpp = File(self.filename + '.cc')
1972667Sstever@eecs.umich.edu        self.symname = PySource.invalid_sym_char.sub('_', modpath)
1982667Sstever@eecs.umich.edu
1992667Sstever@eecs.umich.edu        PySource.modules[modpath] = self
2002667Sstever@eecs.umich.edu        PySource.tnodes[self.tnode] = self
2012667Sstever@eecs.umich.edu        PySource.symnames[self.symname] = self
2021869SN/A
2031869SN/Aclass SimObject(PySource):
2041869SN/A    '''Add a SimObject python file as a python source object and add
2051869SN/A    it to a list of sim object modules'''
2061869SN/A
2071065SN/A    fixed = False
2082632Sstever@eecs.umich.edu    modnames = []
2092632Sstever@eecs.umich.edu
2103918Ssaidi@eecs.umich.edu    def __init__(self, source, **guards):
2113918Ssaidi@eecs.umich.edu        '''Specify the source file and any guards (automatically in
2123940Ssaidi@eecs.umich.edu        the m5.objects package)'''
2133918Ssaidi@eecs.umich.edu        super(SimObject, self).__init__('m5.objects', source, **guards)
2143918Ssaidi@eecs.umich.edu        if self.fixed:
2153918Ssaidi@eecs.umich.edu            raise AttributeError, "Too late to call SimObject now."
2163918Ssaidi@eecs.umich.edu
2173918Ssaidi@eecs.umich.edu        bisect.insort_right(SimObject.modnames, self.modname)
2183918Ssaidi@eecs.umich.edu
2193940Ssaidi@eecs.umich.educlass SwigSource(SourceFile):
2203940Ssaidi@eecs.umich.edu    '''Add a swig file to build'''
2213940Ssaidi@eecs.umich.edu
2223942Ssaidi@eecs.umich.edu    def __init__(self, package, source, **guards):
2233940Ssaidi@eecs.umich.edu        '''Specify the python package, the source file, and any guards'''
2243918Ssaidi@eecs.umich.edu        super(SwigSource, self).__init__(source, **guards)
2253918Ssaidi@eecs.umich.edu
226955SN/A        modname,ext = self.extname
2271858SN/A        assert ext == 'i'
2283918Ssaidi@eecs.umich.edu
2293918Ssaidi@eecs.umich.edu        self.module = modname
2303918Ssaidi@eecs.umich.edu        cc_file = joinpath(self.dirname, modname + '_wrap.cc')
2313918Ssaidi@eecs.umich.edu        py_file = joinpath(self.dirname, modname + '.py')
2323940Ssaidi@eecs.umich.edu
2333940Ssaidi@eecs.umich.edu        self.cc_source = Source(cc_file, swig=True, parent=self)
2343918Ssaidi@eecs.umich.edu        self.py_source = PySource(package, py_file, parent=self)
2353918Ssaidi@eecs.umich.edu
2363918Ssaidi@eecs.umich.educlass UnitTest(object):
2373918Ssaidi@eecs.umich.edu    '''Create a UnitTest'''
2383918Ssaidi@eecs.umich.edu
2393918Ssaidi@eecs.umich.edu    all = []
2403918Ssaidi@eecs.umich.edu    def __init__(self, target, *sources):
2413918Ssaidi@eecs.umich.edu        '''Specify the target name and any sources.  Sources that are
2423918Ssaidi@eecs.umich.edu        not SourceFiles are evalued with Source().  All files are
2433940Ssaidi@eecs.umich.edu        guarded with a guard of the same name as the UnitTest
2443918Ssaidi@eecs.umich.edu        target.'''
2453918Ssaidi@eecs.umich.edu
2461851SN/A        srcs = []
2471851SN/A        for src in sources:
2481858SN/A            if not isinstance(src, SourceFile):
2492632Sstever@eecs.umich.edu                src = Source(src, skip_lib=True)
250955SN/A            src.guards[target] = True
2513053Sstever@eecs.umich.edu            srcs.append(src)
2523053Sstever@eecs.umich.edu
2533053Sstever@eecs.umich.edu        self.sources = srcs
2543053Sstever@eecs.umich.edu        self.target = target
2553053Sstever@eecs.umich.edu        UnitTest.all.append(self)
2563053Sstever@eecs.umich.edu
2573053Sstever@eecs.umich.edu# Children should have access
2583053Sstever@eecs.umich.eduExport('Source')
2593053Sstever@eecs.umich.eduExport('PySource')
2603053Sstever@eecs.umich.eduExport('SimObject')
2613053Sstever@eecs.umich.eduExport('SwigSource')
2623053Sstever@eecs.umich.eduExport('UnitTest')
2633053Sstever@eecs.umich.edu
2643053Sstever@eecs.umich.edu########################################################################
2653053Sstever@eecs.umich.edu#
2663053Sstever@eecs.umich.edu# Debug Flags
2673053Sstever@eecs.umich.edu#
2683053Sstever@eecs.umich.edudebug_flags = {}
2693053Sstever@eecs.umich.edudef DebugFlag(name, desc=None):
2702667Sstever@eecs.umich.edu    if name in debug_flags:
2712667Sstever@eecs.umich.edu        raise AttributeError, "Flag %s already specified" % name
2722667Sstever@eecs.umich.edu    debug_flags[name] = (name, (), desc)
2732667Sstever@eecs.umich.edu
2742667Sstever@eecs.umich.edudef CompoundFlag(name, flags, desc=None):
2752667Sstever@eecs.umich.edu    if name in debug_flags:
2762667Sstever@eecs.umich.edu        raise AttributeError, "Flag %s already specified" % name
2772667Sstever@eecs.umich.edu
2782667Sstever@eecs.umich.edu    compound = tuple(flags)
2792667Sstever@eecs.umich.edu    debug_flags[name] = (name, compound, desc)
2802667Sstever@eecs.umich.edu
2812667Sstever@eecs.umich.eduExport('DebugFlag')
2822638Sstever@eecs.umich.eduExport('CompoundFlag')
2832638Sstever@eecs.umich.edu
2842638Sstever@eecs.umich.edu########################################################################
2853716Sstever@eecs.umich.edu#
2863716Sstever@eecs.umich.edu# Set some compiler variables
2871858SN/A#
2883118Sstever@eecs.umich.edu
2893118Sstever@eecs.umich.edu# Include file paths are rooted in this directory.  SCons will
2903118Sstever@eecs.umich.edu# automatically expand '.' to refer to both the source directory and
2913118Sstever@eecs.umich.edu# the corresponding build directory to pick up generated include
2923118Sstever@eecs.umich.edu# files.
2933118Sstever@eecs.umich.eduenv.Append(CPPPATH=Dir('.'))
2943118Sstever@eecs.umich.edu
2953118Sstever@eecs.umich.edufor extra_dir in extras_dir_list:
2963118Sstever@eecs.umich.edu    env.Append(CPPPATH=Dir(extra_dir))
2973118Sstever@eecs.umich.edu
2983118Sstever@eecs.umich.edu# Workaround for bug in SCons version > 0.97d20071212
2993716Sstever@eecs.umich.edu# Scons bug id: 2006 gem5 Bug id: 308
3003118Sstever@eecs.umich.edufor root, dirs, files in os.walk(base_dir, topdown=True):
3013118Sstever@eecs.umich.edu    Dir(root[len(base_dir) + 1:])
3023118Sstever@eecs.umich.edu
3033118Sstever@eecs.umich.edu########################################################################
3043118Sstever@eecs.umich.edu#
3053118Sstever@eecs.umich.edu# Walk the tree and execute all SConscripts in subdirectories
3063118Sstever@eecs.umich.edu#
3073118Sstever@eecs.umich.edu
3083118Sstever@eecs.umich.eduhere = Dir('.').srcnode().abspath
3093716Sstever@eecs.umich.edufor root, dirs, files in os.walk(base_dir, topdown=True):
3103118Sstever@eecs.umich.edu    if root == here:
3113118Sstever@eecs.umich.edu        # we don't want to recurse back into this SConscript
3123118Sstever@eecs.umich.edu        continue
3133118Sstever@eecs.umich.edu
3143118Sstever@eecs.umich.edu    if 'SConscript' in files:
3153118Sstever@eecs.umich.edu        build_dir = joinpath(env['BUILDDIR'], root[len(base_dir) + 1:])
3163118Sstever@eecs.umich.edu        SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3173118Sstever@eecs.umich.edu
3183118Sstever@eecs.umich.edufor extra_dir in extras_dir_list:
3193118Sstever@eecs.umich.edu    prefix_len = len(dirname(extra_dir)) + 1
3203483Ssaidi@eecs.umich.edu    for root, dirs, files in os.walk(extra_dir, topdown=True):
3213494Ssaidi@eecs.umich.edu        # if build lives in the extras directory, don't walk down it
3223494Ssaidi@eecs.umich.edu        if 'build' in dirs:
3233483Ssaidi@eecs.umich.edu            dirs.remove('build')
3243483Ssaidi@eecs.umich.edu
3253483Ssaidi@eecs.umich.edu        if 'SConscript' in files:
3263053Sstever@eecs.umich.edu            build_dir = joinpath(env['BUILDDIR'], root[prefix_len:])
3273053Sstever@eecs.umich.edu            SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3283918Ssaidi@eecs.umich.edu
3293053Sstever@eecs.umich.edufor opt in export_vars:
3303053Sstever@eecs.umich.edu    env.ConfigFile(opt)
3313053Sstever@eecs.umich.edu
3323053Sstever@eecs.umich.edudef makeTheISA(source, target, env):
3333053Sstever@eecs.umich.edu    isas = [ src.get_contents() for src in source ]
3341858SN/A    target_isa = env['TARGET_ISA']
3351858SN/A    def define(isa):
3361858SN/A        return isa.upper() + '_ISA'
3371858SN/A    
3381858SN/A    def namespace(isa):
3391858SN/A        return isa[0].upper() + isa[1:].lower() + 'ISA' 
3401859SN/A
3411858SN/A
3421858SN/A    code = code_formatter()
3431858SN/A    code('''\
3441859SN/A#ifndef __CONFIG_THE_ISA_HH__
3451859SN/A#define __CONFIG_THE_ISA_HH__
3461862SN/A
3473053Sstever@eecs.umich.edu''')
3483053Sstever@eecs.umich.edu
3493053Sstever@eecs.umich.edu    for i,isa in enumerate(isas):
3503053Sstever@eecs.umich.edu        code('#define $0 $1', define(isa), i + 1)
3511859SN/A
3521859SN/A    code('''
3531859SN/A
3541859SN/A#define THE_ISA ${{define(target_isa)}}
3551859SN/A#define TheISA ${{namespace(target_isa)}}
3561859SN/A
3571859SN/A#endif // __CONFIG_THE_ISA_HH__''')
3581859SN/A
3591862SN/A    code.write(str(target[0]))
3601859SN/A
3611859SN/Aenv.Command('config/the_isa.hh', map(Value, all_isa_list),
3621859SN/A            MakeAction(makeTheISA, Transform("CFG ISA", 0)))
3631858SN/A
3641858SN/A########################################################################
3652139SN/A#
3662139SN/A# Prevent any SimObjects from being added after this point, they
3672139SN/A# should all have been added in the SConscripts above
3682155SN/A#
3692623SN/ASimObject.fixed = True
3703583Sbinkertn@umich.edu
3713583Sbinkertn@umich.educlass DictImporter(object):
3723717Sstever@eecs.umich.edu    '''This importer takes a dictionary of arbitrary module names that
3733583Sbinkertn@umich.edu    map to arbitrary filenames.'''
3742155SN/A    def __init__(self, modules):
3751869SN/A        self.modules = modules
3761869SN/A        self.installed = set()
3771869SN/A
3781869SN/A    def __del__(self):
3791869SN/A        self.unload()
3802139SN/A
3811869SN/A    def unload(self):
3822508SN/A        import sys
3832508SN/A        for module in self.installed:
3842508SN/A            del sys.modules[module]
3852508SN/A        self.installed = set()
3863685Sktlim@umich.edu
3872635Sstever@eecs.umich.edu    def find_module(self, fullname, path):
3881869SN/A        if fullname == 'm5.defines':
3891869SN/A            return self
3901869SN/A
3911869SN/A        if fullname == 'm5.objects':
3921869SN/A            return self
3931869SN/A
3941869SN/A        if fullname.startswith('m5.internal'):
3951869SN/A            return None
3961965SN/A
3971965SN/A        source = self.modules.get(fullname, None)
3981965SN/A        if source is not None and fullname.startswith('m5.objects'):
3991869SN/A            return self
4001869SN/A
4012733Sktlim@umich.edu        return None
4021869SN/A
4031884SN/A    def load_module(self, fullname):
4041884SN/A        mod = imp.new_module(fullname)
4053356Sbinkertn@umich.edu        sys.modules[fullname] = mod
4063356Sbinkertn@umich.edu        self.installed.add(fullname)
4073356Sbinkertn@umich.edu
4083356Sbinkertn@umich.edu        mod.__loader__ = self
4091869SN/A        if fullname == 'm5.objects':
4101858SN/A            mod.__path__ = fullname.split('.')
4111869SN/A            return mod
4121869SN/A
4131869SN/A        if fullname == 'm5.defines':
4141869SN/A            mod.__dict__['buildEnv'] = m5.util.SmartDict(build_env)
4151869SN/A            return mod
4161858SN/A
4172761Sstever@eecs.umich.edu        source = self.modules[fullname]
4181869SN/A        if source.modname == '__init__':
4192733Sktlim@umich.edu            mod.__path__ = source.modpath
4203584Ssaidi@eecs.umich.edu        mod.__file__ = source.abspath
4211869SN/A
4221869SN/A        exec file(source.abspath, 'r') in mod.__dict__
4231869SN/A
4241869SN/A        return mod
4251869SN/A
4261869SN/Aimport m5.SimObject
4271858SN/Aimport m5.params
428955SN/Afrom m5.util import code_formatter
429955SN/A
4301869SN/Am5.SimObject.clear()
4311869SN/Am5.params.clear()
4321869SN/A
4331869SN/A# install the python importer so we can grab stuff from the source
4341869SN/A# tree itself.  We can't have SimObjects added after this point or
4351869SN/A# else we won't know about them for the rest of the stuff.
4361869SN/Aimporter = DictImporter(PySource.modules)
4371869SN/Asys.meta_path[0:0] = [ importer ]
4381869SN/A
4391869SN/A# import all sim objects so we can populate the all_objects list
4401869SN/A# make sure that we're working with a list, then let's sort it
4411869SN/Afor modname in SimObject.modnames:
4421869SN/A    exec('from m5.objects import %s' % modname)
4431869SN/A
4441869SN/A# we need to unload all of the currently imported modules so that they
4451869SN/A# will be re-imported the next time the sconscript is run
4461869SN/Aimporter.unload()
4471869SN/Asys.meta_path.remove(importer)
4481869SN/A
4491869SN/Asim_objects = m5.SimObject.allClasses
4501869SN/Aall_enums = m5.params.allEnums
4511869SN/A
4521869SN/A# Find param types that need to be explicitly wrapped with swig.
4531869SN/A# These will be recognized because the ParamDesc will have a
4541869SN/A# swig_decl() method.  Most param types are based on types that don't
4551869SN/A# need this, either because they're based on native types (like Int)
4561869SN/A# or because they're SimObjects (which get swigged independently).
4571869SN/A# For now the only things handled here are VectorParam types.
4581869SN/Aparams_to_swig = {}
4593716Sstever@eecs.umich.edufor name,obj in sorted(sim_objects.iteritems()):
4603356Sbinkertn@umich.edu    for param in obj._params.local.values():
4613356Sbinkertn@umich.edu        # load the ptype attribute now because it depends on the
4623356Sbinkertn@umich.edu        # current version of SimObject.allClasses, but when scons
4633356Sbinkertn@umich.edu        # actually uses the value, all versions of
4643356Sbinkertn@umich.edu        # SimObject.allClasses will have been loaded
4653356Sbinkertn@umich.edu        param.ptype
4663356Sbinkertn@umich.edu
4671869SN/A        if not hasattr(param, 'swig_decl'):
4681869SN/A            continue
4691869SN/A        pname = param.ptype_str
4701869SN/A        if pname not in params_to_swig:
4711869SN/A            params_to_swig[pname] = param
4721869SN/A
4731869SN/A########################################################################
4742655Sstever@eecs.umich.edu#
4752655Sstever@eecs.umich.edu# calculate extra dependencies
4762655Sstever@eecs.umich.edu#
4772655Sstever@eecs.umich.edumodule_depends = ["m5", "m5.SimObject", "m5.params"]
4782655Sstever@eecs.umich.edudepends = [ PySource.modules[dep].snode for dep in module_depends ]
4792655Sstever@eecs.umich.edu
4802655Sstever@eecs.umich.edu########################################################################
4812655Sstever@eecs.umich.edu#
4822655Sstever@eecs.umich.edu# Commands for the basic automatically generated python files
4832655Sstever@eecs.umich.edu#
4842655Sstever@eecs.umich.edu
4852655Sstever@eecs.umich.edu# Generate Python file containing a dict specifying the current
4862655Sstever@eecs.umich.edu# buildEnv flags.
4872655Sstever@eecs.umich.edudef makeDefinesPyFile(target, source, env):
4882655Sstever@eecs.umich.edu    build_env = source[0].get_contents()
4892655Sstever@eecs.umich.edu
4902655Sstever@eecs.umich.edu    code = code_formatter()
4912655Sstever@eecs.umich.edu    code("""
4922655Sstever@eecs.umich.eduimport m5.internal
4932655Sstever@eecs.umich.eduimport m5.util
4942655Sstever@eecs.umich.edu
4952655Sstever@eecs.umich.edubuildEnv = m5.util.SmartDict($build_env)
4962655Sstever@eecs.umich.edu
4972655Sstever@eecs.umich.educompileDate = m5.internal.core.compileDate
4982655Sstever@eecs.umich.edu_globals = globals()
4992655Sstever@eecs.umich.edufor key,val in m5.internal.core.__dict__.iteritems():
5002634Sstever@eecs.umich.edu    if key.startswith('flag_'):
5012634Sstever@eecs.umich.edu        flag = key[5:]
5022634Sstever@eecs.umich.edu        _globals[flag] = val
5032634Sstever@eecs.umich.edudel _globals
5042634Sstever@eecs.umich.edu""")
5052634Sstever@eecs.umich.edu    code.write(target[0].abspath)
5062638Sstever@eecs.umich.edu
5072638Sstever@eecs.umich.edudefines_info = Value(build_env)
5083716Sstever@eecs.umich.edu# Generate a file with all of the compile options in it
5092638Sstever@eecs.umich.eduenv.Command('python/m5/defines.py', defines_info,
5102638Sstever@eecs.umich.edu            MakeAction(makeDefinesPyFile, Transform("DEFINES", 0)))
5111869SN/APySource('m5', 'python/m5/defines.py')
5121869SN/A
5133546Sgblack@eecs.umich.edu# Generate python file containing info about the M5 source code
5143546Sgblack@eecs.umich.edudef makeInfoPyFile(target, source, env):
5153546Sgblack@eecs.umich.edu    code = code_formatter()
5163546Sgblack@eecs.umich.edu    for src in source:
5173546Sgblack@eecs.umich.edu        data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
5183546Sgblack@eecs.umich.edu        code('$src = ${{repr(data)}}')
5193546Sgblack@eecs.umich.edu    code.write(str(target[0]))
5203546Sgblack@eecs.umich.edu
5213546Sgblack@eecs.umich.edu# Generate a file that wraps the basic top level files
5223546Sgblack@eecs.umich.eduenv.Command('python/m5/info.py',
5233546Sgblack@eecs.umich.edu            [ '#/COPYING', '#/LICENSE', '#/README', ],
5243546Sgblack@eecs.umich.edu            MakeAction(makeInfoPyFile, Transform("INFO")))
5253546Sgblack@eecs.umich.eduPySource('m5', 'python/m5/info.py')
5263546Sgblack@eecs.umich.edu
5273546Sgblack@eecs.umich.edu########################################################################
5283546Sgblack@eecs.umich.edu#
5293546Sgblack@eecs.umich.edu# Create all of the SimObject param headers and enum headers
5303546Sgblack@eecs.umich.edu#
5313546Sgblack@eecs.umich.edu
5323546Sgblack@eecs.umich.edudef createSimObjectParamStruct(target, source, env):
5333546Sgblack@eecs.umich.edu    assert len(target) == 1 and len(source) == 1
5343546Sgblack@eecs.umich.edu
5353546Sgblack@eecs.umich.edu    name = str(source[0].get_contents())
5363546Sgblack@eecs.umich.edu    obj = sim_objects[name]
5373546Sgblack@eecs.umich.edu
5383546Sgblack@eecs.umich.edu    code = code_formatter()
5393546Sgblack@eecs.umich.edu    obj.cxx_param_decl(code)
5403546Sgblack@eecs.umich.edu    code.write(target[0].abspath)
5413546Sgblack@eecs.umich.edu
5423546Sgblack@eecs.umich.edudef createParamSwigWrapper(target, source, env):
5433546Sgblack@eecs.umich.edu    assert len(target) == 1 and len(source) == 1
5443546Sgblack@eecs.umich.edu
5453546Sgblack@eecs.umich.edu    name = str(source[0].get_contents())
5463546Sgblack@eecs.umich.edu    param = params_to_swig[name]
5473546Sgblack@eecs.umich.edu
5483546Sgblack@eecs.umich.edu    code = code_formatter()
5493546Sgblack@eecs.umich.edu    param.swig_decl(code)
5503546Sgblack@eecs.umich.edu    code.write(target[0].abspath)
5513546Sgblack@eecs.umich.edu
5523546Sgblack@eecs.umich.edudef createEnumStrings(target, source, env):
553955SN/A    assert len(target) == 1 and len(source) == 1
554955SN/A
555955SN/A    name = str(source[0].get_contents())
556955SN/A    obj = all_enums[name]
5571858SN/A
5581858SN/A    code = code_formatter()
5591858SN/A    obj.cxx_def(code)
5602632Sstever@eecs.umich.edu    code.write(target[0].abspath)
5612632Sstever@eecs.umich.edu
5622632Sstever@eecs.umich.edudef createEnumDecls(target, source, env):
5632632Sstever@eecs.umich.edu    assert len(target) == 1 and len(source) == 1
5642632Sstever@eecs.umich.edu
5652634Sstever@eecs.umich.edu    name = str(source[0].get_contents())
5662638Sstever@eecs.umich.edu    obj = all_enums[name]
5672023SN/A
5682632Sstever@eecs.umich.edu    code = code_formatter()
5692632Sstever@eecs.umich.edu    obj.cxx_decl(code)
5702632Sstever@eecs.umich.edu    code.write(target[0].abspath)
5712632Sstever@eecs.umich.edu
5722632Sstever@eecs.umich.edudef createEnumSwigWrapper(target, source, env):
5733716Sstever@eecs.umich.edu    assert len(target) == 1 and len(source) == 1
5742632Sstever@eecs.umich.edu
5752632Sstever@eecs.umich.edu    name = str(source[0].get_contents())
5762632Sstever@eecs.umich.edu    obj = all_enums[name]
5772632Sstever@eecs.umich.edu
5782632Sstever@eecs.umich.edu    code = code_formatter()
5792023SN/A    obj.swig_decl(code)
5802632Sstever@eecs.umich.edu    code.write(target[0].abspath)
5812632Sstever@eecs.umich.edu
5821889SN/Adef createSimObjectSwigWrapper(target, source, env):
5831889SN/A    name = source[0].get_contents()
5842632Sstever@eecs.umich.edu    obj = sim_objects[name]
5852632Sstever@eecs.umich.edu
5862632Sstever@eecs.umich.edu    code = code_formatter()
5872632Sstever@eecs.umich.edu    obj.swig_decl(code)
5883716Sstever@eecs.umich.edu    code.write(target[0].abspath)
5893716Sstever@eecs.umich.edu
5902632Sstever@eecs.umich.edu# Generate all of the SimObject param C++ struct header files
5912632Sstever@eecs.umich.eduparams_hh_files = []
5922632Sstever@eecs.umich.edufor name,simobj in sorted(sim_objects.iteritems()):
5932632Sstever@eecs.umich.edu    py_source = PySource.modules[simobj.__module__]
5942632Sstever@eecs.umich.edu    extra_deps = [ py_source.tnode ]
5952632Sstever@eecs.umich.edu
5962632Sstever@eecs.umich.edu    hh_file = File('params/%s.hh' % name)
5972632Sstever@eecs.umich.edu    params_hh_files.append(hh_file)
5981888SN/A    env.Command(hh_file, Value(name),
5991888SN/A                MakeAction(createSimObjectParamStruct, Transform("SO PARAM")))
6001869SN/A    env.Depends(hh_file, depends + extra_deps)
6011869SN/A
6021858SN/A# Generate any needed param SWIG wrapper files
6032598SN/Aparams_i_files = []
6042598SN/Afor name,param in params_to_swig.iteritems():
6052598SN/A    i_file = File('python/m5/internal/%s.i' % (param.swig_module_name()))
6062598SN/A    params_i_files.append(i_file)
6072598SN/A    env.Command(i_file, Value(name),
6081858SN/A                MakeAction(createParamSwigWrapper, Transform("SW PARAM")))
6091858SN/A    env.Depends(i_file, depends)
6101858SN/A    SwigSource('m5.internal', i_file)
6111858SN/A
6121858SN/A# Generate all enum header files
6131858SN/Afor name,enum in sorted(all_enums.iteritems()):
6141858SN/A    py_source = PySource.modules[enum.__module__]
6151858SN/A    extra_deps = [ py_source.tnode ]
6161858SN/A
6171871SN/A    cc_file = File('enums/%s.cc' % name)
6181858SN/A    env.Command(cc_file, Value(name),
6191858SN/A                MakeAction(createEnumStrings, Transform("ENUM STR")))
6201858SN/A    env.Depends(cc_file, depends + extra_deps)
6211858SN/A    Source(cc_file)
6221858SN/A
6231858SN/A    hh_file = File('enums/%s.hh' % name)
6241858SN/A    env.Command(hh_file, Value(name),
6251858SN/A                MakeAction(createEnumDecls, Transform("ENUMDECL")))
6261858SN/A    env.Depends(hh_file, depends + extra_deps)
6271858SN/A
6281858SN/A    i_file = File('python/m5/internal/enum_%s.i' % name)
6291859SN/A    env.Command(i_file, Value(name),
6301859SN/A                MakeAction(createEnumSwigWrapper, Transform("ENUMSWIG")))
6311869SN/A    env.Depends(i_file, depends + extra_deps)
6321888SN/A    SwigSource('m5.internal', i_file)
6332632Sstever@eecs.umich.edu
6341869SN/A# Generate SimObject SWIG wrapper files
6351884SN/Afor name in sim_objects.iterkeys():
6361884SN/A    i_file = File('python/m5/internal/param_%s.i' % name)
6371884SN/A    env.Command(i_file, Value(name),
6381884SN/A                MakeAction(createSimObjectSwigWrapper, Transform("SO SWIG")))
6391884SN/A    env.Depends(i_file, depends)
6401884SN/A    SwigSource('m5.internal', i_file)
6411965SN/A
6421965SN/A# Generate the main swig init file
6431965SN/Adef makeEmbeddedSwigInit(target, source, env):
6442761Sstever@eecs.umich.edu    code = code_formatter()
6451869SN/A    module = source[0].get_contents()
6461869SN/A    code('''\
6472632Sstever@eecs.umich.edu#include "sim/init.hh"
6482667Sstever@eecs.umich.edu
6491869SN/Aextern "C" {
6501869SN/A    void init_${module}();
6512929Sktlim@umich.edu}
6522929Sktlim@umich.edu
6533716Sstever@eecs.umich.eduEmbeddedSwig embed_swig_${module}(init_${module});
6542929Sktlim@umich.edu''')
655955SN/A    code.write(str(target[0]))
6562598SN/A    
6572598SN/A# Build all swig modules
6583546Sgblack@eecs.umich.edufor swig in SwigSource.all:
659955SN/A    env.Command([swig.cc_source.tnode, swig.py_source.tnode], swig.tnode,
660955SN/A                MakeAction('$SWIG $SWIGFLAGS -outdir ${TARGETS[1].dir} '
661955SN/A                '-o ${TARGETS[0]} $SOURCES', Transform("SWIG")))
6621530SN/A    cc_file = str(swig.tnode)
663955SN/A    init_file = '%s/%s_init.cc' % (dirname(cc_file), basename(cc_file))
664955SN/A    env.Command(init_file, Value(swig.module),
665955SN/A                MakeAction(makeEmbeddedSwigInit, Transform("EMBED SW")))
666    Source(init_file, **swig.guards)
667
668#
669# Handle debug flags
670#
671def makeDebugFlagCC(target, source, env):
672    assert(len(target) == 1 and len(source) == 1)
673
674    val = eval(source[0].get_contents())
675    name, compound, desc = val
676    compound = list(sorted(compound))
677
678    code = code_formatter()
679
680    # file header
681    code('''
682/*
683 * DO NOT EDIT THIS FILE! Automatically generated
684 */
685
686#include "base/debug.hh"
687''')
688
689    for flag in compound:
690        code('#include "debug/$flag.hh"')
691    code()
692    code('namespace Debug {')
693    code()
694
695    if not compound:
696        code('SimpleFlag $name("$name", "$desc");')
697    else:
698        code('CompoundFlag $name("$name", "$desc",')
699        code.indent()
700        last = len(compound) - 1
701        for i,flag in enumerate(compound):
702            if i != last:
703                code('$flag,')
704            else:
705                code('$flag);')
706        code.dedent()
707
708    code()
709    code('} // namespace Debug')
710
711    code.write(str(target[0]))
712
713def makeDebugFlagHH(target, source, env):
714    assert(len(target) == 1 and len(source) == 1)
715
716    val = eval(source[0].get_contents())
717    name, compound, desc = val
718
719    code = code_formatter()
720
721    # file header boilerplate
722    code('''\
723/*
724 * DO NOT EDIT THIS FILE!
725 *
726 * Automatically generated by SCons
727 */
728
729#ifndef __DEBUG_${name}_HH__
730#define __DEBUG_${name}_HH__
731
732namespace Debug {
733''')
734
735    if compound:
736        code('class CompoundFlag;')
737    code('class SimpleFlag;')
738
739    if compound:
740        code('extern CompoundFlag $name;')
741        for flag in compound:
742            code('extern SimpleFlag $flag;')
743    else:
744        code('extern SimpleFlag $name;')
745
746    code('''
747}
748
749#endif // __DEBUG_${name}_HH__
750''')
751
752    code.write(str(target[0]))
753
754for name,flag in sorted(debug_flags.iteritems()):
755    n, compound, desc = flag
756    assert n == name
757
758    env.Command('debug/%s.hh' % name, Value(flag),
759                MakeAction(makeDebugFlagHH, Transform("TRACING", 0)))
760    env.Command('debug/%s.cc' % name, Value(flag),
761                MakeAction(makeDebugFlagCC, Transform("TRACING", 0)))
762    Source('debug/%s.cc' % name)
763
764# Embed python files.  All .py files that have been indicated by a
765# PySource() call in a SConscript need to be embedded into the M5
766# library.  To do that, we compile the file to byte code, marshal the
767# byte code, compress it, and then generate a c++ file that
768# inserts the result into an array.
769def embedPyFile(target, source, env):
770    def c_str(string):
771        if string is None:
772            return "0"
773        return '"%s"' % string
774
775    '''Action function to compile a .py into a code object, marshal
776    it, compress it, and stick it into an asm file so the code appears
777    as just bytes with a label in the data section'''
778
779    src = file(str(source[0]), 'r').read()
780
781    pysource = PySource.tnodes[source[0]]
782    compiled = compile(src, pysource.abspath, 'exec')
783    marshalled = marshal.dumps(compiled)
784    compressed = zlib.compress(marshalled)
785    data = compressed
786    sym = pysource.symname
787
788    code = code_formatter()
789    code('''\
790#include "sim/init.hh"
791
792namespace {
793
794const char data_${sym}[] = {
795''')
796    code.indent()
797    step = 16
798    for i in xrange(0, len(data), step):
799        x = array.array('B', data[i:i+step])
800        code(''.join('%d,' % d for d in x))
801    code.dedent()
802    
803    code('''};
804
805EmbeddedPython embedded_${sym}(
806    ${{c_str(pysource.arcname)}},
807    ${{c_str(pysource.abspath)}},
808    ${{c_str(pysource.modpath)}},
809    data_${sym},
810    ${{len(data)}},
811    ${{len(marshalled)}});
812
813} // anonymous namespace
814''')
815    code.write(str(target[0]))
816
817for source in PySource.all:
818    env.Command(source.cpp, source.tnode, 
819                MakeAction(embedPyFile, Transform("EMBED PY")))
820    Source(source.cpp)
821
822########################################################################
823#
824# Define binaries.  Each different build type (debug, opt, etc.) gets
825# a slightly different build environment.
826#
827
828# List of constructed environments to pass back to SConstruct
829envList = []
830
831date_source = Source('base/date.cc', skip_lib=True)
832
833# Function to create a new build environment as clone of current
834# environment 'env' with modified object suffix and optional stripped
835# binary.  Additional keyword arguments are appended to corresponding
836# build environment vars.
837def makeEnv(label, objsfx, strip = False, **kwargs):
838    # SCons doesn't know to append a library suffix when there is a '.' in the
839    # name.  Use '_' instead.
840    libname = 'gem5_' + label
841    exename = 'gem5.' + label
842    secondary_exename = 'm5.' + label
843
844    new_env = env.Clone(OBJSUFFIX=objsfx, SHOBJSUFFIX=objsfx + 's')
845    new_env.Label = label
846    new_env.Append(**kwargs)
847
848    swig_env = new_env.Clone()
849    swig_env.Append(CCFLAGS='-Werror')
850    if env['GCC']:
851        swig_env.Append(CCFLAGS='-Wno-uninitialized')
852        swig_env.Append(CCFLAGS='-Wno-sign-compare')
853        swig_env.Append(CCFLAGS='-Wno-parentheses')
854        swig_env.Append(CCFLAGS='-Wno-unused-label')
855        if compareVersions(env['GCC_VERSION'], '4.6.0') != -1:
856            swig_env.Append(CCFLAGS='-Wno-unused-but-set-variable')
857    if env['CLANG']:
858        swig_env.Append(CCFLAGS=['-Wno-unused-label'])
859
860
861    werror_env = new_env.Clone()
862    werror_env.Append(CCFLAGS='-Werror')
863
864    def make_obj(source, static, extra_deps = None):
865        '''This function adds the specified source to the correct
866        build environment, and returns the corresponding SCons Object
867        nodes'''
868
869        if source.swig:
870            env = swig_env
871        elif source.Werror:
872            env = werror_env
873        else:
874            env = new_env
875
876        if static:
877            obj = env.StaticObject(source.tnode)
878        else:
879            obj = env.SharedObject(source.tnode)
880
881        if extra_deps:
882            env.Depends(obj, extra_deps)
883
884        return obj
885
886    static_objs = \
887        [ make_obj(s, True) for s in Source.get(main=False, skip_lib=False) ]
888    shared_objs = \
889        [ make_obj(s, False) for s in Source.get(main=False, skip_lib=False) ]
890
891    static_date = make_obj(date_source, static=True, extra_deps=static_objs)
892    static_objs.append(static_date)
893    
894    shared_date = make_obj(date_source, static=False, extra_deps=shared_objs)
895    shared_objs.append(shared_date)
896
897    # First make a library of everything but main() so other programs can
898    # link against m5.
899    static_lib = new_env.StaticLibrary(libname, static_objs)
900    shared_lib = new_env.SharedLibrary(libname, shared_objs)
901
902    # Now link a stub with main() and the static library.
903    main_objs = [ make_obj(s, True) for s in Source.get(main=True) ]
904
905    for test in UnitTest.all:
906        flags = { test.target : True }
907        test_sources = Source.get(**flags)
908        test_objs = [ make_obj(s, static=True) for s in test_sources ]
909        testname = "unittest/%s.%s" % (test.target, label)
910        new_env.Program(testname, main_objs + test_objs + static_objs)
911
912    progname = exename
913    if strip:
914        progname += '.unstripped'
915
916    targets = new_env.Program(progname, main_objs + static_objs)
917
918    if strip:
919        if sys.platform == 'sunos5':
920            cmd = 'cp $SOURCE $TARGET; strip $TARGET'
921        else:
922            cmd = 'strip $SOURCE -o $TARGET'
923        targets = new_env.Command(exename, progname,
924                    MakeAction(cmd, Transform("STRIP")))
925
926    new_env.Command(secondary_exename, exename,
927            MakeAction('ln $SOURCE $TARGET', Transform("HARDLINK")))
928
929    new_env.M5Binary = targets[0]
930    envList.append(new_env)
931
932# Debug binary
933ccflags = {}
934if env['GCC'] or env['CLANG']:
935    if sys.platform == 'sunos5':
936        ccflags['debug'] = '-gstabs+'
937    else:
938        ccflags['debug'] = '-ggdb3'
939    ccflags['opt'] = '-g -O3'
940    ccflags['fast'] = '-O3'
941    ccflags['prof'] = '-O3 -g -pg'
942elif env['SUNCC']:
943    ccflags['debug'] = '-g0'
944    ccflags['opt'] = '-g -O'
945    ccflags['fast'] = '-fast'
946    ccflags['prof'] = '-fast -g -pg'
947elif env['ICC']:
948    ccflags['debug'] = '-g -O0'
949    ccflags['opt'] = '-g -O'
950    ccflags['fast'] = '-fast'
951    ccflags['prof'] = '-fast -g -pg'
952else:
953    print 'Unknown compiler, please fix compiler options'
954    Exit(1)
955
956
957# To speed things up, we only instantiate the build environments we
958# need.  We try to identify the needed environment for each target; if
959# we can't, we fall back on instantiating all the environments just to
960# be safe.
961target_types = ['debug', 'opt', 'fast', 'prof']
962obj2target = {'do': 'debug', 'o': 'opt', 'fo': 'fast', 'po': 'prof'}
963
964def identifyTarget(t):
965    ext = t.split('.')[-1]
966    if ext in target_types:
967        return ext
968    if obj2target.has_key(ext):
969        return obj2target[ext]
970    match = re.search(r'/tests/([^/]+)/', t)
971    if match and match.group(1) in target_types:
972        return match.group(1)
973    return 'all'
974
975needed_envs = [identifyTarget(target) for target in BUILD_TARGETS]
976if 'all' in needed_envs:
977    needed_envs += target_types
978
979# Debug binary
980if 'debug' in needed_envs:
981    makeEnv('debug', '.do',
982            CCFLAGS = Split(ccflags['debug']),
983            CPPDEFINES = ['DEBUG', 'TRACING_ON=1'])
984
985# Optimized binary
986if 'opt' in needed_envs:
987    makeEnv('opt', '.o',
988            CCFLAGS = Split(ccflags['opt']),
989            CPPDEFINES = ['TRACING_ON=1'])
990
991# "Fast" binary
992if 'fast' in needed_envs:
993    makeEnv('fast', '.fo', strip = True,
994            CCFLAGS = Split(ccflags['fast']),
995            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'])
996
997# Profiled binary
998if 'prof' in needed_envs:
999    makeEnv('prof', '.po',
1000            CCFLAGS = Split(ccflags['prof']),
1001            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1002            LINKFLAGS = '-pg')
1003
1004Return('envList')
1005