helper.h 10.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 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
#include <string>
#include <vector>

#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/InitLLVM.h"
#include "llvm/Support/Signals.h"
#include "llvm/TableGen/Main.h"
#include "llvm/TableGen/Record.h"
#include "llvm/TableGen/TableGenBackend.h"
#include "mlir/TableGen/Attribute.h"
#include "mlir/TableGen/Format.h"
#include "mlir/TableGen/Operator.h"

using llvm::formatv;
using llvm::StringRef;
using llvm::Record;

#define ASSERT(stmt, msg) \
    if (!(stmt)) { \
        std::cerr << "\033[1;31m" \
            << "tablegen autogen abort due to: " << msg \
            << "\033[0m" << std::endl; \
        exit(1); \
    }

namespace mlir {
namespace tblgen {
template<typename ConcreteType>
struct MgbInterface : public ConcreteType {
    MgbInterface() = delete;
    MgbInterface(const MgbInterface&) = delete;
    MgbInterface(MgbInterface&&) = delete;
    ~MgbInterface() = delete;
};

struct MgbAttrWrapperBase : public MgbInterface<Attribute> {
private:
    struct RecordVisitor : public MgbInterface<Constraint> {
    public:
        static bool classof(const Constraint*) {
            return true;
        }

        const llvm::Record* getDef() const {
            return def;
        }
    };
public:
    static bool classof(const Attribute* attr) {
        return attr->isSubClassOf("MgbAttrWrapperBase");
    }

    const llvm::Record* getBaseRecord() const {
        auto baseAttr = getBaseAttr();
        return llvm::cast<RecordVisitor>(baseAttr).getDef();
    }
    llvm::StringRef getUnderlyingType() const {
        return def->getValueAsString("underlyingType");
    }
};

struct MgbEnumAttrMixin : public MgbAttrWrapperBase {
    static bool classof(const Attribute* attr) {
        return attr->getBaseAttr().isSubClassOf("MgbEnumAttrMixin");
    }

    llvm::StringRef getParentNamespace() const {
69
        return getBaseRecord()->getValueAsString("parentNamespace");
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
    }
    llvm::StringRef getEnumName() const {
        return getBaseRecord()->getValueAsString("enumName");
    }
    std::vector<StringRef> getEnumMembers() const {
        return getBaseRecord()->getValueAsListOfStrings("enumMembers");
    }
};

struct MgbHashableAttrMixin : public MgbAttrWrapperBase {
    static bool classof(const Attribute* attr) {
        return attr->getBaseAttr().isSubClassOf("MgbHashableAttrMixin");
    }

    llvm::StringRef getHashFunctionTemplate() const {
        return getBaseRecord()->getValueAsString("hashFunction");
    }
    llvm::StringRef getCmpFunctionTemplate() const {
        return getBaseRecord()->getValueAsString("cmpFunction");
    }
90 91 92
    llvm::StringRef getReprFunctionTemplate() const {
        return getBaseRecord()->getValueAsString("reprFunction");
    }
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 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 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
};

struct MgbAliasAttrMixin : public MgbAttrWrapperBase {
    static bool classof(const Attribute* attr) {
        return attr->getBaseAttr().isSubClassOf("MgbAliasAttrMixin");
    }

    Attribute getAliasBase() const {
        return Attribute(getBaseRecord()->getValueAsDef("aliasBase"));
    }
};

class MgbPackedParam {
public:
    MgbPackedParam(Record* def_): def(def_) {
        auto&& dag = def->getValueAsDag("fields");
        for (size_t i = 0; i < dag->getNumArgs(); ++ i) {
            fields.push_back({
                dag->getArgNameStr(i),
                Attribute(llvm::cast<llvm::DefInit>(dag->getArg(i)))
            });
        }
    }

    llvm::StringRef getFullName() const {
        return def->getValueAsString("fullName");
    }
    std::vector<NamedAttribute> getFields() const {
        return fields;
    }
    llvm::StringRef getAccessor() const {
        return def->getValueAsString("paramAccessor");
    }
private:
    std::vector<NamedAttribute> fields;
    Record* def;
};

struct MgbOpBase : public MgbInterface<Operator> {
    static bool isPackedParam(Record* def) {
        return def->isSubClassOf("MgbPackedParamBase");
    }

public:
    static bool classof(const Operator* op) {
        return op->getDef().isSubClassOf("MgbOp");
    }

    std::vector<NamedAttribute> getMgbAttributes() const {
        std::vector<NamedAttribute> ret;
        for (auto&& i: getAttributes()) {
            if (isa<MgbAttrWrapperBase>(i.attr)) {
                ret.push_back(i);
            }
        }
        return ret;
    }
    std::vector<NamedAttribute> getExtraArguments() const {
        std::vector<NamedAttribute> ret;
        auto&& dag = getDef().getValueAsDag("extraArguments");
        for (size_t i = 0; i < dag->getNumArgs(); ++ i) {
            ret.push_back({
                dag->getArgNameStr(i),
                Attribute(llvm::cast<llvm::DefInit>(dag->getArg(i)))
            });
        }
        return ret;
    }
    llvm::Optional<StringRef> getExtraOpdefDecl() const {
        return getDef().getValueAsOptionalString("extraOpdefDecl");
    }
    std::vector<MgbPackedParam> getPackedParams() const {
        std::vector<MgbPackedParam> ret;
        for (auto&& i : getDef().getValueAsListOfDefs("dnnParams")) {
            if (isPackedParam(i)) {
                ret.emplace_back(i);
            }
        }
        return ret;
    }
};

struct MgbHashableOpMixin : public MgbOpBase {
private:
    std::string getDefaultHashFunction() const {
        std::string body = "    size_t val = mgb::hash($_self.dyn_typeinfo());\n";
        if (!getMgbAttributes().empty()) {
            auto getHashFunc = [&](auto&& iter) {
                auto&& attr = llvm::cast<MgbHashableAttrMixin>(iter.attr);
                return attr.getHashFunctionTemplate();
            };
            mlir::tblgen::FmtContext ctx;
            for (auto&& it: getMgbAttributes()) {
                body += formatv(
                    "    val = mgb::hash_pair_combine(val, {0});\n",
                    mlir::tblgen::tgfmt(getHashFunc(it), &ctx, "$_self." + it.name)
                );
            }
        }
        body += "    return val;\n";
        return body;
    }
    std::string getDefaultCmpFunction() const {
        std::string body;
        if (!getMgbAttributes().empty()) {
            mlir::tblgen::FmtContext ctx;
            for (auto&& it : getMgbAttributes()) {
                auto&& attr = llvm::cast<MgbHashableAttrMixin>(it.attr);
                body += formatv(
                    "    if ({0}) return false;\n",
                    mlir::tblgen::tgfmt(attr.getCmpFunctionTemplate(),
                        &ctx, "$0." + it.name, "$1." + it.name)
                );
            }
        }
        body += "    return true;\n";
        return body;
    }
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
    std::string getDefaultPropsFunction() const {
        std::string body = "    std::vector<std::pair<const char*, std::string>> props_;\n";
        if (!getMgbAttributes().empty()) {
            mlir::tblgen::FmtContext ctx;
            for (auto&& it : getMgbAttributes()) {
                if (auto* enumAttr = llvm::dyn_cast<MgbEnumAttrMixin>(&it.attr)) {
                    body += formatv("    switch ({0}){{\n", "$_self." + it.name);
                    for (auto&& enumMember: enumAttr->getEnumMembers()) {
                        body += formatv(
                            "    case {0}::{1}::{2}:\n",
                            getCppClassName(), enumAttr->getEnumName(), enumMember
                        );
                        body += formatv(
                            "        props_.emplace_back(\"{0}\", \"{1}\");\n",
                            it.name, enumMember
                        );
                        body += "        break;\n";
                    }
                    body += "    default: break;\n";
                    body += "    }\n";
                } else {
                    auto&& attr = llvm::cast<MgbHashableAttrMixin>(it.attr);
                    body += formatv(
                        "    props_.emplace_back(\"{0}\", {1});\n", it.name,
                        mlir::tblgen::tgfmt(attr.getReprFunctionTemplate(),
                            &ctx, "$_self." + it.name)
                    );
                }
            }
        }
        body += "    return props_;\n";
        return body;
    }
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
    std::string getModeName() const {
        std::string body = formatv(
            "    auto&& op_ = def_.cast_final_safe<{0}>();\n"
            "    static_cast<void>(op_);\n",
            getCppClassName()
        );
        for (auto&& it : getMgbAttributes()) {
            if (it.name == "mode") {
                auto* enumAttr = llvm::dyn_cast<MgbEnumAttrMixin>(&it.attr);
                body += "    switch (op_.mode){\n";
                for (auto&& enumMember: enumAttr->getEnumMembers()) {
                    body += formatv(
                        "        case {0}::{1}::{2}:\n",
                        getCppClassName(), enumAttr->getEnumName(), enumMember
                    );
                    body += formatv("            return \"{0}\";\n", enumMember);
                }
                body += formatv(
                    "        default: return \"{0}::Unknown\";\n", getCppClassName());
                body += "    }\n";
            }
        }
        return body;
    }
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
public:
    static bool classof(const Operator* op) {
        return op->getDef().isSubClassOf("MgbHashableOpMixin");
    }

    std::string getHashFunctionTemplate() const {
        if (auto f = getDef().getValueAsOptionalString("hashFunction")) {
            return f.getValue().str();
        }
        return getDefaultHashFunction();
    }
    std::string getCmpFunctionTemplate() const {
        if (auto f = getDef().getValueAsOptionalString("cmpFunction")) {
            return f.getValue().str();
        }
        return getDefaultCmpFunction();
    }
285 286 287 288 289 290
    std::string getPropsFunctionTemplate() const {
        if (auto f = getDef().getValueAsOptionalString("propsFunction")) {
            return f.getValue().str();
        }
        return getDefaultPropsFunction();
    }
291 292 293 294 295 296
    std::string getNameFunctionTemplate() const {
        if (getDef().getValueAsBit("usingModeName")) {
            return getModeName();
        }
        return formatv("    return \"{0}\";\n", getCppClassName());
    }
297 298 299
};

} // namespace tblgen
300
} // namespace mlir