#!/usr/bin/env python3 """gen_stubs.py -- regenerate libhalo/halo_stubs.cpp and libhalo's HALO_UNITS. python3 libhalo/gen_stubs.py # rewrite both files in place python3 libhalo/gen_stubs.py --check # exit 1 if either is not what this would write python3 libhalo/gen_stubs.py --check --verbose WHAT IT DERIVES, AND FROM WHERE (nothing is guessed; every input is read from the tree) * The entries that must exist: every `halo_*` function declaration in libhalo/halo_plugin.h (the shims the row table, the layout hooks and the fusion claims take the addresses of) and in libhalo/halo.h (the plain C ABI the engine dlsyms), PLUS every line already in halo_stubs.cpp whose symbol neither header declares -- a tuning hook a unit calls without a public declaration stays alive. So the stub set never shrinks by accident. * What is already implemented: a *definition* of that symbol -- a declaration whose parameter list is followed by `{` -- in a source the build compiles, i.e. the HALO_UNITS device units and the HALO_DECLARATION host sources listed in libhalo/CMakeLists.txt. A comment or a call mentioning the name does not count, and a file the build does not compile does not count (its symbol must stay stubbed, or the shared object would come out with an undefined entry). * HALO_UNITS: every libhalo/halo_*.hip present, minus the pure bodies -- a file another file `#include`s as text and that defines no `extern "C"` entry point of its own (the `#define`+`#include` wrapper pattern: the wrapper is the unit, the body is not). A file that is both included and defines its own entries (libr4d's r4d_attn_paged_gqa8.hip is the precedent) stays a unit. Per-unit extra flags already in CMakeLists.txt are preserved. WHY `__attribute__((weak))` A stub is a weak definition, so a real definition of the same symbol in any unit -- including one written via a token-pasting macro, which this script cannot see -- wins at link time without touching this file. Consequence: an entry's stub line does NOT have to be deleted when its unit lands. Two runs over the same tree produce byte-identical files, so regenerating after a merge is safe, and a branch that adds a unit and forgets the stub merges cleanly. """ import os import re import sys HERE = os.path.dirname(os.path.abspath(__file__)) STUBS = os.path.join(HERE, "halo_stubs.cpp") CMAKE = os.path.join(HERE, "CMakeLists.txt") DECL_HEADERS = ("halo_plugin.h", "halo.h") # A declaration of one of the entries, at the start of a line: what halo_plugin.h and halo.h use. DECL_RE = re.compile( r'^[ \t]*(?:extern[ \t]+"C"[ \t]+)?' r'(?:unsigned[ \t]+|signed[ \t]+)?' r'(int64_t|uint64_t|int32_t|uint32_t|int|void|long|float|double|char|size_t|unsigned)' r'[ \t\*]+(halo_[A-Za-z0-9_]+)[ \t]*\(', re.M) # A kernel unit's file name is built from an op name, so only .hip files are units. UNIT_RE = re.compile(r'^halo_[A-Za-z0-9_]+\.hip$') BODY_INCLUDE_RE = re.compile(r'#include\s+"(halo_[A-Za-z0-9_]+\.hip)"') EXTERN_C_RE = re.compile(r'extern\s+"C"') # One generated stub line, as this script writes it (so a re-run reproduces it exactly). STUB_LINE_RE = re.compile(r'^(?P(?:extern "C" )?)(?P__attribute__\(\(weak\)\) )?' r'(?P.*?\b(?Phalo_[A-Za-z0-9_]+)[ \t]*\(.*)$') # Return types whose a stub body can only say "not ported". BODY = { "int": "{ return RAD_E_UNSUPPORTED; }", "int32_t": "{ return RAD_E_UNSUPPORTED; }", "uint32_t": "{ return -1; }", "long": "{ return -1; }", "int64_t": "{ return -1; }", "uint64_t": "{ return -1; }", "size_t": "{ return 0; }", "unsigned": "{ return 0; }", "char": "{ return 0; }", "float": "{ return 0.0f; }", "double": "{ return 0.0; }", "void": "{}", } # Type words that are never a parameter name (a trailing one must not be dropped). KEYWORDS = {"int", "long", "short", "char", "void", "float", "double", "unsigned", "signed", "const", "struct", "union", "enum", "bool"} HEADER = """/* halo_stubs.cpp -- GENERATED by libhalo/gen_stubs.py; do not edit by hand. * * One weak body per hook libhalo/halo_plugin.h or libhalo/halo.h declares whose definition is not * in a source libhalo/CMakeLists.txt compiles yet. Every body is __attribute__((weak)), so a real * definition in any unit overrides it at link time and this file never has to be edited while a * port lands: run gen_stubs.py when the set of units changes, not per unit. An unimplemented * launch or init returns RAD_E_UNSUPPORTED, so a row that resolves to it fails by name at first * use instead of at dlopen. The line count is the parity scoreboard: done means zero. */ #include "halo_plugin.h" #include "halo.h" /* the C entries' types (HaloArgs, hipStream_t); this file is scaffolding, not one of the ROCm-free declaration sources */ """ # The name list the generated file exports (see HOOKS). Not a stub: a fixed trailer whose body is # the set of names just written, so a caller can tell a weak no-op hook from a real one. HOOKS_SYMBOL = "halo_stub_hooks" HOOKS = """ /* The hooks this file still stubs, space separated, empty when the port is complete. * * A weak no-op body is RESOLVED, so a dlsym of a test hook answers even though the plugin does not * implement it -- and a pinned-form test built on that answer asserts about a pin that pins * nothing (a vacuous pass, or one spurious FAILure per form when the row itself is a stub). This * list is the only place that knows which hooks are still stubs, and it is generated from the same * scan as the bodies above, so a unit that lands a real hook drops its name here on the next run. * halo_selftest reads it through libhalo/halo_selftest.cpp's `hook()`. */ extern \"C\" const char* %s(void) { return \"%s\"; } """ CMAKE_MARK = """# HALO_UNITS is generated: libhalo/gen_stubs.py writes the list below from the halo_*.hip files # present (each "unit|extra flags", mirroring libr4d's R4D_UNITS), so add a unit by adding its # .hip, not by editing the list. Every unit compiles -ffp-contract=off (rad_hipify): the # quantised all-reduce requires it, for the reason libr4d/CMakeLists.txt gives.""" def read(path): with open(path, "r", encoding="utf-8") as f: return f.read() def code_only(text): """`text` with its comments removed: a commented-out definition defines nothing.""" text = re.sub(r'/\*.*?\*/', '', text, flags=re.S) return re.sub(r'//[^\n]*', '', text) def declarations(): """name -> (return type, header it was declared in).""" decl = {} for h in DECL_HEADERS: path = os.path.join(HERE, h) if not os.path.exists(path): sys.exit("gen_stubs.py: %s is missing" % path) for m in DECL_RE.finditer(read(path)): decl.setdefault(m.group(2), (m.group(1), h)) return decl def cmake_lists(): """(per-unit extra flags from the current HALO_UNITS, the HALO_DECLARATION host sources).""" text = read(CMAKE) flags = {} m = re.search(r'set\(\s*HALO_UNITS\b(.*?)\n[ \t]*\)', text, re.S) if m: for unit, extra in re.findall(r'"(halo_[A-Za-z0-9_]+)\|([^"]*)"', m.group(1)): flags[unit] = extra m = re.search(r'set\(\s*HALO_DECLARATION\b(.*?)\)', text, re.S) if not m: sys.exit("gen_stubs.py: CMakeLists.txt has no HALO_DECLARATION list") host = re.findall(r'([A-Za-z0-9_]+\.cpp)', m.group(1)) if not host: sys.exit("gen_stubs.py: HALO_DECLARATION names no host source") return flags, host def bodies(names): """(all units, the included files that are units too, the pure bodies).""" hips = sorted(f for f in os.listdir(HERE) if UNIT_RE.match(f)) included = set() for f in os.listdir(HERE): if not f.endswith((".hip", ".cpp", ".h")): continue for inc in BODY_INCLUDE_RE.findall(read(os.path.join(HERE, f))): if inc != f: included.add(inc) pure = set() for inc in sorted(included): path = os.path.join(HERE, inc) # A file that defines an entry point of its own is a unit even when a wrapper includes it # (libr4d's r4d_attn_paged_gqa8.hip is the precedent: its ratios are built by the wrappers # that include it, and its own gqa-8 entries come from compiling it). if defined_in(path, names, set()): continue if not EXTERN_C_RE.search(code_only(read(path))): pure.add(inc) return hips, included - pure, pure def match_close(text, start): """Index just past the ')' that closes the '(' at `start`, or -1.""" depth = 0 i = start while i < len(text): c = text[i] if c == "(": depth += 1 elif c == ")": depth -= 1 if depth == 0: return i + 1 elif c in "\";'": j = i + 1 while j < len(text) and text[j] != c: j += 2 if text[j] == "\\" else 1 i = j i += 1 return -1 def defined_in(path, names, under): """The subset of `names` this file defines: `type name(...) {` -- a definition, not a call.""" text = code_only(read(path)) found = set() for name in names: if name in under: continue pat = re.compile(r'(?]*[ \t\*&]*$', head): continue close = match_close(text, m.end() - 1) if close < 0: continue tail = text[close:] if re.match(r'[ \t\n]*(?:const[ \t\n]*)?[{]', tail): found.add(name) break return found def implemented(units, host): """The entry names a compiled source defines.""" names = set(declarations()) srcs = [os.path.join(HERE, u + ".hip") for u in units] srcs += [os.path.join(HERE, h) for h in host if h != "halo_stubs.cpp"] done = set() for s in srcs: if os.path.exists(s): done |= defined_in(s, names, done) return done def existing_stubs(): """name -> the line already in halo_stubs.cpp, with any weak attribute removed.""" if not os.path.exists(STUBS): return {} out = {} for line in read(STUBS).splitlines(): if not line.strip() or line.lstrip().startswith(("/*", "*", "#")): continue m = STUB_LINE_RE.match(line) if not m or not line.rstrip().endswith("}"): continue if m.group("name") == HOOKS_SYMBOL: # this script's own trailer, not a stub continue stripped = m.group("lead") + m.group("rest") out[m.group("name")] = stripped return out def signature(decl_type, hole, cxx_c): """A definition's declarator from the header's, with parameter names and defaults dropped.""" close = match_close(hole, 0) if close < 0 or close != len(hole) or not hole.startswith("("): return None params = hole[1:-1] out = [] for p in params.split(","): p = re.sub(r'=.*$', '', p).strip() if not p: continue toks = p.split() # Drop the parameter's name when there is a type left without it, so the stub does not # warn about an unused parameter (-Wunused-parameter) and matches the file's style. if len(toks) > 1 and re.match(r'^[A-Za-z_][A-Za-z0-9_]*$', toks[-1]) \ and toks[-1] not in KEYWORDS: p = " ".join(toks[:-1]) out.append(p) return ("extern \"C\" " if cxx_c else "") + decl_type + " " + "%s(" + ", ".join(out) + ")" def weak(lead, rest): """The line with the weak attribute where the tree's style puts it: after `extern "C" `.""" return lead + "__attribute__((weak)) " + rest def stub_line(name, decl, existing, decl_text): if name in existing: line = existing[name] lead, rest = ("extern \"C\" ", line[len("extern \"C\" "):]) \ if line.startswith("extern \"C\" ") else ("", line) return weak(lead, rest) decl_type, header = decl[name] sig = signature(decl_type, decl_text[name], header == "halo.h") if sig is None: sys.exit("gen_stubs.py: cannot read the declaration of %s in %s" % (name, header)) lead, rest = (("extern \"C\" ", sig[len("extern \"C\" "):]) \ if sig.startswith("extern \"C\" ") else ("", sig)) return weak(lead, rest) % name + " " + BODY[decl_type] def decl_param_text(): """name -> the header's parameter list text, from '(' to ')'.""" out = {} for h in DECL_HEADERS: text = read(os.path.join(HERE, h)) for m in DECL_RE.finditer(text): after = text[m.end() - 1:] close = match_close(after, 0) if close < 0: sys.exit("gen_stubs.py: unbalanced declaration of %s in %s" % (m.group(2), h)) out.setdefault(m.group(2), after[:close]) return out def generate(verbose=False): decl = declarations() flags, host = cmake_lists() hips, units_keep, bodies_pure = bodies(set(decl)) units = sorted(f[:-4] for f in hips if f not in bodies_pure) done = implemented(units, host) existing = existing_stubs() # The stub set: every declared entry with no definition, plus every line already here whose # symbol no header declares (kept so a hook a unit calls cannot vanish). undeclared = {n: ("void", "halo_plugin.h") for n in existing if n not in decl} want = {n: decl[n] for n in decl if n not in done} want.update(undeclared) params = decl_param_text() lines = [stub_line(n, want, existing, params) for n in sorted(want)] stub_text = HEADER + "\n" + "\n".join(lines) + "\n" + HOOKS % (HOOKS_SYMBOL, " ".join(sorted(want))) cmake_text = read(CMAKE) block = "\n".join(' "%s|%s"' % (u, flags.get(u, "")) for u in units) new_units = "set(HALO_UNITS\n%s\n)" % block old = re.search(r'set\(\s*HALO_UNITS\b.*?\n[ \t]*\)', cmake_text, re.S) if not old: sys.exit("gen_stubs.py: CMakeLists.txt has no HALO_UNITS block") # Replace the comment block that documents HALO_UNITS along with the list, so a re-run # reproduces the file byte for byte; everything outside that block is left alone. head = cmake_text[:old.start()] comment = re.search(r'(?:^[ \t]*#[^\n]*\n)+\Z', head, re.M) if comment: head = head[:comment.start()] cmake_out = head + CMAKE_MARK + "\n" + new_units + cmake_text[old.end():] old_stub = read(STUBS) if os.path.exists(STUBS) else "" changed = [] if old_stub != stub_text: changed.append(STUBS) if cmake_text != cmake_out: changed.append(CMAKE) if verbose: print("gen_stubs.py: %d unit(s), %d stub(s) (%d kept verbatim, %d synthesised), " "%d declaration(s) implemented, %d undeclared line(s) kept" % (len(units), len(want), len(want) - len([n for n in want if n not in existing]), len([n for n in want if n not in existing]), len(done), len(undeclared))) for b in sorted(bodies_pure): print("gen_stubs.py: %s is included as a body and defines no entry point: not a unit" % b) if "--check" in sys.argv: for c in changed: print("gen_stubs.py: %s is out of date -- run python3 libhalo/gen_stubs.py" % c) return 1 if changed else 0 for path, text in ((STUBS, stub_text), (CMAKE, cmake_out)): if read(path) != text: with open(path, "w", encoding="utf-8") as f: f.write(text) if changed: for c in changed: print("gen_stubs.py: rewrote %s" % c) return 0 if __name__ == "__main__": sys.exit(generate("--verbose" in sys.argv))