SConscript revision 9226
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
331608SN/Aimport imp
34955SN/Aimport marshal
35955SN/Aimport os
36955SN/Aimport re
37955SN/Aimport sys
38955SN/Aimport zlib
39955SN/A
40955SN/Afrom os.path import basename, dirname, exists, isdir, isfile, join as joinpath
41955SN/A
42955SN/Aimport SCons
43955SN/A
44955SN/A# This file defines how to build a particular configuration of gem5
45955SN/A# based on variable settings in the 'env' build environment.
46955SN/A
47955SN/AImport('*')
482023SN/A
49955SN/A# Children need to see the environment
50955SN/AExport('env')
51955SN/A
52955SN/Abuild_env = [(opt, env[opt]) for opt in export_vars]
53955SN/A
54955SN/Afrom m5.util import code_formatter, compareVersions
55955SN/A
56955SN/A########################################################################
57955SN/A# Code for adding source files of various types
581031SN/A#
59955SN/A# When specifying a source file of some type, a set of guards can be
601388SN/A# specified for that file.  When get() is used to find the files, if
61955SN/A# get specifies a set of filters, only files that match those filters
62955SN/A# will be accepted (unspecified filters on files are assumed to be
631296SN/A# false).  Current filters are:
64955SN/A#     main -- specifies the gem5 main() function
652609SN/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
69955SN/A# values will be retrieved recursively from parents (children override
70955SN/A# parents).
71955SN/A#
72955SN/Aclass SourceMeta(type):
73955SN/A    '''Meta class for source files that keeps track of all files of a
74955SN/A    particular type and has a get function for finding all functions
75955SN/A    of a certain type that match a set of guards'''
76955SN/A    def __init__(cls, name, bases, dict):
77955SN/A        super(SourceMeta, cls).__init__(name, bases, dict)
78955SN/A        cls.all = []
79955SN/A        
80955SN/A    def get(cls, **guards):
81955SN/A        '''Find all files that match the specified guards.  If a source
82955SN/A        file does not specify a flag, the default is False'''
83955SN/A        for src in cls.all:
841717SN/A            for flag,value in guards.iteritems():
852190SN/A                # if the flag is found and has a different value, skip
862652Ssaidi@eecs.umich.edu                # this file
87955SN/A                if src.all_guards.get(flag, False) != value:
882410SN/A                    break
89955SN/A            else:
90955SN/A                yield src
911717SN/A
922568SN/Aclass SourceFile(object):
932568SN/A    '''Base object that encapsulates the notion of a source file.
942568SN/A    This includes, the source node, target node, various manipulations
952499SN/A    of those.  A source file also specifies a set of guards which
962462SN/A    describing which builds the source file applies to.  A parent can
972568SN/A    also be specified to get default guards from'''
982395SN/A    __metaclass__ = SourceMeta
992405SN/A    def __init__(self, source, parent=None, **guards):
100955SN/A        self.guards = guards
101955SN/A        self.parent = parent
102955SN/A
103955SN/A        tnode = source
104955SN/A        if not isinstance(source, SCons.Node.FS.File):
1052090SN/A            tnode = File(source)
106955SN/A
1072667Sstever@eecs.umich.edu        self.tnode = tnode
108955SN/A        self.snode = tnode.srcnode()
109955SN/A
1101696SN/A        for base in type(self).__mro__:
111955SN/A            if issubclass(base, SourceFile):
112955SN/A                base.all.append(self)
113955SN/A
1141127SN/A    @property
115955SN/A    def filename(self):
116955SN/A        return str(self.tnode)
1172379SN/A
118955SN/A    @property
119955SN/A    def dirname(self):
120955SN/A        return dirname(self.filename)
1212155SN/A
1222155SN/A    @property
1232155SN/A    def basename(self):
1242155SN/A        return basename(self.filename)
1252155SN/A
1262155SN/A    @property
1272155SN/A    def extname(self):
1282155SN/A        index = self.basename.rfind('.')
1292155SN/A        if index <= 0:
1302155SN/A            # dot files aren't extensions
1312155SN/A            return self.basename, None
1322155SN/A
1332155SN/A        return self.basename[:index], self.basename[index+1:]
1342155SN/A
1352155SN/A    @property
1362155SN/A    def all_guards(self):
1372155SN/A        '''find all guards for this object getting default values
1382155SN/A        recursively from its parents'''
1392155SN/A        guards = {}
1402155SN/A        if self.parent:
1412155SN/A            guards.update(self.parent.guards)
1422155SN/A        guards.update(self.guards)
1432155SN/A        return guards
1442155SN/A
1452155SN/A    def __lt__(self, other): return self.filename < other.filename
1462155SN/A    def __le__(self, other): return self.filename <= other.filename
1472155SN/A    def __gt__(self, other): return self.filename > other.filename
1482155SN/A    def __ge__(self, other): return self.filename >= other.filename
1492155SN/A    def __eq__(self, other): return self.filename == other.filename
1502155SN/A    def __ne__(self, other): return self.filename != other.filename
1512155SN/A        
1522155SN/Aclass Source(SourceFile):
1532155SN/A    '''Add a c/c++ source file to the build'''
1542155SN/A    def __init__(self, source, Werror=True, swig=False, **guards):
1552155SN/A        '''specify the source file, and any guards'''
1562155SN/A        super(Source, self).__init__(source, **guards)
1572155SN/A
1582155SN/A        self.Werror = Werror
1592155SN/A        self.swig = swig
1602422SN/A
1612422SN/Aclass PySource(SourceFile):
1622422SN/A    '''Add a python source file to the named package'''
1632422SN/A    invalid_sym_char = re.compile('[^A-z0-9_]')
1642422SN/A    modules = {}
1652422SN/A    tnodes = {}
1662422SN/A    symnames = {}
1672397SN/A    
1682397SN/A    def __init__(self, package, source, **guards):
1692422SN/A        '''specify the python package, the source file, and any guards'''
1702422SN/A        super(PySource, self).__init__(source, **guards)
171955SN/A
172955SN/A        modname,ext = self.extname
173955SN/A        assert ext == 'py'
174955SN/A
175955SN/A        if package:
176955SN/A            path = package.split('.')
177955SN/A        else:
178955SN/A            path = []
1791078SN/A
180955SN/A        modpath = path[:]
181955SN/A        if modname != '__init__':
182955SN/A            modpath += [ modname ]
183955SN/A        modpath = '.'.join(modpath)
1841917SN/A
185955SN/A        arcpath = path + [ self.basename ]
186955SN/A        abspath = self.snode.abspath
187955SN/A        if not exists(abspath):
188955SN/A            abspath = self.tnode.abspath
189974SN/A
190955SN/A        self.package = package
191955SN/A        self.modname = modname
192955SN/A        self.modpath = modpath
193955SN/A        self.arcname = joinpath(*arcpath)
1942566SN/A        self.abspath = abspath
1952566SN/A        self.compiled = File(self.filename + 'c')
196955SN/A        self.cpp = File(self.filename + '.cc')
197955SN/A        self.symname = PySource.invalid_sym_char.sub('_', modpath)
1982539SN/A
199955SN/A        PySource.modules[modpath] = self
200955SN/A        PySource.tnodes[self.tnode] = self
201955SN/A        PySource.symnames[self.symname] = self
2021817SN/A
2031154SN/Aclass SimObject(PySource):
2041840SN/A    '''Add a SimObject python file as a python source object and add
2052522SN/A    it to a list of sim object modules'''
2062522SN/A
2072629SN/A    fixed = False
208955SN/A    modnames = []
209955SN/A
210955SN/A    def __init__(self, source, **guards):
2112539SN/A        '''Specify the source file and any guards (automatically in
212955SN/A        the m5.objects package)'''
2132539SN/A        super(SimObject, self).__init__('m5.objects', source, **guards)
214955SN/A        if self.fixed:
2151730SN/A            raise AttributeError, "Too late to call SimObject now."
216955SN/A
2171070SN/A        bisect.insort_right(SimObject.modnames, self.modname)
218955SN/A
219955SN/Aclass SwigSource(SourceFile):
2202212SN/A    '''Add a swig file to build'''
221955SN/A
2221040SN/A    def __init__(self, package, source, **guards):
2232507SN/A        '''Specify the python package, the source file, and any guards'''
2242521SN/A        super(SwigSource, self).__init__(source, **guards)
2252521SN/A
2262507SN/A        modname,ext = self.extname
2272507SN/A        assert ext == 'i'
2282507SN/A
2292521SN/A        self.module = modname
2302507SN/A        cc_file = joinpath(self.dirname, modname + '_wrap.cc')
2312507SN/A        py_file = joinpath(self.dirname, modname + '.py')
232955SN/A
233955SN/A        self.cc_source = Source(cc_file, swig=True, parent=self)
234955SN/A        self.py_source = PySource(package, py_file, parent=self)
235955SN/A
236955SN/Aclass UnitTest(object):
237955SN/A    '''Create a UnitTest'''
2381742SN/A
2391742SN/A    all = []
2401742SN/A    def __init__(self, target, *sources, **kwargs):
2411742SN/A        '''Specify the target name and any sources.  Sources that are
2421742SN/A        not SourceFiles are evalued with Source().  All files are
2431742SN/A        guarded with a guard of the same name as the UnitTest
2441742SN/A        target.'''
2451742SN/A
2461742SN/A        srcs = []
2471742SN/A        for src in sources:
2481742SN/A            if not isinstance(src, SourceFile):
2491742SN/A                src = Source(src, skip_lib=True)
2501742SN/A            src.guards[target] = True
2511742SN/A            srcs.append(src)
2521742SN/A
2531742SN/A        self.sources = srcs
2541742SN/A        self.target = target
2551742SN/A        self.main = kwargs.get('main', False)
2561742SN/A        UnitTest.all.append(self)
2571742SN/A
258955SN/A# Children should have access
259955SN/AExport('Source')
2602520SN/AExport('PySource')
2612517SN/AExport('SimObject')
2622253SN/AExport('SwigSource')
2632253SN/AExport('UnitTest')
2642253SN/A
2652253SN/A########################################################################
2662553SN/A#
2672553SN/A# Debug Flags
2682553SN/A#
2692553SN/Adebug_flags = {}
2702507SN/Adef DebugFlag(name, desc=None):
2712470SN/A    if name in debug_flags:
2721744SN/A        raise AttributeError, "Flag %s already specified" % name
2731744SN/A    debug_flags[name] = (name, (), desc)
2742470SN/A
2752470SN/Adef CompoundFlag(name, flags, desc=None):
2762470SN/A    if name in debug_flags:
2772470SN/A        raise AttributeError, "Flag %s already specified" % name
2782470SN/A
2792470SN/A    compound = tuple(flags)
2802400SN/A    debug_flags[name] = (name, compound, desc)
2812400SN/A
282955SN/AExport('DebugFlag')
283955SN/AExport('CompoundFlag')
2842667Sstever@eecs.umich.edu
2852667Sstever@eecs.umich.edu########################################################################
2862667Sstever@eecs.umich.edu#
2872667Sstever@eecs.umich.edu# Set some compiler variables
2882667Sstever@eecs.umich.edu#
2892667Sstever@eecs.umich.edu
2902037SN/A# Include file paths are rooted in this directory.  SCons will
2912037SN/A# automatically expand '.' to refer to both the source directory and
2922037SN/A# the corresponding build directory to pick up generated include
2932667Sstever@eecs.umich.edu# files.
2942139SN/Aenv.Append(CPPPATH=Dir('.'))
2952667Sstever@eecs.umich.edu
2962155SN/Afor extra_dir in extras_dir_list:
2972155SN/A    env.Append(CPPPATH=Dir(extra_dir))
2982155SN/A
2992155SN/A# Workaround for bug in SCons version > 0.97d20071212
3002155SN/A# Scons bug id: 2006 gem5 Bug id: 308
3012155SN/Afor root, dirs, files in os.walk(base_dir, topdown=True):
302955SN/A    Dir(root[len(base_dir) + 1:])
3032155SN/A
304955SN/A########################################################################
305955SN/A#
306955SN/A# Walk the tree and execute all SConscripts in subdirectories
3071742SN/A#
3081742SN/A
309955SN/Ahere = Dir('.').srcnode().abspath
310955SN/Afor root, dirs, files in os.walk(base_dir, topdown=True):
311955SN/A    if root == here:
3121858SN/A        # we don't want to recurse back into this SConscript
313955SN/A        continue
3141858SN/A
3151858SN/A    if 'SConscript' in files:
3161858SN/A        build_dir = joinpath(env['BUILDDIR'], root[len(base_dir) + 1:])
3171085SN/A        SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
318955SN/A
319955SN/Afor extra_dir in extras_dir_list:
320955SN/A    prefix_len = len(dirname(extra_dir)) + 1
321955SN/A    for root, dirs, files in os.walk(extra_dir, topdown=True):
322955SN/A        # if build lives in the extras directory, don't walk down it
323955SN/A        if 'build' in dirs:
324955SN/A            dirs.remove('build')
325955SN/A
326955SN/A        if 'SConscript' in files:
327955SN/A            build_dir = joinpath(env['BUILDDIR'], root[prefix_len:])
328955SN/A            SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
329955SN/A
3302667Sstever@eecs.umich.edufor opt in export_vars:
3311045SN/A    env.ConfigFile(opt)
332955SN/A
333955SN/Adef makeTheISA(source, target, env):
334955SN/A    isas = [ src.get_contents() for src in source ]
335955SN/A    target_isa = env['TARGET_ISA']
3361108SN/A    def define(isa):
337955SN/A        return isa.upper() + '_ISA'
338955SN/A    
339955SN/A    def namespace(isa):
340955SN/A        return isa[0].upper() + isa[1:].lower() + 'ISA' 
341955SN/A
342955SN/A
343955SN/A    code = code_formatter()
344955SN/A    code('''\
345955SN/A#ifndef __CONFIG_THE_ISA_HH__
346955SN/A#define __CONFIG_THE_ISA_HH__
347955SN/A
348955SN/A''')
349955SN/A
350955SN/A    for i,isa in enumerate(isas):
351955SN/A        code('#define $0 $1', define(isa), i + 1)
352955SN/A
3532655Sstever@eecs.umich.edu    code('''
3542655Sstever@eecs.umich.edu
3552655Sstever@eecs.umich.edu#define THE_ISA ${{define(target_isa)}}
3562655Sstever@eecs.umich.edu#define TheISA ${{namespace(target_isa)}}
3572655Sstever@eecs.umich.edu#define THE_ISA_STR "${{target_isa}}"
3582655Sstever@eecs.umich.edu
3592655Sstever@eecs.umich.edu#endif // __CONFIG_THE_ISA_HH__''')
3602655Sstever@eecs.umich.edu
3612655Sstever@eecs.umich.edu    code.write(str(target[0]))
3622655Sstever@eecs.umich.edu
3632655Sstever@eecs.umich.eduenv.Command('config/the_isa.hh', map(Value, all_isa_list),
3642655Sstever@eecs.umich.edu            MakeAction(makeTheISA, Transform("CFG ISA", 0)))
3652655Sstever@eecs.umich.edu
3662655Sstever@eecs.umich.edu########################################################################
3672655Sstever@eecs.umich.edu#
3682655Sstever@eecs.umich.edu# Prevent any SimObjects from being added after this point, they
3692655Sstever@eecs.umich.edu# should all have been added in the SConscripts above
3702655Sstever@eecs.umich.edu#
3712655Sstever@eecs.umich.eduSimObject.fixed = True
3722655Sstever@eecs.umich.edu
3732655Sstever@eecs.umich.educlass DictImporter(object):
3742655Sstever@eecs.umich.edu    '''This importer takes a dictionary of arbitrary module names that
375955SN/A    map to arbitrary filenames.'''
3762655Sstever@eecs.umich.edu    def __init__(self, modules):
3772655Sstever@eecs.umich.edu        self.modules = modules
3782655Sstever@eecs.umich.edu        self.installed = set()
379955SN/A
380955SN/A    def __del__(self):
3812655Sstever@eecs.umich.edu        self.unload()
3822655Sstever@eecs.umich.edu
383955SN/A    def unload(self):
384955SN/A        import sys
3852655Sstever@eecs.umich.edu        for module in self.installed:
3862655Sstever@eecs.umich.edu            del sys.modules[module]
3872655Sstever@eecs.umich.edu        self.installed = set()
388955SN/A
389955SN/A    def find_module(self, fullname, path):
3902655Sstever@eecs.umich.edu        if fullname == 'm5.defines':
3912655Sstever@eecs.umich.edu            return self
3922655Sstever@eecs.umich.edu
3931869SN/A        if fullname == 'm5.objects':
3941869SN/A            return self
395
396        if fullname.startswith('m5.internal'):
397            return None
398
399        source = self.modules.get(fullname, None)
400        if source is not None and fullname.startswith('m5.objects'):
401            return self
402
403        return None
404
405    def load_module(self, fullname):
406        mod = imp.new_module(fullname)
407        sys.modules[fullname] = mod
408        self.installed.add(fullname)
409
410        mod.__loader__ = self
411        if fullname == 'm5.objects':
412            mod.__path__ = fullname.split('.')
413            return mod
414
415        if fullname == 'm5.defines':
416            mod.__dict__['buildEnv'] = m5.util.SmartDict(build_env)
417            return mod
418
419        source = self.modules[fullname]
420        if source.modname == '__init__':
421            mod.__path__ = source.modpath
422        mod.__file__ = source.abspath
423
424        exec file(source.abspath, 'r') in mod.__dict__
425
426        return mod
427
428import m5.SimObject
429import m5.params
430from m5.util import code_formatter
431
432m5.SimObject.clear()
433m5.params.clear()
434
435# install the python importer so we can grab stuff from the source
436# tree itself.  We can't have SimObjects added after this point or
437# else we won't know about them for the rest of the stuff.
438importer = DictImporter(PySource.modules)
439sys.meta_path[0:0] = [ importer ]
440
441# import all sim objects so we can populate the all_objects list
442# make sure that we're working with a list, then let's sort it
443for modname in SimObject.modnames:
444    exec('from m5.objects import %s' % modname)
445
446# we need to unload all of the currently imported modules so that they
447# will be re-imported the next time the sconscript is run
448importer.unload()
449sys.meta_path.remove(importer)
450
451sim_objects = m5.SimObject.allClasses
452all_enums = m5.params.allEnums
453
454# Find param types that need to be explicitly wrapped with swig.
455# These will be recognized because the ParamDesc will have a
456# swig_decl() method.  Most param types are based on types that don't
457# need this, either because they're based on native types (like Int)
458# or because they're SimObjects (which get swigged independently).
459# For now the only things handled here are VectorParam types.
460params_to_swig = {}
461for name,obj in sorted(sim_objects.iteritems()):
462    for param in obj._params.local.values():
463        # load the ptype attribute now because it depends on the
464        # current version of SimObject.allClasses, but when scons
465        # actually uses the value, all versions of
466        # SimObject.allClasses will have been loaded
467        param.ptype
468
469        if not hasattr(param, 'swig_decl'):
470            continue
471        pname = param.ptype_str
472        if pname not in params_to_swig:
473            params_to_swig[pname] = param
474
475########################################################################
476#
477# calculate extra dependencies
478#
479module_depends = ["m5", "m5.SimObject", "m5.params"]
480depends = [ PySource.modules[dep].snode for dep in module_depends ]
481
482########################################################################
483#
484# Commands for the basic automatically generated python files
485#
486
487# Generate Python file containing a dict specifying the current
488# buildEnv flags.
489def makeDefinesPyFile(target, source, env):
490    build_env = source[0].get_contents()
491
492    code = code_formatter()
493    code("""
494import m5.internal
495import m5.util
496
497buildEnv = m5.util.SmartDict($build_env)
498
499compileDate = m5.internal.core.compileDate
500_globals = globals()
501for key,val in m5.internal.core.__dict__.iteritems():
502    if key.startswith('flag_'):
503        flag = key[5:]
504        _globals[flag] = val
505del _globals
506""")
507    code.write(target[0].abspath)
508
509defines_info = Value(build_env)
510# Generate a file with all of the compile options in it
511env.Command('python/m5/defines.py', defines_info,
512            MakeAction(makeDefinesPyFile, Transform("DEFINES", 0)))
513PySource('m5', 'python/m5/defines.py')
514
515# Generate python file containing info about the M5 source code
516def makeInfoPyFile(target, source, env):
517    code = code_formatter()
518    for src in source:
519        data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
520        code('$src = ${{repr(data)}}')
521    code.write(str(target[0]))
522
523# Generate a file that wraps the basic top level files
524env.Command('python/m5/info.py',
525            [ '#/COPYING', '#/LICENSE', '#/README', ],
526            MakeAction(makeInfoPyFile, Transform("INFO")))
527PySource('m5', 'python/m5/info.py')
528
529########################################################################
530#
531# Create all of the SimObject param headers and enum headers
532#
533
534def createSimObjectParamStruct(target, source, env):
535    assert len(target) == 1 and len(source) == 1
536
537    name = str(source[0].get_contents())
538    obj = sim_objects[name]
539
540    code = code_formatter()
541    obj.cxx_param_decl(code)
542    code.write(target[0].abspath)
543
544def createParamSwigWrapper(target, source, env):
545    assert len(target) == 1 and len(source) == 1
546
547    name = str(source[0].get_contents())
548    param = params_to_swig[name]
549
550    code = code_formatter()
551    param.swig_decl(code)
552    code.write(target[0].abspath)
553
554def createEnumStrings(target, source, env):
555    assert len(target) == 1 and len(source) == 1
556
557    name = str(source[0].get_contents())
558    obj = all_enums[name]
559
560    code = code_formatter()
561    obj.cxx_def(code)
562    code.write(target[0].abspath)
563
564def createEnumDecls(target, source, env):
565    assert len(target) == 1 and len(source) == 1
566
567    name = str(source[0].get_contents())
568    obj = all_enums[name]
569
570    code = code_formatter()
571    obj.cxx_decl(code)
572    code.write(target[0].abspath)
573
574def createEnumSwigWrapper(target, source, env):
575    assert len(target) == 1 and len(source) == 1
576
577    name = str(source[0].get_contents())
578    obj = all_enums[name]
579
580    code = code_formatter()
581    obj.swig_decl(code)
582    code.write(target[0].abspath)
583
584def createSimObjectSwigWrapper(target, source, env):
585    name = source[0].get_contents()
586    obj = sim_objects[name]
587
588    code = code_formatter()
589    obj.swig_decl(code)
590    code.write(target[0].abspath)
591
592# Generate all of the SimObject param C++ struct header files
593params_hh_files = []
594for name,simobj in sorted(sim_objects.iteritems()):
595    py_source = PySource.modules[simobj.__module__]
596    extra_deps = [ py_source.tnode ]
597
598    hh_file = File('params/%s.hh' % name)
599    params_hh_files.append(hh_file)
600    env.Command(hh_file, Value(name),
601                MakeAction(createSimObjectParamStruct, Transform("SO PARAM")))
602    env.Depends(hh_file, depends + extra_deps)
603
604# Generate any needed param SWIG wrapper files
605params_i_files = []
606for name,param in params_to_swig.iteritems():
607    i_file = File('python/m5/internal/%s.i' % (param.swig_module_name()))
608    params_i_files.append(i_file)
609    env.Command(i_file, Value(name),
610                MakeAction(createParamSwigWrapper, Transform("SW PARAM")))
611    env.Depends(i_file, depends)
612    SwigSource('m5.internal', i_file)
613
614# Generate all enum header files
615for name,enum in sorted(all_enums.iteritems()):
616    py_source = PySource.modules[enum.__module__]
617    extra_deps = [ py_source.tnode ]
618
619    cc_file = File('enums/%s.cc' % name)
620    env.Command(cc_file, Value(name),
621                MakeAction(createEnumStrings, Transform("ENUM STR")))
622    env.Depends(cc_file, depends + extra_deps)
623    Source(cc_file)
624
625    hh_file = File('enums/%s.hh' % name)
626    env.Command(hh_file, Value(name),
627                MakeAction(createEnumDecls, Transform("ENUMDECL")))
628    env.Depends(hh_file, depends + extra_deps)
629
630    i_file = File('python/m5/internal/enum_%s.i' % name)
631    env.Command(i_file, Value(name),
632                MakeAction(createEnumSwigWrapper, Transform("ENUMSWIG")))
633    env.Depends(i_file, depends + extra_deps)
634    SwigSource('m5.internal', i_file)
635
636# Generate SimObject SWIG wrapper files
637for name in sim_objects.iterkeys():
638    i_file = File('python/m5/internal/param_%s.i' % name)
639    env.Command(i_file, Value(name),
640                MakeAction(createSimObjectSwigWrapper, Transform("SO SWIG")))
641    env.Depends(i_file, depends)
642    SwigSource('m5.internal', i_file)
643
644# Generate the main swig init file
645def makeEmbeddedSwigInit(target, source, env):
646    code = code_formatter()
647    module = source[0].get_contents()
648    code('''\
649#include "sim/init.hh"
650
651extern "C" {
652    void init_${module}();
653}
654
655EmbeddedSwig embed_swig_${module}(init_${module});
656''')
657    code.write(str(target[0]))
658    
659# Build all swig modules
660for swig in SwigSource.all:
661    env.Command([swig.cc_source.tnode, swig.py_source.tnode], swig.tnode,
662                MakeAction('$SWIG $SWIGFLAGS -outdir ${TARGETS[1].dir} '
663                '-o ${TARGETS[0]} $SOURCES', Transform("SWIG")))
664    cc_file = str(swig.tnode)
665    init_file = '%s/%s_init.cc' % (dirname(cc_file), basename(cc_file))
666    env.Command(init_file, Value(swig.module),
667                MakeAction(makeEmbeddedSwigInit, Transform("EMBED SW")))
668    Source(init_file, **swig.guards)
669
670#
671# Handle debug flags
672#
673def makeDebugFlagCC(target, source, env):
674    assert(len(target) == 1 and len(source) == 1)
675
676    val = eval(source[0].get_contents())
677    name, compound, desc = val
678    compound = list(sorted(compound))
679
680    code = code_formatter()
681
682    # file header
683    code('''
684/*
685 * DO NOT EDIT THIS FILE! Automatically generated
686 */
687
688#include "base/debug.hh"
689''')
690
691    for flag in compound:
692        code('#include "debug/$flag.hh"')
693    code()
694    code('namespace Debug {')
695    code()
696
697    if not compound:
698        code('SimpleFlag $name("$name", "$desc");')
699    else:
700        code('CompoundFlag $name("$name", "$desc",')
701        code.indent()
702        last = len(compound) - 1
703        for i,flag in enumerate(compound):
704            if i != last:
705                code('$flag,')
706            else:
707                code('$flag);')
708        code.dedent()
709
710    code()
711    code('} // namespace Debug')
712
713    code.write(str(target[0]))
714
715def makeDebugFlagHH(target, source, env):
716    assert(len(target) == 1 and len(source) == 1)
717
718    val = eval(source[0].get_contents())
719    name, compound, desc = val
720
721    code = code_formatter()
722
723    # file header boilerplate
724    code('''\
725/*
726 * DO NOT EDIT THIS FILE!
727 *
728 * Automatically generated by SCons
729 */
730
731#ifndef __DEBUG_${name}_HH__
732#define __DEBUG_${name}_HH__
733
734namespace Debug {
735''')
736
737    if compound:
738        code('class CompoundFlag;')
739    code('class SimpleFlag;')
740
741    if compound:
742        code('extern CompoundFlag $name;')
743        for flag in compound:
744            code('extern SimpleFlag $flag;')
745    else:
746        code('extern SimpleFlag $name;')
747
748    code('''
749}
750
751#endif // __DEBUG_${name}_HH__
752''')
753
754    code.write(str(target[0]))
755
756for name,flag in sorted(debug_flags.iteritems()):
757    n, compound, desc = flag
758    assert n == name
759
760    env.Command('debug/%s.hh' % name, Value(flag),
761                MakeAction(makeDebugFlagHH, Transform("TRACING", 0)))
762    env.Command('debug/%s.cc' % name, Value(flag),
763                MakeAction(makeDebugFlagCC, Transform("TRACING", 0)))
764    Source('debug/%s.cc' % name)
765
766# Embed python files.  All .py files that have been indicated by a
767# PySource() call in a SConscript need to be embedded into the M5
768# library.  To do that, we compile the file to byte code, marshal the
769# byte code, compress it, and then generate a c++ file that
770# inserts the result into an array.
771def embedPyFile(target, source, env):
772    def c_str(string):
773        if string is None:
774            return "0"
775        return '"%s"' % string
776
777    '''Action function to compile a .py into a code object, marshal
778    it, compress it, and stick it into an asm file so the code appears
779    as just bytes with a label in the data section'''
780
781    src = file(str(source[0]), 'r').read()
782
783    pysource = PySource.tnodes[source[0]]
784    compiled = compile(src, pysource.abspath, 'exec')
785    marshalled = marshal.dumps(compiled)
786    compressed = zlib.compress(marshalled)
787    data = compressed
788    sym = pysource.symname
789
790    code = code_formatter()
791    code('''\
792#include "sim/init.hh"
793
794namespace {
795
796const uint8_t data_${sym}[] = {
797''')
798    code.indent()
799    step = 16
800    for i in xrange(0, len(data), step):
801        x = array.array('B', data[i:i+step])
802        code(''.join('%d,' % d for d in x))
803    code.dedent()
804    
805    code('''};
806
807EmbeddedPython embedded_${sym}(
808    ${{c_str(pysource.arcname)}},
809    ${{c_str(pysource.abspath)}},
810    ${{c_str(pysource.modpath)}},
811    data_${sym},
812    ${{len(data)}},
813    ${{len(marshalled)}});
814
815} // anonymous namespace
816''')
817    code.write(str(target[0]))
818
819for source in PySource.all:
820    env.Command(source.cpp, source.tnode, 
821                MakeAction(embedPyFile, Transform("EMBED PY")))
822    Source(source.cpp)
823
824########################################################################
825#
826# Define binaries.  Each different build type (debug, opt, etc.) gets
827# a slightly different build environment.
828#
829
830# List of constructed environments to pass back to SConstruct
831envList = []
832
833date_source = Source('base/date.cc', skip_lib=True)
834
835# Function to create a new build environment as clone of current
836# environment 'env' with modified object suffix and optional stripped
837# binary.  Additional keyword arguments are appended to corresponding
838# build environment vars.
839def makeEnv(label, objsfx, strip = False, **kwargs):
840    # SCons doesn't know to append a library suffix when there is a '.' in the
841    # name.  Use '_' instead.
842    libname = 'gem5_' + label
843    exename = 'gem5.' + label
844    secondary_exename = 'm5.' + label
845
846    new_env = env.Clone(OBJSUFFIX=objsfx, SHOBJSUFFIX=objsfx + 's')
847    new_env.Label = label
848    new_env.Append(**kwargs)
849
850    swig_env = new_env.Clone()
851    swig_env.Append(CCFLAGS='-Werror')
852    if env['GCC']:
853        swig_env.Append(CCFLAGS=['-Wno-uninitialized', '-Wno-sign-compare',
854                                 '-Wno-parentheses', '-Wno-unused-label',
855                                 '-Wno-unused-value'])
856        if compareVersions(env['GCC_VERSION'], '4.6') >= 0:
857            swig_env.Append(CCFLAGS='-Wno-unused-but-set-variable')
858    if env['CLANG']:
859        swig_env.Append(CCFLAGS=['-Wno-unused-label', '-Wno-unused-value'])
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        if test.main:
910            test_objs += main_objs
911        testname = "unittest/%s.%s" % (test.target, label)
912        new_env.Program(testname, test_objs + static_objs)
913
914    progname = exename
915    if strip:
916        progname += '.unstripped'
917
918    targets = new_env.Program(progname, main_objs + static_objs)
919
920    if strip:
921        if sys.platform == 'sunos5':
922            cmd = 'cp $SOURCE $TARGET; strip $TARGET'
923        else:
924            cmd = 'strip $SOURCE -o $TARGET'
925        targets = new_env.Command(exename, progname,
926                    MakeAction(cmd, Transform("STRIP")))
927
928    new_env.Command(secondary_exename, exename,
929            MakeAction('ln $SOURCE $TARGET', Transform("HARDLINK")))
930
931    new_env.M5Binary = targets[0]
932    envList.append(new_env)
933
934# Start out with the compiler flags common to all compilers,
935# i.e. they all use -g for opt and -g -pg for prof
936ccflags = {'debug' : [], 'opt' : ['-g'], 'fast' : [], 'prof' : ['-g', '-pg'],
937           'perf' : ['-g']}
938
939# Start out with the linker flags common to all linkers, i.e. -pg for
940# prof, and -lprofiler for perf. The -lprofile flag is surrounded by
941# no-as-needed and as-needed as the binutils linker is too clever and
942# simply doesn't link to the library otherwise.
943ldflags = {'debug' : [], 'opt' : [], 'fast' : [], 'prof' : ['-pg'],
944           'perf' : ['-Wl,--no-as-needed', '-lprofiler', '-Wl,--as-needed']}
945
946if env['GCC']:
947    if sys.platform == 'sunos5':
948        ccflags['debug'] += ['-gstabs+']
949    else:
950        ccflags['debug'] += ['-ggdb3']
951    ldflags['debug'] += ['-O0']
952    # opt, fast, prof and perf all share the same cc flags
953    for target in ['opt', 'fast', 'prof', 'perf']:
954        ccflags[target] += ['-O3']
955elif env['SUNCC']:
956    ccflags['debug'] += ['-g0']
957    ccflags['opt'] += ['-O']
958    for target in ['fast', 'prof', 'perf']:
959        ccflags[target] += ['-fast']
960elif env['ICC']:
961    ccflags['debug'] += ['-g', '-O0']
962    ccflags['opt'] += ['-O']
963    for target in ['fast', 'prof', 'perf']:
964        ccflags[target] += ['-fast']
965elif env['CLANG']:
966    ccflags['debug'] += ['-g', '-O0']
967    # opt, fast, prof and perf all share the same cc flags
968    for target in ['opt', 'fast', 'prof', 'perf']:
969        ccflags[target] += ['-O3']
970else:
971    print 'Unknown compiler, please fix compiler options'
972    Exit(1)
973
974
975# To speed things up, we only instantiate the build environments we
976# need.  We try to identify the needed environment for each target; if
977# we can't, we fall back on instantiating all the environments just to
978# be safe.
979target_types = ['debug', 'opt', 'fast', 'prof', 'perf']
980obj2target = {'do': 'debug', 'o': 'opt', 'fo': 'fast', 'po': 'prof',
981              'gpo' : 'perf'}
982
983def identifyTarget(t):
984    ext = t.split('.')[-1]
985    if ext in target_types:
986        return ext
987    if obj2target.has_key(ext):
988        return obj2target[ext]
989    match = re.search(r'/tests/([^/]+)/', t)
990    if match and match.group(1) in target_types:
991        return match.group(1)
992    return 'all'
993
994needed_envs = [identifyTarget(target) for target in BUILD_TARGETS]
995if 'all' in needed_envs:
996    needed_envs += target_types
997
998# Debug binary
999if 'debug' in needed_envs:
1000    makeEnv('debug', '.do',
1001            CCFLAGS = Split(ccflags['debug']),
1002            CPPDEFINES = ['DEBUG', 'TRACING_ON=1'],
1003            LINKFLAGS = Split(ldflags['debug']))
1004
1005# Optimized binary
1006if 'opt' in needed_envs:
1007    makeEnv('opt', '.o',
1008            CCFLAGS = Split(ccflags['opt']),
1009            CPPDEFINES = ['TRACING_ON=1'],
1010            LINKFLAGS = Split(ldflags['opt']))
1011
1012# "Fast" binary
1013if 'fast' in needed_envs:
1014    makeEnv('fast', '.fo', strip = True,
1015            CCFLAGS = Split(ccflags['fast']),
1016            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1017            LINKFLAGS = Split(ldflags['fast']))
1018
1019# Profiled binary using gprof
1020if 'prof' in needed_envs:
1021    makeEnv('prof', '.po',
1022            CCFLAGS = Split(ccflags['prof']),
1023            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1024            LINKFLAGS = Split(ldflags['prof']))
1025
1026# Profiled binary using google-pprof
1027if 'perf' in needed_envs:
1028    makeEnv('perf', '.gpo',
1029            CCFLAGS = Split(ccflags['perf']),
1030            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1031            LINKFLAGS = Split(ldflags['perf']))
1032
1033Return('envList')
1034