SConscript revision 5192
111539Sandreas.hansson@arm.com# -*- mode:python -*-
29522SAndreas.Sandberg@ARM.com
311320Ssteve.reinhardt@amd.com# Copyright (c) 2004-2005 The Regents of The University of Michigan
49522SAndreas.Sandberg@ARM.com# All rights reserved.
59522SAndreas.Sandberg@ARM.com#
69522SAndreas.Sandberg@ARM.com# Redistribution and use in source and binary forms, with or without
79522SAndreas.Sandberg@ARM.com# modification, are permitted provided that the following conditions are
89522SAndreas.Sandberg@ARM.com# met: redistributions of source code must retain the above copyright
99522SAndreas.Sandberg@ARM.com# notice, this list of conditions and the following disclaimer;
109522SAndreas.Sandberg@ARM.com# redistributions in binary form must reproduce the above copyright
119522SAndreas.Sandberg@ARM.com# notice, this list of conditions and the following disclaimer in the
1211320Ssteve.reinhardt@amd.com# documentation and/or other materials provided with the distribution;
136981SLisa.Hsu@amd.com# neither the name of the copyright holders nor the names of its
146981SLisa.Hsu@amd.com# contributors may be used to endorse or promote products derived from
156981SLisa.Hsu@amd.com# this software without specific prior written permission.
166981SLisa.Hsu@amd.com#
176981SLisa.Hsu@amd.com# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
186981SLisa.Hsu@amd.com# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
196981SLisa.Hsu@amd.com# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
206981SLisa.Hsu@amd.com# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
216981SLisa.Hsu@amd.com# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
226981SLisa.Hsu@amd.com# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
236981SLisa.Hsu@amd.com# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
246981SLisa.Hsu@amd.com# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
256981SLisa.Hsu@amd.com# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
266981SLisa.Hsu@amd.com# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
276981SLisa.Hsu@amd.com# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
286981SLisa.Hsu@amd.com#
296981SLisa.Hsu@amd.com# Authors: Nathan Binkert
306981SLisa.Hsu@amd.com
316981SLisa.Hsu@amd.comimport imp
326981SLisa.Hsu@amd.comimport os
336981SLisa.Hsu@amd.comimport sys
346981SLisa.Hsu@amd.com
356981SLisa.Hsu@amd.comfrom os.path import basename
366981SLisa.Hsu@amd.comfrom os.path import join as joinpath
376981SLisa.Hsu@amd.comfrom os.path import exists
386981SLisa.Hsu@amd.comfrom os.path import isdir
396981SLisa.Hsu@amd.comfrom os.path import isfile
406981SLisa.Hsu@amd.com
416981SLisa.Hsu@amd.comimport SCons
426981SLisa.Hsu@amd.com
436981SLisa.Hsu@amd.com# This file defines how to build a particular configuration of M5
446981SLisa.Hsu@amd.com# based on variable settings in the 'env' build environment.
456981SLisa.Hsu@amd.com
466981SLisa.Hsu@amd.comImport('*')
476981SLisa.Hsu@amd.com
486981SLisa.Hsu@amd.com# Children need to see the environment
4910780SCurtis.Dunham@arm.comExport('env')
5010780SCurtis.Dunham@arm.com
5110780SCurtis.Dunham@arm.comdef sort_list(_list):
5210780SCurtis.Dunham@arm.com    """return a sorted copy of '_list'"""
5310780SCurtis.Dunham@arm.com    if isinstance(_list, list):
5410780SCurtis.Dunham@arm.com        _list = _list[:]
5510780SCurtis.Dunham@arm.com    else:
5612014Sgabeblack@google.com        _list = list(_list)
579522SAndreas.Sandberg@ARM.com    _list.sort()
5812097Sandreas.sandberg@arm.com    return _list
599522SAndreas.Sandberg@ARM.com
6012097Sandreas.sandberg@arm.comclass PySourceFile(object):
619522SAndreas.Sandberg@ARM.com    def __init__(self, package, source):
629522SAndreas.Sandberg@ARM.com        filename = str(source)
6311539Sandreas.hansson@arm.com        pyname = basename(filename)
6411539Sandreas.hansson@arm.com        assert pyname.endswith('.py')
6511539Sandreas.hansson@arm.com        name = pyname[:-3]
669522SAndreas.Sandberg@ARM.com        path = package.split('.')
6711539Sandreas.hansson@arm.com        modpath = path
6811539Sandreas.hansson@arm.com        if name != '__init__':
6911539Sandreas.hansson@arm.com            modpath += [name]
7011539Sandreas.hansson@arm.com        modpath = '.'.join(modpath)
7111539Sandreas.hansson@arm.com
729522SAndreas.Sandberg@ARM.com        arcpath = package.split('.') + [ pyname + 'c' ]
739815SAndreas Hansson <andreas.hansson>        arcname = joinpath(*arcpath)
749815SAndreas Hansson <andreas.hansson>
759815SAndreas Hansson <andreas.hansson>        self.source = source
7611251Sradhika.jagtap@ARM.com        self.pyname = pyname
7711251Sradhika.jagtap@ARM.com        self.srcpath = source.srcnode().abspath
7811251Sradhika.jagtap@ARM.com        self.package = package
7911251Sradhika.jagtap@ARM.com        self.modpath = modpath
8011251Sradhika.jagtap@ARM.com        self.arcname = arcname
8111251Sradhika.jagtap@ARM.com        self.filename = filename
8211251Sradhika.jagtap@ARM.com        self.compiled = File(filename + 'c')
836981SLisa.Hsu@amd.com
849284Sandreas.hansson@arm.com########################################################################
859284Sandreas.hansson@arm.com# Code for adding source files of various types
8610720Sandreas.hansson@arm.com#
879793Sakash.bagdia@arm.comcc_sources = []
889522SAndreas.Sandberg@ARM.comdef Source(source):
899815SAndreas Hansson <andreas.hansson>    '''Add a C/C++ source file to the build'''
908724Srdreslin@umich.edu    if not isinstance(source, SCons.Node.FS.File):
9110720Sandreas.hansson@arm.com        source = File(source)
928839Sandreas.hansson@arm.com
938839Sandreas.hansson@arm.com    cc_sources.append(source)
946981SLisa.Hsu@amd.com
9510613SMarco.Elver@ARM.compy_sources = []
9610613SMarco.Elver@ARM.comdef PySource(package, source):
9710613SMarco.Elver@ARM.com    '''Add a python source file to the named package'''
986981SLisa.Hsu@amd.com    if not isinstance(source, SCons.Node.FS.File):
996981SLisa.Hsu@amd.com        source = File(source)
1009522SAndreas.Sandberg@ARM.com
1019815SAndreas Hansson <andreas.hansson>    source = PySourceFile(package, source)
1029522SAndreas.Sandberg@ARM.com    py_sources.append(source)
1039815SAndreas Hansson <andreas.hansson>
1048724Srdreslin@umich.edusim_objects_fixed = False
10511539Sandreas.hansson@arm.comsim_object_modfiles = set()
10611539Sandreas.hansson@arm.comdef SimObject(source):
10711539Sandreas.hansson@arm.com    '''Add a SimObject python file as a python source object and add
10811539Sandreas.hansson@arm.com    it to a list of sim object modules'''
10911539Sandreas.hansson@arm.com
11011539Sandreas.hansson@arm.com    if sim_objects_fixed:
11111539Sandreas.hansson@arm.com        raise AttributeError, "Too late to call SimObject now."
11211539Sandreas.hansson@arm.com
11311539Sandreas.hansson@arm.com    if not isinstance(source, SCons.Node.FS.File):
11410613SMarco.Elver@ARM.com        source = File(source)
11510613SMarco.Elver@ARM.com
11610613SMarco.Elver@ARM.com    PySource('m5.objects', source)
11710613SMarco.Elver@ARM.com    modfile = basename(str(source))
11810613SMarco.Elver@ARM.com    assert modfile.endswith('.py')
11910613SMarco.Elver@ARM.com    modname = modfile[:-3]
12010613SMarco.Elver@ARM.com    sim_object_modfiles.add(modname)
12110613SMarco.Elver@ARM.com
12210613SMarco.Elver@ARM.comswig_sources = []
12310613SMarco.Elver@ARM.comdef SwigSource(package, source):
12410613SMarco.Elver@ARM.com    '''Add a swig file to build'''
12510613SMarco.Elver@ARM.com    if not isinstance(source, SCons.Node.FS.File):
12610613SMarco.Elver@ARM.com        source = File(source)
12710613SMarco.Elver@ARM.com    val = source,package
12810613SMarco.Elver@ARM.com    swig_sources.append(val)
1299284Sandreas.hansson@arm.com
1309284Sandreas.hansson@arm.com# Children should have access
13111539Sandreas.hansson@arm.comExport('Source')
13211539Sandreas.hansson@arm.comExport('PySource')
13310613SMarco.Elver@ARM.comExport('SimObject')
13410613SMarco.Elver@ARM.comExport('SwigSource')
13510613SMarco.Elver@ARM.com
13610613SMarco.Elver@ARM.com########################################################################
13710613SMarco.Elver@ARM.com#
13810613SMarco.Elver@ARM.com# Trace Flags
13910613SMarco.Elver@ARM.com#
14010780SCurtis.Dunham@arm.comall_flags = {}
14110780SCurtis.Dunham@arm.comtrace_flags = []
14210780SCurtis.Dunham@arm.comdef TraceFlag(name, desc=''):
14310780SCurtis.Dunham@arm.com    if name in all_flags:
14410780SCurtis.Dunham@arm.com        raise AttributeError, "Flag %s already specified" % name
14510780SCurtis.Dunham@arm.com    flag = (name, (), desc)
14610780SCurtis.Dunham@arm.com    trace_flags.append(flag)
14710780SCurtis.Dunham@arm.com    all_flags[name] = ()
14810780SCurtis.Dunham@arm.com
14910780SCurtis.Dunham@arm.comdef CompoundFlag(name, flags, desc=''):
15010780SCurtis.Dunham@arm.com    if name in all_flags:
15110780SCurtis.Dunham@arm.com        raise AttributeError, "Flag %s already specified" % name
15210780SCurtis.Dunham@arm.com
15310780SCurtis.Dunham@arm.com    compound = tuple(flags)
15410780SCurtis.Dunham@arm.com    for flag in compound:
15510780SCurtis.Dunham@arm.com        if flag not in all_flags:
15610780SCurtis.Dunham@arm.com            raise AttributeError, "Trace flag %s not found" % flag
1578863Snilay@cs.wisc.edu        if all_flags[flag]:
1586981SLisa.Hsu@amd.com            raise AttributeError, \
1597876Sgblack@eecs.umich.edu                "Compound flag can't point to another compound flag"
16010780SCurtis.Dunham@arm.com
16110780SCurtis.Dunham@arm.com    flag = (name, compound, desc)
1626981SLisa.Hsu@amd.com    trace_flags.append(flag)
1637876Sgblack@eecs.umich.edu    all_flags[name] = compound
1646981SLisa.Hsu@amd.com
1656981SLisa.Hsu@amd.comExport('TraceFlag')
16610780SCurtis.Dunham@arm.comExport('CompoundFlag')
16710780SCurtis.Dunham@arm.com
16810780SCurtis.Dunham@arm.com########################################################################
16910780SCurtis.Dunham@arm.com#
17010780SCurtis.Dunham@arm.com# Set some compiler variables
17110780SCurtis.Dunham@arm.com#
17210780SCurtis.Dunham@arm.com
17310780SCurtis.Dunham@arm.com# Include file paths are rooted in this directory.  SCons will
17410780SCurtis.Dunham@arm.com# automatically expand '.' to refer to both the source directory and
17510780SCurtis.Dunham@arm.com# the corresponding build directory to pick up generated include
17610780SCurtis.Dunham@arm.com# files.
17710780SCurtis.Dunham@arm.comenv.Append(CPPPATH=Dir('.'))
17810780SCurtis.Dunham@arm.com
17910780SCurtis.Dunham@arm.com# Add a flag defining what THE_ISA should be for all compilation
18010780SCurtis.Dunham@arm.comenv.Append(CPPDEFINES=[('THE_ISA','%s_ISA' % env['TARGET_ISA'].upper())])
18110780SCurtis.Dunham@arm.com
18210780SCurtis.Dunham@arm.com########################################################################
18310780SCurtis.Dunham@arm.com#
18410780SCurtis.Dunham@arm.com# Walk the tree and execute all SConscripts
18510780SCurtis.Dunham@arm.com#
18610780SCurtis.Dunham@arm.comsrcdir = env['SRCDIR']
187for root, dirs, files in os.walk(srcdir, topdown=True):
188    if root == srcdir:
189        # we don't want to recurse back into this SConscript
190        continue
191
192    if 'SConscript' in files:
193        # strip off the srcdir part since scons will try to find the
194        # script in the build directory
195        base = root[len(srcdir) + 1:]
196        SConscript(joinpath(base, 'SConscript'))
197
198extra_string = env['EXTRAS']
199if extra_string and extra_string != '' and not extra_string.isspace():
200    for extra in extra_string.split(':'):
201        extra = os.path.expanduser(extra)
202        extra = os.path.normpath(extra)
203        env.Append(CPPPATH=[Dir(extra)])
204        for root, dirs, files in os.walk(extra, topdown=True):
205            if 'SConscript' in files:
206                subdir = root[len(os.path.dirname(extra))+1:]
207                build_dir = joinpath(env['BUILDDIR'], subdir)
208                SConscript(joinpath(root, 'SConscript'), build_dir=build_dir)
209
210for opt in env.ExportOptions:
211    env.ConfigFile(opt)
212
213########################################################################
214#
215# Prevent any SimObjects from being added after this point, they
216# should all have been added in the SConscripts above
217#
218sim_objects_fixed = True
219
220########################################################################
221#
222# Manually turn python/generate.py into a python module and import it
223#
224generate_file = File('python/generate.py')
225generate_module = imp.new_module('generate')
226sys.modules['generate'] = generate_module
227exec file(generate_file.srcnode().abspath, 'r') in generate_module.__dict__
228
229########################################################################
230#
231# build a generate
232#
233from generate import Generate
234optionDict = dict([(opt, env[opt]) for opt in env.ExportOptions])
235generate = Generate(py_sources, sim_object_modfiles, optionDict)
236m5 = generate.m5
237
238########################################################################
239#
240# calculate extra dependencies
241#
242module_depends = ["m5", "m5.SimObject", "m5.params"]
243module_depends = [ File(generate.py_modules[dep]) for dep in module_depends ]
244file_depends = [ generate_file ]
245depends = module_depends + file_depends
246
247########################################################################
248#
249# Commands for the basic automatically generated python files
250#
251
252# Generate a file with all of the compile options in it
253env.Command('python/m5/defines.py', Value(optionDict),
254            generate.makeDefinesPyFile)
255PySource('m5', 'python/m5/defines.py')
256
257# Generate a file that wraps the basic top level files
258env.Command('python/m5/info.py',
259            [ '#/AUTHORS', '#/LICENSE', '#/README', '#/RELEASE_NOTES' ],
260            generate.makeInfoPyFile)
261PySource('m5', 'python/m5/info.py')
262
263# Generate an __init__.py file for the objects package
264env.Command('python/m5/objects/__init__.py',
265            [ Value(o) for o in sort_list(sim_object_modfiles) ],
266            generate.makeObjectsInitFile)
267PySource('m5.objects', 'python/m5/objects/__init__.py')
268
269########################################################################
270#
271# Create all of the SimObject param headers and enum headers
272#
273
274# Generate all of the SimObject param struct header files
275params_hh_files = []
276for name,simobj in generate.sim_objects.iteritems():
277    extra_deps = [ File(generate.py_modules[simobj.__module__]) ]
278
279    hh_file = File('params/%s.hh' % name)
280    params_hh_files.append(hh_file)
281    env.Command(hh_file, Value(name), generate.createSimObjectParam)
282    env.Depends(hh_file, depends + extra_deps)
283
284# Generate any parameter header files needed
285for name,param in generate.params.iteritems():
286    if isinstance(param, m5.params.VectorParamDesc):
287        ext = 'vptype'
288    else:
289        ext = 'ptype'
290
291    i_file = File('params/%s_%s.i' % (name, ext))
292    env.Command(i_file, Value(name), generate.createSwigParam)
293    env.Depends(i_file, depends)
294
295# Generate all enum header files
296for name,enum in generate.enums.iteritems():
297    extra_deps = [ File(generate.py_modules[enum.__module__]) ]
298
299    cc_file = File('enums/%s.cc' % name)
300    env.Command(cc_file, Value(name), generate.createEnumStrings)
301    env.Depends(cc_file, depends + extra_deps)
302    Source(cc_file)
303
304    hh_file = File('enums/%s.hh' % name)
305    env.Command(hh_file, Value(name), generate.createEnumParam)
306    env.Depends(hh_file, depends + extra_deps)
307
308# Build the big monolithic swigged params module (wraps all SimObject
309# param structs and enum structs)
310params_file = File('params/params.i')
311names = sort_list(generate.sim_objects.keys())
312env.Command(params_file, [ Value(v) for v in names ],
313            generate.buildParams)
314env.Depends(params_file, params_hh_files + depends)
315SwigSource('m5.objects', params_file)
316
317# Build all swig modules
318swig_modules = []
319for source,package in swig_sources:
320    filename = str(source)
321    assert filename.endswith('.i')
322
323    base = '.'.join(filename.split('.')[:-1])
324    module = basename(base)
325    cc_file = base + '_wrap.cc'
326    py_file = base + '.py'
327
328    env.Command([cc_file, py_file], source,
329                '$SWIG $SWIGFLAGS -outdir ${TARGETS[1].dir} '
330                '-o ${TARGETS[0]} $SOURCES')
331    env.Depends(py_file, source)
332    env.Depends(cc_file, source)
333
334    swig_modules.append(Value(module))
335    Source(cc_file)
336    PySource(package, py_file)
337
338# Generate the main swig init file
339env.Command('swig/init.cc', swig_modules, generate.makeSwigInit)
340Source('swig/init.cc')
341
342# Generate traceflags.py
343flags = [ Value(f) for f in trace_flags ]
344env.Command('base/traceflags.py', flags, generate.traceFlagsPy)
345PySource('m5', 'base/traceflags.py')
346
347env.Command('base/traceflags.hh', flags, generate.traceFlagsHH)
348env.Command('base/traceflags.cc', flags, generate.traceFlagsCC)
349Source('base/traceflags.cc')
350
351# Build the zip file
352py_compiled = []
353py_zip_depends = []
354for source in py_sources:
355    env.Command(source.compiled, source.source, generate.compilePyFile)
356    py_compiled.append(source.compiled)
357
358    # make the zipfile depend on the archive name so that the archive
359    # is rebuilt if the name changes
360    py_zip_depends.append(Value(source.arcname))
361
362# Add the zip file target to the environment.
363m5zip = File('m5py.zip')
364env.Command(m5zip, py_compiled, generate.buildPyZip)
365env.Depends(m5zip, py_zip_depends)
366
367########################################################################
368#
369# Define binaries.  Each different build type (debug, opt, etc.) gets
370# a slightly different build environment.
371#
372
373# List of constructed environments to pass back to SConstruct
374envList = []
375
376# This function adds the specified sources to the given build
377# environment, and returns a list of all the corresponding SCons
378# Object nodes (including an extra one for date.cc).  We explicitly
379# add the Object nodes so we can set up special dependencies for
380# date.cc.
381def make_objs(sources, env):
382    objs = [env.Object(s) for s in sources]
383    # make date.cc depend on all other objects so it always gets
384    # recompiled whenever anything else does
385    date_obj = env.Object('base/date.cc')
386    env.Depends(date_obj, objs)
387    objs.append(date_obj)
388    return objs
389
390# Function to create a new build environment as clone of current
391# environment 'env' with modified object suffix and optional stripped
392# binary.  Additional keyword arguments are appended to corresponding
393# build environment vars.
394def makeEnv(label, objsfx, strip = False, **kwargs):
395    newEnv = env.Copy(OBJSUFFIX=objsfx)
396    newEnv.Label = label
397    newEnv.Append(**kwargs)
398    exe = 'm5.' + label  # final executable
399    bin = exe + '.bin'   # executable w/o appended Python zip archive
400    newEnv.Program(bin, make_objs(cc_sources, newEnv))
401    if strip:
402        stripped_bin = bin + '.stripped'
403        if sys.platform == 'sunos5':
404            cmd = 'cp $SOURCE $TARGET; strip $TARGET'
405        else:
406            cmd = 'strip $SOURCE -o $TARGET'
407        newEnv.Command(stripped_bin, bin, cmd)
408        bin = stripped_bin
409    targets = newEnv.Concat(exe, [bin, 'm5py.zip'])
410    newEnv.M5Binary = targets[0]
411    envList.append(newEnv)
412
413# Debug binary
414ccflags = {}
415if env['GCC']:
416    if sys.platform == 'sunos5':
417        ccflags['debug'] = '-gstabs+'
418    else:
419        ccflags['debug'] = '-ggdb3'
420    ccflags['opt'] = '-g -O3'
421    ccflags['fast'] = '-O3'
422    ccflags['prof'] = '-O3 -g -pg'
423elif env['SUNCC']:
424    ccflags['debug'] = '-g0'
425    ccflags['opt'] = '-g -O'
426    ccflags['fast'] = '-fast'
427    ccflags['prof'] = '-fast -g -pg'
428elif env['ICC']:
429    ccflags['debug'] = '-g -O0'
430    ccflags['opt'] = '-g -O'
431    ccflags['fast'] = '-fast'
432    ccflags['prof'] = '-fast -g -pg'
433else:
434    print 'Unknown compiler, please fix compiler options'
435    Exit(1)
436
437makeEnv('debug', '.do',
438        CCFLAGS = Split(ccflags['debug']),
439        CPPDEFINES = ['DEBUG', 'TRACING_ON=1'])
440
441# Optimized binary
442makeEnv('opt', '.o',
443        CCFLAGS = Split(ccflags['opt']),
444        CPPDEFINES = ['TRACING_ON=1'])
445
446# "Fast" binary
447makeEnv('fast', '.fo', strip = True,
448        CCFLAGS = Split(ccflags['fast']),
449        CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'])
450
451# Profiled binary
452makeEnv('prof', '.po',
453        CCFLAGS = Split(ccflags['prof']),
454        CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
455        LINKFLAGS = '-pg')
456
457Return('envList')
458