ARM: Get rid of some comments/todos that no longer apply.
[gem5.git] / SConstruct
old mode 100644 (file)
new mode 100755 (executable)
index 07ddfd5..eee1c78
@@ -1,5 +1,6 @@
 # -*- mode:python -*-
 
+# Copyright (c) 2011 Advanced Micro Devices, Inc.
 # Copyright (c) 2009 The Hewlett-Packard Development Company
 # Copyright (c) 2004-2005 The Regents of The University of Michigan
 # All rights reserved.
@@ -120,6 +121,51 @@ sys.path[1:1] = extra_python_paths
 
 from m5.util import compareVersions, readCommand
 
+help_texts = {
+    "options" : "",
+    "global_vars" : "",
+    "local_vars" : ""
+}
+
+Export("help_texts")
+
+def AddM5Option(*args, **kwargs):
+    col_width = 30
+
+    help = "  " + ", ".join(args)
+    if "help" in kwargs:
+        length = len(help)
+        if length >= col_width:
+            help += "\n" + " " * col_width
+        else:
+            help += " " * (col_width - length)
+        help += kwargs["help"]
+    help_texts["options"] += help + "\n"
+
+    AddOption(*args, **kwargs)
+
+AddM5Option('--colors', dest='use_colors', action='store_true',
+            help="Add color to abbreviated scons output")
+AddM5Option('--no-colors', dest='use_colors', action='store_false',
+            help="Don't add color to abbreviated scons output")
+AddM5Option('--default', dest='default', type='string', action='store',
+            help='Override which build_opts file to use for defaults')
+AddM5Option('--ignore-style', dest='ignore_style', action='store_true',
+            help='Disable style checking hooks')
+AddM5Option('--update-ref', dest='update_ref', action='store_true',
+            help='Update test reference outputs')
+AddM5Option('--verbose', dest='verbose', action='store_true',
+            help='Print full tool command lines')
+
+use_colors = GetOption('use_colors')
+if use_colors:
+    from m5.util.terminal import termcap
+elif use_colors is None:
+    # option unspecified; default behavior is to use colors iff isatty
+    from m5.util.terminal import tty_termcap as termcap
+else:
+    from m5.util.terminal import no_termcap as termcap
+
 ########################################################################
 #
 # Set up the main build environment.
@@ -164,8 +210,8 @@ or your personal .hgrc
 style = %s/util/style.py
 
 [hooks]
-pretxncommit.style = python:style.check_whitespace
-pre-qrefresh.style = python:style.check_whitespace
+pretxncommit.style = python:style.check_style
+pre-qrefresh.style = python:style.check_style
 """ % (main.root)
 
 mercurial_bin_not_found = """
@@ -181,19 +227,11 @@ If you are actually a M5 developer, please fix this and
 run the style hook. It is important.
 """
 
-hg_info = "Unknown"
 if hgdir.exists():
-    # 1) Grab repository revision if we know it.
-    cmd = "hg id -n -i -t -b"
-    try:
-        hg_info = readCommand(cmd, cwd=main.root.abspath).strip()
-    except OSError:
-        print mercurial_bin_not_found
-
-    # 2) Ensure that the style hook is in place.
+    # Ensure that the style hook is in place.
     try:
         ui = None
-        if ARGUMENTS.get('IGNORE_STYLE') != 'True':
+        if not GetOption('ignore_style'):
             from mercurial import ui
             ui = ui.ui()
     except ImportError:
@@ -209,8 +247,6 @@ if hgdir.exists():
 else:
     print ".hg directory not found"
 
-main['HG_INFO'] = hg_info
-
 ###################################################
 #
 # Figure out which configurations to set up based on the path(s) of
@@ -305,43 +341,26 @@ def PathListAllExist(key, val, env):
         if not isdir(path):
             raise SCons.Errors.UserError("Path does not exist: '%s'" % path)
 
-global_sticky_vars_file = joinpath(build_root, 'variables.global')
+global_vars_file = joinpath(build_root, 'variables.global')
 
-global_sticky_vars = Variables(global_sticky_vars_file, args=ARGUMENTS)
-global_nonsticky_vars = Variables(args=ARGUMENTS)
+global_vars = Variables(global_vars_file, args=ARGUMENTS)
 
-global_sticky_vars.AddVariables(
+global_vars.AddVariables(
     ('CC', 'C compiler', environ.get('CC', main['CC'])),
     ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
     ('BATCH', 'Use batch pool for build and tests', False),
     ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
     ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
-    ('EXTRAS', 'Add Extra directories to the compilation', '',
+    ('EXTRAS', 'Add extra directories to the compilation', '',
      PathListAllExist, PathListMakeAbsolute),
     )
 
-global_nonsticky_vars.AddVariables(
-    ('VERBOSE', 'Print full tool command lines', False),
-    ('update_ref', 'Update test reference outputs', False)
-    )
-
-
-# base help text
-help_text = '''
-Usage: scons [scons options] [build options] [target(s)]
-
-Global sticky options:
-'''
-
-# Update main environment with values from ARGUMENTS & global_sticky_vars_file
-global_sticky_vars.Update(main)
-global_nonsticky_vars.Update(main)
-
-help_text += global_sticky_vars.GenerateHelpText(main)
-help_text += global_nonsticky_vars.GenerateHelpText(main)
+# Update main environment with values from ARGUMENTS & global_vars_file
+global_vars.Update(main)
+help_texts["global_vars"] += global_vars.GenerateHelpText(main)
 
 # Save sticky variable settings back to current variables file
-global_sticky_vars.Save(global_sticky_vars_file, main)
+global_vars.Save(global_vars_file, main)
 
 # Parse EXTRAS variable to build list of all directories where we're
 # look for sources etc.  This list is exported as base_dir_list.
@@ -357,7 +376,7 @@ Export('extras_dir_list')
 # the ext directory should be on the #includes path
 main.Append(CPPPATH=[Dir('ext')])
 
-def _STRIP(path, env):
+def strip_build_path(path, env):
     path = str(path)
     variant_base = env['BUILDROOT'] + os.path.sep
     if path.startswith(variant_base):
@@ -366,29 +385,94 @@ def _STRIP(path, env):
         path = path[6:]
     return path
 
-def _STRIP_SOURCE(target, source, env, for_signature):
-    return _STRIP(source[0], env)
-main['STRIP_SOURCE'] = _STRIP_SOURCE
-
-def _STRIP_TARGET(target, source, env, for_signature):
-    return _STRIP(target[0], env)
-main['STRIP_TARGET'] = _STRIP_TARGET
-
-if main['VERBOSE']:
+# Generate a string of the form:
+#   common/path/prefix/src1, src2 -> tgt1, tgt2
+# to print while building.
+class Transform(object):
+    # all specific color settings should be here and nowhere else
+    tool_color = termcap.Normal
+    pfx_color = termcap.Yellow
+    srcs_color = termcap.Yellow + termcap.Bold
+    arrow_color = termcap.Blue + termcap.Bold
+    tgts_color = termcap.Yellow + termcap.Bold
+
+    def __init__(self, tool, max_sources=99):
+        self.format = self.tool_color + (" [%8s] " % tool) \
+                      + self.pfx_color + "%s" \
+                      + self.srcs_color + "%s" \
+                      + self.arrow_color + " -> " \
+                      + self.tgts_color + "%s" \
+                      + termcap.Normal
+        self.max_sources = max_sources
+
+    def __call__(self, target, source, env, for_signature=None):
+        # truncate source list according to max_sources param
+        source = source[0:self.max_sources]
+        def strip(f):
+            return strip_build_path(str(f), env)
+        if len(source) > 0:
+            srcs = map(strip, source)
+        else:
+            srcs = ['']
+        tgts = map(strip, target)
+        # surprisingly, os.path.commonprefix is a dumb char-by-char string
+        # operation that has nothing to do with paths.
+        com_pfx = os.path.commonprefix(srcs + tgts)
+        com_pfx_len = len(com_pfx)
+        if com_pfx:
+            # do some cleanup and sanity checking on common prefix
+            if com_pfx[-1] == ".":
+                # prefix matches all but file extension: ok
+                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
+                com_pfx = com_pfx[0:-1]
+            elif com_pfx[-1] == "/":
+                # common prefix is directory path: OK
+                pass
+            else:
+                src0_len = len(srcs[0])
+                tgt0_len = len(tgts[0])
+                if src0_len == com_pfx_len:
+                    # source is a substring of target, OK
+                    pass
+                elif tgt0_len == com_pfx_len:
+                    # target is a substring of source, need to back up to
+                    # avoid empty string on RHS of arrow
+                    sep_idx = com_pfx.rfind(".")
+                    if sep_idx != -1:
+                        com_pfx = com_pfx[0:sep_idx]
+                    else:
+                        com_pfx = ''
+                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
+                    # still splitting at file extension: ok
+                    pass
+                else:
+                    # probably a fluke; ignore it
+                    com_pfx = ''
+        # recalculate length in case com_pfx was modified
+        com_pfx_len = len(com_pfx)
+        def fmt(files):
+            f = map(lambda s: s[com_pfx_len:], files)
+            return ', '.join(f)
+        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
+
+Export('Transform')
+
+
+if GetOption('verbose'):
     def MakeAction(action, string, *args, **kwargs):
         return Action(action, *args, **kwargs)
 else:
     MakeAction = Action
-    main['CCCOMSTR']        = ' [      CC] $STRIP_SOURCE'
-    main['CXXCOMSTR']       = ' [     CXX] $STRIP_SOURCE'
-    main['ASCOMSTR']        = ' [      AS] $STRIP_SOURCE'
-    main['SWIGCOMSTR']      = ' [    SWIG] $STRIP_SOURCE'
-    main['ARCOMSTR']        = ' [      AR] $STRIP_TARGET'
-    main['LINKCOMSTR']      = ' [    LINK] $STRIP_TARGET'
-    main['RANLIBCOMSTR']    = ' [  RANLIB] $STRIP_TARGET'
-    main['M4COMSTR']        = ' [      M4] $STRIP_TARGET'
-    main['SHCCCOMSTR']      = ' [    SHCC] $STRIP_TARGET'
-    main['SHCXXCOMSTR']     = ' [   SHCXX] $STRIP_TARGET'
+    main['CCCOMSTR']        = Transform("CC")
+    main['CXXCOMSTR']       = Transform("CXX")
+    main['ASCOMSTR']        = Transform("AS")
+    main['SWIGCOMSTR']      = Transform("SWIG")
+    main['ARCOMSTR']        = Transform("AR", 0)
+    main['LINKCOMSTR']      = Transform("LINK", 0)
+    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
+    main['M4COMSTR']        = Transform("M4")
+    main['SHCCCOMSTR']      = Transform("SHCC")
+    main['SHCXXCOMSTR']     = Transform("SHCXX")
 Export('MakeAction')
 
 CXX_version = readCommand([main['CXX'],'--version'], exception=False)
@@ -625,6 +709,16 @@ if not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
     print '       Please install zlib and try again.'
     Exit(1)
 
+# Check for librt.
+have_posix_clock = \
+    conf.CheckLibWithHeader(None, 'time.h', 'C',
+                            'clock_nanosleep(0,0,NULL,NULL);') or \
+    conf.CheckLibWithHeader('rt', 'time.h', 'C',
+                            'clock_nanosleep(0,0,NULL,NULL);')
+
+if not have_posix_clock:
+    print "Can't find library for POSIX clocks."
+
 # Check for <fenv.h> (C99 FP environment control)
 have_fenv = conf.CheckHeader('fenv.h', '<>')
 if not have_fenv:
@@ -728,8 +822,8 @@ sticky_vars.AddVariables(
                  sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
                  sorted(CpuModel.list)),
     BoolVariable('NO_FAST_ALLOC', 'Disable fast object allocator', False),
-    BoolVariable('FAST_ALLOC_DEBUG', 'Enable fast object allocator debugging',
-                 False),
+    BoolVariable('FORCE_FAST_ALLOC',
+                 'Enable fast object allocator, even for m5.debug', False),
     BoolVariable('FAST_ALLOC_STATS', 'Enable fast object allocator statistics',
                  False),
     BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
@@ -741,6 +835,7 @@ sticky_vars.AddVariables(
                  'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
                  False),
     BoolVariable('USE_MYSQL', 'Use MySQL for stats output', have_mysql),
+    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
     BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
     BoolVariable('USE_CHECKER', 'Use checker for detailed CPU models', False),
     BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
@@ -749,8 +844,9 @@ sticky_vars.AddVariables(
 
 # These variables get exported to #defines in config/*.hh (see src/SConscript).
 export_vars += ['FULL_SYSTEM', 'USE_FENV', 'USE_MYSQL',
-                'NO_FAST_ALLOC', 'FAST_ALLOC_DEBUG', 'FAST_ALLOC_STATS',
-                'SS_COMPATIBLE_FP', 'USE_CHECKER', 'TARGET_ISA', 'CP_ANNOTATE']
+                'NO_FAST_ALLOC', 'FORCE_FAST_ALLOC', 'FAST_ALLOC_STATS',
+                'SS_COMPATIBLE_FP', 'USE_CHECKER', 'TARGET_ISA', 'CP_ANNOTATE',
+                'USE_POSIX_CLOCK' ]
 
 ###################################################
 #
@@ -828,7 +924,7 @@ def make_switching_dir(dname, switch_headers, env):
     # action depends on; when env['ALL_ISA_LIST'] changes these actions
     # should get re-executed.
     switch_hdr_action = MakeAction(gen_switch_hdr,
-                     " [GENERATE] $STRIP_TARGET", varlist=['ALL_ISA_LIST'])
+                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
 
     # Instantiate actions for each header
     for hdr in switch_headers:
@@ -872,8 +968,10 @@ for variant_path in variant_paths:
         # Get default build variables from source tree.  Variables are
         # normally determined by name of $VARIANT_DIR, but can be
         # overriden by 'default=' arg on command line.
-        default_vars_file = joinpath('build_opts',
-                                     ARGUMENTS.get('default', variant_dir))
+        default = GetOption('default')
+        if not default:
+            default = variant_dir
+        default_vars_file = joinpath('build_opts', default)
         if isfile(default_vars_file):
             sticky_vars.files.append(default_vars_file)
             print "Variables file %s not found,\n  using defaults in %s" \
@@ -886,7 +984,8 @@ for variant_path in variant_paths:
     # Apply current variable settings to env
     sticky_vars.Update(env)
 
-    help_text += "\nSticky variables for %s:\n" % variant_dir \
+    help_texts["local_vars"] += \
+        "Build variables for %s:\n" % variant_dir \
                  + sticky_vars.GenerateHelpText(env)
 
     # Process variable settings.
@@ -931,4 +1030,15 @@ for variant_path in variant_paths:
                    variant_dir = joinpath(variant_path, 'tests', e.Label),
                    exports = { 'env' : e }, duplicate = False)
 
-Help(help_text)
+# base help text
+Help('''
+Usage: scons [scons options] [build variables] [target(s)]
+
+Extra scons options:
+%(options)s
+
+Global build variables:
+%(global_vars)s
+
+%(local_vars)s
+''' % help_texts)