Imported Upstream version 1.4.0
[platform/core/ml/nnfw.git] / infra / cmake / packages / ARMCompute / SConstruct
1 # Copyright (c) 2016, 2017 ARM Limited.
2 #
3 # SPDX-License-Identifier: MIT
4 #
5 # Permission is hereby granted, free of charge, to any person obtaining a copy
6 # of this software and associated documentation files (the "Software"), to
7 # deal in the Software without restriction, including without limitation the
8 # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
9 # sell copies of the Software, and to permit persons to whom the Software is
10 # furnished to do so, subject to the following conditions:
11 #
12 # The above copyright notice and this permission notice shall be included in all
13 # copies or substantial portions of the Software.
14 #
15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 # SOFTWARE.
22
23 import SCons
24 import os
25 import subprocess
26
27 def version_at_least(version, required):
28     end = min(len(version), len(required))
29
30     for i in range(0, end, 2):
31         if int(version[i]) < int(required[i]):
32             return False
33         elif int(version[i]) > int(required[i]):
34             return True
35
36     return True
37
38 vars = Variables("scons")
39 vars.AddVariables(
40     BoolVariable("debug", "Debug", False),
41     BoolVariable("asserts", "Enable asserts (this flag is forced to 1 for debug=1)", False),
42     BoolVariable("logging", "Logging (this flag is forced to 1 for debug=1)", False),
43     EnumVariable("arch", "Target Architecture", "armv7a", allowed_values=("armv7a", "arm64-v8a", "arm64-v8.2-a", "arm64-v8.2-a-sve", "x86_32", "x86_64")),
44     EnumVariable("os", "Target OS", "linux", allowed_values=("linux", "android", "tizen", "bare_metal")),
45     EnumVariable("build", "Build type", "cross_compile", allowed_values=("native", "cross_compile", "embed_only")),
46     BoolVariable("examples", "Build example programs", True),
47     BoolVariable("Werror", "Enable/disable the -Werror compilation flag", True),
48     BoolVariable("standalone", "Builds the tests as standalone executables, links statically with libgcc, libstdc++ and libarm_compute", False),
49     BoolVariable("opencl", "Enable OpenCL support", True),
50     BoolVariable("neon", "Enable Neon support", False),
51     BoolVariable("gles_compute", "Enable OpenGL ES Compute Shader support", False),
52     BoolVariable("embed_kernels", "Embed OpenCL kernels and OpenGL ES compute shaders in library binary", True),
53     BoolVariable("set_soname", "Set the library's soname and shlibversion (requires SCons 2.4 or above)", False),
54     BoolVariable("openmp", "Enable OpenMP backend", False),
55     BoolVariable("cppthreads", "Enable C++11 threads backend", True),
56     PathVariable("build_dir", "Specify sub-folder for the build", ".", PathVariable.PathAccept),
57     PathVariable("install_dir", "Specify sub-folder for the install", "", PathVariable.PathAccept),
58     ("extra_cxx_flags", "Extra CXX flags to be appended to the build command", ""),
59     ("extra_link_flags", "Extra LD flags to be appended to the build command", ""),
60     ("compiler_cache", "Command to prefix to the C and C++ compiler (e.g ccache)", "")
61 )
62
63 env = Environment(platform="posix", variables=vars, ENV = os.environ)
64 build_path = env['build_dir']
65 # If build_dir is a relative path then add a #build/ prefix:
66 if not env['build_dir'].startswith('/'):
67     SConsignFile('build/%s/.scons' % build_path)
68     build_path = "#build/%s" % build_path
69 else:
70     SConsignFile('%s/.scons' % build_path)
71
72 install_path = env['install_dir']
73 #If the install_dir is a relative path then assume it's from inside build_dir
74 if not env['install_dir'].startswith('/') and install_path != "":
75     install_path = "%s/%s" % (build_path, install_path)
76
77 env.Append(LIBPATH = [build_path])
78 Export('env')
79 Export('vars')
80
81 def install_lib( lib ):
82     # If there is no install folder, then there is nothing to do:
83     if install_path == "":
84         return lib
85     return env.Install( "%s/lib/" % install_path, lib)
86 def install_bin( bin ):
87     # If there is no install folder, then there is nothing to do:
88     if install_path == "":
89         return bin
90     return env.Install( "%s/bin/" % install_path, bin)
91 def install_include( inc ):
92     if install_path == "":
93         return inc
94     return env.Install( "%s/include/" % install_path, inc)
95
96 Export('install_lib')
97 Export('install_bin')
98
99 Help(vars.GenerateHelpText(env))
100
101 if env['build'] == "embed_only":
102     SConscript('./SConscript', variant_dir=build_path, duplicate=0)
103     Return()
104
105 if env['neon'] and 'x86' in env['arch']:
106     print("Cannot compile NEON for x86")
107     Exit(1)
108
109 if env['set_soname'] and not version_at_least(SCons.__version__, "2.4"):
110     print("Setting the library's SONAME / SHLIBVERSION requires SCons 2.4 or above")
111     print("Update your version of SCons or use set_soname=0")
112     Exit(1)
113
114 if env['os'] == 'bare_metal':
115     if env['cppthreads'] or env['openmp']:
116          print("ERROR: OpenMP and C++11 threads not supported in bare_metal. Use cppthreads=0 openmp=0")
117          Exit(1)
118
119 env.Append(CXXFLAGS = ['-Wno-deprecated-declarations','-Wall','-DARCH_ARM',
120          '-Wextra','-Wno-unused-parameter','-pedantic','-Wdisabled-optimization','-Wformat=2',
121          '-Winit-self','-Wstrict-overflow=2','-Wswitch-default',
122          '-fpermissive','-std=gnu++11','-Wno-vla','-Woverloaded-virtual',
123          '-Wctor-dtor-privacy','-Wsign-promo','-Weffc++','-Wno-format-nonliteral','-Wno-overlength-strings','-Wno-strict-overflow'])
124
125 env.Append(CPPDEFINES = ['_GLIBCXX_USE_NANOSLEEP'])
126
127 default_cpp_compiler = 'g++' if env['os'] != 'android' else 'clang++'
128 default_c_compiler = 'gcc' if env['os'] != 'android' else 'clang'
129 cpp_compiler = os.environ.get('CXX', default_cpp_compiler)
130 c_compiler = os.environ.get('CC', default_c_compiler)
131
132 if env['os'] == 'android' and ( 'clang++' not in cpp_compiler or 'clang' not in c_compiler ):
133     print( "WARNING: Only clang is officially supported to build the Compute Library for Android")
134
135 if 'clang++' in cpp_compiler:
136     env.Append(CXXFLAGS = ['-Wno-format-nonliteral','-Wno-deprecated-increment-bool','-Wno-vla-extension','-Wno-mismatched-tags'])
137 else:
138     env.Append(CXXFLAGS = ['-Wlogical-op','-Wnoexcept','-Wstrict-null-sentinel','-Wno-implicit-fallthrough'])
139
140 if env['cppthreads']:
141     env.Append(CPPDEFINES = [('ARM_COMPUTE_CPP_SCHEDULER', 1)])
142
143 if env['openmp']:
144     if 'clang++' in cpp_compiler:
145         print( "Clang does not support OpenMP. Use scheduler=cpp.")
146         Exit(1)
147
148     env.Append(CPPDEFINES = [('ARM_COMPUTE_OPENMP_SCHEDULER', 1)])
149     env.Append(CXXFLAGS = ['-fopenmp'])
150     env.Append(LINKFLAGS = ['-fopenmp'])
151
152 prefix = ""
153 if env['arch'] == 'armv7a':
154     env.Append(CXXFLAGS = ['-march=armv7-a', '-mthumb', '-mfpu=neon'])
155
156     if env['os'] == 'linux':
157         prefix = "arm-linux-gnueabihf-"
158         env.Append(CXXFLAGS = ['-mfloat-abi=hard'])
159     elif env['os'] == 'bare_metal':
160         prefix = "arm-eabi-"
161         env.Append(CXXFLAGS = ['-mfloat-abi=hard'])
162     elif env['os'] == 'android':
163         prefix = "arm-linux-androideabi-"
164         env.Append(CXXFLAGS = ['-mfloat-abi=softfp'])
165     elif env['os'] == 'tizen':
166         prefix = "arm-linux-gnueabi-"
167         env.Append(CXXFLAGS = ['-mfloat-abi=softfp'])
168 elif env['arch'] == 'arm64-v8a':
169     env.Append(CXXFLAGS = ['-march=armv8-a'])
170     env.Append(CPPDEFINES = ['ARM_COMPUTE_AARCH64_V8A','NO_DOT_IN_TOOLCHAIN'])
171     if env['os'] == 'linux':
172         prefix = "aarch64-linux-gnu-"
173     elif env['os'] == 'bare_metal':
174         prefix = "aarch64-elf-"
175     elif env['os'] == 'android':
176         prefix = "aarch64-linux-android-"
177     elif env['os'] == 'tizen':
178         prefix = "aarch64-linux-gnu-"
179     if 'clang++' in cpp_compiler:
180         env.Append(CXXFLAGS = ['-no-integrated-as'])
181 elif 'arm64-v8.2-a' in env['arch']:
182     if env['arch'] == 'arm64-v8.2-a-sve':
183         if env['os'] != 'bare_metal':
184             print("Only bare metal SVE is supported at the moment")
185             Exit(1)
186         env.Append(CXXFLAGS = ['-march=armv8.2-a+sve+fp16+dotprod'])
187     else:
188         env.Append(CXXFLAGS = ['-march=armv8.2-a+fp16']) # explicitly enable fp16 extension otherwise __ARM_FEATURE_FP16_VECTOR_ARITHMETIC is undefined
189         if env['os'] == 'linux':
190             prefix = "aarch64-linux-gnu-"
191         elif env['os'] == 'bare_metal':
192             prefix = "aarch64-elf-"
193         elif env['os'] == 'android':
194             prefix = "aarch64-linux-android-"
195         elif env['os'] == 'tizen':
196             prefix = "aarch64-linux-gnu-"
197     env.Append(CPPDEFINES = ['ARM_COMPUTE_AARCH64_V8_2','NO_DOT_IN_TOOLCHAIN'])
198     if 'clang++' in cpp_compiler:
199         env.Append(CXXFLAGS = ['-no-integrated-as'])
200 elif env['arch'] == 'x86_32':
201     env.Append(CCFLAGS = ['-m32'])
202     env.Append(LINKFLAGS = ['-m32'])
203 elif env['arch'] == 'x86_64':
204     env.Append(CCFLAGS = ['-m64'])
205     env.Append(LINKFLAGS = ['-m64'])
206
207 if env['build'] == 'native':
208     prefix = ""
209
210 env['CC'] = env['compiler_cache']+" "+prefix + c_compiler
211 env['CXX'] = env['compiler_cache']+" "+prefix + cpp_compiler
212 env['LD'] = prefix + "ld"
213 env['AS'] = prefix + "as"
214 env['AR'] = prefix + "ar"
215 env['RANLIB'] = prefix + "ranlib"
216
217 if not GetOption("help"):
218     try:
219         compiler_ver = subprocess.check_output(env['CXX'].split() + ["-dumpversion"]).strip()
220     except OSError:
221         print("ERROR: Compiler '%s' not found" % env['CXX'])
222         Exit(1)
223
224     if 'clang++' not in cpp_compiler:
225         if env['arch'] == 'arm64-v8.2-a' and not version_at_least(compiler_ver, '6.2.1'):
226             print("GCC 6.2.1 or newer is required to compile armv8.2-a code")
227             Exit(1)
228         elif env['arch'] == 'arm64-v8a' and not version_at_least(compiler_ver, '4.9'):
229             print("GCC 4.9 or newer is required to compile NEON code for AArch64")
230             Exit(1)
231
232         if version_at_least(compiler_ver, '6.1'):
233             env.Append(CXXFLAGS = ['-Wno-ignored-attributes'])
234
235         if compiler_ver == '4.8.3':
236             env.Append(CXXFLAGS = ['-Wno-array-bounds'])
237
238 if env['standalone']:
239     env.Append(CXXFLAGS = ['-fPIC'])
240     env.Append(LINKFLAGS = ['-static-libgcc','-static-libstdc++'])
241
242 if env['Werror']:
243     env.Append(CXXFLAGS = ['-Werror'])
244
245 if env['os'] == 'android':
246     env.Append(CPPDEFINES = ['ANDROID'])
247     env.Append(LINKFLAGS = ['-pie', '-static-libstdc++'])
248 elif env['os'] == 'bare_metal':
249     env.Append(LINKFLAGS = ['-static'])
250     env.Append(LINKFLAGS = ['-specs=rdimon.specs'])
251     env.Append(CXXFLAGS = ['-fPIC'])
252     env.Append(CPPDEFINES = ['NO_MULTI_THREADING'])
253     env.Append(CPPDEFINES = ['BARE_METAL'])
254
255 if env['opencl']:
256     if env['os'] in ['bare_metal'] or env['standalone']:
257         print("Cannot link OpenCL statically, which is required for bare metal / standalone builds")
258         Exit(1)
259
260 if env['gles_compute']:
261     if env['os'] in ['bare_metal'] or env['standalone']:
262         print("Cannot link OpenGLES statically, which is required for bare metal / standalone builds")
263         Exit(1)
264
265 if env["os"] not in ["android", "bare_metal"] and (env['opencl'] or env['cppthreads']):
266     env.Append(LIBS = ['pthread'])
267
268 if env['opencl'] or env['gles_compute']:
269     if env['embed_kernels']:
270         env.Append(CPPDEFINES = ['EMBEDDED_KERNELS'])
271
272 if env['debug']:
273     env['asserts'] = True
274     env['logging'] = True
275     env.Append(CXXFLAGS = ['-O0','-g','-gdwarf-2'])
276     env.Append(CPPDEFINES = ['ARM_COMPUTE_DEBUG_ENABLED'])
277 else:
278     env.Append(CXXFLAGS = ['-O3','-ftree-vectorize'])
279
280 if env['asserts']:
281     env.Append(CPPDEFINES = ['ARM_COMPUTE_ASSERTS_ENABLED'])
282     env.Append(CXXFLAGS = ['-fstack-protector-strong'])
283
284 if env['logging']:
285     env.Append(CPPDEFINES = ['ARM_COMPUTE_LOGGING_ENABLED'])
286
287 env.Append(CPPPATH = ['#/include', "#"])
288 env.Append(CXXFLAGS = env['extra_cxx_flags'])
289 env.Append(LINKFLAGS = env['extra_link_flags'])
290
291 Default( install_include("arm_compute"))
292 Default( install_include("support"))
293
294 Export('version_at_least')
295
296 if env['opencl']:
297     SConscript("./opencl-1.2-stubs/SConscript", variant_dir="%s/opencl-1.2-stubs" % build_path, duplicate=0)
298
299 if env['gles_compute'] and env['os'] != 'android':
300     env.Append(CPPPATH = ['#/include/linux'])
301     SConscript("./opengles-3.1-stubs/SConscript", variant_dir="%s/opengles-3.1-stubs" % build_path, duplicate=0)
302
303 SConscript('./SConscript', variant_dir=build_path, duplicate=0)
304
305 if env['examples'] and env['os'] != 'bare_metal':
306     SConscript('./examples/SConscript', variant_dir='%s/examples' % build_path, duplicate=0)
307
308 if env['os'] != 'bare_metal':
309     SConscript('./tests/SConscript', variant_dir='%s/tests' % build_path, duplicate=0)