SConscript revision 13508
1955SN/A# -*- mode:python -*-
2955SN/A
31762SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
4955SN/A# All rights reserved.
5955SN/A#
6955SN/A# Redistribution and use in source and binary forms, with or without
7955SN/A# modification, are permitted provided that the following conditions are
8955SN/A# met: redistributions of source code must retain the above copyright
9955SN/A# notice, this list of conditions and the following disclaimer;
10955SN/A# redistributions in binary form must reproduce the above copyright
11955SN/A# notice, this list of conditions and the following disclaimer in the
12955SN/A# documentation and/or other materials provided with the distribution;
13955SN/A# neither the name of the copyright holders nor the names of its
14955SN/A# contributors may be used to endorse or promote products derived from
15955SN/A# this software without specific prior written permission.
16955SN/A#
17955SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18955SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22955SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23955SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24955SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26955SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27955SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
282665Ssaidi@eecs.umich.edu#
294762Snate@binkert.org# Authors: Nathan Binkert
30955SN/A
3112563Sgabeblack@google.comfrom __future__ import print_function
3212563Sgabeblack@google.com
335522Snate@binkert.orgimport array
346143Snate@binkert.orgimport bisect
3512371Sgabeblack@google.comimport functools
364762Snate@binkert.orgimport imp
375522Snate@binkert.orgimport marshal
38955SN/Aimport os
395522Snate@binkert.orgimport re
4011974Sgabeblack@google.comimport subprocess
41955SN/Aimport sys
425522Snate@binkert.orgimport zlib
434202Sbinkertn@umich.edu
445742Snate@binkert.orgfrom os.path import basename, dirname, exists, isdir, isfile, join as joinpath
45955SN/A
464381Sbinkertn@umich.eduimport SCons
474381Sbinkertn@umich.edu
4812246Sgabeblack@google.comfrom gem5_scons import Transform
4912246Sgabeblack@google.com
508334Snate@binkert.org# This file defines how to build a particular configuration of gem5
51955SN/A# based on variable settings in the 'env' build environment.
52955SN/A
534202Sbinkertn@umich.eduImport('*')
54955SN/A
554382Sbinkertn@umich.edu# Children need to see the environment
564382Sbinkertn@umich.eduExport('env')
574382Sbinkertn@umich.edu
586654Snate@binkert.orgbuild_env = [(opt, env[opt]) for opt in export_vars]
595517Snate@binkert.org
608614Sgblack@eecs.umich.edufrom m5.util import code_formatter, compareVersions
617674Snate@binkert.org
626143Snate@binkert.org########################################################################
636143Snate@binkert.org# Code for adding source files of various types
646143Snate@binkert.org#
6512302Sgabeblack@google.com# When specifying a source file of some type, a set of tags can be
6612302Sgabeblack@google.com# specified for that file.
6712302Sgabeblack@google.com
6812371Sgabeblack@google.comclass SourceFilter(object):
6912371Sgabeblack@google.com    def __init__(self, predicate):
7012371Sgabeblack@google.com        self.predicate = predicate
7112371Sgabeblack@google.com
7212371Sgabeblack@google.com    def __or__(self, other):
7312371Sgabeblack@google.com        return SourceFilter(lambda tags: self.predicate(tags) or
7412371Sgabeblack@google.com                                         other.predicate(tags))
7512371Sgabeblack@google.com
7612371Sgabeblack@google.com    def __and__(self, other):
7712371Sgabeblack@google.com        return SourceFilter(lambda tags: self.predicate(tags) and
7812371Sgabeblack@google.com                                         other.predicate(tags))
7912371Sgabeblack@google.com
8012371Sgabeblack@google.comdef with_tags_that(predicate):
8112371Sgabeblack@google.com    '''Return a list of sources with tags that satisfy a predicate.'''
8212371Sgabeblack@google.com    return SourceFilter(predicate)
8312371Sgabeblack@google.com
8412371Sgabeblack@google.comdef with_any_tags(*tags):
8512371Sgabeblack@google.com    '''Return a list of sources with any of the supplied tags.'''
8612371Sgabeblack@google.com    return SourceFilter(lambda stags: len(set(tags) & stags) > 0)
8712371Sgabeblack@google.com
8812371Sgabeblack@google.comdef with_all_tags(*tags):
8912371Sgabeblack@google.com    '''Return a list of sources with all of the supplied tags.'''
9012371Sgabeblack@google.com    return SourceFilter(lambda stags: set(tags) <= stags)
9112371Sgabeblack@google.com
9212371Sgabeblack@google.comdef with_tag(tag):
9312371Sgabeblack@google.com    '''Return a list of sources with the supplied tag.'''
9412371Sgabeblack@google.com    return SourceFilter(lambda stags: tag in stags)
9512371Sgabeblack@google.com
9612371Sgabeblack@google.comdef without_tags(*tags):
9712371Sgabeblack@google.com    '''Return a list of sources without any of the supplied tags.'''
9812371Sgabeblack@google.com    return SourceFilter(lambda stags: len(set(tags) & stags) == 0)
9912371Sgabeblack@google.com
10012371Sgabeblack@google.comdef without_tag(tag):
10112371Sgabeblack@google.com    '''Return a list of sources with the supplied tag.'''
10212371Sgabeblack@google.com    return SourceFilter(lambda stags: tag not in stags)
10312371Sgabeblack@google.com
10412371Sgabeblack@google.comsource_filter_factories = {
10512371Sgabeblack@google.com    'with_tags_that': with_tags_that,
10612371Sgabeblack@google.com    'with_any_tags': with_any_tags,
10712371Sgabeblack@google.com    'with_all_tags': with_all_tags,
10812371Sgabeblack@google.com    'with_tag': with_tag,
10912371Sgabeblack@google.com    'without_tags': without_tags,
11012371Sgabeblack@google.com    'without_tag': without_tag,
11112371Sgabeblack@google.com}
11212371Sgabeblack@google.com
11312371Sgabeblack@google.comExport(source_filter_factories)
11412371Sgabeblack@google.com
11512302Sgabeblack@google.comclass SourceList(list):
11612371Sgabeblack@google.com    def apply_filter(self, f):
11712302Sgabeblack@google.com        def match(source):
11812371Sgabeblack@google.com            return f.predicate(source.tags)
11912302Sgabeblack@google.com        return SourceList(filter(match, self))
12012302Sgabeblack@google.com
12112371Sgabeblack@google.com    def __getattr__(self, name):
12212371Sgabeblack@google.com        func = source_filter_factories.get(name, None)
12312371Sgabeblack@google.com        if not func:
12412371Sgabeblack@google.com            raise AttributeError
12512302Sgabeblack@google.com
12612371Sgabeblack@google.com        @functools.wraps(func)
12712371Sgabeblack@google.com        def wrapper(*args, **kwargs):
12812371Sgabeblack@google.com            return self.apply_filter(func(*args, **kwargs))
12912371Sgabeblack@google.com        return wrapper
13011983Sgabeblack@google.com
1316143Snate@binkert.orgclass SourceMeta(type):
1328233Snate@binkert.org    '''Meta class for source files that keeps track of all files of a
13312302Sgabeblack@google.com    particular type.'''
1346143Snate@binkert.org    def __init__(cls, name, bases, dict):
1356143Snate@binkert.org        super(SourceMeta, cls).__init__(name, bases, dict)
13612302Sgabeblack@google.com        cls.all = SourceList()
1374762Snate@binkert.org
1386143Snate@binkert.orgclass SourceFile(object):
1398233Snate@binkert.org    '''Base object that encapsulates the notion of a source file.
1408233Snate@binkert.org    This includes, the source node, target node, various manipulations
14112302Sgabeblack@google.com    of those.  A source file also specifies a set of tags which
14212302Sgabeblack@google.com    describing arbitrary properties of the source file.'''
1436143Snate@binkert.org    __metaclass__ = SourceMeta
14412362Sgabeblack@google.com
14512362Sgabeblack@google.com    static_objs = {}
14612362Sgabeblack@google.com    shared_objs = {}
14712362Sgabeblack@google.com
14812302Sgabeblack@google.com    def __init__(self, source, tags=None, add_tags=None):
14912302Sgabeblack@google.com        if tags is None:
15012302Sgabeblack@google.com            tags='gem5 lib'
15112302Sgabeblack@google.com        if isinstance(tags, basestring):
15212302Sgabeblack@google.com            tags = set([tags])
15312363Sgabeblack@google.com        if not isinstance(tags, set):
15412363Sgabeblack@google.com            tags = set(tags)
15512363Sgabeblack@google.com        self.tags = tags
15612363Sgabeblack@google.com
15712302Sgabeblack@google.com        if add_tags:
15812363Sgabeblack@google.com            if isinstance(add_tags, basestring):
15912363Sgabeblack@google.com                add_tags = set([add_tags])
16012363Sgabeblack@google.com            if not isinstance(add_tags, set):
16112363Sgabeblack@google.com                add_tags = set(add_tags)
16212363Sgabeblack@google.com            self.tags |= add_tags
1638233Snate@binkert.org
1646143Snate@binkert.org        tnode = source
1656143Snate@binkert.org        if not isinstance(source, SCons.Node.FS.File):
1666143Snate@binkert.org            tnode = File(source)
1676143Snate@binkert.org
1686143Snate@binkert.org        self.tnode = tnode
1696143Snate@binkert.org        self.snode = tnode.srcnode()
1706143Snate@binkert.org
1716143Snate@binkert.org        for base in type(self).__mro__:
1726143Snate@binkert.org            if issubclass(base, SourceFile):
1737065Snate@binkert.org                base.all.append(self)
1746143Snate@binkert.org
17512362Sgabeblack@google.com    def static(self, env):
17612362Sgabeblack@google.com        key = (self.tnode, env['OBJSUFFIX'])
17712362Sgabeblack@google.com        if not key in self.static_objs:
17812362Sgabeblack@google.com            self.static_objs[key] = env.StaticObject(self.tnode)
17912362Sgabeblack@google.com        return self.static_objs[key]
18012362Sgabeblack@google.com
18112362Sgabeblack@google.com    def shared(self, env):
18212362Sgabeblack@google.com        key = (self.tnode, env['OBJSUFFIX'])
18312362Sgabeblack@google.com        if not key in self.shared_objs:
18412362Sgabeblack@google.com            self.shared_objs[key] = env.SharedObject(self.tnode)
18512362Sgabeblack@google.com        return self.shared_objs[key]
18612362Sgabeblack@google.com
1878233Snate@binkert.org    @property
1888233Snate@binkert.org    def filename(self):
1898233Snate@binkert.org        return str(self.tnode)
1908233Snate@binkert.org
1918233Snate@binkert.org    @property
1928233Snate@binkert.org    def dirname(self):
1938233Snate@binkert.org        return dirname(self.filename)
1948233Snate@binkert.org
1958233Snate@binkert.org    @property
1968233Snate@binkert.org    def basename(self):
1978233Snate@binkert.org        return basename(self.filename)
1988233Snate@binkert.org
1998233Snate@binkert.org    @property
2008233Snate@binkert.org    def extname(self):
2018233Snate@binkert.org        index = self.basename.rfind('.')
2028233Snate@binkert.org        if index <= 0:
2038233Snate@binkert.org            # dot files aren't extensions
2048233Snate@binkert.org            return self.basename, None
2058233Snate@binkert.org
2068233Snate@binkert.org        return self.basename[:index], self.basename[index+1:]
2078233Snate@binkert.org
2086143Snate@binkert.org    def __lt__(self, other): return self.filename < other.filename
2096143Snate@binkert.org    def __le__(self, other): return self.filename <= other.filename
2106143Snate@binkert.org    def __gt__(self, other): return self.filename > other.filename
2116143Snate@binkert.org    def __ge__(self, other): return self.filename >= other.filename
2126143Snate@binkert.org    def __eq__(self, other): return self.filename == other.filename
2136143Snate@binkert.org    def __ne__(self, other): return self.filename != other.filename
2149982Satgutier@umich.edu
2156143Snate@binkert.orgclass Source(SourceFile):
21612302Sgabeblack@google.com    ungrouped_tag = 'No link group'
21712302Sgabeblack@google.com    source_groups = set()
21812302Sgabeblack@google.com
21912302Sgabeblack@google.com    _current_group_tag = ungrouped_tag
22012302Sgabeblack@google.com
22112302Sgabeblack@google.com    @staticmethod
22212302Sgabeblack@google.com    def link_group_tag(group):
22312302Sgabeblack@google.com        return 'link group: %s' % group
22411983Sgabeblack@google.com
22511983Sgabeblack@google.com    @classmethod
22611983Sgabeblack@google.com    def set_group(cls, group):
22712302Sgabeblack@google.com        new_tag = Source.link_group_tag(group)
22812302Sgabeblack@google.com        Source._current_group_tag = new_tag
22912302Sgabeblack@google.com        Source.source_groups.add(group)
23012302Sgabeblack@google.com
23112302Sgabeblack@google.com    def _add_link_group_tag(self):
23212302Sgabeblack@google.com        self.tags.add(Source._current_group_tag)
23311983Sgabeblack@google.com
2346143Snate@binkert.org    '''Add a c/c++ source file to the build'''
23512305Sgabeblack@google.com    def __init__(self, source, tags=None, add_tags=None):
23612302Sgabeblack@google.com        '''specify the source file, and any tags'''
23712302Sgabeblack@google.com        super(Source, self).__init__(source, tags, add_tags)
23812302Sgabeblack@google.com        self._add_link_group_tag()
2396143Snate@binkert.org
2406143Snate@binkert.orgclass PySource(SourceFile):
2416143Snate@binkert.org    '''Add a python source file to the named package'''
2425522Snate@binkert.org    invalid_sym_char = re.compile('[^A-z0-9_]')
2436143Snate@binkert.org    modules = {}
2446143Snate@binkert.org    tnodes = {}
2456143Snate@binkert.org    symnames = {}
2469982Satgutier@umich.edu
24712302Sgabeblack@google.com    def __init__(self, package, source, tags=None, add_tags=None):
24812302Sgabeblack@google.com        '''specify the python package, the source file, and any tags'''
24912302Sgabeblack@google.com        super(PySource, self).__init__(source, tags, add_tags)
2506143Snate@binkert.org
2516143Snate@binkert.org        modname,ext = self.extname
2526143Snate@binkert.org        assert ext == 'py'
2536143Snate@binkert.org
2545522Snate@binkert.org        if package:
2555522Snate@binkert.org            path = package.split('.')
2565522Snate@binkert.org        else:
2575522Snate@binkert.org            path = []
2585604Snate@binkert.org
2595604Snate@binkert.org        modpath = path[:]
2606143Snate@binkert.org        if modname != '__init__':
2616143Snate@binkert.org            modpath += [ modname ]
2624762Snate@binkert.org        modpath = '.'.join(modpath)
2634762Snate@binkert.org
2646143Snate@binkert.org        arcpath = path + [ self.basename ]
2656727Ssteve.reinhardt@amd.com        abspath = self.snode.abspath
2666727Ssteve.reinhardt@amd.com        if not exists(abspath):
2676727Ssteve.reinhardt@amd.com            abspath = self.tnode.abspath
2684762Snate@binkert.org
2696143Snate@binkert.org        self.package = package
2706143Snate@binkert.org        self.modname = modname
2716143Snate@binkert.org        self.modpath = modpath
2726143Snate@binkert.org        self.arcname = joinpath(*arcpath)
2736727Ssteve.reinhardt@amd.com        self.abspath = abspath
2746143Snate@binkert.org        self.compiled = File(self.filename + 'c')
2757674Snate@binkert.org        self.cpp = File(self.filename + '.cc')
2767674Snate@binkert.org        self.symname = PySource.invalid_sym_char.sub('_', modpath)
2775604Snate@binkert.org
2786143Snate@binkert.org        PySource.modules[modpath] = self
2796143Snate@binkert.org        PySource.tnodes[self.tnode] = self
2806143Snate@binkert.org        PySource.symnames[self.symname] = self
2814762Snate@binkert.org
2826143Snate@binkert.orgclass SimObject(PySource):
2834762Snate@binkert.org    '''Add a SimObject python file as a python source object and add
2844762Snate@binkert.org    it to a list of sim object modules'''
2854762Snate@binkert.org
2866143Snate@binkert.org    fixed = False
2876143Snate@binkert.org    modnames = []
2884762Snate@binkert.org
28912302Sgabeblack@google.com    def __init__(self, source, tags=None, add_tags=None):
29012302Sgabeblack@google.com        '''Specify the source file and any tags (automatically in
2918233Snate@binkert.org        the m5.objects package)'''
29212302Sgabeblack@google.com        super(SimObject, self).__init__('m5.objects', source, tags, add_tags)
2936143Snate@binkert.org        if self.fixed:
2946143Snate@binkert.org            raise AttributeError, "Too late to call SimObject now."
2954762Snate@binkert.org
2966143Snate@binkert.org        bisect.insort_right(SimObject.modnames, self.modname)
2974762Snate@binkert.org
2989396Sandreas.hansson@arm.comclass ProtoBuf(SourceFile):
2999396Sandreas.hansson@arm.com    '''Add a Protocol Buffer to build'''
3009396Sandreas.hansson@arm.com
30112302Sgabeblack@google.com    def __init__(self, source, tags=None, add_tags=None):
30212302Sgabeblack@google.com        '''Specify the source file, and any tags'''
30312302Sgabeblack@google.com        super(ProtoBuf, self).__init__(source, tags, add_tags)
3049396Sandreas.hansson@arm.com
3059396Sandreas.hansson@arm.com        # Get the file name and the extension
3069396Sandreas.hansson@arm.com        modname,ext = self.extname
3079396Sandreas.hansson@arm.com        assert ext == 'proto'
3089396Sandreas.hansson@arm.com
3099396Sandreas.hansson@arm.com        # Currently, we stick to generating the C++ headers, so we
3109396Sandreas.hansson@arm.com        # only need to track the source and header.
3119930Sandreas.hansson@arm.com        self.cc_file = File(modname + '.pb.cc')
3129930Sandreas.hansson@arm.com        self.hh_file = File(modname + '.pb.h')
3139396Sandreas.hansson@arm.com
3146143Snate@binkert.org
31512797Sgabeblack@google.comexectuable_classes = []
31612797Sgabeblack@google.comclass ExecutableMeta(type):
31712797Sgabeblack@google.com    '''Meta class for Executables.'''
3188235Snate@binkert.org    all = []
31912797Sgabeblack@google.com
32012797Sgabeblack@google.com    def __init__(cls, name, bases, d):
32112797Sgabeblack@google.com        if not d.pop('abstract', False):
32212797Sgabeblack@google.com            ExecutableMeta.all.append(cls)
32312797Sgabeblack@google.com        super(ExecutableMeta, cls).__init__(name, bases, d)
32412797Sgabeblack@google.com
32512797Sgabeblack@google.com        cls.all = []
32612797Sgabeblack@google.com
32712797Sgabeblack@google.comclass Executable(object):
32812797Sgabeblack@google.com    '''Base class for creating an executable from sources.'''
32912797Sgabeblack@google.com    __metaclass__ = ExecutableMeta
33012797Sgabeblack@google.com
33112797Sgabeblack@google.com    abstract = True
33212797Sgabeblack@google.com
33312797Sgabeblack@google.com    def __init__(self, target, *srcs_and_filts):
33412757Sgabeblack@google.com        '''Specify the target name and any sources. Sources that are
33512757Sgabeblack@google.com        not SourceFiles are evalued with Source().'''
33612797Sgabeblack@google.com        super(Executable, self).__init__()
33712797Sgabeblack@google.com        self.all.append(self)
33812797Sgabeblack@google.com        self.target = target
33912757Sgabeblack@google.com
34012757Sgabeblack@google.com        isFilter = lambda arg: isinstance(arg, SourceFilter)
34112757Sgabeblack@google.com        self.filters = filter(isFilter, srcs_and_filts)
34212757Sgabeblack@google.com        sources = filter(lambda a: not isFilter(a), srcs_and_filts)
3438235Snate@binkert.org
34412302Sgabeblack@google.com        srcs = SourceList()
3458235Snate@binkert.org        for src in sources:
3468235Snate@binkert.org            if not isinstance(src, SourceFile):
34712757Sgabeblack@google.com                src = Source(src, tags=[])
3488235Snate@binkert.org            srcs.append(src)
3498235Snate@binkert.org
3508235Snate@binkert.org        self.sources = srcs
35112757Sgabeblack@google.com        self.dir = Dir('.')
35212313Sgabeblack@google.com
35312797Sgabeblack@google.com    def path(self, env):
35412797Sgabeblack@google.com        return self.dir.File(self.target + '.' + env['EXE_SUFFIX'])
35512797Sgabeblack@google.com
35612797Sgabeblack@google.com    def srcs_to_objs(self, env, sources):
35712797Sgabeblack@google.com        return list([ s.static(env) for s in sources ])
35812797Sgabeblack@google.com
35912797Sgabeblack@google.com    @classmethod
36012797Sgabeblack@google.com    def declare_all(cls, env):
36112797Sgabeblack@google.com        return list([ instance.declare(env) for instance in cls.all ])
36212797Sgabeblack@google.com
36312797Sgabeblack@google.com    def declare(self, env, objs=None):
36412797Sgabeblack@google.com        if objs is None:
36512797Sgabeblack@google.com            objs = self.srcs_to_objs(env, self.sources)
36612797Sgabeblack@google.com
36712797Sgabeblack@google.com        if env['STRIP_EXES']:
36812797Sgabeblack@google.com            stripped = self.path(env)
36912797Sgabeblack@google.com            unstripped = env.File(str(stripped) + '.unstripped')
37012797Sgabeblack@google.com            if sys.platform == 'sunos5':
37112797Sgabeblack@google.com                cmd = 'cp $SOURCE $TARGET; strip $TARGET'
37212797Sgabeblack@google.com            else:
37312797Sgabeblack@google.com                cmd = 'strip $SOURCE -o $TARGET'
37412797Sgabeblack@google.com            env.Program(unstripped, objs)
37512797Sgabeblack@google.com            return env.Command(stripped, unstripped,
37612797Sgabeblack@google.com                               MakeAction(cmd, Transform("STRIP")))
37712797Sgabeblack@google.com        else:
37812797Sgabeblack@google.com            return env.Program(self.path(env), objs)
37912797Sgabeblack@google.com
38012797Sgabeblack@google.comclass UnitTest(Executable):
38112797Sgabeblack@google.com    '''Create a UnitTest'''
38212797Sgabeblack@google.com    def __init__(self, target, *srcs_and_filts, **kwargs):
38312797Sgabeblack@google.com        super(UnitTest, self).__init__(target, *srcs_and_filts)
38412797Sgabeblack@google.com
38512797Sgabeblack@google.com        self.main = kwargs.get('main', False)
38612797Sgabeblack@google.com
38712797Sgabeblack@google.com    def declare(self, env):
38812797Sgabeblack@google.com        sources = list(self.sources)
38912797Sgabeblack@google.com        for f in self.filters:
39012797Sgabeblack@google.com            sources = Source.all.apply_filter(f)
39112797Sgabeblack@google.com        objs = self.srcs_to_objs(env, sources) + env['STATIC_OBJS']
39212797Sgabeblack@google.com        if self.main:
39312797Sgabeblack@google.com            objs += env['MAIN_OBJS']
39412797Sgabeblack@google.com        return super(UnitTest, self).declare(env, objs)
39512797Sgabeblack@google.com
39612797Sgabeblack@google.comclass GTest(Executable):
39712313Sgabeblack@google.com    '''Create a unit test based on the google test framework.'''
39812313Sgabeblack@google.com    all = []
39912797Sgabeblack@google.com    def __init__(self, *srcs_and_filts, **kwargs):
40012797Sgabeblack@google.com        super(GTest, self).__init__(*srcs_and_filts)
40112797Sgabeblack@google.com
40212371Sgabeblack@google.com        self.skip_lib = kwargs.pop('skip_lib', False)
4035584Snate@binkert.org
40412797Sgabeblack@google.com    @classmethod
40512797Sgabeblack@google.com    def declare_all(cls, env):
40612797Sgabeblack@google.com        env = env.Clone()
40712797Sgabeblack@google.com        env.Append(LIBS=env['GTEST_LIBS'])
40812797Sgabeblack@google.com        env.Append(CPPFLAGS=env['GTEST_CPPFLAGS'])
40912797Sgabeblack@google.com        env['GTEST_LIB_SOURCES'] = Source.all.with_tag('gtest lib')
41012797Sgabeblack@google.com        env['GTEST_OUT_DIR'] = \
41112797Sgabeblack@google.com            Dir(env['BUILDDIR']).Dir('unittests.' + env['EXE_SUFFIX'])
41212797Sgabeblack@google.com        return super(GTest, cls).declare_all(env)
41312797Sgabeblack@google.com
41412797Sgabeblack@google.com    def declare(self, env):
41512797Sgabeblack@google.com        sources = list(self.sources)
41612797Sgabeblack@google.com        if not self.skip_lib:
41712797Sgabeblack@google.com            sources += env['GTEST_LIB_SOURCES']
41812797Sgabeblack@google.com        for f in self.filters:
41912797Sgabeblack@google.com            sources += Source.all.apply_filter(f)
42012797Sgabeblack@google.com        objs = self.srcs_to_objs(env, sources)
42112797Sgabeblack@google.com
42212797Sgabeblack@google.com        binary = super(GTest, self).declare(env, objs)
42312797Sgabeblack@google.com
42412797Sgabeblack@google.com        out_dir = env['GTEST_OUT_DIR']
42512797Sgabeblack@google.com        xml_file = out_dir.Dir(str(self.dir)).File(self.target + '.xml')
42612797Sgabeblack@google.com        AlwaysBuild(env.Command(xml_file, binary,
42712797Sgabeblack@google.com            "${SOURCES[0]} --gtest_output=xml:${TARGETS[0]}"))
42812797Sgabeblack@google.com
42912797Sgabeblack@google.com        return binary
43012797Sgabeblack@google.com
43112797Sgabeblack@google.comclass Gem5(Executable):
43212797Sgabeblack@google.com    '''Create a gem5 executable.'''
43312797Sgabeblack@google.com
43412797Sgabeblack@google.com    def __init__(self, target):
43512797Sgabeblack@google.com        super(Gem5, self).__init__(target)
43612797Sgabeblack@google.com
43712797Sgabeblack@google.com    def declare(self, env):
43812797Sgabeblack@google.com        objs = env['MAIN_OBJS'] + env['STATIC_OBJS']
43912797Sgabeblack@google.com        return super(Gem5, self).declare(env, objs)
44012797Sgabeblack@google.com
44112797Sgabeblack@google.com
4424382Sbinkertn@umich.edu# Children should have access
4434202Sbinkertn@umich.eduExport('Source')
4444382Sbinkertn@umich.eduExport('PySource')
4454382Sbinkertn@umich.eduExport('SimObject')
4469396Sandreas.hansson@arm.comExport('ProtoBuf')
44712797Sgabeblack@google.comExport('Executable')
4485584Snate@binkert.orgExport('UnitTest')
44912313Sgabeblack@google.comExport('GTest')
4504382Sbinkertn@umich.edu
4514382Sbinkertn@umich.edu########################################################################
4524382Sbinkertn@umich.edu#
4538232Snate@binkert.org# Debug Flags
4545192Ssaidi@eecs.umich.edu#
4558232Snate@binkert.orgdebug_flags = {}
4568232Snate@binkert.orgdef DebugFlag(name, desc=None):
4578232Snate@binkert.org    if name in debug_flags:
4585192Ssaidi@eecs.umich.edu        raise AttributeError, "Flag %s already specified" % name
4598232Snate@binkert.org    debug_flags[name] = (name, (), desc)
4605192Ssaidi@eecs.umich.edu
4615799Snate@binkert.orgdef CompoundFlag(name, flags, desc=None):
4628232Snate@binkert.org    if name in debug_flags:
4635192Ssaidi@eecs.umich.edu        raise AttributeError, "Flag %s already specified" % name
4645192Ssaidi@eecs.umich.edu
4655192Ssaidi@eecs.umich.edu    compound = tuple(flags)
4668232Snate@binkert.org    debug_flags[name] = (name, compound, desc)
4675192Ssaidi@eecs.umich.edu
4688232Snate@binkert.orgExport('DebugFlag')
4695192Ssaidi@eecs.umich.eduExport('CompoundFlag')
4705192Ssaidi@eecs.umich.edu
4715192Ssaidi@eecs.umich.edu########################################################################
4725192Ssaidi@eecs.umich.edu#
4734382Sbinkertn@umich.edu# Set some compiler variables
4744382Sbinkertn@umich.edu#
4754382Sbinkertn@umich.edu
4762667Sstever@eecs.umich.edu# Include file paths are rooted in this directory.  SCons will
4772667Sstever@eecs.umich.edu# automatically expand '.' to refer to both the source directory and
4782667Sstever@eecs.umich.edu# the corresponding build directory to pick up generated include
4792667Sstever@eecs.umich.edu# files.
4802667Sstever@eecs.umich.eduenv.Append(CPPPATH=Dir('.'))
4812667Sstever@eecs.umich.edu
4825742Snate@binkert.orgfor extra_dir in extras_dir_list:
4835742Snate@binkert.org    env.Append(CPPPATH=Dir(extra_dir))
4845742Snate@binkert.org
4855793Snate@binkert.org# Workaround for bug in SCons version > 0.97d20071212
4868334Snate@binkert.org# Scons bug id: 2006 gem5 Bug id: 308
4875793Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
4885793Snate@binkert.org    Dir(root[len(base_dir) + 1:])
4895793Snate@binkert.org
4904382Sbinkertn@umich.edu########################################################################
4914762Snate@binkert.org#
4925344Sstever@gmail.com# Walk the tree and execute all SConscripts in subdirectories
4934382Sbinkertn@umich.edu#
4945341Sstever@gmail.com
4955742Snate@binkert.orghere = Dir('.').srcnode().abspath
4965742Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
4975742Snate@binkert.org    if root == here:
4985742Snate@binkert.org        # we don't want to recurse back into this SConscript
4995742Snate@binkert.org        continue
5004762Snate@binkert.org
5015742Snate@binkert.org    if 'SConscript' in files:
5025742Snate@binkert.org        build_dir = joinpath(env['BUILDDIR'], root[len(base_dir) + 1:])
50311984Sgabeblack@google.com        Source.set_group(build_dir)
5047722Sgblack@eecs.umich.edu        SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
5055742Snate@binkert.org
5065742Snate@binkert.orgfor extra_dir in extras_dir_list:
5075742Snate@binkert.org    prefix_len = len(dirname(extra_dir)) + 1
5089930Sandreas.hansson@arm.com
5099930Sandreas.hansson@arm.com    # Also add the corresponding build directory to pick up generated
5109930Sandreas.hansson@arm.com    # include files.
5119930Sandreas.hansson@arm.com    env.Append(CPPPATH=Dir(joinpath(env['BUILDDIR'], extra_dir[prefix_len:])))
5129930Sandreas.hansson@arm.com
5135742Snate@binkert.org    for root, dirs, files in os.walk(extra_dir, topdown=True):
5148242Sbradley.danofsky@amd.com        # if build lives in the extras directory, don't walk down it
5158242Sbradley.danofsky@amd.com        if 'build' in dirs:
5168242Sbradley.danofsky@amd.com            dirs.remove('build')
5178242Sbradley.danofsky@amd.com
5185341Sstever@gmail.com        if 'SConscript' in files:
5195742Snate@binkert.org            build_dir = joinpath(env['BUILDDIR'], root[prefix_len:])
5207722Sgblack@eecs.umich.edu            SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
5214773Snate@binkert.org
5226108Snate@binkert.orgfor opt in export_vars:
5231858SN/A    env.ConfigFile(opt)
5241085SN/A
5256658Snate@binkert.orgdef makeTheISA(source, target, env):
5266658Snate@binkert.org    isas = [ src.get_contents() for src in source ]
5277673Snate@binkert.org    target_isa = env['TARGET_ISA']
5286658Snate@binkert.org    def define(isa):
5296658Snate@binkert.org        return isa.upper() + '_ISA'
53011308Santhony.gutierrez@amd.com
5316658Snate@binkert.org    def namespace(isa):
53211308Santhony.gutierrez@amd.com        return isa[0].upper() + isa[1:].lower() + 'ISA'
5336658Snate@binkert.org
5346658Snate@binkert.org
5357673Snate@binkert.org    code = code_formatter()
5367673Snate@binkert.org    code('''\
5377673Snate@binkert.org#ifndef __CONFIG_THE_ISA_HH__
5387673Snate@binkert.org#define __CONFIG_THE_ISA_HH__
5397673Snate@binkert.org
5407673Snate@binkert.org''')
5417673Snate@binkert.org
54210467Sandreas.hansson@arm.com    # create defines for the preprocessing and compile-time determination
5436658Snate@binkert.org    for i,isa in enumerate(isas):
5447673Snate@binkert.org        code('#define $0 $1', define(isa), i + 1)
54510467Sandreas.hansson@arm.com    code()
54610467Sandreas.hansson@arm.com
54710467Sandreas.hansson@arm.com    # create an enum for any run-time determination of the ISA, we
54810467Sandreas.hansson@arm.com    # reuse the same name as the namespaces
54910467Sandreas.hansson@arm.com    code('enum class Arch {')
55010467Sandreas.hansson@arm.com    for i,isa in enumerate(isas):
55110467Sandreas.hansson@arm.com        if i + 1 == len(isas):
55210467Sandreas.hansson@arm.com            code('  $0 = $1', namespace(isa), define(isa))
55310467Sandreas.hansson@arm.com        else:
55410467Sandreas.hansson@arm.com            code('  $0 = $1,', namespace(isa), define(isa))
55510467Sandreas.hansson@arm.com    code('};')
5567673Snate@binkert.org
5577673Snate@binkert.org    code('''
5587673Snate@binkert.org
5597673Snate@binkert.org#define THE_ISA ${{define(target_isa)}}
5607673Snate@binkert.org#define TheISA ${{namespace(target_isa)}}
5619048SAli.Saidi@ARM.com#define THE_ISA_STR "${{target_isa}}"
5627673Snate@binkert.org
5637673Snate@binkert.org#endif // __CONFIG_THE_ISA_HH__''')
5647673Snate@binkert.org
5657673Snate@binkert.org    code.write(str(target[0]))
5666658Snate@binkert.org
5677756SAli.Saidi@ARM.comenv.Command('config/the_isa.hh', map(Value, all_isa_list),
5687816Ssteve.reinhardt@amd.com            MakeAction(makeTheISA, Transform("CFG ISA", 0)))
5696658Snate@binkert.org
57011308Santhony.gutierrez@amd.comdef makeTheGPUISA(source, target, env):
57111308Santhony.gutierrez@amd.com    isas = [ src.get_contents() for src in source ]
57211308Santhony.gutierrez@amd.com    target_gpu_isa = env['TARGET_GPU_ISA']
57311308Santhony.gutierrez@amd.com    def define(isa):
57411308Santhony.gutierrez@amd.com        return isa.upper() + '_ISA'
57511308Santhony.gutierrez@amd.com
57611308Santhony.gutierrez@amd.com    def namespace(isa):
57711308Santhony.gutierrez@amd.com        return isa[0].upper() + isa[1:].lower() + 'ISA'
57811308Santhony.gutierrez@amd.com
57911308Santhony.gutierrez@amd.com
58011308Santhony.gutierrez@amd.com    code = code_formatter()
58111308Santhony.gutierrez@amd.com    code('''\
58211308Santhony.gutierrez@amd.com#ifndef __CONFIG_THE_GPU_ISA_HH__
58311308Santhony.gutierrez@amd.com#define __CONFIG_THE_GPU_ISA_HH__
58411308Santhony.gutierrez@amd.com
58511308Santhony.gutierrez@amd.com''')
58611308Santhony.gutierrez@amd.com
58711308Santhony.gutierrez@amd.com    # create defines for the preprocessing and compile-time determination
58811308Santhony.gutierrez@amd.com    for i,isa in enumerate(isas):
58911308Santhony.gutierrez@amd.com        code('#define $0 $1', define(isa), i + 1)
59011308Santhony.gutierrez@amd.com    code()
59111308Santhony.gutierrez@amd.com
59211308Santhony.gutierrez@amd.com    # create an enum for any run-time determination of the ISA, we
59311308Santhony.gutierrez@amd.com    # reuse the same name as the namespaces
59411308Santhony.gutierrez@amd.com    code('enum class GPUArch {')
59511308Santhony.gutierrez@amd.com    for i,isa in enumerate(isas):
59611308Santhony.gutierrez@amd.com        if i + 1 == len(isas):
59711308Santhony.gutierrez@amd.com            code('  $0 = $1', namespace(isa), define(isa))
59811308Santhony.gutierrez@amd.com        else:
59911308Santhony.gutierrez@amd.com            code('  $0 = $1,', namespace(isa), define(isa))
60011308Santhony.gutierrez@amd.com    code('};')
60111308Santhony.gutierrez@amd.com
60211308Santhony.gutierrez@amd.com    code('''
60311308Santhony.gutierrez@amd.com
60411308Santhony.gutierrez@amd.com#define THE_GPU_ISA ${{define(target_gpu_isa)}}
60511308Santhony.gutierrez@amd.com#define TheGpuISA ${{namespace(target_gpu_isa)}}
60611308Santhony.gutierrez@amd.com#define THE_GPU_ISA_STR "${{target_gpu_isa}}"
60711308Santhony.gutierrez@amd.com
60811308Santhony.gutierrez@amd.com#endif // __CONFIG_THE_GPU_ISA_HH__''')
60911308Santhony.gutierrez@amd.com
61011308Santhony.gutierrez@amd.com    code.write(str(target[0]))
61111308Santhony.gutierrez@amd.com
61211308Santhony.gutierrez@amd.comenv.Command('config/the_gpu_isa.hh', map(Value, all_gpu_isa_list),
61311308Santhony.gutierrez@amd.com            MakeAction(makeTheGPUISA, Transform("CFG ISA", 0)))
61411308Santhony.gutierrez@amd.com
6154382Sbinkertn@umich.edu########################################################################
6164382Sbinkertn@umich.edu#
6174762Snate@binkert.org# Prevent any SimObjects from being added after this point, they
6184762Snate@binkert.org# should all have been added in the SConscripts above
6194762Snate@binkert.org#
6206654Snate@binkert.orgSimObject.fixed = True
6216654Snate@binkert.org
6225517Snate@binkert.orgclass DictImporter(object):
6235517Snate@binkert.org    '''This importer takes a dictionary of arbitrary module names that
6245517Snate@binkert.org    map to arbitrary filenames.'''
6255517Snate@binkert.org    def __init__(self, modules):
6265517Snate@binkert.org        self.modules = modules
6275517Snate@binkert.org        self.installed = set()
6285517Snate@binkert.org
6295517Snate@binkert.org    def __del__(self):
6305517Snate@binkert.org        self.unload()
6315517Snate@binkert.org
6325517Snate@binkert.org    def unload(self):
6335517Snate@binkert.org        import sys
6345517Snate@binkert.org        for module in self.installed:
6355517Snate@binkert.org            del sys.modules[module]
6365517Snate@binkert.org        self.installed = set()
6375517Snate@binkert.org
6385517Snate@binkert.org    def find_module(self, fullname, path):
6396654Snate@binkert.org        if fullname == 'm5.defines':
6405517Snate@binkert.org            return self
6415517Snate@binkert.org
6425517Snate@binkert.org        if fullname == 'm5.objects':
6435517Snate@binkert.org            return self
6445517Snate@binkert.org
64511802Sandreas.sandberg@arm.com        if fullname.startswith('_m5'):
6465517Snate@binkert.org            return None
6475517Snate@binkert.org
6486143Snate@binkert.org        source = self.modules.get(fullname, None)
6496654Snate@binkert.org        if source is not None and fullname.startswith('m5.objects'):
6505517Snate@binkert.org            return self
6515517Snate@binkert.org
6525517Snate@binkert.org        return None
6535517Snate@binkert.org
6545517Snate@binkert.org    def load_module(self, fullname):
6555517Snate@binkert.org        mod = imp.new_module(fullname)
6565517Snate@binkert.org        sys.modules[fullname] = mod
6575517Snate@binkert.org        self.installed.add(fullname)
6585517Snate@binkert.org
6595517Snate@binkert.org        mod.__loader__ = self
6605517Snate@binkert.org        if fullname == 'm5.objects':
6615517Snate@binkert.org            mod.__path__ = fullname.split('.')
6625517Snate@binkert.org            return mod
6635517Snate@binkert.org
6646654Snate@binkert.org        if fullname == 'm5.defines':
6656654Snate@binkert.org            mod.__dict__['buildEnv'] = m5.util.SmartDict(build_env)
6665517Snate@binkert.org            return mod
6675517Snate@binkert.org
6686143Snate@binkert.org        source = self.modules[fullname]
6696143Snate@binkert.org        if source.modname == '__init__':
6706143Snate@binkert.org            mod.__path__ = source.modpath
6716727Ssteve.reinhardt@amd.com        mod.__file__ = source.abspath
6725517Snate@binkert.org
6736727Ssteve.reinhardt@amd.com        exec file(source.abspath, 'r') in mod.__dict__
6745517Snate@binkert.org
6755517Snate@binkert.org        return mod
6765517Snate@binkert.org
6776654Snate@binkert.orgimport m5.SimObject
6786654Snate@binkert.orgimport m5.params
6797673Snate@binkert.orgfrom m5.util import code_formatter
6806654Snate@binkert.org
6816654Snate@binkert.orgm5.SimObject.clear()
6826654Snate@binkert.orgm5.params.clear()
6836654Snate@binkert.org
6845517Snate@binkert.org# install the python importer so we can grab stuff from the source
6855517Snate@binkert.org# tree itself.  We can't have SimObjects added after this point or
6865517Snate@binkert.org# else we won't know about them for the rest of the stuff.
6876143Snate@binkert.orgimporter = DictImporter(PySource.modules)
6885517Snate@binkert.orgsys.meta_path[0:0] = [ importer ]
6894762Snate@binkert.org
6905517Snate@binkert.org# import all sim objects so we can populate the all_objects list
6915517Snate@binkert.org# make sure that we're working with a list, then let's sort it
6926143Snate@binkert.orgfor modname in SimObject.modnames:
6936143Snate@binkert.org    exec('from m5.objects import %s' % modname)
6945517Snate@binkert.org
6955517Snate@binkert.org# we need to unload all of the currently imported modules so that they
6965517Snate@binkert.org# will be re-imported the next time the sconscript is run
6975517Snate@binkert.orgimporter.unload()
6985517Snate@binkert.orgsys.meta_path.remove(importer)
6995517Snate@binkert.org
7005517Snate@binkert.orgsim_objects = m5.SimObject.allClasses
7015517Snate@binkert.orgall_enums = m5.params.allEnums
7025517Snate@binkert.org
7036143Snate@binkert.orgfor name,obj in sorted(sim_objects.iteritems()):
7045517Snate@binkert.org    for param in obj._params.local.values():
7056654Snate@binkert.org        # load the ptype attribute now because it depends on the
7066654Snate@binkert.org        # current version of SimObject.allClasses, but when scons
7076654Snate@binkert.org        # actually uses the value, all versions of
7086654Snate@binkert.org        # SimObject.allClasses will have been loaded
7096654Snate@binkert.org        param.ptype
7106654Snate@binkert.org
7114762Snate@binkert.org########################################################################
7124762Snate@binkert.org#
7134762Snate@binkert.org# calculate extra dependencies
7144762Snate@binkert.org#
7154762Snate@binkert.orgmodule_depends = ["m5", "m5.SimObject", "m5.params"]
7167675Snate@binkert.orgdepends = [ PySource.modules[dep].snode for dep in module_depends ]
71710584Sandreas.hansson@arm.comdepends.sort(key = lambda x: x.name)
7184762Snate@binkert.org
7194762Snate@binkert.org########################################################################
7204762Snate@binkert.org#
7214762Snate@binkert.org# Commands for the basic automatically generated python files
7224382Sbinkertn@umich.edu#
7234382Sbinkertn@umich.edu
7245517Snate@binkert.org# Generate Python file containing a dict specifying the current
7256654Snate@binkert.org# buildEnv flags.
7265517Snate@binkert.orgdef makeDefinesPyFile(target, source, env):
7278126Sgblack@eecs.umich.edu    build_env = source[0].get_contents()
7286654Snate@binkert.org
7297673Snate@binkert.org    code = code_formatter()
7306654Snate@binkert.org    code("""
73111802Sandreas.sandberg@arm.comimport _m5.core
7326654Snate@binkert.orgimport m5.util
7336654Snate@binkert.org
7346654Snate@binkert.orgbuildEnv = m5.util.SmartDict($build_env)
7356654Snate@binkert.org
73611802Sandreas.sandberg@arm.comcompileDate = _m5.core.compileDate
7376669Snate@binkert.org_globals = globals()
73811802Sandreas.sandberg@arm.comfor key,val in _m5.core.__dict__.iteritems():
7396669Snate@binkert.org    if key.startswith('flag_'):
7406669Snate@binkert.org        flag = key[5:]
7416669Snate@binkert.org        _globals[flag] = val
7426669Snate@binkert.orgdel _globals
7436654Snate@binkert.org""")
7447673Snate@binkert.org    code.write(target[0].abspath)
7455517Snate@binkert.org
7468126Sgblack@eecs.umich.edudefines_info = Value(build_env)
7475798Snate@binkert.org# Generate a file with all of the compile options in it
7487756SAli.Saidi@ARM.comenv.Command('python/m5/defines.py', defines_info,
7497816Ssteve.reinhardt@amd.com            MakeAction(makeDefinesPyFile, Transform("DEFINES", 0)))
7505798Snate@binkert.orgPySource('m5', 'python/m5/defines.py')
7515798Snate@binkert.org
7525517Snate@binkert.org# Generate python file containing info about the M5 source code
7535517Snate@binkert.orgdef makeInfoPyFile(target, source, env):
7547673Snate@binkert.org    code = code_formatter()
7555517Snate@binkert.org    for src in source:
7565517Snate@binkert.org        data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
7577673Snate@binkert.org        code('$src = ${{repr(data)}}')
7587673Snate@binkert.org    code.write(str(target[0]))
7595517Snate@binkert.org
7605798Snate@binkert.org# Generate a file that wraps the basic top level files
7615798Snate@binkert.orgenv.Command('python/m5/info.py',
7628333Snate@binkert.org            [ '#/COPYING', '#/LICENSE', '#/README', ],
7637816Ssteve.reinhardt@amd.com            MakeAction(makeInfoPyFile, Transform("INFO")))
7645798Snate@binkert.orgPySource('m5', 'python/m5/info.py')
7655798Snate@binkert.org
7664762Snate@binkert.org########################################################################
7674762Snate@binkert.org#
7684762Snate@binkert.org# Create all of the SimObject param headers and enum headers
7694762Snate@binkert.org#
7704762Snate@binkert.org
7718596Ssteve.reinhardt@amd.comdef createSimObjectParamStruct(target, source, env):
7725517Snate@binkert.org    assert len(target) == 1 and len(source) == 1
7735517Snate@binkert.org
77411997Sgabeblack@google.com    name = source[0].get_text_contents()
7755517Snate@binkert.org    obj = sim_objects[name]
7765517Snate@binkert.org
7777673Snate@binkert.org    code = code_formatter()
7788596Ssteve.reinhardt@amd.com    obj.cxx_param_decl(code)
7797673Snate@binkert.org    code.write(target[0].abspath)
7805517Snate@binkert.org
78110458Sandreas.hansson@arm.comdef createSimObjectCxxConfig(is_header):
78210458Sandreas.hansson@arm.com    def body(target, source, env):
78310458Sandreas.hansson@arm.com        assert len(target) == 1 and len(source) == 1
78410458Sandreas.hansson@arm.com
78510458Sandreas.hansson@arm.com        name = str(source[0].get_contents())
78610458Sandreas.hansson@arm.com        obj = sim_objects[name]
78710458Sandreas.hansson@arm.com
78810458Sandreas.hansson@arm.com        code = code_formatter()
78910458Sandreas.hansson@arm.com        obj.cxx_config_param_file(code, is_header)
79010458Sandreas.hansson@arm.com        code.write(target[0].abspath)
79110458Sandreas.hansson@arm.com    return body
79210458Sandreas.hansson@arm.com
7935517Snate@binkert.orgdef createEnumStrings(target, source, env):
79411996Sgabeblack@google.com    assert len(target) == 1 and len(source) == 2
7955517Snate@binkert.org
79611997Sgabeblack@google.com    name = source[0].get_text_contents()
79711996Sgabeblack@google.com    use_python = source[1].read()
7985517Snate@binkert.org    obj = all_enums[name]
7995517Snate@binkert.org
8007673Snate@binkert.org    code = code_formatter()
8017673Snate@binkert.org    obj.cxx_def(code)
80211996Sgabeblack@google.com    if use_python:
80311988Sandreas.sandberg@arm.com        obj.pybind_def(code)
8047673Snate@binkert.org    code.write(target[0].abspath)
8055517Snate@binkert.org
8068596Ssteve.reinhardt@amd.comdef createEnumDecls(target, source, env):
8075517Snate@binkert.org    assert len(target) == 1 and len(source) == 1
8085517Snate@binkert.org
80911997Sgabeblack@google.com    name = source[0].get_text_contents()
8105517Snate@binkert.org    obj = all_enums[name]
8115517Snate@binkert.org
8127673Snate@binkert.org    code = code_formatter()
8137673Snate@binkert.org    obj.cxx_decl(code)
8147673Snate@binkert.org    code.write(target[0].abspath)
8155517Snate@binkert.org
81611988Sandreas.sandberg@arm.comdef createSimObjectPyBindWrapper(target, source, env):
81711997Sgabeblack@google.com    name = source[0].get_text_contents()
8188596Ssteve.reinhardt@amd.com    obj = sim_objects[name]
8198596Ssteve.reinhardt@amd.com
8208596Ssteve.reinhardt@amd.com    code = code_formatter()
82111988Sandreas.sandberg@arm.com    obj.pybind_decl(code)
8228596Ssteve.reinhardt@amd.com    code.write(target[0].abspath)
8238596Ssteve.reinhardt@amd.com
8248596Ssteve.reinhardt@amd.com# Generate all of the SimObject param C++ struct header files
8254762Snate@binkert.orgparams_hh_files = []
8266143Snate@binkert.orgfor name,simobj in sorted(sim_objects.iteritems()):
8276143Snate@binkert.org    py_source = PySource.modules[simobj.__module__]
8286143Snate@binkert.org    extra_deps = [ py_source.tnode ]
8294762Snate@binkert.org
8304762Snate@binkert.org    hh_file = File('params/%s.hh' % name)
8314762Snate@binkert.org    params_hh_files.append(hh_file)
8327756SAli.Saidi@ARM.com    env.Command(hh_file, Value(name),
8338596Ssteve.reinhardt@amd.com                MakeAction(createSimObjectParamStruct, Transform("SO PARAM")))
8344762Snate@binkert.org    env.Depends(hh_file, depends + extra_deps)
8354762Snate@binkert.org
83610458Sandreas.hansson@arm.com# C++ parameter description files
83710458Sandreas.hansson@arm.comif GetOption('with_cxx_config'):
83810458Sandreas.hansson@arm.com    for name,simobj in sorted(sim_objects.iteritems()):
83910458Sandreas.hansson@arm.com        py_source = PySource.modules[simobj.__module__]
84010458Sandreas.hansson@arm.com        extra_deps = [ py_source.tnode ]
84110458Sandreas.hansson@arm.com
84210458Sandreas.hansson@arm.com        cxx_config_hh_file = File('cxx_config/%s.hh' % name)
84310458Sandreas.hansson@arm.com        cxx_config_cc_file = File('cxx_config/%s.cc' % name)
84410458Sandreas.hansson@arm.com        env.Command(cxx_config_hh_file, Value(name),
84510458Sandreas.hansson@arm.com                    MakeAction(createSimObjectCxxConfig(True),
84610458Sandreas.hansson@arm.com                    Transform("CXXCPRHH")))
84710458Sandreas.hansson@arm.com        env.Command(cxx_config_cc_file, Value(name),
84810458Sandreas.hansson@arm.com                    MakeAction(createSimObjectCxxConfig(False),
84910458Sandreas.hansson@arm.com                    Transform("CXXCPRCC")))
85010458Sandreas.hansson@arm.com        env.Depends(cxx_config_hh_file, depends + extra_deps +
85110458Sandreas.hansson@arm.com                    [File('params/%s.hh' % name), File('sim/cxx_config.hh')])
85210458Sandreas.hansson@arm.com        env.Depends(cxx_config_cc_file, depends + extra_deps +
85310458Sandreas.hansson@arm.com                    [cxx_config_hh_file])
85410458Sandreas.hansson@arm.com        Source(cxx_config_cc_file)
85510458Sandreas.hansson@arm.com
85610458Sandreas.hansson@arm.com    cxx_config_init_cc_file = File('cxx_config/init.cc')
85710458Sandreas.hansson@arm.com
85810458Sandreas.hansson@arm.com    def createCxxConfigInitCC(target, source, env):
85910458Sandreas.hansson@arm.com        assert len(target) == 1 and len(source) == 1
86010458Sandreas.hansson@arm.com
86110458Sandreas.hansson@arm.com        code = code_formatter()
86210458Sandreas.hansson@arm.com
86310458Sandreas.hansson@arm.com        for name,simobj in sorted(sim_objects.iteritems()):
86410458Sandreas.hansson@arm.com            if not hasattr(simobj, 'abstract') or not simobj.abstract:
86510458Sandreas.hansson@arm.com                code('#include "cxx_config/${name}.hh"')
86610458Sandreas.hansson@arm.com        code()
86710458Sandreas.hansson@arm.com        code('void cxxConfigInit()')
86810458Sandreas.hansson@arm.com        code('{')
86910458Sandreas.hansson@arm.com        code.indent()
87010458Sandreas.hansson@arm.com        for name,simobj in sorted(sim_objects.iteritems()):
87110458Sandreas.hansson@arm.com            not_abstract = not hasattr(simobj, 'abstract') or \
87210458Sandreas.hansson@arm.com                not simobj.abstract
87310458Sandreas.hansson@arm.com            if not_abstract and 'type' in simobj.__dict__:
87410458Sandreas.hansson@arm.com                code('cxx_config_directory["${name}"] = '
87510458Sandreas.hansson@arm.com                     '${name}CxxConfigParams::makeDirectoryEntry();')
87610458Sandreas.hansson@arm.com        code.dedent()
87710458Sandreas.hansson@arm.com        code('}')
87810458Sandreas.hansson@arm.com        code.write(target[0].abspath)
87910458Sandreas.hansson@arm.com
88010458Sandreas.hansson@arm.com    py_source = PySource.modules[simobj.__module__]
88110458Sandreas.hansson@arm.com    extra_deps = [ py_source.tnode ]
88210458Sandreas.hansson@arm.com    env.Command(cxx_config_init_cc_file, Value(name),
88310458Sandreas.hansson@arm.com        MakeAction(createCxxConfigInitCC, Transform("CXXCINIT")))
88410458Sandreas.hansson@arm.com    cxx_param_hh_files = ["cxx_config/%s.hh" % simobj
88510584Sandreas.hansson@arm.com        for name,simobj in sorted(sim_objects.iteritems())
88610458Sandreas.hansson@arm.com        if not hasattr(simobj, 'abstract') or not simobj.abstract]
88710458Sandreas.hansson@arm.com    Depends(cxx_config_init_cc_file, cxx_param_hh_files +
88810458Sandreas.hansson@arm.com            [File('sim/cxx_config.hh')])
88910458Sandreas.hansson@arm.com    Source(cxx_config_init_cc_file)
89010458Sandreas.hansson@arm.com
8914762Snate@binkert.org# Generate all enum header files
8926143Snate@binkert.orgfor name,enum in sorted(all_enums.iteritems()):
8936143Snate@binkert.org    py_source = PySource.modules[enum.__module__]
8946143Snate@binkert.org    extra_deps = [ py_source.tnode ]
8954762Snate@binkert.org
8964762Snate@binkert.org    cc_file = File('enums/%s.cc' % name)
89711996Sgabeblack@google.com    env.Command(cc_file, [Value(name), Value(env['USE_PYTHON'])],
8987816Ssteve.reinhardt@amd.com                MakeAction(createEnumStrings, Transform("ENUM STR")))
8994762Snate@binkert.org    env.Depends(cc_file, depends + extra_deps)
9004762Snate@binkert.org    Source(cc_file)
9014762Snate@binkert.org
9024762Snate@binkert.org    hh_file = File('enums/%s.hh' % name)
9037756SAli.Saidi@ARM.com    env.Command(hh_file, Value(name),
9048596Ssteve.reinhardt@amd.com                MakeAction(createEnumDecls, Transform("ENUMDECL")))
9054762Snate@binkert.org    env.Depends(hh_file, depends + extra_deps)
9064762Snate@binkert.org
90711988Sandreas.sandberg@arm.com# Generate SimObject Python bindings wrapper files
90811988Sandreas.sandberg@arm.comif env['USE_PYTHON']:
90911988Sandreas.sandberg@arm.com    for name,simobj in sorted(sim_objects.iteritems()):
91011988Sandreas.sandberg@arm.com        py_source = PySource.modules[simobj.__module__]
91111988Sandreas.sandberg@arm.com        extra_deps = [ py_source.tnode ]
91211988Sandreas.sandberg@arm.com        cc_file = File('python/_m5/param_%s.cc' % name)
91311988Sandreas.sandberg@arm.com        env.Command(cc_file, Value(name),
91411988Sandreas.sandberg@arm.com                    MakeAction(createSimObjectPyBindWrapper,
91511988Sandreas.sandberg@arm.com                               Transform("SO PyBind")))
91611988Sandreas.sandberg@arm.com        env.Depends(cc_file, depends + extra_deps)
91711988Sandreas.sandberg@arm.com        Source(cc_file)
9184382Sbinkertn@umich.edu
9199396Sandreas.hansson@arm.com# Build all protocol buffers if we have got protoc and protobuf available
9209396Sandreas.hansson@arm.comif env['HAVE_PROTOBUF']:
9219396Sandreas.hansson@arm.com    for proto in ProtoBuf.all:
9229396Sandreas.hansson@arm.com        # Use both the source and header as the target, and the .proto
9239396Sandreas.hansson@arm.com        # file as the source. When executing the protoc compiler, also
9249396Sandreas.hansson@arm.com        # specify the proto_path to avoid having the generated files
9259396Sandreas.hansson@arm.com        # include the path.
9269396Sandreas.hansson@arm.com        env.Command([proto.cc_file, proto.hh_file], proto.tnode,
9279396Sandreas.hansson@arm.com                    MakeAction('$PROTOC --cpp_out ${TARGET.dir} '
9289396Sandreas.hansson@arm.com                               '--proto_path ${SOURCE.dir} $SOURCE',
9299396Sandreas.hansson@arm.com                               Transform("PROTOC")))
9309396Sandreas.hansson@arm.com
9319396Sandreas.hansson@arm.com        # Add the C++ source file
93212302Sgabeblack@google.com        Source(proto.cc_file, tags=proto.tags)
9339396Sandreas.hansson@arm.comelif ProtoBuf.all:
93412563Sgabeblack@google.com    print('Got protobuf to build, but lacks support!')
9359396Sandreas.hansson@arm.com    Exit(1)
9369396Sandreas.hansson@arm.com
9378232Snate@binkert.org#
9388232Snate@binkert.org# Handle debug flags
9398232Snate@binkert.org#
9408232Snate@binkert.orgdef makeDebugFlagCC(target, source, env):
9418232Snate@binkert.org    assert(len(target) == 1 and len(source) == 1)
9426229Snate@binkert.org
94310455SCurtis.Dunham@arm.com    code = code_formatter()
9446229Snate@binkert.org
94510455SCurtis.Dunham@arm.com    # delay definition of CompoundFlags until after all the definition
94610455SCurtis.Dunham@arm.com    # of all constituent SimpleFlags
94710455SCurtis.Dunham@arm.com    comp_code = code_formatter()
9485517Snate@binkert.org
9495517Snate@binkert.org    # file header
9507673Snate@binkert.org    code('''
9515517Snate@binkert.org/*
95210455SCurtis.Dunham@arm.com * DO NOT EDIT THIS FILE! Automatically generated by SCons.
9535517Snate@binkert.org */
9545517Snate@binkert.org
9558232Snate@binkert.org#include "base/debug.hh"
95610455SCurtis.Dunham@arm.com
95710455SCurtis.Dunham@arm.comnamespace Debug {
95810455SCurtis.Dunham@arm.com
9597673Snate@binkert.org''')
9607673Snate@binkert.org
96110455SCurtis.Dunham@arm.com    for name, flag in sorted(source[0].read().iteritems()):
96210455SCurtis.Dunham@arm.com        n, compound, desc = flag
96310455SCurtis.Dunham@arm.com        assert n == name
9645517Snate@binkert.org
96510455SCurtis.Dunham@arm.com        if not compound:
96610455SCurtis.Dunham@arm.com            code('SimpleFlag $name("$name", "$desc");')
96710455SCurtis.Dunham@arm.com        else:
96810455SCurtis.Dunham@arm.com            comp_code('CompoundFlag $name("$name", "$desc",')
96910455SCurtis.Dunham@arm.com            comp_code.indent()
97010455SCurtis.Dunham@arm.com            last = len(compound) - 1
97110455SCurtis.Dunham@arm.com            for i,flag in enumerate(compound):
97210455SCurtis.Dunham@arm.com                if i != last:
97310685Sandreas.hansson@arm.com                    comp_code('&$flag,')
97410455SCurtis.Dunham@arm.com                else:
97510685Sandreas.hansson@arm.com                    comp_code('&$flag);')
97610455SCurtis.Dunham@arm.com            comp_code.dedent()
9775517Snate@binkert.org
97810455SCurtis.Dunham@arm.com    code.append(comp_code)
9798232Snate@binkert.org    code()
9808232Snate@binkert.org    code('} // namespace Debug')
9815517Snate@binkert.org
9827673Snate@binkert.org    code.write(str(target[0]))
9835517Snate@binkert.org
9848232Snate@binkert.orgdef makeDebugFlagHH(target, source, env):
9858232Snate@binkert.org    assert(len(target) == 1 and len(source) == 1)
9865517Snate@binkert.org
9878232Snate@binkert.org    val = eval(source[0].get_contents())
9888232Snate@binkert.org    name, compound, desc = val
9898232Snate@binkert.org
9907673Snate@binkert.org    code = code_formatter()
9915517Snate@binkert.org
9925517Snate@binkert.org    # file header boilerplate
9937673Snate@binkert.org    code('''\
9945517Snate@binkert.org/*
99510455SCurtis.Dunham@arm.com * DO NOT EDIT THIS FILE! Automatically generated by SCons.
9965517Snate@binkert.org */
9975517Snate@binkert.org
9988232Snate@binkert.org#ifndef __DEBUG_${name}_HH__
9998232Snate@binkert.org#define __DEBUG_${name}_HH__
10005517Snate@binkert.org
10018232Snate@binkert.orgnamespace Debug {
10028232Snate@binkert.org''')
10035517Snate@binkert.org
10048232Snate@binkert.org    if compound:
10058232Snate@binkert.org        code('class CompoundFlag;')
10068232Snate@binkert.org    code('class SimpleFlag;')
10075517Snate@binkert.org
10088232Snate@binkert.org    if compound:
10098232Snate@binkert.org        code('extern CompoundFlag $name;')
10108232Snate@binkert.org        for flag in compound:
10118232Snate@binkert.org            code('extern SimpleFlag $flag;')
10128232Snate@binkert.org    else:
10138232Snate@binkert.org        code('extern SimpleFlag $name;')
10145517Snate@binkert.org
10158232Snate@binkert.org    code('''
10168232Snate@binkert.org}
10175517Snate@binkert.org
10188232Snate@binkert.org#endif // __DEBUG_${name}_HH__
10197673Snate@binkert.org''')
10205517Snate@binkert.org
10217673Snate@binkert.org    code.write(str(target[0]))
10225517Snate@binkert.org
10238232Snate@binkert.orgfor name,flag in sorted(debug_flags.iteritems()):
10248232Snate@binkert.org    n, compound, desc = flag
10258232Snate@binkert.org    assert n == name
10265192Ssaidi@eecs.umich.edu
102710454SCurtis.Dunham@arm.com    hh_file = 'debug/%s.hh' % name
102810454SCurtis.Dunham@arm.com    env.Command(hh_file, Value(flag),
10298232Snate@binkert.org                MakeAction(makeDebugFlagHH, Transform("TRACING", 0)))
103010455SCurtis.Dunham@arm.com
103110455SCurtis.Dunham@arm.comenv.Command('debug/flags.cc', Value(debug_flags),
103210455SCurtis.Dunham@arm.com            MakeAction(makeDebugFlagCC, Transform("TRACING", 0)))
103310455SCurtis.Dunham@arm.comSource('debug/flags.cc')
10345192Ssaidi@eecs.umich.edu
103511077SCurtis.Dunham@arm.com# version tags
103611330SCurtis.Dunham@arm.comtags = \
103711077SCurtis.Dunham@arm.comenv.Command('sim/tags.cc', None,
103811077SCurtis.Dunham@arm.com            MakeAction('util/cpt_upgrader.py --get-cc-file > $TARGET',
103911077SCurtis.Dunham@arm.com                       Transform("VER TAGS")))
104011330SCurtis.Dunham@arm.comenv.AlwaysBuild(tags)
104111077SCurtis.Dunham@arm.com
10427674Snate@binkert.org# Embed python files.  All .py files that have been indicated by a
10435522Snate@binkert.org# PySource() call in a SConscript need to be embedded into the M5
10445522Snate@binkert.org# library.  To do that, we compile the file to byte code, marshal the
10457674Snate@binkert.org# byte code, compress it, and then generate a c++ file that
10467674Snate@binkert.org# inserts the result into an array.
10477674Snate@binkert.orgdef embedPyFile(target, source, env):
10487674Snate@binkert.org    def c_str(string):
10497674Snate@binkert.org        if string is None:
10507674Snate@binkert.org            return "0"
10517674Snate@binkert.org        return '"%s"' % string
10527674Snate@binkert.org
10535522Snate@binkert.org    '''Action function to compile a .py into a code object, marshal
10545522Snate@binkert.org    it, compress it, and stick it into an asm file so the code appears
10555522Snate@binkert.org    as just bytes with a label in the data section'''
10565517Snate@binkert.org
10575522Snate@binkert.org    src = file(str(source[0]), 'r').read()
10585517Snate@binkert.org
10596143Snate@binkert.org    pysource = PySource.tnodes[source[0]]
10606727Ssteve.reinhardt@amd.com    compiled = compile(src, pysource.abspath, 'exec')
10615522Snate@binkert.org    marshalled = marshal.dumps(compiled)
10625522Snate@binkert.org    compressed = zlib.compress(marshalled)
10635522Snate@binkert.org    data = compressed
10647674Snate@binkert.org    sym = pysource.symname
10655517Snate@binkert.org
10667673Snate@binkert.org    code = code_formatter()
10677673Snate@binkert.org    code('''\
10687674Snate@binkert.org#include "sim/init.hh"
10697673Snate@binkert.org
10707674Snate@binkert.orgnamespace {
10717674Snate@binkert.org
10728946Sandreas.hansson@arm.comconst uint8_t data_${sym}[] = {
10737674Snate@binkert.org''')
10747674Snate@binkert.org    code.indent()
10757674Snate@binkert.org    step = 16
10765522Snate@binkert.org    for i in xrange(0, len(data), step):
10775522Snate@binkert.org        x = array.array('B', data[i:i+step])
10787674Snate@binkert.org        code(''.join('%d,' % d for d in x))
10797674Snate@binkert.org    code.dedent()
108011308Santhony.gutierrez@amd.com
10817674Snate@binkert.org    code('''};
10827673Snate@binkert.org
10837674Snate@binkert.orgEmbeddedPython embedded_${sym}(
10847674Snate@binkert.org    ${{c_str(pysource.arcname)}},
10857674Snate@binkert.org    ${{c_str(pysource.abspath)}},
10867674Snate@binkert.org    ${{c_str(pysource.modpath)}},
10877674Snate@binkert.org    data_${sym},
10887674Snate@binkert.org    ${{len(data)}},
10897674Snate@binkert.org    ${{len(marshalled)}});
10907674Snate@binkert.org
10917811Ssteve.reinhardt@amd.com} // anonymous namespace
10927674Snate@binkert.org''')
10937673Snate@binkert.org    code.write(str(target[0]))
10945522Snate@binkert.org
10956143Snate@binkert.orgfor source in PySource.all:
109610453SAndrew.Bardsley@arm.com    env.Command(source.cpp, source.tnode,
10977816Ssteve.reinhardt@amd.com                MakeAction(embedPyFile, Transform("EMBED PY")))
109812302Sgabeblack@google.com    Source(source.cpp, tags=source.tags, add_tags='python')
10994382Sbinkertn@umich.edu
11004382Sbinkertn@umich.edu########################################################################
11014382Sbinkertn@umich.edu#
11024382Sbinkertn@umich.edu# Define binaries.  Each different build type (debug, opt, etc.) gets
11034382Sbinkertn@umich.edu# a slightly different build environment.
11044382Sbinkertn@umich.edu#
11054382Sbinkertn@umich.edu
11064382Sbinkertn@umich.edu# List of constructed environments to pass back to SConstruct
110712302Sgabeblack@google.comdate_source = Source('base/date.cc', tags=[])
11084382Sbinkertn@umich.edu
110912797Sgabeblack@google.comgem5_binary = Gem5('gem5')
111012797Sgabeblack@google.com
11112655Sstever@eecs.umich.edu# Function to create a new build environment as clone of current
11122655Sstever@eecs.umich.edu# environment 'env' with modified object suffix and optional stripped
11132655Sstever@eecs.umich.edu# binary.  Additional keyword arguments are appended to corresponding
11142655Sstever@eecs.umich.edu# build environment vars.
111512063Sgabeblack@google.comdef makeEnv(env, label, objsfx, strip=False, disable_partial=False, **kwargs):
11165601Snate@binkert.org    # SCons doesn't know to append a library suffix when there is a '.' in the
11175601Snate@binkert.org    # name.  Use '_' instead.
111812222Sgabeblack@google.com    libname = 'gem5_' + label
111912222Sgabeblack@google.com    secondary_exename = 'm5.' + label
11205522Snate@binkert.org
11215863Snate@binkert.org    new_env = env.Clone(OBJSUFFIX=objsfx, SHOBJSUFFIX=objsfx + 's')
11225601Snate@binkert.org    new_env.Label = label
11235601Snate@binkert.org    new_env.Append(**kwargs)
11245601Snate@binkert.org
112512302Sgabeblack@google.com    lib_sources = Source.all.with_tag('gem5 lib')
112610453SAndrew.Bardsley@arm.com
112711988Sandreas.sandberg@arm.com    # Without Python, leave out all Python content from the library
112811988Sandreas.sandberg@arm.com    # builds.  The option doesn't affect gem5 built as a program
112910453SAndrew.Bardsley@arm.com    if GetOption('without_python'):
113012302Sgabeblack@google.com        lib_sources = lib_sources.without_tag('python')
113110453SAndrew.Bardsley@arm.com
113211983Sgabeblack@google.com    static_objs = []
113311983Sgabeblack@google.com    shared_objs = []
113412302Sgabeblack@google.com
113512302Sgabeblack@google.com    for s in lib_sources.with_tag(Source.ungrouped_tag):
113612362Sgabeblack@google.com        static_objs.append(s.static(new_env))
113712362Sgabeblack@google.com        shared_objs.append(s.shared(new_env))
113811983Sgabeblack@google.com
113912302Sgabeblack@google.com    for group in Source.source_groups:
114012302Sgabeblack@google.com        srcs = lib_sources.with_tag(Source.link_group_tag(group))
114111983Sgabeblack@google.com        if not srcs:
114211983Sgabeblack@google.com            continue
114311983Sgabeblack@google.com
114412362Sgabeblack@google.com        group_static = [ s.static(new_env) for s in srcs ]
114512362Sgabeblack@google.com        group_shared = [ s.shared(new_env) for s in srcs ]
114612310Sgabeblack@google.com
114712063Sgabeblack@google.com        # If partial linking is disabled, add these sources to the build
114812063Sgabeblack@google.com        # directly, and short circuit this loop.
114912063Sgabeblack@google.com        if disable_partial:
115012310Sgabeblack@google.com            static_objs.extend(group_static)
115112310Sgabeblack@google.com            shared_objs.extend(group_shared)
115212063Sgabeblack@google.com            continue
115312063Sgabeblack@google.com
115411983Sgabeblack@google.com        # Set up the static partially linked objects.
115511983Sgabeblack@google.com        file_name = new_env.subst("${OBJPREFIX}lib${OBJSUFFIX}.partial")
115611983Sgabeblack@google.com        target = File(joinpath(group, file_name))
115712310Sgabeblack@google.com        partial = env.PartialStatic(target=target, source=group_static)
115812310Sgabeblack@google.com        static_objs.extend(partial)
115911983Sgabeblack@google.com
116011983Sgabeblack@google.com        # Set up the shared partially linked objects.
116111983Sgabeblack@google.com        file_name = new_env.subst("${SHOBJPREFIX}lib${SHOBJSUFFIX}.partial")
116211983Sgabeblack@google.com        target = File(joinpath(group, file_name))
116312310Sgabeblack@google.com        partial = env.PartialShared(target=target, source=group_shared)
116412310Sgabeblack@google.com        shared_objs.extend(partial)
11656143Snate@binkert.org
116612362Sgabeblack@google.com    static_date = date_source.static(new_env)
116712306Sgabeblack@google.com    new_env.Depends(static_date, static_objs)
116812310Sgabeblack@google.com    static_objs.extend(static_date)
116910453SAndrew.Bardsley@arm.com
117012362Sgabeblack@google.com    shared_date = date_source.shared(new_env)
117112306Sgabeblack@google.com    new_env.Depends(shared_date, shared_objs)
117212310Sgabeblack@google.com    shared_objs.extend(shared_date)
11735554Snate@binkert.org
117412797Sgabeblack@google.com    main_objs = [ s.static(new_env) for s in Source.all.with_tag('main') ]
117512797Sgabeblack@google.com
11765522Snate@binkert.org    # First make a library of everything but main() so other programs can
11775522Snate@binkert.org    # link against m5.
11785797Snate@binkert.org    static_lib = new_env.StaticLibrary(libname, static_objs)
11795797Snate@binkert.org    shared_lib = new_env.SharedLibrary(libname, shared_objs)
11805522Snate@binkert.org
118112797Sgabeblack@google.com    # Keep track of the object files generated so far so Executables can
118212797Sgabeblack@google.com    # include them.
118312797Sgabeblack@google.com    new_env['STATIC_OBJS'] = static_objs
118412797Sgabeblack@google.com    new_env['SHARED_OBJS'] = shared_objs
118512797Sgabeblack@google.com    new_env['MAIN_OBJS'] = main_objs
11868233Snate@binkert.org
118712797Sgabeblack@google.com    new_env['STATIC_LIB'] = static_lib
118812797Sgabeblack@google.com    new_env['SHARED_LIB'] = shared_lib
11898235Snate@binkert.org
119012797Sgabeblack@google.com    # Record some settings for building Executables.
119112797Sgabeblack@google.com    new_env['EXE_SUFFIX'] = label
119212797Sgabeblack@google.com    new_env['STRIP_EXES'] = strip
119312370Sgabeblack@google.com
119412797Sgabeblack@google.com    for cls in ExecutableMeta.all:
119512797Sgabeblack@google.com        cls.declare_all(new_env)
119612313Sgabeblack@google.com
119712797Sgabeblack@google.com    new_env.M5Binary = File(gem5_binary.path(new_env))
11986143Snate@binkert.org
119912797Sgabeblack@google.com    new_env.Command(secondary_exename, new_env.M5Binary,
12008334Snate@binkert.org            MakeAction('ln $SOURCE $TARGET', Transform("HARDLINK")))
12018334Snate@binkert.org
120211993Sgabeblack@google.com    # Set up regression tests.
120311993Sgabeblack@google.com    SConscript(os.path.join(env.root.abspath, 'tests', 'SConscript'),
120412223Sgabeblack@google.com               variant_dir=Dir('tests').Dir(new_env.Label),
120511993Sgabeblack@google.com               exports={ 'env' : new_env }, duplicate=False)
12062655Sstever@eecs.umich.edu
12079225Sandreas.hansson@arm.com# Start out with the compiler flags common to all compilers,
12089225Sandreas.hansson@arm.com# i.e. they all use -g for opt and -g -pg for prof
12099226Sandreas.hansson@arm.comccflags = {'debug' : [], 'opt' : ['-g'], 'fast' : [], 'prof' : ['-g', '-pg'],
12109226Sandreas.hansson@arm.com           'perf' : ['-g']}
12119225Sandreas.hansson@arm.com
12129226Sandreas.hansson@arm.com# Start out with the linker flags common to all linkers, i.e. -pg for
12139226Sandreas.hansson@arm.com# prof, and -lprofiler for perf. The -lprofile flag is surrounded by
12149226Sandreas.hansson@arm.com# no-as-needed and as-needed as the binutils linker is too clever and
12159226Sandreas.hansson@arm.com# simply doesn't link to the library otherwise.
12169226Sandreas.hansson@arm.comldflags = {'debug' : [], 'opt' : [], 'fast' : [], 'prof' : ['-pg'],
12179226Sandreas.hansson@arm.com           'perf' : ['-Wl,--no-as-needed', '-lprofiler', '-Wl,--as-needed']}
12189225Sandreas.hansson@arm.com
12199227Sandreas.hansson@arm.com# For Link Time Optimization, the optimisation flags used to compile
12209227Sandreas.hansson@arm.com# individual files are decoupled from those used at link time
12219227Sandreas.hansson@arm.com# (i.e. you can compile with -O3 and perform LTO with -O0), so we need
12229227Sandreas.hansson@arm.com# to also update the linker flags based on the target.
12238946Sandreas.hansson@arm.comif env['GCC']:
12243918Ssaidi@eecs.umich.edu    if sys.platform == 'sunos5':
12259225Sandreas.hansson@arm.com        ccflags['debug'] += ['-gstabs+']
12263918Ssaidi@eecs.umich.edu    else:
12279225Sandreas.hansson@arm.com        ccflags['debug'] += ['-ggdb3']
12289225Sandreas.hansson@arm.com    ldflags['debug'] += ['-O0']
12299227Sandreas.hansson@arm.com    # opt, fast, prof and perf all share the same cc flags, also add
12309227Sandreas.hansson@arm.com    # the optimization to the ldflags as LTO defers the optimization
12319227Sandreas.hansson@arm.com    # to link time
12329226Sandreas.hansson@arm.com    for target in ['opt', 'fast', 'prof', 'perf']:
12339225Sandreas.hansson@arm.com        ccflags[target] += ['-O3']
12349227Sandreas.hansson@arm.com        ldflags[target] += ['-O3']
12359227Sandreas.hansson@arm.com
12369227Sandreas.hansson@arm.com    ccflags['fast'] += env['LTO_CCFLAGS']
12379227Sandreas.hansson@arm.com    ldflags['fast'] += env['LTO_LDFLAGS']
12388946Sandreas.hansson@arm.comelif env['CLANG']:
12399225Sandreas.hansson@arm.com    ccflags['debug'] += ['-g', '-O0']
12409226Sandreas.hansson@arm.com    # opt, fast, prof and perf all share the same cc flags
12419226Sandreas.hansson@arm.com    for target in ['opt', 'fast', 'prof', 'perf']:
12429226Sandreas.hansson@arm.com        ccflags[target] += ['-O3']
12433515Ssaidi@eecs.umich.eduelse:
124412563Sgabeblack@google.com    print('Unknown compiler, please fix compiler options')
12454762Snate@binkert.org    Exit(1)
12463515Ssaidi@eecs.umich.edu
12478881Smarc.orr@gmail.com
12488881Smarc.orr@gmail.com# To speed things up, we only instantiate the build environments we
12498881Smarc.orr@gmail.com# need.  We try to identify the needed environment for each target; if
12508881Smarc.orr@gmail.com# we can't, we fall back on instantiating all the environments just to
12518881Smarc.orr@gmail.com# be safe.
12529226Sandreas.hansson@arm.comtarget_types = ['debug', 'opt', 'fast', 'prof', 'perf']
12539226Sandreas.hansson@arm.comobj2target = {'do': 'debug', 'o': 'opt', 'fo': 'fast', 'po': 'prof',
12549226Sandreas.hansson@arm.com              'gpo' : 'perf'}
12558881Smarc.orr@gmail.com
12568881Smarc.orr@gmail.comdef identifyTarget(t):
12578881Smarc.orr@gmail.com    ext = t.split('.')[-1]
12588881Smarc.orr@gmail.com    if ext in target_types:
12598881Smarc.orr@gmail.com        return ext
12608881Smarc.orr@gmail.com    if obj2target.has_key(ext):
12618881Smarc.orr@gmail.com        return obj2target[ext]
12628881Smarc.orr@gmail.com    match = re.search(r'/tests/([^/]+)/', t)
12638881Smarc.orr@gmail.com    if match and match.group(1) in target_types:
12648881Smarc.orr@gmail.com        return match.group(1)
12658881Smarc.orr@gmail.com    return 'all'
12668881Smarc.orr@gmail.com
12678881Smarc.orr@gmail.comneeded_envs = [identifyTarget(target) for target in BUILD_TARGETS]
12688881Smarc.orr@gmail.comif 'all' in needed_envs:
12698881Smarc.orr@gmail.com    needed_envs += target_types
12708881Smarc.orr@gmail.com
127113508Snikos.nikoleris@arm.comdisable_partial = False
127213508Snikos.nikoleris@arm.comif env['PLATFORM'] == 'darwin':
127313508Snikos.nikoleris@arm.com    # Up until Apple LLVM version 10.0.0 (clang-1000.11.45.5), partial
127413508Snikos.nikoleris@arm.com    # linked objects do not expose symbols that are marked with the
127513508Snikos.nikoleris@arm.com    # hidden visibility and consequently building gem5 on Mac OS
127613508Snikos.nikoleris@arm.com    # fails. As a workaround, we disable partial linking, however, we
127713508Snikos.nikoleris@arm.com    # may want to revisit in the future.
127813508Snikos.nikoleris@arm.com    disable_partial = True
127913508Snikos.nikoleris@arm.com
128012222Sgabeblack@google.com# Debug binary
128112222Sgabeblack@google.comif 'debug' in needed_envs:
128212222Sgabeblack@google.com    makeEnv(env, 'debug', '.do',
128312222Sgabeblack@google.com            CCFLAGS = Split(ccflags['debug']),
128412222Sgabeblack@google.com            CPPDEFINES = ['DEBUG', 'TRACING_ON=1'],
128513508Snikos.nikoleris@arm.com            LINKFLAGS = Split(ldflags['debug']),
128613508Snikos.nikoleris@arm.com            disable_partial=disable_partial)
1287955SN/A
128812222Sgabeblack@google.com# Optimized binary
128912222Sgabeblack@google.comif 'opt' in needed_envs:
129012222Sgabeblack@google.com    makeEnv(env, 'opt', '.o',
129112222Sgabeblack@google.com            CCFLAGS = Split(ccflags['opt']),
129212222Sgabeblack@google.com            CPPDEFINES = ['TRACING_ON=1'],
129313508Snikos.nikoleris@arm.com            LINKFLAGS = Split(ldflags['opt']),
129413508Snikos.nikoleris@arm.com            disable_partial=disable_partial)
1295955SN/A
129612222Sgabeblack@google.com# "Fast" binary
129712222Sgabeblack@google.comif 'fast' in needed_envs:
129813508Snikos.nikoleris@arm.com    disable_partial = disable_partial and \
129912222Sgabeblack@google.com            env.get('BROKEN_INCREMENTAL_LTO', False) and \
130012222Sgabeblack@google.com            GetOption('force_lto')
130112222Sgabeblack@google.com    makeEnv(env, 'fast', '.fo', strip = True,
130212222Sgabeblack@google.com            CCFLAGS = Split(ccflags['fast']),
130312222Sgabeblack@google.com            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
130412222Sgabeblack@google.com            LINKFLAGS = Split(ldflags['fast']),
130512222Sgabeblack@google.com            disable_partial=disable_partial)
13061869SN/A
130712222Sgabeblack@google.com# Profiled binary using gprof
130812222Sgabeblack@google.comif 'prof' in needed_envs:
130912222Sgabeblack@google.com    makeEnv(env, 'prof', '.po',
131012222Sgabeblack@google.com            CCFLAGS = Split(ccflags['prof']),
131112222Sgabeblack@google.com            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
131213508Snikos.nikoleris@arm.com            LINKFLAGS = Split(ldflags['prof']),
131313508Snikos.nikoleris@arm.com            disable_partial=disable_partial)
13149226Sandreas.hansson@arm.com
131512222Sgabeblack@google.com# Profiled binary using google-pprof
131612222Sgabeblack@google.comif 'perf' in needed_envs:
131712222Sgabeblack@google.com    makeEnv(env, 'perf', '.gpo',
131812222Sgabeblack@google.com            CCFLAGS = Split(ccflags['perf']),
131912222Sgabeblack@google.com            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
132013508Snikos.nikoleris@arm.com            LINKFLAGS = Split(ldflags['perf']),
132113508Snikos.nikoleris@arm.com            disable_partial=disable_partial)
1322