muapitoirbuildercomminstsimpl.py 12.4 KB
Newer Older
Kunshan Wang's avatar
Kunshan Wang committed
1 2 3 4 5 6 7
"""
Read muapi.h and write common instruction definitions in reStructuredText.

Usage: python3 muapitoirbuildercomminstsimpl.py
"""

import muapiparser
8
import sys, os, re
Kunshan Wang's avatar
Kunshan Wang committed
9 10
from collections import namedtuple

11
from refimpl2injectablefiles import injectable_files, muapi_h_path
Kunshan Wang's avatar
Kunshan Wang committed
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

start_id_comminst = 0x300   # this is in the spec
#start_id_constant = 0x400

CommInstDesc = namedtuple("CommInstDesc", """
        funcname
        paramnames
        cparamtys
        cretty
        muid
        muname
        muparamtys
        muretty
        arrays
        sizes
27
        optionals
Kunshan Wang's avatar
Kunshan Wang committed
28 29 30 31 32 33
        """.split())

_type_map = {
        "void"            : "",
        "MuID"            : "int<32>",
        "MuName"          : "iref<int<8>>",
Kunshan Wang's avatar
Kunshan Wang committed
34
        "MuCString"       : "iref<int<8>>",
Kunshan Wang's avatar
Kunshan Wang committed
35 36 37
        "MuBool"          : "int<32>",
        "MuWPID"          : "int<32>",
        "MuArraySize"     : "int<64>",
38
        "MuBinOpStatus"   : "int<32>",
Kunshan Wang's avatar
Kunshan Wang committed
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
        "MuBinOptr"       : "int<32>",
        "MuCmpOptr"       : "int<32>",
        "MuConvOptr"      : "int<32>",
        "MuDestKind"      : "int<32>",
        "MuMemOrd"        : "int<32>",
        "MuAtomicRMWOptr" : "int<32>",
        "MuCallConv"      : "int<32>",
        "MuCommInst"      : "int<32>",
        "MuFlag"          : "int<32>",
        "int"             : "int<32>",
        "long"            : "int<64>",
        "int8_t"          : "int<8>",
        "uint8_t"         : "int<8>",
        "int16_t"         : "int<16>",
        "uint16_t"        : "int<16>",
        "int32_t"         : "int<32>",
        "uint32_t"        : "int<32>",
        "int64_t"         : "int<64>",
        "uint64_t"        : "int<64>",
        "intptr_t"        : "int<64>",
        "uintptr_t"       : "int<64>",
        "float"           : "float",
        "double"          : "double",
        }

64 65 66 67 68
r_node_ty = re.compile(r'^Mu\w*(Node|Clause)$')

def type_is_node(ty):
    return r_node_ty.match(ty) is not None

Kunshan Wang's avatar
Kunshan Wang committed
69
def to_mu_ty(cty):
70 71 72
    if cty == "MuIRBuilder*":
        return "irbuilderref"
    elif cty.endswith("*"):
Kunshan Wang's avatar
Kunshan Wang committed
73
        return "iref<{}>".format(to_mu_ty(cty[:-1]))
74 75
    elif type_is_node(cty):
        return "int<32>"
Kunshan Wang's avatar
Kunshan Wang committed
76 77 78 79 80 81 82
    elif cty in _type_map:
        return _type_map[cty]
    else:
        raise Exception("I don't know how to translate: {}".format(cty))

def get_comminsts(ast):
    muctx_methods = [s["methods"] for s in ast["structs"]
83
            if s["name"] == "MuIRBuilder"][0]
Kunshan Wang's avatar
Kunshan Wang committed
84

85
    comminsts = []
Kunshan Wang's avatar
Kunshan Wang committed
86 87 88

    next_id = start_id_comminst

89
    for i in range(len(muctx_methods)):
Kunshan Wang's avatar
Kunshan Wang committed
90 91 92 93 94 95
        meth = muctx_methods[i]
        name = meth["name"]
        cparams = meth["params"]
        cretty = meth["ret_ty"]
        arrays = {}
        sizes = set()
96
        optionals = set()
Kunshan Wang's avatar
Kunshan Wang committed
97 98 99 100 101

        paramnames = []
        cparamtys = []
        muparamtys = []

102
        for param in cparams:
Kunshan Wang's avatar
Kunshan Wang committed
103 104 105 106 107 108 109 110
            pn = param["name"]
            pt = param["type"]
            mpt = to_mu_ty(pt)

            paramnames.append(pn)
            cparamtys.append(pt)
            muparamtys.append(mpt)

111 112 113 114 115 116 117 118 119 120
            array_sz = param.get("array_sz_param", None)
            is_optional = param.get("is_optional", False)
            is_out = param.get("is_out", False)

            if array_sz != None:
                arrays[pn] = array_sz
                sizes.add(array_sz)

            if is_optional:
                optionals.add(pn)
Kunshan Wang's avatar
Kunshan Wang committed
121 122 123 124 125 126 127 128 129 130 131 132 133 134

        muretty = to_mu_ty(cretty)

        comminst = CommInstDesc(
            funcname   = name,
            paramnames = paramnames,
            cparamtys  = cparamtys,
            cretty     = cretty,
            muid       = next_id,
            muname     = "@uvm.irbuilder." + name,
            muparamtys = muparamtys,
            muretty    = muretty,
            arrays     = arrays,
            sizes      = sizes,
135
            optionals  = optionals,
Kunshan Wang's avatar
Kunshan Wang committed
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
            )
        comminsts.append(comminst)

        next_id += 1

    return comminsts

def gen_comminsts_defs(comminsts):
    lines = []
    for comminst in comminsts:
        lines.append('  commInst(0x{:x}, "{}")'.format(
            comminst.muid, comminst.muname))

    return "\n".join(lines)

_mu_ty_to_internal = {
        "": "", # no return values
        #"int<1>": "I1",
        #"int<8>": "I8",
        #"int<16>": "I16",
        "int<32>": "I32",
        #"int<64>": "I64",
        #"float": "FLOAT",
        #"double": "DOUBLE",
160
        "irbuilderref": "IRBUILDERREF",
Kunshan Wang's avatar
Kunshan Wang committed
161 162 163 164 165 166 167 168 169
        }

def mu_ty_to_internal(mty):
    if mty in _mu_ty_to_internal:
        return _mu_ty_to_internal[mty]

    raise Exception("I don't know how to convert to internal: {}".format(mty))

def gen_comminsts_retvals(comminsts):
170 171 172
    lines_retvals = []
    lines_nretvals = []

Kunshan Wang's avatar
Kunshan Wang committed
173 174

    for comminst in comminsts:
175
        lines_retvals.append('      case "{}" => Seq({})'.format(
Kunshan Wang's avatar
Kunshan Wang committed
176
            comminst.muname, mu_ty_to_internal(comminst.muretty)))
177 178
        lines_nretvals.append('      case "{}" => {}'.format(
            comminst.muname, 0 if comminst.muretty == "" else 1))
Kunshan Wang's avatar
Kunshan Wang committed
179

180
    return ("\n".join(lines_retvals), "\n".join(lines_nretvals))
Kunshan Wang's avatar
Kunshan Wang committed
181

182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
_get_arg_meths = {
        "int<64>": "asInt64.toLong",
        "int<32>": "asInt32.toInt",
        "float": "asFloat",
        "double": "asDouble",
        }

def get_arg_meth(mty, cty, cname):
    if mty in _get_arg_meths:
        return _get_arg_meths[mty]
    elif mty.startswith("iref<"):
        return "asIRef"

    raise Exception("I don't know how to get arg: {}, {}, {}".format(mty, cty, cname))

def get_arg(ind, mty, cty, cname, is_optional):
198 199 200
    if mty == "irbuilderref":
        meth = 'asIRBuilder.getOrElse(throw new UvmNullGenRefException("CommInst arg %{} must not be null"))'.format(cname)
    elif cty == "MuID" or type_is_node(cty):
201
        if is_optional:
202
            meth = 'asInt32.toInt.asOptionalID'
203
        else:
204
            meth = 'asInt32.toInt'
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
    else:
        meth = get_arg_meth(mty, cty, cname)
    return "        val {} = argList({}).{}".format(cname, ind, meth)

_set_arg_meths = {
        "int<32>": "asInt32",
        }

def set_arg_meth(mty, cty):
    if mty in _set_arg_meths:
        return _set_arg_meths[mty]
    elif mty.startswith("iref<"):
        return "asIRef"

    raise Exception("I don't know how to set return value: {}, {}".format(mty, cty))

def set_ret(ind, mty, cty, value):
    if mty == "irnoderef":
223
        meth = 'asIRNodeWeak'
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 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
        return "        results({}).{} = Some({})".format(ind, meth, value)
    else:
        meth = set_arg_meth(mty, cty)
        return "        results({}).{} = {}".format(ind, meth, value)

_special_cases = {
        "id":             "ID",
        "sint8":          "SInt8",
        "uint8":          "UInt8",
        "sint16":         "SInt16",
        "uint16":         "UInt16",
        "sint32":         "SInt32",
        "uint32":         "UInt32",
        "sint64":         "SInt64",
        "uint64":         "UInt64",
        "uint64s":        "UInt64s",
        "fp":             "FP",
        "uptr":           "UPtr",
        "ufuncptr":       "UFuncPtr",
        "iref":           "IRef",
        "weakref":        "WeakRef",
        "funcref":        "FuncRef",
        "tagref64":       "TagRef64",
        "threadref":      "ThreadRef",
        "stackref":       "StackRef",
        "framecursorref": "FrameCursorRef",
        "irnoderef":      "IRNodeRef",
        "funcsig":        "FuncSig",
        "bb":             "BB",
        "binop":          "BinOp",
        "tailcall":       "TailCall",
        "extractvalue":   "ExtractValue",
        "insertvalue":    "InsertValue",
        "extractelement": "ExtractElement",
        "insertelement":  "InsertElement",
        "shufflevector":  "ShuffleVector",
        "newhybrid":      "NewHybrid",
        "allocahybrid":   "AllocaHybrid",
        "getiref":        "GetIRef",
        "getfieldiref":   "GetFieldIRef",
        "getelemiref":    "GetElemIRef",
        "shiftiref":      "ShiftIRef",
        "getvarpartiref": "GetVarPartIRef",
        "cmpxchg":        "CmpXchg",
        "atomicrmw":      "AtomicRMW",
        "watchpoint":     "WatchPoint",
        "wpbranch":       "WPBranch",
        "ccall":          "CCall",
        "newthread":      "NewThread",
        "newstack":       "NewStack",
        "swapstack":      "SwapStack",
        "comminst":       "CommInst",
276 277
        "ir":             "IR",
        "irbuilderref":   "IRBuilderRef",
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
        }

def toCamelCase(name):
    ins = name.split("_")
    outs = [ins[0]]
    for inn in ins[1:]:
        if inn in _special_cases:
            outs.append(_special_cases[inn])
        else:
            outs.append(inn[0].upper()+inn[1:])

    return "".join(outs)

def gen_comminst_impl(comminst):
    lines = []

    lines.append('      case "{}" => {{'.format(comminst.muname))

    for ind, (cty, mty, cname) in enumerate(zip(
            comminst.cparamtys, comminst.muparamtys, comminst.paramnames)):
        lines.append(get_arg(ind, mty, cty, cname,
            is_optional=(cname in comminst.optionals)))

    ir_builder_args = []

    for cty, mty, cname in zip(
            comminst.cparamtys, comminst.muparamtys, comminst.paramnames):
        if cname in comminst.arrays:
            sz = comminst.arrays[cname]
            loaded_array_name = "_ary_" + cname
            if mty == "iref<irnoderef>":
                loader_func = "loadIRNodeArray"
            elif mty == "iref<int<64>>":
                loader_func = "loadInt64Array"
312 313
            elif mty == "iref<int<32>>":
                loader_func = "loadInt32Array"
314 315 316 317 318 319 320 321 322 323 324 325 326 327
            elif cty == "MuFlag*":
                loader_func = "loadFlagArray"
            else:
                raise Exception("I don't know how to load array: {}, {}, {}".format(
                    cty, mty, cname))
            lines.append('        val {} = {}({}, {})'.format(
                loaded_array_name, loader_func, cname, sz))
            ir_builder_args.append(loaded_array_name)
        elif cname in comminst.sizes:
            pass    # skip array sizes
        elif cty == "MuBool":
            bool_name = "_bool_" + cname
            lines.append('        val {} = {} != 0'.format(bool_name, cname))
            ir_builder_args.append(bool_name)
Kunshan Wang's avatar
Kunshan Wang committed
328
        elif cty in ["MuName", "MuCString"]:
329 330 331 332 333 334 335 336

            if cname in comminst.optionals:
                str_name = "_maybestr_" + cname
                lines.append('        val {} = loadMaybeCString({})'.format(str_name, cname))
            else:
                str_name = "_str_" + cname
                lines.append('        val {} = loadCString({})'.format(str_name, cname))

Kunshan Wang's avatar
Kunshan Wang committed
337
            ir_builder_args.append(str_name)
338 339 340
        else:
            ir_builder_args.append(cname)

341 342
    ir_builder_itself, actual_args = ir_builder_args[0], ir_builder_args[1:]

343
    ir_builder_meth_name = toCamelCase(comminst.funcname)
344 345
    lines.append('        val _rv = {}.{}({})'.format(
        ir_builder_itself, ir_builder_meth_name, ", ".join(actual_args)))
346 347 348 349 350 351 352 353 354 355 356 357 358

    if comminst.cretty != "void":
        lines.append(set_ret(0, comminst.muretty, comminst.cretty, "_rv"))
    
    lines.append("        continueNormally()")
    lines.append("      }")

    return "\n".join(lines)

# These functions are too speical. Implemented manually in Scala.
_blacklist = [
        "load_bundle_from_node",
        "abort_bundle_node",
Kunshan Wang's avatar
Kunshan Wang committed
359
        #"set_name",
360 361 362
        "new_const_int_ex",
        ]

Kunshan Wang's avatar
Kunshan Wang committed
363 364 365 366
def gen_comminsts_impls(comminsts):
    lines = []

    for comminst in comminsts:
367 368
        if comminst.funcname not in _blacklist:
            lines.append(gen_comminst_impl(comminst))
Kunshan Wang's avatar
Kunshan Wang committed
369 370 371 372 373 374 375 376 377 378 379 380

    return "\n".join(lines)

def main():
    with open(muapi_h_path) as f:
        txt = f.read()

    ast = muapiparser.parse_muapi(txt)

    comminsts = get_comminsts(ast)

    comminsts_defs    = gen_comminsts_defs(comminsts)
381
    comminsts_retvals, comminsts_nretvals = gen_comminsts_retvals(comminsts)
Kunshan Wang's avatar
Kunshan Wang committed
382 383 384 385
    comminsts_impls   = gen_comminsts_impls(comminsts)

    #print(comminsts_defs)

386 387 388 389
    injectable_files.inject_many({
        "comminsts.scala": {
            "IRBUILDER_COMMINSTS": comminsts_defs,
            },
390
        "TypeInferer.scala": {
391 392
            "IRBUILDER_RETVALS": comminsts_retvals,
            },
393 394 395
        "InstructionResultInferer.scala": {
            "IRBUILDER_RETVAL_NUMS": comminsts_nretvals,
            },
396 397 398
        "ir-ci-exec": {
            "IRBUILDER_IMPL": comminsts_impls,
            },
Kunshan Wang's avatar
Kunshan Wang committed
399 400 401 402 403 404 405 406 407 408
        })

    #print()
    #print_constants(ast)  # Do not print. This merely pollutes the pre-loaded
                           # space with more constants, and not profitable.
                           # We keep muapi.h as the canonical definition.
                           # Clients should define their own constants.

if __name__=='__main__':
    main()