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

Usage: python3 muapitoirbuildercomminstsimpl.py
"""

import muapiparser
import sys, os
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 27

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

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

_type_map = {
        "void"            : "",
        "MuID"            : "int<32>",
        "MuName"          : "iref<int<8>>",
Kunshan Wang's avatar
Kunshan Wang committed
35
        "MuCString"       : "iref<int<8>>",
Kunshan Wang's avatar
Kunshan Wang committed
36 37 38 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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
        "MuBool"          : "int<32>",
        "MuWPID"          : "int<32>",
        "MuArraySize"     : "int<64>",
        "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",
        }

def to_mu_ty(cty):
    if cty.endswith("*"):
        return "iref<{}>".format(to_mu_ty(cty[:-1]))
    elif cty.startswith("Mu") and cty.endswith("Node"):
        return "irnoderef"
    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"]
            if s["name"] == "MuCtx"][0]

    index_new_bundle = 0
    while muctx_methods[index_new_bundle]["name"] != "new_bundle":
        index_new_bundle += 1

    next_id = start_id_comminst

    comminsts = []

    for i in range(index_new_bundle, len(muctx_methods)):
        meth = muctx_methods[i]
        name = meth["name"]
        cparams = meth["params"]
        cretty = meth["ret_ty"]
        pragmas = meth["pragmas"]
        arrays = {}
        sizes = set()
94
        optionals = set()
Kunshan Wang's avatar
Kunshan Wang committed
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114

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

        for param in cparams[1:]: # skip MuCtx*
            pn = param["name"]
            pt = param["type"]
            mpt = to_mu_ty(pt)

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

            mypragmas = [pw for pw in (p.split(":") for p in pragmas) if pw[0] == pn]
            for pragma in mypragmas:
                if pragma[1] == "array":
                    sz = pragma[2]
                    arrays[pn] = sz
                    sizes.add(sz)
115 116
                elif pragma[1] == "optional":
                    optionals.add(pn)
Kunshan Wang's avatar
Kunshan Wang committed
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131

        muretty = to_mu_ty(cretty)

        comminst = CommInstDesc(
            funcname   = name,
            paramnames = paramnames,
            cparamtys  = cparamtys,
            cretty     = cretty,
            pragmas    = pragmas,
            muid       = next_id,
            muname     = "@uvm.irbuilder." + name,
            muparamtys = muparamtys,
            muretty    = muretty,
            arrays     = arrays,
            sizes      = sizes,
132
            optionals  = optionals,
Kunshan Wang's avatar
Kunshan Wang committed
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
            )
        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",
        "irnoderef": "IRNODEREF",
        }

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):
167 168 169
    lines_retvals = []
    lines_nretvals = []

Kunshan Wang's avatar
Kunshan Wang committed
170 171

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

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

179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
_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):
    if cty == "MuBundleNode":
196
        meth = 'asIRNode.getOrElse(throw new UvmNullGenRefException("CommInst arg %{} must not be null")).asInstanceOf[TB]'.format(cname)
197 198
    elif mty == "irnoderef":
        if is_optional:
199
            meth = 'asIRNodeWeak'
200
        else:
201
            meth = 'asIRNodeWeak.getOrElse(throw new UvmNullGenRefException("CommInst arg %{} must not be null"))'.format(cname)
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
    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":
220
        meth = 'asIRNodeWeak'
221 222 223 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 276 277 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 312 313 314 315 316 317 318 319 320
        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",
        }

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"
            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
321 322 323 324
        elif cty in ["MuName", "MuCString"]:
            str_name = "_str_" + cname
            lines.append('        val {} = loadCString({})'.format(str_name, cname))
            ir_builder_args.append(str_name)
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
        else:
            ir_builder_args.append(cname)

    ir_builder_meth_name = toCamelCase(comminst.funcname)
    lines.append('        val _rv = irBuilder.{}({})'.format(
        ir_builder_meth_name, ", ".join(ir_builder_args)))

    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
344
        #"set_name",
345 346 347
        "new_const_int_ex",
        ]

Kunshan Wang's avatar
Kunshan Wang committed
348 349 350 351
def gen_comminsts_impls(comminsts):
    lines = []

    for comminst in comminsts:
352 353
        if comminst.funcname not in _blacklist:
            lines.append(gen_comminst_impl(comminst))
Kunshan Wang's avatar
Kunshan Wang committed
354 355 356 357 358 359 360 361 362 363 364 365

    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)
366
    comminsts_retvals, comminsts_nretvals = gen_comminsts_retvals(comminsts)
Kunshan Wang's avatar
Kunshan Wang committed
367 368 369 370
    comminsts_impls   = gen_comminsts_impls(comminsts)

    #print(comminsts_defs)

371 372 373 374 375 376 377
    injectable_files.inject_many({
        "comminsts.scala": {
            "IRBUILDER_COMMINSTS": comminsts_defs,
            },
        "internals.scala": {
            "IRBUILDER_RETVALS": comminsts_retvals,
            },
378 379 380
        "InstructionResultInferer.scala": {
            "IRBUILDER_RETVAL_NUMS": comminsts_nretvals,
            },
381 382 383
        "ir-ci-exec": {
            "IRBUILDER_IMPL": comminsts_impls,
            },
Kunshan Wang's avatar
Kunshan Wang committed
384 385 386 387 388 389 390 391 392 393
        })

    #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()