SConstruct revision 2634:db0b1133abd5
1# -*- mode:python -*-
2
3# Copyright (c) 2004-2005 The Regents of The University of Michigan
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met: redistributions of source code must retain the above copyright
9# notice, this list of conditions and the following disclaimer;
10# redistributions in binary form must reproduce the above copyright
11# notice, this list of conditions and the following disclaimer in the
12# documentation and/or other materials provided with the distribution;
13# neither the name of the copyright holders nor the names of its
14# contributors may be used to endorse or promote products derived from
15# this software without specific prior written permission.
16#
17# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29###################################################
30#
31# SCons top-level build description (SConstruct) file.
32#
33# While in this directory ('m5'), just type 'scons' to build the default
34# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
35# to build some other configuration (e.g., 'build/ALPHA_FS/m5.opt' for
36# the optimized full-system version).
37#
38# You can build M5 in a different directory as long as there is a
39# 'build/<CONFIG>' somewhere along the target path.  The build system
40# expdects that all configs under the same build directory are being
41# built for the same host system.
42#
43# Examples:
44#   These two commands are equivalent.  The '-u' option tells scons to
45#   search up the directory tree for this SConstruct file.
46#   % cd <path-to-src>/m5 ; scons build/ALPHA_FS/m5.debug
47#   % cd <path-to-src>/m5/build/ALPHA_FS; scons -u m5.debug
48#   These two commands are equivalent and demonstrate building in a
49#   directory outside of the source tree.  The '-C' option tells scons
50#   to chdir to the specified directory to find this SConstruct file.
51#   % cd <path-to-src>/m5 ; scons /local/foo/build/ALPHA_FS/m5.debug
52#   % cd /local/foo/build/ALPHA_FS; scons -C <path-to-src>/m5 m5.debug
53#
54# You can use 'scons -H' to print scons options.  If you're in this
55# 'm5' directory (or use -u or -C to tell scons where to find this
56# file), you can use 'scons -h' to print all the M5-specific build
57# options as well.
58#
59###################################################
60
61# Python library imports
62import sys
63import os
64
65# Check for recent-enough Python and SCons versions
66EnsurePythonVersion(2,3)
67EnsureSConsVersion(0,96,91)
68
69# The absolute path to the current directory (where this file lives).
70ROOT = Dir('.').abspath
71
72# Paths to the M5 and external source trees.
73SRCDIR = os.path.join(ROOT, 'src')
74
75# tell python where to find m5 python code
76sys.path.append(os.path.join(ROOT, 'src/python'))
77
78###################################################
79#
80# Figure out which configurations to set up based on the path(s) of
81# the target(s).
82#
83###################################################
84
85# Find default configuration & binary.
86Default(os.environ.get('M5_DEFAULT_BINARY', 'build/ALPHA_SE/m5.debug'))
87
88# Ask SCons which directory it was invoked from.
89launch_dir = GetLaunchDir()
90
91# Make targets relative to invocation directory
92abs_targets = map(lambda x: os.path.normpath(os.path.join(launch_dir, str(x))),
93                  BUILD_TARGETS)
94
95# helper function: find last occurrence of element in list
96def rfind(l, elt, offs = -1):
97    for i in range(len(l)+offs, 0, -1):
98        if l[i] == elt:
99            return i
100    raise ValueError, "element not found"
101
102# Each target must have 'build' in the interior of the path; the
103# directory below this will determine the build parameters.  For
104# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
105# recognize that ALPHA_SE specifies the configuration because it
106# follow 'build' in the bulid path.
107
108# Generate a list of the unique build roots and configs that the
109# collected targets reference.
110build_paths = []
111build_roots = []
112for t in abs_targets:
113    path_dirs = t.split('/')
114    try:
115        build_top = rfind(path_dirs, 'build', -2)
116    except:
117        print "Error: no non-leaf 'build' dir found on target path", t
118        Exit(1)
119    build_root = os.path.join('/',*path_dirs[:build_top+1])
120    if build_root not in build_roots:
121        build_roots.append(build_root)
122    build_path = os.path.join('/',*path_dirs[:build_top+2])
123    if build_path not in build_paths:
124        build_paths.append(build_path)
125
126###################################################
127#
128# Set up the default build environment.  This environment is copied
129# and modified according to each selected configuration.
130#
131###################################################
132
133env = Environment(ENV = os.environ,  # inherit user's environment vars
134                  ROOT = ROOT,
135                  SRCDIR = SRCDIR)
136
137env.SConsignFile("sconsign")
138
139# I waffle on this setting... it does avoid a few painful but
140# unnecessary builds, but it also seems to make trivial builds take
141# noticeably longer.
142if False:
143    env.TargetSignatures('content')
144
145# M5_PLY is used by isa_parser.py to find the PLY package.
146env.Append(ENV = { 'M5_PLY' : Dir('ext/ply') })
147
148# Set up default C++ compiler flags
149env.Append(CCFLAGS='-pipe')
150env.Append(CCFLAGS='-fno-strict-aliasing')
151env.Append(CCFLAGS=Split('-Wall -Wno-sign-compare -Werror -Wundef'))
152if sys.platform == 'cygwin':
153    # cygwin has some header file issues...
154    env.Append(CCFLAGS=Split("-Wno-uninitialized"))
155env.Append(CPPPATH=[Dir('ext/dnet')])
156
157# Default libraries
158env.Append(LIBS=['z'])
159
160# Platform-specific configuration
161conf = Configure(env)
162
163# Check for <fenv.h> (C99 FP environment control)
164have_fenv = conf.CheckHeader('fenv.h', '<>')
165if not have_fenv:
166    print "Warning: Header file <fenv.h> not found."
167    print "         This host has no IEEE FP rounding mode control."
168
169# Check for mysql.
170mysql_config = WhereIs('mysql_config')
171have_mysql = mysql_config != None
172
173# Check MySQL version.
174if have_mysql:
175    mysql_version = os.popen(mysql_config + ' --version').read()
176    mysql_version = mysql_version.split('.')
177    mysql_major = int(mysql_version[0])
178    mysql_minor = int(mysql_version[1])
179    # This version check is probably overly conservative, but it deals
180    # with the versions we have installed.
181    if mysql_major < 4 or (mysql_major == 4 and mysql_minor < 1):
182        print "Warning: MySQL v4.1 or newer required."
183        have_mysql = False
184
185# Set up mysql_config commands.
186if have_mysql:
187    mysql_config_include = mysql_config + ' --include'
188    if os.system(mysql_config_include + ' > /dev/null') != 0:
189        # older mysql_config versions don't support --include, use
190        # --cflags instead
191        mysql_config_include = mysql_config + ' --cflags | sed s/\\\'//g'
192    # This seems to work in all versions
193    mysql_config_libs = mysql_config + ' --libs'
194
195env = conf.Finish()
196
197# Define the universe of supported ISAs
198env['ALL_ISA_LIST'] = ['alpha', 'sparc', 'mips']
199
200# Define the universe of supported CPU models
201env['ALL_CPU_LIST'] = ['AtomicSimpleCPU', 'TimingSimpleCPU',
202                       'FastCPU', 'FullCPU', 'AlphaFullCPU']
203
204# Sticky options get saved in the options file so they persist from
205# one invocation to the next (unless overridden, in which case the new
206# value becomes sticky).
207sticky_opts = Options(args=ARGUMENTS)
208sticky_opts.AddOptions(
209    EnumOption('TARGET_ISA', 'Target ISA', 'alpha', env['ALL_ISA_LIST']),
210    BoolOption('FULL_SYSTEM', 'Full-system support', False),
211    # There's a bug in scons 0.96.1 that causes ListOptions with list
212    # values (more than one value) not to be able to be restored from
213    # a saved option file.  If this causes trouble then upgrade to
214    # scons 0.96.90 or later.
215    ListOption('CPU_MODELS', 'CPU models', 'all', env['ALL_CPU_LIST']),
216    BoolOption('ALPHA_TLASER',
217               'Model Alpha TurboLaser platform (vs. Tsunami)', False),
218    BoolOption('NO_FAST_ALLOC', 'Disable fast object allocator', False),
219    BoolOption('EFENCE', 'Link with Electric Fence malloc debugger',
220               False),
221    BoolOption('SS_COMPATIBLE_FP',
222               'Make floating-point results compatible with SimpleScalar',
223               False),
224    BoolOption('USE_SSE2',
225               'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
226               False),
227    BoolOption('STATS_BINNING', 'Bin statistics by CPU mode', have_mysql),
228    BoolOption('USE_MYSQL', 'Use MySQL for stats output', have_mysql),
229    BoolOption('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
230    ('CC', 'C compiler', os.environ.get('CC', env['CC'])),
231    ('CXX', 'C++ compiler', os.environ.get('CXX', env['CXX'])),
232    BoolOption('BATCH', 'Use batch pool for build and tests', False),
233    ('BATCH_CMD', 'Batch pool submission command name', 'qdo')
234    )
235
236# Non-sticky options only apply to the current build.
237nonsticky_opts = Options(args=ARGUMENTS)
238nonsticky_opts.AddOptions(
239    BoolOption('update_ref', 'Update test reference outputs', False)
240    )
241
242# These options get exported to #defines in config/*.hh (see m5/SConscript).
243env.ExportOptions = ['FULL_SYSTEM', 'ALPHA_TLASER', 'USE_FENV', \
244                     'USE_MYSQL', 'NO_FAST_ALLOC', 'SS_COMPATIBLE_FP', \
245                     'STATS_BINNING']
246
247# Define a handy 'no-op' action
248def no_action(target, source, env):
249    return 0
250
251env.NoAction = Action(no_action, None)
252
253###################################################
254#
255# Define a SCons builder for configuration flag headers.
256#
257###################################################
258
259# This function generates a config header file that #defines the
260# option symbol to the current option setting (0 or 1).  The source
261# operands are the name of the option and a Value node containing the
262# value of the option.
263def build_config_file(target, source, env):
264    (option, value) = [s.get_contents() for s in source]
265    f = file(str(target[0]), 'w')
266    print >> f, '#define', option, value
267    f.close()
268    return None
269
270# Generate the message to be printed when building the config file.
271def build_config_file_string(target, source, env):
272    (option, value) = [s.get_contents() for s in source]
273    return "Defining %s as %s in %s." % (option, value, target[0])
274
275# Combine the two functions into a scons Action object.
276config_action = Action(build_config_file, build_config_file_string)
277
278# The emitter munges the source & target node lists to reflect what
279# we're really doing.
280def config_emitter(target, source, env):
281    # extract option name from Builder arg
282    option = str(target[0])
283    # True target is config header file
284    target = os.path.join('config', option.lower() + '.hh')
285    # Force value to 0/1 even if it's a Python bool
286    val = int(eval(str(env[option])))
287    # Sources are option name & value (packaged in SCons Value nodes)
288    return ([target], [Value(option), Value(val)])
289
290config_builder = Builder(emitter = config_emitter, action = config_action)
291
292env.Append(BUILDERS = { 'ConfigFile' : config_builder })
293
294# base help text
295help_text = '''
296Usage: scons [scons options] [build options] [target(s)]
297
298'''
299
300###################################################
301#
302# Define build environments for selected configurations.
303#
304###################################################
305
306# rename base env
307base_env = env
308
309# Spme things (just libelf currently) are shared across all configs in
310# a "build root".  Need to define how to build these just once for
311# each referenced root.
312build_root_env = {}
313for build_root in build_roots:
314    env = base_env.Copy()
315    env.SConscript('ext/libelf/SConscript',
316                   build_dir = os.path.join(build_root, 'libelf'),
317                   exports = 'env')
318    build_root_env[build_root] = env
319
320for build_path in build_paths:
321    print "Building in", build_path
322    # build_dir is the tail component of build path, and is used to
323    # determine the build parameters (e.g., 'ALPHA_SE')
324    (build_root, build_dir) = os.path.split(build_path)
325    # Make a copy of the build-root environment to use for this config.
326    env = build_root_env[build_root].Copy()
327
328    # Set env options according to the build directory config.
329    sticky_opts.files = []
330    # Options for $BUILD_ROOT/$BUILD_DIR are stored in
331    # $BUILD_ROOT/options/$BUILD_DIR so you can nuke
332    # $BUILD_ROOT/$BUILD_DIR without losing your options settings.
333    current_opts_file = os.path.join(build_root, 'options', build_dir)
334    if os.path.isfile(current_opts_file):
335        sticky_opts.files.append(current_opts_file)
336        print "Using saved options file %s" % current_opts_file
337    else:
338        # Build dir-specific options file doesn't exist.
339
340        # Make sure the directory is there so we can create it later
341        opt_dir = os.path.dirname(current_opts_file)
342        if not os.path.isdir(opt_dir):
343            os.mkdir(opt_dir)
344
345        # Get default build options from source tree.  Options are
346        # normally determined by name of $BUILD_DIR, but can be
347        # overriden by 'default=' arg on command line.
348        default_opts_file = os.path.join('build_opts',
349                                         ARGUMENTS.get('default', build_dir))
350        if os.path.isfile(default_opts_file):
351            sticky_opts.files.append(default_opts_file)
352            print "Options file %s not found,\n  using defaults in %s" \
353                  % (current_opts_file, default_opts_file)
354        else:
355            print "Error: cannot find options file %s or %s" \
356                  % (current_opts_file, default_opts_file)
357            Exit(1)
358
359    # Apply current option settings to env
360    sticky_opts.Update(env)
361    nonsticky_opts.Update(env)
362
363    help_text += "Sticky options for %s:\n" % build_dir \
364                 + sticky_opts.GenerateHelpText(env) \
365                 + "\nNon-sticky options for %s:\n" % build_dir \
366                 + nonsticky_opts.GenerateHelpText(env)
367
368    # Process option settings.
369
370    if not have_fenv and env['USE_FENV']:
371        print "Warning: <fenv.h> not available; " \
372              "forcing USE_FENV to False in", build_dir + "."
373        env['USE_FENV'] = False
374
375    if not env['USE_FENV']:
376        print "Warning: No IEEE FP rounding mode control in", build_dir + "."
377        print "         FP results may deviate slightly from other platforms."
378
379    if env['EFENCE']:
380        env.Append(LIBS=['efence'])
381
382    if env['USE_MYSQL']:
383        if not have_mysql:
384            print "Warning: MySQL not available; " \
385                  "forcing USE_MYSQL to False in", build_dir + "."
386            env['USE_MYSQL'] = False
387        else:
388            print "Compiling in", build_dir, "with MySQL support."
389            env.ParseConfig(mysql_config_libs)
390            env.ParseConfig(mysql_config_include)
391
392    # Save sticky option settings back to current options file
393    sticky_opts.Save(current_opts_file, env)
394
395    # Do this after we save setting back, or else we'll tack on an
396    # extra 'qdo' every time we run scons.
397    if env['BATCH']:
398        env['CC']  = env['BATCH_CMD'] + ' ' + env['CC']
399        env['CXX'] = env['BATCH_CMD'] + ' ' + env['CXX']
400
401    if env['USE_SSE2']:
402        env.Append(CCFLAGS='-msse2')
403
404    # The m5/SConscript file sets up the build rules in 'env' according
405    # to the configured options.  It returns a list of environments,
406    # one for each variant build (debug, opt, etc.)
407    envList = SConscript('src/SConscript', build_dir = build_path,
408                         exports = 'env', duplicate = False)
409
410    # Set up the regression tests for each build.
411#    for e in envList:
412#        SConscript('m5-test/SConscript',
413#                   build_dir = os.path.join(build_dir, 'test', e.Label),
414#                   exports = { 'env' : e }, duplicate = False)
415
416Help(help_text)
417
418###################################################
419#
420# Let SCons do its thing.  At this point SCons will use the defined
421# build environments to build the requested targets.
422#
423###################################################
424
425