SConscript revision 14039
1955SN/A# -*- mode:python -*-
2955SN/A
313576Sciro.santilli@arm.com# Copyright (c) 2018 ARM Limited
413576Sciro.santilli@arm.com#
513576Sciro.santilli@arm.com# The license below extends only to copyright in the software and shall
613576Sciro.santilli@arm.com# not be construed as granting a license to any other intellectual
713576Sciro.santilli@arm.com# property including but not limited to intellectual property relating
813576Sciro.santilli@arm.com# to a hardware implementation of the functionality of the software
913576Sciro.santilli@arm.com# licensed hereunder.  You may use the software subject to the license
1013576Sciro.santilli@arm.com# terms below provided that you ensure that this notice is replicated
1113576Sciro.santilli@arm.com# unmodified and in its entirety in all distributions of the software,
1213576Sciro.santilli@arm.com# modified or unmodified, in source code or in binary form.
1313576Sciro.santilli@arm.com#
141762SN/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
30955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32955SN/A# 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
38955SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
392665Ssaidi@eecs.umich.edu#
404762Snate@binkert.org# Authors: Nathan Binkert
41955SN/A
4212563Sgabeblack@google.comfrom __future__ import print_function
4312563Sgabeblack@google.com
445522Snate@binkert.orgimport array
456143Snate@binkert.orgimport bisect
4612371Sgabeblack@google.comimport functools
474762Snate@binkert.orgimport imp
48955SN/Aimport os
495522Snate@binkert.orgimport re
50955SN/Aimport sys
515522Snate@binkert.orgimport zlib
524202Sbinkertn@umich.edu
535742Snate@binkert.orgfrom os.path import basename, dirname, exists, isdir, isfile, join as joinpath
54955SN/A
554381Sbinkertn@umich.eduimport SCons
564381Sbinkertn@umich.edu
5712246Sgabeblack@google.comfrom gem5_scons import Transform
5812246Sgabeblack@google.com
598334Snate@binkert.org# This file defines how to build a particular configuration of gem5
60955SN/A# based on variable settings in the 'env' build environment.
61955SN/A
624202Sbinkertn@umich.eduImport('*')
63955SN/A
644382Sbinkertn@umich.edu# Children need to see the environment
654382Sbinkertn@umich.eduExport('env')
664382Sbinkertn@umich.edu
676654Snate@binkert.orgbuild_env = [(opt, env[opt]) for opt in export_vars]
685517Snate@binkert.org
698614Sgblack@eecs.umich.edufrom m5.util import code_formatter, compareVersions
707674Snate@binkert.org
716143Snate@binkert.org########################################################################
726143Snate@binkert.org# Code for adding source files of various types
736143Snate@binkert.org#
7412302Sgabeblack@google.com# When specifying a source file of some type, a set of tags can be
7512302Sgabeblack@google.com# specified for that file.
7612302Sgabeblack@google.com
7712371Sgabeblack@google.comclass SourceFilter(object):
7812371Sgabeblack@google.com    def __init__(self, predicate):
7912371Sgabeblack@google.com        self.predicate = predicate
8012371Sgabeblack@google.com
8112371Sgabeblack@google.com    def __or__(self, other):
8212371Sgabeblack@google.com        return SourceFilter(lambda tags: self.predicate(tags) or
8312371Sgabeblack@google.com                                         other.predicate(tags))
8412371Sgabeblack@google.com
8512371Sgabeblack@google.com    def __and__(self, other):
8612371Sgabeblack@google.com        return SourceFilter(lambda tags: self.predicate(tags) and
8712371Sgabeblack@google.com                                         other.predicate(tags))
8812371Sgabeblack@google.com
8912371Sgabeblack@google.comdef with_tags_that(predicate):
9012371Sgabeblack@google.com    '''Return a list of sources with tags that satisfy a predicate.'''
9112371Sgabeblack@google.com    return SourceFilter(predicate)
9212371Sgabeblack@google.com
9312371Sgabeblack@google.comdef with_any_tags(*tags):
9412371Sgabeblack@google.com    '''Return a list of sources with any of the supplied tags.'''
9512371Sgabeblack@google.com    return SourceFilter(lambda stags: len(set(tags) & stags) > 0)
9612371Sgabeblack@google.com
9712371Sgabeblack@google.comdef with_all_tags(*tags):
9812371Sgabeblack@google.com    '''Return a list of sources with all of the supplied tags.'''
9912371Sgabeblack@google.com    return SourceFilter(lambda stags: set(tags) <= stags)
10012371Sgabeblack@google.com
10112371Sgabeblack@google.comdef with_tag(tag):
10212371Sgabeblack@google.com    '''Return a list of sources with the supplied tag.'''
10312371Sgabeblack@google.com    return SourceFilter(lambda stags: tag in stags)
10412371Sgabeblack@google.com
10512371Sgabeblack@google.comdef without_tags(*tags):
10612371Sgabeblack@google.com    '''Return a list of sources without any of the supplied tags.'''
10712371Sgabeblack@google.com    return SourceFilter(lambda stags: len(set(tags) & stags) == 0)
10812371Sgabeblack@google.com
10912371Sgabeblack@google.comdef without_tag(tag):
11012371Sgabeblack@google.com    '''Return a list of sources with the supplied tag.'''
11112371Sgabeblack@google.com    return SourceFilter(lambda stags: tag not in stags)
11212371Sgabeblack@google.com
11312371Sgabeblack@google.comsource_filter_factories = {
11412371Sgabeblack@google.com    'with_tags_that': with_tags_that,
11512371Sgabeblack@google.com    'with_any_tags': with_any_tags,
11612371Sgabeblack@google.com    'with_all_tags': with_all_tags,
11712371Sgabeblack@google.com    'with_tag': with_tag,
11812371Sgabeblack@google.com    'without_tags': without_tags,
11912371Sgabeblack@google.com    'without_tag': without_tag,
12012371Sgabeblack@google.com}
12112371Sgabeblack@google.com
12212371Sgabeblack@google.comExport(source_filter_factories)
12312371Sgabeblack@google.com
12412302Sgabeblack@google.comclass SourceList(list):
12512371Sgabeblack@google.com    def apply_filter(self, f):
12612302Sgabeblack@google.com        def match(source):
12712371Sgabeblack@google.com            return f.predicate(source.tags)
12812302Sgabeblack@google.com        return SourceList(filter(match, self))
12912302Sgabeblack@google.com
13012371Sgabeblack@google.com    def __getattr__(self, name):
13112371Sgabeblack@google.com        func = source_filter_factories.get(name, None)
13212371Sgabeblack@google.com        if not func:
13312371Sgabeblack@google.com            raise AttributeError
13412302Sgabeblack@google.com
13512371Sgabeblack@google.com        @functools.wraps(func)
13612371Sgabeblack@google.com        def wrapper(*args, **kwargs):
13712371Sgabeblack@google.com            return self.apply_filter(func(*args, **kwargs))
13812371Sgabeblack@google.com        return wrapper
13911983Sgabeblack@google.com
1406143Snate@binkert.orgclass SourceMeta(type):
1418233Snate@binkert.org    '''Meta class for source files that keeps track of all files of a
14212302Sgabeblack@google.com    particular type.'''
1436143Snate@binkert.org    def __init__(cls, name, bases, dict):
1446143Snate@binkert.org        super(SourceMeta, cls).__init__(name, bases, dict)
14512302Sgabeblack@google.com        cls.all = SourceList()
1464762Snate@binkert.org
1476143Snate@binkert.orgclass SourceFile(object):
1488233Snate@binkert.org    '''Base object that encapsulates the notion of a source file.
1498233Snate@binkert.org    This includes, the source node, target node, various manipulations
15012302Sgabeblack@google.com    of those.  A source file also specifies a set of tags which
15112302Sgabeblack@google.com    describing arbitrary properties of the source file.'''
1526143Snate@binkert.org    __metaclass__ = SourceMeta
15312362Sgabeblack@google.com
15412362Sgabeblack@google.com    static_objs = {}
15512362Sgabeblack@google.com    shared_objs = {}
15612362Sgabeblack@google.com
15712302Sgabeblack@google.com    def __init__(self, source, tags=None, add_tags=None):
15812302Sgabeblack@google.com        if tags is None:
15912302Sgabeblack@google.com            tags='gem5 lib'
16012302Sgabeblack@google.com        if isinstance(tags, basestring):
16112302Sgabeblack@google.com            tags = set([tags])
16212363Sgabeblack@google.com        if not isinstance(tags, set):
16312363Sgabeblack@google.com            tags = set(tags)
16412363Sgabeblack@google.com        self.tags = tags
16512363Sgabeblack@google.com
16612302Sgabeblack@google.com        if add_tags:
16712363Sgabeblack@google.com            if isinstance(add_tags, basestring):
16812363Sgabeblack@google.com                add_tags = set([add_tags])
16912363Sgabeblack@google.com            if not isinstance(add_tags, set):
17012363Sgabeblack@google.com                add_tags = set(add_tags)
17112363Sgabeblack@google.com            self.tags |= add_tags
1728233Snate@binkert.org
1736143Snate@binkert.org        tnode = source
1746143Snate@binkert.org        if not isinstance(source, SCons.Node.FS.File):
1756143Snate@binkert.org            tnode = File(source)
1766143Snate@binkert.org
1776143Snate@binkert.org        self.tnode = tnode
1786143Snate@binkert.org        self.snode = tnode.srcnode()
1796143Snate@binkert.org
1806143Snate@binkert.org        for base in type(self).__mro__:
1816143Snate@binkert.org            if issubclass(base, SourceFile):
1827065Snate@binkert.org                base.all.append(self)
1836143Snate@binkert.org
18412362Sgabeblack@google.com    def static(self, env):
18512362Sgabeblack@google.com        key = (self.tnode, env['OBJSUFFIX'])
18612362Sgabeblack@google.com        if not key in self.static_objs:
18712362Sgabeblack@google.com            self.static_objs[key] = env.StaticObject(self.tnode)
18812362Sgabeblack@google.com        return self.static_objs[key]
18912362Sgabeblack@google.com
19012362Sgabeblack@google.com    def shared(self, env):
19112362Sgabeblack@google.com        key = (self.tnode, env['OBJSUFFIX'])
19212362Sgabeblack@google.com        if not key in self.shared_objs:
19312362Sgabeblack@google.com            self.shared_objs[key] = env.SharedObject(self.tnode)
19412362Sgabeblack@google.com        return self.shared_objs[key]
19512362Sgabeblack@google.com
1968233Snate@binkert.org    @property
1978233Snate@binkert.org    def filename(self):
1988233Snate@binkert.org        return str(self.tnode)
1998233Snate@binkert.org
2008233Snate@binkert.org    @property
2018233Snate@binkert.org    def dirname(self):
2028233Snate@binkert.org        return dirname(self.filename)
2038233Snate@binkert.org
2048233Snate@binkert.org    @property
2058233Snate@binkert.org    def basename(self):
2068233Snate@binkert.org        return basename(self.filename)
2078233Snate@binkert.org
2088233Snate@binkert.org    @property
2098233Snate@binkert.org    def extname(self):
2108233Snate@binkert.org        index = self.basename.rfind('.')
2118233Snate@binkert.org        if index <= 0:
2128233Snate@binkert.org            # dot files aren't extensions
2138233Snate@binkert.org            return self.basename, None
2148233Snate@binkert.org
2158233Snate@binkert.org        return self.basename[:index], self.basename[index+1:]
2168233Snate@binkert.org
2176143Snate@binkert.org    def __lt__(self, other): return self.filename < other.filename
2186143Snate@binkert.org    def __le__(self, other): return self.filename <= other.filename
2196143Snate@binkert.org    def __gt__(self, other): return self.filename > other.filename
2206143Snate@binkert.org    def __ge__(self, other): return self.filename >= other.filename
2216143Snate@binkert.org    def __eq__(self, other): return self.filename == other.filename
2226143Snate@binkert.org    def __ne__(self, other): return self.filename != other.filename
2239982Satgutier@umich.edu
22413576Sciro.santilli@arm.comdef blobToCpp(data, symbol, cpp_code, hpp_code=None, namespace=None):
22513576Sciro.santilli@arm.com    '''
22613576Sciro.santilli@arm.com    Convert bytes data into C++ .cpp and .hh uint8_t byte array
22713576Sciro.santilli@arm.com    code containing that binary data.
22813576Sciro.santilli@arm.com
22913576Sciro.santilli@arm.com    :param data: binary data to be converted to C++
23013576Sciro.santilli@arm.com    :param symbol: name of the symbol
23113576Sciro.santilli@arm.com    :param cpp_code: append the generated cpp_code to this object
23213576Sciro.santilli@arm.com    :param hpp_code: append the generated hpp_code to this object
23313576Sciro.santilli@arm.com                     If None, ignore it. Otherwise, also include it
23413576Sciro.santilli@arm.com                     in the .cpp file.
23513576Sciro.santilli@arm.com    :param namespace: namespace to put the symbol into. If None,
23613576Sciro.santilli@arm.com                      don't put the symbols into any namespace.
23713576Sciro.santilli@arm.com    '''
23813576Sciro.santilli@arm.com    symbol_len_declaration = 'const std::size_t {}_len'.format(symbol)
23913576Sciro.santilli@arm.com    symbol_declaration = 'const std::uint8_t {}[]'.format(symbol)
24013576Sciro.santilli@arm.com    if hpp_code is not None:
24113576Sciro.santilli@arm.com        cpp_code('''\
24213576Sciro.santilli@arm.com#include "blobs/{}.hh"
24313576Sciro.santilli@arm.com'''.format(symbol))
24413576Sciro.santilli@arm.com        hpp_code('''\
24513576Sciro.santilli@arm.com#include <cstddef>
24613576Sciro.santilli@arm.com#include <cstdint>
24713576Sciro.santilli@arm.com''')
24813576Sciro.santilli@arm.com        if namespace is not None:
24913576Sciro.santilli@arm.com            hpp_code('namespace {} {{'.format(namespace))
25013576Sciro.santilli@arm.com        hpp_code('extern ' + symbol_len_declaration + ';')
25113576Sciro.santilli@arm.com        hpp_code('extern ' + symbol_declaration + ';')
25213576Sciro.santilli@arm.com        if namespace is not None:
25313576Sciro.santilli@arm.com            hpp_code('}')
25413576Sciro.santilli@arm.com    if namespace is not None:
25513576Sciro.santilli@arm.com        cpp_code('namespace {} {{'.format(namespace))
25613630Sciro.santilli@arm.com    if hpp_code is not None:
25713630Sciro.santilli@arm.com        cpp_code(symbol_len_declaration + ' = {};'.format(len(data)))
25813576Sciro.santilli@arm.com    cpp_code(symbol_declaration + ' = {')
25913576Sciro.santilli@arm.com    cpp_code.indent()
26013576Sciro.santilli@arm.com    step = 16
26113576Sciro.santilli@arm.com    for i in xrange(0, len(data), step):
26213576Sciro.santilli@arm.com        x = array.array('B', data[i:i+step])
26313576Sciro.santilli@arm.com        cpp_code(''.join('%d,' % d for d in x))
26413576Sciro.santilli@arm.com    cpp_code.dedent()
26513576Sciro.santilli@arm.com    cpp_code('};')
26613576Sciro.santilli@arm.com    if namespace is not None:
26713576Sciro.santilli@arm.com        cpp_code('}')
26813576Sciro.santilli@arm.com
26913576Sciro.santilli@arm.comdef Blob(blob_path, symbol):
27013576Sciro.santilli@arm.com    '''
27113576Sciro.santilli@arm.com    Embed an arbitrary blob into the gem5 executable,
27213576Sciro.santilli@arm.com    and make it accessible to C++ as a byte array.
27313576Sciro.santilli@arm.com    '''
27413576Sciro.santilli@arm.com    blob_path = os.path.abspath(blob_path)
27513576Sciro.santilli@arm.com    blob_out_dir = os.path.join(env['BUILDDIR'], 'blobs')
27613576Sciro.santilli@arm.com    path_noext = joinpath(blob_out_dir, symbol)
27713576Sciro.santilli@arm.com    cpp_path = path_noext + '.cc'
27813576Sciro.santilli@arm.com    hpp_path = path_noext + '.hh'
27913576Sciro.santilli@arm.com    def embedBlob(target, source, env):
28013576Sciro.santilli@arm.com        data = file(str(source[0]), 'r').read()
28113576Sciro.santilli@arm.com        cpp_code = code_formatter()
28213576Sciro.santilli@arm.com        hpp_code = code_formatter()
28313576Sciro.santilli@arm.com        blobToCpp(data, symbol, cpp_code, hpp_code, namespace='Blobs')
28413576Sciro.santilli@arm.com        cpp_path = str(target[0])
28513576Sciro.santilli@arm.com        hpp_path = str(target[1])
28613576Sciro.santilli@arm.com        cpp_dir = os.path.split(cpp_path)[0]
28713576Sciro.santilli@arm.com        if not os.path.exists(cpp_dir):
28813576Sciro.santilli@arm.com            os.makedirs(cpp_dir)
28913576Sciro.santilli@arm.com        cpp_code.write(cpp_path)
29013576Sciro.santilli@arm.com        hpp_code.write(hpp_path)
29113576Sciro.santilli@arm.com    env.Command([cpp_path, hpp_path], blob_path,
29213576Sciro.santilli@arm.com                MakeAction(embedBlob, Transform("EMBED BLOB")))
29313576Sciro.santilli@arm.com    Source(cpp_path)
29413576Sciro.santilli@arm.com
29513577Sciro.santilli@arm.comdef GdbXml(xml_id, symbol):
29613577Sciro.santilli@arm.com    Blob(joinpath(gdb_xml_dir, xml_id), symbol)
29713577Sciro.santilli@arm.com
2986143Snate@binkert.orgclass Source(SourceFile):
29912302Sgabeblack@google.com    ungrouped_tag = 'No link group'
30012302Sgabeblack@google.com    source_groups = set()
30112302Sgabeblack@google.com
30212302Sgabeblack@google.com    _current_group_tag = ungrouped_tag
30312302Sgabeblack@google.com
30412302Sgabeblack@google.com    @staticmethod
30512302Sgabeblack@google.com    def link_group_tag(group):
30612302Sgabeblack@google.com        return 'link group: %s' % group
30711983Sgabeblack@google.com
30811983Sgabeblack@google.com    @classmethod
30911983Sgabeblack@google.com    def set_group(cls, group):
31012302Sgabeblack@google.com        new_tag = Source.link_group_tag(group)
31112302Sgabeblack@google.com        Source._current_group_tag = new_tag
31212302Sgabeblack@google.com        Source.source_groups.add(group)
31312302Sgabeblack@google.com
31412302Sgabeblack@google.com    def _add_link_group_tag(self):
31512302Sgabeblack@google.com        self.tags.add(Source._current_group_tag)
31611983Sgabeblack@google.com
3176143Snate@binkert.org    '''Add a c/c++ source file to the build'''
31812305Sgabeblack@google.com    def __init__(self, source, tags=None, add_tags=None):
31912302Sgabeblack@google.com        '''specify the source file, and any tags'''
32012302Sgabeblack@google.com        super(Source, self).__init__(source, tags, add_tags)
32112302Sgabeblack@google.com        self._add_link_group_tag()
3226143Snate@binkert.org
3236143Snate@binkert.orgclass PySource(SourceFile):
3246143Snate@binkert.org    '''Add a python source file to the named package'''
3255522Snate@binkert.org    invalid_sym_char = re.compile('[^A-z0-9_]')
3266143Snate@binkert.org    modules = {}
3276143Snate@binkert.org    tnodes = {}
3286143Snate@binkert.org    symnames = {}
3299982Satgutier@umich.edu
33012302Sgabeblack@google.com    def __init__(self, package, source, tags=None, add_tags=None):
33112302Sgabeblack@google.com        '''specify the python package, the source file, and any tags'''
33212302Sgabeblack@google.com        super(PySource, self).__init__(source, tags, add_tags)
3336143Snate@binkert.org
3346143Snate@binkert.org        modname,ext = self.extname
3356143Snate@binkert.org        assert ext == 'py'
3366143Snate@binkert.org
3375522Snate@binkert.org        if package:
3385522Snate@binkert.org            path = package.split('.')
3395522Snate@binkert.org        else:
3405522Snate@binkert.org            path = []
3415604Snate@binkert.org
3425604Snate@binkert.org        modpath = path[:]
3436143Snate@binkert.org        if modname != '__init__':
3446143Snate@binkert.org            modpath += [ modname ]
3454762Snate@binkert.org        modpath = '.'.join(modpath)
3464762Snate@binkert.org
3476143Snate@binkert.org        arcpath = path + [ self.basename ]
3486727Ssteve.reinhardt@amd.com        abspath = self.snode.abspath
3496727Ssteve.reinhardt@amd.com        if not exists(abspath):
3506727Ssteve.reinhardt@amd.com            abspath = self.tnode.abspath
3514762Snate@binkert.org
3526143Snate@binkert.org        self.package = package
3536143Snate@binkert.org        self.modname = modname
3546143Snate@binkert.org        self.modpath = modpath
3556143Snate@binkert.org        self.arcname = joinpath(*arcpath)
3566727Ssteve.reinhardt@amd.com        self.abspath = abspath
3576143Snate@binkert.org        self.compiled = File(self.filename + 'c')
3587674Snate@binkert.org        self.cpp = File(self.filename + '.cc')
3597674Snate@binkert.org        self.symname = PySource.invalid_sym_char.sub('_', modpath)
3605604Snate@binkert.org
3616143Snate@binkert.org        PySource.modules[modpath] = self
3626143Snate@binkert.org        PySource.tnodes[self.tnode] = self
3636143Snate@binkert.org        PySource.symnames[self.symname] = self
3644762Snate@binkert.org
3656143Snate@binkert.orgclass SimObject(PySource):
3664762Snate@binkert.org    '''Add a SimObject python file as a python source object and add
3674762Snate@binkert.org    it to a list of sim object modules'''
3684762Snate@binkert.org
3696143Snate@binkert.org    fixed = False
3706143Snate@binkert.org    modnames = []
3714762Snate@binkert.org
37212302Sgabeblack@google.com    def __init__(self, source, tags=None, add_tags=None):
37312302Sgabeblack@google.com        '''Specify the source file and any tags (automatically in
3748233Snate@binkert.org        the m5.objects package)'''
37512302Sgabeblack@google.com        super(SimObject, self).__init__('m5.objects', source, tags, add_tags)
3766143Snate@binkert.org        if self.fixed:
3776143Snate@binkert.org            raise AttributeError, "Too late to call SimObject now."
3784762Snate@binkert.org
3796143Snate@binkert.org        bisect.insort_right(SimObject.modnames, self.modname)
3804762Snate@binkert.org
3819396Sandreas.hansson@arm.comclass ProtoBuf(SourceFile):
3829396Sandreas.hansson@arm.com    '''Add a Protocol Buffer to build'''
3839396Sandreas.hansson@arm.com
38412302Sgabeblack@google.com    def __init__(self, source, tags=None, add_tags=None):
38512302Sgabeblack@google.com        '''Specify the source file, and any tags'''
38612302Sgabeblack@google.com        super(ProtoBuf, self).__init__(source, tags, add_tags)
3879396Sandreas.hansson@arm.com
3889396Sandreas.hansson@arm.com        # Get the file name and the extension
3899396Sandreas.hansson@arm.com        modname,ext = self.extname
3909396Sandreas.hansson@arm.com        assert ext == 'proto'
3919396Sandreas.hansson@arm.com
3929396Sandreas.hansson@arm.com        # Currently, we stick to generating the C++ headers, so we
3939396Sandreas.hansson@arm.com        # only need to track the source and header.
3949930Sandreas.hansson@arm.com        self.cc_file = File(modname + '.pb.cc')
3959930Sandreas.hansson@arm.com        self.hh_file = File(modname + '.pb.h')
3969396Sandreas.hansson@arm.com
3976143Snate@binkert.org
39812797Sgabeblack@google.comexectuable_classes = []
39912797Sgabeblack@google.comclass ExecutableMeta(type):
40012797Sgabeblack@google.com    '''Meta class for Executables.'''
4018235Snate@binkert.org    all = []
40212797Sgabeblack@google.com
40312797Sgabeblack@google.com    def __init__(cls, name, bases, d):
40412797Sgabeblack@google.com        if not d.pop('abstract', False):
40512797Sgabeblack@google.com            ExecutableMeta.all.append(cls)
40612797Sgabeblack@google.com        super(ExecutableMeta, cls).__init__(name, bases, d)
40712797Sgabeblack@google.com
40812797Sgabeblack@google.com        cls.all = []
40912797Sgabeblack@google.com
41012797Sgabeblack@google.comclass Executable(object):
41112797Sgabeblack@google.com    '''Base class for creating an executable from sources.'''
41212797Sgabeblack@google.com    __metaclass__ = ExecutableMeta
41312797Sgabeblack@google.com
41412797Sgabeblack@google.com    abstract = True
41512797Sgabeblack@google.com
41612797Sgabeblack@google.com    def __init__(self, target, *srcs_and_filts):
41712757Sgabeblack@google.com        '''Specify the target name and any sources. Sources that are
41812757Sgabeblack@google.com        not SourceFiles are evalued with Source().'''
41912797Sgabeblack@google.com        super(Executable, self).__init__()
42012797Sgabeblack@google.com        self.all.append(self)
42112797Sgabeblack@google.com        self.target = target
42212757Sgabeblack@google.com
42312757Sgabeblack@google.com        isFilter = lambda arg: isinstance(arg, SourceFilter)
42412757Sgabeblack@google.com        self.filters = filter(isFilter, srcs_and_filts)
42512757Sgabeblack@google.com        sources = filter(lambda a: not isFilter(a), srcs_and_filts)
4268235Snate@binkert.org
42712302Sgabeblack@google.com        srcs = SourceList()
4288235Snate@binkert.org        for src in sources:
4298235Snate@binkert.org            if not isinstance(src, SourceFile):
43012757Sgabeblack@google.com                src = Source(src, tags=[])
4318235Snate@binkert.org            srcs.append(src)
4328235Snate@binkert.org
4338235Snate@binkert.org        self.sources = srcs
43412757Sgabeblack@google.com        self.dir = Dir('.')
43512313Sgabeblack@google.com
43612797Sgabeblack@google.com    def path(self, env):
43712797Sgabeblack@google.com        return self.dir.File(self.target + '.' + env['EXE_SUFFIX'])
43812797Sgabeblack@google.com
43912797Sgabeblack@google.com    def srcs_to_objs(self, env, sources):
44012797Sgabeblack@google.com        return list([ s.static(env) for s in sources ])
44112797Sgabeblack@google.com
44212797Sgabeblack@google.com    @classmethod
44312797Sgabeblack@google.com    def declare_all(cls, env):
44412797Sgabeblack@google.com        return list([ instance.declare(env) for instance in cls.all ])
44512797Sgabeblack@google.com
44612797Sgabeblack@google.com    def declare(self, env, objs=None):
44712797Sgabeblack@google.com        if objs is None:
44812797Sgabeblack@google.com            objs = self.srcs_to_objs(env, self.sources)
44912797Sgabeblack@google.com
45013706Sgabeblack@google.com        env = env.Clone()
45113706Sgabeblack@google.com        env['BIN_RPATH_PREFIX'] = os.path.relpath(
45213706Sgabeblack@google.com                env['BUILDDIR'], self.path(env).dir.abspath)
45313706Sgabeblack@google.com
45412797Sgabeblack@google.com        if env['STRIP_EXES']:
45512797Sgabeblack@google.com            stripped = self.path(env)
45612797Sgabeblack@google.com            unstripped = env.File(str(stripped) + '.unstripped')
45712797Sgabeblack@google.com            if sys.platform == 'sunos5':
45812797Sgabeblack@google.com                cmd = 'cp $SOURCE $TARGET; strip $TARGET'
45912797Sgabeblack@google.com            else:
46012797Sgabeblack@google.com                cmd = 'strip $SOURCE -o $TARGET'
46112797Sgabeblack@google.com            env.Program(unstripped, objs)
46212797Sgabeblack@google.com            return env.Command(stripped, unstripped,
46312797Sgabeblack@google.com                               MakeAction(cmd, Transform("STRIP")))
46412797Sgabeblack@google.com        else:
46512797Sgabeblack@google.com            return env.Program(self.path(env), objs)
46612797Sgabeblack@google.com
46712797Sgabeblack@google.comclass UnitTest(Executable):
46812797Sgabeblack@google.com    '''Create a UnitTest'''
46912797Sgabeblack@google.com    def __init__(self, target, *srcs_and_filts, **kwargs):
47012797Sgabeblack@google.com        super(UnitTest, self).__init__(target, *srcs_and_filts)
47112797Sgabeblack@google.com
47212797Sgabeblack@google.com        self.main = kwargs.get('main', False)
47312797Sgabeblack@google.com
47412797Sgabeblack@google.com    def declare(self, env):
47512797Sgabeblack@google.com        sources = list(self.sources)
47612797Sgabeblack@google.com        for f in self.filters:
47713656Sgabeblack@google.com            sources += Source.all.apply_filter(f)
47812797Sgabeblack@google.com        objs = self.srcs_to_objs(env, sources) + env['STATIC_OBJS']
47912797Sgabeblack@google.com        if self.main:
48012797Sgabeblack@google.com            objs += env['MAIN_OBJS']
48112797Sgabeblack@google.com        return super(UnitTest, self).declare(env, objs)
48212797Sgabeblack@google.com
48312797Sgabeblack@google.comclass GTest(Executable):
48412313Sgabeblack@google.com    '''Create a unit test based on the google test framework.'''
48512313Sgabeblack@google.com    all = []
48612797Sgabeblack@google.com    def __init__(self, *srcs_and_filts, **kwargs):
48712797Sgabeblack@google.com        super(GTest, self).__init__(*srcs_and_filts)
48812797Sgabeblack@google.com
48912371Sgabeblack@google.com        self.skip_lib = kwargs.pop('skip_lib', False)
4905584Snate@binkert.org
49112797Sgabeblack@google.com    @classmethod
49212797Sgabeblack@google.com    def declare_all(cls, env):
49312797Sgabeblack@google.com        env = env.Clone()
49412797Sgabeblack@google.com        env.Append(LIBS=env['GTEST_LIBS'])
49512797Sgabeblack@google.com        env.Append(CPPFLAGS=env['GTEST_CPPFLAGS'])
49612797Sgabeblack@google.com        env['GTEST_LIB_SOURCES'] = Source.all.with_tag('gtest lib')
49712797Sgabeblack@google.com        env['GTEST_OUT_DIR'] = \
49812797Sgabeblack@google.com            Dir(env['BUILDDIR']).Dir('unittests.' + env['EXE_SUFFIX'])
49912797Sgabeblack@google.com        return super(GTest, cls).declare_all(env)
50012797Sgabeblack@google.com
50112797Sgabeblack@google.com    def declare(self, env):
50212797Sgabeblack@google.com        sources = list(self.sources)
50312797Sgabeblack@google.com        if not self.skip_lib:
50412797Sgabeblack@google.com            sources += env['GTEST_LIB_SOURCES']
50512797Sgabeblack@google.com        for f in self.filters:
50612797Sgabeblack@google.com            sources += Source.all.apply_filter(f)
50712797Sgabeblack@google.com        objs = self.srcs_to_objs(env, sources)
50812797Sgabeblack@google.com
50912797Sgabeblack@google.com        binary = super(GTest, self).declare(env, objs)
51012797Sgabeblack@google.com
51112797Sgabeblack@google.com        out_dir = env['GTEST_OUT_DIR']
51212797Sgabeblack@google.com        xml_file = out_dir.Dir(str(self.dir)).File(self.target + '.xml')
51312797Sgabeblack@google.com        AlwaysBuild(env.Command(xml_file, binary,
51412797Sgabeblack@google.com            "${SOURCES[0]} --gtest_output=xml:${TARGETS[0]}"))
51512797Sgabeblack@google.com
51612797Sgabeblack@google.com        return binary
51712797Sgabeblack@google.com
51812797Sgabeblack@google.comclass Gem5(Executable):
51912797Sgabeblack@google.com    '''Create a gem5 executable.'''
52012797Sgabeblack@google.com
52112797Sgabeblack@google.com    def __init__(self, target):
52212797Sgabeblack@google.com        super(Gem5, self).__init__(target)
52312797Sgabeblack@google.com
52412797Sgabeblack@google.com    def declare(self, env):
52512797Sgabeblack@google.com        objs = env['MAIN_OBJS'] + env['STATIC_OBJS']
52612797Sgabeblack@google.com        return super(Gem5, self).declare(env, objs)
52712797Sgabeblack@google.com
52812797Sgabeblack@google.com
5294382Sbinkertn@umich.edu# Children should have access
53013576Sciro.santilli@arm.comExport('Blob')
53113577Sciro.santilli@arm.comExport('GdbXml')
5324202Sbinkertn@umich.eduExport('Source')
5334382Sbinkertn@umich.eduExport('PySource')
5344382Sbinkertn@umich.eduExport('SimObject')
5359396Sandreas.hansson@arm.comExport('ProtoBuf')
53612797Sgabeblack@google.comExport('Executable')
5375584Snate@binkert.orgExport('UnitTest')
53812313Sgabeblack@google.comExport('GTest')
5394382Sbinkertn@umich.edu
5404382Sbinkertn@umich.edu########################################################################
5414382Sbinkertn@umich.edu#
5428232Snate@binkert.org# Debug Flags
5435192Ssaidi@eecs.umich.edu#
5448232Snate@binkert.orgdebug_flags = {}
5458232Snate@binkert.orgdef DebugFlag(name, desc=None):
5468232Snate@binkert.org    if name in debug_flags:
5475192Ssaidi@eecs.umich.edu        raise AttributeError, "Flag %s already specified" % name
5488232Snate@binkert.org    debug_flags[name] = (name, (), desc)
5495192Ssaidi@eecs.umich.edu
5505799Snate@binkert.orgdef CompoundFlag(name, flags, desc=None):
5518232Snate@binkert.org    if name in debug_flags:
5525192Ssaidi@eecs.umich.edu        raise AttributeError, "Flag %s already specified" % name
5535192Ssaidi@eecs.umich.edu
5545192Ssaidi@eecs.umich.edu    compound = tuple(flags)
5558232Snate@binkert.org    debug_flags[name] = (name, compound, desc)
5565192Ssaidi@eecs.umich.edu
5578232Snate@binkert.orgExport('DebugFlag')
5585192Ssaidi@eecs.umich.eduExport('CompoundFlag')
5595192Ssaidi@eecs.umich.edu
5605192Ssaidi@eecs.umich.edu########################################################################
5615192Ssaidi@eecs.umich.edu#
5624382Sbinkertn@umich.edu# Set some compiler variables
5634382Sbinkertn@umich.edu#
5644382Sbinkertn@umich.edu
5652667Sstever@eecs.umich.edu# Include file paths are rooted in this directory.  SCons will
5662667Sstever@eecs.umich.edu# automatically expand '.' to refer to both the source directory and
5672667Sstever@eecs.umich.edu# the corresponding build directory to pick up generated include
5682667Sstever@eecs.umich.edu# files.
5692667Sstever@eecs.umich.eduenv.Append(CPPPATH=Dir('.'))
5702667Sstever@eecs.umich.edu
5715742Snate@binkert.orgfor extra_dir in extras_dir_list:
5725742Snate@binkert.org    env.Append(CPPPATH=Dir(extra_dir))
5735742Snate@binkert.org
5745793Snate@binkert.org# Workaround for bug in SCons version > 0.97d20071212
5758334Snate@binkert.org# Scons bug id: 2006 gem5 Bug id: 308
5765793Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
5775793Snate@binkert.org    Dir(root[len(base_dir) + 1:])
5785793Snate@binkert.org
5794382Sbinkertn@umich.edu########################################################################
5804762Snate@binkert.org#
5815344Sstever@gmail.com# Walk the tree and execute all SConscripts in subdirectories
5824382Sbinkertn@umich.edu#
5835341Sstever@gmail.com
5845742Snate@binkert.orghere = Dir('.').srcnode().abspath
5855742Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
5865742Snate@binkert.org    if root == here:
5875742Snate@binkert.org        # we don't want to recurse back into this SConscript
5885742Snate@binkert.org        continue
5894762Snate@binkert.org
5905742Snate@binkert.org    if 'SConscript' in files:
5915742Snate@binkert.org        build_dir = joinpath(env['BUILDDIR'], root[len(base_dir) + 1:])
59211984Sgabeblack@google.com        Source.set_group(build_dir)
5937722Sgblack@eecs.umich.edu        SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
5945742Snate@binkert.org
5955742Snate@binkert.orgfor extra_dir in extras_dir_list:
5965742Snate@binkert.org    prefix_len = len(dirname(extra_dir)) + 1
5979930Sandreas.hansson@arm.com
5989930Sandreas.hansson@arm.com    # Also add the corresponding build directory to pick up generated
5999930Sandreas.hansson@arm.com    # include files.
6009930Sandreas.hansson@arm.com    env.Append(CPPPATH=Dir(joinpath(env['BUILDDIR'], extra_dir[prefix_len:])))
6019930Sandreas.hansson@arm.com
6025742Snate@binkert.org    for root, dirs, files in os.walk(extra_dir, topdown=True):
6038242Sbradley.danofsky@amd.com        # if build lives in the extras directory, don't walk down it
6048242Sbradley.danofsky@amd.com        if 'build' in dirs:
6058242Sbradley.danofsky@amd.com            dirs.remove('build')
6068242Sbradley.danofsky@amd.com
6075341Sstever@gmail.com        if 'SConscript' in files:
6085742Snate@binkert.org            build_dir = joinpath(env['BUILDDIR'], root[prefix_len:])
6097722Sgblack@eecs.umich.edu            SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
6104773Snate@binkert.org
6116108Snate@binkert.orgfor opt in export_vars:
6121858SN/A    env.ConfigFile(opt)
6131085SN/A
6146658Snate@binkert.orgdef makeTheISA(source, target, env):
6156658Snate@binkert.org    isas = [ src.get_contents() for src in source ]
6167673Snate@binkert.org    target_isa = env['TARGET_ISA']
6176658Snate@binkert.org    def define(isa):
6186658Snate@binkert.org        return isa.upper() + '_ISA'
61911308Santhony.gutierrez@amd.com
6206658Snate@binkert.org    def namespace(isa):
62111308Santhony.gutierrez@amd.com        return isa[0].upper() + isa[1:].lower() + 'ISA'
6226658Snate@binkert.org
6236658Snate@binkert.org
6247673Snate@binkert.org    code = code_formatter()
6257673Snate@binkert.org    code('''\
6267673Snate@binkert.org#ifndef __CONFIG_THE_ISA_HH__
6277673Snate@binkert.org#define __CONFIG_THE_ISA_HH__
6287673Snate@binkert.org
6297673Snate@binkert.org''')
6307673Snate@binkert.org
63110467Sandreas.hansson@arm.com    # create defines for the preprocessing and compile-time determination
6326658Snate@binkert.org    for i,isa in enumerate(isas):
6337673Snate@binkert.org        code('#define $0 $1', define(isa), i + 1)
63410467Sandreas.hansson@arm.com    code()
63510467Sandreas.hansson@arm.com
63610467Sandreas.hansson@arm.com    # create an enum for any run-time determination of the ISA, we
63710467Sandreas.hansson@arm.com    # reuse the same name as the namespaces
63810467Sandreas.hansson@arm.com    code('enum class Arch {')
63910467Sandreas.hansson@arm.com    for i,isa in enumerate(isas):
64010467Sandreas.hansson@arm.com        if i + 1 == len(isas):
64110467Sandreas.hansson@arm.com            code('  $0 = $1', namespace(isa), define(isa))
64210467Sandreas.hansson@arm.com        else:
64310467Sandreas.hansson@arm.com            code('  $0 = $1,', namespace(isa), define(isa))
64410467Sandreas.hansson@arm.com    code('};')
6457673Snate@binkert.org
6467673Snate@binkert.org    code('''
6477673Snate@binkert.org
6487673Snate@binkert.org#define THE_ISA ${{define(target_isa)}}
6497673Snate@binkert.org#define TheISA ${{namespace(target_isa)}}
6509048SAli.Saidi@ARM.com#define THE_ISA_STR "${{target_isa}}"
6517673Snate@binkert.org
6527673Snate@binkert.org#endif // __CONFIG_THE_ISA_HH__''')
6537673Snate@binkert.org
6547673Snate@binkert.org    code.write(str(target[0]))
6556658Snate@binkert.org
6567756SAli.Saidi@ARM.comenv.Command('config/the_isa.hh', map(Value, all_isa_list),
6577816Ssteve.reinhardt@amd.com            MakeAction(makeTheISA, Transform("CFG ISA", 0)))
6586658Snate@binkert.org
65911308Santhony.gutierrez@amd.comdef makeTheGPUISA(source, target, env):
66011308Santhony.gutierrez@amd.com    isas = [ src.get_contents() for src in source ]
66111308Santhony.gutierrez@amd.com    target_gpu_isa = env['TARGET_GPU_ISA']
66211308Santhony.gutierrez@amd.com    def define(isa):
66311308Santhony.gutierrez@amd.com        return isa.upper() + '_ISA'
66411308Santhony.gutierrez@amd.com
66511308Santhony.gutierrez@amd.com    def namespace(isa):
66611308Santhony.gutierrez@amd.com        return isa[0].upper() + isa[1:].lower() + 'ISA'
66711308Santhony.gutierrez@amd.com
66811308Santhony.gutierrez@amd.com
66911308Santhony.gutierrez@amd.com    code = code_formatter()
67011308Santhony.gutierrez@amd.com    code('''\
67111308Santhony.gutierrez@amd.com#ifndef __CONFIG_THE_GPU_ISA_HH__
67211308Santhony.gutierrez@amd.com#define __CONFIG_THE_GPU_ISA_HH__
67311308Santhony.gutierrez@amd.com
67411308Santhony.gutierrez@amd.com''')
67511308Santhony.gutierrez@amd.com
67611308Santhony.gutierrez@amd.com    # create defines for the preprocessing and compile-time determination
67711308Santhony.gutierrez@amd.com    for i,isa in enumerate(isas):
67811308Santhony.gutierrez@amd.com        code('#define $0 $1', define(isa), i + 1)
67911308Santhony.gutierrez@amd.com    code()
68011308Santhony.gutierrez@amd.com
68111308Santhony.gutierrez@amd.com    # create an enum for any run-time determination of the ISA, we
68211308Santhony.gutierrez@amd.com    # reuse the same name as the namespaces
68311308Santhony.gutierrez@amd.com    code('enum class GPUArch {')
68411308Santhony.gutierrez@amd.com    for i,isa in enumerate(isas):
68511308Santhony.gutierrez@amd.com        if i + 1 == len(isas):
68611308Santhony.gutierrez@amd.com            code('  $0 = $1', namespace(isa), define(isa))
68711308Santhony.gutierrez@amd.com        else:
68811308Santhony.gutierrez@amd.com            code('  $0 = $1,', namespace(isa), define(isa))
68911308Santhony.gutierrez@amd.com    code('};')
69011308Santhony.gutierrez@amd.com
69111308Santhony.gutierrez@amd.com    code('''
69211308Santhony.gutierrez@amd.com
69311308Santhony.gutierrez@amd.com#define THE_GPU_ISA ${{define(target_gpu_isa)}}
69411308Santhony.gutierrez@amd.com#define TheGpuISA ${{namespace(target_gpu_isa)}}
69511308Santhony.gutierrez@amd.com#define THE_GPU_ISA_STR "${{target_gpu_isa}}"
69611308Santhony.gutierrez@amd.com
69711308Santhony.gutierrez@amd.com#endif // __CONFIG_THE_GPU_ISA_HH__''')
69811308Santhony.gutierrez@amd.com
69911308Santhony.gutierrez@amd.com    code.write(str(target[0]))
70011308Santhony.gutierrez@amd.com
70111308Santhony.gutierrez@amd.comenv.Command('config/the_gpu_isa.hh', map(Value, all_gpu_isa_list),
70211308Santhony.gutierrez@amd.com            MakeAction(makeTheGPUISA, Transform("CFG ISA", 0)))
70311308Santhony.gutierrez@amd.com
7044382Sbinkertn@umich.edu########################################################################
7054382Sbinkertn@umich.edu#
7064762Snate@binkert.org# Prevent any SimObjects from being added after this point, they
7074762Snate@binkert.org# should all have been added in the SConscripts above
7084762Snate@binkert.org#
7096654Snate@binkert.orgSimObject.fixed = True
7106654Snate@binkert.org
7115517Snate@binkert.orgclass DictImporter(object):
7125517Snate@binkert.org    '''This importer takes a dictionary of arbitrary module names that
7135517Snate@binkert.org    map to arbitrary filenames.'''
7145517Snate@binkert.org    def __init__(self, modules):
7155517Snate@binkert.org        self.modules = modules
7165517Snate@binkert.org        self.installed = set()
7175517Snate@binkert.org
7185517Snate@binkert.org    def __del__(self):
7195517Snate@binkert.org        self.unload()
7205517Snate@binkert.org
7215517Snate@binkert.org    def unload(self):
7225517Snate@binkert.org        import sys
7235517Snate@binkert.org        for module in self.installed:
7245517Snate@binkert.org            del sys.modules[module]
7255517Snate@binkert.org        self.installed = set()
7265517Snate@binkert.org
7275517Snate@binkert.org    def find_module(self, fullname, path):
7286654Snate@binkert.org        if fullname == 'm5.defines':
7295517Snate@binkert.org            return self
7305517Snate@binkert.org
7315517Snate@binkert.org        if fullname == 'm5.objects':
7325517Snate@binkert.org            return self
7335517Snate@binkert.org
73411802Sandreas.sandberg@arm.com        if fullname.startswith('_m5'):
7355517Snate@binkert.org            return None
7365517Snate@binkert.org
7376143Snate@binkert.org        source = self.modules.get(fullname, None)
7386654Snate@binkert.org        if source is not None and fullname.startswith('m5.objects'):
7395517Snate@binkert.org            return self
7405517Snate@binkert.org
7415517Snate@binkert.org        return None
7425517Snate@binkert.org
7435517Snate@binkert.org    def load_module(self, fullname):
7445517Snate@binkert.org        mod = imp.new_module(fullname)
7455517Snate@binkert.org        sys.modules[fullname] = mod
7465517Snate@binkert.org        self.installed.add(fullname)
7475517Snate@binkert.org
7485517Snate@binkert.org        mod.__loader__ = self
7495517Snate@binkert.org        if fullname == 'm5.objects':
7505517Snate@binkert.org            mod.__path__ = fullname.split('.')
7515517Snate@binkert.org            return mod
7525517Snate@binkert.org
7536654Snate@binkert.org        if fullname == 'm5.defines':
7546654Snate@binkert.org            mod.__dict__['buildEnv'] = m5.util.SmartDict(build_env)
7555517Snate@binkert.org            return mod
7565517Snate@binkert.org
7576143Snate@binkert.org        source = self.modules[fullname]
7586143Snate@binkert.org        if source.modname == '__init__':
7596143Snate@binkert.org            mod.__path__ = source.modpath
7606727Ssteve.reinhardt@amd.com        mod.__file__ = source.abspath
7615517Snate@binkert.org
7626727Ssteve.reinhardt@amd.com        exec file(source.abspath, 'r') in mod.__dict__
7635517Snate@binkert.org
7645517Snate@binkert.org        return mod
7655517Snate@binkert.org
7666654Snate@binkert.orgimport m5.SimObject
7676654Snate@binkert.orgimport m5.params
7687673Snate@binkert.orgfrom m5.util import code_formatter
7696654Snate@binkert.org
7706654Snate@binkert.orgm5.SimObject.clear()
7716654Snate@binkert.orgm5.params.clear()
7726654Snate@binkert.org
7735517Snate@binkert.org# install the python importer so we can grab stuff from the source
7745517Snate@binkert.org# tree itself.  We can't have SimObjects added after this point or
7755517Snate@binkert.org# else we won't know about them for the rest of the stuff.
7766143Snate@binkert.orgimporter = DictImporter(PySource.modules)
7775517Snate@binkert.orgsys.meta_path[0:0] = [ importer ]
7784762Snate@binkert.org
7795517Snate@binkert.org# import all sim objects so we can populate the all_objects list
7805517Snate@binkert.org# make sure that we're working with a list, then let's sort it
7816143Snate@binkert.orgfor modname in SimObject.modnames:
7826143Snate@binkert.org    exec('from m5.objects import %s' % modname)
7835517Snate@binkert.org
7845517Snate@binkert.org# we need to unload all of the currently imported modules so that they
7855517Snate@binkert.org# will be re-imported the next time the sconscript is run
7865517Snate@binkert.orgimporter.unload()
7875517Snate@binkert.orgsys.meta_path.remove(importer)
7885517Snate@binkert.org
7895517Snate@binkert.orgsim_objects = m5.SimObject.allClasses
7905517Snate@binkert.orgall_enums = m5.params.allEnums
7915517Snate@binkert.org
7926143Snate@binkert.orgfor name,obj in sorted(sim_objects.iteritems()):
7935517Snate@binkert.org    for param in obj._params.local.values():
7946654Snate@binkert.org        # load the ptype attribute now because it depends on the
7956654Snate@binkert.org        # current version of SimObject.allClasses, but when scons
7966654Snate@binkert.org        # actually uses the value, all versions of
7976654Snate@binkert.org        # SimObject.allClasses will have been loaded
7986654Snate@binkert.org        param.ptype
7996654Snate@binkert.org
8004762Snate@binkert.org########################################################################
8014762Snate@binkert.org#
8024762Snate@binkert.org# calculate extra dependencies
8034762Snate@binkert.org#
8044762Snate@binkert.orgmodule_depends = ["m5", "m5.SimObject", "m5.params"]
8057675Snate@binkert.orgdepends = [ PySource.modules[dep].snode for dep in module_depends ]
80610584Sandreas.hansson@arm.comdepends.sort(key = lambda x: x.name)
8074762Snate@binkert.org
8084762Snate@binkert.org########################################################################
8094762Snate@binkert.org#
8104762Snate@binkert.org# Commands for the basic automatically generated python files
8114382Sbinkertn@umich.edu#
8124382Sbinkertn@umich.edu
8135517Snate@binkert.org# Generate Python file containing a dict specifying the current
8146654Snate@binkert.org# buildEnv flags.
8155517Snate@binkert.orgdef makeDefinesPyFile(target, source, env):
8168126Sgblack@eecs.umich.edu    build_env = source[0].get_contents()
8176654Snate@binkert.org
8187673Snate@binkert.org    code = code_formatter()
8196654Snate@binkert.org    code("""
82011802Sandreas.sandberg@arm.comimport _m5.core
8216654Snate@binkert.orgimport m5.util
8226654Snate@binkert.org
8236654Snate@binkert.orgbuildEnv = m5.util.SmartDict($build_env)
8246654Snate@binkert.org
82511802Sandreas.sandberg@arm.comcompileDate = _m5.core.compileDate
8266669Snate@binkert.org_globals = globals()
82713709Sandreas.sandberg@arm.comfor key,val in _m5.core.__dict__.items():
8286669Snate@binkert.org    if key.startswith('flag_'):
8296669Snate@binkert.org        flag = key[5:]
8306669Snate@binkert.org        _globals[flag] = val
8316669Snate@binkert.orgdel _globals
8326654Snate@binkert.org""")
8337673Snate@binkert.org    code.write(target[0].abspath)
8345517Snate@binkert.org
8358126Sgblack@eecs.umich.edudefines_info = Value(build_env)
8365798Snate@binkert.org# Generate a file with all of the compile options in it
8377756SAli.Saidi@ARM.comenv.Command('python/m5/defines.py', defines_info,
8387816Ssteve.reinhardt@amd.com            MakeAction(makeDefinesPyFile, Transform("DEFINES", 0)))
8395798Snate@binkert.orgPySource('m5', 'python/m5/defines.py')
8405798Snate@binkert.org
8415517Snate@binkert.org# Generate python file containing info about the M5 source code
8425517Snate@binkert.orgdef makeInfoPyFile(target, source, env):
8437673Snate@binkert.org    code = code_formatter()
8445517Snate@binkert.org    for src in source:
8455517Snate@binkert.org        data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
8467673Snate@binkert.org        code('$src = ${{repr(data)}}')
8477673Snate@binkert.org    code.write(str(target[0]))
8485517Snate@binkert.org
8495798Snate@binkert.org# Generate a file that wraps the basic top level files
8505798Snate@binkert.orgenv.Command('python/m5/info.py',
8518333Snate@binkert.org            [ '#/COPYING', '#/LICENSE', '#/README', ],
8527816Ssteve.reinhardt@amd.com            MakeAction(makeInfoPyFile, Transform("INFO")))
8535798Snate@binkert.orgPySource('m5', 'python/m5/info.py')
8545798Snate@binkert.org
8554762Snate@binkert.org########################################################################
8564762Snate@binkert.org#
8574762Snate@binkert.org# Create all of the SimObject param headers and enum headers
8584762Snate@binkert.org#
8594762Snate@binkert.org
8608596Ssteve.reinhardt@amd.comdef createSimObjectParamStruct(target, source, env):
8615517Snate@binkert.org    assert len(target) == 1 and len(source) == 1
8625517Snate@binkert.org
86311997Sgabeblack@google.com    name = source[0].get_text_contents()
8645517Snate@binkert.org    obj = sim_objects[name]
8655517Snate@binkert.org
8667673Snate@binkert.org    code = code_formatter()
8678596Ssteve.reinhardt@amd.com    obj.cxx_param_decl(code)
8687673Snate@binkert.org    code.write(target[0].abspath)
8695517Snate@binkert.org
87010458Sandreas.hansson@arm.comdef createSimObjectCxxConfig(is_header):
87110458Sandreas.hansson@arm.com    def body(target, source, env):
87210458Sandreas.hansson@arm.com        assert len(target) == 1 and len(source) == 1
87310458Sandreas.hansson@arm.com
87410458Sandreas.hansson@arm.com        name = str(source[0].get_contents())
87510458Sandreas.hansson@arm.com        obj = sim_objects[name]
87610458Sandreas.hansson@arm.com
87710458Sandreas.hansson@arm.com        code = code_formatter()
87810458Sandreas.hansson@arm.com        obj.cxx_config_param_file(code, is_header)
87910458Sandreas.hansson@arm.com        code.write(target[0].abspath)
88010458Sandreas.hansson@arm.com    return body
88110458Sandreas.hansson@arm.com
8825517Snate@binkert.orgdef createEnumStrings(target, source, env):
88311996Sgabeblack@google.com    assert len(target) == 1 and len(source) == 2
8845517Snate@binkert.org
88511997Sgabeblack@google.com    name = source[0].get_text_contents()
88611996Sgabeblack@google.com    use_python = source[1].read()
8875517Snate@binkert.org    obj = all_enums[name]
8885517Snate@binkert.org
8897673Snate@binkert.org    code = code_formatter()
8907673Snate@binkert.org    obj.cxx_def(code)
89111996Sgabeblack@google.com    if use_python:
89211988Sandreas.sandberg@arm.com        obj.pybind_def(code)
8937673Snate@binkert.org    code.write(target[0].abspath)
8945517Snate@binkert.org
8958596Ssteve.reinhardt@amd.comdef createEnumDecls(target, source, env):
8965517Snate@binkert.org    assert len(target) == 1 and len(source) == 1
8975517Snate@binkert.org
89811997Sgabeblack@google.com    name = source[0].get_text_contents()
8995517Snate@binkert.org    obj = all_enums[name]
9005517Snate@binkert.org
9017673Snate@binkert.org    code = code_formatter()
9027673Snate@binkert.org    obj.cxx_decl(code)
9037673Snate@binkert.org    code.write(target[0].abspath)
9045517Snate@binkert.org
90511988Sandreas.sandberg@arm.comdef createSimObjectPyBindWrapper(target, source, env):
90611997Sgabeblack@google.com    name = source[0].get_text_contents()
9078596Ssteve.reinhardt@amd.com    obj = sim_objects[name]
9088596Ssteve.reinhardt@amd.com
9098596Ssteve.reinhardt@amd.com    code = code_formatter()
91011988Sandreas.sandberg@arm.com    obj.pybind_decl(code)
9118596Ssteve.reinhardt@amd.com    code.write(target[0].abspath)
9128596Ssteve.reinhardt@amd.com
9138596Ssteve.reinhardt@amd.com# Generate all of the SimObject param C++ struct header files
9144762Snate@binkert.orgparams_hh_files = []
9156143Snate@binkert.orgfor name,simobj in sorted(sim_objects.iteritems()):
9166143Snate@binkert.org    py_source = PySource.modules[simobj.__module__]
9176143Snate@binkert.org    extra_deps = [ py_source.tnode ]
9184762Snate@binkert.org
9194762Snate@binkert.org    hh_file = File('params/%s.hh' % name)
9204762Snate@binkert.org    params_hh_files.append(hh_file)
9217756SAli.Saidi@ARM.com    env.Command(hh_file, Value(name),
9228596Ssteve.reinhardt@amd.com                MakeAction(createSimObjectParamStruct, Transform("SO PARAM")))
9234762Snate@binkert.org    env.Depends(hh_file, depends + extra_deps)
9244762Snate@binkert.org
92510458Sandreas.hansson@arm.com# C++ parameter description files
92610458Sandreas.hansson@arm.comif GetOption('with_cxx_config'):
92710458Sandreas.hansson@arm.com    for name,simobj in sorted(sim_objects.iteritems()):
92810458Sandreas.hansson@arm.com        py_source = PySource.modules[simobj.__module__]
92910458Sandreas.hansson@arm.com        extra_deps = [ py_source.tnode ]
93010458Sandreas.hansson@arm.com
93110458Sandreas.hansson@arm.com        cxx_config_hh_file = File('cxx_config/%s.hh' % name)
93210458Sandreas.hansson@arm.com        cxx_config_cc_file = File('cxx_config/%s.cc' % name)
93310458Sandreas.hansson@arm.com        env.Command(cxx_config_hh_file, Value(name),
93410458Sandreas.hansson@arm.com                    MakeAction(createSimObjectCxxConfig(True),
93510458Sandreas.hansson@arm.com                    Transform("CXXCPRHH")))
93610458Sandreas.hansson@arm.com        env.Command(cxx_config_cc_file, Value(name),
93710458Sandreas.hansson@arm.com                    MakeAction(createSimObjectCxxConfig(False),
93810458Sandreas.hansson@arm.com                    Transform("CXXCPRCC")))
93910458Sandreas.hansson@arm.com        env.Depends(cxx_config_hh_file, depends + extra_deps +
94010458Sandreas.hansson@arm.com                    [File('params/%s.hh' % name), File('sim/cxx_config.hh')])
94110458Sandreas.hansson@arm.com        env.Depends(cxx_config_cc_file, depends + extra_deps +
94210458Sandreas.hansson@arm.com                    [cxx_config_hh_file])
94310458Sandreas.hansson@arm.com        Source(cxx_config_cc_file)
94410458Sandreas.hansson@arm.com
94510458Sandreas.hansson@arm.com    cxx_config_init_cc_file = File('cxx_config/init.cc')
94610458Sandreas.hansson@arm.com
94710458Sandreas.hansson@arm.com    def createCxxConfigInitCC(target, source, env):
94810458Sandreas.hansson@arm.com        assert len(target) == 1 and len(source) == 1
94910458Sandreas.hansson@arm.com
95010458Sandreas.hansson@arm.com        code = code_formatter()
95110458Sandreas.hansson@arm.com
95210458Sandreas.hansson@arm.com        for name,simobj in sorted(sim_objects.iteritems()):
95310458Sandreas.hansson@arm.com            if not hasattr(simobj, 'abstract') or not simobj.abstract:
95410458Sandreas.hansson@arm.com                code('#include "cxx_config/${name}.hh"')
95510458Sandreas.hansson@arm.com        code()
95610458Sandreas.hansson@arm.com        code('void cxxConfigInit()')
95710458Sandreas.hansson@arm.com        code('{')
95810458Sandreas.hansson@arm.com        code.indent()
95910458Sandreas.hansson@arm.com        for name,simobj in sorted(sim_objects.iteritems()):
96010458Sandreas.hansson@arm.com            not_abstract = not hasattr(simobj, 'abstract') or \
96110458Sandreas.hansson@arm.com                not simobj.abstract
96210458Sandreas.hansson@arm.com            if not_abstract and 'type' in simobj.__dict__:
96310458Sandreas.hansson@arm.com                code('cxx_config_directory["${name}"] = '
96410458Sandreas.hansson@arm.com                     '${name}CxxConfigParams::makeDirectoryEntry();')
96510458Sandreas.hansson@arm.com        code.dedent()
96610458Sandreas.hansson@arm.com        code('}')
96710458Sandreas.hansson@arm.com        code.write(target[0].abspath)
96810458Sandreas.hansson@arm.com
96910458Sandreas.hansson@arm.com    py_source = PySource.modules[simobj.__module__]
97010458Sandreas.hansson@arm.com    extra_deps = [ py_source.tnode ]
97110458Sandreas.hansson@arm.com    env.Command(cxx_config_init_cc_file, Value(name),
97210458Sandreas.hansson@arm.com        MakeAction(createCxxConfigInitCC, Transform("CXXCINIT")))
97310458Sandreas.hansson@arm.com    cxx_param_hh_files = ["cxx_config/%s.hh" % simobj
97410584Sandreas.hansson@arm.com        for name,simobj in sorted(sim_objects.iteritems())
97510458Sandreas.hansson@arm.com        if not hasattr(simobj, 'abstract') or not simobj.abstract]
97610458Sandreas.hansson@arm.com    Depends(cxx_config_init_cc_file, cxx_param_hh_files +
97710458Sandreas.hansson@arm.com            [File('sim/cxx_config.hh')])
97810458Sandreas.hansson@arm.com    Source(cxx_config_init_cc_file)
97910458Sandreas.hansson@arm.com
9804762Snate@binkert.org# Generate all enum header files
9816143Snate@binkert.orgfor name,enum in sorted(all_enums.iteritems()):
9826143Snate@binkert.org    py_source = PySource.modules[enum.__module__]
9836143Snate@binkert.org    extra_deps = [ py_source.tnode ]
9844762Snate@binkert.org
9854762Snate@binkert.org    cc_file = File('enums/%s.cc' % name)
98611996Sgabeblack@google.com    env.Command(cc_file, [Value(name), Value(env['USE_PYTHON'])],
9877816Ssteve.reinhardt@amd.com                MakeAction(createEnumStrings, Transform("ENUM STR")))
9884762Snate@binkert.org    env.Depends(cc_file, depends + extra_deps)
9894762Snate@binkert.org    Source(cc_file)
9904762Snate@binkert.org
9914762Snate@binkert.org    hh_file = File('enums/%s.hh' % name)
9927756SAli.Saidi@ARM.com    env.Command(hh_file, Value(name),
9938596Ssteve.reinhardt@amd.com                MakeAction(createEnumDecls, Transform("ENUMDECL")))
9944762Snate@binkert.org    env.Depends(hh_file, depends + extra_deps)
9954762Snate@binkert.org
99611988Sandreas.sandberg@arm.com# Generate SimObject Python bindings wrapper files
99711988Sandreas.sandberg@arm.comif env['USE_PYTHON']:
99811988Sandreas.sandberg@arm.com    for name,simobj in sorted(sim_objects.iteritems()):
99911988Sandreas.sandberg@arm.com        py_source = PySource.modules[simobj.__module__]
100011988Sandreas.sandberg@arm.com        extra_deps = [ py_source.tnode ]
100111988Sandreas.sandberg@arm.com        cc_file = File('python/_m5/param_%s.cc' % name)
100211988Sandreas.sandberg@arm.com        env.Command(cc_file, Value(name),
100311988Sandreas.sandberg@arm.com                    MakeAction(createSimObjectPyBindWrapper,
100411988Sandreas.sandberg@arm.com                               Transform("SO PyBind")))
100511988Sandreas.sandberg@arm.com        env.Depends(cc_file, depends + extra_deps)
100611988Sandreas.sandberg@arm.com        Source(cc_file)
10074382Sbinkertn@umich.edu
10089396Sandreas.hansson@arm.com# Build all protocol buffers if we have got protoc and protobuf available
10099396Sandreas.hansson@arm.comif env['HAVE_PROTOBUF']:
10109396Sandreas.hansson@arm.com    for proto in ProtoBuf.all:
10119396Sandreas.hansson@arm.com        # Use both the source and header as the target, and the .proto
10129396Sandreas.hansson@arm.com        # file as the source. When executing the protoc compiler, also
10139396Sandreas.hansson@arm.com        # specify the proto_path to avoid having the generated files
10149396Sandreas.hansson@arm.com        # include the path.
10159396Sandreas.hansson@arm.com        env.Command([proto.cc_file, proto.hh_file], proto.tnode,
10169396Sandreas.hansson@arm.com                    MakeAction('$PROTOC --cpp_out ${TARGET.dir} '
10179396Sandreas.hansson@arm.com                               '--proto_path ${SOURCE.dir} $SOURCE',
10189396Sandreas.hansson@arm.com                               Transform("PROTOC")))
10199396Sandreas.hansson@arm.com
10209396Sandreas.hansson@arm.com        # Add the C++ source file
102112302Sgabeblack@google.com        Source(proto.cc_file, tags=proto.tags)
10229396Sandreas.hansson@arm.comelif ProtoBuf.all:
102312563Sgabeblack@google.com    print('Got protobuf to build, but lacks support!')
10249396Sandreas.hansson@arm.com    Exit(1)
10259396Sandreas.hansson@arm.com
10268232Snate@binkert.org#
10278232Snate@binkert.org# Handle debug flags
10288232Snate@binkert.org#
10298232Snate@binkert.orgdef makeDebugFlagCC(target, source, env):
10308232Snate@binkert.org    assert(len(target) == 1 and len(source) == 1)
10316229Snate@binkert.org
103210455SCurtis.Dunham@arm.com    code = code_formatter()
10336229Snate@binkert.org
103410455SCurtis.Dunham@arm.com    # delay definition of CompoundFlags until after all the definition
103510455SCurtis.Dunham@arm.com    # of all constituent SimpleFlags
103610455SCurtis.Dunham@arm.com    comp_code = code_formatter()
10375517Snate@binkert.org
10385517Snate@binkert.org    # file header
10397673Snate@binkert.org    code('''
10405517Snate@binkert.org/*
104110455SCurtis.Dunham@arm.com * DO NOT EDIT THIS FILE! Automatically generated by SCons.
10425517Snate@binkert.org */
10435517Snate@binkert.org
10448232Snate@binkert.org#include "base/debug.hh"
104510455SCurtis.Dunham@arm.com
104610455SCurtis.Dunham@arm.comnamespace Debug {
104710455SCurtis.Dunham@arm.com
10487673Snate@binkert.org''')
10497673Snate@binkert.org
105010455SCurtis.Dunham@arm.com    for name, flag in sorted(source[0].read().iteritems()):
105110455SCurtis.Dunham@arm.com        n, compound, desc = flag
105210455SCurtis.Dunham@arm.com        assert n == name
10535517Snate@binkert.org
105410455SCurtis.Dunham@arm.com        if not compound:
105510455SCurtis.Dunham@arm.com            code('SimpleFlag $name("$name", "$desc");')
105610455SCurtis.Dunham@arm.com        else:
105710455SCurtis.Dunham@arm.com            comp_code('CompoundFlag $name("$name", "$desc",')
105810455SCurtis.Dunham@arm.com            comp_code.indent()
105910455SCurtis.Dunham@arm.com            last = len(compound) - 1
106010455SCurtis.Dunham@arm.com            for i,flag in enumerate(compound):
106110455SCurtis.Dunham@arm.com                if i != last:
106210685Sandreas.hansson@arm.com                    comp_code('&$flag,')
106310455SCurtis.Dunham@arm.com                else:
106410685Sandreas.hansson@arm.com                    comp_code('&$flag);')
106510455SCurtis.Dunham@arm.com            comp_code.dedent()
10665517Snate@binkert.org
106710455SCurtis.Dunham@arm.com    code.append(comp_code)
10688232Snate@binkert.org    code()
10698232Snate@binkert.org    code('} // namespace Debug')
10705517Snate@binkert.org
10717673Snate@binkert.org    code.write(str(target[0]))
10725517Snate@binkert.org
10738232Snate@binkert.orgdef makeDebugFlagHH(target, source, env):
10748232Snate@binkert.org    assert(len(target) == 1 and len(source) == 1)
10755517Snate@binkert.org
10768232Snate@binkert.org    val = eval(source[0].get_contents())
10778232Snate@binkert.org    name, compound, desc = val
10788232Snate@binkert.org
10797673Snate@binkert.org    code = code_formatter()
10805517Snate@binkert.org
10815517Snate@binkert.org    # file header boilerplate
10827673Snate@binkert.org    code('''\
10835517Snate@binkert.org/*
108410455SCurtis.Dunham@arm.com * DO NOT EDIT THIS FILE! Automatically generated by SCons.
10855517Snate@binkert.org */
10865517Snate@binkert.org
10878232Snate@binkert.org#ifndef __DEBUG_${name}_HH__
10888232Snate@binkert.org#define __DEBUG_${name}_HH__
10895517Snate@binkert.org
10908232Snate@binkert.orgnamespace Debug {
10918232Snate@binkert.org''')
10925517Snate@binkert.org
10938232Snate@binkert.org    if compound:
10948232Snate@binkert.org        code('class CompoundFlag;')
10958232Snate@binkert.org    code('class SimpleFlag;')
10965517Snate@binkert.org
10978232Snate@binkert.org    if compound:
10988232Snate@binkert.org        code('extern CompoundFlag $name;')
10998232Snate@binkert.org        for flag in compound:
11008232Snate@binkert.org            code('extern SimpleFlag $flag;')
11018232Snate@binkert.org    else:
11028232Snate@binkert.org        code('extern SimpleFlag $name;')
11035517Snate@binkert.org
11048232Snate@binkert.org    code('''
11058232Snate@binkert.org}
11065517Snate@binkert.org
11078232Snate@binkert.org#endif // __DEBUG_${name}_HH__
11087673Snate@binkert.org''')
11095517Snate@binkert.org
11107673Snate@binkert.org    code.write(str(target[0]))
11115517Snate@binkert.org
11128232Snate@binkert.orgfor name,flag in sorted(debug_flags.iteritems()):
11138232Snate@binkert.org    n, compound, desc = flag
11148232Snate@binkert.org    assert n == name
11155192Ssaidi@eecs.umich.edu
111610454SCurtis.Dunham@arm.com    hh_file = 'debug/%s.hh' % name
111710454SCurtis.Dunham@arm.com    env.Command(hh_file, Value(flag),
11188232Snate@binkert.org                MakeAction(makeDebugFlagHH, Transform("TRACING", 0)))
111910455SCurtis.Dunham@arm.com
112010455SCurtis.Dunham@arm.comenv.Command('debug/flags.cc', Value(debug_flags),
112110455SCurtis.Dunham@arm.com            MakeAction(makeDebugFlagCC, Transform("TRACING", 0)))
112210455SCurtis.Dunham@arm.comSource('debug/flags.cc')
11235192Ssaidi@eecs.umich.edu
112411077SCurtis.Dunham@arm.com# version tags
112511330SCurtis.Dunham@arm.comtags = \
112611077SCurtis.Dunham@arm.comenv.Command('sim/tags.cc', None,
112711077SCurtis.Dunham@arm.com            MakeAction('util/cpt_upgrader.py --get-cc-file > $TARGET',
112811077SCurtis.Dunham@arm.com                       Transform("VER TAGS")))
112911330SCurtis.Dunham@arm.comenv.AlwaysBuild(tags)
113011077SCurtis.Dunham@arm.com
113113730Sandreas.sandberg@arm.com# Build a small helper that marshals the Python code using the same
113213730Sandreas.sandberg@arm.com# version of Python as gem5. This is in an unorthodox location to
113313730Sandreas.sandberg@arm.com# avoid building it for every variant.
113413993Schunchenhsu@google.compy_marshal = env.Program('marshal', 'python/marshal.cc')[0]
113513730Sandreas.sandberg@arm.com
11367674Snate@binkert.org# Embed python files.  All .py files that have been indicated by a
11375522Snate@binkert.org# PySource() call in a SConscript need to be embedded into the M5
11385522Snate@binkert.org# library.  To do that, we compile the file to byte code, marshal the
11397674Snate@binkert.org# byte code, compress it, and then generate a c++ file that
11407674Snate@binkert.org# inserts the result into an array.
11417674Snate@binkert.orgdef embedPyFile(target, source, env):
11427674Snate@binkert.org    def c_str(string):
11437674Snate@binkert.org        if string is None:
11447674Snate@binkert.org            return "0"
11457674Snate@binkert.org        return '"%s"' % string
11467674Snate@binkert.org
114713730Sandreas.sandberg@arm.com    '''Action function to compile a .py into a code object, marshal it,
114813730Sandreas.sandberg@arm.com    compress it, and stick it into an asm file so the code appears as
114913730Sandreas.sandberg@arm.com    just bytes with a label in the data section. The action takes two
115013730Sandreas.sandberg@arm.com    sources:
11515517Snate@binkert.org
115213730Sandreas.sandberg@arm.com    source[0]: Binary used to marshal Python sources
115313730Sandreas.sandberg@arm.com    source[1]: Python script to marshal
115413730Sandreas.sandberg@arm.com    '''
11555517Snate@binkert.org
115613730Sandreas.sandberg@arm.com    import subprocess
115713730Sandreas.sandberg@arm.com
115813730Sandreas.sandberg@arm.com    marshalled = subprocess.check_output([source[0].abspath, str(source[1])])
115913730Sandreas.sandberg@arm.com
11605522Snate@binkert.org    compressed = zlib.compress(marshalled)
11615522Snate@binkert.org    data = compressed
116213730Sandreas.sandberg@arm.com    pysource = PySource.tnodes[source[1]]
11637674Snate@binkert.org    sym = pysource.symname
11645517Snate@binkert.org
11657673Snate@binkert.org    code = code_formatter()
11667673Snate@binkert.org    code('''\
11677674Snate@binkert.org#include "sim/init.hh"
11687673Snate@binkert.org
11697674Snate@binkert.orgnamespace {
11707674Snate@binkert.org
11717674Snate@binkert.org''')
117213576Sciro.santilli@arm.com    blobToCpp(data, 'data_' + sym, code)
117313576Sciro.santilli@arm.com    code('''\
117411308Santhony.gutierrez@amd.com
11757673Snate@binkert.org
11767674Snate@binkert.orgEmbeddedPython embedded_${sym}(
11777674Snate@binkert.org    ${{c_str(pysource.arcname)}},
11787674Snate@binkert.org    ${{c_str(pysource.abspath)}},
11797674Snate@binkert.org    ${{c_str(pysource.modpath)}},
11807674Snate@binkert.org    data_${sym},
11817674Snate@binkert.org    ${{len(data)}},
11827674Snate@binkert.org    ${{len(marshalled)}});
11837674Snate@binkert.org
11847811Ssteve.reinhardt@amd.com} // anonymous namespace
11857674Snate@binkert.org''')
11867673Snate@binkert.org    code.write(str(target[0]))
11875522Snate@binkert.org
11886143Snate@binkert.orgfor source in PySource.all:
118913730Sandreas.sandberg@arm.com    env.Command(source.cpp, [ py_marshal, source.tnode ],
11907816Ssteve.reinhardt@amd.com                MakeAction(embedPyFile, Transform("EMBED PY")))
119112302Sgabeblack@google.com    Source(source.cpp, tags=source.tags, add_tags='python')
11924382Sbinkertn@umich.edu
11934382Sbinkertn@umich.edu########################################################################
11944382Sbinkertn@umich.edu#
11954382Sbinkertn@umich.edu# Define binaries.  Each different build type (debug, opt, etc.) gets
11964382Sbinkertn@umich.edu# a slightly different build environment.
11974382Sbinkertn@umich.edu#
11984382Sbinkertn@umich.edu
11994382Sbinkertn@umich.edu# List of constructed environments to pass back to SConstruct
120012302Sgabeblack@google.comdate_source = Source('base/date.cc', tags=[])
12014382Sbinkertn@umich.edu
120212797Sgabeblack@google.comgem5_binary = Gem5('gem5')
120312797Sgabeblack@google.com
12042655Sstever@eecs.umich.edu# Function to create a new build environment as clone of current
12052655Sstever@eecs.umich.edu# environment 'env' with modified object suffix and optional stripped
12062655Sstever@eecs.umich.edu# binary.  Additional keyword arguments are appended to corresponding
12072655Sstever@eecs.umich.edu# build environment vars.
120812063Sgabeblack@google.comdef makeEnv(env, label, objsfx, strip=False, disable_partial=False, **kwargs):
12095601Snate@binkert.org    # SCons doesn't know to append a library suffix when there is a '.' in the
12105601Snate@binkert.org    # name.  Use '_' instead.
121112222Sgabeblack@google.com    libname = 'gem5_' + label
121212222Sgabeblack@google.com    secondary_exename = 'm5.' + label
12135522Snate@binkert.org
12145863Snate@binkert.org    new_env = env.Clone(OBJSUFFIX=objsfx, SHOBJSUFFIX=objsfx + 's')
12155601Snate@binkert.org    new_env.Label = label
12165601Snate@binkert.org    new_env.Append(**kwargs)
12175601Snate@binkert.org
121812302Sgabeblack@google.com    lib_sources = Source.all.with_tag('gem5 lib')
121910453SAndrew.Bardsley@arm.com
122011988Sandreas.sandberg@arm.com    # Without Python, leave out all Python content from the library
122111988Sandreas.sandberg@arm.com    # builds.  The option doesn't affect gem5 built as a program
122210453SAndrew.Bardsley@arm.com    if GetOption('without_python'):
122312302Sgabeblack@google.com        lib_sources = lib_sources.without_tag('python')
122410453SAndrew.Bardsley@arm.com
122511983Sgabeblack@google.com    static_objs = []
122611983Sgabeblack@google.com    shared_objs = []
122712302Sgabeblack@google.com
122812302Sgabeblack@google.com    for s in lib_sources.with_tag(Source.ungrouped_tag):
122912362Sgabeblack@google.com        static_objs.append(s.static(new_env))
123012362Sgabeblack@google.com        shared_objs.append(s.shared(new_env))
123111983Sgabeblack@google.com
123212302Sgabeblack@google.com    for group in Source.source_groups:
123312302Sgabeblack@google.com        srcs = lib_sources.with_tag(Source.link_group_tag(group))
123411983Sgabeblack@google.com        if not srcs:
123511983Sgabeblack@google.com            continue
123611983Sgabeblack@google.com
123712362Sgabeblack@google.com        group_static = [ s.static(new_env) for s in srcs ]
123812362Sgabeblack@google.com        group_shared = [ s.shared(new_env) for s in srcs ]
123912310Sgabeblack@google.com
124012063Sgabeblack@google.com        # If partial linking is disabled, add these sources to the build
124112063Sgabeblack@google.com        # directly, and short circuit this loop.
124212063Sgabeblack@google.com        if disable_partial:
124312310Sgabeblack@google.com            static_objs.extend(group_static)
124412310Sgabeblack@google.com            shared_objs.extend(group_shared)
124512063Sgabeblack@google.com            continue
124612063Sgabeblack@google.com
124711983Sgabeblack@google.com        # Set up the static partially linked objects.
124811983Sgabeblack@google.com        file_name = new_env.subst("${OBJPREFIX}lib${OBJSUFFIX}.partial")
124911983Sgabeblack@google.com        target = File(joinpath(group, file_name))
125012310Sgabeblack@google.com        partial = env.PartialStatic(target=target, source=group_static)
125112310Sgabeblack@google.com        static_objs.extend(partial)
125211983Sgabeblack@google.com
125311983Sgabeblack@google.com        # Set up the shared partially linked objects.
125411983Sgabeblack@google.com        file_name = new_env.subst("${SHOBJPREFIX}lib${SHOBJSUFFIX}.partial")
125511983Sgabeblack@google.com        target = File(joinpath(group, file_name))
125612310Sgabeblack@google.com        partial = env.PartialShared(target=target, source=group_shared)
125712310Sgabeblack@google.com        shared_objs.extend(partial)
12586143Snate@binkert.org
125912362Sgabeblack@google.com    static_date = date_source.static(new_env)
126012306Sgabeblack@google.com    new_env.Depends(static_date, static_objs)
126112310Sgabeblack@google.com    static_objs.extend(static_date)
126210453SAndrew.Bardsley@arm.com
126312362Sgabeblack@google.com    shared_date = date_source.shared(new_env)
126412306Sgabeblack@google.com    new_env.Depends(shared_date, shared_objs)
126512310Sgabeblack@google.com    shared_objs.extend(shared_date)
12665554Snate@binkert.org
126712797Sgabeblack@google.com    main_objs = [ s.static(new_env) for s in Source.all.with_tag('main') ]
126812797Sgabeblack@google.com
12695522Snate@binkert.org    # First make a library of everything but main() so other programs can
12705522Snate@binkert.org    # link against m5.
12715797Snate@binkert.org    static_lib = new_env.StaticLibrary(libname, static_objs)
12725797Snate@binkert.org    shared_lib = new_env.SharedLibrary(libname, shared_objs)
12735522Snate@binkert.org
127412797Sgabeblack@google.com    # Keep track of the object files generated so far so Executables can
127512797Sgabeblack@google.com    # include them.
127612797Sgabeblack@google.com    new_env['STATIC_OBJS'] = static_objs
127712797Sgabeblack@google.com    new_env['SHARED_OBJS'] = shared_objs
127812797Sgabeblack@google.com    new_env['MAIN_OBJS'] = main_objs
12798233Snate@binkert.org
128012797Sgabeblack@google.com    new_env['STATIC_LIB'] = static_lib
128112797Sgabeblack@google.com    new_env['SHARED_LIB'] = shared_lib
12828235Snate@binkert.org
128312797Sgabeblack@google.com    # Record some settings for building Executables.
128412797Sgabeblack@google.com    new_env['EXE_SUFFIX'] = label
128512797Sgabeblack@google.com    new_env['STRIP_EXES'] = strip
128612370Sgabeblack@google.com
128712797Sgabeblack@google.com    for cls in ExecutableMeta.all:
128812797Sgabeblack@google.com        cls.declare_all(new_env)
128912313Sgabeblack@google.com
129012797Sgabeblack@google.com    new_env.M5Binary = File(gem5_binary.path(new_env))
12916143Snate@binkert.org
129212797Sgabeblack@google.com    new_env.Command(secondary_exename, new_env.M5Binary,
12938334Snate@binkert.org            MakeAction('ln $SOURCE $TARGET', Transform("HARDLINK")))
12948334Snate@binkert.org
129511993Sgabeblack@google.com    # Set up regression tests.
129611993Sgabeblack@google.com    SConscript(os.path.join(env.root.abspath, 'tests', 'SConscript'),
129712223Sgabeblack@google.com               variant_dir=Dir('tests').Dir(new_env.Label),
129811993Sgabeblack@google.com               exports={ 'env' : new_env }, duplicate=False)
12992655Sstever@eecs.umich.edu
13009225Sandreas.hansson@arm.com# Start out with the compiler flags common to all compilers,
13019225Sandreas.hansson@arm.com# i.e. they all use -g for opt and -g -pg for prof
13029226Sandreas.hansson@arm.comccflags = {'debug' : [], 'opt' : ['-g'], 'fast' : [], 'prof' : ['-g', '-pg'],
13039226Sandreas.hansson@arm.com           'perf' : ['-g']}
13049225Sandreas.hansson@arm.com
13059226Sandreas.hansson@arm.com# Start out with the linker flags common to all linkers, i.e. -pg for
13069226Sandreas.hansson@arm.com# prof, and -lprofiler for perf. The -lprofile flag is surrounded by
13079226Sandreas.hansson@arm.com# no-as-needed and as-needed as the binutils linker is too clever and
13089226Sandreas.hansson@arm.com# simply doesn't link to the library otherwise.
13099226Sandreas.hansson@arm.comldflags = {'debug' : [], 'opt' : [], 'fast' : [], 'prof' : ['-pg'],
13109226Sandreas.hansson@arm.com           'perf' : ['-Wl,--no-as-needed', '-lprofiler', '-Wl,--as-needed']}
13119225Sandreas.hansson@arm.com
13129227Sandreas.hansson@arm.com# For Link Time Optimization, the optimisation flags used to compile
13139227Sandreas.hansson@arm.com# individual files are decoupled from those used at link time
13149227Sandreas.hansson@arm.com# (i.e. you can compile with -O3 and perform LTO with -O0), so we need
13159227Sandreas.hansson@arm.com# to also update the linker flags based on the target.
13168946Sandreas.hansson@arm.comif env['GCC']:
13173918Ssaidi@eecs.umich.edu    if sys.platform == 'sunos5':
13189225Sandreas.hansson@arm.com        ccflags['debug'] += ['-gstabs+']
13193918Ssaidi@eecs.umich.edu    else:
13209225Sandreas.hansson@arm.com        ccflags['debug'] += ['-ggdb3']
13219225Sandreas.hansson@arm.com    ldflags['debug'] += ['-O0']
13229227Sandreas.hansson@arm.com    # opt, fast, prof and perf all share the same cc flags, also add
13239227Sandreas.hansson@arm.com    # the optimization to the ldflags as LTO defers the optimization
13249227Sandreas.hansson@arm.com    # to link time
13259226Sandreas.hansson@arm.com    for target in ['opt', 'fast', 'prof', 'perf']:
13269225Sandreas.hansson@arm.com        ccflags[target] += ['-O3']
13279227Sandreas.hansson@arm.com        ldflags[target] += ['-O3']
13289227Sandreas.hansson@arm.com
13299227Sandreas.hansson@arm.com    ccflags['fast'] += env['LTO_CCFLAGS']
13309227Sandreas.hansson@arm.com    ldflags['fast'] += env['LTO_LDFLAGS']
13318946Sandreas.hansson@arm.comelif env['CLANG']:
13329225Sandreas.hansson@arm.com    ccflags['debug'] += ['-g', '-O0']
13339226Sandreas.hansson@arm.com    # opt, fast, prof and perf all share the same cc flags
13349226Sandreas.hansson@arm.com    for target in ['opt', 'fast', 'prof', 'perf']:
13359226Sandreas.hansson@arm.com        ccflags[target] += ['-O3']
13363515Ssaidi@eecs.umich.eduelse:
133712563Sgabeblack@google.com    print('Unknown compiler, please fix compiler options')
13384762Snate@binkert.org    Exit(1)
13393515Ssaidi@eecs.umich.edu
13408881Smarc.orr@gmail.com
13418881Smarc.orr@gmail.com# To speed things up, we only instantiate the build environments we
13428881Smarc.orr@gmail.com# need.  We try to identify the needed environment for each target; if
13438881Smarc.orr@gmail.com# we can't, we fall back on instantiating all the environments just to
13448881Smarc.orr@gmail.com# be safe.
13459226Sandreas.hansson@arm.comtarget_types = ['debug', 'opt', 'fast', 'prof', 'perf']
13469226Sandreas.hansson@arm.comobj2target = {'do': 'debug', 'o': 'opt', 'fo': 'fast', 'po': 'prof',
13479226Sandreas.hansson@arm.com              'gpo' : 'perf'}
13488881Smarc.orr@gmail.com
13498881Smarc.orr@gmail.comdef identifyTarget(t):
13508881Smarc.orr@gmail.com    ext = t.split('.')[-1]
13518881Smarc.orr@gmail.com    if ext in target_types:
13528881Smarc.orr@gmail.com        return ext
135313675Sandreas.sandberg@arm.com    if ext in obj2target:
13548881Smarc.orr@gmail.com        return obj2target[ext]
13558881Smarc.orr@gmail.com    match = re.search(r'/tests/([^/]+)/', t)
13568881Smarc.orr@gmail.com    if match and match.group(1) in target_types:
13578881Smarc.orr@gmail.com        return match.group(1)
13588881Smarc.orr@gmail.com    return 'all'
13598881Smarc.orr@gmail.com
13608881Smarc.orr@gmail.comneeded_envs = [identifyTarget(target) for target in BUILD_TARGETS]
13618881Smarc.orr@gmail.comif 'all' in needed_envs:
13628881Smarc.orr@gmail.com    needed_envs += target_types
13638881Smarc.orr@gmail.com
136413508Snikos.nikoleris@arm.comdisable_partial = False
136513508Snikos.nikoleris@arm.comif env['PLATFORM'] == 'darwin':
136613508Snikos.nikoleris@arm.com    # Up until Apple LLVM version 10.0.0 (clang-1000.11.45.5), partial
136713508Snikos.nikoleris@arm.com    # linked objects do not expose symbols that are marked with the
136813508Snikos.nikoleris@arm.com    # hidden visibility and consequently building gem5 on Mac OS
136913508Snikos.nikoleris@arm.com    # fails. As a workaround, we disable partial linking, however, we
137013508Snikos.nikoleris@arm.com    # may want to revisit in the future.
137113508Snikos.nikoleris@arm.com    disable_partial = True
137213508Snikos.nikoleris@arm.com
137312222Sgabeblack@google.com# Debug binary
137412222Sgabeblack@google.comif 'debug' in needed_envs:
137512222Sgabeblack@google.com    makeEnv(env, 'debug', '.do',
137612222Sgabeblack@google.com            CCFLAGS = Split(ccflags['debug']),
137712222Sgabeblack@google.com            CPPDEFINES = ['DEBUG', 'TRACING_ON=1'],
137813508Snikos.nikoleris@arm.com            LINKFLAGS = Split(ldflags['debug']),
137913508Snikos.nikoleris@arm.com            disable_partial=disable_partial)
1380955SN/A
138112222Sgabeblack@google.com# Optimized binary
138212222Sgabeblack@google.comif 'opt' in needed_envs:
138312222Sgabeblack@google.com    makeEnv(env, 'opt', '.o',
138412222Sgabeblack@google.com            CCFLAGS = Split(ccflags['opt']),
138512222Sgabeblack@google.com            CPPDEFINES = ['TRACING_ON=1'],
138613508Snikos.nikoleris@arm.com            LINKFLAGS = Split(ldflags['opt']),
138713508Snikos.nikoleris@arm.com            disable_partial=disable_partial)
1388955SN/A
138912222Sgabeblack@google.com# "Fast" binary
139012222Sgabeblack@google.comif 'fast' in needed_envs:
139113777Shoanguyen@ucdavis.edu    disable_partial = disable_partial or \
139213777Shoanguyen@ucdavis.edu            (env.get('BROKEN_INCREMENTAL_LTO', False) and \
139313777Shoanguyen@ucdavis.edu            GetOption('force_lto'))
139412222Sgabeblack@google.com    makeEnv(env, 'fast', '.fo', strip = True,
139512222Sgabeblack@google.com            CCFLAGS = Split(ccflags['fast']),
139612222Sgabeblack@google.com            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
139712222Sgabeblack@google.com            LINKFLAGS = Split(ldflags['fast']),
139812222Sgabeblack@google.com            disable_partial=disable_partial)
13991869SN/A
140012222Sgabeblack@google.com# Profiled binary using gprof
140112222Sgabeblack@google.comif 'prof' in needed_envs:
140212222Sgabeblack@google.com    makeEnv(env, 'prof', '.po',
140312222Sgabeblack@google.com            CCFLAGS = Split(ccflags['prof']),
140412222Sgabeblack@google.com            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
140513508Snikos.nikoleris@arm.com            LINKFLAGS = Split(ldflags['prof']),
140613508Snikos.nikoleris@arm.com            disable_partial=disable_partial)
14079226Sandreas.hansson@arm.com
140812222Sgabeblack@google.com# Profiled binary using google-pprof
140912222Sgabeblack@google.comif 'perf' in needed_envs:
141012222Sgabeblack@google.com    makeEnv(env, 'perf', '.gpo',
141112222Sgabeblack@google.com            CCFLAGS = Split(ccflags['perf']),
141212222Sgabeblack@google.com            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
141313508Snikos.nikoleris@arm.com            LINKFLAGS = Split(ldflags['perf']),
141413508Snikos.nikoleris@arm.com            disable_partial=disable_partial)
1415