blob: b5505ff534ae5e2b7d5e7283abc687d74977c764 [file] [log] [blame]
Steve Reinhardtba2eae52006-05-22 14:29:33 -04001# -*- mode:python -*-
2
Ciro Santilliae7dd922020-01-15 16:11:30 +00003# Copyright (c) 2013, 2015-2020 ARM Limited
Andreas Hansson3ede4dc2013-07-18 08:29:28 -04004# All rights reserved.
5#
6# The license below extends only to copyright in the software and shall
7# not be construed as granting a license to any other intellectual
8# property including but not limited to intellectual property relating
9# to a hardware implementation of the functionality of the software
10# licensed hereunder. You may use the software subject to the license
11# terms below provided that you ensure that this notice is replicated
12# unmodified and in its entirety in all distributions of the software,
13# modified or unmodified, in source code or in binary form.
14#
Steve Reinhardtd650f412011-01-07 21:50:13 -080015# Copyright (c) 2011 Advanced Micro Devices, Inc.
Nathan Binkert312fbb12009-02-11 16:58:51 -080016# Copyright (c) 2009 The Hewlett-Packard Development Company
Steve Reinhardtba2eae52006-05-22 14:29:33 -040017# Copyright (c) 2004-2005 The Regents of The University of Michigan
18# All rights reserved.
19#
20# Redistribution and use in source and binary forms, with or without
21# modification, are permitted provided that the following conditions are
22# met: redistributions of source code must retain the above copyright
23# notice, this list of conditions and the following disclaimer;
24# redistributions in binary form must reproduce the above copyright
25# notice, this list of conditions and the following disclaimer in the
26# documentation and/or other materials provided with the distribution;
27# neither the name of the copyright holders nor the names of its
28# contributors may be used to endorse or promote products derived from
29# this software without specific prior written permission.
30#
31# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
32# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
33# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
34# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
35# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
36# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
37# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
38# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
41# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42
43###################################################
44#
45# SCons top-level build description (SConstruct) file.
46#
Steve Reinhardtf71a5c52012-03-02 13:53:52 -080047# While in this directory ('gem5'), just type 'scons' to build the default
Steve Reinhardtba2eae52006-05-22 14:29:33 -040048# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
Gabe Blackbc8d4922020-02-17 02:26:05 -080049# to build some other configuration (e.g., 'build/X86/gem5.opt' for
Steve Reinhardtba2eae52006-05-22 14:29:33 -040050# the optimized full-system version).
51#
Steve Reinhardtf71a5c52012-03-02 13:53:52 -080052# You can build gem5 in a different directory as long as there is a
Steve Reinhardtba2eae52006-05-22 14:29:33 -040053# 'build/<CONFIG>' somewhere along the target path. The build system
Steve Reinhardt7efd0ea2006-06-17 09:26:08 -040054# expects that all configs under the same build directory are being
Steve Reinhardtba2eae52006-05-22 14:29:33 -040055# built for the same host system.
56#
57# Examples:
Steve Reinhardt7efd0ea2006-06-17 09:26:08 -040058#
59# The following two commands are equivalent. The '-u' option tells
60# scons to search up the directory tree for this SConstruct file.
Gabe Blackbc8d4922020-02-17 02:26:05 -080061# % cd <path-to-src>/gem5 ; scons build/X86/gem5.debug
62# % cd <path-to-src>/gem5/build/X86; scons -u gem5.debug
Steve Reinhardt7efd0ea2006-06-17 09:26:08 -040063#
64# The following two commands are equivalent and demonstrate building
65# in a directory outside of the source tree. The '-C' option tells
66# scons to chdir to the specified directory to find this SConstruct
67# file.
Gabe Blackbc8d4922020-02-17 02:26:05 -080068# % cd <path-to-src>/gem5 ; scons /local/foo/build/X86/gem5.debug
69# % cd /local/foo/build/X86; scons -C <path-to-src>/gem5 gem5.debug
Steve Reinhardtba2eae52006-05-22 14:29:33 -040070#
71# You can use 'scons -H' to print scons options. If you're in this
Steve Reinhardtf71a5c52012-03-02 13:53:52 -080072# 'gem5' directory (or use -u or -C to tell scons where to find this
73# file), you can use 'scons -h' to print all the gem5-specific build
Steve Reinhardtba2eae52006-05-22 14:29:33 -040074# options as well.
75#
76###################################################
77
Gabe Black0bb50e62018-03-05 22:05:47 -080078from __future__ import print_function
79
Nathan Binkert9a8cb7d2009-09-22 15:24:16 -070080# Global Python includes
Gabe Black1c595592020-03-26 04:48:53 -070081import atexit
Curtis Dunhamfe27f932014-05-09 18:58:47 -040082import itertools
Steve Reinhardtba2eae52006-05-22 14:29:33 -040083import os
Ali Saidid9d79ce2008-04-07 23:40:23 -040084import re
Andreas Sandberg7277def2016-03-30 15:29:42 +010085import shutil
Nathan Binkertdd6ea872009-02-09 20:10:14 -080086import subprocess
87import sys
Nathan Binkert1aef5c02007-03-10 23:00:54 -080088
Nathan Binkertdd6ea872009-02-09 20:10:14 -080089from os import mkdir, environ
90from os.path import abspath, basename, dirname, expanduser, normpath
91from os.path import exists, isdir, isfile
92from os.path import join as joinpath, split as splitpath
Andrea Mondelliad9a2332019-01-10 10:33:13 -050093from re import match
Steve Reinhardtba2eae52006-05-22 14:29:33 -040094
Nathan Binkert9a8cb7d2009-09-22 15:24:16 -070095# SCons includes
Steve Reinhardt785eb132007-11-16 20:10:33 -080096import SCons
Nathan Binkert312fbb12009-02-11 16:58:51 -080097import SCons.Node
Gabe Black91195ae2019-03-12 05:00:41 -070098import SCons.Node.FS
Steve Reinhardt785eb132007-11-16 20:10:33 -080099
Jason Lowe-Power0bc5d772020-05-06 17:38:41 -0700100from m5.util import compareVersions, readCommand, readCommandWithReturn
Ali Saidid9d79ce2008-04-07 23:40:23 -0400101
Gabe Black08ab4572020-08-03 21:38:55 -0700102AddOption('--colors', dest='use_colors', action='store_true',
103 help="Add color to abbreviated scons output")
104AddOption('--no-colors', dest='use_colors', action='store_false',
105 help="Don't add color to abbreviated scons output")
106AddOption('--with-cxx-config', action='store_true',
107 help="Build with support for C++-based configuration")
108AddOption('--default',
109 help='Override which build_opts file to use for defaults')
110AddOption('--ignore-style', action='store_true',
111 help='Disable style checking hooks')
112AddOption('--gold-linker', action='store_true', help='Use the gold linker')
113AddOption('--no-lto', action='store_true',
114 help='Disable Link-Time Optimization for fast')
115AddOption('--force-lto', action='store_true',
116 help='Use Link-Time Optimization instead of partial linking' +
117 ' when the compiler doesn\'t support using them together.')
118AddOption('--verbose', action='store_true',
119 help='Print full tool command lines')
120AddOption('--without-python', action='store_true',
121 help='Build without Python configuration support')
122AddOption('--without-tcmalloc', action='store_true',
123 help='Disable linking against tcmalloc')
124AddOption('--with-ubsan', action='store_true',
125 help='Build with Undefined Behavior Sanitizer if available')
126AddOption('--with-asan', action='store_true',
127 help='Build with Address Sanitizer if available')
128AddOption('--with-systemc-tests', action='store_true',
129 help='Build systemc tests')
Gabe Blackfa448122011-03-03 23:54:31 -0800130
Gabe Black1c595592020-03-26 04:48:53 -0700131from gem5_scons import Transform, error, warning, summarize_warnings
Gabe Black80283482019-11-18 17:41:49 -0800132
Gabe Black670436b2017-06-05 22:23:18 -0700133if GetOption('no_lto') and GetOption('force_lto'):
Gabe Black80283482019-11-18 17:41:49 -0800134 error('--no-lto and --force-lto are mutually exclusive')
Gabe Black670436b2017-06-05 22:23:18 -0700135
Nathan Binkert312fbb12009-02-11 16:58:51 -0800136########################################################################
137#
Nathan Binkert05d8c9a2009-04-21 17:17:16 -0700138# Set up the main build environment.
Nathan Binkert312fbb12009-02-11 16:58:51 -0800139#
140########################################################################
Stan Czerniawskic2553742013-10-17 10:20:45 -0500141
Gabe Blacka4e5d2c2020-12-18 09:40:09 -0800142main = Environment(tools=['default', 'git'])
Steve Reinhardtba2eae52006-05-22 14:29:33 -0400143
Gabe Black49cf9fd2017-11-08 19:59:04 -0800144from gem5_scons.util import get_termcap
145termcap = get_termcap()
146
Andreas Hansson166afc42012-09-21 10:11:22 -0400147main_dict_keys = main.Dictionary().keys()
148
149# Check that we have a C/C++ compiler
150if not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
Gabe Black80283482019-11-18 17:41:49 -0800151 error("No C++ compiler installed (package g++ on Ubuntu and RedHat)")
Andreas Hansson166afc42012-09-21 10:11:22 -0400152
Steve Reinhardtba2eae52006-05-22 14:29:33 -0400153###################################################
154#
155# Figure out which configurations to set up based on the path(s) of
156# the target(s).
157#
158###################################################
159
160# Find default configuration & binary.
Gabe Blackbc8d4922020-02-17 02:26:05 -0800161Default(environ.get('M5_DEFAULT_BINARY', 'build/ARM/gem5.debug'))
Steve Reinhardtba2eae52006-05-22 14:29:33 -0400162
Steve Reinhardtba2eae52006-05-22 14:29:33 -0400163# helper function: find last occurrence of element in list
164def rfind(l, elt, offs = -1):
165 for i in range(len(l)+offs, 0, -1):
166 if l[i] == elt:
167 return i
Gabe Blacka39c8db2019-12-02 17:52:44 -0800168 raise ValueError("element not found")
Steve Reinhardtba2eae52006-05-22 14:29:33 -0400169
Steve Reinhardt8ce85d32011-05-02 12:40:32 -0700170# Take a list of paths (or SCons Nodes) and return a list with all
171# paths made absolute and ~-expanded. Paths will be interpreted
172# relative to the launch directory unless a different root is provided
173def makePathListAbsolute(path_list, root=GetLaunchDir()):
174 return [abspath(joinpath(root, expanduser(str(p))))
175 for p in path_list]
176
Steve Reinhardtba2eae52006-05-22 14:29:33 -0400177# Each target must have 'build' in the interior of the path; the
178# directory below this will determine the build parameters. For
Gabe Blackbc8d4922020-02-17 02:26:05 -0800179# example, for target 'foo/bar/build/X86/arch/x86/blah.do' we
180# recognize that X86 specifies the configuration because it
Steve Reinhardt8ce85d32011-05-02 12:40:32 -0700181# follow 'build' in the build path.
Steve Reinhardtba2eae52006-05-22 14:29:33 -0400182
Steve Reinhardt8ce85d32011-05-02 12:40:32 -0700183# The funky assignment to "[:]" is needed to replace the list contents
184# in place rather than reassign the symbol to a new list, which
185# doesn't work (obviously!).
186BUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
Steve Reinhardt51e36882006-12-04 09:09:36 -0800187
Steve Reinhardta7c95f72006-05-22 21:51:59 -0400188# Generate a list of the unique build roots and configs that the
189# collected targets reference.
Nathan Binkertdd6ea872009-02-09 20:10:14 -0800190variant_paths = []
Steve Reinhardt20051d42006-05-22 22:37:56 -0400191build_root = None
Steve Reinhardt8ce85d32011-05-02 12:40:32 -0700192for t in BUILD_TARGETS:
Steve Reinhardtba2eae52006-05-22 14:29:33 -0400193 path_dirs = t.split('/')
194 try:
195 build_top = rfind(path_dirs, 'build', -2)
196 except:
Gabe Black80283482019-11-18 17:41:49 -0800197 error("No non-leaf 'build' dir found on target path.", t)
Steve Reinhardt6ae75ac2006-12-04 08:55:06 -0800198 this_build_root = joinpath('/',*path_dirs[:build_top+1])
Steve Reinhardt20051d42006-05-22 22:37:56 -0400199 if not build_root:
200 build_root = this_build_root
201 else:
202 if this_build_root != build_root:
Gabe Black80283482019-11-18 17:41:49 -0800203 error("build targets not under same build root\n"
Gabe Black0bb50e62018-03-05 22:05:47 -0800204 " %s\n %s" % (build_root, this_build_root))
Nathan Binkertdd6ea872009-02-09 20:10:14 -0800205 variant_path = joinpath('/',*path_dirs[:build_top+2])
206 if variant_path not in variant_paths:
207 variant_paths.append(variant_path)
Steve Reinhardtba2eae52006-05-22 14:29:33 -0400208
Steve Reinhardtd725ff42008-02-05 17:40:08 -0800209# Make sure build_root exists (might not if this is the first build there)
210if not isdir(build_root):
Nathan Binkertdd6ea872009-02-09 20:10:14 -0800211 mkdir(build_root)
Ali Saidid4767f42010-11-15 14:04:04 -0600212main['BUILDROOT'] = build_root
Steve Reinhardtd725ff42008-02-05 17:40:08 -0800213
Nathan Binkert05d8c9a2009-04-21 17:17:16 -0700214Export('main')
Ali Saidi01934762007-05-30 17:08:12 -0400215
Nathan Binkert05d8c9a2009-04-21 17:17:16 -0700216main.SConsignFile(joinpath(build_root, "sconsign"))
Steve Reinhardtba2eae52006-05-22 14:29:33 -0400217
Steve Reinhardt29e34a72006-06-09 23:01:31 -0400218# Default duplicate option is to use hard links, but this messes up
219# when you use emacs to edit a file in the target dir, as emacs moves
220# file to file~ then copies to file, breaking the link. Symbolic
221# (soft) links work better.
Nathan Binkert05d8c9a2009-04-21 17:17:16 -0700222main.SetOption('duplicate', 'soft-copy')
Steve Reinhardt29e34a72006-06-09 23:01:31 -0400223
Steve Reinhardtd725ff42008-02-05 17:40:08 -0800224#
Nathan Binkertdd6ea872009-02-09 20:10:14 -0800225# Set up global sticky variables... these are common to an entire build
Gabe Blackbc8d4922020-02-17 02:26:05 -0800226# tree (not specific to a particular build like X86)
Steve Reinhardtd725ff42008-02-05 17:40:08 -0800227#
228
Gabe Blackfa448122011-03-03 23:54:31 -0800229global_vars_file = joinpath(build_root, 'variables.global')
Steve Reinhardtd725ff42008-02-05 17:40:08 -0800230
Gabe Blackfa448122011-03-03 23:54:31 -0800231global_vars = Variables(global_vars_file, args=ARGUMENTS)
Steve Reinhardtd725ff42008-02-05 17:40:08 -0800232
Gabe Blackfa448122011-03-03 23:54:31 -0800233global_vars.AddVariables(
Nathan Binkert05d8c9a2009-04-21 17:17:16 -0700234 ('CC', 'C compiler', environ.get('CC', main['CC'])),
235 ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
Ciro Santilliec502252019-05-21 13:19:24 +0100236 ('CCFLAGS_EXTRA', 'Extra C and C++ compiler flags', ''),
237 ('LDFLAGS_EXTRA', 'Extra linker flags', ''),
Giacomo Travaglinia1b64712020-06-04 12:45:52 +0100238 ('MARSHAL_CCFLAGS_EXTRA', 'Extra C and C++ marshal compiler flags', ''),
239 ('MARSHAL_LDFLAGS_EXTRA', 'Extra marshal linker flags', ''),
Andreas Sandberga3c81f92019-01-25 11:14:29 +0000240 ('PYTHON_CONFIG', 'Python config binary to use',
Andreas Sandberg4af84812020-10-23 10:49:43 +0100241 [ 'python3-config', 'python-config']
Bobby R. Bruce5eb9cdd2020-09-28 11:23:38 -0700242 ),
Andreas Hansson41f228c2013-01-07 13:05:37 -0500243 ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
Ali Saidibee4d452008-04-07 23:40:24 -0400244 ('BATCH', 'Use batch pool for build and tests', False),
245 ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
Ali Saidi5fcf4422010-11-08 13:58:24 -0600246 ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
Steve Reinhardt8ce85d32011-05-02 12:40:32 -0700247 ('EXTRAS', 'Add extra directories to the compilation', '')
Nathan Binkertcf6b4ef2009-05-11 10:38:46 -0700248 )
Steve Reinhardtd725ff42008-02-05 17:40:08 -0800249
Gabe Blackfa448122011-03-03 23:54:31 -0800250# Update main environment with values from ARGUMENTS & global_vars_file
251global_vars.Update(main)
Gabe Black08ab4572020-08-03 21:38:55 -0700252Help('''
253Global build variables:
254{help}
255'''.format(help=global_vars.GenerateHelpText(main)), append=True)
Gabe Blackde904a62010-01-17 02:22:30 -0800256
Nathan Binkertdd6ea872009-02-09 20:10:14 -0800257# Save sticky variable settings back to current variables file
Gabe Blackfa448122011-03-03 23:54:31 -0800258global_vars.Save(global_vars_file, main)
Steve Reinhardtd725ff42008-02-05 17:40:08 -0800259
Nathan Binkertdd6ea872009-02-09 20:10:14 -0800260# Parse EXTRAS variable to build list of all directories where we're
Steve Reinhardt8ce85d32011-05-02 12:40:32 -0700261# look for sources etc. This list is exported as extras_dir_list.
Gabe Blacka4e5d2c2020-12-18 09:40:09 -0800262base_dir = Dir('#src').abspath
Nathan Binkert05d8c9a2009-04-21 17:17:16 -0700263if main['EXTRAS']:
Steve Reinhardt8ce85d32011-05-02 12:40:32 -0700264 extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
Nathan Binkert4d64d762008-11-10 11:51:18 -0800265else:
266 extras_dir_list = []
Steve Reinhardtd725ff42008-02-05 17:40:08 -0800267
Nathan Binkert4d64d762008-11-10 11:51:18 -0800268Export('base_dir')
269Export('extras_dir_list')
Steve Reinhardtd725ff42008-02-05 17:40:08 -0800270
Nathan Binkerta102f842009-03-17 12:49:03 -0700271# the ext directory should be on the #includes path
Nathan Binkert05d8c9a2009-04-21 17:17:16 -0700272main.Append(CPPPATH=[Dir('ext')])
Nathan Binkerta102f842009-03-17 12:49:03 -0700273
Andreas Sandbergf2d0adf2017-07-27 15:08:05 +0100274# Add shared top-level headers
275main.Prepend(CPPPATH=Dir('include'))
276
Gabe Blackfa448122011-03-03 23:54:31 -0800277if GetOption('verbose'):
Ali Saidid4767f42010-11-15 14:04:04 -0600278 def MakeAction(action, string, *args, **kwargs):
279 return Action(action, *args, **kwargs)
280else:
281 MakeAction = Action
Steve Reinhardtd650f412011-01-07 21:50:13 -0800282 main['CCCOMSTR'] = Transform("CC")
283 main['CXXCOMSTR'] = Transform("CXX")
284 main['ASCOMSTR'] = Transform("AS")
Steve Reinhardtd650f412011-01-07 21:50:13 -0800285 main['ARCOMSTR'] = Transform("AR", 0)
286 main['LINKCOMSTR'] = Transform("LINK", 0)
Gabe Black334b1e52017-04-28 03:49:24 -0700287 main['SHLINKCOMSTR'] = Transform("SHLINK", 0)
Steve Reinhardtd650f412011-01-07 21:50:13 -0800288 main['RANLIBCOMSTR'] = Transform("RANLIB", 0)
289 main['M4COMSTR'] = Transform("M4")
290 main['SHCCCOMSTR'] = Transform("SHCC")
291 main['SHCXXCOMSTR'] = Transform("SHCXX")
Ali Saidid4767f42010-11-15 14:04:04 -0600292Export('MakeAction')
293
Andreas Hanssond1f3a3b2012-09-14 12:13:22 -0400294# Initialize the Link-Time Optimization (LTO) flags
295main['LTO_CCFLAGS'] = []
296main['LTO_LDFLAGS'] = []
297
Andreas Sandberg468ad102013-03-18 10:57:26 +0100298# According to the readme, tcmalloc works best if the compiler doesn't
299# assume that we're using the builtin malloc and friends. These flags
300# are compiler-specific, so we need to set them after we detect which
301# compiler we're using.
302main['TCMALLOC_CCFLAGS'] = []
303
Nathan Binkert9a8cb7d2009-09-22 15:24:16 -0700304CXX_version = readCommand([main['CXX'],'--version'], exception=False)
305CXX_V = readCommand([main['CXX'],'-V'], exception=False)
Nathan Binkert312fbb12009-02-11 16:58:51 -0800306
Nathan Binkert05d8c9a2009-04-21 17:17:16 -0700307main['GCC'] = CXX_version and CXX_version.find('g++') >= 0
Andreas Hanssonb6aa6d52012-04-14 05:43:31 -0400308main['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
Andreas Hansson22130232013-01-07 13:05:39 -0500309if main['GCC'] + main['CLANG'] > 1:
Gabe Black80283482019-11-18 17:41:49 -0800310 error('Two compilers enabled at once?')
Ali Saidi63fdabf2007-01-26 18:48:51 -0500311
Steve Reinhardtba2eae52006-05-22 14:29:33 -0400312# Set up default C++ compiler flags
Andreas Hansson08a5fd32013-02-19 05:56:07 -0500313if main['GCC'] or main['CLANG']:
314 # As gcc and clang share many flags, do the common parts here
315 main.Append(CCFLAGS=['-pipe'])
316 main.Append(CCFLAGS=['-fno-strict-aliasing'])
Andreas Hansson12eb0342016-01-11 05:52:20 -0500317 # Enable -Wall and -Wextra and then disable the few warnings that
318 # we consistently violate
319 main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
320 '-Wno-sign-compare', '-Wno-unused-parameter'])
Gabe Blackdcffee02020-09-17 22:33:37 -0700321 # We always compile using C++14
322 main.Append(CXXFLAGS=['-std=c++14'])
Bjoern A. Zeebe07f0c52017-02-09 19:00:00 -0500323 if sys.platform.startswith('freebsd'):
324 main.Append(CCFLAGS=['-I/usr/local/include'])
325 main.Append(CXXFLAGS=['-I/usr/local/include'])
Gabe Black45765412017-04-28 03:57:09 -0700326
Nikos Nikoleris25620a72020-04-23 20:07:51 +0100327 # On Mac OS X/Darwin the default linker doesn't support the
328 # option --as-needed
329 if sys.platform != "darwin":
330 main.Append(LINKFLAGS='-Wl,--as-needed')
Gabe Black45765412017-04-28 03:57:09 -0700331 main['FILTER_PSHLINKFLAGS'] = lambda x: str(x).replace(' -shared', '')
332 main['PSHLINKFLAGS'] = main.subst('${FILTER_PSHLINKFLAGS(SHLINKFLAGS)}')
Ciro Santillifafe4e82018-11-07 00:00:00 +0000333 if GetOption('gold_linker'):
334 main.Append(LINKFLAGS='-fuse-ld=gold')
Ciro Santilliae7dd922020-01-15 16:11:30 +0000335 main['PLINKFLAGS'] = main.get('LINKFLAGS')
Gabe Black32fd8902017-05-03 00:37:19 -0700336 shared_partial_flags = ['-r', '-nostdlib']
Gabe Black45765412017-04-28 03:57:09 -0700337 main.Append(PSHLINKFLAGS=shared_partial_flags)
338 main.Append(PLINKFLAGS=shared_partial_flags)
Gabe Black08d60882017-11-20 18:26:29 -0800339
Bobby R. Brucec0ae17c2020-09-30 20:53:14 -0700340 # Treat warnings as errors but white list some warnings that we
341 # want to allow (e.g., deprecation warnings).
342 main.Append(CCFLAGS=['-Werror',
343 '-Wno-error=deprecated-declarations',
344 '-Wno-error=deprecated',
345 ])
Andreas Hansson08a5fd32013-02-19 05:56:07 -0500346else:
Gabe Black38e46032020-02-07 17:27:02 -0800347 error('\n'.join((
Gabe Black80283482019-11-18 17:41:49 -0800348 "Don't know what compiler options to use for your compiler.",
349 "compiler: " + main['CXX'],
350 "version: " + CXX_version.replace('\n', '<nl>') if
351 CXX_version else 'COMMAND NOT FOUND!',
352 "If you're trying to use a compiler other than GCC",
353 "or clang, there appears to be something wrong with your",
354 "environment.",
355 "",
356 "If you are trying to use a compiler other than those listed",
357 "above you will need to ease fix SConstruct and ",
Gabe Black38e46032020-02-07 17:27:02 -0800358 "src/SConscript to support that compiler.")))
Andreas Hansson08a5fd32013-02-19 05:56:07 -0500359
Nathan Binkert05d8c9a2009-04-21 17:17:16 -0700360if main['GCC']:
Andreas Hansson406891c2013-01-07 13:05:39 -0500361 gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
Bobby R. Brucea1a2edd2020-08-28 18:28:23 -0700362 if compareVersions(gcc_version, "5") < 0:
363 error('gcc version 5 or newer required.\n'
Gabe Black80283482019-11-18 17:41:49 -0800364 'Installed version:', gcc_version)
Andreas Hansson406891c2013-01-07 13:05:39 -0500365 Exit(1)
366
367 main['GCC_VERSION'] = gcc_version
Andreas Hansson406891c2013-01-07 13:05:39 -0500368
Bobby R. Brucea1a2edd2020-08-28 18:28:23 -0700369 # Incremental linking with LTO is currently broken in gcc versions
370 # 4.9 and above. A version where everything works completely hasn't
371 # yet been identified.
372 #
373 # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67548
374 main['BROKEN_INCREMENTAL_LTO'] = True
375
Bobby R. Bruce6a54bb72020-05-18 10:09:52 -0700376 if compareVersions(gcc_version, '6.0') >= 0:
Gabe Black670436b2017-06-05 22:23:18 -0700377 # gcc versions 6.0 and greater accept an -flinker-output flag which
378 # selects what type of output the linker should generate. This is
379 # necessary for incremental lto to work, but is also broken in
Bobby R. Bruce6a54bb72020-05-18 10:09:52 -0700380 # current versions of gcc. It may not be necessary in future
381 # versions. We add it here since it might be, and as a reminder that
382 # it exists. It's excluded if lto is being forced.
Gabe Black670436b2017-06-05 22:23:18 -0700383 #
384 # https://gcc.gnu.org/gcc-6/changes.html
385 # https://gcc.gnu.org/ml/gcc-patches/2015-11/msg03161.html
386 # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69866
Bobby R. Bruce6a54bb72020-05-18 10:09:52 -0700387 if not GetOption('force_lto'):
388 main.Append(PSHLINKFLAGS='-flinker-output=rel')
389 main.Append(PLINKFLAGS='-flinker-output=rel')
Gabe Black670436b2017-06-05 22:23:18 -0700390
Gabe Black670436b2017-06-05 22:23:18 -0700391 disable_lto = GetOption('no_lto')
392 if not disable_lto and main.get('BROKEN_INCREMENTAL_LTO', False) and \
393 not GetOption('force_lto'):
Gabe Blackec236a52020-03-26 03:47:38 -0700394 warning('Your compiler doesn\'t support incremental linking and lto '
395 'at the same time, so lto is being disabled. To force lto on '
396 'anyway, use the --force-lto option. That will disable '
Gabe Black80283482019-11-18 17:41:49 -0800397 'partial linking.')
Gabe Black670436b2017-06-05 22:23:18 -0700398 disable_lto = True
399
Andreas Hanssonfdb965f2014-06-10 17:44:39 -0400400 # Add the appropriate Link-Time Optimization (LTO) flags
401 # unless LTO is explicitly turned off. Note that these flags
402 # are only used by the fast target.
Gabe Black670436b2017-06-05 22:23:18 -0700403 if not disable_lto:
Andreas Hanssonfdb965f2014-06-10 17:44:39 -0400404 # Pass the LTO flag when compiling to produce GIMPLE
405 # output, we merely create the flags here and only append
Andreas Hanssondeb22002014-09-27 09:08:34 -0400406 # them later
Andreas Hanssonfdb965f2014-06-10 17:44:39 -0400407 main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
Andreas Hanssond1f3a3b2012-09-14 12:13:22 -0400408
Andreas Hanssonfdb965f2014-06-10 17:44:39 -0400409 # Use the same amount of jobs for LTO as we are running
Andreas Hanssondeb22002014-09-27 09:08:34 -0400410 # scons with
411 main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
Andreas Hanssond1f3a3b2012-09-14 12:13:22 -0400412
Andreas Sandberg468ad102013-03-18 10:57:26 +0100413 main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
414 '-fno-builtin-realloc', '-fno-builtin-free'])
415
Koan-Sin Tan7d4f1872012-01-31 12:05:52 -0500416elif main['CLANG']:
417 clang_version_re = re.compile(".* version (\d+\.\d+)")
Mitch Hayenga7084e312014-03-07 15:56:23 -0500418 clang_version_match = clang_version_re.search(CXX_version)
Koan-Sin Tan7d4f1872012-01-31 12:05:52 -0500419 if (clang_version_match):
420 clang_version = clang_version_match.groups()[0]
Gabe Blacka83316e2020-09-17 22:31:50 -0700421 if compareVersions(clang_version, "3.9") < 0:
422 error('clang version 3.9 or newer required.\n'
Gabe Black80283482019-11-18 17:41:49 -0800423 'Installed version:', clang_version)
Koan-Sin Tan7d4f1872012-01-31 12:05:52 -0500424 else:
Gabe Black80283482019-11-18 17:41:49 -0800425 error('Unable to determine clang version.')
Koan-Sin Tan7d4f1872012-01-31 12:05:52 -0500426
Andreas Hansson12eb0342016-01-11 05:52:20 -0500427 # clang has a few additional warnings that we disable, extraneous
Andreas Hansson08a5fd32013-02-19 05:56:07 -0500428 # parantheses are allowed due to Ruby's printing of the AST,
429 # finally self assignments are allowed as the generated CPU code
430 # is relying on this
Andreas Hansson12eb0342016-01-11 05:52:20 -0500431 main.Append(CCFLAGS=['-Wno-parentheses',
Andreas Sandberg6b908212014-08-13 06:57:28 -0400432 '-Wno-self-assign',
433 # Some versions of libstdc++ (4.8?) seem to
434 # use struct hash and class hash
435 # interchangeably.
436 '-Wno-mismatched-tags',
437 ])
Nikos Nikoleris6bd0a392020-08-31 08:19:09 +0300438 if sys.platform != "darwin" and \
439 compareVersions(clang_version, "10.0") >= 0:
Gabe Black92711fe2020-02-09 20:03:58 -0800440 main.Append(CCFLAGS=['-Wno-c99-designator'])
Andreas Hansson08a5fd32013-02-19 05:56:07 -0500441
Bobby R. Bruce1f292ed2020-05-26 15:11:59 -0700442 if compareVersions(clang_version, "8.0") >= 0:
443 main.Append(CCFLAGS=['-Wno-defaulted-function-deleted'])
444
Andreas Sandberg468ad102013-03-18 10:57:26 +0100445 main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
446
Andreas Hansson406891c2013-01-07 13:05:39 -0500447 # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
Andreas Hanssonfdf6f6c2013-09-04 13:22:54 -0400448 # opposed to libstdc++, as the later is dated.
449 if sys.platform == "darwin":
450 main.Append(CXXFLAGS=['-stdlib=libc++'])
451 main.Append(LIBS=['c++'])
Andreas Hanssonb6aa6d52012-04-14 05:43:31 -0400452
Bjoern A. Zeebe07f0c52017-02-09 19:00:00 -0500453 # On FreeBSD we need libthr.
454 if sys.platform.startswith('freebsd'):
455 main.Append(LIBS=['thr'])
456
Nikos Nikoleris8f5b7e72019-12-20 12:41:40 +0000457# Add sanitizers flags
458sanitizers=[]
459if GetOption('with_ubsan'):
Bobby R. Brucea1a2edd2020-08-28 18:28:23 -0700460 sanitizers.append('undefined')
Nikos Nikoleris8f5b7e72019-12-20 12:41:40 +0000461if GetOption('with_asan'):
Bobby R. Brucea1a2edd2020-08-28 18:28:23 -0700462 # Available for gcc >= 5 or llvm >= 3.1 both a requirement
Nikos Nikoleris8f5b7e72019-12-20 12:41:40 +0000463 # by the build system
464 sanitizers.append('address')
Gabe Blackb5a3c0d2020-03-26 03:20:41 -0700465 suppressions_file = Dir('util').File('lsan-suppressions').get_abspath()
466 suppressions_opt = 'suppressions=%s' % suppressions_file
467 main['ENV']['LSAN_OPTIONS'] = ':'.join([suppressions_opt,
468 'print_suppressions=0'])
469 print()
470 warning('To suppress false positive leaks, set the LSAN_OPTIONS '
471 'environment variable to "%s" when running gem5' %
472 suppressions_opt)
473 warning('LSAN_OPTIONS=suppressions=%s' % suppressions_opt)
474 print()
Nikos Nikoleris8f5b7e72019-12-20 12:41:40 +0000475if sanitizers:
476 sanitizers = ','.join(sanitizers)
477 if main['GCC'] or main['CLANG']:
478 main.Append(CCFLAGS=['-fsanitize=%s' % sanitizers,
Earl Oua1e5fcc2018-09-07 15:16:53 +0800479 '-fno-omit-frame-pointer'],
Nikos Nikoleris8f5b7e72019-12-20 12:41:40 +0000480 LINKFLAGS='-fsanitize=%s' % sanitizers)
481 else:
482 warning("Don't know how to enable %s sanitizer(s) for your "
483 "compiler." % sanitizers)
Gabe Black316ef3d2017-11-20 18:21:19 -0800484
Nathan Binkert7311fd72009-05-11 10:38:46 -0700485# Set up common yacc/bison flags (needed for Ruby)
486main['YACCFLAGS'] = '-d'
487main['YACCHXXFILESUFFIX'] = '.hh'
488
Ali Saidibee4d452008-04-07 23:40:24 -0400489# Do this after we save setting back, or else we'll tack on an
490# extra 'qdo' every time we run scons.
Nathan Binkert05d8c9a2009-04-21 17:17:16 -0700491if main['BATCH']:
492 main['CC'] = main['BATCH_CMD'] + ' ' + main['CC']
493 main['CXX'] = main['BATCH_CMD'] + ' ' + main['CXX']
494 main['AS'] = main['BATCH_CMD'] + ' ' + main['AS']
495 main['AR'] = main['BATCH_CMD'] + ' ' + main['AR']
496 main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
Ali Saidibee4d452008-04-07 23:40:24 -0400497
Steve Reinhardtba2eae52006-05-22 14:29:33 -0400498if sys.platform == 'cygwin':
499 # cygwin has some header file issues...
Gabe Black14b27fc2010-11-09 11:03:40 -0800500 main.Append(CCFLAGS=["-Wno-uninitialized"])
Steve Reinhardtba2eae52006-05-22 14:29:33 -0400501
Andreas Sandberg51d38a42016-04-22 22:26:56 +0100502
503have_pkg_config = readCommand(['pkg-config', '--version'], exception='')
504
Andreas Hansson41f228c2013-01-07 13:05:37 -0500505# Check for the protobuf compiler
Gabe Blackdc3c6ee2019-11-18 16:00:22 -0800506try:
507 main['HAVE_PROTOC'] = True
508 protoc_version = readCommand([main['PROTOC'], '--version']).split()
Andreas Hansson41f228c2013-01-07 13:05:37 -0500509
Gabe Blackdc3c6ee2019-11-18 16:00:22 -0800510 # First two words should be "libprotoc x.y.z"
511 if len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
Gabe Black80283482019-11-18 17:41:49 -0800512 warning('Protocol buffer compiler (protoc) not found.\n'
513 'Please install protobuf-compiler for tracing support.')
Gabe Blackdc3c6ee2019-11-18 16:00:22 -0800514 main['HAVE_PROTOC'] = False
Andreas Hansson62544f92013-01-21 09:20:18 -0500515 else:
Gabe Blackdc3c6ee2019-11-18 16:00:22 -0800516 # Based on the availability of the compress stream wrappers,
517 # require 2.1.0
518 min_protoc_version = '2.1.0'
519 if compareVersions(protoc_version[1], min_protoc_version) < 0:
Gabe Black80283482019-11-18 17:41:49 -0800520 warning('protoc version', min_protoc_version,
521 'or newer required.\n'
522 'Installed version:', protoc_version[1])
Gabe Blackdc3c6ee2019-11-18 16:00:22 -0800523 main['HAVE_PROTOC'] = False
524 else:
525 # Attempt to determine the appropriate include path and
526 # library path using pkg-config, that means we also need to
527 # check for pkg-config. Note that it is possible to use
528 # protobuf without the involvement of pkg-config. Later on we
529 # check go a library config check and at that point the test
530 # will fail if libprotobuf cannot be found.
531 if have_pkg_config:
532 try:
533 # Attempt to establish what linking flags to add for
534 # protobuf
535 # using pkg-config
536 main.ParseConfig(
537 'pkg-config --cflags --libs-only-L protobuf')
538 except:
Gabe Black80283482019-11-18 17:41:49 -0800539 warning('pkg-config could not get protobuf flags.')
Gabe Blackdc3c6ee2019-11-18 16:00:22 -0800540except Exception as e:
Gabe Black80283482019-11-18 17:41:49 -0800541 warning('While checking protoc version:', str(e))
Gabe Blackdc3c6ee2019-11-18 16:00:22 -0800542 main['HAVE_PROTOC'] = False
Steve Reinhardt29e34a72006-06-09 23:01:31 -0400543
Andreas Hanssoneed07952015-03-02 04:00:29 -0500544# Check for 'timeout' from GNU coreutils. If present, regressions will
545# be run with a time limit. We require version 8.13 since we rely on
546# support for the '--foreground' option.
Bjoern A. Zeebe07f0c52017-02-09 19:00:00 -0500547if sys.platform.startswith('freebsd'):
548 timeout_lines = readCommand(['gtimeout', '--version'],
549 exception='').splitlines()
550else:
551 timeout_lines = readCommand(['timeout', '--version'],
552 exception='').splitlines()
Andreas Hanssoneed07952015-03-02 04:00:29 -0500553# Get the first line and tokenize it
554timeout_version = timeout_lines[0].split() if timeout_lines else []
555main['TIMEOUT'] = timeout_version and \
556 compareVersions(timeout_version[-1], '8.13') >= 0
Curtis Dunhame553ca62014-08-25 14:32:00 -0500557
Andreas Sandberg4b8be6a2013-10-15 10:09:23 +0200558# Add a custom Check function to test for structure members.
559def CheckMember(context, include, decl, member, include_quotes="<>"):
560 context.Message("Checking for member %s in %s..." %
561 (member, decl))
562 text = """
563#include %(header)s
564int main(){
565 %(decl)s test;
566 (void)test.%(member)s;
567 return 0;
568};
569""" % { "header" : include_quotes[0] + include + include_quotes[1],
570 "decl" : decl,
571 "member" : member,
572 }
573
574 ret = context.TryCompile(text, extension=".cc")
575 context.Result(ret)
576 return ret
577
Andreas Sandbergbc2e1232020-10-21 17:41:56 +0100578def CheckPythonLib(context):
579 context.Message('Checking Python version... ')
580 ret = context.TryRun(r"""
581#include <pybind11/embed.h>
582
583int
584main(int argc, char **argv) {
585 pybind11::scoped_interpreter guard{};
586 pybind11::exec(
587 "import sys\n"
588 "vi = sys.version_info\n"
589 "sys.stdout.write('%i.%i.%i' % (vi.major, vi.minor, vi.micro));\n");
590 return 0;
591}
592 """, extension=".cc")
593 context.Result(ret[1] if ret[0] == 1 else 0)
594 if ret[0] == 0:
595 return None
596 else:
597 return tuple(map(int, ret[1].split(".")))
598
Steve Reinhardt20051d42006-05-22 22:37:56 -0400599# Platform-specific configuration. Note again that we assume that all
600# builds under a given build root run on the same host platform.
Nathan Binkert05d8c9a2009-04-21 17:17:16 -0700601conf = Configure(main,
Steve Reinhardt6ae75ac2006-12-04 08:55:06 -0800602 conf_dir = joinpath(build_root, '.scons_config'),
Nathan Binkertede89c22008-08-03 18:19:54 -0700603 log_file = joinpath(build_root, 'scons_config.log'),
Andreas Sandberg4b8be6a2013-10-15 10:09:23 +0200604 custom_tests = {
Andreas Sandberg4b8be6a2013-10-15 10:09:23 +0200605 'CheckMember' : CheckMember,
Andreas Sandbergbc2e1232020-10-21 17:41:56 +0100606 'CheckPythonLib' : CheckPythonLib,
Andreas Sandberg4b8be6a2013-10-15 10:09:23 +0200607 })
Nathan Binkertede89c22008-08-03 18:19:54 -0700608
Ali Saidic01421a2007-11-08 17:45:58 -0500609# Check if we should compile a 64 bit binary on Mac OS X/Darwin
610try:
611 import platform
612 uname = platform.uname()
Nathan Binkert9a8cb7d2009-09-22 15:24:16 -0700613 if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
614 if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
Ali Saidi5c6f4a02010-11-19 18:00:59 -0600615 main.Append(CCFLAGS=['-arch', 'x86_64'])
616 main.Append(CFLAGS=['-arch', 'x86_64'])
617 main.Append(LINKFLAGS=['-arch', 'x86_64'])
618 main.Append(ASFLAGS=['-arch', 'x86_64'])
Ali Saidic01421a2007-11-08 17:45:58 -0500619except:
620 pass
621
Steve Reinhardt67b46d02007-11-01 14:28:59 -0700622# Recent versions of scons substitute a "Null" object for Configure()
623# when configuration isn't necessary, e.g., if the "--help" option is
624# present. Unfortuantely this Null object always returns false,
625# breaking all our configuration checks. We replace it with our own
626# more optimistic null object that returns True instead.
627if not conf:
628 def NullCheck(*args, **kwargs):
629 return True
630
631 class NullConf:
632 def __init__(self, env):
633 self.env = env
634 def Finish(self):
635 return self.env
636 def __getattr__(self, mname):
637 return NullCheck
638
Nathan Binkert05d8c9a2009-04-21 17:17:16 -0700639 conf = NullConf(main)
Steve Reinhardt67b46d02007-11-01 14:28:59 -0700640
Ali Saidi5fcf4422010-11-08 13:58:24 -0600641# Cache build files in the supplied directory.
642if main['M5_BUILD_CACHE']:
Gabe Black0bb50e62018-03-05 22:05:47 -0800643 print('Using build cache located at', main['M5_BUILD_CACHE'])
Ali Saidi5fcf4422010-11-08 13:58:24 -0600644 CacheDir(main['M5_BUILD_CACHE'])
645
Andreas Sandberg60e6e782017-02-27 13:17:51 +0000646main['USE_PYTHON'] = not GetOption('without_python')
647if main['USE_PYTHON']:
Andrew Bardsleyd8502ee2014-10-16 05:49:32 -0400648 # Find Python include and library directories for embedding the
649 # interpreter. We rely on python-config to resolve the appropriate
650 # includes and linker flags. ParseConfig does not seem to understand
651 # the more exotic linker flags such as -Xlinker and -export-dynamic so
652 # we add them explicitly below. If you want to link in an alternate
653 # version of python, see above for instructions on how to invoke
654 # scons with the appropriate PATH set.
Andreas Sandberga3c81f92019-01-25 11:14:29 +0000655
Gabe Black55ae5a82020-03-26 03:38:14 -0700656 python_config = main.Detect(main['PYTHON_CONFIG'])
Andreas Sandberga3c81f92019-01-25 11:14:29 +0000657 if python_config is None:
Gabe Black80283482019-11-18 17:41:49 -0800658 error("Can't find a suitable python-config, tried %s" % \
Andreas Sandberga3c81f92019-01-25 11:14:29 +0000659 main['PYTHON_CONFIG'])
Andreas Sandberga3c81f92019-01-25 11:14:29 +0000660
661 print("Info: Using Python config: %s" % (python_config, ))
Bobby R. Bruce81779302020-09-28 11:56:19 -0700662
Andrew Bardsleyd8502ee2014-10-16 05:49:32 -0400663 py_includes = readCommand([python_config, '--includes'],
664 exception='').split()
Giacomo Travaglini10b48422020-03-02 14:30:25 +0000665 py_includes = list(filter(
666 lambda s: match(r'.*\/include\/.*',s), py_includes))
Andrew Bardsleyd8502ee2014-10-16 05:49:32 -0400667 # Strip the -I from the include folders before adding them to the
668 # CPPPATH
Giacomo Travaglini10b48422020-03-02 14:30:25 +0000669 py_includes = list(map(
670 lambda s: s[2:] if s.startswith('-I') else s, py_includes))
Andrea Mondelliad9a2332019-01-10 10:33:13 -0500671 main.Append(CPPPATH=py_includes)
Andreas Hansson3ede4dc2013-07-18 08:29:28 -0400672
Andrew Bardsleyd8502ee2014-10-16 05:49:32 -0400673 # Read the linker flags and split them into libraries and other link
674 # flags. The libraries are added later through the call the CheckLib.
Jason Lowe-Power0bc5d772020-05-06 17:38:41 -0700675 # Note: starting in Python 3.8 the --embed flag is required to get the
676 # -lpython3.8 linker flag
677 retcode, cmd_stdout = readCommandWithReturn(
678 [python_config, '--ldflags', '--embed'], exception='')
679 if retcode != 0:
680 # If --embed isn't detected then we're running python <3.8
681 retcode, cmd_stdout = readCommandWithReturn(
682 [python_config, '--ldflags'], exception='')
683
684 # Checking retcode again
685 if retcode != 0:
686 error("Failing on python-config --ldflags command")
687
688 py_ld_flags = cmd_stdout.split()
689
Andrew Bardsleyd8502ee2014-10-16 05:49:32 -0400690 py_libs = []
691 for lib in py_ld_flags:
692 if not lib.startswith('-l'):
693 main.Append(LINKFLAGS=[lib])
694 else:
695 lib = lib[2:]
696 if lib not in py_libs:
697 py_libs.append(lib)
Ali Saidi5fcf4422010-11-08 13:58:24 -0600698
Andrew Bardsleyd8502ee2014-10-16 05:49:32 -0400699 # verify that this stuff works
700 if not conf.CheckHeader('Python.h', '<>'):
Gabe Blacka39c8db2019-12-02 17:52:44 -0800701 error("Check failed for Python.h header in",
702 ' '.join(py_includes), "\n"
Gabe Black80283482019-11-18 17:41:49 -0800703 "Two possible reasons:\n"
704 "1. Python headers are not installed (You can install the "
705 "package python-dev on Ubuntu and RedHat)\n"
706 "2. SCons is using a wrong C compiler. This can happen if "
707 "CC has the wrong value.\n"
708 "CC = %s" % main['CC'])
Steve Reinhardt85436fd2006-10-01 01:42:18 -0400709
Andrew Bardsleyd8502ee2014-10-16 05:49:32 -0400710 for lib in py_libs:
711 if not conf.CheckLib(lib):
Gabe Black80283482019-11-18 17:41:49 -0800712 error("Can't find library %s required by python." % lib)
Andrew Bardsleyd8502ee2014-10-16 05:49:32 -0400713
Nikos Nikolerisa0414b52020-04-30 17:33:13 +0100714main.Prepend(CPPPATH=Dir('ext/pybind11/include/'))
715# Bare minimum environment that only includes python
Giacomo Travaglinia1b64712020-06-04 12:45:52 +0100716marshal_env = main.Clone()
717marshal_env.Append(CCFLAGS='$MARSHAL_CCFLAGS_EXTRA')
718marshal_env.Append(LINKFLAGS='$MARSHAL_LDFLAGS_EXTRA')
Andreas Sandbergbc2e1232020-10-21 17:41:56 +0100719py_version = conf.CheckPythonLib()
720if not py_version:
721 error("Can't find a working Python installation")
722
723# Found a working Python installation. Check if it meets minimum
724# requirements.
725if py_version[0] < 3 or \
726 (py_version[0] == 3 and py_version[1] < 6):
727 error('Python version too old. Version 3.6 or newer is required.')
728elif py_version[0] > 3:
729 warning('Python version too new. Python 3 expected.')
Nikos Nikolerisa0414b52020-04-30 17:33:13 +0100730
Ali Saidi21cf4a42006-11-04 21:41:01 -0500731# On Solaris you need to use libsocket for socket ops
Ali Saidi430622c2006-11-06 10:15:27 -0500732if not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
Gabe Black80283482019-11-18 17:41:49 -0800733 if not conf.CheckLibWithHeader('socket', 'sys/socket.h',
734 'C++', 'accept(0,0,0);'):
735 error("Can't find library with socket calls (e.g. accept()).")
Ali Saidi21cf4a42006-11-04 21:41:01 -0500736
Steve Reinhardta016e132006-08-21 18:25:33 -0400737# Check for zlib. If the check passes, libz will be automatically
738# added to the LIBS environment variable.
Ali Saidi63fdabf2007-01-26 18:48:51 -0500739if not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
Gabe Black80283482019-11-18 17:41:49 -0800740 error('Did not find needed zlib compression library '
741 'and/or zlib.h header file.\n'
742 'Please install zlib and try again.')
Steve Reinhardta016e132006-08-21 18:25:33 -0400743
Andreas Hansson41f228c2013-01-07 13:05:37 -0500744# If we have the protobuf compiler, also make sure we have the
745# development libraries. If the check passes, libprotobuf will be
746# automatically added to the LIBS environment variable. After
747# this, we can use the HAVE_PROTOBUF flag to determine if we have
748# got both protoc and libprotobuf available.
Gabe Blackdc3c6ee2019-11-18 16:00:22 -0800749main['HAVE_PROTOBUF'] = main['HAVE_PROTOC'] and \
Andreas Hansson41f228c2013-01-07 13:05:37 -0500750 conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
751 'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
752
Gabe Blacka3385da2018-08-22 16:49:22 -0700753# Valgrind gets much less confused if you tell it when you're using
754# alternative stacks.
755main['HAVE_VALGRIND'] = conf.CheckCHeader('valgrind/valgrind.h')
756
Andreas Hansson62544f92013-01-21 09:20:18 -0500757# If we have the compiler but not the library, print another warning.
Gabe Blackdc3c6ee2019-11-18 16:00:22 -0800758if main['HAVE_PROTOC'] and not main['HAVE_PROTOBUF']:
Gabe Black80283482019-11-18 17:41:49 -0800759 warning('Did not find protocol buffer library and/or headers.\n'
760 'Please install libprotobuf-dev for tracing support.')
Andreas Hansson41f228c2013-01-07 13:05:37 -0500761
Nathan Binkert318bfe92011-01-15 07:48:25 -0800762# Check for librt.
Gabe Black0e64e1b2011-01-21 17:51:22 -0800763have_posix_clock = \
764 conf.CheckLibWithHeader(None, 'time.h', 'C',
765 'clock_nanosleep(0,0,NULL,NULL);') or \
766 conf.CheckLibWithHeader('rt', 'time.h', 'C',
767 'clock_nanosleep(0,0,NULL,NULL);')
Nathan Binkert318bfe92011-01-15 07:48:25 -0800768
Andreas Sandbergd3d53932013-10-01 15:56:47 +0200769have_posix_timers = \
770 conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
771 'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
772
Curtis Dunhamded540a2014-09-22 14:37:23 -0500773if not GetOption('without_tcmalloc'):
774 if conf.CheckLib('tcmalloc'):
775 main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
776 elif conf.CheckLib('tcmalloc_minimal'):
777 main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
778 else:
Gabe Black80283482019-11-18 17:41:49 -0800779 warning("You can get a 12% performance improvement by "
780 "installing tcmalloc (libgoogle-perftools-dev package "
781 "on Ubuntu or RedHat).")
Ali Saidiaec7a442012-06-05 01:23:09 -0400782
Andreas Sandbergdaa53da2015-12-04 00:12:58 +0000783
784# Detect back trace implementations. The last implementation in the
785# list will be used by default.
786backtrace_impls = [ "none" ]
787
Hanhwi Jangc8721432018-01-30 19:17:33 +0900788backtrace_checker = 'char temp;' + \
789 ' backtrace_symbols_fd((void*)&temp, 0, 0);'
790if conf.CheckLibWithHeader(None, 'execinfo.h', 'C', backtrace_checker):
Andreas Sandbergdaa53da2015-12-04 00:12:58 +0000791 backtrace_impls.append("glibc")
Bjoern A. Zeebe07f0c52017-02-09 19:00:00 -0500792elif conf.CheckLibWithHeader('execinfo', 'execinfo.h', 'C',
Hanhwi Jangc8721432018-01-30 19:17:33 +0900793 backtrace_checker):
Bjoern A. Zeebe07f0c52017-02-09 19:00:00 -0500794 # NetBSD and FreeBSD need libexecinfo.
795 backtrace_impls.append("glibc")
796 main.Append(LIBS=['execinfo'])
Andreas Sandbergdaa53da2015-12-04 00:12:58 +0000797
798if backtrace_impls[-1] == "none":
799 default_backtrace_impl = "none"
Gabe Black80283482019-11-18 17:41:49 -0800800 warning("No suitable back trace implementation found.")
Andreas Sandbergdaa53da2015-12-04 00:12:58 +0000801
Nathan Binkert318bfe92011-01-15 07:48:25 -0800802if not have_posix_clock:
Gabe Black80283482019-11-18 17:41:49 -0800803 warning("Can't find library for POSIX clocks.")
Nathan Binkert318bfe92011-01-15 07:48:25 -0800804
Steve Reinhardtba2eae52006-05-22 14:29:33 -0400805# Check for <fenv.h> (C99 FP environment control)
806have_fenv = conf.CheckHeader('fenv.h', '<>')
807if not have_fenv:
Gabe Black80283482019-11-18 17:41:49 -0800808 warning("Header file <fenv.h> not found.\n"
809 "This host has no IEEE FP rounding mode control.")
Steve Reinhardtba2eae52006-05-22 14:29:33 -0400810
Giacomo Travaglini12fb1ca2017-09-28 13:01:08 +0100811# Check for <png.h> (libpng library needed if wanting to dump
812# frame buffer image in png format)
813have_png = conf.CheckHeader('png.h', '<>')
814if not have_png:
Gabe Black80283482019-11-18 17:41:49 -0800815 warning("Header file <png.h> not found.\n"
816 "This host has no libpng library.\n"
817 "Disabling support for PNG framebuffers.")
Giacomo Travaglini12fb1ca2017-09-28 13:01:08 +0100818
Andreas Hansson05ed2de2013-10-02 06:08:45 -0400819# Check if we should enable KVM-based hardware virtualization. The API
820# we rely on exists since version 2.6.36 of the kernel, but somehow
821# the KVM_API_VERSION does not reflect the change. We test for one of
822# the types as a fall back.
Andreas Sandberg12e91f72015-05-23 13:37:18 +0100823have_kvm = conf.CheckHeader('linux/kvm.h', '<>')
Andreas Sandbergf485ad12013-04-22 13:20:32 -0400824if not have_kvm:
Gabe Black0bb50e62018-03-05 22:05:47 -0800825 print("Info: Compatible header file <linux/kvm.h> not found, "
826 "disabling KVM support.")
Andreas Sandbergf485ad12013-04-22 13:20:32 -0400827
Gabe Blackc58537c2017-06-03 07:23:05 -0700828# Check if the TUN/TAP driver is available.
829have_tuntap = conf.CheckHeader('linux/if_tun.h', '<>')
830if not have_tuntap:
Gabe Black0bb50e62018-03-05 22:05:47 -0800831 print("Info: Compatible header file <linux/if_tun.h> not found.")
Gabe Blackc58537c2017-06-03 07:23:05 -0700832
Andreas Sandberg12e91f72015-05-23 13:37:18 +0100833# x86 needs support for xsave. We test for the structure here since we
834# won't be able to run new tests by the time we know which ISA we're
835# targeting.
836have_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
837 '#include <linux/kvm.h>') != 0
838
Andreas Sandbergf485ad12013-04-22 13:20:32 -0400839# Check if the requested target ISA is compatible with the host
840def is_isa_kvm_compatible(isa):
Andreas Sandbergf485ad12013-04-22 13:20:32 -0400841 try:
842 import platform
843 host_isa = platform.machine()
844 except:
Gabe Black80283482019-11-18 17:41:49 -0800845 warning("Failed to determine host ISA.")
Andreas Sandbergf485ad12013-04-22 13:20:32 -0400846 return False
847
Andreas Sandberg12e91f72015-05-23 13:37:18 +0100848 if not have_posix_timers:
Gabe Black80283482019-11-18 17:41:49 -0800849 warning("Can not enable KVM, host seems to lack support "
850 "for POSIX timers")
Andreas Sandberg12e91f72015-05-23 13:37:18 +0100851 return False
852
853 if isa == "arm":
Andreas Sandberg7c4eb3b2015-06-01 19:44:19 +0100854 return host_isa in ( "armv7l", "aarch64" )
Andreas Sandberg12e91f72015-05-23 13:37:18 +0100855 elif isa == "x86":
856 if host_isa != "x86_64":
857 return False
858
859 if not have_kvm_xsave:
Gabe Black80283482019-11-18 17:41:49 -0800860 warning("KVM on x86 requires xsave support in kernel headers.")
Andreas Sandberg12e91f72015-05-23 13:37:18 +0100861 return False
862
863 return True
864 else:
865 return False
Andreas Sandbergf485ad12013-04-22 13:20:32 -0400866
867
Andreas Sandberg4b8be6a2013-10-15 10:09:23 +0200868# Check if the exclude_host attribute is available. We want this to
869# get accurate instruction counts in KVM.
870main['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
871 'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
872
Andreas Sandberg51d38a42016-04-22 22:26:56 +0100873def check_hdf5():
874 return \
875 conf.CheckLibWithHeader('hdf5', 'hdf5.h', 'C',
876 'H5Fcreate("", 0, 0, 0);') and \
877 conf.CheckLibWithHeader('hdf5_cpp', 'H5Cpp.h', 'C++',
878 'H5::H5File("", 0);')
879
880def check_hdf5_pkg(name):
881 print("Checking for %s using pkg-config..." % name, end="")
882 if not have_pkg_config:
883 print(" pkg-config not found")
884 return False
885
886 try:
887 main.ParseConfig('pkg-config --cflags-only-I --libs-only-L %s' % name)
888 print(" yes")
889 return True
890 except:
891 print(" no")
892 return False
893
894# Check if there is a pkg-config configuration for hdf5. If we find
895# it, setup the environment to enable linking and header inclusion. We
896# don't actually try to include any headers or link with hdf5 at this
897# stage.
898if not check_hdf5_pkg('hdf5-serial'):
899 check_hdf5_pkg('hdf5')
900
901# Check if the HDF5 libraries can be found. This check respects the
902# include path and library path provided by pkg-config. We perform
903# this check even if there isn't a pkg-config configuration for hdf5
904# since some installations don't use pkg-config.
905have_hdf5 = check_hdf5()
906if not have_hdf5:
907 print("Warning: Couldn't find any HDF5 C++ libraries. Disabling")
908 print(" HDF5 support.")
Andreas Sandberg4b8be6a2013-10-15 10:09:23 +0200909
Nathan Binkertdd6ea872009-02-09 20:10:14 -0800910######################################################################
911#
Nathan Binkertdd6ea872009-02-09 20:10:14 -0800912# Finish the configuration
913#
Nathan Binkert05d8c9a2009-04-21 17:17:16 -0700914main = conf.Finish()
Steve Reinhardtba2eae52006-05-22 14:29:33 -0400915
Nathan Binkertdd6ea872009-02-09 20:10:14 -0800916######################################################################
917#
918# Collect all non-global variables
919#
920
Steve Reinhardtba2eae52006-05-22 14:29:33 -0400921# Define the universe of supported ISAs
Nathan Binkert1aef5c02007-03-10 23:00:54 -0800922all_isa_list = [ ]
Tony Gutierrez1a7d3f92016-01-19 14:28:22 -0500923all_gpu_isa_list = [ ]
Nathan Binkert1aef5c02007-03-10 23:00:54 -0800924Export('all_isa_list')
Tony Gutierrez1a7d3f92016-01-19 14:28:22 -0500925Export('all_gpu_isa_list')
Steve Reinhardtba2eae52006-05-22 14:29:33 -0400926
Nathan Binkertf0b42592010-02-26 18:14:48 -0800927class CpuModel(object):
928 '''The CpuModel class encapsulates everything the ISA parser needs to
929 know about a particular CPU model.'''
930
931 # Dict of available CPU model objects. Accessible as CpuModel.dict.
932 dict = {}
Nathan Binkertf0b42592010-02-26 18:14:48 -0800933
934 # Constructor. Automatically adds models to CpuModel.dict.
Andreas Sandberg326662b2014-09-03 07:42:22 -0400935 def __init__(self, name, default=False):
Nathan Binkertf0b42592010-02-26 18:14:48 -0800936 self.name = name # name of model
Nathan Binkertf0b42592010-02-26 18:14:48 -0800937
938 # This cpu is enabled by default
939 self.default = default
940
941 # Add self to dict
942 if name in CpuModel.dict:
Gabe Blacka39c8db2019-12-02 17:52:44 -0800943 raise AttributeError("CpuModel '%s' already registered" % name)
Nathan Binkertf0b42592010-02-26 18:14:48 -0800944 CpuModel.dict[name] = self
Nathan Binkertf0b42592010-02-26 18:14:48 -0800945
946Export('CpuModel')
Steve Reinhardtba2eae52006-05-22 14:29:33 -0400947
Nathan Binkertdd6ea872009-02-09 20:10:14 -0800948# Sticky variables get saved in the variables file so they persist from
Steve Reinhardtba2eae52006-05-22 14:29:33 -0400949# one invocation to the next (unless overridden, in which case the new
950# value becomes sticky).
Nathan Binkertdd6ea872009-02-09 20:10:14 -0800951sticky_vars = Variables(args=ARGUMENTS)
952Export('sticky_vars')
Nathan Binkert1aef5c02007-03-10 23:00:54 -0800953
Nathan Binkertb0489d12009-04-21 08:17:36 -0700954# Sticky variables that should be exported
955export_vars = []
956Export('export_vars')
957
Jason Poweraa8bcd12012-09-12 14:52:04 -0500958# For Ruby
959all_protocols = []
960Export('all_protocols')
961protocol_dirs = []
962Export('protocol_dirs')
963slicc_includes = []
964Export('slicc_includes')
965
Nathan Binkert1aef5c02007-03-10 23:00:54 -0800966# Walk the tree and execute all SConsopts scripts that wil add to the
Nathan Binkertdd6ea872009-02-09 20:10:14 -0800967# above variables
Curtis Dunhama3d582f2014-03-23 11:11:51 -0400968if GetOption('verbose'):
Gabe Black0bb50e62018-03-05 22:05:47 -0800969 print("Reading SConsopts")
Nathan Binkert4d64d762008-11-10 11:51:18 -0800970for bdir in [ base_dir ] + extras_dir_list:
Steve Reinhardt8ce85d32011-05-02 12:40:32 -0700971 if not isdir(bdir):
Gabe Black80283482019-11-18 17:41:49 -0800972 error("Directory '%s' does not exist." % bdir)
Nathan Binkert4d64d762008-11-10 11:51:18 -0800973 for root, dirs, files in os.walk(bdir):
Steve Reinhardtd725ff42008-02-05 17:40:08 -0800974 if 'SConsopts' in files:
Gabe Blackf8ac16b2011-07-19 02:56:02 -0700975 if GetOption('verbose'):
Gabe Black0bb50e62018-03-05 22:05:47 -0800976 print("Reading", joinpath(root, 'SConsopts'))
Steve Reinhardtb96631e2008-02-05 17:43:45 -0800977 SConscript(joinpath(root, 'SConsopts'))
Nathan Binkert1aef5c02007-03-10 23:00:54 -0800978
979all_isa_list.sort()
Tony Gutierrez1a7d3f92016-01-19 14:28:22 -0500980all_gpu_isa_list.sort()
Nathan Binkert1aef5c02007-03-10 23:00:54 -0800981
Nathan Binkertdd6ea872009-02-09 20:10:14 -0800982sticky_vars.AddVariables(
Giacomo Travaglini7ce081d2020-06-04 10:34:41 +0100983 EnumVariable('TARGET_ISA', 'Target ISA', 'null', all_isa_list),
Tony Gutierrez9d51dec2018-05-01 17:34:29 -0400984 EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'gcn3', all_gpu_isa_list),
Nathan Binkertf0b42592010-02-26 18:14:48 -0800985 ListVariable('CPU_MODELS', 'CPU models',
Giacomo Travaglini10b48422020-03-02 14:30:25 +0000986 sorted(n for n,m in CpuModel.dict.items() if m.default),
Andreas Sandberg326662b2014-09-03 07:42:22 -0400987 sorted(CpuModel.dict.keys())),
Nathan Binkertdd6ea872009-02-09 20:10:14 -0800988 BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
989 False),
Nathan Binkertdd6ea872009-02-09 20:10:14 -0800990 BoolVariable('USE_SSE2',
991 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
992 False),
Nathan Binkert318bfe92011-01-15 07:48:25 -0800993 BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
Nathan Binkertdd6ea872009-02-09 20:10:14 -0800994 BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
Giacomo Travaglini12fb1ca2017-09-28 13:01:08 +0100995 BoolVariable('USE_PNG', 'Enable support for PNG images', have_png),
Giacomo Travaglini12fb1ca2017-09-28 13:01:08 +0100996 BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models',
997 have_kvm),
Gabe Blackc58537c2017-06-03 07:23:05 -0700998 BoolVariable('USE_TUNTAP',
999 'Enable using a tap device to bridge to the host network',
1000 have_tuntap),
Tony Gutierrez1a7d3f92016-01-19 14:28:22 -05001001 BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
Jason Poweraa8bcd12012-09-12 14:52:04 -05001002 EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
1003 all_protocols),
Andreas Sandbergdaa53da2015-12-04 00:12:58 +00001004 EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
John Alsopf5cf6d52017-04-20 11:26:39 -04001005 backtrace_impls[-1], backtrace_impls),
1006 ('NUMBER_BITS_PER_SET', 'Max elements in set (default 64)',
1007 64),
Andreas Sandberg51d38a42016-04-22 22:26:56 +01001008 BoolVariable('USE_HDF5', 'Enable the HDF5 support', have_hdf5),
Steve Reinhardtba2eae52006-05-22 14:29:33 -04001009 )
1010
Nathan Binkertdd6ea872009-02-09 20:10:14 -08001011# These variables get exported to #defines in config/*.hh (see src/SConscript).
Gabe Black9d1278d2020-08-19 20:14:49 -07001012export_vars += ['USE_FENV', 'TARGET_ISA', 'TARGET_GPU_ISA',
Gabe Blacke01ead42020-02-04 16:19:38 -08001013 'USE_POSIX_CLOCK', 'USE_KVM', 'USE_TUNTAP', 'PROTOCOL',
1014 'HAVE_PROTOBUF', 'HAVE_VALGRIND',
John Alsopf5cf6d52017-04-20 11:26:39 -04001015 'HAVE_PERF_ATTR_EXCLUDE_HOST', 'USE_PNG',
Andreas Sandberg51d38a42016-04-22 22:26:56 +01001016 'NUMBER_BITS_PER_SET', 'USE_HDF5']
Steve Reinhardtba2eae52006-05-22 14:29:33 -04001017
Steve Reinhardtba2eae52006-05-22 14:29:33 -04001018###################################################
1019#
1020# Define a SCons builder for configuration flag headers.
1021#
1022###################################################
1023
1024# This function generates a config header file that #defines the
Nathan Binkertdd6ea872009-02-09 20:10:14 -08001025# variable symbol to the current variable setting (0 or 1). The source
1026# operands are the name of the variable and a Value node containing the
1027# value of the variable.
Steve Reinhardtba2eae52006-05-22 14:29:33 -04001028def build_config_file(target, source, env):
Giacomo Travaglinie06ec8c2020-03-02 15:16:09 +00001029 (variable, value) = [s.get_contents().decode('utf-8') for s in source]
Gabe Blacka4e5d2c2020-12-18 09:40:09 -08001030 with open(str(target[0].abspath), 'w') as f:
Giacomo Travaglinibb95aa12020-03-02 15:08:41 +00001031 print('#define', variable, value, file=f)
Steve Reinhardtba2eae52006-05-22 14:29:33 -04001032 return None
1033
Steve Reinhardtba2eae52006-05-22 14:29:33 -04001034# Combine the two functions into a scons Action object.
Gabe Black1c68c322011-08-02 03:22:11 -07001035config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
Steve Reinhardtba2eae52006-05-22 14:29:33 -04001036
1037# The emitter munges the source & target node lists to reflect what
1038# we're really doing.
1039def config_emitter(target, source, env):
Nathan Binkertdd6ea872009-02-09 20:10:14 -08001040 # extract variable name from Builder arg
1041 variable = str(target[0])
Steve Reinhardtba2eae52006-05-22 14:29:33 -04001042 # True target is config header file
Gabe Blacka4e5d2c2020-12-18 09:40:09 -08001043 target = Dir('config').File(variable.lower() + '.hh')
Nathan Binkertdd6ea872009-02-09 20:10:14 -08001044 val = env[variable]
Nathan Binkert6c6b7812006-10-20 11:37:59 -07001045 if isinstance(val, bool):
1046 # Force value to 0/1
1047 val = int(val)
1048 elif isinstance(val, str):
1049 val = '"' + val + '"'
Nathan Binkertc27e23f2007-07-28 16:49:20 -07001050
Nathan Binkertdd6ea872009-02-09 20:10:14 -08001051 # Sources are variable name & value (packaged in SCons Value nodes)
Gabe Blacka4e5d2c2020-12-18 09:40:09 -08001052 return [target], [Value(variable), Value(val)]
Steve Reinhardtba2eae52006-05-22 14:29:33 -04001053
Gabe Blacka4e5d2c2020-12-18 09:40:09 -08001054config_builder = Builder(emitter=config_emitter, action=config_action)
Steve Reinhardtba2eae52006-05-22 14:29:33 -04001055
Nathan Binkert05d8c9a2009-04-21 17:17:16 -07001056main.Append(BUILDERS = { 'ConfigFile' : config_builder })
Steve Reinhardtba2eae52006-05-22 14:29:33 -04001057
Gabe Black45765412017-04-28 03:57:09 -07001058###################################################
1059#
1060# Builders for static and shared partially linked object files.
1061#
1062###################################################
1063
1064partial_static_builder = Builder(action=SCons.Defaults.LinkAction,
1065 src_suffix='$OBJSUFFIX',
1066 src_builder=['StaticObject', 'Object'],
1067 LINKFLAGS='$PLINKFLAGS',
1068 LIBS='')
1069
1070def partial_shared_emitter(target, source, env):
1071 for tgt in target:
1072 tgt.attributes.shared = 1
1073 return (target, source)
1074partial_shared_builder = Builder(action=SCons.Defaults.ShLinkAction,
1075 emitter=partial_shared_emitter,
1076 src_suffix='$SHOBJSUFFIX',
1077 src_builder='SharedObject',
1078 SHLINKFLAGS='$PSHLINKFLAGS',
1079 LIBS='')
1080
1081main.Append(BUILDERS = { 'PartialShared' : partial_shared_builder,
1082 'PartialStatic' : partial_static_builder })
1083
Gabe Black0a737262019-02-20 17:43:15 -08001084def add_local_rpath(env, *targets):
1085 '''Set up an RPATH for a library which lives in the build directory.
1086
1087 The construction environment variable BIN_RPATH_PREFIX should be set to
1088 the relative path of the build directory starting from the location of the
1089 binary.'''
1090 for target in targets:
1091 target = env.Entry(target)
Gabe Black91195ae2019-03-12 05:00:41 -07001092 if not isinstance(target, SCons.Node.FS.Dir):
Gabe Black0a737262019-02-20 17:43:15 -08001093 target = target.dir
1094 relpath = os.path.relpath(target.abspath, env['BUILDDIR'])
1095 components = [
1096 '\\$$ORIGIN',
1097 '${BIN_RPATH_PREFIX}',
1098 relpath
1099 ]
1100 env.Append(RPATH=[env.Literal(os.path.join(*components))])
1101
Andrea Mondellif59e5502019-02-22 11:42:16 -05001102if sys.platform != "darwin":
1103 main.Append(LINKFLAGS=Split('-z origin'))
1104
Gabe Black0a737262019-02-20 17:43:15 -08001105main.AddMethod(add_local_rpath, 'AddLocalRPATH')
1106
Gabe Black4d1e1472017-04-27 23:50:09 -07001107# builds in ext are shared across all configs in the build root.
Gabe Blacka4e5d2c2020-12-18 09:40:09 -08001108ext_dir = Dir('#ext').abspath
Gabe Blacke897c522017-05-19 16:30:45 -07001109ext_build_dirs = []
Gabe Black4d1e1472017-04-27 23:50:09 -07001110for root, dirs, files in os.walk(ext_dir):
1111 if 'SConscript' in files:
1112 build_dir = os.path.relpath(root, ext_dir)
Gabe Blacke897c522017-05-19 16:30:45 -07001113 ext_build_dirs.append(build_dir)
Gabe Black4d1e1472017-04-27 23:50:09 -07001114 main.SConscript(joinpath(root, 'SConscript'),
1115 variant_dir=joinpath(build_root, build_dir))
Andreas Sandbergc2740572015-07-07 10:03:13 +01001116
Ciro Santilli9712a632018-12-21 14:22:30 +00001117gdb_xml_dir = joinpath(ext_dir, 'gdb-xml')
1118Export('gdb_xml_dir')
1119
Steve Reinhardtba2eae52006-05-22 14:29:33 -04001120###################################################
1121#
Gabe Black8ee95f32017-05-01 21:58:41 -07001122# This builder and wrapper method are used to set up a directory with
1123# switching headers. Those are headers which are in a generic location and
1124# that include more specific headers from a directory chosen at build time
1125# based on the current build settings.
Gabe Blackeb4ef3a2006-11-07 05:33:21 -05001126#
1127###################################################
1128
Gabe Black8ee95f32017-05-01 21:58:41 -07001129def build_switching_header(target, source, env):
1130 path = str(target[0])
1131 subdir = str(source[0])
1132 dp, fp = os.path.split(path)
1133 dp = os.path.relpath(os.path.realpath(dp),
1134 os.path.realpath(env['BUILDDIR']))
1135 with open(path, 'w') as hdr:
Gabe Black0bb50e62018-03-05 22:05:47 -08001136 print('#include "%s/%s/%s"' % (dp, subdir, fp), file=hdr)
Gabe Blackeb4ef3a2006-11-07 05:33:21 -05001137
Gabe Black8ee95f32017-05-01 21:58:41 -07001138switching_header_action = MakeAction(build_switching_header,
1139 Transform('GENERATE'))
Curtis Dunhamfe27f932014-05-09 18:58:47 -04001140
Gabe Black8ee95f32017-05-01 21:58:41 -07001141switching_header_builder = Builder(action=switching_header_action,
1142 source_factory=Value,
1143 single_source=True)
1144
1145main.Append(BUILDERS = { 'SwitchingHeader': switching_header_builder })
1146
1147def switching_headers(self, headers, source):
1148 for header in headers:
1149 self.SwitchingHeader(header, source)
1150
1151main.AddMethod(switching_headers, 'SwitchingHeaders')
Gabe Blackeb4ef3a2006-11-07 05:33:21 -05001152
1153###################################################
1154#
Steve Reinhardtba2eae52006-05-22 14:29:33 -04001155# Define build environments for selected configurations.
1156#
1157###################################################
1158
Nathan Binkertdd6ea872009-02-09 20:10:14 -08001159for variant_path in variant_paths:
Curtis Dunhama3d582f2014-03-23 11:11:51 -04001160 if not GetOption('silent'):
Gabe Black0bb50e62018-03-05 22:05:47 -08001161 print("Building in", variant_path)
Steve Reinhardt476a2ee2008-02-11 07:47:44 -08001162
1163 # Make a copy of the build-root environment to use for this config.
Nathan Binkert05d8c9a2009-04-21 17:17:16 -07001164 env = main.Clone()
Nathan Binkertdd6ea872009-02-09 20:10:14 -08001165 env['BUILDDIR'] = variant_path
Nathan Binkert19c01e82007-07-25 18:21:11 -07001166
Nathan Binkertdd6ea872009-02-09 20:10:14 -08001167 # variant_dir is the tail component of build path, and is used to
Gabe Blackbc8d4922020-02-17 02:26:05 -08001168 # determine the build parameters (e.g., 'X86')
Nathan Binkertdd6ea872009-02-09 20:10:14 -08001169 (build_root, variant_dir) = splitpath(variant_path)
Steve Reinhardtba2eae52006-05-22 14:29:33 -04001170
Nathan Binkertdd6ea872009-02-09 20:10:14 -08001171 # Set env variables according to the build directory config.
1172 sticky_vars.files = []
1173 # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1174 # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1175 # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1176 current_vars_file = joinpath(build_root, 'variables', variant_dir)
1177 if isfile(current_vars_file):
1178 sticky_vars.files.append(current_vars_file)
Curtis Dunhama3d582f2014-03-23 11:11:51 -04001179 if not GetOption('silent'):
Gabe Black0bb50e62018-03-05 22:05:47 -08001180 print("Using saved variables file %s" % current_vars_file)
Gabe Blacke897c522017-05-19 16:30:45 -07001181 elif variant_dir in ext_build_dirs:
1182 # Things in ext are built without a variant directory.
1183 continue
Steve Reinhardtba2eae52006-05-22 14:29:33 -04001184 else:
Nathan Binkertdd6ea872009-02-09 20:10:14 -08001185 # Build dir-specific variables file doesn't exist.
Steve Reinhardtba2eae52006-05-22 14:29:33 -04001186
1187 # Make sure the directory is there so we can create it later
Nathan Binkertdd6ea872009-02-09 20:10:14 -08001188 opt_dir = dirname(current_vars_file)
Steve Reinhardtb96631e2008-02-05 17:43:45 -08001189 if not isdir(opt_dir):
Nathan Binkertdd6ea872009-02-09 20:10:14 -08001190 mkdir(opt_dir)
Steve Reinhardtba2eae52006-05-22 14:29:33 -04001191
Nathan Binkertdd6ea872009-02-09 20:10:14 -08001192 # Get default build variables from source tree. Variables are
1193 # normally determined by name of $VARIANT_DIR, but can be
Steve Reinhardtf713af92011-05-02 12:40:31 -07001194 # overridden by '--default=' arg on command line.
Gabe Blackfa448122011-03-03 23:54:31 -08001195 default = GetOption('default')
Gabe Blacka4e5d2c2020-12-18 09:40:09 -08001196 opts_dir = Dir('#build_opts').abspath
Steve Reinhardtf713af92011-05-02 12:40:31 -07001197 if default:
1198 default_vars_files = [joinpath(build_root, 'variables', default),
1199 joinpath(opts_dir, default)]
1200 else:
1201 default_vars_files = [joinpath(opts_dir, variant_dir)]
Giacomo Travaglini10b48422020-03-02 14:30:25 +00001202 existing_files = list(filter(isfile, default_vars_files))
Steve Reinhardtf713af92011-05-02 12:40:31 -07001203 if existing_files:
1204 default_vars_file = existing_files[0]
Nathan Binkertdd6ea872009-02-09 20:10:14 -08001205 sticky_vars.files.append(default_vars_file)
Gabe Black0bb50e62018-03-05 22:05:47 -08001206 print("Variables file %s not found,\n using defaults in %s"
1207 % (current_vars_file, default_vars_file))
Steve Reinhardtba2eae52006-05-22 14:29:33 -04001208 else:
Gabe Black80283482019-11-18 17:41:49 -08001209 error("Cannot find variables file %s or default file(s) %s"
Gabe Black0bb50e62018-03-05 22:05:47 -08001210 % (current_vars_file, ' or '.join(default_vars_files)))
Steve Reinhardtba2eae52006-05-22 14:29:33 -04001211 Exit(1)
1212
Nathan Binkertdd6ea872009-02-09 20:10:14 -08001213 # Apply current variable settings to env
1214 sticky_vars.Update(env)
Steve Reinhardtba2eae52006-05-22 14:29:33 -04001215
Gabe Black08ab4572020-08-03 21:38:55 -07001216 Help('''
1217Build variables for {dir}:
1218{help}
1219'''.format(dir=variant_dir, help=sticky_vars.GenerateHelpText(env)),
1220 append=True)
Steve Reinhardtba2eae52006-05-22 14:29:33 -04001221
Nathan Binkertdd6ea872009-02-09 20:10:14 -08001222 # Process variable settings.
Steve Reinhardtba2eae52006-05-22 14:29:33 -04001223
1224 if not have_fenv and env['USE_FENV']:
Gabe Black80283482019-11-18 17:41:49 -08001225 warning("<fenv.h> not available; forcing USE_FENV to False in",
1226 variant_dir + ".")
Steve Reinhardtba2eae52006-05-22 14:29:33 -04001227 env['USE_FENV'] = False
1228
1229 if not env['USE_FENV']:
Gabe Black80283482019-11-18 17:41:49 -08001230 warning("No IEEE FP rounding mode control in", variant_dir + ".\n"
1231 "FP results may deviate slightly from other platforms.")
Steve Reinhardtba2eae52006-05-22 14:29:33 -04001232
Giacomo Travaglini12fb1ca2017-09-28 13:01:08 +01001233 if not have_png and env['USE_PNG']:
Gabe Black80283482019-11-18 17:41:49 -08001234 warning("<png.h> not available; forcing USE_PNG to False in",
1235 variant_dir + ".")
Giacomo Travaglini12fb1ca2017-09-28 13:01:08 +01001236 env['USE_PNG'] = False
1237
1238 if env['USE_PNG']:
1239 env.Append(LIBS=['png'])
1240
Steve Reinhardtba2eae52006-05-22 14:29:33 -04001241 if env['EFENCE']:
1242 env.Append(LIBS=['efence'])
1243
Andreas Sandbergf485ad12013-04-22 13:20:32 -04001244 if env['USE_KVM']:
1245 if not have_kvm:
Gabe Black80283482019-11-18 17:41:49 -08001246 warning("Can not enable KVM, host seems to lack KVM support")
Andreas Sandbergf485ad12013-04-22 13:20:32 -04001247 env['USE_KVM'] = False
1248 elif not is_isa_kvm_compatible(env['TARGET_ISA']):
Gabe Black0bb50e62018-03-05 22:05:47 -08001249 print("Info: KVM support disabled due to unsupported host and "
1250 "target ISA combination")
Andreas Sandbergf485ad12013-04-22 13:20:32 -04001251 env['USE_KVM'] = False
1252
Gabe Blackc58537c2017-06-03 07:23:05 -07001253 if env['USE_TUNTAP']:
1254 if not have_tuntap:
Gabe Black80283482019-11-18 17:41:49 -08001255 warning("Can't connect EtherTap with a tap device.")
Gabe Blackc58537c2017-06-03 07:23:05 -07001256 env['USE_TUNTAP'] = False
1257
Tony Gutierrez1961a942017-01-19 11:59:34 -05001258 if env['BUILD_GPU']:
1259 env.Append(CPPDEFINES=['BUILD_GPU'])
1260
Andreas Sandberg4b8be6a2013-10-15 10:09:23 +02001261 # Warn about missing optional functionality
1262 if env['USE_KVM']:
1263 if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
Gabe Black80283482019-11-18 17:41:49 -08001264 warning("perf_event headers lack support for the exclude_host "
1265 "attribute. KVM instruction counts will be inaccurate.")
Andreas Sandberg4b8be6a2013-10-15 10:09:23 +02001266
Nathan Binkertdd6ea872009-02-09 20:10:14 -08001267 # Save sticky variable settings back to current variables file
1268 sticky_vars.Save(current_vars_file, env)
Steve Reinhardtba2eae52006-05-22 14:29:33 -04001269
Steve Reinhardtba2eae52006-05-22 14:29:33 -04001270 if env['USE_SSE2']:
Gabe Black14b27fc2010-11-09 11:03:40 -08001271 env.Append(CCFLAGS=['-msse2'])
Steve Reinhardtba2eae52006-05-22 14:29:33 -04001272
Ciro Santilliec502252019-05-21 13:19:24 +01001273 env.Append(CCFLAGS='$CCFLAGS_EXTRA')
1274 env.Append(LINKFLAGS='$LDFLAGS_EXTRA')
1275
Steve Reinhardt7efd0ea2006-06-17 09:26:08 -04001276 # The src/SConscript file sets up the build rules in 'env' according
Nathan Binkertdd6ea872009-02-09 20:10:14 -08001277 # to the configured variables. It returns a list of environments,
Steve Reinhardtba2eae52006-05-22 14:29:33 -04001278 # one for each variant build (debug, opt, etc.)
Nikos Nikolerisa0414b52020-04-30 17:33:13 +01001279 SConscript('src/SConscript', variant_dir=variant_path,
Giacomo Travaglinia1b64712020-06-04 12:45:52 +01001280 exports=['env', 'marshal_env'])
Steve Reinhardtba2eae52006-05-22 14:29:33 -04001281
Gabe Black1c595592020-03-26 04:48:53 -07001282atexit.register(summarize_warnings)