SConstruct revision 2654:9559cfa91b9d
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)
67
68# Ironically, SCons 0.96 dies if you give EnsureSconsVersion a
69# 3-element version number.
70min_scons_version = (0,96,91)
71try:
72    EnsureSConsVersion(*min_scons_version)
73except:
74    print "Error checking current SCons version."
75    print "SCons", ".".join(map(str,min_scons_version)), "or greater required."
76    Exit(2)
77    
78
79# The absolute path to the current directory (where this file lives).
80ROOT = Dir('.').abspath
81
82# Paths to the M5 and external source trees.
83SRCDIR = os.path.join(ROOT, 'src')
84
85# tell python where to find m5 python code
86sys.path.append(os.path.join(ROOT, 'src/python'))
87
88###################################################
89#
90# Figure out which configurations to set up based on the path(s) of
91# the target(s).
92#
93###################################################
94
95# Find default configuration & binary.
96Default(os.environ.get('M5_DEFAULT_BINARY', 'build/ALPHA_SE/m5.debug'))
97
98# Ask SCons which directory it was invoked from.
99launch_dir = GetLaunchDir()
100
101# Make targets relative to invocation directory
102abs_targets = map(lambda x: os.path.normpath(os.path.join(launch_dir, str(x))),
103                  BUILD_TARGETS)
104
105# helper function: find last occurrence of element in list
106def rfind(l, elt, offs = -1):
107    for i in range(len(l)+offs, 0, -1):
108        if l[i] == elt:
109            return i
110    raise ValueError, "element not found"
111
112# Each target must have 'build' in the interior of the path; the
113# directory below this will determine the build parameters.  For
114# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
115# recognize that ALPHA_SE specifies the configuration because it
116# follow 'build' in the bulid path.
117
118# Generate a list of the unique build roots and configs that the
119# collected targets reference.
120build_paths = []
121build_root = None
122for t in abs_targets:
123    path_dirs = t.split('/')
124    try:
125        build_top = rfind(path_dirs, 'build', -2)
126    except:
127        print "Error: no non-leaf 'build' dir found on target path", t
128        Exit(1)
129    this_build_root = os.path.join('/',*path_dirs[:build_top+1])
130    if not build_root:
131        build_root = this_build_root
132    else:
133        if this_build_root != build_root:
134            print "Error: build targets not under same build root\n"\
135                  "  %s\n  %s" % (build_root, this_build_root)
136            Exit(1)
137    build_path = os.path.join('/',*path_dirs[:build_top+2])
138    if build_path not in build_paths:
139        build_paths.append(build_path)
140
141###################################################
142#
143# Set up the default build environment.  This environment is copied
144# and modified according to each selected configuration.
145#
146###################################################
147
148env = Environment(ENV = os.environ,  # inherit user's environment vars
149                  ROOT = ROOT,
150                  SRCDIR = SRCDIR)
151
152env.SConsignFile("sconsign")
153
154# I waffle on this setting... it does avoid a few painful but
155# unnecessary builds, but it also seems to make trivial builds take
156# noticeably longer.
157if False:
158    env.TargetSignatures('content')
159
160# M5_PLY is used by isa_parser.py to find the PLY package.
161env.Append(ENV = { 'M5_PLY' : Dir('ext/ply') })
162
163# Set up default C++ compiler flags
164env.Append(CCFLAGS='-pipe')
165env.Append(CCFLAGS='-fno-strict-aliasing')
166env.Append(CCFLAGS=Split('-Wall -Wno-sign-compare -Werror -Wundef'))
167if sys.platform == 'cygwin':
168    # cygwin has some header file issues...
169    env.Append(CCFLAGS=Split("-Wno-uninitialized"))
170env.Append(CPPPATH=[Dir('ext/dnet')])
171
172# Default libraries
173env.Append(LIBS=['z'])
174
175# Platform-specific configuration.  Note again that we assume that all
176# builds under a given build root run on the same host platform.
177conf = Configure(env,
178                 conf_dir = os.path.join(build_root, '.scons_config'),
179                 log_file = os.path.join(build_root, 'scons_config.log'))
180
181# Check for <fenv.h> (C99 FP environment control)
182have_fenv = conf.CheckHeader('fenv.h', '<>')
183if not have_fenv:
184    print "Warning: Header file <fenv.h> not found."
185    print "         This host has no IEEE FP rounding mode control."
186
187# Check for mysql.
188mysql_config = WhereIs('mysql_config')
189have_mysql = mysql_config != None
190
191# Check MySQL version.
192if have_mysql:
193    mysql_version = os.popen(mysql_config + ' --version').read()
194    mysql_version = mysql_version.split('.')
195    mysql_major = int(mysql_version[0])
196    mysql_minor = int(mysql_version[1])
197    # This version check is probably overly conservative, but it deals
198    # with the versions we have installed.
199    if mysql_major < 4 or (mysql_major == 4 and mysql_minor < 1):
200        print "Warning: MySQL v4.1 or newer required."
201        have_mysql = False
202
203# Set up mysql_config commands.
204if have_mysql:
205    mysql_config_include = mysql_config + ' --include'
206    if os.system(mysql_config_include + ' > /dev/null') != 0:
207        # older mysql_config versions don't support --include, use
208        # --cflags instead
209        mysql_config_include = mysql_config + ' --cflags | sed s/\\\'//g'
210    # This seems to work in all versions
211    mysql_config_libs = mysql_config + ' --libs'
212
213env = conf.Finish()
214
215# Define the universe of supported ISAs
216env['ALL_ISA_LIST'] = ['alpha', 'sparc', 'mips']
217
218# Define the universe of supported CPU models
219env['ALL_CPU_LIST'] = ['AtomicSimpleCPU', 'TimingSimpleCPU',
220                       'FullCPU', 'AlphaFullCPU',
221                       'OzoneSimpleCPU', 'OzoneCPU', 'CheckerCPU']
222
223# Sticky options get saved in the options file so they persist from
224# one invocation to the next (unless overridden, in which case the new
225# value becomes sticky).
226sticky_opts = Options(args=ARGUMENTS)
227sticky_opts.AddOptions(
228    EnumOption('TARGET_ISA', 'Target ISA', 'alpha', env['ALL_ISA_LIST']),
229    BoolOption('FULL_SYSTEM', 'Full-system support', False),
230    # There's a bug in scons 0.96.1 that causes ListOptions with list
231    # values (more than one value) not to be able to be restored from
232    # a saved option file.  If this causes trouble then upgrade to
233    # scons 0.96.90 or later.
234    ListOption('CPU_MODELS', 'CPU models', 'AtomicSimpleCPU,TimingSimpleCPU',
235               env['ALL_CPU_LIST']),
236    BoolOption('ALPHA_TLASER',
237               'Model Alpha TurboLaser platform (vs. Tsunami)', False),
238    BoolOption('NO_FAST_ALLOC', 'Disable fast object allocator', False),
239    BoolOption('EFENCE', 'Link with Electric Fence malloc debugger',
240               False),
241    BoolOption('SS_COMPATIBLE_FP',
242               'Make floating-point results compatible with SimpleScalar',
243               False),
244    BoolOption('USE_SSE2',
245               'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
246               False),
247    BoolOption('STATS_BINNING', 'Bin statistics by CPU mode', have_mysql),
248    BoolOption('USE_MYSQL', 'Use MySQL for stats output', have_mysql),
249    BoolOption('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
250    ('CC', 'C compiler', os.environ.get('CC', env['CC'])),
251    ('CXX', 'C++ compiler', os.environ.get('CXX', env['CXX'])),
252    BoolOption('BATCH', 'Use batch pool for build and tests', False),
253    ('BATCH_CMD', 'Batch pool submission command name', 'qdo')
254    )
255
256# Non-sticky options only apply to the current build.
257nonsticky_opts = Options(args=ARGUMENTS)
258nonsticky_opts.AddOptions(
259    BoolOption('update_ref', 'Update test reference outputs', False)
260    )
261
262# These options get exported to #defines in config/*.hh (see m5/SConscript).
263env.ExportOptions = ['FULL_SYSTEM', 'ALPHA_TLASER', 'USE_FENV', \
264                     'USE_MYSQL', 'NO_FAST_ALLOC', 'SS_COMPATIBLE_FP', \
265                     'STATS_BINNING']
266
267# Define a handy 'no-op' action
268def no_action(target, source, env):
269    return 0
270
271env.NoAction = Action(no_action, None)
272
273###################################################
274#
275# Define a SCons builder for configuration flag headers.
276#
277###################################################
278
279# This function generates a config header file that #defines the
280# option symbol to the current option setting (0 or 1).  The source
281# operands are the name of the option and a Value node containing the
282# value of the option.
283def build_config_file(target, source, env):
284    (option, value) = [s.get_contents() for s in source]
285    f = file(str(target[0]), 'w')
286    print >> f, '#define', option, value
287    f.close()
288    return None
289
290# Generate the message to be printed when building the config file.
291def build_config_file_string(target, source, env):
292    (option, value) = [s.get_contents() for s in source]
293    return "Defining %s as %s in %s." % (option, value, target[0])
294
295# Combine the two functions into a scons Action object.
296config_action = Action(build_config_file, build_config_file_string)
297
298# The emitter munges the source & target node lists to reflect what
299# we're really doing.
300def config_emitter(target, source, env):
301    # extract option name from Builder arg
302    option = str(target[0])
303    # True target is config header file
304    target = os.path.join('config', option.lower() + '.hh')
305    # Force value to 0/1 even if it's a Python bool
306    val = int(eval(str(env[option])))
307    # Sources are option name & value (packaged in SCons Value nodes)
308    return ([target], [Value(option), Value(val)])
309
310config_builder = Builder(emitter = config_emitter, action = config_action)
311
312env.Append(BUILDERS = { 'ConfigFile' : config_builder })
313
314# base help text
315help_text = '''
316Usage: scons [scons options] [build options] [target(s)]
317
318'''
319
320# libelf build is shared across all configs in the build root.
321env.SConscript('ext/libelf/SConscript',
322               build_dir = os.path.join(build_root, 'libelf'),
323               exports = 'env')
324
325###################################################
326#
327# Define build environments for selected configurations.
328#
329###################################################
330
331# rename base env
332base_env = env
333
334for build_path in build_paths:
335    print "Building in", build_path
336    # build_dir is the tail component of build path, and is used to
337    # determine the build parameters (e.g., 'ALPHA_SE')
338    (build_root, build_dir) = os.path.split(build_path)
339    # Make a copy of the build-root environment to use for this config.
340    env = base_env.Copy()
341
342    # Set env options according to the build directory config.
343    sticky_opts.files = []
344    # Options for $BUILD_ROOT/$BUILD_DIR are stored in
345    # $BUILD_ROOT/options/$BUILD_DIR so you can nuke
346    # $BUILD_ROOT/$BUILD_DIR without losing your options settings.
347    current_opts_file = os.path.join(build_root, 'options', build_dir)
348    if os.path.isfile(current_opts_file):
349        sticky_opts.files.append(current_opts_file)
350        print "Using saved options file %s" % current_opts_file
351    else:
352        # Build dir-specific options file doesn't exist.
353
354        # Make sure the directory is there so we can create it later
355        opt_dir = os.path.dirname(current_opts_file)
356        if not os.path.isdir(opt_dir):
357            os.mkdir(opt_dir)
358
359        # Get default build options from source tree.  Options are
360        # normally determined by name of $BUILD_DIR, but can be
361        # overriden by 'default=' arg on command line.
362        default_opts_file = os.path.join('build_opts',
363                                         ARGUMENTS.get('default', build_dir))
364        if os.path.isfile(default_opts_file):
365            sticky_opts.files.append(default_opts_file)
366            print "Options file %s not found,\n  using defaults in %s" \
367                  % (current_opts_file, default_opts_file)
368        else:
369            print "Error: cannot find options file %s or %s" \
370                  % (current_opts_file, default_opts_file)
371            Exit(1)
372
373    # Apply current option settings to env
374    sticky_opts.Update(env)
375    nonsticky_opts.Update(env)
376
377    help_text += "Sticky options for %s:\n" % build_dir \
378                 + sticky_opts.GenerateHelpText(env) \
379                 + "\nNon-sticky options for %s:\n" % build_dir \
380                 + nonsticky_opts.GenerateHelpText(env)
381
382    # Process option settings.
383
384    if not have_fenv and env['USE_FENV']:
385        print "Warning: <fenv.h> not available; " \
386              "forcing USE_FENV to False in", build_dir + "."
387        env['USE_FENV'] = False
388
389    if not env['USE_FENV']:
390        print "Warning: No IEEE FP rounding mode control in", build_dir + "."
391        print "         FP results may deviate slightly from other platforms."
392
393    if env['EFENCE']:
394        env.Append(LIBS=['efence'])
395
396    if env['USE_MYSQL']:
397        if not have_mysql:
398            print "Warning: MySQL not available; " \
399                  "forcing USE_MYSQL to False in", build_dir + "."
400            env['USE_MYSQL'] = False
401        else:
402            print "Compiling in", build_dir, "with MySQL support."
403            env.ParseConfig(mysql_config_libs)
404            env.ParseConfig(mysql_config_include)
405
406    # Save sticky option settings back to current options file
407    sticky_opts.Save(current_opts_file, env)
408
409    # Do this after we save setting back, or else we'll tack on an
410    # extra 'qdo' every time we run scons.
411    if env['BATCH']:
412        env['CC']  = env['BATCH_CMD'] + ' ' + env['CC']
413        env['CXX'] = env['BATCH_CMD'] + ' ' + env['CXX']
414
415    if env['USE_SSE2']:
416        env.Append(CCFLAGS='-msse2')
417
418    # The m5/SConscript file sets up the build rules in 'env' according
419    # to the configured options.  It returns a list of environments,
420    # one for each variant build (debug, opt, etc.)
421    envList = SConscript('src/SConscript', build_dir = build_path,
422                         exports = 'env', duplicate = False)
423
424    # Set up the regression tests for each build.
425#    for e in envList:
426#        SConscript('m5-test/SConscript',
427#                   build_dir = os.path.join(build_dir, 'test', e.Label),
428#                   exports = { 'env' : e }, duplicate = False)
429
430Help(help_text)
431
432###################################################
433#
434# Let SCons do its thing.  At this point SCons will use the defined
435# build environments to build the requested targets.
436#
437###################################################
438
439