aboutsummaryrefslogtreecommitdiff
path: root/compute_kernel_writer/SConstruct
blob: a67522fedd04a8fe74870e161ebd4b8dff63d412 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
# -*- coding: utf-8 -*-

# Copyright (c) 2023 Arm Limited.
#
# SPDX-License-Identifier: MIT
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

import SCons
import os
from subprocess import check_output

def version_at_least(version, required):

    version_list = version.split('.')
    required_list = required.split('.')
    end = min(len(version_list), len(required_list))
    for i in range(0, end):
        if int(version_list[i]) < int(required_list[i]):
            return False
        elif int(version_list[i]) > int(required_list[i]):
            return True

    return True

vars = Variables("scons")
vars.AddVariables(
    BoolVariable("debug", "Debug", False),
    BoolVariable("asserts", "Enable asserts (this flag is forced to 1 for debug=1)", False),
    EnumVariable("arch", "Target Architecture.", "armv8.2-a",
                  allowed_values=("x86_64", "armv8.2-a")),
    EnumVariable("os", "Target OS.", "linux", allowed_values=("linux", "android")),
    EnumVariable("build", "Either build directly on your device (native) or cross compile from your desktop machine (cross-compile). In both cases make sure the compiler is available in your path.", "cross_compile", allowed_values=("native", "cross_compile", "embed_only")),
    BoolVariable("Werror", "Enable/disable the -Werror compilation flag", True),
    PathVariable("build_dir", "Specify sub-folder for the build", ".", PathVariable.PathAccept),
    PathVariable("install_dir", "Specify sub-folder for the install", "", PathVariable.PathAccept),
    BoolVariable("exceptions", "Enable/disable C++ exception support", True),
    PathVariable("linker_script", "Use an external linker script", "", PathVariable.PathAccept),
    ("toolchain_prefix", "Override the toolchain prefix; used by all toolchain components: compilers, linker, assembler etc. If unspecified, use default(auto) prefixes; if passed an empty string '' prefixes would be disabled", "auto"),
    ("compiler_prefix", "Override the compiler prefix; used by just compilers (CC,CXX); further overrides toolchain_prefix for compilers; this is for when the compiler prefixes are different from that of the linkers, archivers etc. If unspecified, this is the same as toolchain_prefix; if passed an empty string '' prefixes would be disabled", "auto"),
    ("extra_cxx_flags", "Extra CXX flags to be appended to the build command", ""),
    ("extra_link_flags", "Extra LD flags to be appended to the build command", ""),
    ("compiler_cache", "Command to prefix to the C and C++ compiler (e.g ccache)", ""),
    ("specs_file", "Specs file to use (e.g. rdimon.specs)", "")
)

if version_at_least(SCons.__version__, "4.0"):
    vars.Add(BoolVariable("export_compile_commands", "Export compile_commands.json file.", False))

env = Environment(variables=vars, ENV = os.environ)

build_path = env['build_dir']
# If build_dir is a relative path then add a #build/ prefix:
if not env['build_dir'].startswith('/'):
    SConsignFile('build/%s/.scons' % build_path)
    build_path = "#build/%s" % build_path
else:
    SConsignFile('%s/.scons' % build_path)

install_path = env['install_dir']
#If the install_dir is a relative path then assume it's from inside build_dir
if not env['install_dir'].startswith('/') and install_path != "":
    install_path = "%s/%s" % (build_path, install_path)

env.Append(LIBPATH = [build_path])
Export('env')
Export('vars')

def install_lib( lib ):
    # If there is no install folder, then there is nothing to do:
    if install_path == "":
        return lib
    return env.Install( "%s/lib/" % install_path, lib)
def install_bin( bin ):
    # If there is no install folder, then there is nothing to do:
    if install_path == "":
        return bin
    return env.Install( "%s/bin/" % install_path, bin)
def install_include( inc ):
    if install_path == "":
        return inc
    return env.Install( "%s/include/" % install_path, inc)

Export('install_lib')
Export('install_bin')

Help(vars.GenerateHelpText(env))

env.Append(CXXFLAGS = [
         '-Wextra','-Wdisabled-optimization','-Wformat=2',
         '-Winit-self','-Wstrict-overflow=2','-Wswitch-default',
         '-Woverloaded-virtual', '-Wformat-security',
         '-Wctor-dtor-privacy','-Wsign-promo','-Weffc++','-Wno-overlength-strings'])

env.Append(CXXFLAGS = ['-Wall','-std=c++14', '-pedantic' ])

env.Append(CPPDEFINES = ['_GLIBCXX_USE_NANOSLEEP'])

cpp_tool = {'linux': 'g++', 'android' : 'clang++'}

c_tool = {'linux':'gcc', 'android': 'clang'}

default_cpp_compiler = cpp_tool[env['os']]
default_c_compiler = c_tool[env['os']]
cpp_compiler = os.environ.get('CXX', default_cpp_compiler)
c_compiler = os.environ.get('CC', default_c_compiler)

if env['os'] == 'android' and ( 'clang++' not in cpp_compiler or 'clang' not in c_compiler ):
    print( "WARNING: Only clang is officially supported to build the Compute Kernel Writer (CKW) for Android")

if 'clang++' in cpp_compiler:
    env.Append(CXXFLAGS = ['-Wno-vla-extension'])
elif 'armclang' in cpp_compiler:
    pass
else:
    env.Append(CXXFLAGS = ['-Wlogical-op','-Wnoexcept','-Wstrict-null-sentinel','-Wno-misleading-indentation'])

if cpp_compiler == 'g++':
    # Don't strip comments that could include markers
    env.Append(CXXFLAGS = ['-C'])

if 'armv8-a' in env['arch']:
    env.Append(CXXFLAGS = ['-march=armv8-a'])

if 'x86_64' in env['arch']:
    env.Append(CXXFLAGS = ['-fPIC'])
    env.Append(CCFLAGS = ['-m64'])
    env.Append(LINKFLAGS = ['-m64'])

# Define toolchain
# The reason why we distinguish toolchain_prefix from compiler_prefix is for cases where the linkers/archivers use a
# different prefix than the compilers. An example is the NDK r20 toolchain
auto_toolchain_prefix = ""
if 'x86' not in env['arch']:
    if env['os'] == 'linux':
        auto_toolchain_prefix = "aarch64-linux-gnu-"
    elif env['os'] == 'android':
        auto_toolchain_prefix = "aarch64-tizen-linux-gnu-"

if env['build'] == 'native' or env["toolchain_prefix"] == "":
    toolchain_prefix = ""
elif env["toolchain_prefix"] == "auto":
    toolchain_prefix = auto_toolchain_prefix
else:
    toolchain_prefix = env["toolchain_prefix"]

if env['build'] == 'native' or env["compiler_prefix"] == "":
    compiler_prefix = ""
elif env["compiler_prefix"] == "auto":
    compiler_prefix = toolchain_prefix
else:
    compiler_prefix = env["compiler_prefix"]

env['CC'] = env['compiler_cache']+ " " + compiler_prefix + c_compiler
env['CXX'] = env['compiler_cache']+ " " + compiler_prefix + cpp_compiler
env['LD'] = toolchain_prefix + "ld"
env['AS'] = toolchain_prefix + "as"
env['AR'] = toolchain_prefix + "ar"
env['RANLIB'] = toolchain_prefix + "ranlib"

print("Using compilers:")
print("CC", env['CC'])
print("CXX", env['CXX'])

if not GetOption("help"):
    try:
        compiler_ver = check_output(env['CXX'].split() + ["-dumpversion"]).decode().strip()
    except OSError:
        print("ERROR: Compiler '%s' not found" % env['CXX'])
        Exit(1)

    if 'armclang' in cpp_compiler:
        pass
    elif 'clang++' not in cpp_compiler:
        if env['arch'] == 'arm64-v8.2-a' and not version_at_least(compiler_ver, '6.2.1'):
            print("GCC 6.2.1 or newer is required to compile armv8.2-a code")
            Exit(1)

        if version_at_least(compiler_ver, '6.1'):
            env.Append(CXXFLAGS = ['-Wno-ignored-attributes'])

        if compiler_ver == '4.8.3':
            env.Append(CXXFLAGS = ['-Wno-array-bounds'])

    # Add Android NDK toolchain specific flags
    if 'clang++' in cpp_compiler and env['os'] == 'android':
        # For NDK >= r21, clang 9 or above is used
        if version_at_least(compiler_ver, '9.0.0'):
            env['ndk_above_r21'] = True

        # For NDK >= r23, clang 12 or above is used. This condition detects NDK < r23
        if not version_at_least(compiler_ver, '12.0.0'):
            # System assembler is deprecated and integrated assembler is preferred since r23.
            # However integrated assembler has always been suppressed for NDK < r23.
            # Thus for backward compatibility, we include this flag only for NDK < r23
            env.Append(CXXFLAGS = ['-no-integrated-as'])

if env['Werror']:
    env.Append(CXXFLAGS = ['-Werror'])

if env['os'] == 'android':
    env.Append(CPPDEFINES = ['ANDROID'])
    env.Append(LINKFLAGS = ['-pie', '-static-libstdc++', '-ldl'])

if env['specs_file'] != "":
    env.Append(LINKFLAGS = ['-specs='+env['specs_file']])

if env['debug']:
    env['asserts'] = True
    env.Append(CXXFLAGS = ['-O0','-g','-gdwarf-2'])
    env.Append(CPPDEFINES = ['COMPUTE_KERNEL_WRITER_DEBUG_ENABLED'])
else:
    # Optimize for size
    env.Append(CXXFLAGS = ['-Os'])

if env['asserts']:
    env.Append(CPPDEFINES = ['COMPUTE_KERNEL_WRITER_ASSERTS_ENABLED'])
    env.Append(CXXFLAGS = ['-fstack-protector-strong'])

env.Append(CPPPATH = ['#/include', "#"])
env.Append(CXXFLAGS = env['extra_cxx_flags'])
env.Append(LINKFLAGS = env['extra_link_flags'])
env.Append(LIBS = [])

Export('version_at_least')

SConscript('./SConscript', variant_dir=build_path, duplicate=0)

# Tests
SConscript('./validation/SConscript', variant_dir='%s/validation' % build_path, duplicate=0)

# Unknown variables are not allowed
# Note: we must delay the call of UnknownVariables until after
# we have applied the Variables object to the construction environment
unknown = vars.UnknownVariables()
if unknown:
    print("Unknown variables: %s" % " ".join(unknown.keys()))
    Exit(1)