xref: /llvm-project/mlir/lib/CAPI/IR/IR.cpp (revision a77250fd782530f42a90f8562bcef0eb26abb010)
175f239e9SAlex Zinenko //===- IR.cpp - C Interface for Core MLIR APIs ----------------------------===//
275f239e9SAlex Zinenko //
375f239e9SAlex Zinenko // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
475f239e9SAlex Zinenko // See https://llvm.org/LICENSE.txt for license information.
575f239e9SAlex Zinenko // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
675f239e9SAlex Zinenko //
775f239e9SAlex Zinenko //===----------------------------------------------------------------------===//
875f239e9SAlex Zinenko 
975f239e9SAlex Zinenko #include "mlir-c/IR.h"
1064c0c9f0SAlex Zinenko #include "mlir-c/Support.h"
1175f239e9SAlex Zinenko 
12c60b897dSRiver Riddle #include "mlir/AsmParser/AsmParser.h"
1389418ddcSMehdi Amini #include "mlir/Bytecode/BytecodeWriter.h"
1474f57784SAlex Zinenko #include "mlir/CAPI/IR.h"
1564c0c9f0SAlex Zinenko #include "mlir/CAPI/Support.h"
16b76f523bSzhanghb97 #include "mlir/CAPI/Utils.h"
1775f239e9SAlex Zinenko #include "mlir/IR/Attributes.h"
18e767ef47SJacques Pienaar #include "mlir/IR/BuiltinAttributes.h"
1965fcddffSRiver Riddle #include "mlir/IR/BuiltinOps.h"
209ea6b30aSMehdi Amini #include "mlir/IR/Diagnostics.h"
21f9dc2b70SMehdi Amini #include "mlir/IR/Dialect.h"
22f7bf8a86SJacques Pienaar #include "mlir/IR/Location.h"
2375f239e9SAlex Zinenko #include "mlir/IR/Operation.h"
24e767ef47SJacques Pienaar #include "mlir/IR/OperationSupport.h"
2575f239e9SAlex Zinenko #include "mlir/IR/Types.h"
2681233c70Smax #include "mlir/IR/Value.h"
271c215949SMehdi Amini #include "mlir/IR/Verifier.h"
28bdc3e6cbSMaksim Levental #include "mlir/IR/Visitors.h"
2952586c46SStella Laurenzo #include "mlir/Interfaces/InferTypeOpInterface.h"
309eaff423SRiver Riddle #include "mlir/Parser/Parser.h"
3121df3251SPerry Gibson #include "llvm/ADT/SmallPtrSet.h"
326594f428SMehdi Amini #include "llvm/Support/ThreadPool.h"
3375f239e9SAlex Zinenko 
34782a97a9SDaniel Resnick #include <cstddef>
35e767ef47SJacques Pienaar #include <memory>
36a1fe1f5fSKazu Hirata #include <optional>
37caa159f0SNicolas Vasilache 
3875f239e9SAlex Zinenko using namespace mlir;
3975f239e9SAlex Zinenko 
40c7994bd9SMehdi Amini //===----------------------------------------------------------------------===//
41c7994bd9SMehdi Amini // Context API.
42c7994bd9SMehdi Amini //===----------------------------------------------------------------------===//
4375f239e9SAlex Zinenko 
4475f239e9SAlex Zinenko MlirContext mlirContextCreate() {
45e7021232SMehdi Amini   auto *context = new MLIRContext;
4675f239e9SAlex Zinenko   return wrap(context);
4775f239e9SAlex Zinenko }
4875f239e9SAlex Zinenko 
49d9e04b06SKrzysztof Drewniak static inline MLIRContext::Threading toThreadingEnum(bool threadingEnabled) {
50d9e04b06SKrzysztof Drewniak   return threadingEnabled ? MLIRContext::Threading::ENABLED
51d9e04b06SKrzysztof Drewniak                           : MLIRContext::Threading::DISABLED;
52d9e04b06SKrzysztof Drewniak }
53d9e04b06SKrzysztof Drewniak 
54d9e04b06SKrzysztof Drewniak MlirContext mlirContextCreateWithThreading(bool threadingEnabled) {
55d9e04b06SKrzysztof Drewniak   auto *context = new MLIRContext(toThreadingEnum(threadingEnabled));
56d9e04b06SKrzysztof Drewniak   return wrap(context);
57d9e04b06SKrzysztof Drewniak }
58d9e04b06SKrzysztof Drewniak 
59d9e04b06SKrzysztof Drewniak MlirContext mlirContextCreateWithRegistry(MlirDialectRegistry registry,
60d9e04b06SKrzysztof Drewniak                                           bool threadingEnabled) {
61d9e04b06SKrzysztof Drewniak   auto *context =
62d9e04b06SKrzysztof Drewniak       new MLIRContext(*unwrap(registry), toThreadingEnum(threadingEnabled));
63d9e04b06SKrzysztof Drewniak   return wrap(context);
64d9e04b06SKrzysztof Drewniak }
65d9e04b06SKrzysztof Drewniak 
668b6bea9bSGeorge bool mlirContextEqual(MlirContext ctx1, MlirContext ctx2) {
672d1362e0SStella Laurenzo   return unwrap(ctx1) == unwrap(ctx2);
682d1362e0SStella Laurenzo }
692d1362e0SStella Laurenzo 
7075f239e9SAlex Zinenko void mlirContextDestroy(MlirContext context) { delete unwrap(context); }
7175f239e9SAlex Zinenko 
7262195b75SStella Laurenzo void mlirContextSetAllowUnregisteredDialects(MlirContext context, bool allow) {
734cf754c4SStella Laurenzo   unwrap(context)->allowUnregisteredDialects(allow);
744cf754c4SStella Laurenzo }
754cf754c4SStella Laurenzo 
7662195b75SStella Laurenzo bool mlirContextGetAllowUnregisteredDialects(MlirContext context) {
774cf754c4SStella Laurenzo   return unwrap(context)->allowsUnregisteredDialects();
784cf754c4SStella Laurenzo }
7964c0c9f0SAlex Zinenko intptr_t mlirContextGetNumRegisteredDialects(MlirContext context) {
8064c0c9f0SAlex Zinenko   return static_cast<intptr_t>(unwrap(context)->getAvailableDialects().size());
8164c0c9f0SAlex Zinenko }
8264c0c9f0SAlex Zinenko 
8397fc5682SDaniel Resnick void mlirContextAppendDialectRegistry(MlirContext ctx,
8497fc5682SDaniel Resnick                                       MlirDialectRegistry registry) {
8597fc5682SDaniel Resnick   unwrap(ctx)->appendDialectRegistry(*unwrap(registry));
8697fc5682SDaniel Resnick }
8797fc5682SDaniel Resnick 
8864c0c9f0SAlex Zinenko // TODO: expose a cheaper way than constructing + sorting a vector only to take
8964c0c9f0SAlex Zinenko // its size.
9064c0c9f0SAlex Zinenko intptr_t mlirContextGetNumLoadedDialects(MlirContext context) {
9164c0c9f0SAlex Zinenko   return static_cast<intptr_t>(unwrap(context)->getLoadedDialects().size());
9264c0c9f0SAlex Zinenko }
9364c0c9f0SAlex Zinenko 
9464c0c9f0SAlex Zinenko MlirDialect mlirContextGetOrLoadDialect(MlirContext context,
9564c0c9f0SAlex Zinenko                                         MlirStringRef name) {
9664c0c9f0SAlex Zinenko   return wrap(unwrap(context)->getOrLoadDialect(unwrap(name)));
9764c0c9f0SAlex Zinenko }
9864c0c9f0SAlex Zinenko 
999a9214faSStella Laurenzo bool mlirContextIsRegisteredOperation(MlirContext context, MlirStringRef name) {
1009a9214faSStella Laurenzo   return unwrap(context)->isOperationRegistered(unwrap(name));
1019a9214faSStella Laurenzo }
1029a9214faSStella Laurenzo 
103caa159f0SNicolas Vasilache void mlirContextEnableMultithreading(MlirContext context, bool enable) {
104caa159f0SNicolas Vasilache   return unwrap(context)->enableMultithreading(enable);
105caa159f0SNicolas Vasilache }
106caa159f0SNicolas Vasilache 
1075e83a5b4SStella Laurenzo void mlirContextLoadAllAvailableDialects(MlirContext context) {
1085e83a5b4SStella Laurenzo   unwrap(context)->loadAllAvailableDialects();
1095e83a5b4SStella Laurenzo }
1105e83a5b4SStella Laurenzo 
111d9e04b06SKrzysztof Drewniak void mlirContextSetThreadPool(MlirContext context,
112d9e04b06SKrzysztof Drewniak                               MlirLlvmThreadPool threadPool) {
113d9e04b06SKrzysztof Drewniak   unwrap(context)->setThreadPool(*unwrap(threadPool));
114d9e04b06SKrzysztof Drewniak }
115d9e04b06SKrzysztof Drewniak 
116c7994bd9SMehdi Amini //===----------------------------------------------------------------------===//
117c7994bd9SMehdi Amini // Dialect API.
118c7994bd9SMehdi Amini //===----------------------------------------------------------------------===//
11964c0c9f0SAlex Zinenko 
12064c0c9f0SAlex Zinenko MlirContext mlirDialectGetContext(MlirDialect dialect) {
12164c0c9f0SAlex Zinenko   return wrap(unwrap(dialect)->getContext());
12264c0c9f0SAlex Zinenko }
12364c0c9f0SAlex Zinenko 
1248b6bea9bSGeorge bool mlirDialectEqual(MlirDialect dialect1, MlirDialect dialect2) {
12564c0c9f0SAlex Zinenko   return unwrap(dialect1) == unwrap(dialect2);
12664c0c9f0SAlex Zinenko }
12764c0c9f0SAlex Zinenko 
12864c0c9f0SAlex Zinenko MlirStringRef mlirDialectGetNamespace(MlirDialect dialect) {
12964c0c9f0SAlex Zinenko   return wrap(unwrap(dialect)->getNamespace());
13064c0c9f0SAlex Zinenko }
1314cf754c4SStella Laurenzo 
132c7994bd9SMehdi Amini //===----------------------------------------------------------------------===//
13397fc5682SDaniel Resnick // DialectRegistry API.
13497fc5682SDaniel Resnick //===----------------------------------------------------------------------===//
13597fc5682SDaniel Resnick 
13697fc5682SDaniel Resnick MlirDialectRegistry mlirDialectRegistryCreate() {
13797fc5682SDaniel Resnick   return wrap(new DialectRegistry());
13897fc5682SDaniel Resnick }
13997fc5682SDaniel Resnick 
14097fc5682SDaniel Resnick void mlirDialectRegistryDestroy(MlirDialectRegistry registry) {
14197fc5682SDaniel Resnick   delete unwrap(registry);
14297fc5682SDaniel Resnick }
14397fc5682SDaniel Resnick 
14497fc5682SDaniel Resnick //===----------------------------------------------------------------------===//
14531ebe98eSJacques Pienaar // AsmState API.
14631ebe98eSJacques Pienaar //===----------------------------------------------------------------------===//
14731ebe98eSJacques Pienaar 
14831ebe98eSJacques Pienaar MlirAsmState mlirAsmStateCreateForOperation(MlirOperation op,
14931ebe98eSJacques Pienaar                                             MlirOpPrintingFlags flags) {
15031ebe98eSJacques Pienaar   return wrap(new AsmState(unwrap(op), *unwrap(flags)));
15131ebe98eSJacques Pienaar }
15231ebe98eSJacques Pienaar 
15331ebe98eSJacques Pienaar static Operation *findParent(Operation *op, bool shouldUseLocalScope) {
15431ebe98eSJacques Pienaar   do {
15531ebe98eSJacques Pienaar     // If we are printing local scope, stop at the first operation that is
15631ebe98eSJacques Pienaar     // isolated from above.
15731ebe98eSJacques Pienaar     if (shouldUseLocalScope && op->hasTrait<OpTrait::IsIsolatedFromAbove>())
15831ebe98eSJacques Pienaar       break;
15931ebe98eSJacques Pienaar 
16031ebe98eSJacques Pienaar     // Otherwise, traverse up to the next parent.
16131ebe98eSJacques Pienaar     Operation *parentOp = op->getParentOp();
16231ebe98eSJacques Pienaar     if (!parentOp)
16331ebe98eSJacques Pienaar       break;
16431ebe98eSJacques Pienaar     op = parentOp;
16531ebe98eSJacques Pienaar   } while (true);
16631ebe98eSJacques Pienaar   return op;
16731ebe98eSJacques Pienaar }
16831ebe98eSJacques Pienaar 
16931ebe98eSJacques Pienaar MlirAsmState mlirAsmStateCreateForValue(MlirValue value,
17031ebe98eSJacques Pienaar                                         MlirOpPrintingFlags flags) {
17131ebe98eSJacques Pienaar   Operation *op;
17231ebe98eSJacques Pienaar   mlir::Value val = unwrap(value);
17331ebe98eSJacques Pienaar   if (auto result = llvm::dyn_cast<OpResult>(val)) {
17431ebe98eSJacques Pienaar     op = result.getOwner();
17531ebe98eSJacques Pienaar   } else {
17631ebe98eSJacques Pienaar     op = llvm::cast<BlockArgument>(val).getOwner()->getParentOp();
17731ebe98eSJacques Pienaar     if (!op) {
17831ebe98eSJacques Pienaar       emitError(val.getLoc()) << "<<UNKNOWN SSA VALUE>>";
17931ebe98eSJacques Pienaar       return {nullptr};
18031ebe98eSJacques Pienaar     }
18131ebe98eSJacques Pienaar   }
18231ebe98eSJacques Pienaar   op = findParent(op, unwrap(flags)->shouldUseLocalScope());
18331ebe98eSJacques Pienaar   return wrap(new AsmState(op, *unwrap(flags)));
18431ebe98eSJacques Pienaar }
18531ebe98eSJacques Pienaar 
18631ebe98eSJacques Pienaar /// Destroys printing flags created with mlirAsmStateCreate.
18731ebe98eSJacques Pienaar void mlirAsmStateDestroy(MlirAsmState state) { delete unwrap(state); }
18831ebe98eSJacques Pienaar 
18931ebe98eSJacques Pienaar //===----------------------------------------------------------------------===//
190c7994bd9SMehdi Amini // Printing flags API.
191c7994bd9SMehdi Amini //===----------------------------------------------------------------------===//
19274a58ec9SStella Laurenzo 
19374a58ec9SStella Laurenzo MlirOpPrintingFlags mlirOpPrintingFlagsCreate() {
19474a58ec9SStella Laurenzo   return wrap(new OpPrintingFlags());
19574a58ec9SStella Laurenzo }
19674a58ec9SStella Laurenzo 
19774a58ec9SStella Laurenzo void mlirOpPrintingFlagsDestroy(MlirOpPrintingFlags flags) {
19874a58ec9SStella Laurenzo   delete unwrap(flags);
19974a58ec9SStella Laurenzo }
20074a58ec9SStella Laurenzo 
20174a58ec9SStella Laurenzo void mlirOpPrintingFlagsElideLargeElementsAttrs(MlirOpPrintingFlags flags,
20274a58ec9SStella Laurenzo                                                 intptr_t largeElementLimit) {
20374a58ec9SStella Laurenzo   unwrap(flags)->elideLargeElementsAttrs(largeElementLimit);
20474a58ec9SStella Laurenzo }
20574a58ec9SStella Laurenzo 
206a582dde1SBrendan Hansknecht void mlirOpPrintingFlagsElideLargeResourceString(MlirOpPrintingFlags flags,
207a582dde1SBrendan Hansknecht                                                  intptr_t largeResourceLimit) {
208a582dde1SBrendan Hansknecht   unwrap(flags)->elideLargeResourceString(largeResourceLimit);
209a582dde1SBrendan Hansknecht }
210a582dde1SBrendan Hansknecht 
211d0236611SRiver Riddle void mlirOpPrintingFlagsEnableDebugInfo(MlirOpPrintingFlags flags, bool enable,
21262195b75SStella Laurenzo                                         bool prettyForm) {
213d0236611SRiver Riddle   unwrap(flags)->enableDebugInfo(enable, /*prettyForm=*/prettyForm);
21474a58ec9SStella Laurenzo }
21574a58ec9SStella Laurenzo 
21674a58ec9SStella Laurenzo void mlirOpPrintingFlagsPrintGenericOpForm(MlirOpPrintingFlags flags) {
21774a58ec9SStella Laurenzo   unwrap(flags)->printGenericOpForm();
21874a58ec9SStella Laurenzo }
21974a58ec9SStella Laurenzo 
22074a58ec9SStella Laurenzo void mlirOpPrintingFlagsUseLocalScope(MlirOpPrintingFlags flags) {
22174a58ec9SStella Laurenzo   unwrap(flags)->useLocalScope();
22274a58ec9SStella Laurenzo }
22374a58ec9SStella Laurenzo 
2242aa12583SRahul Kayaith void mlirOpPrintingFlagsAssumeVerified(MlirOpPrintingFlags flags) {
2252aa12583SRahul Kayaith   unwrap(flags)->assumeVerified();
2262aa12583SRahul Kayaith }
2272aa12583SRahul Kayaith 
228abad8455SJonas Rickert void mlirOpPrintingFlagsSkipRegions(MlirOpPrintingFlags flags) {
229abad8455SJonas Rickert   unwrap(flags)->skipRegions();
230abad8455SJonas Rickert }
231c7994bd9SMehdi Amini //===----------------------------------------------------------------------===//
2320610e2f6SJacques Pienaar // Bytecode printing flags API.
2330610e2f6SJacques Pienaar //===----------------------------------------------------------------------===//
2340610e2f6SJacques Pienaar 
2350610e2f6SJacques Pienaar MlirBytecodeWriterConfig mlirBytecodeWriterConfigCreate() {
2360610e2f6SJacques Pienaar   return wrap(new BytecodeWriterConfig());
2370610e2f6SJacques Pienaar }
2380610e2f6SJacques Pienaar 
2390610e2f6SJacques Pienaar void mlirBytecodeWriterConfigDestroy(MlirBytecodeWriterConfig config) {
2400610e2f6SJacques Pienaar   delete unwrap(config);
2410610e2f6SJacques Pienaar }
2420610e2f6SJacques Pienaar 
2430610e2f6SJacques Pienaar void mlirBytecodeWriterConfigDesiredEmitVersion(MlirBytecodeWriterConfig flags,
2440610e2f6SJacques Pienaar                                                 int64_t version) {
2450610e2f6SJacques Pienaar   unwrap(flags)->setDesiredBytecodeVersion(version);
2460610e2f6SJacques Pienaar }
2470610e2f6SJacques Pienaar 
2480610e2f6SJacques Pienaar //===----------------------------------------------------------------------===//
249c7994bd9SMehdi Amini // Location API.
250c7994bd9SMehdi Amini //===----------------------------------------------------------------------===//
25175f239e9SAlex Zinenko 
2527bfdac0eSAndrew Young MlirAttribute mlirLocationGetAttribute(MlirLocation location) {
2537bfdac0eSAndrew Young   return wrap(LocationAttr(unwrap(location)));
2547bfdac0eSAndrew Young }
2557bfdac0eSAndrew Young 
2567bfdac0eSAndrew Young MlirLocation mlirLocationFromAttribute(MlirAttribute attribute) {
257c1fa60b4STres Popp   return wrap(Location(llvm::cast<LocationAttr>(unwrap(attribute))));
2587bfdac0eSAndrew Young }
2597bfdac0eSAndrew Young 
26075f239e9SAlex Zinenko MlirLocation mlirLocationFileLineColGet(MlirContext context,
261df9ae599SGeorge                                         MlirStringRef filename, unsigned line,
26275f239e9SAlex Zinenko                                         unsigned col) {
263a4bb667dSRiver Riddle   return wrap(Location(
264a4bb667dSRiver Riddle       FileLineColLoc::get(unwrap(context), unwrap(filename), line, col)));
26575f239e9SAlex Zinenko }
26675f239e9SAlex Zinenko 
267*a77250fdSJacques Pienaar MlirLocation
268*a77250fdSJacques Pienaar mlirLocationFileLineColRangeGet(MlirContext context, MlirStringRef filename,
269*a77250fdSJacques Pienaar                                 unsigned startLine, unsigned startCol,
270*a77250fdSJacques Pienaar                                 unsigned endLine, unsigned endCol) {
271*a77250fdSJacques Pienaar   return wrap(
272*a77250fdSJacques Pienaar       Location(FileLineColRange::get(unwrap(context), unwrap(filename),
273*a77250fdSJacques Pienaar                                      startLine, startCol, endLine, endCol)));
274*a77250fdSJacques Pienaar }
275*a77250fdSJacques Pienaar 
2764a327bd2SGeorge MlirLocation mlirLocationCallSiteGet(MlirLocation callee, MlirLocation caller) {
277a4bb667dSRiver Riddle   return wrap(Location(CallSiteLoc::get(unwrap(callee), unwrap(caller))));
2784a327bd2SGeorge }
2794a327bd2SGeorge 
2800a1e569dSJacques Pienaar MlirLocation mlirLocationFusedGet(MlirContext ctx, intptr_t nLocations,
2810a1e569dSJacques Pienaar                                   MlirLocation const *locations,
2820a1e569dSJacques Pienaar                                   MlirAttribute metadata) {
2830a1e569dSJacques Pienaar   SmallVector<Location, 4> locs;
2840a1e569dSJacques Pienaar   ArrayRef<Location> unwrappedLocs = unwrapList(nLocations, locations, locs);
2850a1e569dSJacques Pienaar   return wrap(FusedLoc::get(unwrappedLocs, unwrap(metadata), unwrap(ctx)));
2860a1e569dSJacques Pienaar }
2870a1e569dSJacques Pienaar 
288f7bf8a86SJacques Pienaar MlirLocation mlirLocationNameGet(MlirContext context, MlirStringRef name,
289f7bf8a86SJacques Pienaar                                  MlirLocation childLoc) {
290f7bf8a86SJacques Pienaar   if (mlirLocationIsNull(childLoc))
291f7bf8a86SJacques Pienaar     return wrap(
292195730a6SRiver Riddle         Location(NameLoc::get(StringAttr::get(unwrap(context), unwrap(name)))));
293f7bf8a86SJacques Pienaar   return wrap(Location(NameLoc::get(
294195730a6SRiver Riddle       StringAttr::get(unwrap(context), unwrap(name)), unwrap(childLoc))));
295f7bf8a86SJacques Pienaar }
296f7bf8a86SJacques Pienaar 
29775f239e9SAlex Zinenko MlirLocation mlirLocationUnknownGet(MlirContext context) {
298a4bb667dSRiver Riddle   return wrap(Location(UnknownLoc::get(unwrap(context))));
29975f239e9SAlex Zinenko }
30075f239e9SAlex Zinenko 
30162195b75SStella Laurenzo bool mlirLocationEqual(MlirLocation l1, MlirLocation l2) {
302bd2083c2SStella Laurenzo   return unwrap(l1) == unwrap(l2);
303bd2083c2SStella Laurenzo }
304bd2083c2SStella Laurenzo 
30585185b61SStella Laurenzo MlirContext mlirLocationGetContext(MlirLocation location) {
30685185b61SStella Laurenzo   return wrap(unwrap(location).getContext());
30785185b61SStella Laurenzo }
30885185b61SStella Laurenzo 
309da562974SAlex Zinenko void mlirLocationPrint(MlirLocation location, MlirStringCallback callback,
310321aa19eSAlex Zinenko                        void *userData) {
311b76f523bSzhanghb97   detail::CallbackOstream stream(callback, userData);
312321aa19eSAlex Zinenko   unwrap(location).print(stream);
313321aa19eSAlex Zinenko }
314321aa19eSAlex Zinenko 
315c7994bd9SMehdi Amini //===----------------------------------------------------------------------===//
316c7994bd9SMehdi Amini // Module API.
317c7994bd9SMehdi Amini //===----------------------------------------------------------------------===//
31875f239e9SAlex Zinenko 
31975f239e9SAlex Zinenko MlirModule mlirModuleCreateEmpty(MlirLocation location) {
32075f239e9SAlex Zinenko   return wrap(ModuleOp::create(unwrap(location)));
32175f239e9SAlex Zinenko }
32275f239e9SAlex Zinenko 
323df9ae599SGeorge MlirModule mlirModuleCreateParse(MlirContext context, MlirStringRef module) {
3248f66ab1cSSanjoy Das   OwningOpRef<ModuleOp> owning =
325dfaadf6bSChristian Sigg       parseSourceString<ModuleOp>(unwrap(module), unwrap(context));
32695b77f2eSStella Laurenzo   if (!owning)
32795b77f2eSStella Laurenzo     return MlirModule{nullptr};
32875f239e9SAlex Zinenko   return MlirModule{owning.release().getOperation()};
32975f239e9SAlex Zinenko }
33075f239e9SAlex Zinenko 
33185185b61SStella Laurenzo MlirContext mlirModuleGetContext(MlirModule module) {
33285185b61SStella Laurenzo   return wrap(unwrap(module).getContext());
33385185b61SStella Laurenzo }
33485185b61SStella Laurenzo 
33572023442SMehdi Amini MlirBlock mlirModuleGetBody(MlirModule module) {
33672023442SMehdi Amini   return wrap(unwrap(module).getBody());
33772023442SMehdi Amini }
33872023442SMehdi Amini 
33975f239e9SAlex Zinenko void mlirModuleDestroy(MlirModule module) {
3408f66ab1cSSanjoy Das   // Transfer ownership to an OwningOpRef<ModuleOp> so that its destructor is
3418f66ab1cSSanjoy Das   // called.
3428f66ab1cSSanjoy Das   OwningOpRef<ModuleOp>(unwrap(module));
34375f239e9SAlex Zinenko }
34475f239e9SAlex Zinenko 
34575f239e9SAlex Zinenko MlirOperation mlirModuleGetOperation(MlirModule module) {
34675f239e9SAlex Zinenko   return wrap(unwrap(module).getOperation());
34775f239e9SAlex Zinenko }
34875f239e9SAlex Zinenko 
349d89602edSAdam Paszke MlirModule mlirModuleFromOperation(MlirOperation op) {
350d89602edSAdam Paszke   return wrap(dyn_cast<ModuleOp>(unwrap(op)));
351d89602edSAdam Paszke }
352d89602edSAdam Paszke 
353c7994bd9SMehdi Amini //===----------------------------------------------------------------------===//
354c7994bd9SMehdi Amini // Operation state API.
355c7994bd9SMehdi Amini //===----------------------------------------------------------------------===//
35675f239e9SAlex Zinenko 
357df9ae599SGeorge MlirOperationState mlirOperationStateGet(MlirStringRef name, MlirLocation loc) {
35875f239e9SAlex Zinenko   MlirOperationState state;
35975f239e9SAlex Zinenko   state.name = name;
36075f239e9SAlex Zinenko   state.location = loc;
36175f239e9SAlex Zinenko   state.nResults = 0;
36275f239e9SAlex Zinenko   state.results = nullptr;
36375f239e9SAlex Zinenko   state.nOperands = 0;
36475f239e9SAlex Zinenko   state.operands = nullptr;
36575f239e9SAlex Zinenko   state.nRegions = 0;
36675f239e9SAlex Zinenko   state.regions = nullptr;
36775f239e9SAlex Zinenko   state.nSuccessors = 0;
36875f239e9SAlex Zinenko   state.successors = nullptr;
36975f239e9SAlex Zinenko   state.nAttributes = 0;
37075f239e9SAlex Zinenko   state.attributes = nullptr;
37152586c46SStella Laurenzo   state.enableResultTypeInference = false;
37275f239e9SAlex Zinenko   return state;
37375f239e9SAlex Zinenko }
37475f239e9SAlex Zinenko 
37575f239e9SAlex Zinenko #define APPEND_ELEMS(type, sizeName, elemName)                                 \
37675f239e9SAlex Zinenko   state->elemName =                                                            \
37775f239e9SAlex Zinenko       (type *)realloc(state->elemName, (state->sizeName + n) * sizeof(type));  \
37875f239e9SAlex Zinenko   memcpy(state->elemName + state->sizeName, elemName, n * sizeof(type));       \
37975f239e9SAlex Zinenko   state->sizeName += n;
38075f239e9SAlex Zinenko 
381af838584SAlex Zinenko void mlirOperationStateAddResults(MlirOperationState *state, intptr_t n,
382beb889c1SGeorge                                   MlirType const *results) {
38375f239e9SAlex Zinenko   APPEND_ELEMS(MlirType, nResults, results);
38475f239e9SAlex Zinenko }
38575f239e9SAlex Zinenko 
386af838584SAlex Zinenko void mlirOperationStateAddOperands(MlirOperationState *state, intptr_t n,
387beb889c1SGeorge                                    MlirValue const *operands) {
38875f239e9SAlex Zinenko   APPEND_ELEMS(MlirValue, nOperands, operands);
38975f239e9SAlex Zinenko }
390af838584SAlex Zinenko void mlirOperationStateAddOwnedRegions(MlirOperationState *state, intptr_t n,
391beb889c1SGeorge                                        MlirRegion const *regions) {
39275f239e9SAlex Zinenko   APPEND_ELEMS(MlirRegion, nRegions, regions);
39375f239e9SAlex Zinenko }
394af838584SAlex Zinenko void mlirOperationStateAddSuccessors(MlirOperationState *state, intptr_t n,
395beb889c1SGeorge                                      MlirBlock const *successors) {
39675f239e9SAlex Zinenko   APPEND_ELEMS(MlirBlock, nSuccessors, successors);
39775f239e9SAlex Zinenko }
398af838584SAlex Zinenko void mlirOperationStateAddAttributes(MlirOperationState *state, intptr_t n,
399beb889c1SGeorge                                      MlirNamedAttribute const *attributes) {
40075f239e9SAlex Zinenko   APPEND_ELEMS(MlirNamedAttribute, nAttributes, attributes);
40175f239e9SAlex Zinenko }
40275f239e9SAlex Zinenko 
40352586c46SStella Laurenzo void mlirOperationStateEnableResultTypeInference(MlirOperationState *state) {
40452586c46SStella Laurenzo   state->enableResultTypeInference = true;
40552586c46SStella Laurenzo }
40652586c46SStella Laurenzo 
407c7994bd9SMehdi Amini //===----------------------------------------------------------------------===//
408c7994bd9SMehdi Amini // Operation API.
409c7994bd9SMehdi Amini //===----------------------------------------------------------------------===//
41075f239e9SAlex Zinenko 
41152586c46SStella Laurenzo static LogicalResult inferOperationTypes(OperationState &state) {
41252586c46SStella Laurenzo   MLIRContext *context = state.getContext();
4130a81ace0SKazu Hirata   std::optional<RegisteredOperationName> info = state.name.getRegisteredInfo();
414edc6c0ecSRiver Riddle   if (!info) {
41552586c46SStella Laurenzo     emitError(state.location)
41652586c46SStella Laurenzo         << "type inference was requested for the operation " << state.name
417e767ef47SJacques Pienaar         << ", but the operation was not registered; ensure that the dialect "
41852586c46SStella Laurenzo            "containing the operation is linked into MLIR and registered with "
41952586c46SStella Laurenzo            "the context";
42052586c46SStella Laurenzo     return failure();
42152586c46SStella Laurenzo   }
42252586c46SStella Laurenzo 
423edc6c0ecSRiver Riddle   auto *inferInterface = info->getInterface<InferTypeOpInterface>();
42452586c46SStella Laurenzo   if (!inferInterface) {
42552586c46SStella Laurenzo     emitError(state.location)
42652586c46SStella Laurenzo         << "type inference was requested for the operation " << state.name
427e767ef47SJacques Pienaar         << ", but the operation does not support type inference; result "
428e767ef47SJacques Pienaar            "types must be specified explicitly";
429e767ef47SJacques Pienaar     return failure();
430e767ef47SJacques Pienaar   }
431e767ef47SJacques Pienaar 
432e767ef47SJacques Pienaar   DictionaryAttr attributes = state.attributes.getDictionary(context);
433e767ef47SJacques Pienaar   OpaqueProperties properties = state.getRawProperties();
434e767ef47SJacques Pienaar 
435e767ef47SJacques Pienaar   if (!properties && info->getOpPropertyByteSize() > 0 && !attributes.empty()) {
436e767ef47SJacques Pienaar     auto prop = std::make_unique<char[]>(info->getOpPropertyByteSize());
437e767ef47SJacques Pienaar     properties = OpaqueProperties(prop.get());
4388c2bff1aSMehdi Amini     if (properties) {
439c50617daSMehdi Amini       auto emitError = [&]() {
440c50617daSMehdi Amini         return mlir::emitError(state.location)
4419ea6b30aSMehdi Amini                << " failed properties conversion while building "
442c50617daSMehdi Amini                << state.name.getStringRef() << " with `" << attributes << "`: ";
4438c2bff1aSMehdi Amini       };
444e767ef47SJacques Pienaar       if (failed(info->setOpPropertiesFromAttribute(state.name, properties,
445c50617daSMehdi Amini                                                     attributes, emitError)))
44652586c46SStella Laurenzo         return failure();
44752586c46SStella Laurenzo     }
44852586c46SStella Laurenzo     if (succeeded(inferInterface->inferReturnTypes(
449e767ef47SJacques Pienaar             context, state.location, state.operands, attributes, properties,
450e767ef47SJacques Pienaar             state.regions, state.types))) {
451e767ef47SJacques Pienaar       return success();
452e767ef47SJacques Pienaar     }
453e767ef47SJacques Pienaar     // Diagnostic emitted by interface.
454e767ef47SJacques Pienaar     return failure();
455e767ef47SJacques Pienaar   }
456e767ef47SJacques Pienaar 
457e767ef47SJacques Pienaar   if (succeeded(inferInterface->inferReturnTypes(
458e767ef47SJacques Pienaar           context, state.location, state.operands, attributes, properties,
4595e118f93SMehdi Amini           state.regions, state.types)))
46052586c46SStella Laurenzo     return success();
46152586c46SStella Laurenzo 
46252586c46SStella Laurenzo   // Diagnostic emitted by interface.
46352586c46SStella Laurenzo   return failure();
46452586c46SStella Laurenzo }
46552586c46SStella Laurenzo 
46652586c46SStella Laurenzo MlirOperation mlirOperationCreate(MlirOperationState *state) {
46775f239e9SAlex Zinenko   assert(state);
468df9ae599SGeorge   OperationState cppState(unwrap(state->location), unwrap(state->name));
46975f239e9SAlex Zinenko   SmallVector<Type, 4> resultStorage;
47075f239e9SAlex Zinenko   SmallVector<Value, 8> operandStorage;
47175f239e9SAlex Zinenko   SmallVector<Block *, 2> successorStorage;
47275f239e9SAlex Zinenko   cppState.addTypes(unwrapList(state->nResults, state->results, resultStorage));
47375f239e9SAlex Zinenko   cppState.addOperands(
47475f239e9SAlex Zinenko       unwrapList(state->nOperands, state->operands, operandStorage));
47575f239e9SAlex Zinenko   cppState.addSuccessors(
47675f239e9SAlex Zinenko       unwrapList(state->nSuccessors, state->successors, successorStorage));
47775f239e9SAlex Zinenko 
47875f239e9SAlex Zinenko   cppState.attributes.reserve(state->nAttributes);
479af838584SAlex Zinenko   for (intptr_t i = 0; i < state->nAttributes; ++i)
480df9ae599SGeorge     cppState.addAttribute(unwrap(state->attributes[i].name),
48175f239e9SAlex Zinenko                           unwrap(state->attributes[i].attribute));
48275f239e9SAlex Zinenko 
483af838584SAlex Zinenko   for (intptr_t i = 0; i < state->nRegions; ++i)
48475f239e9SAlex Zinenko     cppState.addRegion(std::unique_ptr<Region>(unwrap(state->regions[i])));
48575f239e9SAlex Zinenko 
48669eb7e36SJing Pu   free(state->results);
48769eb7e36SJing Pu   free(state->operands);
48869eb7e36SJing Pu   free(state->successors);
489af838584SAlex Zinenko   free(state->regions);
49069eb7e36SJing Pu   free(state->attributes);
49152586c46SStella Laurenzo 
49252586c46SStella Laurenzo   // Infer result types.
49352586c46SStella Laurenzo   if (state->enableResultTypeInference) {
49452586c46SStella Laurenzo     assert(cppState.types.empty() &&
49552586c46SStella Laurenzo            "result type inference enabled and result types provided");
49652586c46SStella Laurenzo     if (failed(inferOperationTypes(cppState)))
49752586c46SStella Laurenzo       return {nullptr};
49852586c46SStella Laurenzo   }
49952586c46SStella Laurenzo 
500e767ef47SJacques Pienaar   return wrap(Operation::create(cppState));
50175f239e9SAlex Zinenko }
50275f239e9SAlex Zinenko 
50337107e17Srkayaith MlirOperation mlirOperationCreateParse(MlirContext context,
50437107e17Srkayaith                                        MlirStringRef sourceStr,
50537107e17Srkayaith                                        MlirStringRef sourceName) {
50637107e17Srkayaith 
50737107e17Srkayaith   return wrap(
50837107e17Srkayaith       parseSourceString(unwrap(sourceStr), unwrap(context), unwrap(sourceName))
50937107e17Srkayaith           .release());
51037107e17Srkayaith }
51137107e17Srkayaith 
512d3e6c2ddSGeorge MlirOperation mlirOperationClone(MlirOperation op) {
513d3e6c2ddSGeorge   return wrap(unwrap(op)->clone());
514d3e6c2ddSGeorge }
515d3e6c2ddSGeorge 
51675f239e9SAlex Zinenko void mlirOperationDestroy(MlirOperation op) { unwrap(op)->erase(); }
51775f239e9SAlex Zinenko 
51824685aaeSAlex Zinenko void mlirOperationRemoveFromParent(MlirOperation op) { unwrap(op)->remove(); }
51924685aaeSAlex Zinenko 
5208b6bea9bSGeorge bool mlirOperationEqual(MlirOperation op, MlirOperation other) {
52139613c2cSAlex Zinenko   return unwrap(op) == unwrap(other);
52239613c2cSAlex Zinenko }
52339613c2cSAlex Zinenko 
5248f130f10SGeorge MlirContext mlirOperationGetContext(MlirOperation op) {
5258f130f10SGeorge   return wrap(unwrap(op)->getContext());
5268f130f10SGeorge }
5278f130f10SGeorge 
528d5429a13Srkayaith MlirLocation mlirOperationGetLocation(MlirOperation op) {
529d5429a13Srkayaith   return wrap(unwrap(op)->getLoc());
530d5429a13Srkayaith }
531d5429a13Srkayaith 
532782a97a9SDaniel Resnick MlirTypeID mlirOperationGetTypeID(MlirOperation op) {
533edc6c0ecSRiver Riddle   if (auto info = unwrap(op)->getRegisteredInfo())
534edc6c0ecSRiver Riddle     return wrap(info->getTypeID());
535782a97a9SDaniel Resnick   return {nullptr};
536782a97a9SDaniel Resnick }
537782a97a9SDaniel Resnick 
538b85f2f5cSStella Laurenzo MlirIdentifier mlirOperationGetName(MlirOperation op) {
539b85f2f5cSStella Laurenzo   return wrap(unwrap(op)->getName().getIdentifier());
540b85f2f5cSStella Laurenzo }
541b85f2f5cSStella Laurenzo 
542c645ea5eSStella Laurenzo MlirBlock mlirOperationGetBlock(MlirOperation op) {
543c645ea5eSStella Laurenzo   return wrap(unwrap(op)->getBlock());
544c645ea5eSStella Laurenzo }
545c645ea5eSStella Laurenzo 
546c645ea5eSStella Laurenzo MlirOperation mlirOperationGetParentOperation(MlirOperation op) {
547c645ea5eSStella Laurenzo   return wrap(unwrap(op)->getParentOp());
548c645ea5eSStella Laurenzo }
549c645ea5eSStella Laurenzo 
550af838584SAlex Zinenko intptr_t mlirOperationGetNumRegions(MlirOperation op) {
551af838584SAlex Zinenko   return static_cast<intptr_t>(unwrap(op)->getNumRegions());
55275f239e9SAlex Zinenko }
55375f239e9SAlex Zinenko 
554af838584SAlex Zinenko MlirRegion mlirOperationGetRegion(MlirOperation op, intptr_t pos) {
555af838584SAlex Zinenko   return wrap(&unwrap(op)->getRegion(static_cast<unsigned>(pos)));
55675f239e9SAlex Zinenko }
55775f239e9SAlex Zinenko 
558d1a688ceSJacques Pienaar MlirRegion mlirOperationGetFirstRegion(MlirOperation op) {
559d1a688ceSJacques Pienaar   Operation *cppOp = unwrap(op);
560d1a688ceSJacques Pienaar   if (cppOp->getNumRegions() == 0)
561d1a688ceSJacques Pienaar     return wrap(static_cast<Region *>(nullptr));
562d1a688ceSJacques Pienaar   return wrap(&cppOp->getRegion(0));
563d1a688ceSJacques Pienaar }
564d1a688ceSJacques Pienaar 
565d1a688ceSJacques Pienaar MlirRegion mlirRegionGetNextInOperation(MlirRegion region) {
566d1a688ceSJacques Pienaar   Region *cppRegion = unwrap(region);
567d1a688ceSJacques Pienaar   Operation *parent = cppRegion->getParentOp();
568d1a688ceSJacques Pienaar   intptr_t next = cppRegion->getRegionNumber() + 1;
569d1a688ceSJacques Pienaar   if (parent->getNumRegions() > next)
570d1a688ceSJacques Pienaar     return wrap(&parent->getRegion(next));
571d1a688ceSJacques Pienaar   return wrap(static_cast<Region *>(nullptr));
572d1a688ceSJacques Pienaar }
573d1a688ceSJacques Pienaar 
57475f239e9SAlex Zinenko MlirOperation mlirOperationGetNextInBlock(MlirOperation op) {
57575f239e9SAlex Zinenko   return wrap(unwrap(op)->getNextNode());
57675f239e9SAlex Zinenko }
57775f239e9SAlex Zinenko 
578af838584SAlex Zinenko intptr_t mlirOperationGetNumOperands(MlirOperation op) {
579af838584SAlex Zinenko   return static_cast<intptr_t>(unwrap(op)->getNumOperands());
58075f239e9SAlex Zinenko }
58175f239e9SAlex Zinenko 
582af838584SAlex Zinenko MlirValue mlirOperationGetOperand(MlirOperation op, intptr_t pos) {
583af838584SAlex Zinenko   return wrap(unwrap(op)->getOperand(static_cast<unsigned>(pos)));
58475f239e9SAlex Zinenko }
58575f239e9SAlex Zinenko 
58663d16d06SMike Urbach void mlirOperationSetOperand(MlirOperation op, intptr_t pos,
58763d16d06SMike Urbach                              MlirValue newValue) {
58863d16d06SMike Urbach   unwrap(op)->setOperand(static_cast<unsigned>(pos), unwrap(newValue));
58963d16d06SMike Urbach }
59063d16d06SMike Urbach 
59186bc2e3aSAdam Paszke void mlirOperationSetOperands(MlirOperation op, intptr_t nOperands,
59286bc2e3aSAdam Paszke                               MlirValue const *operands) {
59386bc2e3aSAdam Paszke   SmallVector<Value> ops;
59486bc2e3aSAdam Paszke   unwrap(op)->setOperands(unwrapList(nOperands, operands, ops));
59586bc2e3aSAdam Paszke }
59686bc2e3aSAdam Paszke 
597af838584SAlex Zinenko intptr_t mlirOperationGetNumResults(MlirOperation op) {
598af838584SAlex Zinenko   return static_cast<intptr_t>(unwrap(op)->getNumResults());
59975f239e9SAlex Zinenko }
60075f239e9SAlex Zinenko 
601af838584SAlex Zinenko MlirValue mlirOperationGetResult(MlirOperation op, intptr_t pos) {
602af838584SAlex Zinenko   return wrap(unwrap(op)->getResult(static_cast<unsigned>(pos)));
60375f239e9SAlex Zinenko }
60475f239e9SAlex Zinenko 
605af838584SAlex Zinenko intptr_t mlirOperationGetNumSuccessors(MlirOperation op) {
606af838584SAlex Zinenko   return static_cast<intptr_t>(unwrap(op)->getNumSuccessors());
60775f239e9SAlex Zinenko }
60875f239e9SAlex Zinenko 
609af838584SAlex Zinenko MlirBlock mlirOperationGetSuccessor(MlirOperation op, intptr_t pos) {
610af838584SAlex Zinenko   return wrap(unwrap(op)->getSuccessor(static_cast<unsigned>(pos)));
61175f239e9SAlex Zinenko }
61275f239e9SAlex Zinenko 
6137675f541SMehdi Amini MLIR_CAPI_EXPORTED bool
6147675f541SMehdi Amini mlirOperationHasInherentAttributeByName(MlirOperation op, MlirStringRef name) {
6157675f541SMehdi Amini   std::optional<Attribute> attr = unwrap(op)->getInherentAttr(unwrap(name));
6167675f541SMehdi Amini   return attr.has_value();
6177675f541SMehdi Amini }
6187675f541SMehdi Amini 
6197675f541SMehdi Amini MlirAttribute mlirOperationGetInherentAttributeByName(MlirOperation op,
6207675f541SMehdi Amini                                                       MlirStringRef name) {
6217675f541SMehdi Amini   std::optional<Attribute> attr = unwrap(op)->getInherentAttr(unwrap(name));
6227675f541SMehdi Amini   if (attr.has_value())
6237675f541SMehdi Amini     return wrap(*attr);
6247675f541SMehdi Amini   return {};
6257675f541SMehdi Amini }
6267675f541SMehdi Amini 
6277675f541SMehdi Amini void mlirOperationSetInherentAttributeByName(MlirOperation op,
6287675f541SMehdi Amini                                              MlirStringRef name,
6297675f541SMehdi Amini                                              MlirAttribute attr) {
6307675f541SMehdi Amini   unwrap(op)->setInherentAttr(
6317675f541SMehdi Amini       StringAttr::get(unwrap(op)->getContext(), unwrap(name)), unwrap(attr));
6327675f541SMehdi Amini }
6337675f541SMehdi Amini 
6347675f541SMehdi Amini intptr_t mlirOperationGetNumDiscardableAttributes(MlirOperation op) {
635c1eab576SOleksandr "Alex" Zinenko   return static_cast<intptr_t>(
636c1eab576SOleksandr "Alex" Zinenko       llvm::range_size(unwrap(op)->getDiscardableAttrs()));
6377675f541SMehdi Amini }
6387675f541SMehdi Amini 
6397675f541SMehdi Amini MlirNamedAttribute mlirOperationGetDiscardableAttribute(MlirOperation op,
6407675f541SMehdi Amini                                                         intptr_t pos) {
641c1eab576SOleksandr "Alex" Zinenko   NamedAttribute attr =
642c1eab576SOleksandr "Alex" Zinenko       *std::next(unwrap(op)->getDiscardableAttrs().begin(), pos);
6437675f541SMehdi Amini   return MlirNamedAttribute{wrap(attr.getName()), wrap(attr.getValue())};
6447675f541SMehdi Amini }
6457675f541SMehdi Amini 
6467675f541SMehdi Amini MlirAttribute mlirOperationGetDiscardableAttributeByName(MlirOperation op,
6477675f541SMehdi Amini                                                          MlirStringRef name) {
6487675f541SMehdi Amini   return wrap(unwrap(op)->getDiscardableAttr(unwrap(name)));
6497675f541SMehdi Amini }
6507675f541SMehdi Amini 
6517675f541SMehdi Amini void mlirOperationSetDiscardableAttributeByName(MlirOperation op,
6527675f541SMehdi Amini                                                 MlirStringRef name,
6537675f541SMehdi Amini                                                 MlirAttribute attr) {
6547675f541SMehdi Amini   unwrap(op)->setDiscardableAttr(unwrap(name), unwrap(attr));
6557675f541SMehdi Amini }
6567675f541SMehdi Amini 
6577675f541SMehdi Amini bool mlirOperationRemoveDiscardableAttributeByName(MlirOperation op,
6587675f541SMehdi Amini                                                    MlirStringRef name) {
6597675f541SMehdi Amini   return !!unwrap(op)->removeDiscardableAttr(unwrap(name));
6607675f541SMehdi Amini }
6617675f541SMehdi Amini 
662d7e49736SMaksim Levental void mlirOperationSetSuccessor(MlirOperation op, intptr_t pos,
663d7e49736SMaksim Levental                                MlirBlock block) {
664d7e49736SMaksim Levental   unwrap(op)->setSuccessor(unwrap(block), static_cast<unsigned>(pos));
665d7e49736SMaksim Levental }
666d7e49736SMaksim Levental 
667af838584SAlex Zinenko intptr_t mlirOperationGetNumAttributes(MlirOperation op) {
668af838584SAlex Zinenko   return static_cast<intptr_t>(unwrap(op)->getAttrs().size());
66975f239e9SAlex Zinenko }
67075f239e9SAlex Zinenko 
671af838584SAlex Zinenko MlirNamedAttribute mlirOperationGetAttribute(MlirOperation op, intptr_t pos) {
67275f239e9SAlex Zinenko   NamedAttribute attr = unwrap(op)->getAttrs()[pos];
6730c7890c8SRiver Riddle   return MlirNamedAttribute{wrap(attr.getName()), wrap(attr.getValue())};
67475f239e9SAlex Zinenko }
67575f239e9SAlex Zinenko 
67675f239e9SAlex Zinenko MlirAttribute mlirOperationGetAttributeByName(MlirOperation op,
677df9ae599SGeorge                                               MlirStringRef name) {
678df9ae599SGeorge   return wrap(unwrap(op)->getAttr(unwrap(name)));
67975f239e9SAlex Zinenko }
68075f239e9SAlex Zinenko 
681df9ae599SGeorge void mlirOperationSetAttributeByName(MlirOperation op, MlirStringRef name,
6824aa21716SStella Laurenzo                                      MlirAttribute attr) {
683df9ae599SGeorge   unwrap(op)->setAttr(unwrap(name), unwrap(attr));
6844aa21716SStella Laurenzo }
6854aa21716SStella Laurenzo 
68662195b75SStella Laurenzo bool mlirOperationRemoveAttributeByName(MlirOperation op, MlirStringRef name) {
687fc5cf50eSRiver Riddle   return !!unwrap(op)->removeAttr(unwrap(name));
6884aa21716SStella Laurenzo }
6894aa21716SStella Laurenzo 
690da562974SAlex Zinenko void mlirOperationPrint(MlirOperation op, MlirStringCallback callback,
691321aa19eSAlex Zinenko                         void *userData) {
692b76f523bSzhanghb97   detail::CallbackOstream stream(callback, userData);
693321aa19eSAlex Zinenko   unwrap(op)->print(stream);
694321aa19eSAlex Zinenko }
695321aa19eSAlex Zinenko 
69674a58ec9SStella Laurenzo void mlirOperationPrintWithFlags(MlirOperation op, MlirOpPrintingFlags flags,
69774a58ec9SStella Laurenzo                                  MlirStringCallback callback, void *userData) {
69874a58ec9SStella Laurenzo   detail::CallbackOstream stream(callback, userData);
69974a58ec9SStella Laurenzo   unwrap(op)->print(stream, *unwrap(flags));
70074a58ec9SStella Laurenzo }
70174a58ec9SStella Laurenzo 
702e0928abbSJacques Pienaar void mlirOperationPrintWithState(MlirOperation op, MlirAsmState state,
703e0928abbSJacques Pienaar                                  MlirStringCallback callback, void *userData) {
704e0928abbSJacques Pienaar   detail::CallbackOstream stream(callback, userData);
705e0928abbSJacques Pienaar   if (state.ptr)
706e0928abbSJacques Pienaar     unwrap(op)->print(stream, *unwrap(state));
707e0928abbSJacques Pienaar   unwrap(op)->print(stream);
708e0928abbSJacques Pienaar }
709e0928abbSJacques Pienaar 
7105c90e1ffSJacques Pienaar void mlirOperationWriteBytecode(MlirOperation op, MlirStringCallback callback,
71189418ddcSMehdi Amini                                 void *userData) {
71289418ddcSMehdi Amini   detail::CallbackOstream stream(callback, userData);
7135c90e1ffSJacques Pienaar   // As no desired version is set, no failure can occur.
7145c90e1ffSJacques Pienaar   (void)writeBytecodeToFile(unwrap(op), stream);
7150610e2f6SJacques Pienaar }
7160610e2f6SJacques Pienaar 
7175c90e1ffSJacques Pienaar MlirLogicalResult mlirOperationWriteBytecodeWithConfig(
7180610e2f6SJacques Pienaar     MlirOperation op, MlirBytecodeWriterConfig config,
7190610e2f6SJacques Pienaar     MlirStringCallback callback, void *userData) {
7200610e2f6SJacques Pienaar   detail::CallbackOstream stream(callback, userData);
7215c90e1ffSJacques Pienaar   return wrap(writeBytecodeToFile(unwrap(op), stream, *unwrap(config)));
72289418ddcSMehdi Amini }
72389418ddcSMehdi Amini 
72475f239e9SAlex Zinenko void mlirOperationDump(MlirOperation op) { return unwrap(op)->dump(); }
72575f239e9SAlex Zinenko 
7261c215949SMehdi Amini bool mlirOperationVerify(MlirOperation op) {
7271c215949SMehdi Amini   return succeeded(verify(unwrap(op)));
7281c215949SMehdi Amini }
7291c215949SMehdi Amini 
73024685aaeSAlex Zinenko void mlirOperationMoveAfter(MlirOperation op, MlirOperation other) {
73124685aaeSAlex Zinenko   return unwrap(op)->moveAfter(unwrap(other));
73224685aaeSAlex Zinenko }
73324685aaeSAlex Zinenko 
73424685aaeSAlex Zinenko void mlirOperationMoveBefore(MlirOperation op, MlirOperation other) {
73524685aaeSAlex Zinenko   return unwrap(op)->moveBefore(unwrap(other));
73624685aaeSAlex Zinenko }
73724685aaeSAlex Zinenko 
73847148832SHideto Ueno static mlir::WalkResult unwrap(MlirWalkResult result) {
73947148832SHideto Ueno   switch (result) {
74047148832SHideto Ueno   case MlirWalkResultAdvance:
74147148832SHideto Ueno     return mlir::WalkResult::advance();
74247148832SHideto Ueno 
74347148832SHideto Ueno   case MlirWalkResultInterrupt:
74447148832SHideto Ueno     return mlir::WalkResult::interrupt();
74547148832SHideto Ueno 
74647148832SHideto Ueno   case MlirWalkResultSkip:
74747148832SHideto Ueno     return mlir::WalkResult::skip();
74847148832SHideto Ueno   }
749d5746d73SFrank Schlimbach   llvm_unreachable("unknown result in WalkResult::unwrap");
75047148832SHideto Ueno }
75147148832SHideto Ueno 
752bdc3e6cbSMaksim Levental void mlirOperationWalk(MlirOperation op, MlirOperationWalkCallback callback,
753bdc3e6cbSMaksim Levental                        void *userData, MlirWalkOrder walkOrder) {
754bdc3e6cbSMaksim Levental   switch (walkOrder) {
755bdc3e6cbSMaksim Levental 
756bdc3e6cbSMaksim Levental   case MlirWalkPreOrder:
757bdc3e6cbSMaksim Levental     unwrap(op)->walk<mlir::WalkOrder::PreOrder>(
75847148832SHideto Ueno         [callback, userData](Operation *op) {
75947148832SHideto Ueno           return unwrap(callback(wrap(op), userData));
76047148832SHideto Ueno         });
761bdc3e6cbSMaksim Levental     break;
762bdc3e6cbSMaksim Levental   case MlirWalkPostOrder:
763bdc3e6cbSMaksim Levental     unwrap(op)->walk<mlir::WalkOrder::PostOrder>(
76447148832SHideto Ueno         [callback, userData](Operation *op) {
76547148832SHideto Ueno           return unwrap(callback(wrap(op), userData));
76647148832SHideto Ueno         });
767bdc3e6cbSMaksim Levental   }
768bdc3e6cbSMaksim Levental }
769bdc3e6cbSMaksim Levental 
770c7994bd9SMehdi Amini //===----------------------------------------------------------------------===//
771c7994bd9SMehdi Amini // Region API.
772c7994bd9SMehdi Amini //===----------------------------------------------------------------------===//
77375f239e9SAlex Zinenko 
77475f239e9SAlex Zinenko MlirRegion mlirRegionCreate() { return wrap(new Region); }
77575f239e9SAlex Zinenko 
7768e6c55c9SStella Laurenzo bool mlirRegionEqual(MlirRegion region, MlirRegion other) {
7778e6c55c9SStella Laurenzo   return unwrap(region) == unwrap(other);
7788e6c55c9SStella Laurenzo }
7798e6c55c9SStella Laurenzo 
78075f239e9SAlex Zinenko MlirBlock mlirRegionGetFirstBlock(MlirRegion region) {
78175f239e9SAlex Zinenko   Region *cppRegion = unwrap(region);
78275f239e9SAlex Zinenko   if (cppRegion->empty())
78375f239e9SAlex Zinenko     return wrap(static_cast<Block *>(nullptr));
78475f239e9SAlex Zinenko   return wrap(&cppRegion->front());
78575f239e9SAlex Zinenko }
78675f239e9SAlex Zinenko 
78775f239e9SAlex Zinenko void mlirRegionAppendOwnedBlock(MlirRegion region, MlirBlock block) {
78875f239e9SAlex Zinenko   unwrap(region)->push_back(unwrap(block));
78975f239e9SAlex Zinenko }
79075f239e9SAlex Zinenko 
791af838584SAlex Zinenko void mlirRegionInsertOwnedBlock(MlirRegion region, intptr_t pos,
79275f239e9SAlex Zinenko                                 MlirBlock block) {
79375f239e9SAlex Zinenko   auto &blockList = unwrap(region)->getBlocks();
79475f239e9SAlex Zinenko   blockList.insert(std::next(blockList.begin(), pos), unwrap(block));
79575f239e9SAlex Zinenko }
79675f239e9SAlex Zinenko 
797c538169eSAlex Zinenko void mlirRegionInsertOwnedBlockAfter(MlirRegion region, MlirBlock reference,
798c538169eSAlex Zinenko                                      MlirBlock block) {
799c538169eSAlex Zinenko   Region *cppRegion = unwrap(region);
800c538169eSAlex Zinenko   if (mlirBlockIsNull(reference)) {
801c538169eSAlex Zinenko     cppRegion->getBlocks().insert(cppRegion->begin(), unwrap(block));
802c538169eSAlex Zinenko     return;
803c538169eSAlex Zinenko   }
804c538169eSAlex Zinenko 
805c538169eSAlex Zinenko   assert(unwrap(reference)->getParent() == unwrap(region) &&
806c538169eSAlex Zinenko          "expected reference block to belong to the region");
807c538169eSAlex Zinenko   cppRegion->getBlocks().insertAfter(Region::iterator(unwrap(reference)),
808c538169eSAlex Zinenko                                      unwrap(block));
809c538169eSAlex Zinenko }
810c538169eSAlex Zinenko 
811c538169eSAlex Zinenko void mlirRegionInsertOwnedBlockBefore(MlirRegion region, MlirBlock reference,
812c538169eSAlex Zinenko                                       MlirBlock block) {
813c538169eSAlex Zinenko   if (mlirBlockIsNull(reference))
814c538169eSAlex Zinenko     return mlirRegionAppendOwnedBlock(region, block);
815c538169eSAlex Zinenko 
816c538169eSAlex Zinenko   assert(unwrap(reference)->getParent() == unwrap(region) &&
817c538169eSAlex Zinenko          "expected reference block to belong to the region");
818c538169eSAlex Zinenko   unwrap(region)->getBlocks().insert(Region::iterator(unwrap(reference)),
819c538169eSAlex Zinenko                                      unwrap(block));
820c538169eSAlex Zinenko }
821c538169eSAlex Zinenko 
82275f239e9SAlex Zinenko void mlirRegionDestroy(MlirRegion region) {
82375f239e9SAlex Zinenko   delete static_cast<Region *>(region.ptr);
82475f239e9SAlex Zinenko }
82575f239e9SAlex Zinenko 
82686bc2e3aSAdam Paszke void mlirRegionTakeBody(MlirRegion target, MlirRegion source) {
82786bc2e3aSAdam Paszke   unwrap(target)->takeBody(*unwrap(source));
82886bc2e3aSAdam Paszke }
82986bc2e3aSAdam Paszke 
830c7994bd9SMehdi Amini //===----------------------------------------------------------------------===//
831c7994bd9SMehdi Amini // Block API.
832c7994bd9SMehdi Amini //===----------------------------------------------------------------------===//
83375f239e9SAlex Zinenko 
834e084679fSRiver Riddle MlirBlock mlirBlockCreate(intptr_t nArgs, MlirType const *args,
835e084679fSRiver Riddle                           MlirLocation const *locs) {
83675f239e9SAlex Zinenko   Block *b = new Block;
837af838584SAlex Zinenko   for (intptr_t i = 0; i < nArgs; ++i)
838e084679fSRiver Riddle     b->addArgument(unwrap(args[i]), unwrap(locs[i]));
83975f239e9SAlex Zinenko   return wrap(b);
84075f239e9SAlex Zinenko }
84175f239e9SAlex Zinenko 
8428b6bea9bSGeorge bool mlirBlockEqual(MlirBlock block, MlirBlock other) {
84339613c2cSAlex Zinenko   return unwrap(block) == unwrap(other);
84439613c2cSAlex Zinenko }
84539613c2cSAlex Zinenko 
8468f130f10SGeorge MlirOperation mlirBlockGetParentOperation(MlirBlock block) {
8478f130f10SGeorge   return wrap(unwrap(block)->getParentOp());
8488f130f10SGeorge }
8498f130f10SGeorge 
8508e6c55c9SStella Laurenzo MlirRegion mlirBlockGetParentRegion(MlirBlock block) {
8518e6c55c9SStella Laurenzo   return wrap(unwrap(block)->getParent());
8528e6c55c9SStella Laurenzo }
8538e6c55c9SStella Laurenzo 
85475f239e9SAlex Zinenko MlirBlock mlirBlockGetNextInRegion(MlirBlock block) {
85575f239e9SAlex Zinenko   return wrap(unwrap(block)->getNextNode());
85675f239e9SAlex Zinenko }
85775f239e9SAlex Zinenko 
85875f239e9SAlex Zinenko MlirOperation mlirBlockGetFirstOperation(MlirBlock block) {
85975f239e9SAlex Zinenko   Block *cppBlock = unwrap(block);
86075f239e9SAlex Zinenko   if (cppBlock->empty())
86175f239e9SAlex Zinenko     return wrap(static_cast<Operation *>(nullptr));
86275f239e9SAlex Zinenko   return wrap(&cppBlock->front());
86375f239e9SAlex Zinenko }
86475f239e9SAlex Zinenko 
865c645ea5eSStella Laurenzo MlirOperation mlirBlockGetTerminator(MlirBlock block) {
866c645ea5eSStella Laurenzo   Block *cppBlock = unwrap(block);
867c645ea5eSStella Laurenzo   if (cppBlock->empty())
868c645ea5eSStella Laurenzo     return wrap(static_cast<Operation *>(nullptr));
869c645ea5eSStella Laurenzo   Operation &back = cppBlock->back();
870fe7c0d90SRiver Riddle   if (!back.hasTrait<OpTrait::IsTerminator>())
871c645ea5eSStella Laurenzo     return wrap(static_cast<Operation *>(nullptr));
872c645ea5eSStella Laurenzo   return wrap(&back);
873c645ea5eSStella Laurenzo }
874c645ea5eSStella Laurenzo 
87575f239e9SAlex Zinenko void mlirBlockAppendOwnedOperation(MlirBlock block, MlirOperation operation) {
87675f239e9SAlex Zinenko   unwrap(block)->push_back(unwrap(operation));
87775f239e9SAlex Zinenko }
87875f239e9SAlex Zinenko 
879af838584SAlex Zinenko void mlirBlockInsertOwnedOperation(MlirBlock block, intptr_t pos,
88075f239e9SAlex Zinenko                                    MlirOperation operation) {
88175f239e9SAlex Zinenko   auto &opList = unwrap(block)->getOperations();
88275f239e9SAlex Zinenko   opList.insert(std::next(opList.begin(), pos), unwrap(operation));
88375f239e9SAlex Zinenko }
88475f239e9SAlex Zinenko 
885c538169eSAlex Zinenko void mlirBlockInsertOwnedOperationAfter(MlirBlock block,
886c538169eSAlex Zinenko                                         MlirOperation reference,
887c538169eSAlex Zinenko                                         MlirOperation operation) {
888c538169eSAlex Zinenko   Block *cppBlock = unwrap(block);
889c538169eSAlex Zinenko   if (mlirOperationIsNull(reference)) {
890c538169eSAlex Zinenko     cppBlock->getOperations().insert(cppBlock->begin(), unwrap(operation));
891c538169eSAlex Zinenko     return;
892c538169eSAlex Zinenko   }
893c538169eSAlex Zinenko 
894c538169eSAlex Zinenko   assert(unwrap(reference)->getBlock() == unwrap(block) &&
895c538169eSAlex Zinenko          "expected reference operation to belong to the block");
896c538169eSAlex Zinenko   cppBlock->getOperations().insertAfter(Block::iterator(unwrap(reference)),
897c538169eSAlex Zinenko                                         unwrap(operation));
898c538169eSAlex Zinenko }
899c538169eSAlex Zinenko 
900c538169eSAlex Zinenko void mlirBlockInsertOwnedOperationBefore(MlirBlock block,
901c538169eSAlex Zinenko                                          MlirOperation reference,
902c538169eSAlex Zinenko                                          MlirOperation operation) {
903c538169eSAlex Zinenko   if (mlirOperationIsNull(reference))
904c538169eSAlex Zinenko     return mlirBlockAppendOwnedOperation(block, operation);
905c538169eSAlex Zinenko 
906c538169eSAlex Zinenko   assert(unwrap(reference)->getBlock() == unwrap(block) &&
907c538169eSAlex Zinenko          "expected reference operation to belong to the block");
908c538169eSAlex Zinenko   unwrap(block)->getOperations().insert(Block::iterator(unwrap(reference)),
909c538169eSAlex Zinenko                                         unwrap(operation));
910c538169eSAlex Zinenko }
911c538169eSAlex Zinenko 
91275f239e9SAlex Zinenko void mlirBlockDestroy(MlirBlock block) { delete unwrap(block); }
91375f239e9SAlex Zinenko 
9148d8738f6SJohn Demme void mlirBlockDetach(MlirBlock block) {
9158d8738f6SJohn Demme   Block *b = unwrap(block);
9168d8738f6SJohn Demme   b->getParent()->getBlocks().remove(b);
9178d8738f6SJohn Demme }
9188d8738f6SJohn Demme 
919af838584SAlex Zinenko intptr_t mlirBlockGetNumArguments(MlirBlock block) {
920af838584SAlex Zinenko   return static_cast<intptr_t>(unwrap(block)->getNumArguments());
92175f239e9SAlex Zinenko }
92275f239e9SAlex Zinenko 
923e084679fSRiver Riddle MlirValue mlirBlockAddArgument(MlirBlock block, MlirType type,
924e084679fSRiver Riddle                                MlirLocation loc) {
925e084679fSRiver Riddle   return wrap(unwrap(block)->addArgument(unwrap(type), unwrap(loc)));
9269db61142SGeorge }
9279db61142SGeorge 
92855d2fffdSSandeep Dasgupta void mlirBlockEraseArgument(MlirBlock block, unsigned index) {
92955d2fffdSSandeep Dasgupta   return unwrap(block)->eraseArgument(index);
93055d2fffdSSandeep Dasgupta }
93155d2fffdSSandeep Dasgupta 
93286bc2e3aSAdam Paszke MlirValue mlirBlockInsertArgument(MlirBlock block, intptr_t pos, MlirType type,
93386bc2e3aSAdam Paszke                                   MlirLocation loc) {
93486bc2e3aSAdam Paszke   return wrap(unwrap(block)->insertArgument(pos, unwrap(type), unwrap(loc)));
93586bc2e3aSAdam Paszke }
93686bc2e3aSAdam Paszke 
937af838584SAlex Zinenko MlirValue mlirBlockGetArgument(MlirBlock block, intptr_t pos) {
938af838584SAlex Zinenko   return wrap(unwrap(block)->getArgument(static_cast<unsigned>(pos)));
93975f239e9SAlex Zinenko }
94075f239e9SAlex Zinenko 
941da562974SAlex Zinenko void mlirBlockPrint(MlirBlock block, MlirStringCallback callback,
942321aa19eSAlex Zinenko                     void *userData) {
943b76f523bSzhanghb97   detail::CallbackOstream stream(callback, userData);
944321aa19eSAlex Zinenko   unwrap(block)->print(stream);
945321aa19eSAlex Zinenko }
946321aa19eSAlex Zinenko 
947c7994bd9SMehdi Amini //===----------------------------------------------------------------------===//
948c7994bd9SMehdi Amini // Value API.
949c7994bd9SMehdi Amini //===----------------------------------------------------------------------===//
95075f239e9SAlex Zinenko 
9518b6bea9bSGeorge bool mlirValueEqual(MlirValue value1, MlirValue value2) {
9526c7e6b2cSAlex Zinenko   return unwrap(value1) == unwrap(value2);
9536c7e6b2cSAlex Zinenko }
9546c7e6b2cSAlex Zinenko 
95562195b75SStella Laurenzo bool mlirValueIsABlockArgument(MlirValue value) {
956c1fa60b4STres Popp   return llvm::isa<BlockArgument>(unwrap(value));
95739613c2cSAlex Zinenko }
95839613c2cSAlex Zinenko 
95962195b75SStella Laurenzo bool mlirValueIsAOpResult(MlirValue value) {
960c1fa60b4STres Popp   return llvm::isa<OpResult>(unwrap(value));
96139613c2cSAlex Zinenko }
96239613c2cSAlex Zinenko 
96339613c2cSAlex Zinenko MlirBlock mlirBlockArgumentGetOwner(MlirValue value) {
964c1fa60b4STres Popp   return wrap(llvm::cast<BlockArgument>(unwrap(value)).getOwner());
96539613c2cSAlex Zinenko }
96639613c2cSAlex Zinenko 
96739613c2cSAlex Zinenko intptr_t mlirBlockArgumentGetArgNumber(MlirValue value) {
96839613c2cSAlex Zinenko   return static_cast<intptr_t>(
969c1fa60b4STres Popp       llvm::cast<BlockArgument>(unwrap(value)).getArgNumber());
97039613c2cSAlex Zinenko }
97139613c2cSAlex Zinenko 
97239613c2cSAlex Zinenko void mlirBlockArgumentSetType(MlirValue value, MlirType type) {
973c1fa60b4STres Popp   llvm::cast<BlockArgument>(unwrap(value)).setType(unwrap(type));
97439613c2cSAlex Zinenko }
97539613c2cSAlex Zinenko 
97639613c2cSAlex Zinenko MlirOperation mlirOpResultGetOwner(MlirValue value) {
977c1fa60b4STres Popp   return wrap(llvm::cast<OpResult>(unwrap(value)).getOwner());
97839613c2cSAlex Zinenko }
97939613c2cSAlex Zinenko 
98039613c2cSAlex Zinenko intptr_t mlirOpResultGetResultNumber(MlirValue value) {
98139613c2cSAlex Zinenko   return static_cast<intptr_t>(
982c1fa60b4STres Popp       llvm::cast<OpResult>(unwrap(value)).getResultNumber());
98339613c2cSAlex Zinenko }
98439613c2cSAlex Zinenko 
98575f239e9SAlex Zinenko MlirType mlirValueGetType(MlirValue value) {
98675f239e9SAlex Zinenko   return wrap(unwrap(value).getType());
98775f239e9SAlex Zinenko }
98875f239e9SAlex Zinenko 
98925b8433bSmax void mlirValueSetType(MlirValue value, MlirType type) {
99025b8433bSmax   unwrap(value).setType(unwrap(type));
99125b8433bSmax }
99225b8433bSmax 
993580915d6SAlex Zinenko void mlirValueDump(MlirValue value) { unwrap(value).dump(); }
994580915d6SAlex Zinenko 
995da562974SAlex Zinenko void mlirValuePrint(MlirValue value, MlirStringCallback callback,
996321aa19eSAlex Zinenko                     void *userData) {
997b76f523bSzhanghb97   detail::CallbackOstream stream(callback, userData);
998321aa19eSAlex Zinenko   unwrap(value).print(stream);
999321aa19eSAlex Zinenko }
1000321aa19eSAlex Zinenko 
100131ebe98eSJacques Pienaar void mlirValuePrintAsOperand(MlirValue value, MlirAsmState state,
100281233c70Smax                              MlirStringCallback callback, void *userData) {
100381233c70Smax   detail::CallbackOstream stream(callback, userData);
100481233c70Smax   Value cppValue = unwrap(value);
100531ebe98eSJacques Pienaar   cppValue.printAsOperand(stream, *unwrap(state));
100681233c70Smax }
100781233c70Smax 
1008dd8e4435SMike Urbach MlirOpOperand mlirValueGetFirstUse(MlirValue value) {
1009dd8e4435SMike Urbach   Value cppValue = unwrap(value);
1010dd8e4435SMike Urbach   if (cppValue.use_empty())
1011dd8e4435SMike Urbach     return {};
1012dd8e4435SMike Urbach 
1013dd8e4435SMike Urbach   OpOperand *opOperand = cppValue.use_begin().getOperand();
1014dd8e4435SMike Urbach 
1015dd8e4435SMike Urbach   return wrap(opOperand);
1016dd8e4435SMike Urbach }
1017dd8e4435SMike Urbach 
10185b303f21Smax void mlirValueReplaceAllUsesOfWith(MlirValue oldValue, MlirValue newValue) {
10195b303f21Smax   unwrap(oldValue).replaceAllUsesWith(unwrap(newValue));
10205b303f21Smax }
10215b303f21Smax 
102221df3251SPerry Gibson void mlirValueReplaceAllUsesExcept(MlirValue oldValue, MlirValue newValue,
102321df3251SPerry Gibson                                    intptr_t numExceptions,
102421df3251SPerry Gibson                                    MlirOperation *exceptions) {
102521df3251SPerry Gibson   Value oldValueCpp = unwrap(oldValue);
102621df3251SPerry Gibson   Value newValueCpp = unwrap(newValue);
102721df3251SPerry Gibson 
102821df3251SPerry Gibson   llvm::SmallPtrSet<mlir::Operation *, 4> exceptionSet;
102921df3251SPerry Gibson   for (intptr_t i = 0; i < numExceptions; ++i) {
103021df3251SPerry Gibson     exceptionSet.insert(unwrap(exceptions[i]));
103121df3251SPerry Gibson   }
103221df3251SPerry Gibson 
103321df3251SPerry Gibson   oldValueCpp.replaceAllUsesExcept(newValueCpp, exceptionSet);
103421df3251SPerry Gibson }
103521df3251SPerry Gibson 
1036dd8e4435SMike Urbach //===----------------------------------------------------------------------===//
1037dd8e4435SMike Urbach // OpOperand API.
1038dd8e4435SMike Urbach //===----------------------------------------------------------------------===//
1039dd8e4435SMike Urbach 
1040dd8e4435SMike Urbach bool mlirOpOperandIsNull(MlirOpOperand opOperand) { return !opOperand.ptr; }
1041dd8e4435SMike Urbach 
1042dd8e4435SMike Urbach MlirOperation mlirOpOperandGetOwner(MlirOpOperand opOperand) {
1043dd8e4435SMike Urbach   return wrap(unwrap(opOperand)->getOwner());
1044dd8e4435SMike Urbach }
1045dd8e4435SMike Urbach 
1046dc2ce600SShenghang Tsai MlirValue mlirOpOperandGetValue(MlirOpOperand opOperand) {
1047dc2ce600SShenghang Tsai   return wrap(unwrap(opOperand)->get());
1048dc2ce600SShenghang Tsai }
1049dc2ce600SShenghang Tsai 
1050dd8e4435SMike Urbach unsigned mlirOpOperandGetOperandNumber(MlirOpOperand opOperand) {
1051dd8e4435SMike Urbach   return unwrap(opOperand)->getOperandNumber();
1052dd8e4435SMike Urbach }
1053dd8e4435SMike Urbach 
1054dd8e4435SMike Urbach MlirOpOperand mlirOpOperandGetNextUse(MlirOpOperand opOperand) {
1055dd8e4435SMike Urbach   if (mlirOpOperandIsNull(opOperand))
1056dd8e4435SMike Urbach     return {};
1057dd8e4435SMike Urbach 
1058dd8e4435SMike Urbach   OpOperand *nextOpOperand = static_cast<OpOperand *>(
1059dd8e4435SMike Urbach       unwrap(opOperand)->getNextOperandUsingThisValue());
1060dd8e4435SMike Urbach 
1061dd8e4435SMike Urbach   if (!nextOpOperand)
1062dd8e4435SMike Urbach     return {};
1063dd8e4435SMike Urbach 
1064dd8e4435SMike Urbach   return wrap(nextOpOperand);
1065dd8e4435SMike Urbach }
1066dd8e4435SMike Urbach 
1067c7994bd9SMehdi Amini //===----------------------------------------------------------------------===//
1068c7994bd9SMehdi Amini // Type API.
1069c7994bd9SMehdi Amini //===----------------------------------------------------------------------===//
107075f239e9SAlex Zinenko 
1071df9ae599SGeorge MlirType mlirTypeParseGet(MlirContext context, MlirStringRef type) {
1072df9ae599SGeorge   return wrap(mlir::parseType(unwrap(type), unwrap(context)));
107375f239e9SAlex Zinenko }
107475f239e9SAlex Zinenko 
10752d1362e0SStella Laurenzo MlirContext mlirTypeGetContext(MlirType type) {
10762d1362e0SStella Laurenzo   return wrap(unwrap(type).getContext());
10772d1362e0SStella Laurenzo }
10782d1362e0SStella Laurenzo 
1079782a97a9SDaniel Resnick MlirTypeID mlirTypeGetTypeID(MlirType type) {
1080782a97a9SDaniel Resnick   return wrap(unwrap(type).getTypeID());
1081782a97a9SDaniel Resnick }
1082782a97a9SDaniel Resnick 
1083bfb1ba75Smax MlirDialect mlirTypeGetDialect(MlirType type) {
1084bfb1ba75Smax   return wrap(&unwrap(type).getDialect());
1085bfb1ba75Smax }
1086bfb1ba75Smax 
10878b6bea9bSGeorge bool mlirTypeEqual(MlirType t1, MlirType t2) {
10888b6bea9bSGeorge   return unwrap(t1) == unwrap(t2);
10898b6bea9bSGeorge }
109074f57784SAlex Zinenko 
1091da562974SAlex Zinenko void mlirTypePrint(MlirType type, MlirStringCallback callback, void *userData) {
1092b76f523bSzhanghb97   detail::CallbackOstream stream(callback, userData);
1093321aa19eSAlex Zinenko   unwrap(type).print(stream);
1094321aa19eSAlex Zinenko }
1095321aa19eSAlex Zinenko 
109675f239e9SAlex Zinenko void mlirTypeDump(MlirType type) { unwrap(type).dump(); }
109775f239e9SAlex Zinenko 
1098c7994bd9SMehdi Amini //===----------------------------------------------------------------------===//
1099c7994bd9SMehdi Amini // Attribute API.
1100c7994bd9SMehdi Amini //===----------------------------------------------------------------------===//
110175f239e9SAlex Zinenko 
1102df9ae599SGeorge MlirAttribute mlirAttributeParseGet(MlirContext context, MlirStringRef attr) {
1103df9ae599SGeorge   return wrap(mlir::parseAttribute(unwrap(attr), unwrap(context)));
110475f239e9SAlex Zinenko }
110575f239e9SAlex Zinenko 
110685185b61SStella Laurenzo MlirContext mlirAttributeGetContext(MlirAttribute attribute) {
110785185b61SStella Laurenzo   return wrap(unwrap(attribute).getContext());
110885185b61SStella Laurenzo }
110985185b61SStella Laurenzo 
11106771b98cSStella Laurenzo MlirType mlirAttributeGetType(MlirAttribute attribute) {
1111e1795322SJeff Niu   Attribute attr = unwrap(attribute);
1112c1fa60b4STres Popp   if (auto typedAttr = llvm::dyn_cast<TypedAttr>(attr))
1113e1795322SJeff Niu     return wrap(typedAttr.getType());
1114e1795322SJeff Niu   return wrap(NoneType::get(attr.getContext()));
11156771b98cSStella Laurenzo }
11166771b98cSStella Laurenzo 
1117782a97a9SDaniel Resnick MlirTypeID mlirAttributeGetTypeID(MlirAttribute attr) {
1118782a97a9SDaniel Resnick   return wrap(unwrap(attr).getTypeID());
1119782a97a9SDaniel Resnick }
1120782a97a9SDaniel Resnick 
11219566ee28Smax MlirDialect mlirAttributeGetDialect(MlirAttribute attr) {
11229566ee28Smax   return wrap(&unwrap(attr).getDialect());
11239566ee28Smax }
11249566ee28Smax 
11258b6bea9bSGeorge bool mlirAttributeEqual(MlirAttribute a1, MlirAttribute a2) {
1126da562974SAlex Zinenko   return unwrap(a1) == unwrap(a2);
1127da562974SAlex Zinenko }
1128da562974SAlex Zinenko 
1129da562974SAlex Zinenko void mlirAttributePrint(MlirAttribute attr, MlirStringCallback callback,
1130321aa19eSAlex Zinenko                         void *userData) {
1131b76f523bSzhanghb97   detail::CallbackOstream stream(callback, userData);
1132321aa19eSAlex Zinenko   unwrap(attr).print(stream);
1133321aa19eSAlex Zinenko }
1134321aa19eSAlex Zinenko 
113575f239e9SAlex Zinenko void mlirAttributeDump(MlirAttribute attr) { unwrap(attr).dump(); }
113675f239e9SAlex Zinenko 
1137aadcb26eSMehdi Amini MlirNamedAttribute mlirNamedAttributeGet(MlirIdentifier name,
1138df9ae599SGeorge                                          MlirAttribute attr) {
113975f239e9SAlex Zinenko   return MlirNamedAttribute{name, attr};
114075f239e9SAlex Zinenko }
1141b85f2f5cSStella Laurenzo 
1142c7994bd9SMehdi Amini //===----------------------------------------------------------------------===//
1143c7994bd9SMehdi Amini // Identifier API.
1144c7994bd9SMehdi Amini //===----------------------------------------------------------------------===//
1145b85f2f5cSStella Laurenzo 
1146b85f2f5cSStella Laurenzo MlirIdentifier mlirIdentifierGet(MlirContext context, MlirStringRef str) {
1147195730a6SRiver Riddle   return wrap(StringAttr::get(unwrap(context), unwrap(str)));
1148b85f2f5cSStella Laurenzo }
1149b85f2f5cSStella Laurenzo 
11506962bd68SGeorge MlirContext mlirIdentifierGetContext(MlirIdentifier ident) {
11516962bd68SGeorge   return wrap(unwrap(ident).getContext());
11526962bd68SGeorge }
11536962bd68SGeorge 
11548b6bea9bSGeorge bool mlirIdentifierEqual(MlirIdentifier ident, MlirIdentifier other) {
1155b85f2f5cSStella Laurenzo   return unwrap(ident) == unwrap(other);
1156b85f2f5cSStella Laurenzo }
1157b85f2f5cSStella Laurenzo 
1158b85f2f5cSStella Laurenzo MlirStringRef mlirIdentifierStr(MlirIdentifier ident) {
1159b85f2f5cSStella Laurenzo   return wrap(unwrap(ident).strref());
1160b85f2f5cSStella Laurenzo }
1161782a97a9SDaniel Resnick 
1162782a97a9SDaniel Resnick //===----------------------------------------------------------------------===//
116330d61893SAlex Zinenko // Symbol and SymbolTable API.
116430d61893SAlex Zinenko //===----------------------------------------------------------------------===//
116530d61893SAlex Zinenko 
116630d61893SAlex Zinenko MlirStringRef mlirSymbolTableGetSymbolAttributeName() {
116730d61893SAlex Zinenko   return wrap(SymbolTable::getSymbolAttrName());
116830d61893SAlex Zinenko }
116930d61893SAlex Zinenko 
1170bdc31837SStella Laurenzo MlirStringRef mlirSymbolTableGetVisibilityAttributeName() {
1171bdc31837SStella Laurenzo   return wrap(SymbolTable::getVisibilityAttrName());
1172bdc31837SStella Laurenzo }
1173bdc31837SStella Laurenzo 
117430d61893SAlex Zinenko MlirSymbolTable mlirSymbolTableCreate(MlirOperation operation) {
117530d61893SAlex Zinenko   if (!unwrap(operation)->hasTrait<OpTrait::SymbolTable>())
117630d61893SAlex Zinenko     return wrap(static_cast<SymbolTable *>(nullptr));
117730d61893SAlex Zinenko   return wrap(new SymbolTable(unwrap(operation)));
117830d61893SAlex Zinenko }
117930d61893SAlex Zinenko 
118030d61893SAlex Zinenko void mlirSymbolTableDestroy(MlirSymbolTable symbolTable) {
118130d61893SAlex Zinenko   delete unwrap(symbolTable);
118230d61893SAlex Zinenko }
118330d61893SAlex Zinenko 
118430d61893SAlex Zinenko MlirOperation mlirSymbolTableLookup(MlirSymbolTable symbolTable,
118530d61893SAlex Zinenko                                     MlirStringRef name) {
118630d61893SAlex Zinenko   return wrap(unwrap(symbolTable)->lookup(StringRef(name.data, name.length)));
118730d61893SAlex Zinenko }
118830d61893SAlex Zinenko 
118930d61893SAlex Zinenko MlirAttribute mlirSymbolTableInsert(MlirSymbolTable symbolTable,
119030d61893SAlex Zinenko                                     MlirOperation operation) {
1191120591e1SRiver Riddle   return wrap((Attribute)unwrap(symbolTable)->insert(unwrap(operation)));
119230d61893SAlex Zinenko }
119330d61893SAlex Zinenko 
119430d61893SAlex Zinenko void mlirSymbolTableErase(MlirSymbolTable symbolTable,
119530d61893SAlex Zinenko                           MlirOperation operation) {
119630d61893SAlex Zinenko   unwrap(symbolTable)->erase(unwrap(operation));
119730d61893SAlex Zinenko }
1198bdc31837SStella Laurenzo 
1199bdc31837SStella Laurenzo MlirLogicalResult mlirSymbolTableReplaceAllSymbolUses(MlirStringRef oldSymbol,
1200bdc31837SStella Laurenzo                                                       MlirStringRef newSymbol,
1201bdc31837SStella Laurenzo                                                       MlirOperation from) {
120202b6fb21SMehdi Amini   auto *cppFrom = unwrap(from);
1203bdc31837SStella Laurenzo   auto *context = cppFrom->getContext();
120456f62fbfSRiver Riddle   auto oldSymbolAttr = StringAttr::get(context, unwrap(oldSymbol));
120556f62fbfSRiver Riddle   auto newSymbolAttr = StringAttr::get(context, unwrap(newSymbol));
1206bdc31837SStella Laurenzo   return wrap(SymbolTable::replaceAllSymbolUses(oldSymbolAttr, newSymbolAttr,
1207bdc31837SStella Laurenzo                                                 unwrap(from)));
1208bdc31837SStella Laurenzo }
1209bdc31837SStella Laurenzo 
1210bdc31837SStella Laurenzo void mlirSymbolTableWalkSymbolTables(MlirOperation from, bool allSymUsesVisible,
1211bdc31837SStella Laurenzo                                      void (*callback)(MlirOperation, bool,
1212bdc31837SStella Laurenzo                                                       void *userData),
1213bdc31837SStella Laurenzo                                      void *userData) {
1214bdc31837SStella Laurenzo   SymbolTable::walkSymbolTables(unwrap(from), allSymUsesVisible,
1215bdc31837SStella Laurenzo                                 [&](Operation *foundOpCpp, bool isVisible) {
1216bdc31837SStella Laurenzo                                   callback(wrap(foundOpCpp), isVisible,
1217bdc31837SStella Laurenzo                                            userData);
1218bdc31837SStella Laurenzo                                 });
1219bdc31837SStella Laurenzo }
1220