SConscript revision 13667
1955SN/A# -*- mode:python -*-
2955SN/A
31762SN/A# Copyright (c) 2018 ARM Limited
4955SN/A#
5955SN/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#
282665Ssaidi@eecs.umich.edu# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
294762Snate@binkert.org# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
315522Snate@binkert.org# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
326143Snate@binkert.org# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
334762Snate@binkert.org# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
345522Snate@binkert.org# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35955SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
365522Snate@binkert.org# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37955SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
385522Snate@binkert.org# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
394202Sbinkertn@umich.edu#
405742Snate@binkert.org# Authors: Nathan Binkert
41955SN/A
424381Sbinkertn@umich.edufrom __future__ import print_function
434381Sbinkertn@umich.edu
448334Snate@binkert.orgimport array
45955SN/Aimport bisect
46955SN/Aimport functools
474202Sbinkertn@umich.eduimport imp
48955SN/Aimport marshal
494382Sbinkertn@umich.eduimport os
504382Sbinkertn@umich.eduimport re
514382Sbinkertn@umich.eduimport subprocess
526654Snate@binkert.orgimport sys
535517Snate@binkert.orgimport zlib
548614Sgblack@eecs.umich.edu
557674Snate@binkert.orgfrom os.path import basename, dirname, exists, isdir, isfile, join as joinpath
566143Snate@binkert.org
576143Snate@binkert.orgimport SCons
586143Snate@binkert.org
598233Snate@binkert.orgfrom gem5_scons import Transform
608233Snate@binkert.org
618233Snate@binkert.org# This file defines how to build a particular configuration of gem5
628233Snate@binkert.org# based on variable settings in the 'env' build environment.
638233Snate@binkert.org
648334Snate@binkert.orgImport('*')
658334Snate@binkert.org
6610453SAndrew.Bardsley@arm.com# Children need to see the environment
6710453SAndrew.Bardsley@arm.comExport('env')
688233Snate@binkert.org
698233Snate@binkert.orgbuild_env = [(opt, env[opt]) for opt in export_vars]
708233Snate@binkert.org
718233Snate@binkert.orgfrom m5.util import code_formatter, compareVersions
728233Snate@binkert.org
738233Snate@binkert.org########################################################################
746143Snate@binkert.org# Code for adding source files of various types
758233Snate@binkert.org#
768233Snate@binkert.org# When specifying a source file of some type, a set of tags can be
778233Snate@binkert.org# specified for that file.
786143Snate@binkert.org
796143Snate@binkert.orgclass SourceFilter(object):
806143Snate@binkert.org    def __init__(self, predicate):
816143Snate@binkert.org        self.predicate = predicate
828233Snate@binkert.org
838233Snate@binkert.org    def __or__(self, other):
848233Snate@binkert.org        return SourceFilter(lambda tags: self.predicate(tags) or
856143Snate@binkert.org                                         other.predicate(tags))
868233Snate@binkert.org
878233Snate@binkert.org    def __and__(self, other):
888233Snate@binkert.org        return SourceFilter(lambda tags: self.predicate(tags) and
898233Snate@binkert.org                                         other.predicate(tags))
906143Snate@binkert.org
916143Snate@binkert.orgdef with_tags_that(predicate):
926143Snate@binkert.org    '''Return a list of sources with tags that satisfy a predicate.'''
934762Snate@binkert.org    return SourceFilter(predicate)
946143Snate@binkert.org
958233Snate@binkert.orgdef with_any_tags(*tags):
968233Snate@binkert.org    '''Return a list of sources with any of the supplied tags.'''
978233Snate@binkert.org    return SourceFilter(lambda stags: len(set(tags) & stags) > 0)
988233Snate@binkert.org
998233Snate@binkert.orgdef with_all_tags(*tags):
1006143Snate@binkert.org    '''Return a list of sources with all of the supplied tags.'''
1018233Snate@binkert.org    return SourceFilter(lambda stags: set(tags) <= stags)
1028233Snate@binkert.org
1038233Snate@binkert.orgdef with_tag(tag):
1048233Snate@binkert.org    '''Return a list of sources with the supplied tag.'''
1056143Snate@binkert.org    return SourceFilter(lambda stags: tag in stags)
1066143Snate@binkert.org
1076143Snate@binkert.orgdef without_tags(*tags):
1086143Snate@binkert.org    '''Return a list of sources without any of the supplied tags.'''
1096143Snate@binkert.org    return SourceFilter(lambda stags: len(set(tags) & stags) == 0)
1106143Snate@binkert.org
1116143Snate@binkert.orgdef without_tag(tag):
1126143Snate@binkert.org    '''Return a list of sources with the supplied tag.'''
1136143Snate@binkert.org    return SourceFilter(lambda stags: tag not in stags)
1147065Snate@binkert.org
1156143Snate@binkert.orgsource_filter_factories = {
1168233Snate@binkert.org    'with_tags_that': with_tags_that,
1178233Snate@binkert.org    'with_any_tags': with_any_tags,
1188233Snate@binkert.org    'with_all_tags': with_all_tags,
1198233Snate@binkert.org    'with_tag': with_tag,
1208233Snate@binkert.org    'without_tags': without_tags,
1218233Snate@binkert.org    'without_tag': without_tag,
1228233Snate@binkert.org}
1238233Snate@binkert.org
1248233Snate@binkert.orgExport(source_filter_factories)
1258233Snate@binkert.org
1268233Snate@binkert.orgclass SourceList(list):
1278233Snate@binkert.org    def apply_filter(self, f):
1288233Snate@binkert.org        def match(source):
1298233Snate@binkert.org            return f.predicate(source.tags)
1308233Snate@binkert.org        return SourceList(filter(match, self))
1318233Snate@binkert.org
1328233Snate@binkert.org    def __getattr__(self, name):
1338233Snate@binkert.org        func = source_filter_factories.get(name, None)
1348233Snate@binkert.org        if not func:
1358233Snate@binkert.org            raise AttributeError
1368233Snate@binkert.org
1378233Snate@binkert.org        @functools.wraps(func)
1388233Snate@binkert.org        def wrapper(*args, **kwargs):
1398233Snate@binkert.org            return self.apply_filter(func(*args, **kwargs))
1408233Snate@binkert.org        return wrapper
1418233Snate@binkert.org
1428233Snate@binkert.orgclass SourceMeta(type):
1438233Snate@binkert.org    '''Meta class for source files that keeps track of all files of a
1448233Snate@binkert.org    particular type.'''
1458233Snate@binkert.org    def __init__(cls, name, bases, dict):
1468233Snate@binkert.org        super(SourceMeta, cls).__init__(name, bases, dict)
1476143Snate@binkert.org        cls.all = SourceList()
1486143Snate@binkert.org
1496143Snate@binkert.orgclass SourceFile(object):
1506143Snate@binkert.org    '''Base object that encapsulates the notion of a source file.
1516143Snate@binkert.org    This includes, the source node, target node, various manipulations
1526143Snate@binkert.org    of those.  A source file also specifies a set of tags which
1539982Satgutier@umich.edu    describing arbitrary properties of the source file.'''
15410196SCurtis.Dunham@arm.com    __metaclass__ = SourceMeta
15510196SCurtis.Dunham@arm.com
15610196SCurtis.Dunham@arm.com    static_objs = {}
15710196SCurtis.Dunham@arm.com    shared_objs = {}
15810196SCurtis.Dunham@arm.com
15910196SCurtis.Dunham@arm.com    def __init__(self, source, tags=None, add_tags=None):
16010196SCurtis.Dunham@arm.com        if tags is None:
16110196SCurtis.Dunham@arm.com            tags='gem5 lib'
1626143Snate@binkert.org        if isinstance(tags, basestring):
1636143Snate@binkert.org            tags = set([tags])
1648945Ssteve.reinhardt@amd.com        if not isinstance(tags, set):
1658233Snate@binkert.org            tags = set(tags)
1668233Snate@binkert.org        self.tags = tags
1676143Snate@binkert.org
1688945Ssteve.reinhardt@amd.com        if add_tags:
1696143Snate@binkert.org            if isinstance(add_tags, basestring):
1706143Snate@binkert.org                add_tags = set([add_tags])
1716143Snate@binkert.org            if not isinstance(add_tags, set):
1726143Snate@binkert.org                add_tags = set(add_tags)
1735522Snate@binkert.org            self.tags |= add_tags
1746143Snate@binkert.org
1756143Snate@binkert.org        tnode = source
1766143Snate@binkert.org        if not isinstance(source, SCons.Node.FS.File):
1779982Satgutier@umich.edu            tnode = File(source)
1788233Snate@binkert.org
1798233Snate@binkert.org        self.tnode = tnode
1808233Snate@binkert.org        self.snode = tnode.srcnode()
1816143Snate@binkert.org
1826143Snate@binkert.org        for base in type(self).__mro__:
1836143Snate@binkert.org            if issubclass(base, SourceFile):
1846143Snate@binkert.org                base.all.append(self)
1855522Snate@binkert.org
1865522Snate@binkert.org    def static(self, env):
1875522Snate@binkert.org        key = (self.tnode, env['OBJSUFFIX'])
1885522Snate@binkert.org        if not key in self.static_objs:
1895604Snate@binkert.org            self.static_objs[key] = env.StaticObject(self.tnode)
1905604Snate@binkert.org        return self.static_objs[key]
1916143Snate@binkert.org
1926143Snate@binkert.org    def shared(self, env):
1934762Snate@binkert.org        key = (self.tnode, env['OBJSUFFIX'])
1944762Snate@binkert.org        if not key in self.shared_objs:
1956143Snate@binkert.org            self.shared_objs[key] = env.SharedObject(self.tnode)
1966727Ssteve.reinhardt@amd.com        return self.shared_objs[key]
1976727Ssteve.reinhardt@amd.com
1986727Ssteve.reinhardt@amd.com    @property
1994762Snate@binkert.org    def filename(self):
2006143Snate@binkert.org        return str(self.tnode)
2016143Snate@binkert.org
2026143Snate@binkert.org    @property
2036143Snate@binkert.org    def dirname(self):
2046727Ssteve.reinhardt@amd.com        return dirname(self.filename)
2056143Snate@binkert.org
2067674Snate@binkert.org    @property
2077674Snate@binkert.org    def basename(self):
2085604Snate@binkert.org        return basename(self.filename)
2096143Snate@binkert.org
2106143Snate@binkert.org    @property
2116143Snate@binkert.org    def extname(self):
2124762Snate@binkert.org        index = self.basename.rfind('.')
2136143Snate@binkert.org        if index <= 0:
2144762Snate@binkert.org            # dot files aren't extensions
2154762Snate@binkert.org            return self.basename, None
2164762Snate@binkert.org
2176143Snate@binkert.org        return self.basename[:index], self.basename[index+1:]
2186143Snate@binkert.org
2194762Snate@binkert.org    def __lt__(self, other): return self.filename < other.filename
2208233Snate@binkert.org    def __le__(self, other): return self.filename <= other.filename
2218233Snate@binkert.org    def __gt__(self, other): return self.filename > other.filename
2228233Snate@binkert.org    def __ge__(self, other): return self.filename >= other.filename
2238233Snate@binkert.org    def __eq__(self, other): return self.filename == other.filename
2246143Snate@binkert.org    def __ne__(self, other): return self.filename != other.filename
2256143Snate@binkert.org
2264762Snate@binkert.orgdef blobToCpp(data, symbol, cpp_code, hpp_code=None, namespace=None):
2276143Snate@binkert.org    '''
2284762Snate@binkert.org    Convert bytes data into C++ .cpp and .hh uint8_t byte array
2296143Snate@binkert.org    code containing that binary data.
2304762Snate@binkert.org
2316143Snate@binkert.org    :param data: binary data to be converted to C++
2328233Snate@binkert.org    :param symbol: name of the symbol
2338233Snate@binkert.org    :param cpp_code: append the generated cpp_code to this object
23410453SAndrew.Bardsley@arm.com    :param hpp_code: append the generated hpp_code to this object
2356143Snate@binkert.org                     If None, ignore it. Otherwise, also include it
2366143Snate@binkert.org                     in the .cpp file.
2376143Snate@binkert.org    :param namespace: namespace to put the symbol into. If None,
2386143Snate@binkert.org                      don't put the symbols into any namespace.
2396143Snate@binkert.org    '''
2406143Snate@binkert.org    symbol_len_declaration = 'const std::size_t {}_len'.format(symbol)
2416143Snate@binkert.org    symbol_declaration = 'const std::uint8_t {}[]'.format(symbol)
2426143Snate@binkert.org    if hpp_code is not None:
24310453SAndrew.Bardsley@arm.com        cpp_code('''\
24410453SAndrew.Bardsley@arm.com#include "blobs/{}.hh"
245955SN/A'''.format(symbol))
2469396Sandreas.hansson@arm.com        hpp_code('''\
2479396Sandreas.hansson@arm.com#include <cstddef>
2489396Sandreas.hansson@arm.com#include <cstdint>
2499396Sandreas.hansson@arm.com''')
2509396Sandreas.hansson@arm.com        if namespace is not None:
2519396Sandreas.hansson@arm.com            hpp_code('namespace {} {{'.format(namespace))
2529396Sandreas.hansson@arm.com        hpp_code('extern ' + symbol_len_declaration + ';')
2539396Sandreas.hansson@arm.com        hpp_code('extern ' + symbol_declaration + ';')
2549396Sandreas.hansson@arm.com        if namespace is not None:
2559396Sandreas.hansson@arm.com            hpp_code('}')
2569396Sandreas.hansson@arm.com    if namespace is not None:
2579396Sandreas.hansson@arm.com        cpp_code('namespace {} {{'.format(namespace))
2589396Sandreas.hansson@arm.com    if hpp_code is not None:
2599930Sandreas.hansson@arm.com        cpp_code(symbol_len_declaration + ' = {};'.format(len(data)))
2609930Sandreas.hansson@arm.com    cpp_code(symbol_declaration + ' = {')
2619396Sandreas.hansson@arm.com    cpp_code.indent()
2628235Snate@binkert.org    step = 16
2638235Snate@binkert.org    for i in xrange(0, len(data), step):
2646143Snate@binkert.org        x = array.array('B', data[i:i+step])
2658235Snate@binkert.org        cpp_code(''.join('%d,' % d for d in x))
2669003SAli.Saidi@ARM.com    cpp_code.dedent()
2678235Snate@binkert.org    cpp_code('};')
2688235Snate@binkert.org    if namespace is not None:
2698235Snate@binkert.org        cpp_code('}')
2708235Snate@binkert.org
2718235Snate@binkert.orgdef Blob(blob_path, symbol):
2728235Snate@binkert.org    '''
2738235Snate@binkert.org    Embed an arbitrary blob into the gem5 executable,
2748235Snate@binkert.org    and make it accessible to C++ as a byte array.
2758235Snate@binkert.org    '''
2768235Snate@binkert.org    blob_path = os.path.abspath(blob_path)
2778235Snate@binkert.org    blob_out_dir = os.path.join(env['BUILDDIR'], 'blobs')
2788235Snate@binkert.org    path_noext = joinpath(blob_out_dir, symbol)
2798235Snate@binkert.org    cpp_path = path_noext + '.cc'
2808235Snate@binkert.org    hpp_path = path_noext + '.hh'
2819003SAli.Saidi@ARM.com    def embedBlob(target, source, env):
2828235Snate@binkert.org        data = file(str(source[0]), 'r').read()
2835584Snate@binkert.org        cpp_code = code_formatter()
2844382Sbinkertn@umich.edu        hpp_code = code_formatter()
2854202Sbinkertn@umich.edu        blobToCpp(data, symbol, cpp_code, hpp_code, namespace='Blobs')
2864382Sbinkertn@umich.edu        cpp_path = str(target[0])
2874382Sbinkertn@umich.edu        hpp_path = str(target[1])
2884382Sbinkertn@umich.edu        cpp_dir = os.path.split(cpp_path)[0]
2899396Sandreas.hansson@arm.com        if not os.path.exists(cpp_dir):
2905584Snate@binkert.org            os.makedirs(cpp_dir)
2914382Sbinkertn@umich.edu        cpp_code.write(cpp_path)
2924382Sbinkertn@umich.edu        hpp_code.write(hpp_path)
2934382Sbinkertn@umich.edu    env.Command([cpp_path, hpp_path], blob_path,
2948232Snate@binkert.org                MakeAction(embedBlob, Transform("EMBED BLOB")))
2955192Ssaidi@eecs.umich.edu    Source(cpp_path)
2968232Snate@binkert.org
2978232Snate@binkert.orgdef GdbXml(xml_id, symbol):
2988232Snate@binkert.org    Blob(joinpath(gdb_xml_dir, xml_id), symbol)
2995192Ssaidi@eecs.umich.edu
3008232Snate@binkert.orgclass Source(SourceFile):
3015192Ssaidi@eecs.umich.edu    ungrouped_tag = 'No link group'
3025799Snate@binkert.org    source_groups = set()
3038232Snate@binkert.org
3045192Ssaidi@eecs.umich.edu    _current_group_tag = ungrouped_tag
3055192Ssaidi@eecs.umich.edu
3065192Ssaidi@eecs.umich.edu    @staticmethod
3078232Snate@binkert.org    def link_group_tag(group):
3085192Ssaidi@eecs.umich.edu        return 'link group: %s' % group
3098232Snate@binkert.org
3105192Ssaidi@eecs.umich.edu    @classmethod
3115192Ssaidi@eecs.umich.edu    def set_group(cls, group):
3125192Ssaidi@eecs.umich.edu        new_tag = Source.link_group_tag(group)
3135192Ssaidi@eecs.umich.edu        Source._current_group_tag = new_tag
3144382Sbinkertn@umich.edu        Source.source_groups.add(group)
3154382Sbinkertn@umich.edu
3164382Sbinkertn@umich.edu    def _add_link_group_tag(self):
3172667Sstever@eecs.umich.edu        self.tags.add(Source._current_group_tag)
3182667Sstever@eecs.umich.edu
3192667Sstever@eecs.umich.edu    '''Add a c/c++ source file to the build'''
3202667Sstever@eecs.umich.edu    def __init__(self, source, tags=None, add_tags=None):
3212667Sstever@eecs.umich.edu        '''specify the source file, and any tags'''
3222667Sstever@eecs.umich.edu        super(Source, self).__init__(source, tags, add_tags)
3235742Snate@binkert.org        self._add_link_group_tag()
3245742Snate@binkert.org
3255742Snate@binkert.orgclass PySource(SourceFile):
3265793Snate@binkert.org    '''Add a python source file to the named package'''
3278334Snate@binkert.org    invalid_sym_char = re.compile('[^A-z0-9_]')
3285793Snate@binkert.org    modules = {}
3295793Snate@binkert.org    tnodes = {}
3305793Snate@binkert.org    symnames = {}
3314382Sbinkertn@umich.edu
3324762Snate@binkert.org    def __init__(self, package, source, tags=None, add_tags=None):
3335344Sstever@gmail.com        '''specify the python package, the source file, and any tags'''
3344382Sbinkertn@umich.edu        super(PySource, self).__init__(source, tags, add_tags)
3355341Sstever@gmail.com
3365742Snate@binkert.org        modname,ext = self.extname
3375742Snate@binkert.org        assert ext == 'py'
3385742Snate@binkert.org
3395742Snate@binkert.org        if package:
3405742Snate@binkert.org            path = package.split('.')
3414762Snate@binkert.org        else:
3425742Snate@binkert.org            path = []
3435742Snate@binkert.org
3447722Sgblack@eecs.umich.edu        modpath = path[:]
3455742Snate@binkert.org        if modname != '__init__':
3465742Snate@binkert.org            modpath += [ modname ]
3475742Snate@binkert.org        modpath = '.'.join(modpath)
3489930Sandreas.hansson@arm.com
3499930Sandreas.hansson@arm.com        arcpath = path + [ self.basename ]
3509930Sandreas.hansson@arm.com        abspath = self.snode.abspath
3519930Sandreas.hansson@arm.com        if not exists(abspath):
3529930Sandreas.hansson@arm.com            abspath = self.tnode.abspath
3535742Snate@binkert.org
3548242Sbradley.danofsky@amd.com        self.package = package
3558242Sbradley.danofsky@amd.com        self.modname = modname
3568242Sbradley.danofsky@amd.com        self.modpath = modpath
3578242Sbradley.danofsky@amd.com        self.arcname = joinpath(*arcpath)
3585341Sstever@gmail.com        self.abspath = abspath
3595742Snate@binkert.org        self.compiled = File(self.filename + 'c')
3607722Sgblack@eecs.umich.edu        self.cpp = File(self.filename + '.cc')
3614773Snate@binkert.org        self.symname = PySource.invalid_sym_char.sub('_', modpath)
3626108Snate@binkert.org
3631858SN/A        PySource.modules[modpath] = self
3641085SN/A        PySource.tnodes[self.tnode] = self
3656658Snate@binkert.org        PySource.symnames[self.symname] = self
3666658Snate@binkert.org
3677673Snate@binkert.orgclass SimObject(PySource):
3686658Snate@binkert.org    '''Add a SimObject python file as a python source object and add
3696658Snate@binkert.org    it to a list of sim object modules'''
3706658Snate@binkert.org
3716658Snate@binkert.org    fixed = False
3726658Snate@binkert.org    modnames = []
3736658Snate@binkert.org
3746658Snate@binkert.org    def __init__(self, source, tags=None, add_tags=None):
3757673Snate@binkert.org        '''Specify the source file and any tags (automatically in
3767673Snate@binkert.org        the m5.objects package)'''
3777673Snate@binkert.org        super(SimObject, self).__init__('m5.objects', source, tags, add_tags)
3787673Snate@binkert.org        if self.fixed:
3797673Snate@binkert.org            raise AttributeError, "Too late to call SimObject now."
3807673Snate@binkert.org
3817673Snate@binkert.org        bisect.insort_right(SimObject.modnames, self.modname)
38210467Sandreas.hansson@arm.com
3836658Snate@binkert.orgclass ProtoBuf(SourceFile):
3847673Snate@binkert.org    '''Add a Protocol Buffer to build'''
38510467Sandreas.hansson@arm.com
38610467Sandreas.hansson@arm.com    def __init__(self, source, tags=None, add_tags=None):
38710467Sandreas.hansson@arm.com        '''Specify the source file, and any tags'''
38810467Sandreas.hansson@arm.com        super(ProtoBuf, self).__init__(source, tags, add_tags)
38910467Sandreas.hansson@arm.com
39010467Sandreas.hansson@arm.com        # Get the file name and the extension
39110467Sandreas.hansson@arm.com        modname,ext = self.extname
39210467Sandreas.hansson@arm.com        assert ext == 'proto'
39310467Sandreas.hansson@arm.com
39410467Sandreas.hansson@arm.com        # Currently, we stick to generating the C++ headers, so we
39510467Sandreas.hansson@arm.com        # only need to track the source and header.
3967673Snate@binkert.org        self.cc_file = File(modname + '.pb.cc')
3977673Snate@binkert.org        self.hh_file = File(modname + '.pb.h')
3987673Snate@binkert.org
3997673Snate@binkert.org
4007673Snate@binkert.orgexectuable_classes = []
4019048SAli.Saidi@ARM.comclass ExecutableMeta(type):
4027673Snate@binkert.org    '''Meta class for Executables.'''
4037673Snate@binkert.org    all = []
4047673Snate@binkert.org
4057673Snate@binkert.org    def __init__(cls, name, bases, d):
4066658Snate@binkert.org        if not d.pop('abstract', False):
4077756SAli.Saidi@ARM.com            ExecutableMeta.all.append(cls)
4087816Ssteve.reinhardt@amd.com        super(ExecutableMeta, cls).__init__(name, bases, d)
4096658Snate@binkert.org
4104382Sbinkertn@umich.edu        cls.all = []
4114382Sbinkertn@umich.edu
4124762Snate@binkert.orgclass Executable(object):
4134762Snate@binkert.org    '''Base class for creating an executable from sources.'''
4144762Snate@binkert.org    __metaclass__ = ExecutableMeta
4156654Snate@binkert.org
4166654Snate@binkert.org    abstract = True
4175517Snate@binkert.org
4185517Snate@binkert.org    def __init__(self, target, *srcs_and_filts):
4195517Snate@binkert.org        '''Specify the target name and any sources. Sources that are
4205517Snate@binkert.org        not SourceFiles are evalued with Source().'''
4215517Snate@binkert.org        super(Executable, self).__init__()
4225517Snate@binkert.org        self.all.append(self)
4235517Snate@binkert.org        self.target = target
4245517Snate@binkert.org
4255517Snate@binkert.org        isFilter = lambda arg: isinstance(arg, SourceFilter)
4265517Snate@binkert.org        self.filters = filter(isFilter, srcs_and_filts)
4275517Snate@binkert.org        sources = filter(lambda a: not isFilter(a), srcs_and_filts)
4285517Snate@binkert.org
4295517Snate@binkert.org        srcs = SourceList()
4305517Snate@binkert.org        for src in sources:
4315517Snate@binkert.org            if not isinstance(src, SourceFile):
4325517Snate@binkert.org                src = Source(src, tags=[])
4335517Snate@binkert.org            srcs.append(src)
4346654Snate@binkert.org
4355517Snate@binkert.org        self.sources = srcs
4365517Snate@binkert.org        self.dir = Dir('.')
4375517Snate@binkert.org
4385517Snate@binkert.org    def path(self, env):
4395517Snate@binkert.org        return self.dir.File(self.target + '.' + env['EXE_SUFFIX'])
4405517Snate@binkert.org
4415517Snate@binkert.org    def srcs_to_objs(self, env, sources):
4425517Snate@binkert.org        return list([ s.static(env) for s in sources ])
4436143Snate@binkert.org
4446654Snate@binkert.org    @classmethod
4455517Snate@binkert.org    def declare_all(cls, env):
4465517Snate@binkert.org        return list([ instance.declare(env) for instance in cls.all ])
4475517Snate@binkert.org
4485517Snate@binkert.org    def declare(self, env, objs=None):
4495517Snate@binkert.org        if objs is None:
4505517Snate@binkert.org            objs = self.srcs_to_objs(env, self.sources)
4515517Snate@binkert.org
4525517Snate@binkert.org        if env['STRIP_EXES']:
4535517Snate@binkert.org            stripped = self.path(env)
4545517Snate@binkert.org            unstripped = env.File(str(stripped) + '.unstripped')
4555517Snate@binkert.org            if sys.platform == 'sunos5':
4565517Snate@binkert.org                cmd = 'cp $SOURCE $TARGET; strip $TARGET'
4575517Snate@binkert.org            else:
4585517Snate@binkert.org                cmd = 'strip $SOURCE -o $TARGET'
4596654Snate@binkert.org            env.Program(unstripped, objs)
4606654Snate@binkert.org            return env.Command(stripped, unstripped,
4615517Snate@binkert.org                               MakeAction(cmd, Transform("STRIP")))
4625517Snate@binkert.org        else:
4636143Snate@binkert.org            return env.Program(self.path(env), objs)
4646143Snate@binkert.org
4656143Snate@binkert.orgclass UnitTest(Executable):
4666727Ssteve.reinhardt@amd.com    '''Create a UnitTest'''
4675517Snate@binkert.org    def __init__(self, target, *srcs_and_filts, **kwargs):
4686727Ssteve.reinhardt@amd.com        super(UnitTest, self).__init__(target, *srcs_and_filts)
4695517Snate@binkert.org
4705517Snate@binkert.org        self.main = kwargs.get('main', False)
4715517Snate@binkert.org
4726654Snate@binkert.org    def declare(self, env):
4736654Snate@binkert.org        sources = list(self.sources)
4747673Snate@binkert.org        for f in self.filters:
4756654Snate@binkert.org            sources += Source.all.apply_filter(f)
4766654Snate@binkert.org        objs = self.srcs_to_objs(env, sources) + env['STATIC_OBJS']
4776654Snate@binkert.org        if self.main:
4786654Snate@binkert.org            objs += env['MAIN_OBJS']
4795517Snate@binkert.org        return super(UnitTest, self).declare(env, objs)
4805517Snate@binkert.org
4815517Snate@binkert.orgclass GTest(Executable):
4826143Snate@binkert.org    '''Create a unit test based on the google test framework.'''
4835517Snate@binkert.org    all = []
4844762Snate@binkert.org    def __init__(self, *srcs_and_filts, **kwargs):
4855517Snate@binkert.org        super(GTest, self).__init__(*srcs_and_filts)
4865517Snate@binkert.org
4876143Snate@binkert.org        self.skip_lib = kwargs.pop('skip_lib', False)
4886143Snate@binkert.org
4895517Snate@binkert.org    @classmethod
4905517Snate@binkert.org    def declare_all(cls, env):
4915517Snate@binkert.org        env = env.Clone()
4925517Snate@binkert.org        env.Append(LIBS=env['GTEST_LIBS'])
4935517Snate@binkert.org        env.Append(CPPFLAGS=env['GTEST_CPPFLAGS'])
4945517Snate@binkert.org        env['GTEST_LIB_SOURCES'] = Source.all.with_tag('gtest lib')
4955517Snate@binkert.org        env['GTEST_OUT_DIR'] = \
4965517Snate@binkert.org            Dir(env['BUILDDIR']).Dir('unittests.' + env['EXE_SUFFIX'])
4975517Snate@binkert.org        return super(GTest, cls).declare_all(env)
4989338SAndreas.Sandberg@arm.com
4999338SAndreas.Sandberg@arm.com    def declare(self, env):
5009338SAndreas.Sandberg@arm.com        sources = list(self.sources)
5019338SAndreas.Sandberg@arm.com        if not self.skip_lib:
5029338SAndreas.Sandberg@arm.com            sources += env['GTEST_LIB_SOURCES']
5039338SAndreas.Sandberg@arm.com        for f in self.filters:
5048596Ssteve.reinhardt@amd.com            sources += Source.all.apply_filter(f)
5058596Ssteve.reinhardt@amd.com        objs = self.srcs_to_objs(env, sources)
5068596Ssteve.reinhardt@amd.com
5078596Ssteve.reinhardt@amd.com        binary = super(GTest, self).declare(env, objs)
5088596Ssteve.reinhardt@amd.com
5098596Ssteve.reinhardt@amd.com        out_dir = env['GTEST_OUT_DIR']
5108596Ssteve.reinhardt@amd.com        xml_file = out_dir.Dir(str(self.dir)).File(self.target + '.xml')
5116143Snate@binkert.org        AlwaysBuild(env.Command(xml_file, binary,
5125517Snate@binkert.org            "${SOURCES[0]} --gtest_output=xml:${TARGETS[0]}"))
5136654Snate@binkert.org
5146654Snate@binkert.org        return binary
5156654Snate@binkert.org
5166654Snate@binkert.orgclass Gem5(Executable):
5176654Snate@binkert.org    '''Create a gem5 executable.'''
5186654Snate@binkert.org
5195517Snate@binkert.org    def __init__(self, target):
5205517Snate@binkert.org        super(Gem5, self).__init__(target)
5215517Snate@binkert.org
5228596Ssteve.reinhardt@amd.com    def declare(self, env):
5238596Ssteve.reinhardt@amd.com        objs = env['MAIN_OBJS'] + env['STATIC_OBJS']
5244762Snate@binkert.org        return super(Gem5, self).declare(env, objs)
5254762Snate@binkert.org
5264762Snate@binkert.org
5274762Snate@binkert.org# Children should have access
5284762Snate@binkert.orgExport('Blob')
5294762Snate@binkert.orgExport('GdbXml')
5307675Snate@binkert.orgExport('Source')
53110584Sandreas.hansson@arm.comExport('PySource')
5324762Snate@binkert.orgExport('SimObject')
5334762Snate@binkert.orgExport('ProtoBuf')
5344762Snate@binkert.orgExport('Executable')
5354762Snate@binkert.orgExport('UnitTest')
5364382Sbinkertn@umich.eduExport('GTest')
5374382Sbinkertn@umich.edu
5385517Snate@binkert.org########################################################################
5396654Snate@binkert.org#
5405517Snate@binkert.org# Debug Flags
5418126Sgblack@eecs.umich.edu#
5426654Snate@binkert.orgdebug_flags = {}
5437673Snate@binkert.orgdef DebugFlag(name, desc=None):
5446654Snate@binkert.org    if name in debug_flags:
5456654Snate@binkert.org        raise AttributeError, "Flag %s already specified" % name
5466654Snate@binkert.org    debug_flags[name] = (name, (), desc)
5476654Snate@binkert.org
5486654Snate@binkert.orgdef CompoundFlag(name, flags, desc=None):
5496654Snate@binkert.org    if name in debug_flags:
5506654Snate@binkert.org        raise AttributeError, "Flag %s already specified" % name
5516669Snate@binkert.org
5526669Snate@binkert.org    compound = tuple(flags)
5536669Snate@binkert.org    debug_flags[name] = (name, compound, desc)
5546669Snate@binkert.org
5556669Snate@binkert.orgExport('DebugFlag')
5566669Snate@binkert.orgExport('CompoundFlag')
5576654Snate@binkert.org
5587673Snate@binkert.org########################################################################
5595517Snate@binkert.org#
5608126Sgblack@eecs.umich.edu# Set some compiler variables
5615798Snate@binkert.org#
5627756SAli.Saidi@ARM.com
5637816Ssteve.reinhardt@amd.com# Include file paths are rooted in this directory.  SCons will
5645798Snate@binkert.org# automatically expand '.' to refer to both the source directory and
5655798Snate@binkert.org# the corresponding build directory to pick up generated include
5665517Snate@binkert.org# files.
5675517Snate@binkert.orgenv.Append(CPPPATH=Dir('.'))
5687673Snate@binkert.org
5695517Snate@binkert.orgfor extra_dir in extras_dir_list:
5705517Snate@binkert.org    env.Append(CPPPATH=Dir(extra_dir))
5717673Snate@binkert.org
5727673Snate@binkert.org# Workaround for bug in SCons version > 0.97d20071212
5735517Snate@binkert.org# Scons bug id: 2006 gem5 Bug id: 308
5745798Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
5755798Snate@binkert.org    Dir(root[len(base_dir) + 1:])
5768333Snate@binkert.org
5777816Ssteve.reinhardt@amd.com########################################################################
5785798Snate@binkert.org#
5795798Snate@binkert.org# Walk the tree and execute all SConscripts in subdirectories
5804762Snate@binkert.org#
5814762Snate@binkert.org
5824762Snate@binkert.orghere = Dir('.').srcnode().abspath
5834762Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
5844762Snate@binkert.org    if root == here:
5858596Ssteve.reinhardt@amd.com        # we don't want to recurse back into this SConscript
5865517Snate@binkert.org        continue
5875517Snate@binkert.org
5885517Snate@binkert.org    if 'SConscript' in files:
5895517Snate@binkert.org        build_dir = joinpath(env['BUILDDIR'], root[len(base_dir) + 1:])
5905517Snate@binkert.org        Source.set_group(build_dir)
5917673Snate@binkert.org        SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
5928596Ssteve.reinhardt@amd.com
5937673Snate@binkert.orgfor extra_dir in extras_dir_list:
5945517Snate@binkert.org    prefix_len = len(dirname(extra_dir)) + 1
59510458Sandreas.hansson@arm.com
59610458Sandreas.hansson@arm.com    # Also add the corresponding build directory to pick up generated
59710458Sandreas.hansson@arm.com    # include files.
59810458Sandreas.hansson@arm.com    env.Append(CPPPATH=Dir(joinpath(env['BUILDDIR'], extra_dir[prefix_len:])))
59910458Sandreas.hansson@arm.com
60010458Sandreas.hansson@arm.com    for root, dirs, files in os.walk(extra_dir, topdown=True):
60110458Sandreas.hansson@arm.com        # if build lives in the extras directory, don't walk down it
60210458Sandreas.hansson@arm.com        if 'build' in dirs:
60310458Sandreas.hansson@arm.com            dirs.remove('build')
60410458Sandreas.hansson@arm.com
60510458Sandreas.hansson@arm.com        if 'SConscript' in files:
60610458Sandreas.hansson@arm.com            build_dir = joinpath(env['BUILDDIR'], root[prefix_len:])
6078596Ssteve.reinhardt@amd.com            SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
6085517Snate@binkert.org
6095517Snate@binkert.orgfor opt in export_vars:
6105517Snate@binkert.org    env.ConfigFile(opt)
6118596Ssteve.reinhardt@amd.com
6125517Snate@binkert.orgdef makeTheISA(source, target, env):
6137673Snate@binkert.org    isas = [ src.get_contents() for src in source ]
6147673Snate@binkert.org    target_isa = env['TARGET_ISA']
6157673Snate@binkert.org    def define(isa):
6165517Snate@binkert.org        return isa.upper() + '_ISA'
6175517Snate@binkert.org
6185517Snate@binkert.org    def namespace(isa):
6195517Snate@binkert.org        return isa[0].upper() + isa[1:].lower() + 'ISA'
6205517Snate@binkert.org
6215517Snate@binkert.org
6225517Snate@binkert.org    code = code_formatter()
6237673Snate@binkert.org    code('''\
6247673Snate@binkert.org#ifndef __CONFIG_THE_ISA_HH__
6257673Snate@binkert.org#define __CONFIG_THE_ISA_HH__
6265517Snate@binkert.org
6278596Ssteve.reinhardt@amd.com''')
6285517Snate@binkert.org
6295517Snate@binkert.org    # create defines for the preprocessing and compile-time determination
6305517Snate@binkert.org    for i,isa in enumerate(isas):
6315517Snate@binkert.org        code('#define $0 $1', define(isa), i + 1)
6325517Snate@binkert.org    code()
6337673Snate@binkert.org
6347673Snate@binkert.org    # create an enum for any run-time determination of the ISA, we
6357673Snate@binkert.org    # reuse the same name as the namespaces
6365517Snate@binkert.org    code('enum class Arch {')
6378596Ssteve.reinhardt@amd.com    for i,isa in enumerate(isas):
6387675Snate@binkert.org        if i + 1 == len(isas):
6397675Snate@binkert.org            code('  $0 = $1', namespace(isa), define(isa))
6407675Snate@binkert.org        else:
6417675Snate@binkert.org            code('  $0 = $1,', namespace(isa), define(isa))
6427675Snate@binkert.org    code('};')
6437675Snate@binkert.org
6448596Ssteve.reinhardt@amd.com    code('''
6457675Snate@binkert.org
6467675Snate@binkert.org#define THE_ISA ${{define(target_isa)}}
6478596Ssteve.reinhardt@amd.com#define TheISA ${{namespace(target_isa)}}
6488596Ssteve.reinhardt@amd.com#define THE_ISA_STR "${{target_isa}}"
6498596Ssteve.reinhardt@amd.com
6508596Ssteve.reinhardt@amd.com#endif // __CONFIG_THE_ISA_HH__''')
6518596Ssteve.reinhardt@amd.com
6528596Ssteve.reinhardt@amd.com    code.write(str(target[0]))
6538596Ssteve.reinhardt@amd.com
6548596Ssteve.reinhardt@amd.comenv.Command('config/the_isa.hh', map(Value, all_isa_list),
65510454SCurtis.Dunham@arm.com            MakeAction(makeTheISA, Transform("CFG ISA", 0)))
65610454SCurtis.Dunham@arm.com
65710454SCurtis.Dunham@arm.comdef makeTheGPUISA(source, target, env):
65810454SCurtis.Dunham@arm.com    isas = [ src.get_contents() for src in source ]
6598596Ssteve.reinhardt@amd.com    target_gpu_isa = env['TARGET_GPU_ISA']
6604762Snate@binkert.org    def define(isa):
6616143Snate@binkert.org        return isa.upper() + '_ISA'
6626143Snate@binkert.org
6636143Snate@binkert.org    def namespace(isa):
6644762Snate@binkert.org        return isa[0].upper() + isa[1:].lower() + 'ISA'
6654762Snate@binkert.org
6664762Snate@binkert.org
6677756SAli.Saidi@ARM.com    code = code_formatter()
6688596Ssteve.reinhardt@amd.com    code('''\
6694762Snate@binkert.org#ifndef __CONFIG_THE_GPU_ISA_HH__
67010454SCurtis.Dunham@arm.com#define __CONFIG_THE_GPU_ISA_HH__
6714762Snate@binkert.org
67210458Sandreas.hansson@arm.com''')
67310458Sandreas.hansson@arm.com
67410458Sandreas.hansson@arm.com    # create defines for the preprocessing and compile-time determination
67510458Sandreas.hansson@arm.com    for i,isa in enumerate(isas):
67610458Sandreas.hansson@arm.com        code('#define $0 $1', define(isa), i + 1)
67710458Sandreas.hansson@arm.com    code()
67810458Sandreas.hansson@arm.com
67910458Sandreas.hansson@arm.com    # create an enum for any run-time determination of the ISA, we
68010458Sandreas.hansson@arm.com    # reuse the same name as the namespaces
68110458Sandreas.hansson@arm.com    code('enum class GPUArch {')
68210458Sandreas.hansson@arm.com    for i,isa in enumerate(isas):
68310458Sandreas.hansson@arm.com        if i + 1 == len(isas):
68410458Sandreas.hansson@arm.com            code('  $0 = $1', namespace(isa), define(isa))
68510458Sandreas.hansson@arm.com        else:
68610458Sandreas.hansson@arm.com            code('  $0 = $1,', namespace(isa), define(isa))
68710458Sandreas.hansson@arm.com    code('};')
68810458Sandreas.hansson@arm.com
68910458Sandreas.hansson@arm.com    code('''
69010458Sandreas.hansson@arm.com
69110458Sandreas.hansson@arm.com#define THE_GPU_ISA ${{define(target_gpu_isa)}}
69210458Sandreas.hansson@arm.com#define TheGpuISA ${{namespace(target_gpu_isa)}}
69310458Sandreas.hansson@arm.com#define THE_GPU_ISA_STR "${{target_gpu_isa}}"
69410458Sandreas.hansson@arm.com
69510458Sandreas.hansson@arm.com#endif // __CONFIG_THE_GPU_ISA_HH__''')
69610458Sandreas.hansson@arm.com
69710458Sandreas.hansson@arm.com    code.write(str(target[0]))
69810458Sandreas.hansson@arm.com
69910458Sandreas.hansson@arm.comenv.Command('config/the_gpu_isa.hh', map(Value, all_gpu_isa_list),
70010458Sandreas.hansson@arm.com            MakeAction(makeTheGPUISA, Transform("CFG ISA", 0)))
70110458Sandreas.hansson@arm.com
70210458Sandreas.hansson@arm.com########################################################################
70310458Sandreas.hansson@arm.com#
70410458Sandreas.hansson@arm.com# Prevent any SimObjects from being added after this point, they
70510458Sandreas.hansson@arm.com# should all have been added in the SConscripts above
70610458Sandreas.hansson@arm.com#
70710458Sandreas.hansson@arm.comSimObject.fixed = True
70810458Sandreas.hansson@arm.com
70910458Sandreas.hansson@arm.comclass DictImporter(object):
71010458Sandreas.hansson@arm.com    '''This importer takes a dictionary of arbitrary module names that
71110458Sandreas.hansson@arm.com    map to arbitrary filenames.'''
71210458Sandreas.hansson@arm.com    def __init__(self, modules):
71310458Sandreas.hansson@arm.com        self.modules = modules
71410458Sandreas.hansson@arm.com        self.installed = set()
71510458Sandreas.hansson@arm.com
71610458Sandreas.hansson@arm.com    def __del__(self):
71710458Sandreas.hansson@arm.com        self.unload()
71810458Sandreas.hansson@arm.com
71910458Sandreas.hansson@arm.com    def unload(self):
72010458Sandreas.hansson@arm.com        import sys
72110584Sandreas.hansson@arm.com        for module in self.installed:
72210458Sandreas.hansson@arm.com            del sys.modules[module]
72310458Sandreas.hansson@arm.com        self.installed = set()
72410458Sandreas.hansson@arm.com
72510458Sandreas.hansson@arm.com    def find_module(self, fullname, path):
72610458Sandreas.hansson@arm.com        if fullname == 'm5.defines':
7278596Ssteve.reinhardt@amd.com            return self
7285463Snate@binkert.org
72910584Sandreas.hansson@arm.com        if fullname == 'm5.objects':
7308596Ssteve.reinhardt@amd.com            return self
7315463Snate@binkert.org
7327756SAli.Saidi@ARM.com        if fullname.startswith('_m5'):
7338596Ssteve.reinhardt@amd.com            return None
7344762Snate@binkert.org
73510454SCurtis.Dunham@arm.com        source = self.modules.get(fullname, None)
7367677Snate@binkert.org        if source is not None and fullname.startswith('m5.objects'):
7374762Snate@binkert.org            return self
7384762Snate@binkert.org
7396143Snate@binkert.org        return None
7406143Snate@binkert.org
7416143Snate@binkert.org    def load_module(self, fullname):
7424762Snate@binkert.org        mod = imp.new_module(fullname)
7434762Snate@binkert.org        sys.modules[fullname] = mod
7447756SAli.Saidi@ARM.com        self.installed.add(fullname)
7457816Ssteve.reinhardt@amd.com
7464762Snate@binkert.org        mod.__loader__ = self
74710454SCurtis.Dunham@arm.com        if fullname == 'm5.objects':
7484762Snate@binkert.org            mod.__path__ = fullname.split('.')
7494762Snate@binkert.org            return mod
7504762Snate@binkert.org
7517756SAli.Saidi@ARM.com        if fullname == 'm5.defines':
7528596Ssteve.reinhardt@amd.com            mod.__dict__['buildEnv'] = m5.util.SmartDict(build_env)
7534762Snate@binkert.org            return mod
75410454SCurtis.Dunham@arm.com
7554762Snate@binkert.org        source = self.modules[fullname]
7567677Snate@binkert.org        if source.modname == '__init__':
7577756SAli.Saidi@ARM.com            mod.__path__ = source.modpath
7588596Ssteve.reinhardt@amd.com        mod.__file__ = source.abspath
7597675Snate@binkert.org
76010454SCurtis.Dunham@arm.com        exec file(source.abspath, 'r') in mod.__dict__
7617677Snate@binkert.org
7625517Snate@binkert.org        return mod
7638596Ssteve.reinhardt@amd.com
76410584Sandreas.hansson@arm.comimport m5.SimObject
7659248SAndreas.Sandberg@arm.comimport m5.params
7669248SAndreas.Sandberg@arm.comfrom m5.util import code_formatter
7678596Ssteve.reinhardt@amd.com
7688596Ssteve.reinhardt@amd.comm5.SimObject.clear()
7698596Ssteve.reinhardt@amd.comm5.params.clear()
7709248SAndreas.Sandberg@arm.com
7718596Ssteve.reinhardt@amd.com# install the python importer so we can grab stuff from the source
7724762Snate@binkert.org# tree itself.  We can't have SimObjects added after this point or
7737674Snate@binkert.org# else we won't know about them for the rest of the stuff.
7747674Snate@binkert.orgimporter = DictImporter(PySource.modules)
7757674Snate@binkert.orgsys.meta_path[0:0] = [ importer ]
7767674Snate@binkert.org
7777674Snate@binkert.org# import all sim objects so we can populate the all_objects list
7787674Snate@binkert.org# make sure that we're working with a list, then let's sort it
7797674Snate@binkert.orgfor modname in SimObject.modnames:
7807674Snate@binkert.org    exec('from m5.objects import %s' % modname)
7817674Snate@binkert.org
7827674Snate@binkert.org# we need to unload all of the currently imported modules so that they
7837674Snate@binkert.org# will be re-imported the next time the sconscript is run
7847674Snate@binkert.orgimporter.unload()
7857674Snate@binkert.orgsys.meta_path.remove(importer)
7867674Snate@binkert.org
7877674Snate@binkert.orgsim_objects = m5.SimObject.allClasses
7884762Snate@binkert.orgall_enums = m5.params.allEnums
7896143Snate@binkert.org
7906143Snate@binkert.orgfor name,obj in sorted(sim_objects.iteritems()):
7917756SAli.Saidi@ARM.com    for param in obj._params.local.values():
7927816Ssteve.reinhardt@amd.com        # load the ptype attribute now because it depends on the
7938235Snate@binkert.org        # current version of SimObject.allClasses, but when scons
7948596Ssteve.reinhardt@amd.com        # actually uses the value, all versions of
7957756SAli.Saidi@ARM.com        # SimObject.allClasses will have been loaded
7967816Ssteve.reinhardt@amd.com        param.ptype
79710454SCurtis.Dunham@arm.com
7988235Snate@binkert.org########################################################################
7994382Sbinkertn@umich.edu#
8009396Sandreas.hansson@arm.com# calculate extra dependencies
8019396Sandreas.hansson@arm.com#
8029396Sandreas.hansson@arm.commodule_depends = ["m5", "m5.SimObject", "m5.params"]
8039396Sandreas.hansson@arm.comdepends = [ PySource.modules[dep].snode for dep in module_depends ]
8049396Sandreas.hansson@arm.comdepends.sort(key = lambda x: x.name)
8059396Sandreas.hansson@arm.com
8069396Sandreas.hansson@arm.com########################################################################
8079396Sandreas.hansson@arm.com#
8089396Sandreas.hansson@arm.com# Commands for the basic automatically generated python files
8099396Sandreas.hansson@arm.com#
8109396Sandreas.hansson@arm.com
8119396Sandreas.hansson@arm.com# Generate Python file containing a dict specifying the current
81210454SCurtis.Dunham@arm.com# buildEnv flags.
8139396Sandreas.hansson@arm.comdef makeDefinesPyFile(target, source, env):
8149396Sandreas.hansson@arm.com    build_env = source[0].get_contents()
8159396Sandreas.hansson@arm.com
8169396Sandreas.hansson@arm.com    code = code_formatter()
8179396Sandreas.hansson@arm.com    code("""
8189396Sandreas.hansson@arm.comimport _m5.core
8198232Snate@binkert.orgimport m5.util
8208232Snate@binkert.org
8218232Snate@binkert.orgbuildEnv = m5.util.SmartDict($build_env)
8228232Snate@binkert.org
8238232Snate@binkert.orgcompileDate = _m5.core.compileDate
8246229Snate@binkert.org_globals = globals()
82510455SCurtis.Dunham@arm.comfor key,val in _m5.core.__dict__.iteritems():
8266229Snate@binkert.org    if key.startswith('flag_'):
82710455SCurtis.Dunham@arm.com        flag = key[5:]
82810455SCurtis.Dunham@arm.com        _globals[flag] = val
82910455SCurtis.Dunham@arm.comdel _globals
8305517Snate@binkert.org""")
8315517Snate@binkert.org    code.write(target[0].abspath)
8327673Snate@binkert.org
8335517Snate@binkert.orgdefines_info = Value(build_env)
83410455SCurtis.Dunham@arm.com# Generate a file with all of the compile options in it
8355517Snate@binkert.orgenv.Command('python/m5/defines.py', defines_info,
8365517Snate@binkert.org            MakeAction(makeDefinesPyFile, Transform("DEFINES", 0)))
8378232Snate@binkert.orgPySource('m5', 'python/m5/defines.py')
83810455SCurtis.Dunham@arm.com
83910455SCurtis.Dunham@arm.com# Generate python file containing info about the M5 source code
84010455SCurtis.Dunham@arm.comdef makeInfoPyFile(target, source, env):
8417673Snate@binkert.org    code = code_formatter()
8427673Snate@binkert.org    for src in source:
84310455SCurtis.Dunham@arm.com        data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
84410455SCurtis.Dunham@arm.com        code('$src = ${{repr(data)}}')
84510455SCurtis.Dunham@arm.com    code.write(str(target[0]))
8465517Snate@binkert.org
84710455SCurtis.Dunham@arm.com# Generate a file that wraps the basic top level files
84810455SCurtis.Dunham@arm.comenv.Command('python/m5/info.py',
84910455SCurtis.Dunham@arm.com            [ '#/COPYING', '#/LICENSE', '#/README', ],
85010455SCurtis.Dunham@arm.com            MakeAction(makeInfoPyFile, Transform("INFO")))
85110455SCurtis.Dunham@arm.comPySource('m5', 'python/m5/info.py')
85210455SCurtis.Dunham@arm.com
85310455SCurtis.Dunham@arm.com########################################################################
85410455SCurtis.Dunham@arm.com#
85510685Sandreas.hansson@arm.com# Create all of the SimObject param headers and enum headers
85610455SCurtis.Dunham@arm.com#
85710685Sandreas.hansson@arm.com
85810455SCurtis.Dunham@arm.comdef createSimObjectParamStruct(target, source, env):
8595517Snate@binkert.org    assert len(target) == 1 and len(source) == 1
86010455SCurtis.Dunham@arm.com
8618232Snate@binkert.org    name = source[0].get_text_contents()
8628232Snate@binkert.org    obj = sim_objects[name]
8635517Snate@binkert.org
8647673Snate@binkert.org    code = code_formatter()
8655517Snate@binkert.org    obj.cxx_param_decl(code)
8668232Snate@binkert.org    code.write(target[0].abspath)
8678232Snate@binkert.org
8685517Snate@binkert.orgdef createSimObjectCxxConfig(is_header):
8698232Snate@binkert.org    def body(target, source, env):
8708232Snate@binkert.org        assert len(target) == 1 and len(source) == 1
8718232Snate@binkert.org
8727673Snate@binkert.org        name = str(source[0].get_contents())
8735517Snate@binkert.org        obj = sim_objects[name]
8745517Snate@binkert.org
8757673Snate@binkert.org        code = code_formatter()
8765517Snate@binkert.org        obj.cxx_config_param_file(code, is_header)
87710455SCurtis.Dunham@arm.com        code.write(target[0].abspath)
8785517Snate@binkert.org    return body
8795517Snate@binkert.org
8808232Snate@binkert.orgdef createEnumStrings(target, source, env):
8818232Snate@binkert.org    assert len(target) == 1 and len(source) == 2
8825517Snate@binkert.org
8838232Snate@binkert.org    name = source[0].get_text_contents()
8848232Snate@binkert.org    use_python = source[1].read()
8855517Snate@binkert.org    obj = all_enums[name]
8868232Snate@binkert.org
8878232Snate@binkert.org    code = code_formatter()
8888232Snate@binkert.org    obj.cxx_def(code)
8895517Snate@binkert.org    if use_python:
8908232Snate@binkert.org        obj.pybind_def(code)
8918232Snate@binkert.org    code.write(target[0].abspath)
8928232Snate@binkert.org
8938232Snate@binkert.orgdef createEnumDecls(target, source, env):
8948232Snate@binkert.org    assert len(target) == 1 and len(source) == 1
8958232Snate@binkert.org
8965517Snate@binkert.org    name = source[0].get_text_contents()
8978232Snate@binkert.org    obj = all_enums[name]
8988232Snate@binkert.org
8995517Snate@binkert.org    code = code_formatter()
9008232Snate@binkert.org    obj.cxx_decl(code)
9017673Snate@binkert.org    code.write(target[0].abspath)
9025517Snate@binkert.org
9037673Snate@binkert.orgdef createSimObjectPyBindWrapper(target, source, env):
9045517Snate@binkert.org    name = source[0].get_text_contents()
9058232Snate@binkert.org    obj = sim_objects[name]
9068232Snate@binkert.org
9078232Snate@binkert.org    code = code_formatter()
9085192Ssaidi@eecs.umich.edu    obj.pybind_decl(code)
90910454SCurtis.Dunham@arm.com    code.write(target[0].abspath)
91010454SCurtis.Dunham@arm.com
9118232Snate@binkert.org# Generate all of the SimObject param C++ struct header files
91210455SCurtis.Dunham@arm.comparams_hh_files = []
91310455SCurtis.Dunham@arm.comfor name,simobj in sorted(sim_objects.iteritems()):
91410455SCurtis.Dunham@arm.com    py_source = PySource.modules[simobj.__module__]
91510455SCurtis.Dunham@arm.com    extra_deps = [ py_source.tnode ]
91610455SCurtis.Dunham@arm.com
91710455SCurtis.Dunham@arm.com    hh_file = File('params/%s.hh' % name)
9185192Ssaidi@eecs.umich.edu    params_hh_files.append(hh_file)
9197674Snate@binkert.org    env.Command(hh_file, Value(name),
9205522Snate@binkert.org                MakeAction(createSimObjectParamStruct, Transform("SO PARAM")))
9215522Snate@binkert.org    env.Depends(hh_file, depends + extra_deps)
9227674Snate@binkert.org
9237674Snate@binkert.org# C++ parameter description files
9247674Snate@binkert.orgif GetOption('with_cxx_config'):
9257674Snate@binkert.org    for name,simobj in sorted(sim_objects.iteritems()):
9267674Snate@binkert.org        py_source = PySource.modules[simobj.__module__]
9277674Snate@binkert.org        extra_deps = [ py_source.tnode ]
9287674Snate@binkert.org
9297674Snate@binkert.org        cxx_config_hh_file = File('cxx_config/%s.hh' % name)
9305522Snate@binkert.org        cxx_config_cc_file = File('cxx_config/%s.cc' % name)
9315522Snate@binkert.org        env.Command(cxx_config_hh_file, Value(name),
9325522Snate@binkert.org                    MakeAction(createSimObjectCxxConfig(True),
9335517Snate@binkert.org                    Transform("CXXCPRHH")))
9345522Snate@binkert.org        env.Command(cxx_config_cc_file, Value(name),
9355517Snate@binkert.org                    MakeAction(createSimObjectCxxConfig(False),
9366143Snate@binkert.org                    Transform("CXXCPRCC")))
9376727Ssteve.reinhardt@amd.com        env.Depends(cxx_config_hh_file, depends + extra_deps +
9385522Snate@binkert.org                    [File('params/%s.hh' % name), File('sim/cxx_config.hh')])
9395522Snate@binkert.org        env.Depends(cxx_config_cc_file, depends + extra_deps +
9405522Snate@binkert.org                    [cxx_config_hh_file])
9417674Snate@binkert.org        Source(cxx_config_cc_file)
9425517Snate@binkert.org
9437673Snate@binkert.org    cxx_config_init_cc_file = File('cxx_config/init.cc')
9447673Snate@binkert.org
9457674Snate@binkert.org    def createCxxConfigInitCC(target, source, env):
9467673Snate@binkert.org        assert len(target) == 1 and len(source) == 1
9477674Snate@binkert.org
9487674Snate@binkert.org        code = code_formatter()
9498946Sandreas.hansson@arm.com
9507674Snate@binkert.org        for name,simobj in sorted(sim_objects.iteritems()):
9517674Snate@binkert.org            if not hasattr(simobj, 'abstract') or not simobj.abstract:
9527674Snate@binkert.org                code('#include "cxx_config/${name}.hh"')
9535522Snate@binkert.org        code()
9545522Snate@binkert.org        code('void cxxConfigInit()')
9557674Snate@binkert.org        code('{')
9567674Snate@binkert.org        code.indent()
9577674Snate@binkert.org        for name,simobj in sorted(sim_objects.iteritems()):
9587674Snate@binkert.org            not_abstract = not hasattr(simobj, 'abstract') or \
9597673Snate@binkert.org                not simobj.abstract
9607674Snate@binkert.org            if not_abstract and 'type' in simobj.__dict__:
9617674Snate@binkert.org                code('cxx_config_directory["${name}"] = '
9627674Snate@binkert.org                     '${name}CxxConfigParams::makeDirectoryEntry();')
9637674Snate@binkert.org        code.dedent()
9647674Snate@binkert.org        code('}')
9657674Snate@binkert.org        code.write(target[0].abspath)
9667674Snate@binkert.org
9677674Snate@binkert.org    py_source = PySource.modules[simobj.__module__]
9687811Ssteve.reinhardt@amd.com    extra_deps = [ py_source.tnode ]
9697674Snate@binkert.org    env.Command(cxx_config_init_cc_file, Value(name),
9707673Snate@binkert.org        MakeAction(createCxxConfigInitCC, Transform("CXXCINIT")))
9715522Snate@binkert.org    cxx_param_hh_files = ["cxx_config/%s.hh" % simobj
9726143Snate@binkert.org        for name,simobj in sorted(sim_objects.iteritems())
97310453SAndrew.Bardsley@arm.com        if not hasattr(simobj, 'abstract') or not simobj.abstract]
9747816Ssteve.reinhardt@amd.com    Depends(cxx_config_init_cc_file, cxx_param_hh_files +
97510454SCurtis.Dunham@arm.com            [File('sim/cxx_config.hh')])
97610453SAndrew.Bardsley@arm.com    Source(cxx_config_init_cc_file)
9774382Sbinkertn@umich.edu
9784382Sbinkertn@umich.edu# Generate all enum header files
9794382Sbinkertn@umich.edufor name,enum in sorted(all_enums.iteritems()):
9804382Sbinkertn@umich.edu    py_source = PySource.modules[enum.__module__]
9814382Sbinkertn@umich.edu    extra_deps = [ py_source.tnode ]
9824382Sbinkertn@umich.edu
9834382Sbinkertn@umich.edu    cc_file = File('enums/%s.cc' % name)
9844382Sbinkertn@umich.edu    env.Command(cc_file, [Value(name), Value(env['USE_PYTHON'])],
98510196SCurtis.Dunham@arm.com                MakeAction(createEnumStrings, Transform("ENUM STR")))
9864382Sbinkertn@umich.edu    env.Depends(cc_file, depends + extra_deps)
98710196SCurtis.Dunham@arm.com    Source(cc_file)
98810196SCurtis.Dunham@arm.com
98910196SCurtis.Dunham@arm.com    hh_file = File('enums/%s.hh' % name)
99010196SCurtis.Dunham@arm.com    env.Command(hh_file, Value(name),
99110196SCurtis.Dunham@arm.com                MakeAction(createEnumDecls, Transform("ENUMDECL")))
99210196SCurtis.Dunham@arm.com    env.Depends(hh_file, depends + extra_deps)
99310196SCurtis.Dunham@arm.com
994955SN/A# Generate SimObject Python bindings wrapper files
9952655Sstever@eecs.umich.eduif env['USE_PYTHON']:
9962655Sstever@eecs.umich.edu    for name,simobj in sorted(sim_objects.iteritems()):
9972655Sstever@eecs.umich.edu        py_source = PySource.modules[simobj.__module__]
9982655Sstever@eecs.umich.edu        extra_deps = [ py_source.tnode ]
99910196SCurtis.Dunham@arm.com        cc_file = File('python/_m5/param_%s.cc' % name)
10005601Snate@binkert.org        env.Command(cc_file, Value(name),
10015601Snate@binkert.org                    MakeAction(createSimObjectPyBindWrapper,
100210196SCurtis.Dunham@arm.com                               Transform("SO PyBind")))
100310196SCurtis.Dunham@arm.com        env.Depends(cc_file, depends + extra_deps)
100410196SCurtis.Dunham@arm.com        Source(cc_file)
10055522Snate@binkert.org
10065863Snate@binkert.org# Build all protocol buffers if we have got protoc and protobuf available
10075601Snate@binkert.orgif env['HAVE_PROTOBUF']:
10085601Snate@binkert.org    for proto in ProtoBuf.all:
10095601Snate@binkert.org        # Use both the source and header as the target, and the .proto
10105863Snate@binkert.org        # file as the source. When executing the protoc compiler, also
10119556Sandreas.hansson@arm.com        # specify the proto_path to avoid having the generated files
10129556Sandreas.hansson@arm.com        # include the path.
10139556Sandreas.hansson@arm.com        env.Command([proto.cc_file, proto.hh_file], proto.tnode,
10149556Sandreas.hansson@arm.com                    MakeAction('$PROTOC --cpp_out ${TARGET.dir} '
10159556Sandreas.hansson@arm.com                               '--proto_path ${SOURCE.dir} $SOURCE',
10169556Sandreas.hansson@arm.com                               Transform("PROTOC")))
10179556Sandreas.hansson@arm.com
10189556Sandreas.hansson@arm.com        # Add the C++ source file
10199556Sandreas.hansson@arm.com        Source(proto.cc_file, tags=proto.tags)
10205559Snate@binkert.orgelif ProtoBuf.all:
10219556Sandreas.hansson@arm.com    print('Got protobuf to build, but lacks support!')
10229618Ssteve.reinhardt@amd.com    Exit(1)
10239618Ssteve.reinhardt@amd.com
10249618Ssteve.reinhardt@amd.com#
102510238Sandreas.hansson@arm.com# Handle debug flags
102610238Sandreas.hansson@arm.com#
10279554Sandreas.hansson@arm.comdef makeDebugFlagCC(target, source, env):
10289556Sandreas.hansson@arm.com    assert(len(target) == 1 and len(source) == 1)
10299556Sandreas.hansson@arm.com
10309556Sandreas.hansson@arm.com    code = code_formatter()
10319556Sandreas.hansson@arm.com
10329555Sandreas.hansson@arm.com    # delay definition of CompoundFlags until after all the definition
10339555Sandreas.hansson@arm.com    # of all constituent SimpleFlags
10349556Sandreas.hansson@arm.com    comp_code = code_formatter()
103510457Sandreas.hansson@arm.com
103610457Sandreas.hansson@arm.com    # file header
103710457Sandreas.hansson@arm.com    code('''
103810457Sandreas.hansson@arm.com/*
103910457Sandreas.hansson@arm.com * DO NOT EDIT THIS FILE! Automatically generated by SCons.
104010457Sandreas.hansson@arm.com */
104110457Sandreas.hansson@arm.com
104210457Sandreas.hansson@arm.com#include "base/debug.hh"
104310457Sandreas.hansson@arm.com
10448737Skoansin.tan@gmail.comnamespace Debug {
10459556Sandreas.hansson@arm.com
10469556Sandreas.hansson@arm.com''')
10479556Sandreas.hansson@arm.com
10489554Sandreas.hansson@arm.com    for name, flag in sorted(source[0].read().iteritems()):
104910278SAndreas.Sandberg@ARM.com        n, compound, desc = flag
105010278SAndreas.Sandberg@ARM.com        assert n == name
105110278SAndreas.Sandberg@ARM.com
105210278SAndreas.Sandberg@ARM.com        if not compound:
105310278SAndreas.Sandberg@ARM.com            code('SimpleFlag $name("$name", "$desc");')
105410278SAndreas.Sandberg@ARM.com        else:
105510278SAndreas.Sandberg@ARM.com            comp_code('CompoundFlag $name("$name", "$desc",')
105610278SAndreas.Sandberg@ARM.com            comp_code.indent()
105710457Sandreas.hansson@arm.com            last = len(compound) - 1
105810457Sandreas.hansson@arm.com            for i,flag in enumerate(compound):
105910457Sandreas.hansson@arm.com                if i != last:
106010457Sandreas.hansson@arm.com                    comp_code('&$flag,')
106110457Sandreas.hansson@arm.com                else:
106210457Sandreas.hansson@arm.com                    comp_code('&$flag);')
10638945Ssteve.reinhardt@amd.com            comp_code.dedent()
106410686SAndreas.Sandberg@ARM.com
106510686SAndreas.Sandberg@ARM.com    code.append(comp_code)
106610686SAndreas.Sandberg@ARM.com    code()
106710686SAndreas.Sandberg@ARM.com    code('} // namespace Debug')
106810686SAndreas.Sandberg@ARM.com
106910686SAndreas.Sandberg@ARM.com    code.write(str(target[0]))
10708945Ssteve.reinhardt@amd.com
10716143Snate@binkert.orgdef makeDebugFlagHH(target, source, env):
10726143Snate@binkert.org    assert(len(target) == 1 and len(source) == 1)
10736143Snate@binkert.org
10746143Snate@binkert.org    val = eval(source[0].get_contents())
10756143Snate@binkert.org    name, compound, desc = val
10766143Snate@binkert.org
10776143Snate@binkert.org    code = code_formatter()
10788945Ssteve.reinhardt@amd.com
10798945Ssteve.reinhardt@amd.com    # file header boilerplate
10806143Snate@binkert.org    code('''\
10816143Snate@binkert.org/*
10826143Snate@binkert.org * DO NOT EDIT THIS FILE! Automatically generated by SCons.
10836143Snate@binkert.org */
10846143Snate@binkert.org
10856143Snate@binkert.org#ifndef __DEBUG_${name}_HH__
10866143Snate@binkert.org#define __DEBUG_${name}_HH__
10876143Snate@binkert.org
10886143Snate@binkert.orgnamespace Debug {
10896143Snate@binkert.org''')
10906143Snate@binkert.org
10916143Snate@binkert.org    if compound:
10926143Snate@binkert.org        code('class CompoundFlag;')
109310453SAndrew.Bardsley@arm.com    code('class SimpleFlag;')
109410453SAndrew.Bardsley@arm.com
109510453SAndrew.Bardsley@arm.com    if compound:
109610453SAndrew.Bardsley@arm.com        code('extern CompoundFlag $name;')
109710453SAndrew.Bardsley@arm.com        for flag in compound:
109810453SAndrew.Bardsley@arm.com            code('extern SimpleFlag $flag;')
109910453SAndrew.Bardsley@arm.com    else:
110010453SAndrew.Bardsley@arm.com        code('extern SimpleFlag $name;')
110110453SAndrew.Bardsley@arm.com
11026143Snate@binkert.org    code('''
11036143Snate@binkert.org}
11046143Snate@binkert.org
110510453SAndrew.Bardsley@arm.com#endif // __DEBUG_${name}_HH__
11066143Snate@binkert.org''')
11076240Snate@binkert.org
11085554Snate@binkert.org    code.write(str(target[0]))
11095522Snate@binkert.org
11105522Snate@binkert.orgfor name,flag in sorted(debug_flags.iteritems()):
11115797Snate@binkert.org    n, compound, desc = flag
11125797Snate@binkert.org    assert n == name
11135522Snate@binkert.org
11145601Snate@binkert.org    hh_file = 'debug/%s.hh' % name
11158233Snate@binkert.org    env.Command(hh_file, Value(flag),
11168233Snate@binkert.org                MakeAction(makeDebugFlagHH, Transform("TRACING", 0)))
11178235Snate@binkert.org
11188235Snate@binkert.orgenv.Command('debug/flags.cc', Value(debug_flags),
11198235Snate@binkert.org            MakeAction(makeDebugFlagCC, Transform("TRACING", 0)))
11208235Snate@binkert.orgSource('debug/flags.cc')
11219003SAli.Saidi@ARM.com
11229003SAli.Saidi@ARM.com# version tags
112310196SCurtis.Dunham@arm.comtags = \
112410196SCurtis.Dunham@arm.comenv.Command('sim/tags.cc', None,
11258235Snate@binkert.org            MakeAction('util/cpt_upgrader.py --get-cc-file > $TARGET',
11266143Snate@binkert.org                       Transform("VER TAGS")))
11272655Sstever@eecs.umich.eduenv.AlwaysBuild(tags)
11286143Snate@binkert.org
11296143Snate@binkert.org# Embed python files.  All .py files that have been indicated by a
11308233Snate@binkert.org# PySource() call in a SConscript need to be embedded into the M5
11316143Snate@binkert.org# library.  To do that, we compile the file to byte code, marshal the
11326143Snate@binkert.org# byte code, compress it, and then generate a c++ file that
11334007Ssaidi@eecs.umich.edu# inserts the result into an array.
11344596Sbinkertn@umich.edudef embedPyFile(target, source, env):
11354007Ssaidi@eecs.umich.edu    def c_str(string):
11364596Sbinkertn@umich.edu        if string is None:
11377756SAli.Saidi@ARM.com            return "0"
11387816Ssteve.reinhardt@amd.com        return '"%s"' % string
11398334Snate@binkert.org
11408334Snate@binkert.org    '''Action function to compile a .py into a code object, marshal
11418334Snate@binkert.org    it, compress it, and stick it into an asm file so the code appears
11428334Snate@binkert.org    as just bytes with a label in the data section'''
11435601Snate@binkert.org
114410196SCurtis.Dunham@arm.com    src = file(str(source[0]), 'r').read()
11452655Sstever@eecs.umich.edu
11469225Sandreas.hansson@arm.com    pysource = PySource.tnodes[source[0]]
11479225Sandreas.hansson@arm.com    compiled = compile(src, pysource.abspath, 'exec')
11489226Sandreas.hansson@arm.com    marshalled = marshal.dumps(compiled)
11499226Sandreas.hansson@arm.com    compressed = zlib.compress(marshalled)
11509225Sandreas.hansson@arm.com    data = compressed
11519226Sandreas.hansson@arm.com    sym = pysource.symname
11529226Sandreas.hansson@arm.com
11539226Sandreas.hansson@arm.com    code = code_formatter()
11549226Sandreas.hansson@arm.com    code('''\
11559226Sandreas.hansson@arm.com#include "sim/init.hh"
11569226Sandreas.hansson@arm.com
11579225Sandreas.hansson@arm.comnamespace {
11589227Sandreas.hansson@arm.com
11599227Sandreas.hansson@arm.com''')
11609227Sandreas.hansson@arm.com    blobToCpp(data, 'data_' + sym, code)
11619227Sandreas.hansson@arm.com    code('''\
11628946Sandreas.hansson@arm.com
11633918Ssaidi@eecs.umich.edu
11649225Sandreas.hansson@arm.comEmbeddedPython embedded_${sym}(
11653918Ssaidi@eecs.umich.edu    ${{c_str(pysource.arcname)}},
11669225Sandreas.hansson@arm.com    ${{c_str(pysource.abspath)}},
11679225Sandreas.hansson@arm.com    ${{c_str(pysource.modpath)}},
11689227Sandreas.hansson@arm.com    data_${sym},
11699227Sandreas.hansson@arm.com    ${{len(data)}},
11709227Sandreas.hansson@arm.com    ${{len(marshalled)}});
11719226Sandreas.hansson@arm.com
11729225Sandreas.hansson@arm.com} // anonymous namespace
11739227Sandreas.hansson@arm.com''')
11749227Sandreas.hansson@arm.com    code.write(str(target[0]))
11759227Sandreas.hansson@arm.com
11769227Sandreas.hansson@arm.comfor source in PySource.all:
11778946Sandreas.hansson@arm.com    env.Command(source.cpp, source.tnode,
11789225Sandreas.hansson@arm.com                MakeAction(embedPyFile, Transform("EMBED PY")))
11799226Sandreas.hansson@arm.com    Source(source.cpp, tags=source.tags, add_tags='python')
11809226Sandreas.hansson@arm.com
11819226Sandreas.hansson@arm.com########################################################################
11823515Ssaidi@eecs.umich.edu#
11833918Ssaidi@eecs.umich.edu# Define binaries.  Each different build type (debug, opt, etc.) gets
11844762Snate@binkert.org# a slightly different build environment.
11853515Ssaidi@eecs.umich.edu#
11868881Smarc.orr@gmail.com
11878881Smarc.orr@gmail.com# List of constructed environments to pass back to SConstruct
11888881Smarc.orr@gmail.comdate_source = Source('base/date.cc', tags=[])
11898881Smarc.orr@gmail.com
11908881Smarc.orr@gmail.comgem5_binary = Gem5('gem5')
11919226Sandreas.hansson@arm.com
11929226Sandreas.hansson@arm.com# Function to create a new build environment as clone of current
11939226Sandreas.hansson@arm.com# environment 'env' with modified object suffix and optional stripped
11948881Smarc.orr@gmail.com# binary.  Additional keyword arguments are appended to corresponding
11958881Smarc.orr@gmail.com# build environment vars.
11968881Smarc.orr@gmail.comdef makeEnv(env, label, objsfx, strip=False, disable_partial=False, **kwargs):
11978881Smarc.orr@gmail.com    # SCons doesn't know to append a library suffix when there is a '.' in the
11988881Smarc.orr@gmail.com    # name.  Use '_' instead.
11998881Smarc.orr@gmail.com    libname = 'gem5_' + label
12008881Smarc.orr@gmail.com    secondary_exename = 'm5.' + label
12018881Smarc.orr@gmail.com
12028881Smarc.orr@gmail.com    new_env = env.Clone(OBJSUFFIX=objsfx, SHOBJSUFFIX=objsfx + 's')
12038881Smarc.orr@gmail.com    new_env.Label = label
12048881Smarc.orr@gmail.com    new_env.Append(**kwargs)
12058881Smarc.orr@gmail.com
12068881Smarc.orr@gmail.com    lib_sources = Source.all.with_tag('gem5 lib')
12078881Smarc.orr@gmail.com
12088881Smarc.orr@gmail.com    # Without Python, leave out all Python content from the library
12098881Smarc.orr@gmail.com    # builds.  The option doesn't affect gem5 built as a program
121010196SCurtis.Dunham@arm.com    if GetOption('without_python'):
121110196SCurtis.Dunham@arm.com        lib_sources = lib_sources.without_tag('python')
121210196SCurtis.Dunham@arm.com
121310196SCurtis.Dunham@arm.com    static_objs = []
1214955SN/A    shared_objs = []
121510196SCurtis.Dunham@arm.com
1216955SN/A    for s in lib_sources.with_tag(Source.ungrouped_tag):
121710196SCurtis.Dunham@arm.com        static_objs.append(s.static(new_env))
121810196SCurtis.Dunham@arm.com        shared_objs.append(s.shared(new_env))
121910196SCurtis.Dunham@arm.com
122010196SCurtis.Dunham@arm.com    for group in Source.source_groups:
122110196SCurtis.Dunham@arm.com        srcs = lib_sources.with_tag(Source.link_group_tag(group))
122210196SCurtis.Dunham@arm.com        if not srcs:
122310196SCurtis.Dunham@arm.com            continue
1224955SN/A
122510196SCurtis.Dunham@arm.com        group_static = [ s.static(new_env) for s in srcs ]
122610196SCurtis.Dunham@arm.com        group_shared = [ s.shared(new_env) for s in srcs ]
122710196SCurtis.Dunham@arm.com
122810196SCurtis.Dunham@arm.com        # If partial linking is disabled, add these sources to the build
122910196SCurtis.Dunham@arm.com        # directly, and short circuit this loop.
123010196SCurtis.Dunham@arm.com        if disable_partial:
123110196SCurtis.Dunham@arm.com            static_objs.extend(group_static)
12321869SN/A            shared_objs.extend(group_shared)
123310196SCurtis.Dunham@arm.com            continue
123410196SCurtis.Dunham@arm.com
123510196SCurtis.Dunham@arm.com        # Set up the static partially linked objects.
123610196SCurtis.Dunham@arm.com        file_name = new_env.subst("${OBJPREFIX}lib${OBJSUFFIX}.partial")
123710196SCurtis.Dunham@arm.com        target = File(joinpath(group, file_name))
123810196SCurtis.Dunham@arm.com        partial = env.PartialStatic(target=target, source=group_static)
123910196SCurtis.Dunham@arm.com        static_objs.extend(partial)
12409226Sandreas.hansson@arm.com
124110196SCurtis.Dunham@arm.com        # Set up the shared partially linked objects.
124210196SCurtis.Dunham@arm.com        file_name = new_env.subst("${SHOBJPREFIX}lib${SHOBJSUFFIX}.partial")
124310196SCurtis.Dunham@arm.com        target = File(joinpath(group, file_name))
124410196SCurtis.Dunham@arm.com        partial = env.PartialShared(target=target, source=group_shared)
124510196SCurtis.Dunham@arm.com        shared_objs.extend(partial)
124610196SCurtis.Dunham@arm.com
124710196SCurtis.Dunham@arm.com    static_date = date_source.static(new_env)
124810196SCurtis.Dunham@arm.com    new_env.Depends(static_date, static_objs)
124910196SCurtis.Dunham@arm.com    static_objs.extend(static_date)
125010196SCurtis.Dunham@arm.com
125110196SCurtis.Dunham@arm.com    shared_date = date_source.shared(new_env)
125210196SCurtis.Dunham@arm.com    new_env.Depends(shared_date, shared_objs)
125310196SCurtis.Dunham@arm.com    shared_objs.extend(shared_date)
125410196SCurtis.Dunham@arm.com
125510196SCurtis.Dunham@arm.com    main_objs = [ s.static(new_env) for s in Source.all.with_tag('main') ]
125610196SCurtis.Dunham@arm.com
125710196SCurtis.Dunham@arm.com    # First make a library of everything but main() so other programs can
125810196SCurtis.Dunham@arm.com    # link against m5.
125910196SCurtis.Dunham@arm.com    static_lib = new_env.StaticLibrary(libname, static_objs)
126010196SCurtis.Dunham@arm.com    shared_lib = new_env.SharedLibrary(libname, shared_objs)
126110196SCurtis.Dunham@arm.com
126210196SCurtis.Dunham@arm.com    # Keep track of the object files generated so far so Executables can
126310196SCurtis.Dunham@arm.com    # include them.
126410196SCurtis.Dunham@arm.com    new_env['STATIC_OBJS'] = static_objs
126510196SCurtis.Dunham@arm.com    new_env['SHARED_OBJS'] = shared_objs
126610196SCurtis.Dunham@arm.com    new_env['MAIN_OBJS'] = main_objs
126710196SCurtis.Dunham@arm.com
126810196SCurtis.Dunham@arm.com    new_env['STATIC_LIB'] = static_lib
126910196SCurtis.Dunham@arm.com    new_env['SHARED_LIB'] = shared_lib
127010196SCurtis.Dunham@arm.com
127110196SCurtis.Dunham@arm.com    # Record some settings for building Executables.
127210196SCurtis.Dunham@arm.com    new_env['EXE_SUFFIX'] = label
127310196SCurtis.Dunham@arm.com    new_env['STRIP_EXES'] = strip
127410196SCurtis.Dunham@arm.com
127510196SCurtis.Dunham@arm.com    for cls in ExecutableMeta.all:
127610196SCurtis.Dunham@arm.com        cls.declare_all(new_env)
127710196SCurtis.Dunham@arm.com
127810196SCurtis.Dunham@arm.com    new_env.M5Binary = File(gem5_binary.path(new_env))
127910196SCurtis.Dunham@arm.com
128010196SCurtis.Dunham@arm.com    new_env.Command(secondary_exename, new_env.M5Binary,
128110196SCurtis.Dunham@arm.com            MakeAction('ln $SOURCE $TARGET', Transform("HARDLINK")))
128210196SCurtis.Dunham@arm.com
128310196SCurtis.Dunham@arm.com    # Set up regression tests.
1284    SConscript(os.path.join(env.root.abspath, 'tests', 'SConscript'),
1285               variant_dir=Dir('tests').Dir(new_env.Label),
1286               exports={ 'env' : new_env }, duplicate=False)
1287
1288# Start out with the compiler flags common to all compilers,
1289# i.e. they all use -g for opt and -g -pg for prof
1290ccflags = {'debug' : [], 'opt' : ['-g'], 'fast' : [], 'prof' : ['-g', '-pg'],
1291           'perf' : ['-g']}
1292
1293# Start out with the linker flags common to all linkers, i.e. -pg for
1294# prof, and -lprofiler for perf. The -lprofile flag is surrounded by
1295# no-as-needed and as-needed as the binutils linker is too clever and
1296# simply doesn't link to the library otherwise.
1297ldflags = {'debug' : [], 'opt' : [], 'fast' : [], 'prof' : ['-pg'],
1298           'perf' : ['-Wl,--no-as-needed', '-lprofiler', '-Wl,--as-needed']}
1299
1300# For Link Time Optimization, the optimisation flags used to compile
1301# individual files are decoupled from those used at link time
1302# (i.e. you can compile with -O3 and perform LTO with -O0), so we need
1303# to also update the linker flags based on the target.
1304if env['GCC']:
1305    if sys.platform == 'sunos5':
1306        ccflags['debug'] += ['-gstabs+']
1307    else:
1308        ccflags['debug'] += ['-ggdb3']
1309    ldflags['debug'] += ['-O0']
1310    # opt, fast, prof and perf all share the same cc flags, also add
1311    # the optimization to the ldflags as LTO defers the optimization
1312    # to link time
1313    for target in ['opt', 'fast', 'prof', 'perf']:
1314        ccflags[target] += ['-O3']
1315        ldflags[target] += ['-O3']
1316
1317    ccflags['fast'] += env['LTO_CCFLAGS']
1318    ldflags['fast'] += env['LTO_LDFLAGS']
1319elif env['CLANG']:
1320    ccflags['debug'] += ['-g', '-O0']
1321    # opt, fast, prof and perf all share the same cc flags
1322    for target in ['opt', 'fast', 'prof', 'perf']:
1323        ccflags[target] += ['-O3']
1324else:
1325    print('Unknown compiler, please fix compiler options')
1326    Exit(1)
1327
1328
1329# To speed things up, we only instantiate the build environments we
1330# need.  We try to identify the needed environment for each target; if
1331# we can't, we fall back on instantiating all the environments just to
1332# be safe.
1333target_types = ['debug', 'opt', 'fast', 'prof', 'perf']
1334obj2target = {'do': 'debug', 'o': 'opt', 'fo': 'fast', 'po': 'prof',
1335              'gpo' : 'perf'}
1336
1337def identifyTarget(t):
1338    ext = t.split('.')[-1]
1339    if ext in target_types:
1340        return ext
1341    if obj2target.has_key(ext):
1342        return obj2target[ext]
1343    match = re.search(r'/tests/([^/]+)/', t)
1344    if match and match.group(1) in target_types:
1345        return match.group(1)
1346    return 'all'
1347
1348needed_envs = [identifyTarget(target) for target in BUILD_TARGETS]
1349if 'all' in needed_envs:
1350    needed_envs += target_types
1351
1352disable_partial = False
1353if env['PLATFORM'] == 'darwin':
1354    # Up until Apple LLVM version 10.0.0 (clang-1000.11.45.5), partial
1355    # linked objects do not expose symbols that are marked with the
1356    # hidden visibility and consequently building gem5 on Mac OS
1357    # fails. As a workaround, we disable partial linking, however, we
1358    # may want to revisit in the future.
1359    disable_partial = True
1360
1361# Debug binary
1362if 'debug' in needed_envs:
1363    makeEnv(env, 'debug', '.do',
1364            CCFLAGS = Split(ccflags['debug']),
1365            CPPDEFINES = ['DEBUG', 'TRACING_ON=1'],
1366            LINKFLAGS = Split(ldflags['debug']),
1367            disable_partial=disable_partial)
1368
1369# Optimized binary
1370if 'opt' in needed_envs:
1371    makeEnv(env, 'opt', '.o',
1372            CCFLAGS = Split(ccflags['opt']),
1373            CPPDEFINES = ['TRACING_ON=1'],
1374            LINKFLAGS = Split(ldflags['opt']),
1375            disable_partial=disable_partial)
1376
1377# "Fast" binary
1378if 'fast' in needed_envs:
1379    disable_partial = disable_partial and \
1380            env.get('BROKEN_INCREMENTAL_LTO', False) and \
1381            GetOption('force_lto')
1382    makeEnv(env, 'fast', '.fo', strip = True,
1383            CCFLAGS = Split(ccflags['fast']),
1384            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1385            LINKFLAGS = Split(ldflags['fast']),
1386            disable_partial=disable_partial)
1387
1388# Profiled binary using gprof
1389if 'prof' in needed_envs:
1390    makeEnv(env, 'prof', '.po',
1391            CCFLAGS = Split(ccflags['prof']),
1392            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1393            LINKFLAGS = Split(ldflags['prof']),
1394            disable_partial=disable_partial)
1395
1396# Profiled binary using google-pprof
1397if 'perf' in needed_envs:
1398    makeEnv(env, 'perf', '.gpo',
1399            CCFLAGS = Split(ccflags['perf']),
1400            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1401            LINKFLAGS = Split(ldflags['perf']),
1402            disable_partial=disable_partial)
1403