1389 lines · cpp
1//===- IR.cpp - C Interface for Core MLIR APIs ----------------------------===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8 9#include "mlir-c/IR.h"10#include "mlir-c/Support.h"11 12#include "mlir/AsmParser/AsmParser.h"13#include "mlir/Bytecode/BytecodeWriter.h"14#include "mlir/CAPI/IR.h"15#include "mlir/CAPI/Support.h"16#include "mlir/CAPI/Utils.h"17#include "mlir/IR/Attributes.h"18#include "mlir/IR/BuiltinAttributes.h"19#include "mlir/IR/BuiltinOps.h"20#include "mlir/IR/Diagnostics.h"21#include "mlir/IR/Dialect.h"22#include "mlir/IR/Location.h"23#include "mlir/IR/Operation.h"24#include "mlir/IR/OperationSupport.h"25#include "mlir/IR/OwningOpRef.h"26#include "mlir/IR/Types.h"27#include "mlir/IR/Value.h"28#include "mlir/IR/Verifier.h"29#include "mlir/IR/Visitors.h"30#include "mlir/Interfaces/InferTypeOpInterface.h"31#include "mlir/Parser/Parser.h"32#include "llvm/ADT/SmallPtrSet.h"33#include "llvm/Support/ThreadPool.h"34 35#include <cstddef>36#include <memory>37#include <optional>38 39using namespace mlir;40 41//===----------------------------------------------------------------------===//42// Context API.43//===----------------------------------------------------------------------===//44 45MlirContext mlirContextCreate() {46 auto *context = new MLIRContext;47 return wrap(context);48}49 50static inline MLIRContext::Threading toThreadingEnum(bool threadingEnabled) {51 return threadingEnabled ? MLIRContext::Threading::ENABLED52 : MLIRContext::Threading::DISABLED;53}54 55MlirContext mlirContextCreateWithThreading(bool threadingEnabled) {56 auto *context = new MLIRContext(toThreadingEnum(threadingEnabled));57 return wrap(context);58}59 60MlirContext mlirContextCreateWithRegistry(MlirDialectRegistry registry,61 bool threadingEnabled) {62 auto *context =63 new MLIRContext(*unwrap(registry), toThreadingEnum(threadingEnabled));64 return wrap(context);65}66 67bool mlirContextEqual(MlirContext ctx1, MlirContext ctx2) {68 return unwrap(ctx1) == unwrap(ctx2);69}70 71void mlirContextDestroy(MlirContext context) { delete unwrap(context); }72 73void mlirContextSetAllowUnregisteredDialects(MlirContext context, bool allow) {74 unwrap(context)->allowUnregisteredDialects(allow);75}76 77bool mlirContextGetAllowUnregisteredDialects(MlirContext context) {78 return unwrap(context)->allowsUnregisteredDialects();79}80intptr_t mlirContextGetNumRegisteredDialects(MlirContext context) {81 return static_cast<intptr_t>(unwrap(context)->getAvailableDialects().size());82}83 84void mlirContextAppendDialectRegistry(MlirContext ctx,85 MlirDialectRegistry registry) {86 unwrap(ctx)->appendDialectRegistry(*unwrap(registry));87}88 89// TODO: expose a cheaper way than constructing + sorting a vector only to take90// its size.91intptr_t mlirContextGetNumLoadedDialects(MlirContext context) {92 return static_cast<intptr_t>(unwrap(context)->getLoadedDialects().size());93}94 95MlirDialect mlirContextGetOrLoadDialect(MlirContext context,96 MlirStringRef name) {97 return wrap(unwrap(context)->getOrLoadDialect(unwrap(name)));98}99 100bool mlirContextIsRegisteredOperation(MlirContext context, MlirStringRef name) {101 return unwrap(context)->isOperationRegistered(unwrap(name));102}103 104void mlirContextEnableMultithreading(MlirContext context, bool enable) {105 return unwrap(context)->enableMultithreading(enable);106}107 108void mlirContextLoadAllAvailableDialects(MlirContext context) {109 unwrap(context)->loadAllAvailableDialects();110}111 112void mlirContextSetThreadPool(MlirContext context,113 MlirLlvmThreadPool threadPool) {114 unwrap(context)->setThreadPool(*unwrap(threadPool));115}116 117unsigned mlirContextGetNumThreads(MlirContext context) {118 return unwrap(context)->getNumThreads();119}120 121MlirLlvmThreadPool mlirContextGetThreadPool(MlirContext context) {122 return wrap(&unwrap(context)->getThreadPool());123}124 125//===----------------------------------------------------------------------===//126// Dialect API.127//===----------------------------------------------------------------------===//128 129MlirContext mlirDialectGetContext(MlirDialect dialect) {130 return wrap(unwrap(dialect)->getContext());131}132 133bool mlirDialectEqual(MlirDialect dialect1, MlirDialect dialect2) {134 return unwrap(dialect1) == unwrap(dialect2);135}136 137MlirStringRef mlirDialectGetNamespace(MlirDialect dialect) {138 return wrap(unwrap(dialect)->getNamespace());139}140 141//===----------------------------------------------------------------------===//142// DialectRegistry API.143//===----------------------------------------------------------------------===//144 145MlirDialectRegistry mlirDialectRegistryCreate() {146 return wrap(new DialectRegistry());147}148 149void mlirDialectRegistryDestroy(MlirDialectRegistry registry) {150 delete unwrap(registry);151}152 153//===----------------------------------------------------------------------===//154// AsmState API.155//===----------------------------------------------------------------------===//156 157MlirAsmState mlirAsmStateCreateForOperation(MlirOperation op,158 MlirOpPrintingFlags flags) {159 return wrap(new AsmState(unwrap(op), *unwrap(flags)));160}161 162static Operation *findParent(Operation *op, bool shouldUseLocalScope) {163 do {164 // If we are printing local scope, stop at the first operation that is165 // isolated from above.166 if (shouldUseLocalScope && op->hasTrait<OpTrait::IsIsolatedFromAbove>())167 break;168 169 // Otherwise, traverse up to the next parent.170 Operation *parentOp = op->getParentOp();171 if (!parentOp)172 break;173 op = parentOp;174 } while (true);175 return op;176}177 178MlirAsmState mlirAsmStateCreateForValue(MlirValue value,179 MlirOpPrintingFlags flags) {180 Operation *op;181 mlir::Value val = unwrap(value);182 if (auto result = llvm::dyn_cast<OpResult>(val)) {183 op = result.getOwner();184 } else {185 op = llvm::cast<BlockArgument>(val).getOwner()->getParentOp();186 if (!op) {187 emitError(val.getLoc()) << "<<UNKNOWN SSA VALUE>>";188 return {nullptr};189 }190 }191 op = findParent(op, unwrap(flags)->shouldUseLocalScope());192 return wrap(new AsmState(op, *unwrap(flags)));193}194 195/// Destroys printing flags created with mlirAsmStateCreate.196void mlirAsmStateDestroy(MlirAsmState state) { delete unwrap(state); }197 198//===----------------------------------------------------------------------===//199// Printing flags API.200//===----------------------------------------------------------------------===//201 202MlirOpPrintingFlags mlirOpPrintingFlagsCreate() {203 return wrap(new OpPrintingFlags());204}205 206void mlirOpPrintingFlagsDestroy(MlirOpPrintingFlags flags) {207 delete unwrap(flags);208}209 210void mlirOpPrintingFlagsElideLargeElementsAttrs(MlirOpPrintingFlags flags,211 intptr_t largeElementLimit) {212 unwrap(flags)->elideLargeElementsAttrs(largeElementLimit);213}214 215void mlirOpPrintingFlagsElideLargeResourceString(MlirOpPrintingFlags flags,216 intptr_t largeResourceLimit) {217 unwrap(flags)->elideLargeResourceString(largeResourceLimit);218}219 220void mlirOpPrintingFlagsEnableDebugInfo(MlirOpPrintingFlags flags, bool enable,221 bool prettyForm) {222 unwrap(flags)->enableDebugInfo(enable, /*prettyForm=*/prettyForm);223}224 225void mlirOpPrintingFlagsPrintGenericOpForm(MlirOpPrintingFlags flags) {226 unwrap(flags)->printGenericOpForm();227}228 229void mlirOpPrintingFlagsPrintNameLocAsPrefix(MlirOpPrintingFlags flags) {230 unwrap(flags)->printNameLocAsPrefix();231}232 233void mlirOpPrintingFlagsUseLocalScope(MlirOpPrintingFlags flags) {234 unwrap(flags)->useLocalScope();235}236 237void mlirOpPrintingFlagsAssumeVerified(MlirOpPrintingFlags flags) {238 unwrap(flags)->assumeVerified();239}240 241void mlirOpPrintingFlagsSkipRegions(MlirOpPrintingFlags flags) {242 unwrap(flags)->skipRegions();243}244//===----------------------------------------------------------------------===//245// Bytecode printing flags API.246//===----------------------------------------------------------------------===//247 248MlirBytecodeWriterConfig mlirBytecodeWriterConfigCreate() {249 return wrap(new BytecodeWriterConfig());250}251 252void mlirBytecodeWriterConfigDestroy(MlirBytecodeWriterConfig config) {253 delete unwrap(config);254}255 256void mlirBytecodeWriterConfigDesiredEmitVersion(MlirBytecodeWriterConfig flags,257 int64_t version) {258 unwrap(flags)->setDesiredBytecodeVersion(version);259}260 261//===----------------------------------------------------------------------===//262// Location API.263//===----------------------------------------------------------------------===//264 265MlirAttribute mlirLocationGetAttribute(MlirLocation location) {266 return wrap(LocationAttr(unwrap(location)));267}268 269MlirLocation mlirLocationFromAttribute(MlirAttribute attribute) {270 return wrap(Location(llvm::dyn_cast<LocationAttr>(unwrap(attribute))));271}272 273MlirLocation mlirLocationFileLineColGet(MlirContext context,274 MlirStringRef filename, unsigned line,275 unsigned col) {276 return wrap(Location(277 FileLineColLoc::get(unwrap(context), unwrap(filename), line, col)));278}279 280MlirLocation281mlirLocationFileLineColRangeGet(MlirContext context, MlirStringRef filename,282 unsigned startLine, unsigned startCol,283 unsigned endLine, unsigned endCol) {284 return wrap(285 Location(FileLineColRange::get(unwrap(context), unwrap(filename),286 startLine, startCol, endLine, endCol)));287}288 289MlirIdentifier mlirLocationFileLineColRangeGetFilename(MlirLocation location) {290 return wrap(llvm::dyn_cast<FileLineColRange>(unwrap(location)).getFilename());291}292 293int mlirLocationFileLineColRangeGetStartLine(MlirLocation location) {294 if (auto loc = llvm::dyn_cast<FileLineColRange>(unwrap(location)))295 return loc.getStartLine();296 return -1;297}298 299int mlirLocationFileLineColRangeGetStartColumn(MlirLocation location) {300 if (auto loc = llvm::dyn_cast<FileLineColRange>(unwrap(location)))301 return loc.getStartColumn();302 return -1;303}304 305int mlirLocationFileLineColRangeGetEndLine(MlirLocation location) {306 if (auto loc = llvm::dyn_cast<FileLineColRange>(unwrap(location)))307 return loc.getEndLine();308 return -1;309}310 311int mlirLocationFileLineColRangeGetEndColumn(MlirLocation location) {312 if (auto loc = llvm::dyn_cast<FileLineColRange>(unwrap(location)))313 return loc.getEndColumn();314 return -1;315}316 317MlirTypeID mlirLocationFileLineColRangeGetTypeID() {318 return wrap(FileLineColRange::getTypeID());319}320 321bool mlirLocationIsAFileLineColRange(MlirLocation location) {322 return isa<FileLineColRange>(unwrap(location));323}324 325MlirLocation mlirLocationCallSiteGet(MlirLocation callee, MlirLocation caller) {326 return wrap(Location(CallSiteLoc::get(unwrap(callee), unwrap(caller))));327}328 329MlirLocation mlirLocationCallSiteGetCallee(MlirLocation location) {330 return wrap(331 Location(llvm::dyn_cast<CallSiteLoc>(unwrap(location)).getCallee()));332}333 334MlirLocation mlirLocationCallSiteGetCaller(MlirLocation location) {335 return wrap(336 Location(llvm::dyn_cast<CallSiteLoc>(unwrap(location)).getCaller()));337}338 339MlirTypeID mlirLocationCallSiteGetTypeID() {340 return wrap(CallSiteLoc::getTypeID());341}342 343bool mlirLocationIsACallSite(MlirLocation location) {344 return isa<CallSiteLoc>(unwrap(location));345}346 347MlirLocation mlirLocationFusedGet(MlirContext ctx, intptr_t nLocations,348 MlirLocation const *locations,349 MlirAttribute metadata) {350 SmallVector<Location, 4> locs;351 ArrayRef<Location> unwrappedLocs = unwrapList(nLocations, locations, locs);352 return wrap(FusedLoc::get(unwrappedLocs, unwrap(metadata), unwrap(ctx)));353}354 355unsigned mlirLocationFusedGetNumLocations(MlirLocation location) {356 if (auto locationsArrRef = llvm::dyn_cast<FusedLoc>(unwrap(location)))357 return locationsArrRef.getLocations().size();358 return 0;359}360 361void mlirLocationFusedGetLocations(MlirLocation location,362 MlirLocation *locationsCPtr) {363 if (auto locationsArrRef = llvm::dyn_cast<FusedLoc>(unwrap(location))) {364 for (auto [i, location] : llvm::enumerate(locationsArrRef.getLocations()))365 locationsCPtr[i] = wrap(location);366 }367}368 369MlirAttribute mlirLocationFusedGetMetadata(MlirLocation location) {370 return wrap(llvm::dyn_cast<FusedLoc>(unwrap(location)).getMetadata());371}372 373MlirTypeID mlirLocationFusedGetTypeID() { return wrap(FusedLoc::getTypeID()); }374 375bool mlirLocationIsAFused(MlirLocation location) {376 return isa<FusedLoc>(unwrap(location));377}378 379MlirLocation mlirLocationNameGet(MlirContext context, MlirStringRef name,380 MlirLocation childLoc) {381 if (mlirLocationIsNull(childLoc))382 return wrap(383 Location(NameLoc::get(StringAttr::get(unwrap(context), unwrap(name)))));384 return wrap(Location(NameLoc::get(385 StringAttr::get(unwrap(context), unwrap(name)), unwrap(childLoc))));386}387 388MlirIdentifier mlirLocationNameGetName(MlirLocation location) {389 return wrap((llvm::dyn_cast<NameLoc>(unwrap(location)).getName()));390}391 392MlirLocation mlirLocationNameGetChildLoc(MlirLocation location) {393 return wrap(394 Location(llvm::dyn_cast<NameLoc>(unwrap(location)).getChildLoc()));395}396 397MlirTypeID mlirLocationNameGetTypeID() { return wrap(NameLoc::getTypeID()); }398 399bool mlirLocationIsAName(MlirLocation location) {400 return isa<NameLoc>(unwrap(location));401}402 403MlirLocation mlirLocationUnknownGet(MlirContext context) {404 return wrap(Location(UnknownLoc::get(unwrap(context))));405}406 407bool mlirLocationEqual(MlirLocation l1, MlirLocation l2) {408 return unwrap(l1) == unwrap(l2);409}410 411MlirContext mlirLocationGetContext(MlirLocation location) {412 return wrap(unwrap(location).getContext());413}414 415void mlirLocationPrint(MlirLocation location, MlirStringCallback callback,416 void *userData) {417 detail::CallbackOstream stream(callback, userData);418 unwrap(location).print(stream);419}420 421//===----------------------------------------------------------------------===//422// Module API.423//===----------------------------------------------------------------------===//424 425MlirModule mlirModuleCreateEmpty(MlirLocation location) {426 return wrap(ModuleOp::create(unwrap(location)));427}428 429MlirModule mlirModuleCreateParse(MlirContext context, MlirStringRef module) {430 OwningOpRef<ModuleOp> owning =431 parseSourceString<ModuleOp>(unwrap(module), unwrap(context));432 if (!owning)433 return MlirModule{nullptr};434 return MlirModule{owning.release().getOperation()};435}436 437MlirModule mlirModuleCreateParseFromFile(MlirContext context,438 MlirStringRef fileName) {439 OwningOpRef<ModuleOp> owning =440 parseSourceFile<ModuleOp>(unwrap(fileName), unwrap(context));441 if (!owning)442 return MlirModule{nullptr};443 return MlirModule{owning.release().getOperation()};444}445 446MlirContext mlirModuleGetContext(MlirModule module) {447 return wrap(unwrap(module).getContext());448}449 450MlirBlock mlirModuleGetBody(MlirModule module) {451 return wrap(unwrap(module).getBody());452}453 454void mlirModuleDestroy(MlirModule module) {455 // Transfer ownership to an OwningOpRef<ModuleOp> so that its destructor is456 // called.457 OwningOpRef<ModuleOp>(unwrap(module));458}459 460MlirOperation mlirModuleGetOperation(MlirModule module) {461 return wrap(unwrap(module).getOperation());462}463 464MlirModule mlirModuleFromOperation(MlirOperation op) {465 return wrap(dyn_cast<ModuleOp>(unwrap(op)));466}467 468bool mlirModuleEqual(MlirModule lhs, MlirModule rhs) {469 return unwrap(lhs) == unwrap(rhs);470}471 472size_t mlirModuleHashValue(MlirModule mod) {473 return OperationEquivalence::computeHash(unwrap(mod).getOperation());474}475 476//===----------------------------------------------------------------------===//477// Operation state API.478//===----------------------------------------------------------------------===//479 480MlirOperationState mlirOperationStateGet(MlirStringRef name, MlirLocation loc) {481 MlirOperationState state;482 state.name = name;483 state.location = loc;484 state.nResults = 0;485 state.results = nullptr;486 state.nOperands = 0;487 state.operands = nullptr;488 state.nRegions = 0;489 state.regions = nullptr;490 state.nSuccessors = 0;491 state.successors = nullptr;492 state.nAttributes = 0;493 state.attributes = nullptr;494 state.enableResultTypeInference = false;495 return state;496}497 498#define APPEND_ELEMS(type, sizeName, elemName) \499 state->elemName = \500 (type *)realloc(state->elemName, (state->sizeName + n) * sizeof(type)); \501 memcpy(state->elemName + state->sizeName, elemName, n * sizeof(type)); \502 state->sizeName += n;503 504void mlirOperationStateAddResults(MlirOperationState *state, intptr_t n,505 MlirType const *results) {506 APPEND_ELEMS(MlirType, nResults, results);507}508 509void mlirOperationStateAddOperands(MlirOperationState *state, intptr_t n,510 MlirValue const *operands) {511 APPEND_ELEMS(MlirValue, nOperands, operands);512}513void mlirOperationStateAddOwnedRegions(MlirOperationState *state, intptr_t n,514 MlirRegion const *regions) {515 APPEND_ELEMS(MlirRegion, nRegions, regions);516}517void mlirOperationStateAddSuccessors(MlirOperationState *state, intptr_t n,518 MlirBlock const *successors) {519 APPEND_ELEMS(MlirBlock, nSuccessors, successors);520}521void mlirOperationStateAddAttributes(MlirOperationState *state, intptr_t n,522 MlirNamedAttribute const *attributes) {523 APPEND_ELEMS(MlirNamedAttribute, nAttributes, attributes);524}525 526void mlirOperationStateEnableResultTypeInference(MlirOperationState *state) {527 state->enableResultTypeInference = true;528}529 530//===----------------------------------------------------------------------===//531// Operation API.532//===----------------------------------------------------------------------===//533 534static LogicalResult inferOperationTypes(OperationState &state) {535 MLIRContext *context = state.getContext();536 std::optional<RegisteredOperationName> info = state.name.getRegisteredInfo();537 if (!info) {538 emitError(state.location)539 << "type inference was requested for the operation " << state.name540 << ", but the operation was not registered; ensure that the dialect "541 "containing the operation is linked into MLIR and registered with "542 "the context";543 return failure();544 }545 546 auto *inferInterface = info->getInterface<InferTypeOpInterface>();547 if (!inferInterface) {548 emitError(state.location)549 << "type inference was requested for the operation " << state.name550 << ", but the operation does not support type inference; result "551 "types must be specified explicitly";552 return failure();553 }554 555 DictionaryAttr attributes = state.attributes.getDictionary(context);556 OpaqueProperties properties = state.getRawProperties();557 558 if (!properties && info->getOpPropertyByteSize() > 0 && !attributes.empty()) {559 auto prop = std::make_unique<char[]>(info->getOpPropertyByteSize());560 properties = OpaqueProperties(prop.get());561 if (properties) {562 auto emitError = [&]() {563 return mlir::emitError(state.location)564 << " failed properties conversion while building "565 << state.name.getStringRef() << " with `" << attributes << "`: ";566 };567 if (failed(info->setOpPropertiesFromAttribute(state.name, properties,568 attributes, emitError)))569 return failure();570 }571 if (succeeded(inferInterface->inferReturnTypes(572 context, state.location, state.operands, attributes, properties,573 state.regions, state.types))) {574 return success();575 }576 // Diagnostic emitted by interface.577 return failure();578 }579 580 if (succeeded(inferInterface->inferReturnTypes(581 context, state.location, state.operands, attributes, properties,582 state.regions, state.types)))583 return success();584 585 // Diagnostic emitted by interface.586 return failure();587}588 589MlirOperation mlirOperationCreate(MlirOperationState *state) {590 assert(state);591 OperationState cppState(unwrap(state->location), unwrap(state->name));592 SmallVector<Type, 4> resultStorage;593 SmallVector<Value, 8> operandStorage;594 SmallVector<Block *, 2> successorStorage;595 cppState.addTypes(unwrapList(state->nResults, state->results, resultStorage));596 cppState.addOperands(597 unwrapList(state->nOperands, state->operands, operandStorage));598 cppState.addSuccessors(599 unwrapList(state->nSuccessors, state->successors, successorStorage));600 601 cppState.attributes.reserve(state->nAttributes);602 for (intptr_t i = 0; i < state->nAttributes; ++i)603 cppState.addAttribute(unwrap(state->attributes[i].name),604 unwrap(state->attributes[i].attribute));605 606 for (intptr_t i = 0; i < state->nRegions; ++i)607 cppState.addRegion(std::unique_ptr<Region>(unwrap(state->regions[i])));608 609 free(state->results);610 free(state->operands);611 free(state->successors);612 free(state->regions);613 free(state->attributes);614 615 // Infer result types.616 if (state->enableResultTypeInference) {617 assert(cppState.types.empty() &&618 "result type inference enabled and result types provided");619 if (failed(inferOperationTypes(cppState)))620 return {nullptr};621 }622 623 return wrap(Operation::create(cppState));624}625 626MlirOperation mlirOperationCreateParse(MlirContext context,627 MlirStringRef sourceStr,628 MlirStringRef sourceName) {629 630 return wrap(631 parseSourceString(unwrap(sourceStr), unwrap(context), unwrap(sourceName))632 .release());633}634 635MlirOperation mlirOperationClone(MlirOperation op) {636 return wrap(unwrap(op)->clone());637}638 639void mlirOperationDestroy(MlirOperation op) { unwrap(op)->erase(); }640 641void mlirOperationRemoveFromParent(MlirOperation op) { unwrap(op)->remove(); }642 643bool mlirOperationEqual(MlirOperation op, MlirOperation other) {644 return unwrap(op) == unwrap(other);645}646 647size_t mlirOperationHashValue(MlirOperation op) {648 return OperationEquivalence::computeHash(unwrap(op));649}650 651MlirContext mlirOperationGetContext(MlirOperation op) {652 return wrap(unwrap(op)->getContext());653}654 655MlirLocation mlirOperationGetLocation(MlirOperation op) {656 return wrap(unwrap(op)->getLoc());657}658 659void mlirOperationSetLocation(MlirOperation op, MlirLocation loc) {660 unwrap(op)->setLoc(unwrap(loc));661}662 663MlirTypeID mlirOperationGetTypeID(MlirOperation op) {664 if (auto info = unwrap(op)->getRegisteredInfo())665 return wrap(info->getTypeID());666 return {nullptr};667}668 669MlirIdentifier mlirOperationGetName(MlirOperation op) {670 return wrap(unwrap(op)->getName().getIdentifier());671}672 673MlirBlock mlirOperationGetBlock(MlirOperation op) {674 return wrap(unwrap(op)->getBlock());675}676 677MlirOperation mlirOperationGetParentOperation(MlirOperation op) {678 return wrap(unwrap(op)->getParentOp());679}680 681intptr_t mlirOperationGetNumRegions(MlirOperation op) {682 return static_cast<intptr_t>(unwrap(op)->getNumRegions());683}684 685MlirRegion mlirOperationGetRegion(MlirOperation op, intptr_t pos) {686 return wrap(&unwrap(op)->getRegion(static_cast<unsigned>(pos)));687}688 689MlirRegion mlirOperationGetFirstRegion(MlirOperation op) {690 Operation *cppOp = unwrap(op);691 if (cppOp->getNumRegions() == 0)692 return wrap(static_cast<Region *>(nullptr));693 return wrap(&cppOp->getRegion(0));694}695 696MlirRegion mlirRegionGetNextInOperation(MlirRegion region) {697 Region *cppRegion = unwrap(region);698 Operation *parent = cppRegion->getParentOp();699 intptr_t next = cppRegion->getRegionNumber() + 1;700 if (parent->getNumRegions() > next)701 return wrap(&parent->getRegion(next));702 return wrap(static_cast<Region *>(nullptr));703}704 705MlirOperation mlirOperationGetNextInBlock(MlirOperation op) {706 return wrap(unwrap(op)->getNextNode());707}708 709intptr_t mlirOperationGetNumOperands(MlirOperation op) {710 return static_cast<intptr_t>(unwrap(op)->getNumOperands());711}712 713MlirValue mlirOperationGetOperand(MlirOperation op, intptr_t pos) {714 return wrap(unwrap(op)->getOperand(static_cast<unsigned>(pos)));715}716 717void mlirOperationSetOperand(MlirOperation op, intptr_t pos,718 MlirValue newValue) {719 unwrap(op)->setOperand(static_cast<unsigned>(pos), unwrap(newValue));720}721 722void mlirOperationSetOperands(MlirOperation op, intptr_t nOperands,723 MlirValue const *operands) {724 SmallVector<Value> ops;725 unwrap(op)->setOperands(unwrapList(nOperands, operands, ops));726}727 728intptr_t mlirOperationGetNumResults(MlirOperation op) {729 return static_cast<intptr_t>(unwrap(op)->getNumResults());730}731 732MlirValue mlirOperationGetResult(MlirOperation op, intptr_t pos) {733 return wrap(unwrap(op)->getResult(static_cast<unsigned>(pos)));734}735 736intptr_t mlirOperationGetNumSuccessors(MlirOperation op) {737 return static_cast<intptr_t>(unwrap(op)->getNumSuccessors());738}739 740MlirBlock mlirOperationGetSuccessor(MlirOperation op, intptr_t pos) {741 return wrap(unwrap(op)->getSuccessor(static_cast<unsigned>(pos)));742}743 744MLIR_CAPI_EXPORTED bool745mlirOperationHasInherentAttributeByName(MlirOperation op, MlirStringRef name) {746 std::optional<Attribute> attr = unwrap(op)->getInherentAttr(unwrap(name));747 return attr.has_value();748}749 750MlirAttribute mlirOperationGetInherentAttributeByName(MlirOperation op,751 MlirStringRef name) {752 std::optional<Attribute> attr = unwrap(op)->getInherentAttr(unwrap(name));753 if (attr.has_value())754 return wrap(*attr);755 return {};756}757 758void mlirOperationSetInherentAttributeByName(MlirOperation op,759 MlirStringRef name,760 MlirAttribute attr) {761 unwrap(op)->setInherentAttr(762 StringAttr::get(unwrap(op)->getContext(), unwrap(name)), unwrap(attr));763}764 765intptr_t mlirOperationGetNumDiscardableAttributes(MlirOperation op) {766 return static_cast<intptr_t>(767 llvm::range_size(unwrap(op)->getDiscardableAttrs()));768}769 770MlirNamedAttribute mlirOperationGetDiscardableAttribute(MlirOperation op,771 intptr_t pos) {772 NamedAttribute attr =773 *std::next(unwrap(op)->getDiscardableAttrs().begin(), pos);774 return MlirNamedAttribute{wrap(attr.getName()), wrap(attr.getValue())};775}776 777MlirAttribute mlirOperationGetDiscardableAttributeByName(MlirOperation op,778 MlirStringRef name) {779 return wrap(unwrap(op)->getDiscardableAttr(unwrap(name)));780}781 782void mlirOperationSetDiscardableAttributeByName(MlirOperation op,783 MlirStringRef name,784 MlirAttribute attr) {785 unwrap(op)->setDiscardableAttr(unwrap(name), unwrap(attr));786}787 788bool mlirOperationRemoveDiscardableAttributeByName(MlirOperation op,789 MlirStringRef name) {790 return !!unwrap(op)->removeDiscardableAttr(unwrap(name));791}792 793void mlirOperationSetSuccessor(MlirOperation op, intptr_t pos,794 MlirBlock block) {795 unwrap(op)->setSuccessor(unwrap(block), static_cast<unsigned>(pos));796}797 798intptr_t mlirOperationGetNumAttributes(MlirOperation op) {799 return static_cast<intptr_t>(unwrap(op)->getAttrs().size());800}801 802MlirNamedAttribute mlirOperationGetAttribute(MlirOperation op, intptr_t pos) {803 NamedAttribute attr = unwrap(op)->getAttrs()[pos];804 return MlirNamedAttribute{wrap(attr.getName()), wrap(attr.getValue())};805}806 807MlirAttribute mlirOperationGetAttributeByName(MlirOperation op,808 MlirStringRef name) {809 return wrap(unwrap(op)->getAttr(unwrap(name)));810}811 812void mlirOperationSetAttributeByName(MlirOperation op, MlirStringRef name,813 MlirAttribute attr) {814 unwrap(op)->setAttr(unwrap(name), unwrap(attr));815}816 817bool mlirOperationRemoveAttributeByName(MlirOperation op, MlirStringRef name) {818 return !!unwrap(op)->removeAttr(unwrap(name));819}820 821void mlirOperationPrint(MlirOperation op, MlirStringCallback callback,822 void *userData) {823 detail::CallbackOstream stream(callback, userData);824 unwrap(op)->print(stream);825}826 827void mlirOperationPrintWithFlags(MlirOperation op, MlirOpPrintingFlags flags,828 MlirStringCallback callback, void *userData) {829 detail::CallbackOstream stream(callback, userData);830 unwrap(op)->print(stream, *unwrap(flags));831}832 833void mlirOperationPrintWithState(MlirOperation op, MlirAsmState state,834 MlirStringCallback callback, void *userData) {835 detail::CallbackOstream stream(callback, userData);836 if (state.ptr)837 unwrap(op)->print(stream, *unwrap(state));838 unwrap(op)->print(stream);839}840 841void mlirOperationWriteBytecode(MlirOperation op, MlirStringCallback callback,842 void *userData) {843 detail::CallbackOstream stream(callback, userData);844 // As no desired version is set, no failure can occur.845 (void)writeBytecodeToFile(unwrap(op), stream);846}847 848MlirLogicalResult mlirOperationWriteBytecodeWithConfig(849 MlirOperation op, MlirBytecodeWriterConfig config,850 MlirStringCallback callback, void *userData) {851 detail::CallbackOstream stream(callback, userData);852 return wrap(writeBytecodeToFile(unwrap(op), stream, *unwrap(config)));853}854 855void mlirOperationDump(MlirOperation op) { return unwrap(op)->dump(); }856 857bool mlirOperationVerify(MlirOperation op) {858 return succeeded(verify(unwrap(op)));859}860 861void mlirOperationMoveAfter(MlirOperation op, MlirOperation other) {862 return unwrap(op)->moveAfter(unwrap(other));863}864 865void mlirOperationMoveBefore(MlirOperation op, MlirOperation other) {866 return unwrap(op)->moveBefore(unwrap(other));867}868 869bool mlirOperationIsBeforeInBlock(MlirOperation op, MlirOperation other) {870 return unwrap(op)->isBeforeInBlock(unwrap(other));871}872 873static mlir::WalkResult unwrap(MlirWalkResult result) {874 switch (result) {875 case MlirWalkResultAdvance:876 return mlir::WalkResult::advance();877 878 case MlirWalkResultInterrupt:879 return mlir::WalkResult::interrupt();880 881 case MlirWalkResultSkip:882 return mlir::WalkResult::skip();883 }884 llvm_unreachable("unknown result in WalkResult::unwrap");885}886 887void mlirOperationWalk(MlirOperation op, MlirOperationWalkCallback callback,888 void *userData, MlirWalkOrder walkOrder) {889 switch (walkOrder) {890 891 case MlirWalkPreOrder:892 unwrap(op)->walk<mlir::WalkOrder::PreOrder>(893 [callback, userData](Operation *op) {894 return unwrap(callback(wrap(op), userData));895 });896 break;897 case MlirWalkPostOrder:898 unwrap(op)->walk<mlir::WalkOrder::PostOrder>(899 [callback, userData](Operation *op) {900 return unwrap(callback(wrap(op), userData));901 });902 }903}904 905//===----------------------------------------------------------------------===//906// Region API.907//===----------------------------------------------------------------------===//908 909MlirRegion mlirRegionCreate() { return wrap(new Region); }910 911bool mlirRegionEqual(MlirRegion region, MlirRegion other) {912 return unwrap(region) == unwrap(other);913}914 915MlirBlock mlirRegionGetFirstBlock(MlirRegion region) {916 Region *cppRegion = unwrap(region);917 if (cppRegion->empty())918 return wrap(static_cast<Block *>(nullptr));919 return wrap(&cppRegion->front());920}921 922void mlirRegionAppendOwnedBlock(MlirRegion region, MlirBlock block) {923 unwrap(region)->push_back(unwrap(block));924}925 926void mlirRegionInsertOwnedBlock(MlirRegion region, intptr_t pos,927 MlirBlock block) {928 auto &blockList = unwrap(region)->getBlocks();929 blockList.insert(std::next(blockList.begin(), pos), unwrap(block));930}931 932void mlirRegionInsertOwnedBlockAfter(MlirRegion region, MlirBlock reference,933 MlirBlock block) {934 Region *cppRegion = unwrap(region);935 if (mlirBlockIsNull(reference)) {936 cppRegion->getBlocks().insert(cppRegion->begin(), unwrap(block));937 return;938 }939 940 assert(unwrap(reference)->getParent() == unwrap(region) &&941 "expected reference block to belong to the region");942 cppRegion->getBlocks().insertAfter(Region::iterator(unwrap(reference)),943 unwrap(block));944}945 946void mlirRegionInsertOwnedBlockBefore(MlirRegion region, MlirBlock reference,947 MlirBlock block) {948 if (mlirBlockIsNull(reference))949 return mlirRegionAppendOwnedBlock(region, block);950 951 assert(unwrap(reference)->getParent() == unwrap(region) &&952 "expected reference block to belong to the region");953 unwrap(region)->getBlocks().insert(Region::iterator(unwrap(reference)),954 unwrap(block));955}956 957void mlirRegionDestroy(MlirRegion region) {958 delete static_cast<Region *>(region.ptr);959}960 961void mlirRegionTakeBody(MlirRegion target, MlirRegion source) {962 unwrap(target)->takeBody(*unwrap(source));963}964 965//===----------------------------------------------------------------------===//966// Block API.967//===----------------------------------------------------------------------===//968 969MlirBlock mlirBlockCreate(intptr_t nArgs, MlirType const *args,970 MlirLocation const *locs) {971 Block *b = new Block;972 for (intptr_t i = 0; i < nArgs; ++i)973 b->addArgument(unwrap(args[i]), unwrap(locs[i]));974 return wrap(b);975}976 977bool mlirBlockEqual(MlirBlock block, MlirBlock other) {978 return unwrap(block) == unwrap(other);979}980 981MlirOperation mlirBlockGetParentOperation(MlirBlock block) {982 return wrap(unwrap(block)->getParentOp());983}984 985MlirRegion mlirBlockGetParentRegion(MlirBlock block) {986 return wrap(unwrap(block)->getParent());987}988 989MlirBlock mlirBlockGetNextInRegion(MlirBlock block) {990 return wrap(unwrap(block)->getNextNode());991}992 993MlirOperation mlirBlockGetFirstOperation(MlirBlock block) {994 Block *cppBlock = unwrap(block);995 if (cppBlock->empty())996 return wrap(static_cast<Operation *>(nullptr));997 return wrap(&cppBlock->front());998}999 1000MlirOperation mlirBlockGetTerminator(MlirBlock block) {1001 Block *cppBlock = unwrap(block);1002 if (cppBlock->empty())1003 return wrap(static_cast<Operation *>(nullptr));1004 Operation &back = cppBlock->back();1005 if (!back.hasTrait<OpTrait::IsTerminator>())1006 return wrap(static_cast<Operation *>(nullptr));1007 return wrap(&back);1008}1009 1010void mlirBlockAppendOwnedOperation(MlirBlock block, MlirOperation operation) {1011 unwrap(block)->push_back(unwrap(operation));1012}1013 1014void mlirBlockInsertOwnedOperation(MlirBlock block, intptr_t pos,1015 MlirOperation operation) {1016 auto &opList = unwrap(block)->getOperations();1017 opList.insert(std::next(opList.begin(), pos), unwrap(operation));1018}1019 1020void mlirBlockInsertOwnedOperationAfter(MlirBlock block,1021 MlirOperation reference,1022 MlirOperation operation) {1023 Block *cppBlock = unwrap(block);1024 if (mlirOperationIsNull(reference)) {1025 cppBlock->getOperations().insert(cppBlock->begin(), unwrap(operation));1026 return;1027 }1028 1029 assert(unwrap(reference)->getBlock() == unwrap(block) &&1030 "expected reference operation to belong to the block");1031 cppBlock->getOperations().insertAfter(Block::iterator(unwrap(reference)),1032 unwrap(operation));1033}1034 1035void mlirBlockInsertOwnedOperationBefore(MlirBlock block,1036 MlirOperation reference,1037 MlirOperation operation) {1038 if (mlirOperationIsNull(reference))1039 return mlirBlockAppendOwnedOperation(block, operation);1040 1041 assert(unwrap(reference)->getBlock() == unwrap(block) &&1042 "expected reference operation to belong to the block");1043 unwrap(block)->getOperations().insert(Block::iterator(unwrap(reference)),1044 unwrap(operation));1045}1046 1047void mlirBlockDestroy(MlirBlock block) { delete unwrap(block); }1048 1049void mlirBlockDetach(MlirBlock block) {1050 Block *b = unwrap(block);1051 b->getParent()->getBlocks().remove(b);1052}1053 1054intptr_t mlirBlockGetNumArguments(MlirBlock block) {1055 return static_cast<intptr_t>(unwrap(block)->getNumArguments());1056}1057 1058MlirValue mlirBlockAddArgument(MlirBlock block, MlirType type,1059 MlirLocation loc) {1060 return wrap(unwrap(block)->addArgument(unwrap(type), unwrap(loc)));1061}1062 1063void mlirBlockEraseArgument(MlirBlock block, unsigned index) {1064 return unwrap(block)->eraseArgument(index);1065}1066 1067MlirValue mlirBlockInsertArgument(MlirBlock block, intptr_t pos, MlirType type,1068 MlirLocation loc) {1069 return wrap(unwrap(block)->insertArgument(pos, unwrap(type), unwrap(loc)));1070}1071 1072MlirValue mlirBlockGetArgument(MlirBlock block, intptr_t pos) {1073 return wrap(unwrap(block)->getArgument(static_cast<unsigned>(pos)));1074}1075 1076void mlirBlockPrint(MlirBlock block, MlirStringCallback callback,1077 void *userData) {1078 detail::CallbackOstream stream(callback, userData);1079 unwrap(block)->print(stream);1080}1081 1082intptr_t mlirBlockGetNumSuccessors(MlirBlock block) {1083 return static_cast<intptr_t>(unwrap(block)->getNumSuccessors());1084}1085 1086MlirBlock mlirBlockGetSuccessor(MlirBlock block, intptr_t pos) {1087 return wrap(unwrap(block)->getSuccessor(static_cast<unsigned>(pos)));1088}1089 1090intptr_t mlirBlockGetNumPredecessors(MlirBlock block) {1091 Block *b = unwrap(block);1092 return static_cast<intptr_t>(std::distance(b->pred_begin(), b->pred_end()));1093}1094 1095MlirBlock mlirBlockGetPredecessor(MlirBlock block, intptr_t pos) {1096 Block *b = unwrap(block);1097 Block::pred_iterator it = b->pred_begin();1098 std::advance(it, pos);1099 return wrap(*it);1100}1101 1102//===----------------------------------------------------------------------===//1103// Value API.1104//===----------------------------------------------------------------------===//1105 1106bool mlirValueEqual(MlirValue value1, MlirValue value2) {1107 return unwrap(value1) == unwrap(value2);1108}1109 1110bool mlirValueIsABlockArgument(MlirValue value) {1111 return llvm::isa<BlockArgument>(unwrap(value));1112}1113 1114bool mlirValueIsAOpResult(MlirValue value) {1115 return llvm::isa<OpResult>(unwrap(value));1116}1117 1118MlirBlock mlirBlockArgumentGetOwner(MlirValue value) {1119 return wrap(llvm::dyn_cast<BlockArgument>(unwrap(value)).getOwner());1120}1121 1122intptr_t mlirBlockArgumentGetArgNumber(MlirValue value) {1123 return static_cast<intptr_t>(1124 llvm::dyn_cast<BlockArgument>(unwrap(value)).getArgNumber());1125}1126 1127void mlirBlockArgumentSetType(MlirValue value, MlirType type) {1128 if (auto blockArg = llvm::dyn_cast<BlockArgument>(unwrap(value)))1129 blockArg.setType(unwrap(type));1130}1131 1132void mlirBlockArgumentSetLocation(MlirValue value, MlirLocation loc) {1133 if (auto blockArg = llvm::dyn_cast<BlockArgument>(unwrap(value)))1134 blockArg.setLoc(unwrap(loc));1135}1136 1137MlirOperation mlirOpResultGetOwner(MlirValue value) {1138 return wrap(llvm::dyn_cast<OpResult>(unwrap(value)).getOwner());1139}1140 1141intptr_t mlirOpResultGetResultNumber(MlirValue value) {1142 return static_cast<intptr_t>(1143 llvm::dyn_cast<OpResult>(unwrap(value)).getResultNumber());1144}1145 1146MlirType mlirValueGetType(MlirValue value) {1147 return wrap(unwrap(value).getType());1148}1149 1150void mlirValueSetType(MlirValue value, MlirType type) {1151 unwrap(value).setType(unwrap(type));1152}1153 1154void mlirValueDump(MlirValue value) { unwrap(value).dump(); }1155 1156void mlirValuePrint(MlirValue value, MlirStringCallback callback,1157 void *userData) {1158 detail::CallbackOstream stream(callback, userData);1159 unwrap(value).print(stream);1160}1161 1162void mlirValuePrintAsOperand(MlirValue value, MlirAsmState state,1163 MlirStringCallback callback, void *userData) {1164 detail::CallbackOstream stream(callback, userData);1165 Value cppValue = unwrap(value);1166 cppValue.printAsOperand(stream, *unwrap(state));1167}1168 1169MlirOpOperand mlirValueGetFirstUse(MlirValue value) {1170 Value cppValue = unwrap(value);1171 if (cppValue.use_empty())1172 return {};1173 1174 OpOperand *opOperand = cppValue.use_begin().getOperand();1175 1176 return wrap(opOperand);1177}1178 1179void mlirValueReplaceAllUsesOfWith(MlirValue oldValue, MlirValue newValue) {1180 unwrap(oldValue).replaceAllUsesWith(unwrap(newValue));1181}1182 1183void mlirValueReplaceAllUsesExcept(MlirValue oldValue, MlirValue newValue,1184 intptr_t numExceptions,1185 MlirOperation *exceptions) {1186 Value oldValueCpp = unwrap(oldValue);1187 Value newValueCpp = unwrap(newValue);1188 1189 llvm::SmallPtrSet<mlir::Operation *, 4> exceptionSet;1190 for (intptr_t i = 0; i < numExceptions; ++i) {1191 exceptionSet.insert(unwrap(exceptions[i]));1192 }1193 1194 oldValueCpp.replaceAllUsesExcept(newValueCpp, exceptionSet);1195}1196 1197MlirLocation mlirValueGetLocation(MlirValue v) {1198 return wrap(unwrap(v).getLoc());1199}1200 1201MlirContext mlirValueGetContext(MlirValue v) {1202 return wrap(unwrap(v).getContext());1203}1204 1205//===----------------------------------------------------------------------===//1206// OpOperand API.1207//===----------------------------------------------------------------------===//1208 1209bool mlirOpOperandIsNull(MlirOpOperand opOperand) { return !opOperand.ptr; }1210 1211MlirOperation mlirOpOperandGetOwner(MlirOpOperand opOperand) {1212 return wrap(unwrap(opOperand)->getOwner());1213}1214 1215MlirValue mlirOpOperandGetValue(MlirOpOperand opOperand) {1216 return wrap(unwrap(opOperand)->get());1217}1218 1219unsigned mlirOpOperandGetOperandNumber(MlirOpOperand opOperand) {1220 return unwrap(opOperand)->getOperandNumber();1221}1222 1223MlirOpOperand mlirOpOperandGetNextUse(MlirOpOperand opOperand) {1224 if (mlirOpOperandIsNull(opOperand))1225 return {};1226 1227 OpOperand *nextOpOperand = static_cast<OpOperand *>(1228 unwrap(opOperand)->getNextOperandUsingThisValue());1229 1230 if (!nextOpOperand)1231 return {};1232 1233 return wrap(nextOpOperand);1234}1235 1236//===----------------------------------------------------------------------===//1237// Type API.1238//===----------------------------------------------------------------------===//1239 1240MlirType mlirTypeParseGet(MlirContext context, MlirStringRef type) {1241 return wrap(mlir::parseType(unwrap(type), unwrap(context)));1242}1243 1244MlirContext mlirTypeGetContext(MlirType type) {1245 return wrap(unwrap(type).getContext());1246}1247 1248MlirTypeID mlirTypeGetTypeID(MlirType type) {1249 return wrap(unwrap(type).getTypeID());1250}1251 1252MlirDialect mlirTypeGetDialect(MlirType type) {1253 return wrap(&unwrap(type).getDialect());1254}1255 1256bool mlirTypeEqual(MlirType t1, MlirType t2) {1257 return unwrap(t1) == unwrap(t2);1258}1259 1260void mlirTypePrint(MlirType type, MlirStringCallback callback, void *userData) {1261 detail::CallbackOstream stream(callback, userData);1262 unwrap(type).print(stream);1263}1264 1265void mlirTypeDump(MlirType type) { unwrap(type).dump(); }1266 1267//===----------------------------------------------------------------------===//1268// Attribute API.1269//===----------------------------------------------------------------------===//1270 1271MlirAttribute mlirAttributeParseGet(MlirContext context, MlirStringRef attr) {1272 return wrap(mlir::parseAttribute(unwrap(attr), unwrap(context)));1273}1274 1275MlirContext mlirAttributeGetContext(MlirAttribute attribute) {1276 return wrap(unwrap(attribute).getContext());1277}1278 1279MlirType mlirAttributeGetType(MlirAttribute attribute) {1280 Attribute attr = unwrap(attribute);1281 if (auto typedAttr = llvm::dyn_cast<TypedAttr>(attr))1282 return wrap(typedAttr.getType());1283 return wrap(NoneType::get(attr.getContext()));1284}1285 1286MlirTypeID mlirAttributeGetTypeID(MlirAttribute attr) {1287 return wrap(unwrap(attr).getTypeID());1288}1289 1290MlirDialect mlirAttributeGetDialect(MlirAttribute attr) {1291 return wrap(&unwrap(attr).getDialect());1292}1293 1294bool mlirAttributeEqual(MlirAttribute a1, MlirAttribute a2) {1295 return unwrap(a1) == unwrap(a2);1296}1297 1298void mlirAttributePrint(MlirAttribute attr, MlirStringCallback callback,1299 void *userData) {1300 detail::CallbackOstream stream(callback, userData);1301 unwrap(attr).print(stream);1302}1303 1304void mlirAttributeDump(MlirAttribute attr) { unwrap(attr).dump(); }1305 1306MlirNamedAttribute mlirNamedAttributeGet(MlirIdentifier name,1307 MlirAttribute attr) {1308 return MlirNamedAttribute{name, attr};1309}1310 1311//===----------------------------------------------------------------------===//1312// Identifier API.1313//===----------------------------------------------------------------------===//1314 1315MlirIdentifier mlirIdentifierGet(MlirContext context, MlirStringRef str) {1316 return wrap(StringAttr::get(unwrap(context), unwrap(str)));1317}1318 1319MlirContext mlirIdentifierGetContext(MlirIdentifier ident) {1320 return wrap(unwrap(ident).getContext());1321}1322 1323bool mlirIdentifierEqual(MlirIdentifier ident, MlirIdentifier other) {1324 return unwrap(ident) == unwrap(other);1325}1326 1327MlirStringRef mlirIdentifierStr(MlirIdentifier ident) {1328 return wrap(unwrap(ident).strref());1329}1330 1331//===----------------------------------------------------------------------===//1332// Symbol and SymbolTable API.1333//===----------------------------------------------------------------------===//1334 1335MlirStringRef mlirSymbolTableGetSymbolAttributeName() {1336 return wrap(SymbolTable::getSymbolAttrName());1337}1338 1339MlirStringRef mlirSymbolTableGetVisibilityAttributeName() {1340 return wrap(SymbolTable::getVisibilityAttrName());1341}1342 1343MlirSymbolTable mlirSymbolTableCreate(MlirOperation operation) {1344 if (!unwrap(operation)->hasTrait<OpTrait::SymbolTable>())1345 return wrap(static_cast<SymbolTable *>(nullptr));1346 return wrap(new SymbolTable(unwrap(operation)));1347}1348 1349void mlirSymbolTableDestroy(MlirSymbolTable symbolTable) {1350 delete unwrap(symbolTable);1351}1352 1353MlirOperation mlirSymbolTableLookup(MlirSymbolTable symbolTable,1354 MlirStringRef name) {1355 return wrap(unwrap(symbolTable)->lookup(StringRef(name.data, name.length)));1356}1357 1358MlirAttribute mlirSymbolTableInsert(MlirSymbolTable symbolTable,1359 MlirOperation operation) {1360 return wrap((Attribute)unwrap(symbolTable)->insert(unwrap(operation)));1361}1362 1363void mlirSymbolTableErase(MlirSymbolTable symbolTable,1364 MlirOperation operation) {1365 unwrap(symbolTable)->erase(unwrap(operation));1366}1367 1368MlirLogicalResult mlirSymbolTableReplaceAllSymbolUses(MlirStringRef oldSymbol,1369 MlirStringRef newSymbol,1370 MlirOperation from) {1371 auto *cppFrom = unwrap(from);1372 auto *context = cppFrom->getContext();1373 auto oldSymbolAttr = StringAttr::get(context, unwrap(oldSymbol));1374 auto newSymbolAttr = StringAttr::get(context, unwrap(newSymbol));1375 return wrap(SymbolTable::replaceAllSymbolUses(oldSymbolAttr, newSymbolAttr,1376 unwrap(from)));1377}1378 1379void mlirSymbolTableWalkSymbolTables(MlirOperation from, bool allSymUsesVisible,1380 void (*callback)(MlirOperation, bool,1381 void *userData),1382 void *userData) {1383 SymbolTable::walkSymbolTables(unwrap(from), allSymUsesVisible,1384 [&](Operation *foundOpCpp, bool isVisible) {1385 callback(wrap(foundOpCpp), isVisible,1386 userData);1387 });1388}1389