base: Rename Flags::update as Flags::replace
[gem5.git] / src / SConscript
index 90f9b76831adf82cf7295b8a2421bfadaa00de63..b55f48532c6037473daf9b4fe203f956e65b80df 100644 (file)
@@ -1,6 +1,6 @@
 # -*- mode:python -*-
 
-# Copyright (c) 2018 ARM Limited
+# Copyright (c) 2018, 2020 ARM Limited
 #
 # The license below extends only to copyright in the software and shall
 # not be construed as granting a license to any other intellectual
@@ -41,6 +41,7 @@ from __future__ import print_function
 
 import array
 import bisect
+import distutils.spawn
 import functools
 import imp
 import os
@@ -65,7 +66,7 @@ Export('env')
 
 build_env = [(opt, env[opt]) for opt in export_vars]
 
-from m5.util import code_formatter, compareVersions
+from m5.util import code_formatter, compareVersions, readCommand
 
 ########################################################################
 # Code for adding source files of various types
@@ -386,6 +387,34 @@ class SimObject(PySource):
 
         bisect.insort_right(SimObject.modnames, self.modname)
 
+
+# This regular expression is simplistic and assumes that the import takes up
+# the entire line, doesn't have the keyword "public", uses double quotes, has
+# no whitespace at the end before or after the ;, and is all on one line. This
+# should still cover most cases, and a completely accurate scanner would be
+# MUCH more complex.
+protoc_import_re = re.compile(r'^import\s+\"(.*\.proto)\"\;$', re.M)
+
+def protoc_scanner(node, env, path):
+    deps = []
+    for imp in protoc_import_re.findall(node.get_text_contents()):
+        deps.append(Dir(env['BUILDDIR']).File(imp))
+    return deps
+
+env.Append(SCANNERS=Scanner(function=protoc_scanner, skeys=['.proto']))
+
+def protoc_emitter(target, source, env):
+    root, ext = os.path.splitext(source[0].get_abspath())
+    return [root + '.pb.cc', root + '.pb.h'], source
+
+env.Append(BUILDERS={'ProtoBufCC' : Builder(
+            action=MakeAction('${PROTOC} --cpp_out ${BUILDDIR} '
+                              '--proto_path ${BUILDDIR} '
+                              '${SOURCE.get_abspath()}',
+                              Transform("PROTOC")),
+            emitter=protoc_emitter
+        )})
+
 class ProtoBuf(SourceFile):
     '''Add a Protocol Buffer to build'''
 
@@ -393,14 +422,57 @@ class ProtoBuf(SourceFile):
         '''Specify the source file, and any tags'''
         super(ProtoBuf, self).__init__(source, tags, add_tags)
 
+        if not env['HAVE_PROTOC'] or not env['HAVE_PROTOBUF']:
+            error('Got protobuf to build, but lacks support!')
+
         # Get the file name and the extension
         modname,ext = self.extname
         assert ext == 'proto'
 
-        # Currently, we stick to generating the C++ headers, so we
-        # only need to track the source and header.
-        self.cc_file = File(modname + '.pb.cc')
-        self.hh_file = File(modname + '.pb.h')
+        self.cc_file, self.hh_file = env.ProtoBufCC(source=source)
+
+        # Add the C++ source file
+        Source(self.cc_file, tags=self.tags,
+                append={'CXXFLAGS': '-Wno-array-bounds'})
+
+
+
+env['PROTOC_GRPC'] = distutils.spawn.find_executable('grpc_cpp_plugin')
+if env['PROTOC_GRPC']:
+    env.Append(LIBS=['grpc++'])
+
+def protoc_grpc_emitter(target, source, env):
+    root, ext = os.path.splitext(source[0].get_abspath())
+    return [root + '.grpc.pb.cc', root + '.grpc.pb.h'], source
+
+env.Append(BUILDERS={'GrpcProtoBufCC' : Builder(
+            action=MakeAction('${PROTOC} --grpc_out ${BUILDDIR} '
+                              '--plugin=protoc-gen-grpc=${PROTOC_GRPC} '
+                              '--proto_path ${BUILDDIR} '
+                              '${SOURCE.get_abspath()}',
+                              Transform("PROTOC")),
+            emitter=protoc_grpc_emitter
+        )})
+
+class GrpcProtoBuf(SourceFile):
+    '''Add a GRPC protocol buffer to the build'''
+
+    def __init__(self, source, tags=None, add_tags=None):
+        '''Specify the source file, and any tags'''
+
+        super(GrpcProtoBuf, self).__init__(source, tags, add_tags)
+
+        if not env['PROTOC_GRPC']:
+            error('No grpc_cpp_plugin found')
+
+        self.cc_file, self.hh_file = env.GrpcProtoBufCC(source=source)
+
+        # We still need to build the normal protobuf code too.
+        self.protobuf = ProtoBuf(source, tags=self.tags)
+
+        # Add the C++ source file.
+        Source(self.cc_file, tags=self.tags,
+                append={'CXXFLAGS': '-Wno-array-bounds'})
 
 
 exectuable_classes = []
@@ -541,6 +613,7 @@ Export('Source')
 Export('PySource')
 Export('SimObject')
 Export('ProtoBuf')
+Export('GrpcProtoBuf')
 Export('Executable')
 Export('UnitTest')
 Export('GTest')
@@ -624,7 +697,7 @@ def makeTheISA(source, target, env):
     isas = [ src.get_contents().decode('utf-8') for src in source ]
     target_isa = env['TARGET_ISA']
     def define(isa):
-        return isa.upper() + '_ISA'
+        return str(isa.upper()) + '_ISA'
 
     def namespace(isa):
         return isa[0].upper() + isa[1:].lower() + 'ISA'
@@ -645,11 +718,8 @@ def makeTheISA(source, target, env):
     # create an enum for any run-time determination of the ISA, we
     # reuse the same name as the namespaces
     code('enum class Arch {')
-    for i,isa in enumerate(isas):
-        if i + 1 == len(isas):
-            code('  $0 = $1', namespace(isa), define(isa))
-        else:
-            code('  $0 = $1,', namespace(isa), define(isa))
+    for isa in isas:
+        code('  $0 = $1,', namespace(isa), define(isa))
     code('};')
 
     code('''
@@ -666,10 +736,10 @@ env.Command('config/the_isa.hh', list(map(Value, all_isa_list)),
             MakeAction(makeTheISA, Transform("CFG ISA", 0)))
 
 def makeTheGPUISA(source, target, env):
-    isas = [ src.get_contents() for src in source ]
+    isas = [ src.get_contents().decode('utf-8') for src in source ]
     target_gpu_isa = env['TARGET_GPU_ISA']
     def define(isa):
-        return isa.upper() + '_ISA'
+        return str(isa.upper()) + '_ISA'
 
     def namespace(isa):
         return isa[0].upper() + isa[1:].lower() + 'ISA'
@@ -690,11 +760,8 @@ def makeTheGPUISA(source, target, env):
     # create an enum for any run-time determination of the ISA, we
     # reuse the same name as the namespaces
     code('enum class GPUArch {')
-    for i,isa in enumerate(isas):
-        if i + 1 == len(isas):
-            code('  $0 = $1', namespace(isa), define(isa))
-        else:
-            code('  $0 = $1,', namespace(isa), define(isa))
+    for isa in isas:
+        code('  $0 = $1,', namespace(isa), define(isa))
     code('};')
 
     code('''
@@ -757,7 +824,7 @@ class DictImporter(object):
             return mod
 
         if fullname == 'm5.defines':
-            mod.__dict__['buildEnv'] = m5.util.SmartDict(build_env)
+            mod.__dict__['buildEnv'] = dict(build_env)
             return mod
 
         source = self.modules[fullname]
@@ -827,9 +894,10 @@ def makeDefinesPyFile(target, source, env):
 import _m5.core
 import m5.util
 
-buildEnv = m5.util.SmartDict($build_env)
+buildEnv = dict($build_env)
 
 compileDate = _m5.core.compileDate
+gem5Version = _m5.core.gem5Version
 _globals = globals()
 for key,val in _m5.core.__dict__.items():
     if key.startswith('flag_'):
@@ -921,9 +989,17 @@ def createSimObjectPyBindWrapper(target, source, env):
 # Generate all of the SimObject param C++ struct header files
 params_hh_files = []
 for name,simobj in sorted(sim_objects.items()):
+    # If this simobject's source changes, we need to regenerate the header.
     py_source = PySource.modules[simobj.__module__]
     extra_deps = [ py_source.tnode ]
 
+    # Get the params for just this SimObject, excluding base classes.
+    params = simobj._params.local.values()
+    # Extract the parameters' c++ types.
+    types = sorted(map(lambda p: p.ptype.cxx_type, params))
+    # If any of these types have changed, we need to regenerate the header.
+    extra_deps.append(Value(types))
+
     hh_file = File('params/%s.hh' % name)
     params_hh_files.append(hh_file)
     env.Command(hh_file, Value(name),
@@ -1013,24 +1089,6 @@ if env['USE_PYTHON']:
         env.Depends(cc_file, depends + extra_deps)
         Source(cc_file)
 
-# Build all protocol buffers if we have got protoc and protobuf available
-if env['HAVE_PROTOC'] and env['HAVE_PROTOBUF']:
-    for proto in ProtoBuf.all:
-        # Use both the source and header as the target, and the .proto
-        # file as the source. When executing the protoc compiler, also
-        # specify the proto_path to avoid having the generated files
-        # include the path.
-        env.Command([proto.cc_file, proto.hh_file], proto.tnode,
-                    MakeAction('${PROTOC} --cpp_out ${TARGET.dir} '
-                               '--proto_path ${SOURCE.dir} $SOURCE',
-                               Transform("PROTOC")))
-
-        # Add the C++ source file
-        Source(proto.cc_file, tags=proto.tags,
-                append={'CXXFLAGS': '-Wno-array-bounds'})
-elif ProtoBuf.all:
-    error('Got protobuf to build, but lacks support!')
-
 #
 # Handle debug flags
 #
@@ -1062,15 +1120,12 @@ namespace Debug {
         if not compound:
             code('SimpleFlag $name("$name", "$desc");')
         else:
-            comp_code('CompoundFlag $name("$name", "$desc",')
+            comp_code('CompoundFlag $name("$name", "$desc", {')
             comp_code.indent()
-            last = len(compound) - 1
-            for i,flag in enumerate(compound):
-                if i != last:
-                    comp_code('&$flag,')
-                else:
-                    comp_code('&$flag);')
+            for flag in compound:
+                comp_code('&$flag,')
             comp_code.dedent()
+            comp_code('});')
 
     code.append(comp_code)
     code()
@@ -1139,7 +1194,7 @@ env.AlwaysBuild(tags)
 # Build a small helper that marshals the Python code using the same
 # version of Python as gem5. This is in an unorthodox location to
 # avoid building it for every variant.
-py_marshal = env.Program('marshal', 'python/marshal.cc')[0]
+py_marshal = marshal_env.Program('marshal', 'python/marshal.cc')[0]
 
 # Embed python files.  All .py files that have been indicated by a
 # PySource() call in a SConscript need to be embedded into the M5
@@ -1195,8 +1250,8 @@ EmbeddedPython embedded_${sym}(
     code.write(str(target[0]))
 
 for source in PySource.all:
-    env.Command(source.cpp, [ py_marshal, source.tnode ],
-                MakeAction(embedPyFile, Transform("EMBED PY")))
+    marshal_env.Command(source.cpp, [ py_marshal, source.tnode ],
+                        MakeAction(embedPyFile, Transform("EMBED PY")))
     Source(source.cpp, tags=source.tags, add_tags='python')
 
 ########################################################################
@@ -1214,7 +1269,7 @@ gem5_binary = Gem5('gem5')
 # environment 'env' with modified object suffix and optional stripped
 # binary.  Additional keyword arguments are appended to corresponding
 # build environment vars.
-def makeEnv(env, label, objsfx, strip=False, disable_partial=False, **kwargs):
+def makeEnv(env, label, objsfx, strip=False, **kwargs):
     # SCons doesn't know to append a library suffix when there is a '.' in the
     # name.  Use '_' instead.
     libname = 'gem5_' + label
@@ -1246,6 +1301,19 @@ def makeEnv(env, label, objsfx, strip=False, disable_partial=False, **kwargs):
         group_static = [ s.static(new_env) for s in srcs ]
         group_shared = [ s.shared(new_env) for s in srcs ]
 
+        # Disable partial linking if mixing it with LTO is broken and LTO
+        # is enabled.
+        #
+        # Also, up until Apple LLVM version 10.0.0 (clang-1000.11.45.5),
+        # partial linked objects do not expose symbols that are marked with
+        # the hidden visibility and consequently building gem5 on Mac OS
+        # fails. As a workaround, we disable partial linking, however, we
+        # may want to revisit in the future.
+        broken_inc_lto = env.get('BROKEN_INCREMENTAL_LTO', False)
+        forced_lto = GetOption('force_lto')
+        darwin = (env['PLATFORM'] == 'darwin')
+        disable_partial = (broken_inc_lto and forced_lto) or darwin
+
         # If partial linking is disabled, add these sources to the build
         # directly, and short circuit this loop.
         if disable_partial:
@@ -1301,11 +1369,6 @@ def makeEnv(env, label, objsfx, strip=False, disable_partial=False, **kwargs):
     new_env.Command(secondary_exename, new_env.M5Binary,
             MakeAction('ln $SOURCE $TARGET', Transform("HARDLINK")))
 
-    # Set up regression tests.
-    SConscript(os.path.join(env.root.abspath, 'tests', 'SConscript'),
-               variant_dir=Dir('tests').Dir(new_env.Label),
-               exports={ 'env' : new_env }, duplicate=False)
-
 # Start out with the compiler flags common to all compilers,
 # i.e. they all use -g for opt and -g -pg for prof
 ccflags = {'debug' : [], 'opt' : ['-g'], 'fast' : [], 'prof' : ['-g', '-pg'],
@@ -1360,63 +1423,43 @@ def identifyTarget(t):
         return ext
     if ext in obj2target:
         return obj2target[ext]
-    match = re.search(r'/tests/([^/]+)/', t)
-    if match and match.group(1) in target_types:
-        return match.group(1)
     return 'all'
 
 needed_envs = [identifyTarget(target) for target in BUILD_TARGETS]
 if 'all' in needed_envs:
     needed_envs += target_types
 
-disable_partial = False
-if env['PLATFORM'] == 'darwin':
-    # Up until Apple LLVM version 10.0.0 (clang-1000.11.45.5), partial
-    # linked objects do not expose symbols that are marked with the
-    # hidden visibility and consequently building gem5 on Mac OS
-    # fails. As a workaround, we disable partial linking, however, we
-    # may want to revisit in the future.
-    disable_partial = True
-
 # Debug binary
 if 'debug' in needed_envs:
     makeEnv(env, 'debug', '.do',
             CCFLAGS = Split(ccflags['debug']),
             CPPDEFINES = ['DEBUG', 'TRACING_ON=1'],
-            LINKFLAGS = Split(ldflags['debug']),
-            disable_partial=disable_partial)
+            LINKFLAGS = Split(ldflags['debug']))
 
 # Optimized binary
 if 'opt' in needed_envs:
     makeEnv(env, 'opt', '.o',
             CCFLAGS = Split(ccflags['opt']),
             CPPDEFINES = ['TRACING_ON=1'],
-            LINKFLAGS = Split(ldflags['opt']),
-            disable_partial=disable_partial)
+            LINKFLAGS = Split(ldflags['opt']))
 
 # "Fast" binary
 if 'fast' in needed_envs:
-    disable_partial = disable_partial or \
-            (env.get('BROKEN_INCREMENTAL_LTO', False) and \
-            GetOption('force_lto'))
     makeEnv(env, 'fast', '.fo', strip = True,
             CCFLAGS = Split(ccflags['fast']),
             CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
-            LINKFLAGS = Split(ldflags['fast']),
-            disable_partial=disable_partial)
+            LINKFLAGS = Split(ldflags['fast']))
 
 # Profiled binary using gprof
 if 'prof' in needed_envs:
     makeEnv(env, 'prof', '.po',
             CCFLAGS = Split(ccflags['prof']),
             CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
-            LINKFLAGS = Split(ldflags['prof']),
-            disable_partial=disable_partial)
+            LINKFLAGS = Split(ldflags['prof']))
 
 # Profiled binary using google-pprof
 if 'perf' in needed_envs:
     makeEnv(env, 'perf', '.gpo',
             CCFLAGS = Split(ccflags['perf']),
             CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
-            LINKFLAGS = Split(ldflags['perf']),
-            disable_partial=disable_partial)
+            LINKFLAGS = Split(ldflags['perf']))