m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

431 lines
18 KiB

6 months ago
  1. """ Modified version of build_clib that handles fortran source files.
  2. """
  3. import os
  4. from glob import glob
  5. import shutil
  6. from distutils.command.build_clib import build_clib as old_build_clib
  7. from distutils.errors import DistutilsSetupError, DistutilsError, \
  8. DistutilsFileError
  9. from numpy.distutils import log
  10. from distutils.dep_util import newer_group
  11. from numpy.distutils.misc_util import (
  12. filter_sources, get_lib_source_files, get_numpy_include_dirs,
  13. has_cxx_sources, has_f_sources, is_sequence
  14. )
  15. from numpy.distutils.ccompiler_opt import new_ccompiler_opt
  16. # Fix Python distutils bug sf #1718574:
  17. _l = old_build_clib.user_options
  18. for _i in range(len(_l)):
  19. if _l[_i][0] in ['build-clib', 'build-temp']:
  20. _l[_i] = (_l[_i][0] + '=',) + _l[_i][1:]
  21. #
  22. class build_clib(old_build_clib):
  23. description = "build C/C++/F libraries used by Python extensions"
  24. user_options = old_build_clib.user_options + [
  25. ('fcompiler=', None,
  26. "specify the Fortran compiler type"),
  27. ('inplace', 'i', 'Build in-place'),
  28. ('parallel=', 'j',
  29. "number of parallel jobs"),
  30. ('warn-error', None,
  31. "turn all warnings into errors (-Werror)"),
  32. ('cpu-baseline=', None,
  33. "specify a list of enabled baseline CPU optimizations"),
  34. ('cpu-dispatch=', None,
  35. "specify a list of dispatched CPU optimizations"),
  36. ('disable-optimization', None,
  37. "disable CPU optimized code(dispatch,simd,fast...)"),
  38. ]
  39. boolean_options = old_build_clib.boolean_options + \
  40. ['inplace', 'warn-error', 'disable-optimization']
  41. def initialize_options(self):
  42. old_build_clib.initialize_options(self)
  43. self.fcompiler = None
  44. self.inplace = 0
  45. self.parallel = None
  46. self.warn_error = None
  47. self.cpu_baseline = None
  48. self.cpu_dispatch = None
  49. self.disable_optimization = None
  50. def finalize_options(self):
  51. if self.parallel:
  52. try:
  53. self.parallel = int(self.parallel)
  54. except ValueError as e:
  55. raise ValueError("--parallel/-j argument must be an integer") from e
  56. old_build_clib.finalize_options(self)
  57. self.set_undefined_options('build',
  58. ('parallel', 'parallel'),
  59. ('warn_error', 'warn_error'),
  60. ('cpu_baseline', 'cpu_baseline'),
  61. ('cpu_dispatch', 'cpu_dispatch'),
  62. ('disable_optimization', 'disable_optimization')
  63. )
  64. def have_f_sources(self):
  65. for (lib_name, build_info) in self.libraries:
  66. if has_f_sources(build_info.get('sources', [])):
  67. return True
  68. return False
  69. def have_cxx_sources(self):
  70. for (lib_name, build_info) in self.libraries:
  71. if has_cxx_sources(build_info.get('sources', [])):
  72. return True
  73. return False
  74. def run(self):
  75. if not self.libraries:
  76. return
  77. # Make sure that library sources are complete.
  78. languages = []
  79. # Make sure that extension sources are complete.
  80. self.run_command('build_src')
  81. for (lib_name, build_info) in self.libraries:
  82. l = build_info.get('language', None)
  83. if l and l not in languages:
  84. languages.append(l)
  85. from distutils.ccompiler import new_compiler
  86. self.compiler = new_compiler(compiler=self.compiler,
  87. dry_run=self.dry_run,
  88. force=self.force)
  89. self.compiler.customize(self.distribution,
  90. need_cxx=self.have_cxx_sources())
  91. if self.warn_error:
  92. self.compiler.compiler.append('-Werror')
  93. self.compiler.compiler_so.append('-Werror')
  94. libraries = self.libraries
  95. self.libraries = None
  96. self.compiler.customize_cmd(self)
  97. self.libraries = libraries
  98. self.compiler.show_customization()
  99. if not self.disable_optimization:
  100. dispatch_hpath = os.path.join("numpy", "distutils", "include", "npy_cpu_dispatch_config.h")
  101. dispatch_hpath = os.path.join(self.get_finalized_command("build_src").build_src, dispatch_hpath)
  102. opt_cache_path = os.path.abspath(
  103. os.path.join(self.build_temp, 'ccompiler_opt_cache_clib.py')
  104. )
  105. if hasattr(self, "compiler_opt"):
  106. # By default `CCompilerOpt` update the cache at the exit of
  107. # the process, which may lead to duplicate building
  108. # (see build_extension()/force_rebuild) if run() called
  109. # multiple times within the same os process/thread without
  110. # giving the chance the previous instances of `CCompilerOpt`
  111. # to update the cache.
  112. self.compiler_opt.cache_flush()
  113. self.compiler_opt = new_ccompiler_opt(
  114. compiler=self.compiler, dispatch_hpath=dispatch_hpath,
  115. cpu_baseline=self.cpu_baseline, cpu_dispatch=self.cpu_dispatch,
  116. cache_path=opt_cache_path
  117. )
  118. def report(copt):
  119. log.info("\n########### CLIB COMPILER OPTIMIZATION ###########")
  120. log.info(copt.report(full=True))
  121. import atexit
  122. atexit.register(report, self.compiler_opt)
  123. if self.have_f_sources():
  124. from numpy.distutils.fcompiler import new_fcompiler
  125. self._f_compiler = new_fcompiler(compiler=self.fcompiler,
  126. verbose=self.verbose,
  127. dry_run=self.dry_run,
  128. force=self.force,
  129. requiref90='f90' in languages,
  130. c_compiler=self.compiler)
  131. if self._f_compiler is not None:
  132. self._f_compiler.customize(self.distribution)
  133. libraries = self.libraries
  134. self.libraries = None
  135. self._f_compiler.customize_cmd(self)
  136. self.libraries = libraries
  137. self._f_compiler.show_customization()
  138. else:
  139. self._f_compiler = None
  140. self.build_libraries(self.libraries)
  141. if self.inplace:
  142. for l in self.distribution.installed_libraries:
  143. libname = self.compiler.library_filename(l.name)
  144. source = os.path.join(self.build_clib, libname)
  145. target = os.path.join(l.target_dir, libname)
  146. self.mkpath(l.target_dir)
  147. shutil.copy(source, target)
  148. def get_source_files(self):
  149. self.check_library_list(self.libraries)
  150. filenames = []
  151. for lib in self.libraries:
  152. filenames.extend(get_lib_source_files(lib))
  153. return filenames
  154. def build_libraries(self, libraries):
  155. for (lib_name, build_info) in libraries:
  156. self.build_a_library(build_info, lib_name, libraries)
  157. def build_a_library(self, build_info, lib_name, libraries):
  158. # default compilers
  159. compiler = self.compiler
  160. fcompiler = self._f_compiler
  161. sources = build_info.get('sources')
  162. if sources is None or not is_sequence(sources):
  163. raise DistutilsSetupError(("in 'libraries' option (library '%s'), " +
  164. "'sources' must be present and must be " +
  165. "a list of source filenames") % lib_name)
  166. sources = list(sources)
  167. c_sources, cxx_sources, f_sources, fmodule_sources \
  168. = filter_sources(sources)
  169. requiref90 = not not fmodule_sources or \
  170. build_info.get('language', 'c') == 'f90'
  171. # save source type information so that build_ext can use it.
  172. source_languages = []
  173. if c_sources:
  174. source_languages.append('c')
  175. if cxx_sources:
  176. source_languages.append('c++')
  177. if requiref90:
  178. source_languages.append('f90')
  179. elif f_sources:
  180. source_languages.append('f77')
  181. build_info['source_languages'] = source_languages
  182. lib_file = compiler.library_filename(lib_name,
  183. output_dir=self.build_clib)
  184. depends = sources + build_info.get('depends', [])
  185. force_rebuild = self.force
  186. if not self.disable_optimization and not self.compiler_opt.is_cached():
  187. log.debug("Detected changes on compiler optimizations")
  188. force_rebuild = True
  189. if not (force_rebuild or newer_group(depends, lib_file, 'newer')):
  190. log.debug("skipping '%s' library (up-to-date)", lib_name)
  191. return
  192. else:
  193. log.info("building '%s' library", lib_name)
  194. config_fc = build_info.get('config_fc', {})
  195. if fcompiler is not None and config_fc:
  196. log.info('using additional config_fc from setup script '
  197. 'for fortran compiler: %s'
  198. % (config_fc,))
  199. from numpy.distutils.fcompiler import new_fcompiler
  200. fcompiler = new_fcompiler(compiler=fcompiler.compiler_type,
  201. verbose=self.verbose,
  202. dry_run=self.dry_run,
  203. force=self.force,
  204. requiref90=requiref90,
  205. c_compiler=self.compiler)
  206. if fcompiler is not None:
  207. dist = self.distribution
  208. base_config_fc = dist.get_option_dict('config_fc').copy()
  209. base_config_fc.update(config_fc)
  210. fcompiler.customize(base_config_fc)
  211. # check availability of Fortran compilers
  212. if (f_sources or fmodule_sources) and fcompiler is None:
  213. raise DistutilsError("library %s has Fortran sources"
  214. " but no Fortran compiler found" % (lib_name))
  215. if fcompiler is not None:
  216. fcompiler.extra_f77_compile_args = build_info.get(
  217. 'extra_f77_compile_args') or []
  218. fcompiler.extra_f90_compile_args = build_info.get(
  219. 'extra_f90_compile_args') or []
  220. macros = build_info.get('macros')
  221. if macros is None:
  222. macros = []
  223. include_dirs = build_info.get('include_dirs')
  224. if include_dirs is None:
  225. include_dirs = []
  226. extra_postargs = build_info.get('extra_compiler_args') or []
  227. include_dirs.extend(get_numpy_include_dirs())
  228. # where compiled F90 module files are:
  229. module_dirs = build_info.get('module_dirs') or []
  230. module_build_dir = os.path.dirname(lib_file)
  231. if requiref90:
  232. self.mkpath(module_build_dir)
  233. if compiler.compiler_type == 'msvc':
  234. # this hack works around the msvc compiler attributes
  235. # problem, msvc uses its own convention :(
  236. c_sources += cxx_sources
  237. cxx_sources = []
  238. # filtering C dispatch-table sources when optimization is not disabled,
  239. # otherwise treated as normal sources.
  240. copt_c_sources = []
  241. copt_cxx_sources = []
  242. copt_baseline_flags = []
  243. copt_macros = []
  244. if not self.disable_optimization:
  245. bsrc_dir = self.get_finalized_command("build_src").build_src
  246. dispatch_hpath = os.path.join("numpy", "distutils", "include")
  247. dispatch_hpath = os.path.join(bsrc_dir, dispatch_hpath)
  248. include_dirs.append(dispatch_hpath)
  249. copt_build_src = None if self.inplace else bsrc_dir
  250. for _srcs, _dst, _ext in (
  251. ((c_sources,), copt_c_sources, ('.dispatch.c',)),
  252. ((c_sources, cxx_sources), copt_cxx_sources,
  253. ('.dispatch.cpp', '.dispatch.cxx'))
  254. ):
  255. for _src in _srcs:
  256. _dst += [
  257. _src.pop(_src.index(s))
  258. for s in _src[:] if s.endswith(_ext)
  259. ]
  260. copt_baseline_flags = self.compiler_opt.cpu_baseline_flags()
  261. else:
  262. copt_macros.append(("NPY_DISABLE_OPTIMIZATION", 1))
  263. objects = []
  264. if copt_cxx_sources:
  265. log.info("compiling C++ dispatch-able sources")
  266. objects += self.compiler_opt.try_dispatch(
  267. copt_c_sources,
  268. output_dir=self.build_temp,
  269. src_dir=copt_build_src,
  270. macros=macros + copt_macros,
  271. include_dirs=include_dirs,
  272. debug=self.debug,
  273. extra_postargs=extra_postargs,
  274. ccompiler=cxx_compiler
  275. )
  276. if copt_c_sources:
  277. log.info("compiling C dispatch-able sources")
  278. objects += self.compiler_opt.try_dispatch(copt_c_sources,
  279. output_dir=self.build_temp,
  280. src_dir=copt_build_src,
  281. macros=macros + copt_macros,
  282. include_dirs=include_dirs,
  283. debug=self.debug,
  284. extra_postargs=extra_postargs)
  285. if c_sources:
  286. log.info("compiling C sources")
  287. objects += compiler.compile(c_sources,
  288. output_dir=self.build_temp,
  289. macros=macros + copt_macros,
  290. include_dirs=include_dirs,
  291. debug=self.debug,
  292. extra_postargs=extra_postargs + copt_baseline_flags)
  293. if cxx_sources:
  294. log.info("compiling C++ sources")
  295. cxx_compiler = compiler.cxx_compiler()
  296. cxx_objects = cxx_compiler.compile(cxx_sources,
  297. output_dir=self.build_temp,
  298. macros=macros + copt_macros,
  299. include_dirs=include_dirs,
  300. debug=self.debug,
  301. extra_postargs=extra_postargs + copt_baseline_flags)
  302. objects.extend(cxx_objects)
  303. if f_sources or fmodule_sources:
  304. extra_postargs = []
  305. f_objects = []
  306. if requiref90:
  307. if fcompiler.module_dir_switch is None:
  308. existing_modules = glob('*.mod')
  309. extra_postargs += fcompiler.module_options(
  310. module_dirs, module_build_dir)
  311. if fmodule_sources:
  312. log.info("compiling Fortran 90 module sources")
  313. f_objects += fcompiler.compile(fmodule_sources,
  314. output_dir=self.build_temp,
  315. macros=macros,
  316. include_dirs=include_dirs,
  317. debug=self.debug,
  318. extra_postargs=extra_postargs)
  319. if requiref90 and self._f_compiler.module_dir_switch is None:
  320. # move new compiled F90 module files to module_build_dir
  321. for f in glob('*.mod'):
  322. if f in existing_modules:
  323. continue
  324. t = os.path.join(module_build_dir, f)
  325. if os.path.abspath(f) == os.path.abspath(t):
  326. continue
  327. if os.path.isfile(t):
  328. os.remove(t)
  329. try:
  330. self.move_file(f, module_build_dir)
  331. except DistutilsFileError:
  332. log.warn('failed to move %r to %r'
  333. % (f, module_build_dir))
  334. if f_sources:
  335. log.info("compiling Fortran sources")
  336. f_objects += fcompiler.compile(f_sources,
  337. output_dir=self.build_temp,
  338. macros=macros,
  339. include_dirs=include_dirs,
  340. debug=self.debug,
  341. extra_postargs=extra_postargs)
  342. else:
  343. f_objects = []
  344. if f_objects and not fcompiler.can_ccompiler_link(compiler):
  345. # Default linker cannot link Fortran object files, and results
  346. # need to be wrapped later. Instead of creating a real static
  347. # library, just keep track of the object files.
  348. listfn = os.path.join(self.build_clib,
  349. lib_name + '.fobjects')
  350. with open(listfn, 'w') as f:
  351. f.write("\n".join(os.path.abspath(obj) for obj in f_objects))
  352. listfn = os.path.join(self.build_clib,
  353. lib_name + '.cobjects')
  354. with open(listfn, 'w') as f:
  355. f.write("\n".join(os.path.abspath(obj) for obj in objects))
  356. # create empty "library" file for dependency tracking
  357. lib_fname = os.path.join(self.build_clib,
  358. lib_name + compiler.static_lib_extension)
  359. with open(lib_fname, 'wb') as f:
  360. pass
  361. else:
  362. # assume that default linker is suitable for
  363. # linking Fortran object files
  364. objects.extend(f_objects)
  365. compiler.create_static_lib(objects, lib_name,
  366. output_dir=self.build_clib,
  367. debug=self.debug)
  368. # fix library dependencies
  369. clib_libraries = build_info.get('libraries', [])
  370. for lname, binfo in libraries:
  371. if lname in clib_libraries:
  372. clib_libraries.extend(binfo.get('libraries', []))
  373. if clib_libraries:
  374. build_info['libraries'] = clib_libraries