SConscript revision 13993:a599ee1297a7
1955SN/A# -*- mode:python -*-
2955SN/A
37816Ssteve.reinhardt@amd.com# Copyright (c) 2018 ARM Limited
45871Snate@binkert.org#
51762SN/A# The license below extends only to copyright in the software and shall
6955SN/A# not be construed as granting a license to any other intellectual
7955SN/A# property including but not limited to intellectual property relating
8955SN/A# to a hardware implementation of the functionality of the software
9955SN/A# licensed hereunder.  You may use the software subject to the license
10955SN/A# terms below provided that you ensure that this notice is replicated
11955SN/A# unmodified and in its entirety in all distributions of the software,
12955SN/A# modified or unmodified, in source code or in binary form.
13955SN/A#
14955SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
15955SN/A# All rights reserved.
16955SN/A#
17955SN/A# Redistribution and use in source and binary forms, with or without
18955SN/A# modification, are permitted provided that the following conditions are
19955SN/A# met: redistributions of source code must retain the above copyright
20955SN/A# notice, this list of conditions and the following disclaimer;
21955SN/A# redistributions in binary form must reproduce the above copyright
22955SN/A# notice, this list of conditions and the following disclaimer in the
23955SN/A# documentation and/or other materials provided with the distribution;
24955SN/A# neither the name of the copyright holders nor the names of its
25955SN/A# contributors may be used to endorse or promote products derived from
26955SN/A# this software without specific prior written permission.
27955SN/A#
28955SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29955SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
302665Ssaidi@eecs.umich.edu# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
312665Ssaidi@eecs.umich.edu# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
325863Snate@binkert.org# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
33955SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34955SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35955SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37955SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
388878Ssteve.reinhardt@amd.com# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
392632Sstever@eecs.umich.edu#
408878Ssteve.reinhardt@amd.com# Authors: Nathan Binkert
412632Sstever@eecs.umich.edu
42955SN/Afrom __future__ import print_function
438878Ssteve.reinhardt@amd.com
442632Sstever@eecs.umich.eduimport array
452761Sstever@eecs.umich.eduimport bisect
462632Sstever@eecs.umich.eduimport functools
472632Sstever@eecs.umich.eduimport imp
482632Sstever@eecs.umich.eduimport os
492761Sstever@eecs.umich.eduimport re
502761Sstever@eecs.umich.eduimport sys
512761Sstever@eecs.umich.eduimport zlib
528878Ssteve.reinhardt@amd.com
538878Ssteve.reinhardt@amd.comfrom os.path import basename, dirname, exists, isdir, isfile, join as joinpath
542761Sstever@eecs.umich.edu
552761Sstever@eecs.umich.eduimport SCons
562761Sstever@eecs.umich.edu
572761Sstever@eecs.umich.edufrom gem5_scons import Transform
582761Sstever@eecs.umich.edu
598878Ssteve.reinhardt@amd.com# This file defines how to build a particular configuration of gem5
608878Ssteve.reinhardt@amd.com# based on variable settings in the 'env' build environment.
612632Sstever@eecs.umich.edu
622632Sstever@eecs.umich.eduImport('*')
638878Ssteve.reinhardt@amd.com
648878Ssteve.reinhardt@amd.com# Children need to see the environment
652632Sstever@eecs.umich.eduExport('env')
66955SN/A
67955SN/Abuild_env = [(opt, env[opt]) for opt in export_vars]
68955SN/A
695863Snate@binkert.orgfrom m5.util import code_formatter, compareVersions
705863Snate@binkert.org
715863Snate@binkert.org########################################################################
725863Snate@binkert.org# Code for adding source files of various types
735863Snate@binkert.org#
745863Snate@binkert.org# When specifying a source file of some type, a set of tags can be
755863Snate@binkert.org# specified for that file.
765863Snate@binkert.org
775863Snate@binkert.orgclass SourceFilter(object):
785863Snate@binkert.org    def __init__(self, predicate):
795863Snate@binkert.org        self.predicate = predicate
808878Ssteve.reinhardt@amd.com
815863Snate@binkert.org    def __or__(self, other):
825863Snate@binkert.org        return SourceFilter(lambda tags: self.predicate(tags) or
835863Snate@binkert.org                                         other.predicate(tags))
845863Snate@binkert.org
855863Snate@binkert.org    def __and__(self, other):
865863Snate@binkert.org        return SourceFilter(lambda tags: self.predicate(tags) and
875863Snate@binkert.org                                         other.predicate(tags))
885863Snate@binkert.org
895863Snate@binkert.orgdef with_tags_that(predicate):
905863Snate@binkert.org    '''Return a list of sources with tags that satisfy a predicate.'''
915863Snate@binkert.org    return SourceFilter(predicate)
925863Snate@binkert.org
935863Snate@binkert.orgdef with_any_tags(*tags):
945863Snate@binkert.org    '''Return a list of sources with any of the supplied tags.'''
955863Snate@binkert.org    return SourceFilter(lambda stags: len(set(tags) & stags) > 0)
968878Ssteve.reinhardt@amd.com
975863Snate@binkert.orgdef with_all_tags(*tags):
985863Snate@binkert.org    '''Return a list of sources with all of the supplied tags.'''
995863Snate@binkert.org    return SourceFilter(lambda stags: set(tags) <= stags)
1006654Snate@binkert.org
101955SN/Adef with_tag(tag):
1025396Ssaidi@eecs.umich.edu    '''Return a list of sources with the supplied tag.'''
1035863Snate@binkert.org    return SourceFilter(lambda stags: tag in stags)
1045863Snate@binkert.org
1054202Sbinkertn@umich.edudef without_tags(*tags):
1065863Snate@binkert.org    '''Return a list of sources without any of the supplied tags.'''
1075863Snate@binkert.org    return SourceFilter(lambda stags: len(set(tags) & stags) == 0)
1085863Snate@binkert.org
1095863Snate@binkert.orgdef without_tag(tag):
110955SN/A    '''Return a list of sources with the supplied tag.'''
1116654Snate@binkert.org    return SourceFilter(lambda stags: tag not in stags)
1125273Sstever@gmail.com
1135871Snate@binkert.orgsource_filter_factories = {
1145273Sstever@gmail.com    'with_tags_that': with_tags_that,
1156655Snate@binkert.org    'with_any_tags': with_any_tags,
1168878Ssteve.reinhardt@amd.com    'with_all_tags': with_all_tags,
1176655Snate@binkert.org    'with_tag': with_tag,
1186655Snate@binkert.org    'without_tags': without_tags,
1199219Spower.jg@gmail.com    'without_tag': without_tag,
1206655Snate@binkert.org}
1215871Snate@binkert.org
1226654Snate@binkert.orgExport(source_filter_factories)
1238947Sandreas.hansson@arm.com
1245396Ssaidi@eecs.umich.educlass SourceList(list):
1258120Sgblack@eecs.umich.edu    def apply_filter(self, f):
1268120Sgblack@eecs.umich.edu        def match(source):
1278120Sgblack@eecs.umich.edu            return f.predicate(source.tags)
1288120Sgblack@eecs.umich.edu        return SourceList(filter(match, self))
1298120Sgblack@eecs.umich.edu
1308120Sgblack@eecs.umich.edu    def __getattr__(self, name):
1318120Sgblack@eecs.umich.edu        func = source_filter_factories.get(name, None)
1328120Sgblack@eecs.umich.edu        if not func:
1338879Ssteve.reinhardt@amd.com            raise AttributeError
1348879Ssteve.reinhardt@amd.com
1358879Ssteve.reinhardt@amd.com        @functools.wraps(func)
1368879Ssteve.reinhardt@amd.com        def wrapper(*args, **kwargs):
1378879Ssteve.reinhardt@amd.com            return self.apply_filter(func(*args, **kwargs))
1388879Ssteve.reinhardt@amd.com        return wrapper
1398879Ssteve.reinhardt@amd.com
1408879Ssteve.reinhardt@amd.comclass SourceMeta(type):
1418879Ssteve.reinhardt@amd.com    '''Meta class for source files that keeps track of all files of a
1428879Ssteve.reinhardt@amd.com    particular type.'''
1438879Ssteve.reinhardt@amd.com    def __init__(cls, name, bases, dict):
1448879Ssteve.reinhardt@amd.com        super(SourceMeta, cls).__init__(name, bases, dict)
1458879Ssteve.reinhardt@amd.com        cls.all = SourceList()
1468120Sgblack@eecs.umich.edu
1478120Sgblack@eecs.umich.educlass SourceFile(object):
1488120Sgblack@eecs.umich.edu    '''Base object that encapsulates the notion of a source file.
1498120Sgblack@eecs.umich.edu    This includes, the source node, target node, various manipulations
1508120Sgblack@eecs.umich.edu    of those.  A source file also specifies a set of tags which
1518120Sgblack@eecs.umich.edu    describing arbitrary properties of the source file.'''
1528120Sgblack@eecs.umich.edu    __metaclass__ = SourceMeta
1538120Sgblack@eecs.umich.edu
1548120Sgblack@eecs.umich.edu    static_objs = {}
1558120Sgblack@eecs.umich.edu    shared_objs = {}
1568120Sgblack@eecs.umich.edu
1578120Sgblack@eecs.umich.edu    def __init__(self, source, tags=None, add_tags=None):
1588120Sgblack@eecs.umich.edu        if tags is None:
1598120Sgblack@eecs.umich.edu            tags='gem5 lib'
1608879Ssteve.reinhardt@amd.com        if isinstance(tags, basestring):
1618879Ssteve.reinhardt@amd.com            tags = set([tags])
1628879Ssteve.reinhardt@amd.com        if not isinstance(tags, set):
1638879Ssteve.reinhardt@amd.com            tags = set(tags)
1648879Ssteve.reinhardt@amd.com        self.tags = tags
1658879Ssteve.reinhardt@amd.com
1668879Ssteve.reinhardt@amd.com        if add_tags:
1678879Ssteve.reinhardt@amd.com            if isinstance(add_tags, basestring):
1689227Sandreas.hansson@arm.com                add_tags = set([add_tags])
1699227Sandreas.hansson@arm.com            if not isinstance(add_tags, set):
1708879Ssteve.reinhardt@amd.com                add_tags = set(add_tags)
1718879Ssteve.reinhardt@amd.com            self.tags |= add_tags
1728879Ssteve.reinhardt@amd.com
1738879Ssteve.reinhardt@amd.com        tnode = source
1748120Sgblack@eecs.umich.edu        if not isinstance(source, SCons.Node.FS.File):
1758947Sandreas.hansson@arm.com            tnode = File(source)
1767816Ssteve.reinhardt@amd.com
1775871Snate@binkert.org        self.tnode = tnode
1785871Snate@binkert.org        self.snode = tnode.srcnode()
1796121Snate@binkert.org
1805871Snate@binkert.org        for base in type(self).__mro__:
1815871Snate@binkert.org            if issubclass(base, SourceFile):
1829119Sandreas.hansson@arm.com                base.all.append(self)
1839396Sandreas.hansson@arm.com
1849396Sandreas.hansson@arm.com    def static(self, env):
185955SN/A        key = (self.tnode, env['OBJSUFFIX'])
1869416SAndreas.Sandberg@ARM.com        if not key in self.static_objs:
1879416SAndreas.Sandberg@ARM.com            self.static_objs[key] = env.StaticObject(self.tnode)
1889416SAndreas.Sandberg@ARM.com        return self.static_objs[key]
1899416SAndreas.Sandberg@ARM.com
1909416SAndreas.Sandberg@ARM.com    def shared(self, env):
1919416SAndreas.Sandberg@ARM.com        key = (self.tnode, env['OBJSUFFIX'])
1929416SAndreas.Sandberg@ARM.com        if not key in self.shared_objs:
1935871Snate@binkert.org            self.shared_objs[key] = env.SharedObject(self.tnode)
1945871Snate@binkert.org        return self.shared_objs[key]
1959416SAndreas.Sandberg@ARM.com
1969416SAndreas.Sandberg@ARM.com    @property
1975871Snate@binkert.org    def filename(self):
198955SN/A        return str(self.tnode)
1996121Snate@binkert.org
2008881Smarc.orr@gmail.com    @property
2016121Snate@binkert.org    def dirname(self):
2026121Snate@binkert.org        return dirname(self.filename)
2031533SN/A
2049239Sandreas.hansson@arm.com    @property
2059239Sandreas.hansson@arm.com    def basename(self):
2069239Sandreas.hansson@arm.com        return basename(self.filename)
2079239Sandreas.hansson@arm.com
2089239Sandreas.hansson@arm.com    @property
2099239Sandreas.hansson@arm.com    def extname(self):
2109239Sandreas.hansson@arm.com        index = self.basename.rfind('.')
2119239Sandreas.hansson@arm.com        if index <= 0:
2129239Sandreas.hansson@arm.com            # dot files aren't extensions
2139239Sandreas.hansson@arm.com            return self.basename, None
2149239Sandreas.hansson@arm.com
2159239Sandreas.hansson@arm.com        return self.basename[:index], self.basename[index+1:]
2166655Snate@binkert.org
2176655Snate@binkert.org    def __lt__(self, other): return self.filename < other.filename
2186655Snate@binkert.org    def __le__(self, other): return self.filename <= other.filename
2196655Snate@binkert.org    def __gt__(self, other): return self.filename > other.filename
2205871Snate@binkert.org    def __ge__(self, other): return self.filename >= other.filename
2215871Snate@binkert.org    def __eq__(self, other): return self.filename == other.filename
2225863Snate@binkert.org    def __ne__(self, other): return self.filename != other.filename
2235871Snate@binkert.org
2248878Ssteve.reinhardt@amd.comdef blobToCpp(data, symbol, cpp_code, hpp_code=None, namespace=None):
2255871Snate@binkert.org    '''
2265871Snate@binkert.org    Convert bytes data into C++ .cpp and .hh uint8_t byte array
2275871Snate@binkert.org    code containing that binary data.
2285863Snate@binkert.org
2296121Snate@binkert.org    :param data: binary data to be converted to C++
2305863Snate@binkert.org    :param symbol: name of the symbol
2315871Snate@binkert.org    :param cpp_code: append the generated cpp_code to this object
2328336Ssteve.reinhardt@amd.com    :param hpp_code: append the generated hpp_code to this object
2338336Ssteve.reinhardt@amd.com                     If None, ignore it. Otherwise, also include it
2348336Ssteve.reinhardt@amd.com                     in the .cpp file.
2358336Ssteve.reinhardt@amd.com    :param namespace: namespace to put the symbol into. If None,
2364678Snate@binkert.org                      don't put the symbols into any namespace.
2378336Ssteve.reinhardt@amd.com    '''
2388336Ssteve.reinhardt@amd.com    symbol_len_declaration = 'const std::size_t {}_len'.format(symbol)
2398336Ssteve.reinhardt@amd.com    symbol_declaration = 'const std::uint8_t {}[]'.format(symbol)
2404678Snate@binkert.org    if hpp_code is not None:
2414678Snate@binkert.org        cpp_code('''\
2424678Snate@binkert.org#include "blobs/{}.hh"
2434678Snate@binkert.org'''.format(symbol))
2447827Snate@binkert.org        hpp_code('''\
2457827Snate@binkert.org#include <cstddef>
2468336Ssteve.reinhardt@amd.com#include <cstdint>
2474678Snate@binkert.org''')
2488336Ssteve.reinhardt@amd.com        if namespace is not None:
2498336Ssteve.reinhardt@amd.com            hpp_code('namespace {} {{'.format(namespace))
2508336Ssteve.reinhardt@amd.com        hpp_code('extern ' + symbol_len_declaration + ';')
2518336Ssteve.reinhardt@amd.com        hpp_code('extern ' + symbol_declaration + ';')
2528336Ssteve.reinhardt@amd.com        if namespace is not None:
2538336Ssteve.reinhardt@amd.com            hpp_code('}')
2545871Snate@binkert.org    if namespace is not None:
2555871Snate@binkert.org        cpp_code('namespace {} {{'.format(namespace))
2568336Ssteve.reinhardt@amd.com    if hpp_code is not None:
2578336Ssteve.reinhardt@amd.com        cpp_code(symbol_len_declaration + ' = {};'.format(len(data)))
2588336Ssteve.reinhardt@amd.com    cpp_code(symbol_declaration + ' = {')
2598336Ssteve.reinhardt@amd.com    cpp_code.indent()
2608336Ssteve.reinhardt@amd.com    step = 16
2615871Snate@binkert.org    for i in xrange(0, len(data), step):
2628336Ssteve.reinhardt@amd.com        x = array.array('B', data[i:i+step])
2638336Ssteve.reinhardt@amd.com        cpp_code(''.join('%d,' % d for d in x))
2648336Ssteve.reinhardt@amd.com    cpp_code.dedent()
2658336Ssteve.reinhardt@amd.com    cpp_code('};')
2668336Ssteve.reinhardt@amd.com    if namespace is not None:
2674678Snate@binkert.org        cpp_code('}')
2685871Snate@binkert.org
2694678Snate@binkert.orgdef Blob(blob_path, symbol):
2708336Ssteve.reinhardt@amd.com    '''
2718336Ssteve.reinhardt@amd.com    Embed an arbitrary blob into the gem5 executable,
2728336Ssteve.reinhardt@amd.com    and make it accessible to C++ as a byte array.
2738336Ssteve.reinhardt@amd.com    '''
2748336Ssteve.reinhardt@amd.com    blob_path = os.path.abspath(blob_path)
2758336Ssteve.reinhardt@amd.com    blob_out_dir = os.path.join(env['BUILDDIR'], 'blobs')
2768336Ssteve.reinhardt@amd.com    path_noext = joinpath(blob_out_dir, symbol)
2778336Ssteve.reinhardt@amd.com    cpp_path = path_noext + '.cc'
2788336Ssteve.reinhardt@amd.com    hpp_path = path_noext + '.hh'
2798336Ssteve.reinhardt@amd.com    def embedBlob(target, source, env):
2808336Ssteve.reinhardt@amd.com        data = file(str(source[0]), 'r').read()
2818336Ssteve.reinhardt@amd.com        cpp_code = code_formatter()
2828336Ssteve.reinhardt@amd.com        hpp_code = code_formatter()
2838336Ssteve.reinhardt@amd.com        blobToCpp(data, symbol, cpp_code, hpp_code, namespace='Blobs')
2848336Ssteve.reinhardt@amd.com        cpp_path = str(target[0])
2858336Ssteve.reinhardt@amd.com        hpp_path = str(target[1])
2868336Ssteve.reinhardt@amd.com        cpp_dir = os.path.split(cpp_path)[0]
2875871Snate@binkert.org        if not os.path.exists(cpp_dir):
2886121Snate@binkert.org            os.makedirs(cpp_dir)
289955SN/A        cpp_code.write(cpp_path)
290955SN/A        hpp_code.write(hpp_path)
2912632Sstever@eecs.umich.edu    env.Command([cpp_path, hpp_path], blob_path,
2922632Sstever@eecs.umich.edu                MakeAction(embedBlob, Transform("EMBED BLOB")))
293955SN/A    Source(cpp_path)
294955SN/A
295955SN/Adef GdbXml(xml_id, symbol):
296955SN/A    Blob(joinpath(gdb_xml_dir, xml_id), symbol)
2978878Ssteve.reinhardt@amd.com
298955SN/Aclass Source(SourceFile):
2992632Sstever@eecs.umich.edu    ungrouped_tag = 'No link group'
3002632Sstever@eecs.umich.edu    source_groups = set()
3012632Sstever@eecs.umich.edu
3022632Sstever@eecs.umich.edu    _current_group_tag = ungrouped_tag
3032632Sstever@eecs.umich.edu
3042632Sstever@eecs.umich.edu    @staticmethod
3052632Sstever@eecs.umich.edu    def link_group_tag(group):
3068268Ssteve.reinhardt@amd.com        return 'link group: %s' % group
3078268Ssteve.reinhardt@amd.com
3088268Ssteve.reinhardt@amd.com    @classmethod
3098268Ssteve.reinhardt@amd.com    def set_group(cls, group):
3108268Ssteve.reinhardt@amd.com        new_tag = Source.link_group_tag(group)
3118268Ssteve.reinhardt@amd.com        Source._current_group_tag = new_tag
3128268Ssteve.reinhardt@amd.com        Source.source_groups.add(group)
3132632Sstever@eecs.umich.edu
3142632Sstever@eecs.umich.edu    def _add_link_group_tag(self):
3152632Sstever@eecs.umich.edu        self.tags.add(Source._current_group_tag)
3162632Sstever@eecs.umich.edu
3178268Ssteve.reinhardt@amd.com    '''Add a c/c++ source file to the build'''
3182632Sstever@eecs.umich.edu    def __init__(self, source, tags=None, add_tags=None):
3198268Ssteve.reinhardt@amd.com        '''specify the source file, and any tags'''
3208268Ssteve.reinhardt@amd.com        super(Source, self).__init__(source, tags, add_tags)
3218268Ssteve.reinhardt@amd.com        self._add_link_group_tag()
3228268Ssteve.reinhardt@amd.com
3233718Sstever@eecs.umich.educlass PySource(SourceFile):
3242634Sstever@eecs.umich.edu    '''Add a python source file to the named package'''
3252634Sstever@eecs.umich.edu    invalid_sym_char = re.compile('[^A-z0-9_]')
3265863Snate@binkert.org    modules = {}
3272638Sstever@eecs.umich.edu    tnodes = {}
3288268Ssteve.reinhardt@amd.com    symnames = {}
3292632Sstever@eecs.umich.edu
3302632Sstever@eecs.umich.edu    def __init__(self, package, source, tags=None, add_tags=None):
3312632Sstever@eecs.umich.edu        '''specify the python package, the source file, and any tags'''
3322632Sstever@eecs.umich.edu        super(PySource, self).__init__(source, tags, add_tags)
3332632Sstever@eecs.umich.edu
3341858SN/A        modname,ext = self.extname
3353716Sstever@eecs.umich.edu        assert ext == 'py'
3362638Sstever@eecs.umich.edu
3372638Sstever@eecs.umich.edu        if package:
3382638Sstever@eecs.umich.edu            path = package.split('.')
3392638Sstever@eecs.umich.edu        else:
3402638Sstever@eecs.umich.edu            path = []
3412638Sstever@eecs.umich.edu
3422638Sstever@eecs.umich.edu        modpath = path[:]
3435863Snate@binkert.org        if modname != '__init__':
3445863Snate@binkert.org            modpath += [ modname ]
3455863Snate@binkert.org        modpath = '.'.join(modpath)
346955SN/A
3475341Sstever@gmail.com        arcpath = path + [ self.basename ]
3485341Sstever@gmail.com        abspath = self.snode.abspath
3495863Snate@binkert.org        if not exists(abspath):
3507756SAli.Saidi@ARM.com            abspath = self.tnode.abspath
3515341Sstever@gmail.com
3526121Snate@binkert.org        self.package = package
3534494Ssaidi@eecs.umich.edu        self.modname = modname
3546121Snate@binkert.org        self.modpath = modpath
3551105SN/A        self.arcname = joinpath(*arcpath)
3562667Sstever@eecs.umich.edu        self.abspath = abspath
3572667Sstever@eecs.umich.edu        self.compiled = File(self.filename + 'c')
3582667Sstever@eecs.umich.edu        self.cpp = File(self.filename + '.cc')
3592667Sstever@eecs.umich.edu        self.symname = PySource.invalid_sym_char.sub('_', modpath)
3606121Snate@binkert.org
3612667Sstever@eecs.umich.edu        PySource.modules[modpath] = self
3625341Sstever@gmail.com        PySource.tnodes[self.tnode] = self
3635863Snate@binkert.org        PySource.symnames[self.symname] = self
3645341Sstever@gmail.com
3655341Sstever@gmail.comclass SimObject(PySource):
3665341Sstever@gmail.com    '''Add a SimObject python file as a python source object and add
3678120Sgblack@eecs.umich.edu    it to a list of sim object modules'''
3685341Sstever@gmail.com
3698120Sgblack@eecs.umich.edu    fixed = False
3705341Sstever@gmail.com    modnames = []
3718120Sgblack@eecs.umich.edu
3726121Snate@binkert.org    def __init__(self, source, tags=None, add_tags=None):
3736121Snate@binkert.org        '''Specify the source file and any tags (automatically in
3748980Ssteve.reinhardt@amd.com        the m5.objects package)'''
3759396Sandreas.hansson@arm.com        super(SimObject, self).__init__('m5.objects', source, tags, add_tags)
3765397Ssaidi@eecs.umich.edu        if self.fixed:
3775397Ssaidi@eecs.umich.edu            raise AttributeError, "Too late to call SimObject now."
3787727SAli.Saidi@ARM.com
3798268Ssteve.reinhardt@amd.com        bisect.insort_right(SimObject.modnames, self.modname)
3806168Snate@binkert.org
3815341Sstever@gmail.comclass ProtoBuf(SourceFile):
3828120Sgblack@eecs.umich.edu    '''Add a Protocol Buffer to build'''
3838120Sgblack@eecs.umich.edu
3848120Sgblack@eecs.umich.edu    def __init__(self, source, tags=None, add_tags=None):
3856814Sgblack@eecs.umich.edu        '''Specify the source file, and any tags'''
3865863Snate@binkert.org        super(ProtoBuf, self).__init__(source, tags, add_tags)
3878120Sgblack@eecs.umich.edu
3885341Sstever@gmail.com        # Get the file name and the extension
3895863Snate@binkert.org        modname,ext = self.extname
3908268Ssteve.reinhardt@amd.com        assert ext == 'proto'
3916121Snate@binkert.org
3926121Snate@binkert.org        # Currently, we stick to generating the C++ headers, so we
3938268Ssteve.reinhardt@amd.com        # only need to track the source and header.
3945742Snate@binkert.org        self.cc_file = File(modname + '.pb.cc')
3955742Snate@binkert.org        self.hh_file = File(modname + '.pb.h')
3965341Sstever@gmail.com
3975742Snate@binkert.org
3985742Snate@binkert.orgexectuable_classes = []
3995341Sstever@gmail.comclass ExecutableMeta(type):
4006017Snate@binkert.org    '''Meta class for Executables.'''
4016121Snate@binkert.org    all = []
4026017Snate@binkert.org
4037816Ssteve.reinhardt@amd.com    def __init__(cls, name, bases, d):
4047756SAli.Saidi@ARM.com        if not d.pop('abstract', False):
4057756SAli.Saidi@ARM.com            ExecutableMeta.all.append(cls)
4067756SAli.Saidi@ARM.com        super(ExecutableMeta, cls).__init__(name, bases, d)
4077756SAli.Saidi@ARM.com
4087756SAli.Saidi@ARM.com        cls.all = []
4097756SAli.Saidi@ARM.com
4107756SAli.Saidi@ARM.comclass Executable(object):
4117756SAli.Saidi@ARM.com    '''Base class for creating an executable from sources.'''
4127816Ssteve.reinhardt@amd.com    __metaclass__ = ExecutableMeta
4137816Ssteve.reinhardt@amd.com
4147816Ssteve.reinhardt@amd.com    abstract = True
4157816Ssteve.reinhardt@amd.com
4167816Ssteve.reinhardt@amd.com    def __init__(self, target, *srcs_and_filts):
4177816Ssteve.reinhardt@amd.com        '''Specify the target name and any sources. Sources that are
4187816Ssteve.reinhardt@amd.com        not SourceFiles are evalued with Source().'''
4197816Ssteve.reinhardt@amd.com        super(Executable, self).__init__()
4207816Ssteve.reinhardt@amd.com        self.all.append(self)
4217816Ssteve.reinhardt@amd.com        self.target = target
4227756SAli.Saidi@ARM.com
4237816Ssteve.reinhardt@amd.com        isFilter = lambda arg: isinstance(arg, SourceFilter)
4247816Ssteve.reinhardt@amd.com        self.filters = filter(isFilter, srcs_and_filts)
4257816Ssteve.reinhardt@amd.com        sources = filter(lambda a: not isFilter(a), srcs_and_filts)
4267816Ssteve.reinhardt@amd.com
4277816Ssteve.reinhardt@amd.com        srcs = SourceList()
4287816Ssteve.reinhardt@amd.com        for src in sources:
4297816Ssteve.reinhardt@amd.com            if not isinstance(src, SourceFile):
4307816Ssteve.reinhardt@amd.com                src = Source(src, tags=[])
4317816Ssteve.reinhardt@amd.com            srcs.append(src)
4327816Ssteve.reinhardt@amd.com
4337816Ssteve.reinhardt@amd.com        self.sources = srcs
4347816Ssteve.reinhardt@amd.com        self.dir = Dir('.')
4357816Ssteve.reinhardt@amd.com
4367816Ssteve.reinhardt@amd.com    def path(self, env):
4377816Ssteve.reinhardt@amd.com        return self.dir.File(self.target + '.' + env['EXE_SUFFIX'])
4387816Ssteve.reinhardt@amd.com
4397816Ssteve.reinhardt@amd.com    def srcs_to_objs(self, env, sources):
4407816Ssteve.reinhardt@amd.com        return list([ s.static(env) for s in sources ])
4417816Ssteve.reinhardt@amd.com
4427816Ssteve.reinhardt@amd.com    @classmethod
4437816Ssteve.reinhardt@amd.com    def declare_all(cls, env):
4447816Ssteve.reinhardt@amd.com        return list([ instance.declare(env) for instance in cls.all ])
4457816Ssteve.reinhardt@amd.com
4467816Ssteve.reinhardt@amd.com    def declare(self, env, objs=None):
4477816Ssteve.reinhardt@amd.com        if objs is None:
4487816Ssteve.reinhardt@amd.com            objs = self.srcs_to_objs(env, self.sources)
4497816Ssteve.reinhardt@amd.com
4507816Ssteve.reinhardt@amd.com        env = env.Clone()
4517816Ssteve.reinhardt@amd.com        env['BIN_RPATH_PREFIX'] = os.path.relpath(
4527816Ssteve.reinhardt@amd.com                env['BUILDDIR'], self.path(env).dir.abspath)
4537816Ssteve.reinhardt@amd.com
4547816Ssteve.reinhardt@amd.com        if env['STRIP_EXES']:
4557816Ssteve.reinhardt@amd.com            stripped = self.path(env)
4567816Ssteve.reinhardt@amd.com            unstripped = env.File(str(stripped) + '.unstripped')
4577816Ssteve.reinhardt@amd.com            if sys.platform == 'sunos5':
4587816Ssteve.reinhardt@amd.com                cmd = 'cp $SOURCE $TARGET; strip $TARGET'
4597816Ssteve.reinhardt@amd.com            else:
4607816Ssteve.reinhardt@amd.com                cmd = 'strip $SOURCE -o $TARGET'
4617816Ssteve.reinhardt@amd.com            env.Program(unstripped, objs)
4627816Ssteve.reinhardt@amd.com            return env.Command(stripped, unstripped,
4637816Ssteve.reinhardt@amd.com                               MakeAction(cmd, Transform("STRIP")))
4647816Ssteve.reinhardt@amd.com        else:
4657816Ssteve.reinhardt@amd.com            return env.Program(self.path(env), objs)
4667816Ssteve.reinhardt@amd.com
4677816Ssteve.reinhardt@amd.comclass UnitTest(Executable):
4687816Ssteve.reinhardt@amd.com    '''Create a UnitTest'''
4697816Ssteve.reinhardt@amd.com    def __init__(self, target, *srcs_and_filts, **kwargs):
4707816Ssteve.reinhardt@amd.com        super(UnitTest, self).__init__(target, *srcs_and_filts)
4717816Ssteve.reinhardt@amd.com
4727816Ssteve.reinhardt@amd.com        self.main = kwargs.get('main', False)
4737816Ssteve.reinhardt@amd.com
4747816Ssteve.reinhardt@amd.com    def declare(self, env):
4757816Ssteve.reinhardt@amd.com        sources = list(self.sources)
4767816Ssteve.reinhardt@amd.com        for f in self.filters:
4777816Ssteve.reinhardt@amd.com            sources += Source.all.apply_filter(f)
4787816Ssteve.reinhardt@amd.com        objs = self.srcs_to_objs(env, sources) + env['STATIC_OBJS']
4797816Ssteve.reinhardt@amd.com        if self.main:
4807816Ssteve.reinhardt@amd.com            objs += env['MAIN_OBJS']
4817816Ssteve.reinhardt@amd.com        return super(UnitTest, self).declare(env, objs)
4827816Ssteve.reinhardt@amd.com
4837816Ssteve.reinhardt@amd.comclass GTest(Executable):
4848947Sandreas.hansson@arm.com    '''Create a unit test based on the google test framework.'''
4858947Sandreas.hansson@arm.com    all = []
4867756SAli.Saidi@ARM.com    def __init__(self, *srcs_and_filts, **kwargs):
4878120Sgblack@eecs.umich.edu        super(GTest, self).__init__(*srcs_and_filts)
4887756SAli.Saidi@ARM.com
4897756SAli.Saidi@ARM.com        self.skip_lib = kwargs.pop('skip_lib', False)
4907756SAli.Saidi@ARM.com
4917756SAli.Saidi@ARM.com    @classmethod
4927816Ssteve.reinhardt@amd.com    def declare_all(cls, env):
4937816Ssteve.reinhardt@amd.com        env = env.Clone()
4947816Ssteve.reinhardt@amd.com        env.Append(LIBS=env['GTEST_LIBS'])
4957816Ssteve.reinhardt@amd.com        env.Append(CPPFLAGS=env['GTEST_CPPFLAGS'])
4967816Ssteve.reinhardt@amd.com        env['GTEST_LIB_SOURCES'] = Source.all.with_tag('gtest lib')
4977816Ssteve.reinhardt@amd.com        env['GTEST_OUT_DIR'] = \
4987816Ssteve.reinhardt@amd.com            Dir(env['BUILDDIR']).Dir('unittests.' + env['EXE_SUFFIX'])
4997816Ssteve.reinhardt@amd.com        return super(GTest, cls).declare_all(env)
5007816Ssteve.reinhardt@amd.com
5017816Ssteve.reinhardt@amd.com    def declare(self, env):
5027756SAli.Saidi@ARM.com        sources = list(self.sources)
5037756SAli.Saidi@ARM.com        if not self.skip_lib:
5049227Sandreas.hansson@arm.com            sources += env['GTEST_LIB_SOURCES']
5059227Sandreas.hansson@arm.com        for f in self.filters:
5069227Sandreas.hansson@arm.com            sources += Source.all.apply_filter(f)
5079227Sandreas.hansson@arm.com        objs = self.srcs_to_objs(env, sources)
5086654Snate@binkert.org
5096654Snate@binkert.org        binary = super(GTest, self).declare(env, objs)
5105871Snate@binkert.org
5116121Snate@binkert.org        out_dir = env['GTEST_OUT_DIR']
5128946Sandreas.hansson@arm.com        xml_file = out_dir.Dir(str(self.dir)).File(self.target + '.xml')
5139419Sandreas.hansson@arm.com        AlwaysBuild(env.Command(xml_file, binary,
5143940Ssaidi@eecs.umich.edu            "${SOURCES[0]} --gtest_output=xml:${TARGETS[0]}"))
5153918Ssaidi@eecs.umich.edu
5163918Ssaidi@eecs.umich.edu        return binary
5171858SN/A
5189556Sandreas.hansson@arm.comclass Gem5(Executable):
5199556Sandreas.hansson@arm.com    '''Create a gem5 executable.'''
5209556Sandreas.hansson@arm.com
5219556Sandreas.hansson@arm.com    def __init__(self, target):
5229556Sandreas.hansson@arm.com        super(Gem5, self).__init__(target)
5239556Sandreas.hansson@arm.com
5249556Sandreas.hansson@arm.com    def declare(self, env):
5259556Sandreas.hansson@arm.com        objs = env['MAIN_OBJS'] + env['STATIC_OBJS']
5269556Sandreas.hansson@arm.com        return super(Gem5, self).declare(env, objs)
5279556Sandreas.hansson@arm.com
5289556Sandreas.hansson@arm.com
5299556Sandreas.hansson@arm.com# Children should have access
5309556Sandreas.hansson@arm.comExport('Blob')
5319556Sandreas.hansson@arm.comExport('GdbXml')
5329556Sandreas.hansson@arm.comExport('Source')
5339556Sandreas.hansson@arm.comExport('PySource')
5349556Sandreas.hansson@arm.comExport('SimObject')
5359556Sandreas.hansson@arm.comExport('ProtoBuf')
5369556Sandreas.hansson@arm.comExport('Executable')
5379556Sandreas.hansson@arm.comExport('UnitTest')
5389556Sandreas.hansson@arm.comExport('GTest')
5399556Sandreas.hansson@arm.com
5409556Sandreas.hansson@arm.com########################################################################
5419556Sandreas.hansson@arm.com#
5429556Sandreas.hansson@arm.com# Debug Flags
5439556Sandreas.hansson@arm.com#
5449556Sandreas.hansson@arm.comdebug_flags = {}
5459556Sandreas.hansson@arm.comdef DebugFlag(name, desc=None):
5469556Sandreas.hansson@arm.com    if name in debug_flags:
5479556Sandreas.hansson@arm.com        raise AttributeError, "Flag %s already specified" % name
5489556Sandreas.hansson@arm.com    debug_flags[name] = (name, (), desc)
5499556Sandreas.hansson@arm.com
5506121Snate@binkert.orgdef CompoundFlag(name, flags, desc=None):
5519420Sandreas.hansson@arm.com    if name in debug_flags:
5529420Sandreas.hansson@arm.com        raise AttributeError, "Flag %s already specified" % name
5539420Sandreas.hansson@arm.com
5549420Sandreas.hansson@arm.com    compound = tuple(flags)
5559420Sandreas.hansson@arm.com    debug_flags[name] = (name, compound, desc)
5569420Sandreas.hansson@arm.com
5579420Sandreas.hansson@arm.comExport('DebugFlag')
5589420Sandreas.hansson@arm.comExport('CompoundFlag')
5599420Sandreas.hansson@arm.com
5609420Sandreas.hansson@arm.com########################################################################
5619420Sandreas.hansson@arm.com#
5627618SAli.Saidi@arm.com# Set some compiler variables
5637618SAli.Saidi@arm.com#
5647618SAli.Saidi@arm.com
5657739Sgblack@eecs.umich.edu# Include file paths are rooted in this directory.  SCons will
5669227Sandreas.hansson@arm.com# automatically expand '.' to refer to both the source directory and
5679227Sandreas.hansson@arm.com# the corresponding build directory to pick up generated include
5689227Sandreas.hansson@arm.com# files.
5699227Sandreas.hansson@arm.comenv.Append(CPPPATH=Dir('.'))
5709227Sandreas.hansson@arm.com
5719227Sandreas.hansson@arm.comfor extra_dir in extras_dir_list:
5729227Sandreas.hansson@arm.com    env.Append(CPPPATH=Dir(extra_dir))
5739227Sandreas.hansson@arm.com
5749227Sandreas.hansson@arm.com# Workaround for bug in SCons version > 0.97d20071212
5759227Sandreas.hansson@arm.com# Scons bug id: 2006 gem5 Bug id: 308
5769227Sandreas.hansson@arm.comfor root, dirs, files in os.walk(base_dir, topdown=True):
5779227Sandreas.hansson@arm.com    Dir(root[len(base_dir) + 1:])
5789227Sandreas.hansson@arm.com
5799227Sandreas.hansson@arm.com########################################################################
5809227Sandreas.hansson@arm.com#
5819227Sandreas.hansson@arm.com# Walk the tree and execute all SConscripts in subdirectories
5829227Sandreas.hansson@arm.com#
5839227Sandreas.hansson@arm.com
5848737Skoansin.tan@gmail.comhere = Dir('.').srcnode().abspath
5859420Sandreas.hansson@arm.comfor root, dirs, files in os.walk(base_dir, topdown=True):
5869420Sandreas.hansson@arm.com    if root == here:
5879420Sandreas.hansson@arm.com        # we don't want to recurse back into this SConscript
5888737Skoansin.tan@gmail.com        continue
5898737Skoansin.tan@gmail.com
5908737Skoansin.tan@gmail.com    if 'SConscript' in files:
5918737Skoansin.tan@gmail.com        build_dir = joinpath(env['BUILDDIR'], root[len(base_dir) + 1:])
5928737Skoansin.tan@gmail.com        Source.set_group(build_dir)
5938737Skoansin.tan@gmail.com        SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
5948737Skoansin.tan@gmail.com
5958737Skoansin.tan@gmail.comfor extra_dir in extras_dir_list:
5968737Skoansin.tan@gmail.com    prefix_len = len(dirname(extra_dir)) + 1
5978737Skoansin.tan@gmail.com
5988737Skoansin.tan@gmail.com    # Also add the corresponding build directory to pick up generated
5998737Skoansin.tan@gmail.com    # include files.
6009556Sandreas.hansson@arm.com    env.Append(CPPPATH=Dir(joinpath(env['BUILDDIR'], extra_dir[prefix_len:])))
6019556Sandreas.hansson@arm.com
6029556Sandreas.hansson@arm.com    for root, dirs, files in os.walk(extra_dir, topdown=True):
6039556Sandreas.hansson@arm.com        # if build lives in the extras directory, don't walk down it
6049556Sandreas.hansson@arm.com        if 'build' in dirs:
6059556Sandreas.hansson@arm.com            dirs.remove('build')
6069556Sandreas.hansson@arm.com
6079556Sandreas.hansson@arm.com        if 'SConscript' in files:
6089556Sandreas.hansson@arm.com            build_dir = joinpath(env['BUILDDIR'], root[prefix_len:])
6099556Sandreas.hansson@arm.com            SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
6109420Sandreas.hansson@arm.com
6119420Sandreas.hansson@arm.comfor opt in export_vars:
6129420Sandreas.hansson@arm.com    env.ConfigFile(opt)
6139420Sandreas.hansson@arm.com
6149420Sandreas.hansson@arm.comdef makeTheISA(source, target, env):
6159420Sandreas.hansson@arm.com    isas = [ src.get_contents() for src in source ]
6169420Sandreas.hansson@arm.com    target_isa = env['TARGET_ISA']
6179420Sandreas.hansson@arm.com    def define(isa):
6189420Sandreas.hansson@arm.com        return isa.upper() + '_ISA'
6199420Sandreas.hansson@arm.com
6208946Sandreas.hansson@arm.com    def namespace(isa):
6213918Ssaidi@eecs.umich.edu        return isa[0].upper() + isa[1:].lower() + 'ISA'
6229068SAli.Saidi@ARM.com
6239068SAli.Saidi@ARM.com
6249068SAli.Saidi@ARM.com    code = code_formatter()
6259068SAli.Saidi@ARM.com    code('''\
6269068SAli.Saidi@ARM.com#ifndef __CONFIG_THE_ISA_HH__
6279068SAli.Saidi@ARM.com#define __CONFIG_THE_ISA_HH__
6289068SAli.Saidi@ARM.com
6299068SAli.Saidi@ARM.com''')
6309068SAli.Saidi@ARM.com
6319419Sandreas.hansson@arm.com    # create defines for the preprocessing and compile-time determination
6329068SAli.Saidi@ARM.com    for i,isa in enumerate(isas):
6339068SAli.Saidi@ARM.com        code('#define $0 $1', define(isa), i + 1)
6349068SAli.Saidi@ARM.com    code()
6359068SAli.Saidi@ARM.com
6369068SAli.Saidi@ARM.com    # create an enum for any run-time determination of the ISA, we
6379068SAli.Saidi@ARM.com    # reuse the same name as the namespaces
6383918Ssaidi@eecs.umich.edu    code('enum class Arch {')
6393918Ssaidi@eecs.umich.edu    for i,isa in enumerate(isas):
6406157Snate@binkert.org        if i + 1 == len(isas):
6416157Snate@binkert.org            code('  $0 = $1', namespace(isa), define(isa))
6426157Snate@binkert.org        else:
6436157Snate@binkert.org            code('  $0 = $1,', namespace(isa), define(isa))
6445397Ssaidi@eecs.umich.edu    code('};')
6455397Ssaidi@eecs.umich.edu
6466121Snate@binkert.org    code('''
6476121Snate@binkert.org
6486121Snate@binkert.org#define THE_ISA ${{define(target_isa)}}
6496121Snate@binkert.org#define TheISA ${{namespace(target_isa)}}
6506121Snate@binkert.org#define THE_ISA_STR "${{target_isa}}"
6516121Snate@binkert.org
6525397Ssaidi@eecs.umich.edu#endif // __CONFIG_THE_ISA_HH__''')
6531851SN/A
6541851SN/A    code.write(str(target[0]))
6557739Sgblack@eecs.umich.edu
656955SN/Aenv.Command('config/the_isa.hh', map(Value, all_isa_list),
6579396Sandreas.hansson@arm.com            MakeAction(makeTheISA, Transform("CFG ISA", 0)))
6589396Sandreas.hansson@arm.com
6599396Sandreas.hansson@arm.comdef makeTheGPUISA(source, target, env):
6609396Sandreas.hansson@arm.com    isas = [ src.get_contents() for src in source ]
6619396Sandreas.hansson@arm.com    target_gpu_isa = env['TARGET_GPU_ISA']
6629396Sandreas.hansson@arm.com    def define(isa):
6639396Sandreas.hansson@arm.com        return isa.upper() + '_ISA'
6649396Sandreas.hansson@arm.com
6659396Sandreas.hansson@arm.com    def namespace(isa):
6669396Sandreas.hansson@arm.com        return isa[0].upper() + isa[1:].lower() + 'ISA'
6679396Sandreas.hansson@arm.com
6689396Sandreas.hansson@arm.com
6699396Sandreas.hansson@arm.com    code = code_formatter()
6709396Sandreas.hansson@arm.com    code('''\
6719396Sandreas.hansson@arm.com#ifndef __CONFIG_THE_GPU_ISA_HH__
6729396Sandreas.hansson@arm.com#define __CONFIG_THE_GPU_ISA_HH__
6739477Sandreas.hansson@arm.com
6749477Sandreas.hansson@arm.com''')
6759477Sandreas.hansson@arm.com
6769477Sandreas.hansson@arm.com    # create defines for the preprocessing and compile-time determination
6779477Sandreas.hansson@arm.com    for i,isa in enumerate(isas):
6789477Sandreas.hansson@arm.com        code('#define $0 $1', define(isa), i + 1)
6799477Sandreas.hansson@arm.com    code()
6809477Sandreas.hansson@arm.com
6819477Sandreas.hansson@arm.com    # create an enum for any run-time determination of the ISA, we
6829477Sandreas.hansson@arm.com    # reuse the same name as the namespaces
6839477Sandreas.hansson@arm.com    code('enum class GPUArch {')
6849477Sandreas.hansson@arm.com    for i,isa in enumerate(isas):
6859477Sandreas.hansson@arm.com        if i + 1 == len(isas):
6869477Sandreas.hansson@arm.com            code('  $0 = $1', namespace(isa), define(isa))
6879477Sandreas.hansson@arm.com        else:
6889477Sandreas.hansson@arm.com            code('  $0 = $1,', namespace(isa), define(isa))
6899477Sandreas.hansson@arm.com    code('};')
6909477Sandreas.hansson@arm.com
6919477Sandreas.hansson@arm.com    code('''
6929477Sandreas.hansson@arm.com
6939477Sandreas.hansson@arm.com#define THE_GPU_ISA ${{define(target_gpu_isa)}}
6949477Sandreas.hansson@arm.com#define TheGpuISA ${{namespace(target_gpu_isa)}}
6959396Sandreas.hansson@arm.com#define THE_GPU_ISA_STR "${{target_gpu_isa}}"
6963053Sstever@eecs.umich.edu
6976121Snate@binkert.org#endif // __CONFIG_THE_GPU_ISA_HH__''')
6983053Sstever@eecs.umich.edu
6993053Sstever@eecs.umich.edu    code.write(str(target[0]))
7003053Sstever@eecs.umich.edu
7013053Sstever@eecs.umich.eduenv.Command('config/the_gpu_isa.hh', map(Value, all_gpu_isa_list),
7023053Sstever@eecs.umich.edu            MakeAction(makeTheGPUISA, Transform("CFG ISA", 0)))
7039072Sandreas.hansson@arm.com
7043053Sstever@eecs.umich.edu########################################################################
7054742Sstever@eecs.umich.edu#
7064742Sstever@eecs.umich.edu# Prevent any SimObjects from being added after this point, they
7073053Sstever@eecs.umich.edu# should all have been added in the SConscripts above
7083053Sstever@eecs.umich.edu#
7093053Sstever@eecs.umich.eduSimObject.fixed = True
7108960Ssteve.reinhardt@amd.com
7116654Snate@binkert.orgclass DictImporter(object):
7123053Sstever@eecs.umich.edu    '''This importer takes a dictionary of arbitrary module names that
7133053Sstever@eecs.umich.edu    map to arbitrary filenames.'''
7143053Sstever@eecs.umich.edu    def __init__(self, modules):
7153053Sstever@eecs.umich.edu        self.modules = modules
7169585Sandreas@sandberg.pp.se        self.installed = set()
7179585Sandreas@sandberg.pp.se
7189585Sandreas@sandberg.pp.se    def __del__(self):
7199585Sandreas@sandberg.pp.se        self.unload()
7209585Sandreas@sandberg.pp.se
7219585Sandreas@sandberg.pp.se    def unload(self):
7229585Sandreas@sandberg.pp.se        import sys
7239585Sandreas@sandberg.pp.se        for module in self.installed:
7249585Sandreas@sandberg.pp.se            del sys.modules[module]
7252667Sstever@eecs.umich.edu        self.installed = set()
7264554Sbinkertn@umich.edu
7276121Snate@binkert.org    def find_module(self, fullname, path):
7282667Sstever@eecs.umich.edu        if fullname == 'm5.defines':
7294554Sbinkertn@umich.edu            return self
7304554Sbinkertn@umich.edu
7314554Sbinkertn@umich.edu        if fullname == 'm5.objects':
7326121Snate@binkert.org            return self
7334554Sbinkertn@umich.edu
7344554Sbinkertn@umich.edu        if fullname.startswith('_m5'):
7354554Sbinkertn@umich.edu            return None
7364781Snate@binkert.org
7374554Sbinkertn@umich.edu        source = self.modules.get(fullname, None)
7384554Sbinkertn@umich.edu        if source is not None and fullname.startswith('m5.objects'):
7392667Sstever@eecs.umich.edu            return self
7404554Sbinkertn@umich.edu
7414554Sbinkertn@umich.edu        return None
7424554Sbinkertn@umich.edu
7434554Sbinkertn@umich.edu    def load_module(self, fullname):
7442667Sstever@eecs.umich.edu        mod = imp.new_module(fullname)
7454554Sbinkertn@umich.edu        sys.modules[fullname] = mod
7462667Sstever@eecs.umich.edu        self.installed.add(fullname)
7474554Sbinkertn@umich.edu
7486121Snate@binkert.org        mod.__loader__ = self
7492667Sstever@eecs.umich.edu        if fullname == 'm5.objects':
7505522Snate@binkert.org            mod.__path__ = fullname.split('.')
7515522Snate@binkert.org            return mod
7525522Snate@binkert.org
7535522Snate@binkert.org        if fullname == 'm5.defines':
7545522Snate@binkert.org            mod.__dict__['buildEnv'] = m5.util.SmartDict(build_env)
7555522Snate@binkert.org            return mod
7565522Snate@binkert.org
7575522Snate@binkert.org        source = self.modules[fullname]
7585522Snate@binkert.org        if source.modname == '__init__':
7595522Snate@binkert.org            mod.__path__ = source.modpath
7605522Snate@binkert.org        mod.__file__ = source.abspath
7615522Snate@binkert.org
7625522Snate@binkert.org        exec file(source.abspath, 'r') in mod.__dict__
7635522Snate@binkert.org
7645522Snate@binkert.org        return mod
7655522Snate@binkert.org
7665522Snate@binkert.orgimport m5.SimObject
7675522Snate@binkert.orgimport m5.params
7685522Snate@binkert.orgfrom m5.util import code_formatter
7695522Snate@binkert.org
7705522Snate@binkert.orgm5.SimObject.clear()
7715522Snate@binkert.orgm5.params.clear()
7725522Snate@binkert.org
7735522Snate@binkert.org# install the python importer so we can grab stuff from the source
7745522Snate@binkert.org# tree itself.  We can't have SimObjects added after this point or
7755522Snate@binkert.org# else we won't know about them for the rest of the stuff.
7762638Sstever@eecs.umich.eduimporter = DictImporter(PySource.modules)
7772638Sstever@eecs.umich.edusys.meta_path[0:0] = [ importer ]
7786121Snate@binkert.org
7793716Sstever@eecs.umich.edu# import all sim objects so we can populate the all_objects list
7805522Snate@binkert.org# make sure that we're working with a list, then let's sort it
7819420Sandreas.hansson@arm.comfor modname in SimObject.modnames:
7825522Snate@binkert.org    exec('from m5.objects import %s' % modname)
7835522Snate@binkert.org
7845522Snate@binkert.org# we need to unload all of the currently imported modules so that they
7855522Snate@binkert.org# will be re-imported the next time the sconscript is run
7861858SN/Aimporter.unload()
7875227Ssaidi@eecs.umich.edusys.meta_path.remove(importer)
7885227Ssaidi@eecs.umich.edu
7895227Ssaidi@eecs.umich.edusim_objects = m5.SimObject.allClasses
7905227Ssaidi@eecs.umich.eduall_enums = m5.params.allEnums
7916654Snate@binkert.org
7926654Snate@binkert.orgfor name,obj in sorted(sim_objects.iteritems()):
7937769SAli.Saidi@ARM.com    for param in obj._params.local.values():
7947769SAli.Saidi@ARM.com        # load the ptype attribute now because it depends on the
7957769SAli.Saidi@ARM.com        # current version of SimObject.allClasses, but when scons
7967769SAli.Saidi@ARM.com        # actually uses the value, all versions of
7975227Ssaidi@eecs.umich.edu        # SimObject.allClasses will have been loaded
7985227Ssaidi@eecs.umich.edu        param.ptype
7995227Ssaidi@eecs.umich.edu
8005204Sstever@gmail.com########################################################################
8015204Sstever@gmail.com#
8025204Sstever@gmail.com# calculate extra dependencies
8035204Sstever@gmail.com#
8045204Sstever@gmail.commodule_depends = ["m5", "m5.SimObject", "m5.params"]
8055204Sstever@gmail.comdepends = [ PySource.modules[dep].snode for dep in module_depends ]
8065204Sstever@gmail.comdepends.sort(key = lambda x: x.name)
8075204Sstever@gmail.com
8085204Sstever@gmail.com########################################################################
8095204Sstever@gmail.com#
8105204Sstever@gmail.com# Commands for the basic automatically generated python files
8115204Sstever@gmail.com#
8125204Sstever@gmail.com
8135204Sstever@gmail.com# Generate Python file containing a dict specifying the current
8145204Sstever@gmail.com# buildEnv flags.
8155204Sstever@gmail.comdef makeDefinesPyFile(target, source, env):
8165204Sstever@gmail.com    build_env = source[0].get_contents()
8176121Snate@binkert.org
8185204Sstever@gmail.com    code = code_formatter()
8193118Sstever@eecs.umich.edu    code("""
8203118Sstever@eecs.umich.eduimport _m5.core
8213118Sstever@eecs.umich.eduimport m5.util
8223118Sstever@eecs.umich.edu
8233118Sstever@eecs.umich.edubuildEnv = m5.util.SmartDict($build_env)
8245863Snate@binkert.org
8253118Sstever@eecs.umich.educompileDate = _m5.core.compileDate
8265863Snate@binkert.org_globals = globals()
8273118Sstever@eecs.umich.edufor key,val in _m5.core.__dict__.items():
8287457Snate@binkert.org    if key.startswith('flag_'):
8297457Snate@binkert.org        flag = key[5:]
8305863Snate@binkert.org        _globals[flag] = val
8315863Snate@binkert.orgdel _globals
8325863Snate@binkert.org""")
8335863Snate@binkert.org    code.write(target[0].abspath)
8345863Snate@binkert.org
8355863Snate@binkert.orgdefines_info = Value(build_env)
8365863Snate@binkert.org# Generate a file with all of the compile options in it
8376003Snate@binkert.orgenv.Command('python/m5/defines.py', defines_info,
8385863Snate@binkert.org            MakeAction(makeDefinesPyFile, Transform("DEFINES", 0)))
8395863Snate@binkert.orgPySource('m5', 'python/m5/defines.py')
8405863Snate@binkert.org
8416120Snate@binkert.org# Generate python file containing info about the M5 source code
8429588Sandreas@sandberg.pp.sedef makeInfoPyFile(target, source, env):
8439588Sandreas@sandberg.pp.se    code = code_formatter()
8449588Sandreas@sandberg.pp.se    for src in source:
8459588Sandreas@sandberg.pp.se        data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
8469588Sandreas@sandberg.pp.se        code('$src = ${{repr(data)}}')
8475863Snate@binkert.org    code.write(str(target[0]))
8485863Snate@binkert.org
8495863Snate@binkert.org# Generate a file that wraps the basic top level files
8508655Sandreas.hansson@arm.comenv.Command('python/m5/info.py',
8518655Sandreas.hansson@arm.com            [ '#/COPYING', '#/LICENSE', '#/README', ],
8528655Sandreas.hansson@arm.com            MakeAction(makeInfoPyFile, Transform("INFO")))
8538655Sandreas.hansson@arm.comPySource('m5', 'python/m5/info.py')
8548655Sandreas.hansson@arm.com
8558655Sandreas.hansson@arm.com########################################################################
8568655Sandreas.hansson@arm.com#
8578655Sandreas.hansson@arm.com# Create all of the SimObject param headers and enum headers
8586120Snate@binkert.org#
8595863Snate@binkert.org
8606121Snate@binkert.orgdef createSimObjectParamStruct(target, source, env):
8616121Snate@binkert.org    assert len(target) == 1 and len(source) == 1
8625863Snate@binkert.org
8637727SAli.Saidi@ARM.com    name = source[0].get_text_contents()
8647727SAli.Saidi@ARM.com    obj = sim_objects[name]
8657727SAli.Saidi@ARM.com
8667727SAli.Saidi@ARM.com    code = code_formatter()
8677727SAli.Saidi@ARM.com    obj.cxx_param_decl(code)
8687727SAli.Saidi@ARM.com    code.write(target[0].abspath)
8695863Snate@binkert.org
8703118Sstever@eecs.umich.edudef createSimObjectCxxConfig(is_header):
8715863Snate@binkert.org    def body(target, source, env):
8729239Sandreas.hansson@arm.com        assert len(target) == 1 and len(source) == 1
8733118Sstever@eecs.umich.edu
8743118Sstever@eecs.umich.edu        name = str(source[0].get_contents())
8755863Snate@binkert.org        obj = sim_objects[name]
8765863Snate@binkert.org
8775863Snate@binkert.org        code = code_formatter()
8785863Snate@binkert.org        obj.cxx_config_param_file(code, is_header)
8793118Sstever@eecs.umich.edu        code.write(target[0].abspath)
8803483Ssaidi@eecs.umich.edu    return body
8813494Ssaidi@eecs.umich.edu
8823494Ssaidi@eecs.umich.edudef createEnumStrings(target, source, env):
8833483Ssaidi@eecs.umich.edu    assert len(target) == 1 and len(source) == 2
8843483Ssaidi@eecs.umich.edu
8853483Ssaidi@eecs.umich.edu    name = source[0].get_text_contents()
8863053Sstever@eecs.umich.edu    use_python = source[1].read()
8873053Sstever@eecs.umich.edu    obj = all_enums[name]
8883918Ssaidi@eecs.umich.edu
8893053Sstever@eecs.umich.edu    code = code_formatter()
8903053Sstever@eecs.umich.edu    obj.cxx_def(code)
8913053Sstever@eecs.umich.edu    if use_python:
8923053Sstever@eecs.umich.edu        obj.pybind_def(code)
8933053Sstever@eecs.umich.edu    code.write(target[0].abspath)
8949396Sandreas.hansson@arm.com
8959396Sandreas.hansson@arm.comdef createEnumDecls(target, source, env):
8969396Sandreas.hansson@arm.com    assert len(target) == 1 and len(source) == 1
8979396Sandreas.hansson@arm.com
8989396Sandreas.hansson@arm.com    name = source[0].get_text_contents()
8999396Sandreas.hansson@arm.com    obj = all_enums[name]
9009396Sandreas.hansson@arm.com
9019396Sandreas.hansson@arm.com    code = code_formatter()
9029396Sandreas.hansson@arm.com    obj.cxx_decl(code)
9039477Sandreas.hansson@arm.com    code.write(target[0].abspath)
9049396Sandreas.hansson@arm.com
9059477Sandreas.hansson@arm.comdef createSimObjectPyBindWrapper(target, source, env):
9069477Sandreas.hansson@arm.com    name = source[0].get_text_contents()
9079477Sandreas.hansson@arm.com    obj = sim_objects[name]
9089477Sandreas.hansson@arm.com
9099396Sandreas.hansson@arm.com    code = code_formatter()
9107840Snate@binkert.org    obj.pybind_decl(code)
9117865Sgblack@eecs.umich.edu    code.write(target[0].abspath)
9127865Sgblack@eecs.umich.edu
9137865Sgblack@eecs.umich.edu# Generate all of the SimObject param C++ struct header files
9147865Sgblack@eecs.umich.eduparams_hh_files = []
9157865Sgblack@eecs.umich.edufor name,simobj in sorted(sim_objects.iteritems()):
9167840Snate@binkert.org    py_source = PySource.modules[simobj.__module__]
9179045SAli.Saidi@ARM.com    extra_deps = [ py_source.tnode ]
9189045SAli.Saidi@ARM.com
9199045SAli.Saidi@ARM.com    hh_file = File('params/%s.hh' % name)
9209045SAli.Saidi@ARM.com    params_hh_files.append(hh_file)
9219045SAli.Saidi@ARM.com    env.Command(hh_file, Value(name),
9229045SAli.Saidi@ARM.com                MakeAction(createSimObjectParamStruct, Transform("SO PARAM")))
9239071Sandreas.hansson@arm.com    env.Depends(hh_file, depends + extra_deps)
9249071Sandreas.hansson@arm.com
9259045SAli.Saidi@ARM.com# C++ parameter description files
9267840Snate@binkert.orgif GetOption('with_cxx_config'):
9277840Snate@binkert.org    for name,simobj in sorted(sim_objects.iteritems()):
9287840Snate@binkert.org        py_source = PySource.modules[simobj.__module__]
9291858SN/A        extra_deps = [ py_source.tnode ]
9301858SN/A
9311858SN/A        cxx_config_hh_file = File('cxx_config/%s.hh' % name)
9321858SN/A        cxx_config_cc_file = File('cxx_config/%s.cc' % name)
9331858SN/A        env.Command(cxx_config_hh_file, Value(name),
9341858SN/A                    MakeAction(createSimObjectCxxConfig(True),
9355863Snate@binkert.org                    Transform("CXXCPRHH")))
9365863Snate@binkert.org        env.Command(cxx_config_cc_file, Value(name),
9375863Snate@binkert.org                    MakeAction(createSimObjectCxxConfig(False),
9385863Snate@binkert.org                    Transform("CXXCPRCC")))
9396121Snate@binkert.org        env.Depends(cxx_config_hh_file, depends + extra_deps +
9401858SN/A                    [File('params/%s.hh' % name), File('sim/cxx_config.hh')])
9415863Snate@binkert.org        env.Depends(cxx_config_cc_file, depends + extra_deps +
9425863Snate@binkert.org                    [cxx_config_hh_file])
9435863Snate@binkert.org        Source(cxx_config_cc_file)
9445863Snate@binkert.org
9455863Snate@binkert.org    cxx_config_init_cc_file = File('cxx_config/init.cc')
9462139SN/A
9474202Sbinkertn@umich.edu    def createCxxConfigInitCC(target, source, env):
9484202Sbinkertn@umich.edu        assert len(target) == 1 and len(source) == 1
9492139SN/A
9506994Snate@binkert.org        code = code_formatter()
9516994Snate@binkert.org
9526994Snate@binkert.org        for name,simobj in sorted(sim_objects.iteritems()):
9536994Snate@binkert.org            if not hasattr(simobj, 'abstract') or not simobj.abstract:
9546994Snate@binkert.org                code('#include "cxx_config/${name}.hh"')
9556994Snate@binkert.org        code()
9566994Snate@binkert.org        code('void cxxConfigInit()')
9576994Snate@binkert.org        code('{')
9586994Snate@binkert.org        code.indent()
9596994Snate@binkert.org        for name,simobj in sorted(sim_objects.iteritems()):
9606994Snate@binkert.org            not_abstract = not hasattr(simobj, 'abstract') or \
9616994Snate@binkert.org                not simobj.abstract
9626994Snate@binkert.org            if not_abstract and 'type' in simobj.__dict__:
9636994Snate@binkert.org                code('cxx_config_directory["${name}"] = '
9646994Snate@binkert.org                     '${name}CxxConfigParams::makeDirectoryEntry();')
9656994Snate@binkert.org        code.dedent()
9666994Snate@binkert.org        code('}')
9676994Snate@binkert.org        code.write(target[0].abspath)
9686994Snate@binkert.org
9696994Snate@binkert.org    py_source = PySource.modules[simobj.__module__]
9706994Snate@binkert.org    extra_deps = [ py_source.tnode ]
9716994Snate@binkert.org    env.Command(cxx_config_init_cc_file, Value(name),
9726994Snate@binkert.org        MakeAction(createCxxConfigInitCC, Transform("CXXCINIT")))
9736994Snate@binkert.org    cxx_param_hh_files = ["cxx_config/%s.hh" % simobj
9746994Snate@binkert.org        for name,simobj in sorted(sim_objects.iteritems())
9756994Snate@binkert.org        if not hasattr(simobj, 'abstract') or not simobj.abstract]
9766994Snate@binkert.org    Depends(cxx_config_init_cc_file, cxx_param_hh_files +
9776994Snate@binkert.org            [File('sim/cxx_config.hh')])
9782155SN/A    Source(cxx_config_init_cc_file)
9795863Snate@binkert.org
9801869SN/A# Generate all enum header files
9811869SN/Afor name,enum in sorted(all_enums.iteritems()):
9825863Snate@binkert.org    py_source = PySource.modules[enum.__module__]
9835863Snate@binkert.org    extra_deps = [ py_source.tnode ]
9844202Sbinkertn@umich.edu
9856108Snate@binkert.org    cc_file = File('enums/%s.cc' % name)
9866108Snate@binkert.org    env.Command(cc_file, [Value(name), Value(env['USE_PYTHON'])],
9876108Snate@binkert.org                MakeAction(createEnumStrings, Transform("ENUM STR")))
9886108Snate@binkert.org    env.Depends(cc_file, depends + extra_deps)
9899219Spower.jg@gmail.com    Source(cc_file)
9909219Spower.jg@gmail.com
9919219Spower.jg@gmail.com    hh_file = File('enums/%s.hh' % name)
9929219Spower.jg@gmail.com    env.Command(hh_file, Value(name),
9939219Spower.jg@gmail.com                MakeAction(createEnumDecls, Transform("ENUMDECL")))
9949219Spower.jg@gmail.com    env.Depends(hh_file, depends + extra_deps)
9959219Spower.jg@gmail.com
9969219Spower.jg@gmail.com# Generate SimObject Python bindings wrapper files
9974202Sbinkertn@umich.eduif env['USE_PYTHON']:
9985863Snate@binkert.org    for name,simobj in sorted(sim_objects.iteritems()):
9998474Sgblack@eecs.umich.edu        py_source = PySource.modules[simobj.__module__]
10008474Sgblack@eecs.umich.edu        extra_deps = [ py_source.tnode ]
10015742Snate@binkert.org        cc_file = File('python/_m5/param_%s.cc' % name)
10028268Ssteve.reinhardt@amd.com        env.Command(cc_file, Value(name),
10038268Ssteve.reinhardt@amd.com                    MakeAction(createSimObjectPyBindWrapper,
10048268Ssteve.reinhardt@amd.com                               Transform("SO PyBind")))
10055742Snate@binkert.org        env.Depends(cc_file, depends + extra_deps)
10065341Sstever@gmail.com        Source(cc_file)
10078474Sgblack@eecs.umich.edu
10088474Sgblack@eecs.umich.edu# Build all protocol buffers if we have got protoc and protobuf available
10095342Sstever@gmail.comif env['HAVE_PROTOBUF']:
10104202Sbinkertn@umich.edu    for proto in ProtoBuf.all:
10114202Sbinkertn@umich.edu        # Use both the source and header as the target, and the .proto
10124202Sbinkertn@umich.edu        # file as the source. When executing the protoc compiler, also
10135863Snate@binkert.org        # specify the proto_path to avoid having the generated files
10145863Snate@binkert.org        # include the path.
10156994Snate@binkert.org        env.Command([proto.cc_file, proto.hh_file], proto.tnode,
10166994Snate@binkert.org                    MakeAction('$PROTOC --cpp_out ${TARGET.dir} '
10176994Snate@binkert.org                               '--proto_path ${SOURCE.dir} $SOURCE',
10185863Snate@binkert.org                               Transform("PROTOC")))
10195863Snate@binkert.org
10205863Snate@binkert.org        # Add the C++ source file
10215863Snate@binkert.org        Source(proto.cc_file, tags=proto.tags)
10225863Snate@binkert.orgelif ProtoBuf.all:
10235863Snate@binkert.org    print('Got protobuf to build, but lacks support!')
10245863Snate@binkert.org    Exit(1)
10255863Snate@binkert.org
10267840Snate@binkert.org#
10275863Snate@binkert.org# Handle debug flags
10285952Ssaidi@eecs.umich.edu#
10299219Spower.jg@gmail.comdef makeDebugFlagCC(target, source, env):
10309219Spower.jg@gmail.com    assert(len(target) == 1 and len(source) == 1)
10311869SN/A
10321858SN/A    code = code_formatter()
10335863Snate@binkert.org
10349420Sandreas.hansson@arm.com    # delay definition of CompoundFlags until after all the definition
10359420Sandreas.hansson@arm.com    # of all constituent SimpleFlags
10361858SN/A    comp_code = code_formatter()
1037955SN/A
1038955SN/A    # file header
10391869SN/A    code('''
10401869SN/A/*
10411869SN/A * DO NOT EDIT THIS FILE! Automatically generated by SCons.
10421869SN/A */
10431869SN/A
10445863Snate@binkert.org#include "base/debug.hh"
10455863Snate@binkert.org
10465863Snate@binkert.orgnamespace Debug {
10471869SN/A
10485863Snate@binkert.org''')
10491869SN/A
10505863Snate@binkert.org    for name, flag in sorted(source[0].read().iteritems()):
10511869SN/A        n, compound, desc = flag
10521869SN/A        assert n == name
10531869SN/A
10541869SN/A        if not compound:
10558483Sgblack@eecs.umich.edu            code('SimpleFlag $name("$name", "$desc");')
10561869SN/A        else:
10571869SN/A            comp_code('CompoundFlag $name("$name", "$desc",')
10581869SN/A            comp_code.indent()
10591869SN/A            last = len(compound) - 1
10605863Snate@binkert.org            for i,flag in enumerate(compound):
10615863Snate@binkert.org                if i != last:
10621869SN/A                    comp_code('&$flag,')
10635863Snate@binkert.org                else:
10645863Snate@binkert.org                    comp_code('&$flag);')
10653356Sbinkertn@umich.edu            comp_code.dedent()
10663356Sbinkertn@umich.edu
10673356Sbinkertn@umich.edu    code.append(comp_code)
10683356Sbinkertn@umich.edu    code()
10693356Sbinkertn@umich.edu    code('} // namespace Debug')
10704781Snate@binkert.org
10715863Snate@binkert.org    code.write(str(target[0]))
10725863Snate@binkert.org
10731869SN/Adef makeDebugFlagHH(target, source, env):
10741869SN/A    assert(len(target) == 1 and len(source) == 1)
10751869SN/A
10766121Snate@binkert.org    val = eval(source[0].get_contents())
10771869SN/A    name, compound, desc = val
10782638Sstever@eecs.umich.edu
10796121Snate@binkert.org    code = code_formatter()
10806121Snate@binkert.org
10812638Sstever@eecs.umich.edu    # file header boilerplate
10825749Scws3k@cs.virginia.edu    code('''\
10836121Snate@binkert.org/*
10846121Snate@binkert.org * DO NOT EDIT THIS FILE! Automatically generated by SCons.
10855749Scws3k@cs.virginia.edu */
10869537Satgutier@umich.edu
10879537Satgutier@umich.edu#ifndef __DEBUG_${name}_HH__
10889537Satgutier@umich.edu#define __DEBUG_${name}_HH__
10899537Satgutier@umich.edu
10901869SN/Anamespace Debug {
10911869SN/A''')
10923546Sgblack@eecs.umich.edu
10933546Sgblack@eecs.umich.edu    if compound:
10943546Sgblack@eecs.umich.edu        code('class CompoundFlag;')
10953546Sgblack@eecs.umich.edu    code('class SimpleFlag;')
10966121Snate@binkert.org
10975863Snate@binkert.org    if compound:
10983546Sgblack@eecs.umich.edu        code('extern CompoundFlag $name;')
10993546Sgblack@eecs.umich.edu        for flag in compound:
11003546Sgblack@eecs.umich.edu            code('extern SimpleFlag $flag;')
11013546Sgblack@eecs.umich.edu    else:
11024781Snate@binkert.org        code('extern SimpleFlag $name;')
11034781Snate@binkert.org
11046658Snate@binkert.org    code('''
11056658Snate@binkert.org}
11064781Snate@binkert.org
11073546Sgblack@eecs.umich.edu#endif // __DEBUG_${name}_HH__
11083546Sgblack@eecs.umich.edu''')
11093546Sgblack@eecs.umich.edu
11103546Sgblack@eecs.umich.edu    code.write(str(target[0]))
11117756SAli.Saidi@ARM.com
11127816Ssteve.reinhardt@amd.comfor name,flag in sorted(debug_flags.iteritems()):
11133546Sgblack@eecs.umich.edu    n, compound, desc = flag
11143546Sgblack@eecs.umich.edu    assert n == name
11153546Sgblack@eecs.umich.edu
11163546Sgblack@eecs.umich.edu    hh_file = 'debug/%s.hh' % name
11174202Sbinkertn@umich.edu    env.Command(hh_file, Value(flag),
11183546Sgblack@eecs.umich.edu                MakeAction(makeDebugFlagHH, Transform("TRACING", 0)))
11193546Sgblack@eecs.umich.edu
11203546Sgblack@eecs.umich.eduenv.Command('debug/flags.cc', Value(debug_flags),
1121955SN/A            MakeAction(makeDebugFlagCC, Transform("TRACING", 0)))
1122955SN/ASource('debug/flags.cc')
1123955SN/A
1124955SN/A# version tags
11255863Snate@binkert.orgtags = \
11265863Snate@binkert.orgenv.Command('sim/tags.cc', None,
11275343Sstever@gmail.com            MakeAction('util/cpt_upgrader.py --get-cc-file > $TARGET',
11285343Sstever@gmail.com                       Transform("VER TAGS")))
11296121Snate@binkert.orgenv.AlwaysBuild(tags)
11305863Snate@binkert.org
11314773Snate@binkert.org# Build a small helper that marshals the Python code using the same
11325863Snate@binkert.org# version of Python as gem5. This is in an unorthodox location to
11332632Sstever@eecs.umich.edu# avoid building it for every variant.
11345863Snate@binkert.orgpy_marshal = env.Program('marshal', 'python/marshal.cc')[0]
11352023SN/A
11365863Snate@binkert.org# Embed python files.  All .py files that have been indicated by a
11375863Snate@binkert.org# PySource() call in a SConscript need to be embedded into the M5
11385863Snate@binkert.org# library.  To do that, we compile the file to byte code, marshal the
11395863Snate@binkert.org# byte code, compress it, and then generate a c++ file that
11405863Snate@binkert.org# inserts the result into an array.
11415863Snate@binkert.orgdef embedPyFile(target, source, env):
11425863Snate@binkert.org    def c_str(string):
11435863Snate@binkert.org        if string is None:
11445863Snate@binkert.org            return "0"
11452632Sstever@eecs.umich.edu        return '"%s"' % string
11465863Snate@binkert.org
11472023SN/A    '''Action function to compile a .py into a code object, marshal it,
11482632Sstever@eecs.umich.edu    compress it, and stick it into an asm file so the code appears as
11495863Snate@binkert.org    just bytes with a label in the data section. The action takes two
11505342Sstever@gmail.com    sources:
11515863Snate@binkert.org
11522632Sstever@eecs.umich.edu    source[0]: Binary used to marshal Python sources
11535863Snate@binkert.org    source[1]: Python script to marshal
11545863Snate@binkert.org    '''
11558267Ssteve.reinhardt@amd.com
11568120Sgblack@eecs.umich.edu    import subprocess
11578267Ssteve.reinhardt@amd.com
11588267Ssteve.reinhardt@amd.com    marshalled = subprocess.check_output([source[0].abspath, str(source[1])])
11598267Ssteve.reinhardt@amd.com
11608267Ssteve.reinhardt@amd.com    compressed = zlib.compress(marshalled)
11618267Ssteve.reinhardt@amd.com    data = compressed
11628267Ssteve.reinhardt@amd.com    pysource = PySource.tnodes[source[1]]
11638267Ssteve.reinhardt@amd.com    sym = pysource.symname
11648267Ssteve.reinhardt@amd.com
11658267Ssteve.reinhardt@amd.com    code = code_formatter()
11665863Snate@binkert.org    code('''\
11675863Snate@binkert.org#include "sim/init.hh"
11685863Snate@binkert.org
11692632Sstever@eecs.umich.edunamespace {
11708267Ssteve.reinhardt@amd.com
11718267Ssteve.reinhardt@amd.com''')
11728267Ssteve.reinhardt@amd.com    blobToCpp(data, 'data_' + sym, code)
11732632Sstever@eecs.umich.edu    code('''\
11741888SN/A
11755863Snate@binkert.org
11765863Snate@binkert.orgEmbeddedPython embedded_${sym}(
11771858SN/A    ${{c_str(pysource.arcname)}},
11788120Sgblack@eecs.umich.edu    ${{c_str(pysource.abspath)}},
11798120Sgblack@eecs.umich.edu    ${{c_str(pysource.modpath)}},
11807756SAli.Saidi@ARM.com    data_${sym},
11812598SN/A    ${{len(data)}},
11825863Snate@binkert.org    ${{len(marshalled)}});
11831858SN/A
11841858SN/A} // anonymous namespace
11851858SN/A''')
11865863Snate@binkert.org    code.write(str(target[0]))
11871858SN/A
11881858SN/Afor source in PySource.all:
11891858SN/A    env.Command(source.cpp, [ py_marshal, source.tnode ],
11905863Snate@binkert.org                MakeAction(embedPyFile, Transform("EMBED PY")))
11911871SN/A    Source(source.cpp, tags=source.tags, add_tags='python')
11921858SN/A
11931858SN/A########################################################################
11941858SN/A#
11951858SN/A# Define binaries.  Each different build type (debug, opt, etc.) gets
11965863Snate@binkert.org# a slightly different build environment.
11975863Snate@binkert.org#
11981869SN/A
11991965SN/A# List of constructed environments to pass back to SConstruct
12007739Sgblack@eecs.umich.edudate_source = Source('base/date.cc', tags=[])
12011965SN/A
12029045SAli.Saidi@ARM.comgem5_binary = Gem5('gem5')
12039045SAli.Saidi@ARM.com
12049045SAli.Saidi@ARM.com# Function to create a new build environment as clone of current
12052761Sstever@eecs.umich.edu# environment 'env' with modified object suffix and optional stripped
12065863Snate@binkert.org# binary.  Additional keyword arguments are appended to corresponding
12071869SN/A# build environment vars.
12085863Snate@binkert.orgdef makeEnv(env, label, objsfx, strip=False, disable_partial=False, **kwargs):
12092667Sstever@eecs.umich.edu    # SCons doesn't know to append a library suffix when there is a '.' in the
12101869SN/A    # name.  Use '_' instead.
12111869SN/A    libname = 'gem5_' + label
12122929Sktlim@umich.edu    secondary_exename = 'm5.' + label
12132929Sktlim@umich.edu
12145863Snate@binkert.org    new_env = env.Clone(OBJSUFFIX=objsfx, SHOBJSUFFIX=objsfx + 's')
12152929Sktlim@umich.edu    new_env.Label = label
1216955SN/A    new_env.Append(**kwargs)
12178120Sgblack@eecs.umich.edu
12188120Sgblack@eecs.umich.edu    lib_sources = Source.all.with_tag('gem5 lib')
12198120Sgblack@eecs.umich.edu
12208120Sgblack@eecs.umich.edu    # Without Python, leave out all Python content from the library
12218120Sgblack@eecs.umich.edu    # builds.  The option doesn't affect gem5 built as a program
12228120Sgblack@eecs.umich.edu    if GetOption('without_python'):
12238120Sgblack@eecs.umich.edu        lib_sources = lib_sources.without_tag('python')
12248120Sgblack@eecs.umich.edu
12258120Sgblack@eecs.umich.edu    static_objs = []
12268120Sgblack@eecs.umich.edu    shared_objs = []
12278120Sgblack@eecs.umich.edu
12288120Sgblack@eecs.umich.edu    for s in lib_sources.with_tag(Source.ungrouped_tag):
1229        static_objs.append(s.static(new_env))
1230        shared_objs.append(s.shared(new_env))
1231
1232    for group in Source.source_groups:
1233        srcs = lib_sources.with_tag(Source.link_group_tag(group))
1234        if not srcs:
1235            continue
1236
1237        group_static = [ s.static(new_env) for s in srcs ]
1238        group_shared = [ s.shared(new_env) for s in srcs ]
1239
1240        # If partial linking is disabled, add these sources to the build
1241        # directly, and short circuit this loop.
1242        if disable_partial:
1243            static_objs.extend(group_static)
1244            shared_objs.extend(group_shared)
1245            continue
1246
1247        # Set up the static partially linked objects.
1248        file_name = new_env.subst("${OBJPREFIX}lib${OBJSUFFIX}.partial")
1249        target = File(joinpath(group, file_name))
1250        partial = env.PartialStatic(target=target, source=group_static)
1251        static_objs.extend(partial)
1252
1253        # Set up the shared partially linked objects.
1254        file_name = new_env.subst("${SHOBJPREFIX}lib${SHOBJSUFFIX}.partial")
1255        target = File(joinpath(group, file_name))
1256        partial = env.PartialShared(target=target, source=group_shared)
1257        shared_objs.extend(partial)
1258
1259    static_date = date_source.static(new_env)
1260    new_env.Depends(static_date, static_objs)
1261    static_objs.extend(static_date)
1262
1263    shared_date = date_source.shared(new_env)
1264    new_env.Depends(shared_date, shared_objs)
1265    shared_objs.extend(shared_date)
1266
1267    main_objs = [ s.static(new_env) for s in Source.all.with_tag('main') ]
1268
1269    # First make a library of everything but main() so other programs can
1270    # link against m5.
1271    static_lib = new_env.StaticLibrary(libname, static_objs)
1272    shared_lib = new_env.SharedLibrary(libname, shared_objs)
1273
1274    # Keep track of the object files generated so far so Executables can
1275    # include them.
1276    new_env['STATIC_OBJS'] = static_objs
1277    new_env['SHARED_OBJS'] = shared_objs
1278    new_env['MAIN_OBJS'] = main_objs
1279
1280    new_env['STATIC_LIB'] = static_lib
1281    new_env['SHARED_LIB'] = shared_lib
1282
1283    # Record some settings for building Executables.
1284    new_env['EXE_SUFFIX'] = label
1285    new_env['STRIP_EXES'] = strip
1286
1287    for cls in ExecutableMeta.all:
1288        cls.declare_all(new_env)
1289
1290    new_env.M5Binary = File(gem5_binary.path(new_env))
1291
1292    new_env.Command(secondary_exename, new_env.M5Binary,
1293            MakeAction('ln $SOURCE $TARGET', Transform("HARDLINK")))
1294
1295    # Set up regression tests.
1296    SConscript(os.path.join(env.root.abspath, 'tests', 'SConscript'),
1297               variant_dir=Dir('tests').Dir(new_env.Label),
1298               exports={ 'env' : new_env }, duplicate=False)
1299
1300# Start out with the compiler flags common to all compilers,
1301# i.e. they all use -g for opt and -g -pg for prof
1302ccflags = {'debug' : [], 'opt' : ['-g'], 'fast' : [], 'prof' : ['-g', '-pg'],
1303           'perf' : ['-g']}
1304
1305# Start out with the linker flags common to all linkers, i.e. -pg for
1306# prof, and -lprofiler for perf. The -lprofile flag is surrounded by
1307# no-as-needed and as-needed as the binutils linker is too clever and
1308# simply doesn't link to the library otherwise.
1309ldflags = {'debug' : [], 'opt' : [], 'fast' : [], 'prof' : ['-pg'],
1310           'perf' : ['-Wl,--no-as-needed', '-lprofiler', '-Wl,--as-needed']}
1311
1312# For Link Time Optimization, the optimisation flags used to compile
1313# individual files are decoupled from those used at link time
1314# (i.e. you can compile with -O3 and perform LTO with -O0), so we need
1315# to also update the linker flags based on the target.
1316if env['GCC']:
1317    if sys.platform == 'sunos5':
1318        ccflags['debug'] += ['-gstabs+']
1319    else:
1320        ccflags['debug'] += ['-ggdb3']
1321    ldflags['debug'] += ['-O0']
1322    # opt, fast, prof and perf all share the same cc flags, also add
1323    # the optimization to the ldflags as LTO defers the optimization
1324    # to link time
1325    for target in ['opt', 'fast', 'prof', 'perf']:
1326        ccflags[target] += ['-O3']
1327        ldflags[target] += ['-O3']
1328
1329    ccflags['fast'] += env['LTO_CCFLAGS']
1330    ldflags['fast'] += env['LTO_LDFLAGS']
1331elif env['CLANG']:
1332    ccflags['debug'] += ['-g', '-O0']
1333    # opt, fast, prof and perf all share the same cc flags
1334    for target in ['opt', 'fast', 'prof', 'perf']:
1335        ccflags[target] += ['-O3']
1336else:
1337    print('Unknown compiler, please fix compiler options')
1338    Exit(1)
1339
1340
1341# To speed things up, we only instantiate the build environments we
1342# need.  We try to identify the needed environment for each target; if
1343# we can't, we fall back on instantiating all the environments just to
1344# be safe.
1345target_types = ['debug', 'opt', 'fast', 'prof', 'perf']
1346obj2target = {'do': 'debug', 'o': 'opt', 'fo': 'fast', 'po': 'prof',
1347              'gpo' : 'perf'}
1348
1349def identifyTarget(t):
1350    ext = t.split('.')[-1]
1351    if ext in target_types:
1352        return ext
1353    if ext in obj2target:
1354        return obj2target[ext]
1355    match = re.search(r'/tests/([^/]+)/', t)
1356    if match and match.group(1) in target_types:
1357        return match.group(1)
1358    return 'all'
1359
1360needed_envs = [identifyTarget(target) for target in BUILD_TARGETS]
1361if 'all' in needed_envs:
1362    needed_envs += target_types
1363
1364disable_partial = False
1365if env['PLATFORM'] == 'darwin':
1366    # Up until Apple LLVM version 10.0.0 (clang-1000.11.45.5), partial
1367    # linked objects do not expose symbols that are marked with the
1368    # hidden visibility and consequently building gem5 on Mac OS
1369    # fails. As a workaround, we disable partial linking, however, we
1370    # may want to revisit in the future.
1371    disable_partial = True
1372
1373# Debug binary
1374if 'debug' in needed_envs:
1375    makeEnv(env, 'debug', '.do',
1376            CCFLAGS = Split(ccflags['debug']),
1377            CPPDEFINES = ['DEBUG', 'TRACING_ON=1'],
1378            LINKFLAGS = Split(ldflags['debug']),
1379            disable_partial=disable_partial)
1380
1381# Optimized binary
1382if 'opt' in needed_envs:
1383    makeEnv(env, 'opt', '.o',
1384            CCFLAGS = Split(ccflags['opt']),
1385            CPPDEFINES = ['TRACING_ON=1'],
1386            LINKFLAGS = Split(ldflags['opt']),
1387            disable_partial=disable_partial)
1388
1389# "Fast" binary
1390if 'fast' in needed_envs:
1391    disable_partial = disable_partial or \
1392            (env.get('BROKEN_INCREMENTAL_LTO', False) and \
1393            GetOption('force_lto'))
1394    makeEnv(env, 'fast', '.fo', strip = True,
1395            CCFLAGS = Split(ccflags['fast']),
1396            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1397            LINKFLAGS = Split(ldflags['fast']),
1398            disable_partial=disable_partial)
1399
1400# Profiled binary using gprof
1401if 'prof' in needed_envs:
1402    makeEnv(env, 'prof', '.po',
1403            CCFLAGS = Split(ccflags['prof']),
1404            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1405            LINKFLAGS = Split(ldflags['prof']),
1406            disable_partial=disable_partial)
1407
1408# Profiled binary using google-pprof
1409if 'perf' in needed_envs:
1410    makeEnv(env, 'perf', '.gpo',
1411            CCFLAGS = Split(ccflags['perf']),
1412            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1413            LINKFLAGS = Split(ldflags['perf']),
1414            disable_partial=disable_partial)
1415