emitmodule.py 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132
  1. """Generate C code for a Python C extension module from Python source code."""
  2. # FIXME: Basically nothing in this file operates on the level of a
  3. # single module and it should be renamed.
  4. from __future__ import annotations
  5. import json
  6. import os
  7. from typing import Iterable, List, Optional, Tuple, TypeVar
  8. from mypy.build import (
  9. BuildResult,
  10. BuildSource,
  11. State,
  12. build,
  13. compute_hash,
  14. create_metastore,
  15. get_cache_names,
  16. sorted_components,
  17. )
  18. from mypy.errors import CompileError
  19. from mypy.fscache import FileSystemCache
  20. from mypy.nodes import MypyFile
  21. from mypy.options import Options
  22. from mypy.plugin import Plugin, ReportConfigContext
  23. from mypy.util import hash_digest
  24. from mypyc.codegen.cstring import c_string_initializer
  25. from mypyc.codegen.emit import Emitter, EmitterContext, HeaderDeclaration, c_array_initializer
  26. from mypyc.codegen.emitclass import generate_class, generate_class_type_decl
  27. from mypyc.codegen.emitfunc import generate_native_function, native_function_header
  28. from mypyc.codegen.emitwrapper import (
  29. generate_legacy_wrapper_function,
  30. generate_wrapper_function,
  31. legacy_wrapper_function_header,
  32. wrapper_function_header,
  33. )
  34. from mypyc.codegen.literals import Literals
  35. from mypyc.common import (
  36. MODULE_PREFIX,
  37. PREFIX,
  38. RUNTIME_C_FILES,
  39. TOP_LEVEL_NAME,
  40. shared_lib_name,
  41. short_id_from_name,
  42. use_fastcall,
  43. use_vectorcall,
  44. )
  45. from mypyc.errors import Errors
  46. from mypyc.ir.class_ir import ClassIR
  47. from mypyc.ir.func_ir import FuncIR
  48. from mypyc.ir.module_ir import ModuleIR, ModuleIRs, deserialize_modules
  49. from mypyc.ir.ops import DeserMaps, LoadLiteral
  50. from mypyc.ir.rtypes import RType
  51. from mypyc.irbuild.main import build_ir
  52. from mypyc.irbuild.mapper import Mapper
  53. from mypyc.irbuild.prepare import load_type_map
  54. from mypyc.namegen import NameGenerator, exported_name
  55. from mypyc.options import CompilerOptions
  56. from mypyc.transform.exceptions import insert_exception_handling
  57. from mypyc.transform.refcount import insert_ref_count_opcodes
  58. from mypyc.transform.uninit import insert_uninit_checks
  59. # All of the modules being compiled are divided into "groups". A group
  60. # is a set of modules that are placed into the same shared library.
  61. # Two common configurations are that every module is placed in a group
  62. # by itself (fully separate compilation) and that every module is
  63. # placed in the same group (fully whole-program compilation), but we
  64. # support finer-grained control of the group as well.
  65. #
  66. # In fully whole-program compilation, we will generate N+1 extension
  67. # modules: one shim per module and one shared library containing all
  68. # the actual code.
  69. # In fully separate compilation, we (unfortunately) will generate 2*N
  70. # extension modules: one shim per module and also one library containing
  71. # each module's actual code. (This might be fixable in the future,
  72. # but allows a clean separation between setup of the export tables
  73. # (see generate_export_table) and running module top levels.)
  74. #
  75. # A group is represented as a list of BuildSources containing all of
  76. # its modules along with the name of the group. (Which can be None
  77. # only if we are compiling only a single group with a single file in it
  78. # and not using shared libraries).
  79. Group = Tuple[List[BuildSource], Optional[str]]
  80. Groups = List[Group]
  81. # A list of (file name, file contents) pairs.
  82. FileContents = List[Tuple[str, str]]
  83. class MarkedDeclaration:
  84. """Add a mark, useful for topological sort."""
  85. def __init__(self, declaration: HeaderDeclaration, mark: bool) -> None:
  86. self.declaration = declaration
  87. self.mark = False
  88. class MypycPlugin(Plugin):
  89. """Plugin for making mypyc interoperate properly with mypy incremental mode.
  90. Basically the point of this plugin is to force mypy to recheck things
  91. based on the demands of mypyc in a couple situations:
  92. * Any modules in the same group must be compiled together, so we
  93. tell mypy that modules depend on all their groupmates.
  94. * If the IR metadata is missing or stale or any of the generated
  95. C source files associated missing or stale, then we need to
  96. recompile the module so we mark it as stale.
  97. """
  98. def __init__(
  99. self, options: Options, compiler_options: CompilerOptions, groups: Groups
  100. ) -> None:
  101. super().__init__(options)
  102. self.group_map: dict[str, tuple[str | None, list[str]]] = {}
  103. for sources, name in groups:
  104. modules = sorted(source.module for source in sources)
  105. for id in modules:
  106. self.group_map[id] = (name, modules)
  107. self.compiler_options = compiler_options
  108. self.metastore = create_metastore(options)
  109. def report_config_data(self, ctx: ReportConfigContext) -> tuple[str | None, list[str]] | None:
  110. # The config data we report is the group map entry for the module.
  111. # If the data is being used to check validity, we do additional checks
  112. # that the IR cache exists and matches the metadata cache and all
  113. # output source files exist and are up to date.
  114. id, path, is_check = ctx.id, ctx.path, ctx.is_check
  115. if id not in self.group_map:
  116. return None
  117. # If we aren't doing validity checks, just return the cache data
  118. if not is_check:
  119. return self.group_map[id]
  120. # Load the metadata and IR cache
  121. meta_path, _, _ = get_cache_names(id, path, self.options)
  122. ir_path = get_ir_cache_name(id, path, self.options)
  123. try:
  124. meta_json = self.metastore.read(meta_path)
  125. ir_json = self.metastore.read(ir_path)
  126. except FileNotFoundError:
  127. # This could happen if mypyc failed after mypy succeeded
  128. # in the previous run or if some cache files got
  129. # deleted. No big deal, just fail to load the cache.
  130. return None
  131. ir_data = json.loads(ir_json)
  132. # Check that the IR cache matches the metadata cache
  133. if compute_hash(meta_json) != ir_data["meta_hash"]:
  134. return None
  135. # Check that all of the source files are present and as
  136. # expected. The main situation where this would come up is the
  137. # user deleting the build directory without deleting
  138. # .mypy_cache, which we should handle gracefully.
  139. for path, hash in ir_data["src_hashes"].items():
  140. try:
  141. with open(os.path.join(self.compiler_options.target_dir, path), "rb") as f:
  142. contents = f.read()
  143. except FileNotFoundError:
  144. return None
  145. real_hash = hash_digest(contents)
  146. if hash != real_hash:
  147. return None
  148. return self.group_map[id]
  149. def get_additional_deps(self, file: MypyFile) -> list[tuple[int, str, int]]:
  150. # Report dependency on modules in the module's group
  151. return [(10, id, -1) for id in self.group_map.get(file.fullname, (None, []))[1]]
  152. def parse_and_typecheck(
  153. sources: list[BuildSource],
  154. options: Options,
  155. compiler_options: CompilerOptions,
  156. groups: Groups,
  157. fscache: FileSystemCache | None = None,
  158. alt_lib_path: str | None = None,
  159. ) -> BuildResult:
  160. assert options.strict_optional, "strict_optional must be turned on"
  161. result = build(
  162. sources=sources,
  163. options=options,
  164. alt_lib_path=alt_lib_path,
  165. fscache=fscache,
  166. extra_plugins=[MypycPlugin(options, compiler_options, groups)],
  167. )
  168. if result.errors:
  169. raise CompileError(result.errors)
  170. return result
  171. def compile_scc_to_ir(
  172. scc: list[MypyFile],
  173. result: BuildResult,
  174. mapper: Mapper,
  175. compiler_options: CompilerOptions,
  176. errors: Errors,
  177. ) -> ModuleIRs:
  178. """Compile an SCC into ModuleIRs.
  179. Any modules that this SCC depends on must have either compiled or
  180. loaded from a cache into mapper.
  181. Arguments:
  182. scc: The list of MypyFiles to compile
  183. result: The BuildResult from the mypy front-end
  184. mapper: The Mapper object mapping mypy ASTs to class and func IRs
  185. compiler_options: The compilation options
  186. errors: Where to report any errors encountered
  187. Returns the IR of the modules.
  188. """
  189. if compiler_options.verbose:
  190. print("Compiling {}".format(", ".join(x.name for x in scc)))
  191. # Generate basic IR, with missing exception and refcount handling.
  192. modules = build_ir(scc, result.graph, result.types, mapper, compiler_options, errors)
  193. if errors.num_errors > 0:
  194. return modules
  195. # Insert uninit checks.
  196. for module in modules.values():
  197. for fn in module.functions:
  198. insert_uninit_checks(fn)
  199. # Insert exception handling.
  200. for module in modules.values():
  201. for fn in module.functions:
  202. insert_exception_handling(fn)
  203. # Insert refcount handling.
  204. for module in modules.values():
  205. for fn in module.functions:
  206. insert_ref_count_opcodes(fn)
  207. return modules
  208. def compile_modules_to_ir(
  209. result: BuildResult, mapper: Mapper, compiler_options: CompilerOptions, errors: Errors
  210. ) -> ModuleIRs:
  211. """Compile a collection of modules into ModuleIRs.
  212. The modules to compile are specified as part of mapper's group_map.
  213. Returns the IR of the modules.
  214. """
  215. deser_ctx = DeserMaps({}, {})
  216. modules = {}
  217. # Process the graph by SCC in topological order, like we do in mypy.build
  218. for scc in sorted_components(result.graph):
  219. scc_states = [result.graph[id] for id in scc]
  220. trees = [st.tree for st in scc_states if st.id in mapper.group_map and st.tree]
  221. if not trees:
  222. continue
  223. fresh = all(id not in result.manager.rechecked_modules for id in scc)
  224. if fresh:
  225. load_scc_from_cache(trees, result, mapper, deser_ctx)
  226. else:
  227. scc_ir = compile_scc_to_ir(trees, result, mapper, compiler_options, errors)
  228. modules.update(scc_ir)
  229. return modules
  230. def compile_ir_to_c(
  231. groups: Groups,
  232. modules: ModuleIRs,
  233. result: BuildResult,
  234. mapper: Mapper,
  235. compiler_options: CompilerOptions,
  236. ) -> dict[str | None, list[tuple[str, str]]]:
  237. """Compile a collection of ModuleIRs to C source text.
  238. Returns a dictionary mapping group names to a list of (file name,
  239. file text) pairs.
  240. """
  241. source_paths = {
  242. source.module: result.graph[source.module].xpath
  243. for sources, _ in groups
  244. for source in sources
  245. }
  246. names = NameGenerator([[source.module for source in sources] for sources, _ in groups])
  247. # Generate C code for each compilation group. Each group will be
  248. # compiled into a separate extension module.
  249. ctext: dict[str | None, list[tuple[str, str]]] = {}
  250. for group_sources, group_name in groups:
  251. group_modules = {
  252. source.module: modules[source.module]
  253. for source in group_sources
  254. if source.module in modules
  255. }
  256. if not group_modules:
  257. ctext[group_name] = []
  258. continue
  259. generator = GroupGenerator(
  260. group_modules, source_paths, group_name, mapper.group_map, names, compiler_options
  261. )
  262. ctext[group_name] = generator.generate_c_for_modules()
  263. return ctext
  264. def get_ir_cache_name(id: str, path: str, options: Options) -> str:
  265. meta_path, _, _ = get_cache_names(id, path, options)
  266. return meta_path.replace(".meta.json", ".ir.json")
  267. def get_state_ir_cache_name(state: State) -> str:
  268. return get_ir_cache_name(state.id, state.xpath, state.options)
  269. def write_cache(
  270. modules: ModuleIRs,
  271. result: BuildResult,
  272. group_map: dict[str, str | None],
  273. ctext: dict[str | None, list[tuple[str, str]]],
  274. ) -> None:
  275. """Write out the cache information for modules.
  276. Each module has the following cache information written (which is
  277. in addition to the cache information written by mypy itself):
  278. * A serialized version of its mypyc IR, minus the bodies of
  279. functions. This allows code that depends on it to use
  280. these serialized data structures when compiling against it
  281. instead of needing to recompile it. (Compiling against a
  282. module requires access to both its mypy and mypyc data
  283. structures.)
  284. * The hash of the mypy metadata cache file for the module.
  285. This is used to ensure that the mypyc cache and the mypy
  286. cache are in sync and refer to the same version of the code.
  287. This is particularly important if mypyc crashes/errors/is
  288. stopped after mypy has written its cache but before mypyc has.
  289. * The hashes of all of the source file outputs for the group
  290. the module is in. This is so that the module will be
  291. recompiled if the source outputs are missing.
  292. """
  293. hashes = {}
  294. for name, files in ctext.items():
  295. hashes[name] = {file: compute_hash(data) for file, data in files}
  296. # Write out cache data
  297. for id, module in modules.items():
  298. st = result.graph[id]
  299. meta_path, _, _ = get_cache_names(id, st.xpath, result.manager.options)
  300. # If the metadata isn't there, skip writing the cache.
  301. try:
  302. meta_data = result.manager.metastore.read(meta_path)
  303. except OSError:
  304. continue
  305. newpath = get_state_ir_cache_name(st)
  306. ir_data = {
  307. "ir": module.serialize(),
  308. "meta_hash": compute_hash(meta_data),
  309. "src_hashes": hashes[group_map[id]],
  310. }
  311. result.manager.metastore.write(newpath, json.dumps(ir_data, separators=(",", ":")))
  312. result.manager.metastore.commit()
  313. def load_scc_from_cache(
  314. scc: list[MypyFile], result: BuildResult, mapper: Mapper, ctx: DeserMaps
  315. ) -> ModuleIRs:
  316. """Load IR for an SCC of modules from the cache.
  317. Arguments and return are as compile_scc_to_ir.
  318. """
  319. cache_data = {
  320. k.fullname: json.loads(
  321. result.manager.metastore.read(get_state_ir_cache_name(result.graph[k.fullname]))
  322. )["ir"]
  323. for k in scc
  324. }
  325. modules = deserialize_modules(cache_data, ctx)
  326. load_type_map(mapper, scc, ctx)
  327. return modules
  328. def compile_modules_to_c(
  329. result: BuildResult, compiler_options: CompilerOptions, errors: Errors, groups: Groups
  330. ) -> tuple[ModuleIRs, list[FileContents]]:
  331. """Compile Python module(s) to the source of Python C extension modules.
  332. This generates the source code for the "shared library" module
  333. for each group. The shim modules are generated in mypyc.build.
  334. Each shared library module provides, for each module in its group,
  335. a PyCapsule containing an initialization function.
  336. Additionally, it provides a capsule containing an export table of
  337. pointers to all of the group's functions and static variables.
  338. Arguments:
  339. result: The BuildResult from the mypy front-end
  340. compiler_options: The compilation options
  341. errors: Where to report any errors encountered
  342. groups: The groups that we are compiling. See documentation of Groups type above.
  343. Returns the IR of the modules and a list containing the generated files for each group.
  344. """
  345. # Construct a map from modules to what group they belong to
  346. group_map = {source.module: lib_name for group, lib_name in groups for source in group}
  347. mapper = Mapper(group_map)
  348. # Sometimes when we call back into mypy, there might be errors.
  349. # We don't want to crash when that happens.
  350. result.manager.errors.set_file(
  351. "<mypyc>", module=None, scope=None, options=result.manager.options
  352. )
  353. modules = compile_modules_to_ir(result, mapper, compiler_options, errors)
  354. ctext = compile_ir_to_c(groups, modules, result, mapper, compiler_options)
  355. if errors.num_errors == 0:
  356. write_cache(modules, result, group_map, ctext)
  357. return modules, [ctext[name] for _, name in groups]
  358. def generate_function_declaration(fn: FuncIR, emitter: Emitter) -> None:
  359. emitter.context.declarations[emitter.native_function_name(fn.decl)] = HeaderDeclaration(
  360. f"{native_function_header(fn.decl, emitter)};", needs_export=True
  361. )
  362. if fn.name != TOP_LEVEL_NAME:
  363. if is_fastcall_supported(fn, emitter.capi_version):
  364. emitter.context.declarations[PREFIX + fn.cname(emitter.names)] = HeaderDeclaration(
  365. f"{wrapper_function_header(fn, emitter.names)};"
  366. )
  367. else:
  368. emitter.context.declarations[PREFIX + fn.cname(emitter.names)] = HeaderDeclaration(
  369. f"{legacy_wrapper_function_header(fn, emitter.names)};"
  370. )
  371. def pointerize(decl: str, name: str) -> str:
  372. """Given a C decl and its name, modify it to be a declaration to a pointer."""
  373. # This doesn't work in general but does work for all our types...
  374. if "(" in decl:
  375. # Function pointer. Stick an * in front of the name and wrap it in parens.
  376. return decl.replace(name, f"(*{name})")
  377. else:
  378. # Non-function pointer. Just stick an * in front of the name.
  379. return decl.replace(name, f"*{name}")
  380. def group_dir(group_name: str) -> str:
  381. """Given a group name, return the relative directory path for it."""
  382. return os.sep.join(group_name.split(".")[:-1])
  383. class GroupGenerator:
  384. def __init__(
  385. self,
  386. modules: dict[str, ModuleIR],
  387. source_paths: dict[str, str],
  388. group_name: str | None,
  389. group_map: dict[str, str | None],
  390. names: NameGenerator,
  391. compiler_options: CompilerOptions,
  392. ) -> None:
  393. """Generator for C source for a compilation group.
  394. The code for a compilation group contains an internal and an
  395. external .h file, and then one .c if not in multi_file mode or
  396. one .c file per module if in multi_file mode.)
  397. Arguments:
  398. modules: (name, ir) pairs for each module in the group
  399. source_paths: Map from module names to source file paths
  400. group_name: The name of the group (or None if this is single-module compilation)
  401. group_map: A map of modules to their group names
  402. names: The name generator for the compilation
  403. multi_file: Whether to put each module in its own source file regardless
  404. of group structure.
  405. """
  406. self.modules = modules
  407. self.source_paths = source_paths
  408. self.context = EmitterContext(names, group_name, group_map)
  409. self.names = names
  410. # Initializations of globals to simple values that we can't
  411. # do statically because the windows loader is bad.
  412. self.simple_inits: list[tuple[str, str]] = []
  413. self.group_name = group_name
  414. self.use_shared_lib = group_name is not None
  415. self.compiler_options = compiler_options
  416. self.multi_file = compiler_options.multi_file
  417. @property
  418. def group_suffix(self) -> str:
  419. return "_" + exported_name(self.group_name) if self.group_name else ""
  420. @property
  421. def short_group_suffix(self) -> str:
  422. return "_" + exported_name(self.group_name.split(".")[-1]) if self.group_name else ""
  423. def generate_c_for_modules(self) -> list[tuple[str, str]]:
  424. file_contents = []
  425. multi_file = self.use_shared_lib and self.multi_file
  426. # Collect all literal refs in IR.
  427. for module in self.modules.values():
  428. for fn in module.functions:
  429. collect_literals(fn, self.context.literals)
  430. base_emitter = Emitter(self.context)
  431. # Optionally just include the runtime library c files to
  432. # reduce the number of compiler invocations needed
  433. if self.compiler_options.include_runtime_files:
  434. for name in RUNTIME_C_FILES:
  435. base_emitter.emit_line(f'#include "{name}"')
  436. base_emitter.emit_line(f'#include "__native{self.short_group_suffix}.h"')
  437. base_emitter.emit_line(f'#include "__native_internal{self.short_group_suffix}.h"')
  438. emitter = base_emitter
  439. self.generate_literal_tables()
  440. for module_name, module in self.modules.items():
  441. if multi_file:
  442. emitter = Emitter(self.context)
  443. emitter.emit_line(f'#include "__native{self.short_group_suffix}.h"')
  444. emitter.emit_line(f'#include "__native_internal{self.short_group_suffix}.h"')
  445. self.declare_module(module_name, emitter)
  446. self.declare_internal_globals(module_name, emitter)
  447. self.declare_imports(module.imports, emitter)
  448. for cl in module.classes:
  449. if cl.is_ext_class:
  450. generate_class(cl, module_name, emitter)
  451. # Generate Python extension module definitions and module initialization functions.
  452. self.generate_module_def(emitter, module_name, module)
  453. for fn in module.functions:
  454. emitter.emit_line()
  455. generate_native_function(fn, emitter, self.source_paths[module_name], module_name)
  456. if fn.name != TOP_LEVEL_NAME:
  457. emitter.emit_line()
  458. if is_fastcall_supported(fn, emitter.capi_version):
  459. generate_wrapper_function(
  460. fn, emitter, self.source_paths[module_name], module_name
  461. )
  462. else:
  463. generate_legacy_wrapper_function(
  464. fn, emitter, self.source_paths[module_name], module_name
  465. )
  466. if multi_file:
  467. name = f"__native_{emitter.names.private_name(module_name)}.c"
  468. file_contents.append((name, "".join(emitter.fragments)))
  469. # The external header file contains type declarations while
  470. # the internal contains declarations of functions and objects
  471. # (which are shared between shared libraries via dynamic
  472. # exports tables and not accessed directly.)
  473. ext_declarations = Emitter(self.context)
  474. ext_declarations.emit_line(f"#ifndef MYPYC_NATIVE{self.group_suffix}_H")
  475. ext_declarations.emit_line(f"#define MYPYC_NATIVE{self.group_suffix}_H")
  476. ext_declarations.emit_line("#include <Python.h>")
  477. ext_declarations.emit_line("#include <CPy.h>")
  478. declarations = Emitter(self.context)
  479. declarations.emit_line(f"#ifndef MYPYC_NATIVE_INTERNAL{self.group_suffix}_H")
  480. declarations.emit_line(f"#define MYPYC_NATIVE_INTERNAL{self.group_suffix}_H")
  481. declarations.emit_line("#include <Python.h>")
  482. declarations.emit_line("#include <CPy.h>")
  483. declarations.emit_line(f'#include "__native{self.short_group_suffix}.h"')
  484. declarations.emit_line()
  485. declarations.emit_line("int CPyGlobalsInit(void);")
  486. declarations.emit_line()
  487. for module_name, module in self.modules.items():
  488. self.declare_finals(module_name, module.final_names, declarations)
  489. for cl in module.classes:
  490. generate_class_type_decl(cl, emitter, ext_declarations, declarations)
  491. for fn in module.functions:
  492. generate_function_declaration(fn, declarations)
  493. for lib in sorted(self.context.group_deps):
  494. elib = exported_name(lib)
  495. short_lib = exported_name(lib.split(".")[-1])
  496. declarations.emit_lines(
  497. "#include <{}>".format(os.path.join(group_dir(lib), f"__native_{short_lib}.h")),
  498. f"struct export_table_{elib} exports_{elib};",
  499. )
  500. sorted_decls = self.toposort_declarations()
  501. emitter = base_emitter
  502. self.generate_globals_init(emitter)
  503. emitter.emit_line()
  504. for declaration in sorted_decls:
  505. decls = ext_declarations if declaration.is_type else declarations
  506. if not declaration.is_type:
  507. decls.emit_lines(f"extern {declaration.decl[0]}", *declaration.decl[1:])
  508. # If there is a definition, emit it. Otherwise repeat the declaration
  509. # (without an extern).
  510. if declaration.defn:
  511. emitter.emit_lines(*declaration.defn)
  512. else:
  513. emitter.emit_lines(*declaration.decl)
  514. else:
  515. decls.emit_lines(*declaration.decl)
  516. if self.group_name:
  517. self.generate_export_table(ext_declarations, emitter)
  518. self.generate_shared_lib_init(emitter)
  519. ext_declarations.emit_line("#endif")
  520. declarations.emit_line("#endif")
  521. output_dir = group_dir(self.group_name) if self.group_name else ""
  522. return file_contents + [
  523. (
  524. os.path.join(output_dir, f"__native{self.short_group_suffix}.c"),
  525. "".join(emitter.fragments),
  526. ),
  527. (
  528. os.path.join(output_dir, f"__native_internal{self.short_group_suffix}.h"),
  529. "".join(declarations.fragments),
  530. ),
  531. (
  532. os.path.join(output_dir, f"__native{self.short_group_suffix}.h"),
  533. "".join(ext_declarations.fragments),
  534. ),
  535. ]
  536. def generate_literal_tables(self) -> None:
  537. """Generate tables containing descriptions of Python literals to construct.
  538. We will store the constructed literals in a single array that contains
  539. literals of all types. This way we can refer to an arbitrary literal by
  540. its index.
  541. """
  542. literals = self.context.literals
  543. # During module initialization we store all the constructed objects here
  544. self.declare_global("PyObject *[%d]" % literals.num_literals(), "CPyStatics")
  545. # Descriptions of str literals
  546. init_str = c_string_array_initializer(literals.encoded_str_values())
  547. self.declare_global("const char * const []", "CPyLit_Str", initializer=init_str)
  548. # Descriptions of bytes literals
  549. init_bytes = c_string_array_initializer(literals.encoded_bytes_values())
  550. self.declare_global("const char * const []", "CPyLit_Bytes", initializer=init_bytes)
  551. # Descriptions of int literals
  552. init_int = c_string_array_initializer(literals.encoded_int_values())
  553. self.declare_global("const char * const []", "CPyLit_Int", initializer=init_int)
  554. # Descriptions of float literals
  555. init_floats = c_array_initializer(literals.encoded_float_values())
  556. self.declare_global("const double []", "CPyLit_Float", initializer=init_floats)
  557. # Descriptions of complex literals
  558. init_complex = c_array_initializer(literals.encoded_complex_values())
  559. self.declare_global("const double []", "CPyLit_Complex", initializer=init_complex)
  560. # Descriptions of tuple literals
  561. init_tuple = c_array_initializer(literals.encoded_tuple_values())
  562. self.declare_global("const int []", "CPyLit_Tuple", initializer=init_tuple)
  563. # Descriptions of frozenset literals
  564. init_frozenset = c_array_initializer(literals.encoded_frozenset_values())
  565. self.declare_global("const int []", "CPyLit_FrozenSet", initializer=init_frozenset)
  566. def generate_export_table(self, decl_emitter: Emitter, code_emitter: Emitter) -> None:
  567. """Generate the declaration and definition of the group's export struct.
  568. To avoid needing to deal with deeply platform specific issues
  569. involving dynamic library linking (and some possibly
  570. insurmountable issues involving cyclic dependencies), compiled
  571. code accesses functions and data in other compilation groups
  572. via an explicit "export struct".
  573. Each group declares a struct type that contains a pointer to
  574. every function and static variable it exports. It then
  575. populates this struct and stores a pointer to it in a capsule
  576. stored as an attribute named 'exports' on the group's shared
  577. library's python module.
  578. On load, a group's init function will import all of its
  579. dependencies' exports tables using the capsule mechanism and
  580. copy the contents into a local copy of the table (to eliminate
  581. the need for a pointer indirection when accessing it).
  582. Then, all calls to functions in another group and accesses to statics
  583. from another group are done indirectly via the export table.
  584. For example, a group containing a module b, where b contains a class B
  585. and a function bar, would declare an export table like:
  586. struct export_table_b {
  587. PyTypeObject **CPyType_B;
  588. PyObject *(*CPyDef_B)(CPyTagged cpy_r_x);
  589. CPyTagged (*CPyDef_B___foo)(PyObject *cpy_r_self, CPyTagged cpy_r_y);
  590. tuple_T2OI (*CPyDef_bar)(PyObject *cpy_r_x);
  591. char (*CPyDef___top_level__)(void);
  592. };
  593. that would be initialized with:
  594. static struct export_table_b exports = {
  595. &CPyType_B,
  596. &CPyDef_B,
  597. &CPyDef_B___foo,
  598. &CPyDef_bar,
  599. &CPyDef___top_level__,
  600. };
  601. To call `b.foo`, then, a function in another group would do
  602. `exports_b.CPyDef_bar(...)`.
  603. """
  604. decls = decl_emitter.context.declarations
  605. decl_emitter.emit_lines("", f"struct export_table{self.group_suffix} {{")
  606. for name, decl in decls.items():
  607. if decl.needs_export:
  608. decl_emitter.emit_line(pointerize("\n".join(decl.decl), name))
  609. decl_emitter.emit_line("};")
  610. code_emitter.emit_lines("", f"static struct export_table{self.group_suffix} exports = {{")
  611. for name, decl in decls.items():
  612. if decl.needs_export:
  613. code_emitter.emit_line(f"&{name},")
  614. code_emitter.emit_line("};")
  615. def generate_shared_lib_init(self, emitter: Emitter) -> None:
  616. """Generate the init function for a shared library.
  617. A shared library contains all of the actual code for a
  618. compilation group.
  619. The init function is responsible for creating Capsules that
  620. wrap pointers to the initialization function of all the real
  621. init functions for modules in this shared library as well as
  622. the export table containing all of the exported functions and
  623. values from all the modules.
  624. These capsules are stored in attributes of the shared library.
  625. """
  626. assert self.group_name is not None
  627. emitter.emit_line()
  628. emitter.emit_lines(
  629. "PyMODINIT_FUNC PyInit_{}(void)".format(
  630. shared_lib_name(self.group_name).split(".")[-1]
  631. ),
  632. "{",
  633. (
  634. 'static PyModuleDef def = {{ PyModuleDef_HEAD_INIT, "{}", NULL, -1, NULL, NULL }};'.format(
  635. shared_lib_name(self.group_name)
  636. )
  637. ),
  638. "int res;",
  639. "PyObject *capsule;",
  640. "PyObject *tmp;",
  641. "static PyObject *module;",
  642. "if (module) {",
  643. "Py_INCREF(module);",
  644. "return module;",
  645. "}",
  646. "module = PyModule_Create(&def);",
  647. "if (!module) {",
  648. "goto fail;",
  649. "}",
  650. "",
  651. )
  652. emitter.emit_lines(
  653. 'capsule = PyCapsule_New(&exports, "{}.exports", NULL);'.format(
  654. shared_lib_name(self.group_name)
  655. ),
  656. "if (!capsule) {",
  657. "goto fail;",
  658. "}",
  659. 'res = PyObject_SetAttrString(module, "exports", capsule);',
  660. "Py_DECREF(capsule);",
  661. "if (res < 0) {",
  662. "goto fail;",
  663. "}",
  664. "",
  665. )
  666. for mod in self.modules:
  667. name = exported_name(mod)
  668. emitter.emit_lines(
  669. f"extern PyObject *CPyInit_{name}(void);",
  670. 'capsule = PyCapsule_New((void *)CPyInit_{}, "{}.init_{}", NULL);'.format(
  671. name, shared_lib_name(self.group_name), name
  672. ),
  673. "if (!capsule) {",
  674. "goto fail;",
  675. "}",
  676. f'res = PyObject_SetAttrString(module, "init_{name}", capsule);',
  677. "Py_DECREF(capsule);",
  678. "if (res < 0) {",
  679. "goto fail;",
  680. "}",
  681. "",
  682. )
  683. for group in sorted(self.context.group_deps):
  684. egroup = exported_name(group)
  685. emitter.emit_lines(
  686. 'tmp = PyImport_ImportModule("{}"); if (!tmp) goto fail; Py_DECREF(tmp);'.format(
  687. shared_lib_name(group)
  688. ),
  689. 'struct export_table_{} *pexports_{} = PyCapsule_Import("{}.exports", 0);'.format(
  690. egroup, egroup, shared_lib_name(group)
  691. ),
  692. f"if (!pexports_{egroup}) {{",
  693. "goto fail;",
  694. "}",
  695. "memcpy(&exports_{group}, pexports_{group}, sizeof(exports_{group}));".format(
  696. group=egroup
  697. ),
  698. "",
  699. )
  700. emitter.emit_lines("return module;", "fail:", "Py_XDECREF(module);", "return NULL;", "}")
  701. def generate_globals_init(self, emitter: Emitter) -> None:
  702. emitter.emit_lines(
  703. "",
  704. "int CPyGlobalsInit(void)",
  705. "{",
  706. "static int is_initialized = 0;",
  707. "if (is_initialized) return 0;",
  708. "",
  709. )
  710. emitter.emit_line("CPy_Init();")
  711. for symbol, fixup in self.simple_inits:
  712. emitter.emit_line(f"{symbol} = {fixup};")
  713. values = "CPyLit_Str, CPyLit_Bytes, CPyLit_Int, CPyLit_Float, CPyLit_Complex, CPyLit_Tuple, CPyLit_FrozenSet"
  714. emitter.emit_lines(
  715. f"if (CPyStatics_Initialize(CPyStatics, {values}) < 0) {{", "return -1;", "}"
  716. )
  717. emitter.emit_lines("is_initialized = 1;", "return 0;", "}")
  718. def generate_module_def(self, emitter: Emitter, module_name: str, module: ModuleIR) -> None:
  719. """Emit the PyModuleDef struct for a module and the module init function."""
  720. # Emit module methods
  721. module_prefix = emitter.names.private_name(module_name)
  722. emitter.emit_line(f"static PyMethodDef {module_prefix}module_methods[] = {{")
  723. for fn in module.functions:
  724. if fn.class_name is not None or fn.name == TOP_LEVEL_NAME:
  725. continue
  726. name = short_id_from_name(fn.name, fn.decl.shortname, fn.line)
  727. if is_fastcall_supported(fn, emitter.capi_version):
  728. flag = "METH_FASTCALL"
  729. else:
  730. flag = "METH_VARARGS"
  731. emitter.emit_line(
  732. (
  733. '{{"{name}", (PyCFunction){prefix}{cname}, {flag} | METH_KEYWORDS, '
  734. "NULL /* docstring */}},"
  735. ).format(name=name, cname=fn.cname(emitter.names), prefix=PREFIX, flag=flag)
  736. )
  737. emitter.emit_line("{NULL, NULL, 0, NULL}")
  738. emitter.emit_line("};")
  739. emitter.emit_line()
  740. # Emit module definition struct
  741. emitter.emit_lines(
  742. f"static struct PyModuleDef {module_prefix}module = {{",
  743. "PyModuleDef_HEAD_INIT,",
  744. f'"{module_name}",',
  745. "NULL, /* docstring */",
  746. "-1, /* size of per-interpreter state of the module,",
  747. " or -1 if the module keeps state in global variables. */",
  748. f"{module_prefix}module_methods",
  749. "};",
  750. )
  751. emitter.emit_line()
  752. # Emit module init function. If we are compiling just one module, this
  753. # will be the C API init function. If we are compiling 2+ modules, we
  754. # generate a shared library for the modules and shims that call into
  755. # the shared library, and in this case we use an internal module
  756. # initialized function that will be called by the shim.
  757. if not self.use_shared_lib:
  758. declaration = f"PyMODINIT_FUNC PyInit_{module_name}(void)"
  759. else:
  760. declaration = f"PyObject *CPyInit_{exported_name(module_name)}(void)"
  761. emitter.emit_lines(declaration, "{")
  762. emitter.emit_line("PyObject* modname = NULL;")
  763. # Store the module reference in a static and return it when necessary.
  764. # This is separate from the *global* reference to the module that will
  765. # be populated when it is imported by a compiled module. We want that
  766. # reference to only be populated when the module has been successfully
  767. # imported, whereas this we want to have to stop a circular import.
  768. module_static = self.module_internal_static_name(module_name, emitter)
  769. emitter.emit_lines(
  770. f"if ({module_static}) {{",
  771. f"Py_INCREF({module_static});",
  772. f"return {module_static};",
  773. "}",
  774. )
  775. emitter.emit_lines(
  776. f"{module_static} = PyModule_Create(&{module_prefix}module);",
  777. f"if (unlikely({module_static} == NULL))",
  778. " goto fail;",
  779. )
  780. emitter.emit_line(
  781. f'modname = PyObject_GetAttrString((PyObject *){module_static}, "__name__");'
  782. )
  783. module_globals = emitter.static_name("globals", module_name)
  784. emitter.emit_lines(
  785. f"{module_globals} = PyModule_GetDict({module_static});",
  786. f"if (unlikely({module_globals} == NULL))",
  787. " goto fail;",
  788. )
  789. # HACK: Manually instantiate generated classes here
  790. type_structs: list[str] = []
  791. for cl in module.classes:
  792. type_struct = emitter.type_struct_name(cl)
  793. type_structs.append(type_struct)
  794. if cl.is_generated:
  795. emitter.emit_lines(
  796. "{t} = (PyTypeObject *)CPyType_FromTemplate("
  797. "(PyObject *){t}_template, NULL, modname);".format(t=type_struct)
  798. )
  799. emitter.emit_lines(f"if (unlikely(!{type_struct}))", " goto fail;")
  800. emitter.emit_lines("if (CPyGlobalsInit() < 0)", " goto fail;")
  801. self.generate_top_level_call(module, emitter)
  802. emitter.emit_lines("Py_DECREF(modname);")
  803. emitter.emit_line(f"return {module_static};")
  804. emitter.emit_lines("fail:", f"Py_CLEAR({module_static});", "Py_CLEAR(modname);")
  805. for name, typ in module.final_names:
  806. static_name = emitter.static_name(name, module_name)
  807. emitter.emit_dec_ref(static_name, typ, is_xdec=True)
  808. undef = emitter.c_undefined_value(typ)
  809. emitter.emit_line(f"{static_name} = {undef};")
  810. # the type objects returned from CPyType_FromTemplate are all new references
  811. # so we have to decref them
  812. for t in type_structs:
  813. emitter.emit_line(f"Py_CLEAR({t});")
  814. emitter.emit_line("return NULL;")
  815. emitter.emit_line("}")
  816. def generate_top_level_call(self, module: ModuleIR, emitter: Emitter) -> None:
  817. """Generate call to function representing module top level."""
  818. # Optimization: we tend to put the top level last, so reverse iterate
  819. for fn in reversed(module.functions):
  820. if fn.name == TOP_LEVEL_NAME:
  821. emitter.emit_lines(
  822. f"char result = {emitter.native_function_name(fn.decl)}();",
  823. "if (result == 2)",
  824. " goto fail;",
  825. )
  826. break
  827. def toposort_declarations(self) -> list[HeaderDeclaration]:
  828. """Topologically sort the declaration dict by dependencies.
  829. Declarations can require other declarations to come prior in C (such as declaring structs).
  830. In order to guarantee that the C output will compile the declarations will thus need to
  831. be properly ordered. This simple DFS guarantees that we have a proper ordering.
  832. This runs in O(V + E).
  833. """
  834. result = []
  835. marked_declarations: dict[str, MarkedDeclaration] = {}
  836. for k, v in self.context.declarations.items():
  837. marked_declarations[k] = MarkedDeclaration(v, False)
  838. def _toposort_visit(name: str) -> None:
  839. decl = marked_declarations[name]
  840. if decl.mark:
  841. return
  842. for child in decl.declaration.dependencies:
  843. _toposort_visit(child)
  844. result.append(decl.declaration)
  845. decl.mark = True
  846. for name, marked_declaration in marked_declarations.items():
  847. _toposort_visit(name)
  848. return result
  849. def declare_global(
  850. self, type_spaced: str, name: str, *, initializer: str | None = None
  851. ) -> None:
  852. if "[" not in type_spaced:
  853. base = f"{type_spaced}{name}"
  854. else:
  855. a, b = type_spaced.split("[", 1)
  856. base = f"{a}{name}[{b}"
  857. if not initializer:
  858. defn = None
  859. else:
  860. defn = [f"{base} = {initializer};"]
  861. if name not in self.context.declarations:
  862. self.context.declarations[name] = HeaderDeclaration(f"{base};", defn=defn)
  863. def declare_internal_globals(self, module_name: str, emitter: Emitter) -> None:
  864. static_name = emitter.static_name("globals", module_name)
  865. self.declare_global("PyObject *", static_name)
  866. def module_internal_static_name(self, module_name: str, emitter: Emitter) -> str:
  867. return emitter.static_name(module_name + "_internal", None, prefix=MODULE_PREFIX)
  868. def declare_module(self, module_name: str, emitter: Emitter) -> None:
  869. # We declare two globals for each compiled module:
  870. # one used internally in the implementation of module init to cache results
  871. # and prevent infinite recursion in import cycles, and one used
  872. # by other modules to refer to it.
  873. if module_name in self.modules:
  874. internal_static_name = self.module_internal_static_name(module_name, emitter)
  875. self.declare_global("CPyModule *", internal_static_name, initializer="NULL")
  876. static_name = emitter.static_name(module_name, None, prefix=MODULE_PREFIX)
  877. self.declare_global("CPyModule *", static_name)
  878. self.simple_inits.append((static_name, "Py_None"))
  879. def declare_imports(self, imps: Iterable[str], emitter: Emitter) -> None:
  880. for imp in imps:
  881. self.declare_module(imp, emitter)
  882. def declare_finals(
  883. self, module: str, final_names: Iterable[tuple[str, RType]], emitter: Emitter
  884. ) -> None:
  885. for name, typ in final_names:
  886. static_name = emitter.static_name(name, module)
  887. emitter.context.declarations[static_name] = HeaderDeclaration(
  888. f"{emitter.ctype_spaced(typ)}{static_name};",
  889. [self.final_definition(module, name, typ, emitter)],
  890. needs_export=True,
  891. )
  892. def final_definition(self, module: str, name: str, typ: RType, emitter: Emitter) -> str:
  893. static_name = emitter.static_name(name, module)
  894. # Here we rely on the fact that undefined value and error value are always the same
  895. undefined = emitter.c_initializer_undefined_value(typ)
  896. return f"{emitter.ctype_spaced(typ)}{static_name} = {undefined};"
  897. def declare_static_pyobject(self, identifier: str, emitter: Emitter) -> None:
  898. symbol = emitter.static_name(identifier, None)
  899. self.declare_global("PyObject *", symbol)
  900. def sort_classes(classes: list[tuple[str, ClassIR]]) -> list[tuple[str, ClassIR]]:
  901. mod_name = {ir: name for name, ir in classes}
  902. irs = [ir for _, ir in classes]
  903. deps: dict[ClassIR, set[ClassIR]] = {}
  904. for ir in irs:
  905. if ir not in deps:
  906. deps[ir] = set()
  907. if ir.base:
  908. deps[ir].add(ir.base)
  909. deps[ir].update(ir.traits)
  910. sorted_irs = toposort(deps)
  911. return [(mod_name[ir], ir) for ir in sorted_irs]
  912. T = TypeVar("T")
  913. def toposort(deps: dict[T, set[T]]) -> list[T]:
  914. """Topologically sort a dict from item to dependencies.
  915. This runs in O(V + E).
  916. """
  917. result = []
  918. visited: set[T] = set()
  919. def visit(item: T) -> None:
  920. if item in visited:
  921. return
  922. for child in deps[item]:
  923. visit(child)
  924. result.append(item)
  925. visited.add(item)
  926. for item in deps:
  927. visit(item)
  928. return result
  929. def is_fastcall_supported(fn: FuncIR, capi_version: tuple[int, int]) -> bool:
  930. if fn.class_name is not None:
  931. if fn.name == "__call__":
  932. # We can use vectorcalls (PEP 590) when supported
  933. return use_vectorcall(capi_version)
  934. # TODO: Support fastcall for __init__.
  935. return use_fastcall(capi_version) and fn.name != "__init__"
  936. return use_fastcall(capi_version)
  937. def collect_literals(fn: FuncIR, literals: Literals) -> None:
  938. """Store all Python literal object refs in fn.
  939. Collecting literals must happen only after we have the final IR.
  940. This way we won't include literals that have been optimized away.
  941. """
  942. for block in fn.blocks:
  943. for op in block.ops:
  944. if isinstance(op, LoadLiteral):
  945. literals.record_literal(op.value)
  946. def c_string_array_initializer(components: list[bytes]) -> str:
  947. result = []
  948. result.append("{\n")
  949. for s in components:
  950. result.append(" " + c_string_initializer(s) + ",\n")
  951. result.append("}")
  952. return "".join(result)