MLIR  22.0.0git
IR.cpp
Go to the documentation of this file.
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-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "mlir-c/IR.h"
10 #include "mlir-c/Support.h"
11 
14 #include "mlir/CAPI/IR.h"
15 #include "mlir/CAPI/Support.h"
16 #include "mlir/CAPI/Utils.h"
17 #include "mlir/IR/Attributes.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"
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"
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 
39 using namespace mlir;
40 
41 //===----------------------------------------------------------------------===//
42 // Context API.
43 //===----------------------------------------------------------------------===//
44 
45 MlirContext mlirContextCreate() {
46  auto *context = new MLIRContext;
47  return wrap(context);
48 }
49 
50 static inline MLIRContext::Threading toThreadingEnum(bool threadingEnabled) {
51  return threadingEnabled ? MLIRContext::Threading::ENABLED
53 }
54 
55 MlirContext mlirContextCreateWithThreading(bool threadingEnabled) {
56  auto *context = new MLIRContext(toThreadingEnum(threadingEnabled));
57  return wrap(context);
58 }
59 
60 MlirContext mlirContextCreateWithRegistry(MlirDialectRegistry registry,
61  bool threadingEnabled) {
62  auto *context =
63  new MLIRContext(*unwrap(registry), toThreadingEnum(threadingEnabled));
64  return wrap(context);
65 }
66 
67 bool mlirContextEqual(MlirContext ctx1, MlirContext ctx2) {
68  return unwrap(ctx1) == unwrap(ctx2);
69 }
70 
71 void mlirContextDestroy(MlirContext context) { delete unwrap(context); }
72 
73 void mlirContextSetAllowUnregisteredDialects(MlirContext context, bool allow) {
74  unwrap(context)->allowUnregisteredDialects(allow);
75 }
76 
77 bool mlirContextGetAllowUnregisteredDialects(MlirContext context) {
78  return unwrap(context)->allowsUnregisteredDialects();
79 }
80 intptr_t mlirContextGetNumRegisteredDialects(MlirContext context) {
81  return static_cast<intptr_t>(unwrap(context)->getAvailableDialects().size());
82 }
83 
84 void 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 take
90 // its size.
91 intptr_t mlirContextGetNumLoadedDialects(MlirContext context) {
92  return static_cast<intptr_t>(unwrap(context)->getLoadedDialects().size());
93 }
94 
95 MlirDialect mlirContextGetOrLoadDialect(MlirContext context,
96  MlirStringRef name) {
97  return wrap(unwrap(context)->getOrLoadDialect(unwrap(name)));
98 }
99 
100 bool mlirContextIsRegisteredOperation(MlirContext context, MlirStringRef name) {
101  return unwrap(context)->isOperationRegistered(unwrap(name));
102 }
103 
104 void mlirContextEnableMultithreading(MlirContext context, bool enable) {
105  return unwrap(context)->enableMultithreading(enable);
106 }
107 
108 void mlirContextLoadAllAvailableDialects(MlirContext context) {
109  unwrap(context)->loadAllAvailableDialects();
110 }
111 
112 void mlirContextSetThreadPool(MlirContext context,
113  MlirLlvmThreadPool threadPool) {
114  unwrap(context)->setThreadPool(*unwrap(threadPool));
115 }
116 
117 unsigned mlirContextGetNumThreads(MlirContext context) {
118  return unwrap(context)->getNumThreads();
119 }
120 
121 MlirLlvmThreadPool mlirContextGetThreadPool(MlirContext context) {
122  return wrap(&unwrap(context)->getThreadPool());
123 }
124 
125 //===----------------------------------------------------------------------===//
126 // Dialect API.
127 //===----------------------------------------------------------------------===//
128 
129 MlirContext mlirDialectGetContext(MlirDialect dialect) {
130  return wrap(unwrap(dialect)->getContext());
131 }
132 
133 bool mlirDialectEqual(MlirDialect dialect1, MlirDialect dialect2) {
134  return unwrap(dialect1) == unwrap(dialect2);
135 }
136 
138  return wrap(unwrap(dialect)->getNamespace());
139 }
140 
141 //===----------------------------------------------------------------------===//
142 // DialectRegistry API.
143 //===----------------------------------------------------------------------===//
144 
145 MlirDialectRegistry mlirDialectRegistryCreate() {
146  return wrap(new DialectRegistry());
147 }
148 
149 void mlirDialectRegistryDestroy(MlirDialectRegistry registry) {
150  delete unwrap(registry);
151 }
152 
153 //===----------------------------------------------------------------------===//
154 // AsmState API.
155 //===----------------------------------------------------------------------===//
156 
157 MlirAsmState mlirAsmStateCreateForOperation(MlirOperation op,
158  MlirOpPrintingFlags flags) {
159  return wrap(new AsmState(unwrap(op), *unwrap(flags)));
160 }
161 
162 static Operation *findParent(Operation *op, bool shouldUseLocalScope) {
163  do {
164  // If we are printing local scope, stop at the first operation that is
165  // 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 
178 MlirAsmState 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.
196 void mlirAsmStateDestroy(MlirAsmState state) { delete unwrap(state); }
197 
198 //===----------------------------------------------------------------------===//
199 // Printing flags API.
200 //===----------------------------------------------------------------------===//
201 
202 MlirOpPrintingFlags mlirOpPrintingFlagsCreate() {
203  return wrap(new OpPrintingFlags());
204 }
205 
206 void mlirOpPrintingFlagsDestroy(MlirOpPrintingFlags flags) {
207  delete unwrap(flags);
208 }
209 
210 void mlirOpPrintingFlagsElideLargeElementsAttrs(MlirOpPrintingFlags flags,
211  intptr_t largeElementLimit) {
212  unwrap(flags)->elideLargeElementsAttrs(largeElementLimit);
213 }
214 
215 void mlirOpPrintingFlagsElideLargeResourceString(MlirOpPrintingFlags flags,
216  intptr_t largeResourceLimit) {
217  unwrap(flags)->elideLargeResourceString(largeResourceLimit);
218 }
219 
220 void mlirOpPrintingFlagsEnableDebugInfo(MlirOpPrintingFlags flags, bool enable,
221  bool prettyForm) {
222  unwrap(flags)->enableDebugInfo(enable, /*prettyForm=*/prettyForm);
223 }
224 
225 void mlirOpPrintingFlagsPrintGenericOpForm(MlirOpPrintingFlags flags) {
226  unwrap(flags)->printGenericOpForm();
227 }
228 
229 void mlirOpPrintingFlagsPrintNameLocAsPrefix(MlirOpPrintingFlags flags) {
230  unwrap(flags)->printNameLocAsPrefix();
231 }
232 
233 void mlirOpPrintingFlagsUseLocalScope(MlirOpPrintingFlags flags) {
234  unwrap(flags)->useLocalScope();
235 }
236 
237 void mlirOpPrintingFlagsAssumeVerified(MlirOpPrintingFlags flags) {
238  unwrap(flags)->assumeVerified();
239 }
240 
241 void mlirOpPrintingFlagsSkipRegions(MlirOpPrintingFlags flags) {
242  unwrap(flags)->skipRegions();
243 }
244 //===----------------------------------------------------------------------===//
245 // Bytecode printing flags API.
246 //===----------------------------------------------------------------------===//
247 
248 MlirBytecodeWriterConfig mlirBytecodeWriterConfigCreate() {
249  return wrap(new BytecodeWriterConfig());
250 }
251 
252 void mlirBytecodeWriterConfigDestroy(MlirBytecodeWriterConfig config) {
253  delete unwrap(config);
254 }
255 
256 void mlirBytecodeWriterConfigDesiredEmitVersion(MlirBytecodeWriterConfig flags,
257  int64_t version) {
258  unwrap(flags)->setDesiredBytecodeVersion(version);
259 }
260 
261 //===----------------------------------------------------------------------===//
262 // Location API.
263 //===----------------------------------------------------------------------===//
264 
265 MlirAttribute mlirLocationGetAttribute(MlirLocation location) {
266  return wrap(LocationAttr(unwrap(location)));
267 }
268 
269 MlirLocation mlirLocationFromAttribute(MlirAttribute attribute) {
270  return wrap(Location(llvm::dyn_cast<LocationAttr>(unwrap(attribute))));
271 }
272 
273 MlirLocation 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 
280 MlirLocation
281 mlirLocationFileLineColRangeGet(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 
289 MlirIdentifier mlirLocationFileLineColRangeGetFilename(MlirLocation location) {
290  return wrap(llvm::dyn_cast<FileLineColRange>(unwrap(location)).getFilename());
291 }
292 
293 int mlirLocationFileLineColRangeGetStartLine(MlirLocation location) {
294  if (auto loc = llvm::dyn_cast<FileLineColRange>(unwrap(location)))
295  return loc.getStartLine();
296  return -1;
297 }
298 
299 int mlirLocationFileLineColRangeGetStartColumn(MlirLocation location) {
300  if (auto loc = llvm::dyn_cast<FileLineColRange>(unwrap(location)))
301  return loc.getStartColumn();
302  return -1;
303 }
304 
305 int mlirLocationFileLineColRangeGetEndLine(MlirLocation location) {
306  if (auto loc = llvm::dyn_cast<FileLineColRange>(unwrap(location)))
307  return loc.getEndLine();
308  return -1;
309 }
310 
311 int mlirLocationFileLineColRangeGetEndColumn(MlirLocation location) {
312  if (auto loc = llvm::dyn_cast<FileLineColRange>(unwrap(location)))
313  return loc.getEndColumn();
314  return -1;
315 }
316 
318  return wrap(FileLineColRange::getTypeID());
319 }
320 
321 bool mlirLocationIsAFileLineColRange(MlirLocation location) {
322  return isa<FileLineColRange>(unwrap(location));
323 }
324 
325 MlirLocation mlirLocationCallSiteGet(MlirLocation callee, MlirLocation caller) {
326  return wrap(Location(CallSiteLoc::get(unwrap(callee), unwrap(caller))));
327 }
328 
329 MlirLocation mlirLocationCallSiteGetCallee(MlirLocation location) {
330  return wrap(
331  Location(llvm::dyn_cast<CallSiteLoc>(unwrap(location)).getCallee()));
332 }
333 
334 MlirLocation mlirLocationCallSiteGetCaller(MlirLocation location) {
335  return wrap(
336  Location(llvm::dyn_cast<CallSiteLoc>(unwrap(location)).getCaller()));
337 }
338 
340  return wrap(CallSiteLoc::getTypeID());
341 }
342 
343 bool mlirLocationIsACallSite(MlirLocation location) {
344  return isa<CallSiteLoc>(unwrap(location));
345 }
346 
347 MlirLocation mlirLocationFusedGet(MlirContext ctx, intptr_t nLocations,
348  MlirLocation const *locations,
349  MlirAttribute metadata) {
351  ArrayRef<Location> unwrappedLocs = unwrapList(nLocations, locations, locs);
352  return wrap(FusedLoc::get(unwrappedLocs, unwrap(metadata), unwrap(ctx)));
353 }
354 
355 unsigned mlirLocationFusedGetNumLocations(MlirLocation location) {
356  if (auto locationsArrRef = llvm::dyn_cast<FusedLoc>(unwrap(location)))
357  return locationsArrRef.getLocations().size();
358  return 0;
359 }
360 
361 void 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 
369 MlirAttribute mlirLocationFusedGetMetadata(MlirLocation location) {
370  return wrap(llvm::dyn_cast<FusedLoc>(unwrap(location)).getMetadata());
371 }
372 
373 MlirTypeID mlirLocationFusedGetTypeID() { return wrap(FusedLoc::getTypeID()); }
374 
375 bool mlirLocationIsAFused(MlirLocation location) {
376  return isa<FusedLoc>(unwrap(location));
377 }
378 
379 MlirLocation 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 
388 MlirIdentifier mlirLocationNameGetName(MlirLocation location) {
389  return wrap((llvm::dyn_cast<NameLoc>(unwrap(location)).getName()));
390 }
391 
392 MlirLocation mlirLocationNameGetChildLoc(MlirLocation location) {
393  return wrap(
394  Location(llvm::dyn_cast<NameLoc>(unwrap(location)).getChildLoc()));
395 }
396 
397 MlirTypeID mlirLocationNameGetTypeID() { return wrap(NameLoc::getTypeID()); }
398 
399 bool mlirLocationIsAName(MlirLocation location) {
400  return isa<NameLoc>(unwrap(location));
401 }
402 
403 MlirLocation mlirLocationUnknownGet(MlirContext context) {
404  return wrap(Location(UnknownLoc::get(unwrap(context))));
405 }
406 
407 bool mlirLocationEqual(MlirLocation l1, MlirLocation l2) {
408  return unwrap(l1) == unwrap(l2);
409 }
410 
411 MlirContext mlirLocationGetContext(MlirLocation location) {
412  return wrap(unwrap(location).getContext());
413 }
414 
415 void 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 
425 MlirModule mlirModuleCreateEmpty(MlirLocation location) {
426  return wrap(ModuleOp::create(unwrap(location)));
427 }
428 
429 MlirModule 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 
437 MlirModule 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 
446 MlirContext mlirModuleGetContext(MlirModule module) {
447  return wrap(unwrap(module).getContext());
448 }
449 
450 MlirBlock mlirModuleGetBody(MlirModule module) {
451  return wrap(unwrap(module).getBody());
452 }
453 
454 void mlirModuleDestroy(MlirModule module) {
455  // Transfer ownership to an OwningOpRef<ModuleOp> so that its destructor is
456  // called.
457  OwningOpRef<ModuleOp>(unwrap(module));
458 }
459 
460 MlirOperation mlirModuleGetOperation(MlirModule module) {
461  return wrap(unwrap(module).getOperation());
462 }
463 
464 MlirModule mlirModuleFromOperation(MlirOperation op) {
465  return wrap(dyn_cast<ModuleOp>(unwrap(op)));
466 }
467 
468 //===----------------------------------------------------------------------===//
469 // Operation state API.
470 //===----------------------------------------------------------------------===//
471 
473  MlirOperationState state;
474  state.name = name;
475  state.location = loc;
476  state.nResults = 0;
477  state.results = nullptr;
478  state.nOperands = 0;
479  state.operands = nullptr;
480  state.nRegions = 0;
481  state.regions = nullptr;
482  state.nSuccessors = 0;
483  state.successors = nullptr;
484  state.nAttributes = 0;
485  state.attributes = nullptr;
486  state.enableResultTypeInference = false;
487  return state;
488 }
489 
490 #define APPEND_ELEMS(type, sizeName, elemName) \
491  state->elemName = \
492  (type *)realloc(state->elemName, (state->sizeName + n) * sizeof(type)); \
493  memcpy(state->elemName + state->sizeName, elemName, n * sizeof(type)); \
494  state->sizeName += n;
495 
497  MlirType const *results) {
498  APPEND_ELEMS(MlirType, nResults, results);
499 }
500 
502  MlirValue const *operands) {
503  APPEND_ELEMS(MlirValue, nOperands, operands);
504 }
506  MlirRegion const *regions) {
507  APPEND_ELEMS(MlirRegion, nRegions, regions);
508 }
510  MlirBlock const *successors) {
511  APPEND_ELEMS(MlirBlock, nSuccessors, successors);
512 }
514  MlirNamedAttribute const *attributes) {
515  APPEND_ELEMS(MlirNamedAttribute, nAttributes, attributes);
516 }
517 
519  state->enableResultTypeInference = true;
520 }
521 
522 //===----------------------------------------------------------------------===//
523 // Operation API.
524 //===----------------------------------------------------------------------===//
525 
526 static LogicalResult inferOperationTypes(OperationState &state) {
527  MLIRContext *context = state.getContext();
528  std::optional<RegisteredOperationName> info = state.name.getRegisteredInfo();
529  if (!info) {
530  emitError(state.location)
531  << "type inference was requested for the operation " << state.name
532  << ", but the operation was not registered; ensure that the dialect "
533  "containing the operation is linked into MLIR and registered with "
534  "the context";
535  return failure();
536  }
537 
538  auto *inferInterface = info->getInterface<InferTypeOpInterface>();
539  if (!inferInterface) {
540  emitError(state.location)
541  << "type inference was requested for the operation " << state.name
542  << ", but the operation does not support type inference; result "
543  "types must be specified explicitly";
544  return failure();
545  }
546 
547  DictionaryAttr attributes = state.attributes.getDictionary(context);
548  OpaqueProperties properties = state.getRawProperties();
549 
550  if (!properties && info->getOpPropertyByteSize() > 0 && !attributes.empty()) {
551  auto prop = std::make_unique<char[]>(info->getOpPropertyByteSize());
552  properties = OpaqueProperties(prop.get());
553  if (properties) {
554  auto emitError = [&]() {
555  return mlir::emitError(state.location)
556  << " failed properties conversion while building "
557  << state.name.getStringRef() << " with `" << attributes << "`: ";
558  };
559  if (failed(info->setOpPropertiesFromAttribute(state.name, properties,
560  attributes, emitError)))
561  return failure();
562  }
563  if (succeeded(inferInterface->inferReturnTypes(
564  context, state.location, state.operands, attributes, properties,
565  state.regions, state.types))) {
566  return success();
567  }
568  // Diagnostic emitted by interface.
569  return failure();
570  }
571 
572  if (succeeded(inferInterface->inferReturnTypes(
573  context, state.location, state.operands, attributes, properties,
574  state.regions, state.types)))
575  return success();
576 
577  // Diagnostic emitted by interface.
578  return failure();
579 }
580 
582  assert(state);
583  OperationState cppState(unwrap(state->location), unwrap(state->name));
584  SmallVector<Type, 4> resultStorage;
585  SmallVector<Value, 8> operandStorage;
586  SmallVector<Block *, 2> successorStorage;
587  cppState.addTypes(unwrapList(state->nResults, state->results, resultStorage));
588  cppState.addOperands(
589  unwrapList(state->nOperands, state->operands, operandStorage));
590  cppState.addSuccessors(
591  unwrapList(state->nSuccessors, state->successors, successorStorage));
592 
593  cppState.attributes.reserve(state->nAttributes);
594  for (intptr_t i = 0; i < state->nAttributes; ++i)
595  cppState.addAttribute(unwrap(state->attributes[i].name),
596  unwrap(state->attributes[i].attribute));
597 
598  for (intptr_t i = 0; i < state->nRegions; ++i)
599  cppState.addRegion(std::unique_ptr<Region>(unwrap(state->regions[i])));
600 
601  free(state->results);
602  free(state->operands);
603  free(state->successors);
604  free(state->regions);
605  free(state->attributes);
606 
607  // Infer result types.
608  if (state->enableResultTypeInference) {
609  assert(cppState.types.empty() &&
610  "result type inference enabled and result types provided");
611  if (failed(inferOperationTypes(cppState)))
612  return {nullptr};
613  }
614 
615  return wrap(Operation::create(cppState));
616 }
617 
618 MlirOperation mlirOperationCreateParse(MlirContext context,
619  MlirStringRef sourceStr,
620  MlirStringRef sourceName) {
621 
622  return wrap(
623  parseSourceString(unwrap(sourceStr), unwrap(context), unwrap(sourceName))
624  .release());
625 }
626 
627 MlirOperation mlirOperationClone(MlirOperation op) {
628  return wrap(unwrap(op)->clone());
629 }
630 
631 void mlirOperationDestroy(MlirOperation op) { unwrap(op)->erase(); }
632 
633 void mlirOperationRemoveFromParent(MlirOperation op) { unwrap(op)->remove(); }
634 
635 bool mlirOperationEqual(MlirOperation op, MlirOperation other) {
636  return unwrap(op) == unwrap(other);
637 }
638 
639 MlirContext mlirOperationGetContext(MlirOperation op) {
640  return wrap(unwrap(op)->getContext());
641 }
642 
643 MlirLocation mlirOperationGetLocation(MlirOperation op) {
644  return wrap(unwrap(op)->getLoc());
645 }
646 
647 MlirTypeID mlirOperationGetTypeID(MlirOperation op) {
648  if (auto info = unwrap(op)->getRegisteredInfo())
649  return wrap(info->getTypeID());
650  return {nullptr};
651 }
652 
653 MlirIdentifier mlirOperationGetName(MlirOperation op) {
654  return wrap(unwrap(op)->getName().getIdentifier());
655 }
656 
657 MlirBlock mlirOperationGetBlock(MlirOperation op) {
658  return wrap(unwrap(op)->getBlock());
659 }
660 
661 MlirOperation mlirOperationGetParentOperation(MlirOperation op) {
662  return wrap(unwrap(op)->getParentOp());
663 }
664 
665 intptr_t mlirOperationGetNumRegions(MlirOperation op) {
666  return static_cast<intptr_t>(unwrap(op)->getNumRegions());
667 }
668 
669 MlirRegion mlirOperationGetRegion(MlirOperation op, intptr_t pos) {
670  return wrap(&unwrap(op)->getRegion(static_cast<unsigned>(pos)));
671 }
672 
673 MlirRegion mlirOperationGetFirstRegion(MlirOperation op) {
674  Operation *cppOp = unwrap(op);
675  if (cppOp->getNumRegions() == 0)
676  return wrap(static_cast<Region *>(nullptr));
677  return wrap(&cppOp->getRegion(0));
678 }
679 
680 MlirRegion mlirRegionGetNextInOperation(MlirRegion region) {
681  Region *cppRegion = unwrap(region);
682  Operation *parent = cppRegion->getParentOp();
683  intptr_t next = cppRegion->getRegionNumber() + 1;
684  if (parent->getNumRegions() > next)
685  return wrap(&parent->getRegion(next));
686  return wrap(static_cast<Region *>(nullptr));
687 }
688 
689 MlirOperation mlirOperationGetNextInBlock(MlirOperation op) {
690  return wrap(unwrap(op)->getNextNode());
691 }
692 
693 intptr_t mlirOperationGetNumOperands(MlirOperation op) {
694  return static_cast<intptr_t>(unwrap(op)->getNumOperands());
695 }
696 
697 MlirValue mlirOperationGetOperand(MlirOperation op, intptr_t pos) {
698  return wrap(unwrap(op)->getOperand(static_cast<unsigned>(pos)));
699 }
700 
701 void mlirOperationSetOperand(MlirOperation op, intptr_t pos,
702  MlirValue newValue) {
703  unwrap(op)->setOperand(static_cast<unsigned>(pos), unwrap(newValue));
704 }
705 
706 void mlirOperationSetOperands(MlirOperation op, intptr_t nOperands,
707  MlirValue const *operands) {
708  SmallVector<Value> ops;
709  unwrap(op)->setOperands(unwrapList(nOperands, operands, ops));
710 }
711 
712 intptr_t mlirOperationGetNumResults(MlirOperation op) {
713  return static_cast<intptr_t>(unwrap(op)->getNumResults());
714 }
715 
716 MlirValue mlirOperationGetResult(MlirOperation op, intptr_t pos) {
717  return wrap(unwrap(op)->getResult(static_cast<unsigned>(pos)));
718 }
719 
720 intptr_t mlirOperationGetNumSuccessors(MlirOperation op) {
721  return static_cast<intptr_t>(unwrap(op)->getNumSuccessors());
722 }
723 
724 MlirBlock mlirOperationGetSuccessor(MlirOperation op, intptr_t pos) {
725  return wrap(unwrap(op)->getSuccessor(static_cast<unsigned>(pos)));
726 }
727 
730  std::optional<Attribute> attr = unwrap(op)->getInherentAttr(unwrap(name));
731  return attr.has_value();
732 }
733 
734 MlirAttribute mlirOperationGetInherentAttributeByName(MlirOperation op,
735  MlirStringRef name) {
736  std::optional<Attribute> attr = unwrap(op)->getInherentAttr(unwrap(name));
737  if (attr.has_value())
738  return wrap(*attr);
739  return {};
740 }
741 
743  MlirStringRef name,
744  MlirAttribute attr) {
745  unwrap(op)->setInherentAttr(
746  StringAttr::get(unwrap(op)->getContext(), unwrap(name)), unwrap(attr));
747 }
748 
749 intptr_t mlirOperationGetNumDiscardableAttributes(MlirOperation op) {
750  return static_cast<intptr_t>(
751  llvm::range_size(unwrap(op)->getDiscardableAttrs()));
752 }
753 
755  intptr_t pos) {
756  NamedAttribute attr =
757  *std::next(unwrap(op)->getDiscardableAttrs().begin(), pos);
758  return MlirNamedAttribute{wrap(attr.getName()), wrap(attr.getValue())};
759 }
760 
761 MlirAttribute mlirOperationGetDiscardableAttributeByName(MlirOperation op,
762  MlirStringRef name) {
763  return wrap(unwrap(op)->getDiscardableAttr(unwrap(name)));
764 }
765 
767  MlirStringRef name,
768  MlirAttribute attr) {
769  unwrap(op)->setDiscardableAttr(unwrap(name), unwrap(attr));
770 }
771 
773  MlirStringRef name) {
774  return !!unwrap(op)->removeDiscardableAttr(unwrap(name));
775 }
776 
777 void mlirOperationSetSuccessor(MlirOperation op, intptr_t pos,
778  MlirBlock block) {
779  unwrap(op)->setSuccessor(unwrap(block), static_cast<unsigned>(pos));
780 }
781 
782 intptr_t mlirOperationGetNumAttributes(MlirOperation op) {
783  return static_cast<intptr_t>(unwrap(op)->getAttrs().size());
784 }
785 
786 MlirNamedAttribute mlirOperationGetAttribute(MlirOperation op, intptr_t pos) {
787  NamedAttribute attr = unwrap(op)->getAttrs()[pos];
788  return MlirNamedAttribute{wrap(attr.getName()), wrap(attr.getValue())};
789 }
790 
791 MlirAttribute mlirOperationGetAttributeByName(MlirOperation op,
792  MlirStringRef name) {
793  return wrap(unwrap(op)->getAttr(unwrap(name)));
794 }
795 
796 void mlirOperationSetAttributeByName(MlirOperation op, MlirStringRef name,
797  MlirAttribute attr) {
798  unwrap(op)->setAttr(unwrap(name), unwrap(attr));
799 }
800 
801 bool mlirOperationRemoveAttributeByName(MlirOperation op, MlirStringRef name) {
802  return !!unwrap(op)->removeAttr(unwrap(name));
803 }
804 
805 void mlirOperationPrint(MlirOperation op, MlirStringCallback callback,
806  void *userData) {
807  detail::CallbackOstream stream(callback, userData);
808  unwrap(op)->print(stream);
809 }
810 
811 void mlirOperationPrintWithFlags(MlirOperation op, MlirOpPrintingFlags flags,
812  MlirStringCallback callback, void *userData) {
813  detail::CallbackOstream stream(callback, userData);
814  unwrap(op)->print(stream, *unwrap(flags));
815 }
816 
817 void mlirOperationPrintWithState(MlirOperation op, MlirAsmState state,
818  MlirStringCallback callback, void *userData) {
819  detail::CallbackOstream stream(callback, userData);
820  if (state.ptr)
821  unwrap(op)->print(stream, *unwrap(state));
822  unwrap(op)->print(stream);
823 }
824 
825 void mlirOperationWriteBytecode(MlirOperation op, MlirStringCallback callback,
826  void *userData) {
827  detail::CallbackOstream stream(callback, userData);
828  // As no desired version is set, no failure can occur.
829  (void)writeBytecodeToFile(unwrap(op), stream);
830 }
831 
833  MlirOperation op, MlirBytecodeWriterConfig config,
834  MlirStringCallback callback, void *userData) {
835  detail::CallbackOstream stream(callback, userData);
836  return wrap(writeBytecodeToFile(unwrap(op), stream, *unwrap(config)));
837 }
838 
839 void mlirOperationDump(MlirOperation op) { return unwrap(op)->dump(); }
840 
841 bool mlirOperationVerify(MlirOperation op) {
842  return succeeded(verify(unwrap(op)));
843 }
844 
845 void mlirOperationMoveAfter(MlirOperation op, MlirOperation other) {
846  return unwrap(op)->moveAfter(unwrap(other));
847 }
848 
849 void mlirOperationMoveBefore(MlirOperation op, MlirOperation other) {
850  return unwrap(op)->moveBefore(unwrap(other));
851 }
852 
853 bool mlirOperationIsBeforeInBlock(MlirOperation op, MlirOperation other) {
854  return unwrap(op)->isBeforeInBlock(unwrap(other));
855 }
856 
858  switch (result) {
860  return mlir::WalkResult::advance();
861 
864 
865  case MlirWalkResultSkip:
866  return mlir::WalkResult::skip();
867  }
868  llvm_unreachable("unknown result in WalkResult::unwrap");
869 }
870 
871 void mlirOperationWalk(MlirOperation op, MlirOperationWalkCallback callback,
872  void *userData, MlirWalkOrder walkOrder) {
873  switch (walkOrder) {
874 
875  case MlirWalkPreOrder:
877  [callback, userData](Operation *op) {
878  return unwrap(callback(wrap(op), userData));
879  });
880  break;
881  case MlirWalkPostOrder:
883  [callback, userData](Operation *op) {
884  return unwrap(callback(wrap(op), userData));
885  });
886  }
887 }
888 
889 //===----------------------------------------------------------------------===//
890 // Region API.
891 //===----------------------------------------------------------------------===//
892 
893 MlirRegion mlirRegionCreate() { return wrap(new Region); }
894 
895 bool mlirRegionEqual(MlirRegion region, MlirRegion other) {
896  return unwrap(region) == unwrap(other);
897 }
898 
899 MlirBlock mlirRegionGetFirstBlock(MlirRegion region) {
900  Region *cppRegion = unwrap(region);
901  if (cppRegion->empty())
902  return wrap(static_cast<Block *>(nullptr));
903  return wrap(&cppRegion->front());
904 }
905 
906 void mlirRegionAppendOwnedBlock(MlirRegion region, MlirBlock block) {
907  unwrap(region)->push_back(unwrap(block));
908 }
909 
910 void mlirRegionInsertOwnedBlock(MlirRegion region, intptr_t pos,
911  MlirBlock block) {
912  auto &blockList = unwrap(region)->getBlocks();
913  blockList.insert(std::next(blockList.begin(), pos), unwrap(block));
914 }
915 
916 void mlirRegionInsertOwnedBlockAfter(MlirRegion region, MlirBlock reference,
917  MlirBlock block) {
918  Region *cppRegion = unwrap(region);
919  if (mlirBlockIsNull(reference)) {
920  cppRegion->getBlocks().insert(cppRegion->begin(), unwrap(block));
921  return;
922  }
923 
924  assert(unwrap(reference)->getParent() == unwrap(region) &&
925  "expected reference block to belong to the region");
926  cppRegion->getBlocks().insertAfter(Region::iterator(unwrap(reference)),
927  unwrap(block));
928 }
929 
930 void mlirRegionInsertOwnedBlockBefore(MlirRegion region, MlirBlock reference,
931  MlirBlock block) {
932  if (mlirBlockIsNull(reference))
933  return mlirRegionAppendOwnedBlock(region, block);
934 
935  assert(unwrap(reference)->getParent() == unwrap(region) &&
936  "expected reference block to belong to the region");
937  unwrap(region)->getBlocks().insert(Region::iterator(unwrap(reference)),
938  unwrap(block));
939 }
940 
941 void mlirRegionDestroy(MlirRegion region) {
942  delete static_cast<Region *>(region.ptr);
943 }
944 
945 void mlirRegionTakeBody(MlirRegion target, MlirRegion source) {
946  unwrap(target)->takeBody(*unwrap(source));
947 }
948 
949 //===----------------------------------------------------------------------===//
950 // Block API.
951 //===----------------------------------------------------------------------===//
952 
953 MlirBlock mlirBlockCreate(intptr_t nArgs, MlirType const *args,
954  MlirLocation const *locs) {
955  Block *b = new Block;
956  for (intptr_t i = 0; i < nArgs; ++i)
957  b->addArgument(unwrap(args[i]), unwrap(locs[i]));
958  return wrap(b);
959 }
960 
961 bool mlirBlockEqual(MlirBlock block, MlirBlock other) {
962  return unwrap(block) == unwrap(other);
963 }
964 
965 MlirOperation mlirBlockGetParentOperation(MlirBlock block) {
966  return wrap(unwrap(block)->getParentOp());
967 }
968 
969 MlirRegion mlirBlockGetParentRegion(MlirBlock block) {
970  return wrap(unwrap(block)->getParent());
971 }
972 
973 MlirBlock mlirBlockGetNextInRegion(MlirBlock block) {
974  return wrap(unwrap(block)->getNextNode());
975 }
976 
977 MlirOperation mlirBlockGetFirstOperation(MlirBlock block) {
978  Block *cppBlock = unwrap(block);
979  if (cppBlock->empty())
980  return wrap(static_cast<Operation *>(nullptr));
981  return wrap(&cppBlock->front());
982 }
983 
984 MlirOperation mlirBlockGetTerminator(MlirBlock block) {
985  Block *cppBlock = unwrap(block);
986  if (cppBlock->empty())
987  return wrap(static_cast<Operation *>(nullptr));
988  Operation &back = cppBlock->back();
989  if (!back.hasTrait<OpTrait::IsTerminator>())
990  return wrap(static_cast<Operation *>(nullptr));
991  return wrap(&back);
992 }
993 
994 void mlirBlockAppendOwnedOperation(MlirBlock block, MlirOperation operation) {
995  unwrap(block)->push_back(unwrap(operation));
996 }
997 
998 void mlirBlockInsertOwnedOperation(MlirBlock block, intptr_t pos,
999  MlirOperation operation) {
1000  auto &opList = unwrap(block)->getOperations();
1001  opList.insert(std::next(opList.begin(), pos), unwrap(operation));
1002 }
1003 
1005  MlirOperation reference,
1006  MlirOperation operation) {
1007  Block *cppBlock = unwrap(block);
1008  if (mlirOperationIsNull(reference)) {
1009  cppBlock->getOperations().insert(cppBlock->begin(), unwrap(operation));
1010  return;
1011  }
1012 
1013  assert(unwrap(reference)->getBlock() == unwrap(block) &&
1014  "expected reference operation to belong to the block");
1015  cppBlock->getOperations().insertAfter(Block::iterator(unwrap(reference)),
1016  unwrap(operation));
1017 }
1018 
1020  MlirOperation reference,
1021  MlirOperation operation) {
1022  if (mlirOperationIsNull(reference))
1023  return mlirBlockAppendOwnedOperation(block, operation);
1024 
1025  assert(unwrap(reference)->getBlock() == unwrap(block) &&
1026  "expected reference operation to belong to the block");
1027  unwrap(block)->getOperations().insert(Block::iterator(unwrap(reference)),
1028  unwrap(operation));
1029 }
1030 
1031 void mlirBlockDestroy(MlirBlock block) { delete unwrap(block); }
1032 
1033 void mlirBlockDetach(MlirBlock block) {
1034  Block *b = unwrap(block);
1035  b->getParent()->getBlocks().remove(b);
1036 }
1037 
1038 intptr_t mlirBlockGetNumArguments(MlirBlock block) {
1039  return static_cast<intptr_t>(unwrap(block)->getNumArguments());
1040 }
1041 
1042 MlirValue mlirBlockAddArgument(MlirBlock block, MlirType type,
1043  MlirLocation loc) {
1044  return wrap(unwrap(block)->addArgument(unwrap(type), unwrap(loc)));
1045 }
1046 
1047 void mlirBlockEraseArgument(MlirBlock block, unsigned index) {
1048  return unwrap(block)->eraseArgument(index);
1049 }
1050 
1051 MlirValue mlirBlockInsertArgument(MlirBlock block, intptr_t pos, MlirType type,
1052  MlirLocation loc) {
1053  return wrap(unwrap(block)->insertArgument(pos, unwrap(type), unwrap(loc)));
1054 }
1055 
1056 MlirValue mlirBlockGetArgument(MlirBlock block, intptr_t pos) {
1057  return wrap(unwrap(block)->getArgument(static_cast<unsigned>(pos)));
1058 }
1059 
1060 void mlirBlockPrint(MlirBlock block, MlirStringCallback callback,
1061  void *userData) {
1062  detail::CallbackOstream stream(callback, userData);
1063  unwrap(block)->print(stream);
1064 }
1065 
1066 intptr_t mlirBlockGetNumSuccessors(MlirBlock block) {
1067  return static_cast<intptr_t>(unwrap(block)->getNumSuccessors());
1068 }
1069 
1070 MlirBlock mlirBlockGetSuccessor(MlirBlock block, intptr_t pos) {
1071  return wrap(unwrap(block)->getSuccessor(static_cast<unsigned>(pos)));
1072 }
1073 
1074 intptr_t mlirBlockGetNumPredecessors(MlirBlock block) {
1075  Block *b = unwrap(block);
1076  return static_cast<intptr_t>(std::distance(b->pred_begin(), b->pred_end()));
1077 }
1078 
1079 MlirBlock mlirBlockGetPredecessor(MlirBlock block, intptr_t pos) {
1080  Block *b = unwrap(block);
1081  Block::pred_iterator it = b->pred_begin();
1082  std::advance(it, pos);
1083  return wrap(*it);
1084 }
1085 
1086 //===----------------------------------------------------------------------===//
1087 // Value API.
1088 //===----------------------------------------------------------------------===//
1089 
1090 bool mlirValueEqual(MlirValue value1, MlirValue value2) {
1091  return unwrap(value1) == unwrap(value2);
1092 }
1093 
1094 bool mlirValueIsABlockArgument(MlirValue value) {
1095  return llvm::isa<BlockArgument>(unwrap(value));
1096 }
1097 
1098 bool mlirValueIsAOpResult(MlirValue value) {
1099  return llvm::isa<OpResult>(unwrap(value));
1100 }
1101 
1102 MlirBlock mlirBlockArgumentGetOwner(MlirValue value) {
1103  return wrap(llvm::dyn_cast<BlockArgument>(unwrap(value)).getOwner());
1104 }
1105 
1106 intptr_t mlirBlockArgumentGetArgNumber(MlirValue value) {
1107  return static_cast<intptr_t>(
1108  llvm::dyn_cast<BlockArgument>(unwrap(value)).getArgNumber());
1109 }
1110 
1111 void mlirBlockArgumentSetType(MlirValue value, MlirType type) {
1112  if (auto blockArg = llvm::dyn_cast<BlockArgument>(unwrap(value)))
1113  blockArg.setType(unwrap(type));
1114 }
1115 
1116 MlirOperation mlirOpResultGetOwner(MlirValue value) {
1117  return wrap(llvm::dyn_cast<OpResult>(unwrap(value)).getOwner());
1118 }
1119 
1120 intptr_t mlirOpResultGetResultNumber(MlirValue value) {
1121  return static_cast<intptr_t>(
1122  llvm::dyn_cast<OpResult>(unwrap(value)).getResultNumber());
1123 }
1124 
1125 MlirType mlirValueGetType(MlirValue value) {
1126  return wrap(unwrap(value).getType());
1127 }
1128 
1129 void mlirValueSetType(MlirValue value, MlirType type) {
1130  unwrap(value).setType(unwrap(type));
1131 }
1132 
1133 void mlirValueDump(MlirValue value) { unwrap(value).dump(); }
1134 
1135 void mlirValuePrint(MlirValue value, MlirStringCallback callback,
1136  void *userData) {
1137  detail::CallbackOstream stream(callback, userData);
1138  unwrap(value).print(stream);
1139 }
1140 
1141 void mlirValuePrintAsOperand(MlirValue value, MlirAsmState state,
1142  MlirStringCallback callback, void *userData) {
1143  detail::CallbackOstream stream(callback, userData);
1144  Value cppValue = unwrap(value);
1145  cppValue.printAsOperand(stream, *unwrap(state));
1146 }
1147 
1148 MlirOpOperand mlirValueGetFirstUse(MlirValue value) {
1149  Value cppValue = unwrap(value);
1150  if (cppValue.use_empty())
1151  return {};
1152 
1153  OpOperand *opOperand = cppValue.use_begin().getOperand();
1154 
1155  return wrap(opOperand);
1156 }
1157 
1158 void mlirValueReplaceAllUsesOfWith(MlirValue oldValue, MlirValue newValue) {
1159  unwrap(oldValue).replaceAllUsesWith(unwrap(newValue));
1160 }
1161 
1162 void mlirValueReplaceAllUsesExcept(MlirValue oldValue, MlirValue newValue,
1163  intptr_t numExceptions,
1164  MlirOperation *exceptions) {
1165  Value oldValueCpp = unwrap(oldValue);
1166  Value newValueCpp = unwrap(newValue);
1167 
1169  for (intptr_t i = 0; i < numExceptions; ++i) {
1170  exceptionSet.insert(unwrap(exceptions[i]));
1171  }
1172 
1173  oldValueCpp.replaceAllUsesExcept(newValueCpp, exceptionSet);
1174 }
1175 
1176 MlirLocation mlirValueGetLocation(MlirValue v) {
1177  return wrap(unwrap(v).getLoc());
1178 }
1179 
1180 MlirContext mlirValueGetContext(MlirValue v) {
1181  return wrap(unwrap(v).getContext());
1182 }
1183 
1184 //===----------------------------------------------------------------------===//
1185 // OpOperand API.
1186 //===----------------------------------------------------------------------===//
1187 
1188 bool mlirOpOperandIsNull(MlirOpOperand opOperand) { return !opOperand.ptr; }
1189 
1190 MlirOperation mlirOpOperandGetOwner(MlirOpOperand opOperand) {
1191  return wrap(unwrap(opOperand)->getOwner());
1192 }
1193 
1194 MlirValue mlirOpOperandGetValue(MlirOpOperand opOperand) {
1195  return wrap(unwrap(opOperand)->get());
1196 }
1197 
1198 unsigned mlirOpOperandGetOperandNumber(MlirOpOperand opOperand) {
1199  return unwrap(opOperand)->getOperandNumber();
1200 }
1201 
1202 MlirOpOperand mlirOpOperandGetNextUse(MlirOpOperand opOperand) {
1203  if (mlirOpOperandIsNull(opOperand))
1204  return {};
1205 
1206  OpOperand *nextOpOperand = static_cast<OpOperand *>(
1207  unwrap(opOperand)->getNextOperandUsingThisValue());
1208 
1209  if (!nextOpOperand)
1210  return {};
1211 
1212  return wrap(nextOpOperand);
1213 }
1214 
1215 //===----------------------------------------------------------------------===//
1216 // Type API.
1217 //===----------------------------------------------------------------------===//
1218 
1219 MlirType mlirTypeParseGet(MlirContext context, MlirStringRef type) {
1220  return wrap(mlir::parseType(unwrap(type), unwrap(context)));
1221 }
1222 
1223 MlirContext mlirTypeGetContext(MlirType type) {
1224  return wrap(unwrap(type).getContext());
1225 }
1226 
1227 MlirTypeID mlirTypeGetTypeID(MlirType type) {
1228  return wrap(unwrap(type).getTypeID());
1229 }
1230 
1231 MlirDialect mlirTypeGetDialect(MlirType type) {
1232  return wrap(&unwrap(type).getDialect());
1233 }
1234 
1235 bool mlirTypeEqual(MlirType t1, MlirType t2) {
1236  return unwrap(t1) == unwrap(t2);
1237 }
1238 
1239 void mlirTypePrint(MlirType type, MlirStringCallback callback, void *userData) {
1240  detail::CallbackOstream stream(callback, userData);
1241  unwrap(type).print(stream);
1242 }
1243 
1244 void mlirTypeDump(MlirType type) { unwrap(type).dump(); }
1245 
1246 //===----------------------------------------------------------------------===//
1247 // Attribute API.
1248 //===----------------------------------------------------------------------===//
1249 
1250 MlirAttribute mlirAttributeParseGet(MlirContext context, MlirStringRef attr) {
1251  return wrap(mlir::parseAttribute(unwrap(attr), unwrap(context)));
1252 }
1253 
1254 MlirContext mlirAttributeGetContext(MlirAttribute attribute) {
1255  return wrap(unwrap(attribute).getContext());
1256 }
1257 
1258 MlirType mlirAttributeGetType(MlirAttribute attribute) {
1259  Attribute attr = unwrap(attribute);
1260  if (auto typedAttr = llvm::dyn_cast<TypedAttr>(attr))
1261  return wrap(typedAttr.getType());
1262  return wrap(NoneType::get(attr.getContext()));
1263 }
1264 
1265 MlirTypeID mlirAttributeGetTypeID(MlirAttribute attr) {
1266  return wrap(unwrap(attr).getTypeID());
1267 }
1268 
1269 MlirDialect mlirAttributeGetDialect(MlirAttribute attr) {
1270  return wrap(&unwrap(attr).getDialect());
1271 }
1272 
1273 bool mlirAttributeEqual(MlirAttribute a1, MlirAttribute a2) {
1274  return unwrap(a1) == unwrap(a2);
1275 }
1276 
1277 void mlirAttributePrint(MlirAttribute attr, MlirStringCallback callback,
1278  void *userData) {
1279  detail::CallbackOstream stream(callback, userData);
1280  unwrap(attr).print(stream);
1281 }
1282 
1283 void mlirAttributeDump(MlirAttribute attr) { unwrap(attr).dump(); }
1284 
1286  MlirAttribute attr) {
1287  return MlirNamedAttribute{name, attr};
1288 }
1289 
1290 //===----------------------------------------------------------------------===//
1291 // Identifier API.
1292 //===----------------------------------------------------------------------===//
1293 
1294 MlirIdentifier mlirIdentifierGet(MlirContext context, MlirStringRef str) {
1295  return wrap(StringAttr::get(unwrap(context), unwrap(str)));
1296 }
1297 
1298 MlirContext mlirIdentifierGetContext(MlirIdentifier ident) {
1299  return wrap(unwrap(ident).getContext());
1300 }
1301 
1302 bool mlirIdentifierEqual(MlirIdentifier ident, MlirIdentifier other) {
1303  return unwrap(ident) == unwrap(other);
1304 }
1305 
1306 MlirStringRef mlirIdentifierStr(MlirIdentifier ident) {
1307  return wrap(unwrap(ident).strref());
1308 }
1309 
1310 //===----------------------------------------------------------------------===//
1311 // Symbol and SymbolTable API.
1312 //===----------------------------------------------------------------------===//
1313 
1316 }
1317 
1320 }
1321 
1322 MlirSymbolTable mlirSymbolTableCreate(MlirOperation operation) {
1323  if (!unwrap(operation)->hasTrait<OpTrait::SymbolTable>())
1324  return wrap(static_cast<SymbolTable *>(nullptr));
1325  return wrap(new SymbolTable(unwrap(operation)));
1326 }
1327 
1328 void mlirSymbolTableDestroy(MlirSymbolTable symbolTable) {
1329  delete unwrap(symbolTable);
1330 }
1331 
1332 MlirOperation mlirSymbolTableLookup(MlirSymbolTable symbolTable,
1333  MlirStringRef name) {
1334  return wrap(unwrap(symbolTable)->lookup(StringRef(name.data, name.length)));
1335 }
1336 
1337 MlirAttribute mlirSymbolTableInsert(MlirSymbolTable symbolTable,
1338  MlirOperation operation) {
1339  return wrap((Attribute)unwrap(symbolTable)->insert(unwrap(operation)));
1340 }
1341 
1342 void mlirSymbolTableErase(MlirSymbolTable symbolTable,
1343  MlirOperation operation) {
1344  unwrap(symbolTable)->erase(unwrap(operation));
1345 }
1346 
1348  MlirStringRef newSymbol,
1349  MlirOperation from) {
1350  auto *cppFrom = unwrap(from);
1351  auto *context = cppFrom->getContext();
1352  auto oldSymbolAttr = StringAttr::get(context, unwrap(oldSymbol));
1353  auto newSymbolAttr = StringAttr::get(context, unwrap(newSymbol));
1354  return wrap(SymbolTable::replaceAllSymbolUses(oldSymbolAttr, newSymbolAttr,
1355  unwrap(from)));
1356 }
1357 
1358 void mlirSymbolTableWalkSymbolTables(MlirOperation from, bool allSymUsesVisible,
1359  void (*callback)(MlirOperation, bool,
1360  void *userData),
1361  void *userData) {
1362  SymbolTable::walkSymbolTables(unwrap(from), allSymUsesVisible,
1363  [&](Operation *foundOpCpp, bool isVisible) {
1364  callback(wrap(foundOpCpp), isVisible,
1365  userData);
1366  });
1367 }
unsigned mlirOpOperandGetOperandNumber(MlirOpOperand opOperand)
Returns the operand number of an op operand.
Definition: IR.cpp:1198
MlirLocation mlirValueGetLocation(MlirValue v)
Gets the location of the value.
Definition: IR.cpp:1176
void mlirContextDestroy(MlirContext context)
Takes an MLIR context owned by the caller and destroys it.
Definition: IR.cpp:71
void mlirOperationDump(MlirOperation op)
Prints an operation to stderr.
Definition: IR.cpp:839
MlirAttribute mlirOperationGetDiscardableAttributeByName(MlirOperation op, MlirStringRef name)
Returns a discardable attribute attached to the operation given its name.
Definition: IR.cpp:761
MlirOperation mlirSymbolTableLookup(MlirSymbolTable symbolTable, MlirStringRef name)
Looks up a symbol with the given name in the given symbol table and returns the operation that corres...
Definition: IR.cpp:1332
MlirRegion mlirRegionCreate()
Creates a new empty region and transfers ownership to the caller.
Definition: IR.cpp:893
void mlirOperationPrint(MlirOperation op, MlirStringCallback callback, void *userData)
Prints an operation by sending chunks of the string representation and forwarding userData tocallback...
Definition: IR.cpp:805
MlirContext mlirModuleGetContext(MlirModule module)
Gets the context that a module was created with.
Definition: IR.cpp:446
void mlirValuePrint(MlirValue value, MlirStringCallback callback, void *userData)
Prints a value by sending chunks of the string representation and forwarding userData tocallback`.
Definition: IR.cpp:1135
MlirContext mlirLocationGetContext(MlirLocation location)
Gets the context that a location was created with.
Definition: IR.cpp:411
intptr_t mlirBlockGetNumPredecessors(MlirBlock block)
Returns the number of predecessor blocks of the block.
Definition: IR.cpp:1074
bool mlirLocationIsAName(MlirLocation location)
Checks whether the given location is an Name.
Definition: IR.cpp:399
MlirOperation mlirOpOperandGetOwner(MlirOpOperand opOperand)
Returns the owner operation of an op operand.
Definition: IR.cpp:1190
bool mlirDialectEqual(MlirDialect dialect1, MlirDialect dialect2)
Checks if two dialects that belong to the same context are equal.
Definition: IR.cpp:133
MlirRegion mlirRegionGetNextInOperation(MlirRegion region)
Returns the region immediately following the given region in its parent operation.
Definition: IR.cpp:680
MlirLogicalResult mlirOperationWriteBytecodeWithConfig(MlirOperation op, MlirBytecodeWriterConfig config, MlirStringCallback callback, void *userData)
Same as mlirOperationWriteBytecode but with writer config and returns failure only if desired bytecod...
Definition: IR.cpp:832
MlirIdentifier mlirOperationGetName(MlirOperation op)
Gets the name of the operation as an identifier.
Definition: IR.cpp:653
void mlirDialectRegistryDestroy(MlirDialectRegistry registry)
Takes a dialect registry owned by the caller and destroys it.
Definition: IR.cpp:149
bool mlirIdentifierEqual(MlirIdentifier ident, MlirIdentifier other)
Checks whether two identifiers are the same.
Definition: IR.cpp:1302
void mlirOperationPrintWithFlags(MlirOperation op, MlirOpPrintingFlags flags, MlirStringCallback callback, void *userData)
Same as mlirOperationPrint but accepts flags controlling the printing behavior.
Definition: IR.cpp:811
bool mlirValueIsABlockArgument(MlirValue value)
Returns 1 if the value is a block argument, 0 otherwise.
Definition: IR.cpp:1094
MlirTypeID mlirTypeGetTypeID(MlirType type)
Gets the type ID of the type.
Definition: IR.cpp:1227
void mlirValueReplaceAllUsesOfWith(MlirValue oldValue, MlirValue newValue)
Replace all uses of 'of' value with the 'with' value, updating anything in the IR that uses 'of' to u...
Definition: IR.cpp:1158
MlirValue mlirBlockAddArgument(MlirBlock block, MlirType type, MlirLocation loc)
Appends an argument of the specified type to the block.
Definition: IR.cpp:1042
intptr_t mlirOperationGetNumRegions(MlirOperation op)
Returns the number of regions attached to the given operation.
Definition: IR.cpp:665
MlirBlock mlirOperationGetBlock(MlirOperation op)
Gets the block that owns this operation, returning null if the operation is not owned.
Definition: IR.cpp:657
void mlirContextAppendDialectRegistry(MlirContext ctx, MlirDialectRegistry registry)
Append the contents of the given dialect registry to the registry associated with the context.
Definition: IR.cpp:84
MlirIdentifier mlirIdentifierGet(MlirContext context, MlirStringRef str)
Gets an identifier with the given string value.
Definition: IR.cpp:1294
void mlirBlockArgumentSetType(MlirValue value, MlirType type)
Sets the type of the block argument to the given type.
Definition: IR.cpp:1111
MlirLocation mlirLocationFileLineColGet(MlirContext context, MlirStringRef filename, unsigned line, unsigned col)
Creates an File/Line/Column location owned by the given context.
Definition: IR.cpp:273
intptr_t mlirContextGetNumLoadedDialects(MlirContext context)
Returns the number of dialects loaded by the context.
Definition: IR.cpp:91
MlirNamedAttribute mlirNamedAttributeGet(MlirIdentifier name, MlirAttribute attr)
Associates an attribute with the name. Takes ownership of neither.
Definition: IR.cpp:1285
MlirStringRef mlirSymbolTableGetVisibilityAttributeName()
Returns the name of the attribute used to store symbol visibility.
Definition: IR.cpp:1318
void mlirOperationStateAddAttributes(MlirOperationState *state, intptr_t n, MlirNamedAttribute const *attributes)
Definition: IR.cpp:513
MlirValue mlirOperationGetResult(MlirOperation op, intptr_t pos)
Returns pos-th result of the operation.
Definition: IR.cpp:716
bool mlirLocationIsACallSite(MlirLocation location)
Checks whether the given location is an CallSite.
Definition: IR.cpp:343
void mlirSymbolTableWalkSymbolTables(MlirOperation from, bool allSymUsesVisible, void(*callback)(MlirOperation, bool, void *userData), void *userData)
Walks all symbol table operations nested within, and including, op.
Definition: IR.cpp:1358
void mlirContextLoadAllAvailableDialects(MlirContext context)
Eagerly loads all available dialects registered with a context, making them available for use for IR ...
Definition: IR.cpp:108
MlirModule mlirModuleCreateParseFromFile(MlirContext context, MlirStringRef fileName)
Parses a module from file and transfers ownership to the caller.
Definition: IR.cpp:437
void mlirAttributePrint(MlirAttribute attr, MlirStringCallback callback, void *userData)
Prints an attribute by sending chunks of the string representation and forwarding userData tocallback...
Definition: IR.cpp:1277
MlirBlock mlirRegionGetFirstBlock(MlirRegion region)
Gets the first block in the region.
Definition: IR.cpp:899
MlirLogicalResult mlirSymbolTableReplaceAllSymbolUses(MlirStringRef oldSymbol, MlirStringRef newSymbol, MlirOperation from)
Attempt to replace all uses that are nested within the given operation of the given symbol 'oldSymbol...
Definition: IR.cpp:1347
MlirLocation mlirLocationFusedGet(MlirContext ctx, intptr_t nLocations, MlirLocation const *locations, MlirAttribute metadata)
Creates a fused location with an array of locations and metadata.
Definition: IR.cpp:347
MlirAsmState mlirAsmStateCreateForValue(MlirValue value, MlirOpPrintingFlags flags)
Creates new AsmState from value.
Definition: IR.cpp:178
intptr_t mlirOperationGetNumResults(MlirOperation op)
Returns the number of results of the operation.
Definition: IR.cpp:712
MlirOpOperand mlirValueGetFirstUse(MlirValue value)
Returns an op operand representing the first use of the value, or a null op operand if there are no u...
Definition: IR.cpp:1148
void mlirRegionInsertOwnedBlockAfter(MlirRegion region, MlirBlock reference, MlirBlock block)
Takes a block owned by the caller and inserts it after the (non-owned) reference block in the given r...
Definition: IR.cpp:916
void mlirOperationDestroy(MlirOperation op)
Takes an operation owned by the caller and destroys it.
Definition: IR.cpp:631
void mlirValueReplaceAllUsesExcept(MlirValue oldValue, MlirValue newValue, intptr_t numExceptions, MlirOperation *exceptions)
Replace all uses of 'of' value with 'with' value, updating anything in the IR that uses 'of' to use '...
Definition: IR.cpp:1162
void mlirBlockAppendOwnedOperation(MlirBlock block, MlirOperation operation)
Takes an operation owned by the caller and appends it to the block.
Definition: IR.cpp:994
MlirRegion mlirOperationGetFirstRegion(MlirOperation op)
Returns first region attached to the operation.
Definition: IR.cpp:673
MlirAttribute mlirOperationGetInherentAttributeByName(MlirOperation op, MlirStringRef name)
Returns an inherent attribute attached to the operation given its name.
Definition: IR.cpp:734
MlirDialect mlirContextGetOrLoadDialect(MlirContext context, MlirStringRef name)
Gets the dialect instance owned by the given context using the dialect namespace to identify it,...
Definition: IR.cpp:95
MlirContext mlirAttributeGetContext(MlirAttribute attribute)
Gets the context that an attribute was created with.
Definition: IR.cpp:1254
MlirStringRef mlirSymbolTableGetSymbolAttributeName()
Returns the name of the attribute used to store symbol names compatible with symbol tables.
Definition: IR.cpp:1314
void mlirBlockInsertOwnedOperation(MlirBlock block, intptr_t pos, MlirOperation operation)
Takes an operation owned by the caller and inserts it as pos to the block.
Definition: IR.cpp:998
MlirRegion mlirBlockGetParentRegion(MlirBlock block)
Returns the region that contains this block.
Definition: IR.cpp:969
MlirType mlirValueGetType(MlirValue value)
Returns the type of the value.
Definition: IR.cpp:1125
void mlirOperationMoveAfter(MlirOperation op, MlirOperation other)
Moves the given operation immediately after the other operation in its parent block.
Definition: IR.cpp:845
void mlirRegionAppendOwnedBlock(MlirRegion region, MlirBlock block)
Takes a block owned by the caller and appends it to the given region.
Definition: IR.cpp:906
void mlirBlockPrint(MlirBlock block, MlirStringCallback callback, void *userData)
Prints a block by sending chunks of the string representation and forwarding userData tocallback`.
Definition: IR.cpp:1060
void mlirOperationSetDiscardableAttributeByName(MlirOperation op, MlirStringRef name, MlirAttribute attr)
Sets a discardable attribute by name, replacing the existing if it exists or adding a new one otherwi...
Definition: IR.cpp:766
MlirOpPrintingFlags mlirOpPrintingFlagsCreate()
Creates new printing flags with defaults, intended for customization.
Definition: IR.cpp:202
void mlirOpPrintingFlagsElideLargeElementsAttrs(MlirOpPrintingFlags flags, intptr_t largeElementLimit)
Enables the elision of large elements attributes by printing a lexically valid but otherwise meaningl...
Definition: IR.cpp:210
MlirBlock mlirBlockGetNextInRegion(MlirBlock block)
Returns the block immediately following the given block in its parent region.
Definition: IR.cpp:973
void mlirOperationSetSuccessor(MlirOperation op, intptr_t pos, MlirBlock block)
Set pos-th successor of the operation.
Definition: IR.cpp:777
MlirValue mlirOpOperandGetValue(MlirOpOperand opOperand)
Returns the value of an op operand.
Definition: IR.cpp:1194
#define APPEND_ELEMS(type, sizeName, elemName)
Definition: IR.cpp:490
bool mlirContextIsRegisteredOperation(MlirContext context, MlirStringRef name)
Returns whether the given fully-qualified operation (i.e.
Definition: IR.cpp:100
MlirOperation mlirOperationGetNextInBlock(MlirOperation op)
Returns an operation immediately following the given operation it its enclosing block.
Definition: IR.cpp:689
void mlirOpPrintingFlagsEnableDebugInfo(MlirOpPrintingFlags flags, bool enable, bool prettyForm)
Enable or disable printing of debug information (based on enable).
Definition: IR.cpp:220
MlirOperation mlirModuleGetOperation(MlirModule module)
Views the module as a generic operation.
Definition: IR.cpp:460
static mlir::WalkResult unwrap(MlirWalkResult result)
Definition: IR.cpp:857
void mlirOpPrintingFlagsElideLargeResourceString(MlirOpPrintingFlags flags, intptr_t largeResourceLimit)
Enables the elision of large resources strings by omitting them from the dialect_resources section.
Definition: IR.cpp:215
void mlirRegionInsertOwnedBlockBefore(MlirRegion region, MlirBlock reference, MlirBlock block)
Takes a block owned by the caller and inserts it before the (non-owned) reference block in the given ...
Definition: IR.cpp:930
MlirValue mlirBlockGetArgument(MlirBlock block, intptr_t pos)
Returns pos-th argument of the block.
Definition: IR.cpp:1056
unsigned mlirLocationFusedGetNumLocations(MlirLocation location)
Getter for number of locations fused together.
Definition: IR.cpp:355
MlirStringRef mlirDialectGetNamespace(MlirDialect dialect)
Returns the namespace of the given dialect.
Definition: IR.cpp:137
void mlirOpPrintingFlagsUseLocalScope(MlirOpPrintingFlags flags)
Use local scope when printing the operation.
Definition: IR.cpp:233
MlirTypeID mlirOperationGetTypeID(MlirOperation op)
Gets the type id of the operation.
Definition: IR.cpp:647
intptr_t mlirBlockArgumentGetArgNumber(MlirValue value)
Returns the position of the value in the argument list of its block.
Definition: IR.cpp:1106
void mlirOperationWalk(MlirOperation op, MlirOperationWalkCallback callback, void *userData, MlirWalkOrder walkOrder)
Walks operation op in walkOrder and calls callback on that operation.
Definition: IR.cpp:871
MlirBlock mlirOperationGetSuccessor(MlirOperation op, intptr_t pos)
Returns pos-th successor of the operation.
Definition: IR.cpp:724
void mlirBlockInsertOwnedOperationBefore(MlirBlock block, MlirOperation reference, MlirOperation operation)
Takes an operation owned by the caller and inserts it before the (non-owned) reference operation in t...
Definition: IR.cpp:1019
bool mlirAttributeEqual(MlirAttribute a1, MlirAttribute a2)
Checks if two attributes are equal.
Definition: IR.cpp:1273
MlirAsmState mlirAsmStateCreateForOperation(MlirOperation op, MlirOpPrintingFlags flags)
Creates new AsmState, as with AsmState the IR should not be mutated in-between using this state.
Definition: IR.cpp:157
bool mlirOperationEqual(MlirOperation op, MlirOperation other)
Checks whether two operation handles point to the same operation.
Definition: IR.cpp:635
void mlirOperationSetInherentAttributeByName(MlirOperation op, MlirStringRef name, MlirAttribute attr)
Sets an inherent attribute by name, replacing the existing if it exists.
Definition: IR.cpp:742
void mlirOpPrintingFlagsAssumeVerified(MlirOpPrintingFlags flags)
Do not verify the operation when using custom operation printers.
Definition: IR.cpp:237
bool mlirValueEqual(MlirValue value1, MlirValue value2)
Returns 1 if two values are equal, 0 otherwise.
Definition: IR.cpp:1090
MlirContext mlirIdentifierGetContext(MlirIdentifier ident)
Returns the context associated with this identifier.
Definition: IR.cpp:1298
void mlirBytecodeWriterConfigDestroy(MlirBytecodeWriterConfig config)
Destroys printing flags created with mlirBytecodeWriterConfigCreate.
Definition: IR.cpp:252
MlirBlock mlirBlockGetSuccessor(MlirBlock block, intptr_t pos)
Returns pos-th successor of the block.
Definition: IR.cpp:1070
void mlirModuleDestroy(MlirModule module)
Takes a module owned by the caller and deletes it.
Definition: IR.cpp:454
MlirModule mlirModuleCreateEmpty(MlirLocation location)
Creates a new, empty module and transfers ownership to the caller.
Definition: IR.cpp:425
void mlirOpPrintingFlagsPrintGenericOpForm(MlirOpPrintingFlags flags)
Always print operations in the generic form.
Definition: IR.cpp:225
MlirOperation mlirOperationGetParentOperation(MlirOperation op)
Gets the operation that owns this operation, returning null if the operation is not owned.
Definition: IR.cpp:661
void mlirRegionTakeBody(MlirRegion target, MlirRegion source)
Moves the entire content of the source region to the target region.
Definition: IR.cpp:945
MlirLlvmThreadPool mlirContextGetThreadPool(MlirContext context)
Gets the thread pool of the context when enabled multithreading, otherwise an assertion is raised.
Definition: IR.cpp:121
MlirValue mlirBlockInsertArgument(MlirBlock block, intptr_t pos, MlirType type, MlirLocation loc)
Inserts an argument of the specified type at a specified index to the block.
Definition: IR.cpp:1051
void mlirValueSetType(MlirValue value, MlirType type)
Set the type of the value.
Definition: IR.cpp:1129
intptr_t mlirOperationGetNumSuccessors(MlirOperation op)
Returns the number of successor blocks of the operation.
Definition: IR.cpp:720
MlirDialect mlirAttributeGetDialect(MlirAttribute attr)
Gets the dialect of the attribute.
Definition: IR.cpp:1269
void mlirLocationPrint(MlirLocation location, MlirStringCallback callback, void *userData)
Prints a location by sending chunks of the string representation and forwarding userData tocallback`.
Definition: IR.cpp:415
void mlirOperationSetAttributeByName(MlirOperation op, MlirStringRef name, MlirAttribute attr)
Sets an attribute by name, replacing the existing if it exists or adding a new one otherwise.
Definition: IR.cpp:796
void mlirBlockDestroy(MlirBlock block)
Takes a block owned by the caller and destroys it.
Definition: IR.cpp:1031
void mlirRegionInsertOwnedBlock(MlirRegion region, intptr_t pos, MlirBlock block)
Takes a block owned by the caller and inserts it at pos to the given region.
Definition: IR.cpp:910
void mlirOperationSetOperand(MlirOperation op, intptr_t pos, MlirValue newValue)
Sets the pos-th operand of the operation.
Definition: IR.cpp:701
intptr_t mlirBlockGetNumArguments(MlirBlock block)
Returns the number of arguments of the block.
Definition: IR.cpp:1038
MlirTypeID mlirLocationFileLineColRangeGetTypeID()
TypeID Getter for FileLineColRange.
Definition: IR.cpp:317
MlirOperation mlirOpResultGetOwner(MlirValue value)
Returns an operation that produced this value as its result.
Definition: IR.cpp:1116
void mlirBlockEraseArgument(MlirBlock block, unsigned index)
Erase the argument at 'index' and remove it from the argument list.
Definition: IR.cpp:1047
bool mlirOpOperandIsNull(MlirOpOperand opOperand)
Returns whether the op operand is null.
Definition: IR.cpp:1188
MlirDialect mlirTypeGetDialect(MlirType type)
Gets the dialect a type belongs to.
Definition: IR.cpp:1231
MlirModule mlirModuleCreateParse(MlirContext context, MlirStringRef module)
Parses a module from the string and transfers ownership to the caller.
Definition: IR.cpp:429
MlirContext mlirContextCreateWithRegistry(MlirDialectRegistry registry, bool threadingEnabled)
Creates an MLIR context, setting the multithreading setting explicitly and pre-loading the dialects f...
Definition: IR.cpp:60
void mlirContextSetAllowUnregisteredDialects(MlirContext context, bool allow)
Sets whether unregistered dialects are allowed in this context.
Definition: IR.cpp:73
void mlirOperationStateAddResults(MlirOperationState *state, intptr_t n, MlirType const *results)
Adds a list of components to the operation state.
Definition: IR.cpp:496
void mlirOperationMoveBefore(MlirOperation op, MlirOperation other)
Moves the given operation immediately before the other operation in its parent block.
Definition: IR.cpp:849
static LogicalResult inferOperationTypes(OperationState &state)
Definition: IR.cpp:526
MlirOperation mlirOperationClone(MlirOperation op)
Creates a deep copy of an operation.
Definition: IR.cpp:627
void mlirValuePrintAsOperand(MlirValue value, MlirAsmState state, MlirStringCallback callback, void *userData)
Prints a value as an operand (i.e., the ValueID).
Definition: IR.cpp:1141
MlirBlock mlirBlockArgumentGetOwner(MlirValue value)
Returns the block in which this value is defined as an argument.
Definition: IR.cpp:1102
MlirDialectRegistry mlirDialectRegistryCreate()
Creates a dialect registry and transfers its ownership to the caller.
Definition: IR.cpp:145
MlirValue mlirOperationGetOperand(MlirOperation op, intptr_t pos)
Returns pos-th operand of the operation.
Definition: IR.cpp:697
bool mlirContextGetAllowUnregisteredDialects(MlirContext context)
Returns whether the context allows unregistered dialects.
Definition: IR.cpp:77
MlirAttribute mlirLocationGetAttribute(MlirLocation location)
Returns the underlying location attribute of this location.
Definition: IR.cpp:265
MlirModule mlirModuleFromOperation(MlirOperation op)
Views the generic operation as a module.
Definition: IR.cpp:464
MlirTypeID mlirLocationNameGetTypeID()
TypeID Getter for Name.
Definition: IR.cpp:397
MlirLocation mlirOperationGetLocation(MlirOperation op)
Gets the location of the operation.
Definition: IR.cpp:643
bool mlirTypeEqual(MlirType t1, MlirType t2)
Checks if two types are equal.
Definition: IR.cpp:1235
bool mlirContextEqual(MlirContext ctx1, MlirContext ctx2)
Checks if two contexts are equal.
Definition: IR.cpp:67
MlirAttribute mlirOperationGetAttributeByName(MlirOperation op, MlirStringRef name)
Returns an attribute attached to the operation given its name.
Definition: IR.cpp:791
bool mlirOperationIsBeforeInBlock(MlirOperation op, MlirOperation other)
Given an operation 'other' that is within the same parent block, return whether the current operation...
Definition: IR.cpp:853
MlirTypeID mlirAttributeGetTypeID(MlirAttribute attr)
Gets the type id of the attribute.
Definition: IR.cpp:1265
static Operation * findParent(Operation *op, bool shouldUseLocalScope)
Definition: IR.cpp:162
MlirAttribute mlirSymbolTableInsert(MlirSymbolTable symbolTable, MlirOperation operation)
Inserts the given operation into the given symbol table.
Definition: IR.cpp:1337
bool mlirLocationIsAFileLineColRange(MlirLocation location)
Checks whether the given location is an FileLineColRange.
Definition: IR.cpp:321
intptr_t mlirOperationGetNumDiscardableAttributes(MlirOperation op)
Returns the number of discardable attributes attached to the operation.
Definition: IR.cpp:749
MlirSymbolTable mlirSymbolTableCreate(MlirOperation operation)
Creates a symbol table for the given operation.
Definition: IR.cpp:1322
void mlirOperationStateAddOwnedRegions(MlirOperationState *state, intptr_t n, MlirRegion const *regions)
Definition: IR.cpp:505
MlirLocation mlirLocationUnknownGet(MlirContext context)
Creates a location with unknown position owned by the given context.
Definition: IR.cpp:403
MlirLocation mlirLocationCallSiteGetCallee(MlirLocation location)
Getter for callee of CallSite.
Definition: IR.cpp:329
MlirOperation mlirBlockGetFirstOperation(MlirBlock block)
Returns the first operation in the block.
Definition: IR.cpp:977
MlirType mlirAttributeGetType(MlirAttribute attribute)
Gets the type of this attribute.
Definition: IR.cpp:1258
bool mlirOperationRemoveDiscardableAttributeByName(MlirOperation op, MlirStringRef name)
Removes a discardable attribute by name.
Definition: IR.cpp:772
void mlirRegionDestroy(MlirRegion region)
Takes a region owned by the caller and destroys it.
Definition: IR.cpp:941
bool mlirOperationRemoveAttributeByName(MlirOperation op, MlirStringRef name)
Removes an attribute by name.
Definition: IR.cpp:801
bool mlirValueIsAOpResult(MlirValue value)
Returns 1 if the value is an operation result, 0 otherwise.
Definition: IR.cpp:1098
MLIR_CAPI_EXPORTED bool mlirOperationHasInherentAttributeByName(MlirOperation op, MlirStringRef name)
Returns true if this operation defines an inherent attribute with this name.
Definition: IR.cpp:729
MlirContext mlirContextCreateWithThreading(bool threadingEnabled)
Creates an MLIR context with an explicit setting of the multithreading setting and transfers its owne...
Definition: IR.cpp:55
MlirTypeID mlirLocationCallSiteGetTypeID()
TypeID Getter for CallSite.
Definition: IR.cpp:339
MlirBlock mlirBlockGetPredecessor(MlirBlock block, intptr_t pos)
Returns pos-th predecessor of the block.
Definition: IR.cpp:1079
MlirOperation mlirBlockGetTerminator(MlirBlock block)
Returns the terminator operation in the block or null if no terminator.
Definition: IR.cpp:984
bool mlirLocationEqual(MlirLocation l1, MlirLocation l2)
Checks if two locations are equal.
Definition: IR.cpp:407
MlirRegion mlirOperationGetRegion(MlirOperation op, intptr_t pos)
Returns pos-th region attached to the operation.
Definition: IR.cpp:669
int mlirLocationFileLineColRangeGetEndColumn(MlirLocation location)
Getter for end_column of FileLineColRange.
Definition: IR.cpp:311
MlirOperation mlirOperationCreate(MlirOperationState *state)
Creates an operation and transfers ownership to the caller.
Definition: IR.cpp:581
unsigned mlirContextGetNumThreads(MlirContext context)
Gets the number of threads of the thread pool of the context when multithreading is enabled.
Definition: IR.cpp:117
void mlirBytecodeWriterConfigDesiredEmitVersion(MlirBytecodeWriterConfig flags, int64_t version)
Sets the version to emit in the writer config.
Definition: IR.cpp:256
int mlirLocationFileLineColRangeGetStartColumn(MlirLocation location)
Getter for start_column of FileLineColRange.
Definition: IR.cpp:299
MlirAttribute mlirAttributeParseGet(MlirContext context, MlirStringRef attr)
Parses an attribute. The attribute is owned by the context.
Definition: IR.cpp:1250
void mlirLocationFusedGetLocations(MlirLocation location, MlirLocation *locationsCPtr)
Getter for locations of Fused.
Definition: IR.cpp:361
void mlirOperationRemoveFromParent(MlirOperation op)
Removes the given operation from its parent block.
Definition: IR.cpp:633
void mlirSymbolTableDestroy(MlirSymbolTable symbolTable)
Destroys the symbol table created with mlirSymbolTableCreate.
Definition: IR.cpp:1328
intptr_t mlirBlockGetNumSuccessors(MlirBlock block)
Returns the number of successor blocks of the block.
Definition: IR.cpp:1066
MlirContext mlirContextCreate()
Creates an MLIR context and transfers its ownership to the caller.
Definition: IR.cpp:45
void mlirOperationPrintWithState(MlirOperation op, MlirAsmState state, MlirStringCallback callback, void *userData)
Same as mlirOperationPrint but accepts AsmState controlling the printing behavior as well as caching ...
Definition: IR.cpp:817
bool mlirOperationVerify(MlirOperation op)
Verify the operation and return true if it passes, false if it fails.
Definition: IR.cpp:841
void mlirBlockDetach(MlirBlock block)
Detach a block from the owning region and assume ownership.
Definition: IR.cpp:1033
int mlirLocationFileLineColRangeGetEndLine(MlirLocation location)
Getter for end_line of FileLineColRange.
Definition: IR.cpp:305
MlirNamedAttribute mlirOperationGetAttribute(MlirOperation op, intptr_t pos)
Return pos-th attribute of the operation.
Definition: IR.cpp:786
void mlirOpPrintingFlagsDestroy(MlirOpPrintingFlags flags)
Destroys printing flags created with mlirOpPrintingFlagsCreate.
Definition: IR.cpp:206
MlirLocation mlirLocationCallSiteGet(MlirLocation callee, MlirLocation caller)
Creates a call site location with a callee and a caller.
Definition: IR.cpp:325
void mlirOperationWriteBytecode(MlirOperation op, MlirStringCallback callback, void *userData)
Same as mlirOperationPrint but writing the bytecode format.
Definition: IR.cpp:825
void mlirValueDump(MlirValue value)
Prints the value to the standard error stream.
Definition: IR.cpp:1133
void mlirBlockInsertOwnedOperationAfter(MlirBlock block, MlirOperation reference, MlirOperation operation)
Takes an operation owned by the caller and inserts it after the (non-owned) reference operation in th...
Definition: IR.cpp:1004
intptr_t mlirContextGetNumRegisteredDialects(MlirContext context)
Returns the number of dialects registered with the given context.
Definition: IR.cpp:80
MlirTypeID mlirLocationFusedGetTypeID()
TypeID Getter for Fused.
Definition: IR.cpp:373
void mlirOperationSetOperands(MlirOperation op, intptr_t nOperands, MlirValue const *operands)
Replaces the operands of the operation.
Definition: IR.cpp:706
static MLIRContext::Threading toThreadingEnum(bool threadingEnabled)
Definition: IR.cpp:50
MlirIdentifier mlirLocationFileLineColRangeGetFilename(MlirLocation location)
Getter for filename of FileLineColRange.
Definition: IR.cpp:289
MlirContext mlirTypeGetContext(MlirType type)
Gets the context that a type was created with.
Definition: IR.cpp:1223
void mlirTypePrint(MlirType type, MlirStringCallback callback, void *userData)
Prints a location by sending chunks of the string representation and forwarding userData tocallback`.
Definition: IR.cpp:1239
MlirBlock mlirModuleGetBody(MlirModule module)
Gets the body of the module, i.e. the only block it contains.
Definition: IR.cpp:450
MlirContext mlirDialectGetContext(MlirDialect dialect)
Returns the context that owns the dialect.
Definition: IR.cpp:129
bool mlirRegionEqual(MlirRegion region, MlirRegion other)
Checks whether two region handles point to the same region.
Definition: IR.cpp:895
int mlirLocationFileLineColRangeGetStartLine(MlirLocation location)
Getter for start_line of FileLineColRange.
Definition: IR.cpp:293
MlirOperation mlirOperationCreateParse(MlirContext context, MlirStringRef sourceStr, MlirStringRef sourceName)
Parses an operation, giving ownership to the caller.
Definition: IR.cpp:618
MlirLocation mlirLocationCallSiteGetCaller(MlirLocation location)
Getter for caller of CallSite.
Definition: IR.cpp:334
void mlirAsmStateDestroy(MlirAsmState state)
Destroys printing flags created with mlirAsmStateCreate.
Definition: IR.cpp:196
MlirContext mlirOperationGetContext(MlirOperation op)
Gets the context this operation is associated with.
Definition: IR.cpp:639
intptr_t mlirOpResultGetResultNumber(MlirValue value)
Returns the position of the value in the list of results of the operation that produced it.
Definition: IR.cpp:1120
MlirLocation mlirLocationNameGet(MlirContext context, MlirStringRef name, MlirLocation childLoc)
Creates a name location owned by the given context.
Definition: IR.cpp:379
MlirLocation mlirLocationFileLineColRangeGet(MlirContext context, MlirStringRef filename, unsigned startLine, unsigned startCol, unsigned endLine, unsigned endCol)
Creates an File/Line/Column range location owned by the given context.
Definition: IR.cpp:281
bool mlirBlockEqual(MlirBlock block, MlirBlock other)
Checks whether two blocks handles point to the same block.
Definition: IR.cpp:961
bool mlirLocationIsAFused(MlirLocation location)
Checks whether the given location is an Fused.
Definition: IR.cpp:375
MlirAttribute mlirLocationFusedGetMetadata(MlirLocation location)
Getter for metadata of Fused.
Definition: IR.cpp:369
void mlirSymbolTableErase(MlirSymbolTable symbolTable, MlirOperation operation)
Removes the given operation from the symbol table and erases it.
Definition: IR.cpp:1342
MlirLocation mlirLocationNameGetChildLoc(MlirLocation location)
Getter for childLoc of Name.
Definition: IR.cpp:392
MlirNamedAttribute mlirOperationGetDiscardableAttribute(MlirOperation op, intptr_t pos)
Return pos-th discardable attribute of the operation.
Definition: IR.cpp:754
void mlirOperationStateEnableResultTypeInference(MlirOperationState *state)
Enables result type inference for the operation under construction.
Definition: IR.cpp:518
void mlirOperationStateAddSuccessors(MlirOperationState *state, intptr_t n, MlirBlock const *successors)
Definition: IR.cpp:509
MlirBytecodeWriterConfig mlirBytecodeWriterConfigCreate()
Creates new printing flags with defaults, intended for customization.
Definition: IR.cpp:248
void mlirAttributeDump(MlirAttribute attr)
Prints the attribute to the standard error stream.
Definition: IR.cpp:1283
void mlirOpPrintingFlagsPrintNameLocAsPrefix(MlirOpPrintingFlags flags)
Print the name and location, if NamedLoc, as a prefix to the SSA ID.
Definition: IR.cpp:229
MlirIdentifier mlirLocationNameGetName(MlirLocation location)
Getter for name of Name.
Definition: IR.cpp:388
MlirStringRef mlirIdentifierStr(MlirIdentifier ident)
Gets the string value of the identifier.
Definition: IR.cpp:1306
void mlirOpPrintingFlagsSkipRegions(MlirOpPrintingFlags flags)
Skip printing regions.
Definition: IR.cpp:241
void mlirOperationStateAddOperands(MlirOperationState *state, intptr_t n, MlirValue const *operands)
Definition: IR.cpp:501
MlirOperationState mlirOperationStateGet(MlirStringRef name, MlirLocation loc)
Constructs an operation state from a name and a location.
Definition: IR.cpp:472
MlirLocation mlirLocationFromAttribute(MlirAttribute attribute)
Creates a location from a location attribute.
Definition: IR.cpp:269
MlirOperation mlirBlockGetParentOperation(MlirBlock block)
Returns the closest surrounding operation that contains this block.
Definition: IR.cpp:965
MlirOpOperand mlirOpOperandGetNextUse(MlirOpOperand opOperand)
Returns an op operand representing the next use of the value, or a null op operand if there is no nex...
Definition: IR.cpp:1202
intptr_t mlirOperationGetNumOperands(MlirOperation op)
Returns the number of operands of the operation.
Definition: IR.cpp:693
void mlirContextSetThreadPool(MlirContext context, MlirLlvmThreadPool threadPool)
Sets the thread pool of the context explicitly, enabling multithreading in the process.
Definition: IR.cpp:112
MlirType mlirTypeParseGet(MlirContext context, MlirStringRef type)
Parses a type. The type is owned by the context.
Definition: IR.cpp:1219
MlirBlock mlirBlockCreate(intptr_t nArgs, MlirType const *args, MlirLocation const *locs)
Creates a new empty block with the given argument types and transfers ownership to the caller.
Definition: IR.cpp:953
void mlirContextEnableMultithreading(MlirContext context, bool enable)
Set threading mode (must be set to false to mlir-print-ir-after-all).
Definition: IR.cpp:104
void mlirTypeDump(MlirType type)
Prints the type to the standard error stream.
Definition: IR.cpp:1244
intptr_t mlirOperationGetNumAttributes(MlirOperation op)
Returns the number of attributes attached to the operation.
Definition: IR.cpp:782
MlirContext mlirValueGetContext(MlirValue v)
Gets the context that a value was created with.
Definition: IR.cpp:1180
static MLIRContext * getContext(OpFoldResult val)
static llvm::ArrayRef< CppTy > unwrapList(size_t size, CTy *first, llvm::SmallVectorImpl< CppTy > &storage)
Definition: Wrap.h:40
This class provides management for the lifetime of the state used when printing the IR.
Definition: AsmState.h:542
Attributes are known-constant values of operations.
Definition: Attributes.h:25
MLIRContext * getContext() const
Return the context this attribute belongs to.
Definition: Attributes.cpp:37
Block represents an ordered list of Operations.
Definition: Block.h:33
OpListType::iterator iterator
Definition: Block.h:140
bool empty()
Definition: Block.h:148
Operation & back()
Definition: Block.h:152
Region * getParent() const
Provide a 'getParent' method for ilist_node_with_parent methods.
Definition: Block.cpp:27
pred_iterator pred_begin()
Definition: Block.h:233
BlockArgument addArgument(Type type, Location loc)
Add one value to the argument list.
Definition: Block.cpp:153
OpListType & getOperations()
Definition: Block.h:137
Operation & front()
Definition: Block.h:153
iterator begin()
Definition: Block.h:143
pred_iterator pred_end()
Definition: Block.h:236
This class contains the configuration used for the bytecode writer.
The DialectRegistry maps a dialect namespace to a constructor for the matching dialect.
static FileLineColLoc get(StringAttr filename, unsigned line, unsigned column)
Definition: Location.cpp:157
Location objects represent source locations information in MLIR.
Definition: Location.h:32
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition: Location.h:76
MLIRContext is the top-level object for a collection of MLIR operations.
Definition: MLIRContext.h:60
void reserve(size_type N)
NamedAttribute represents a combination of a name and an Attribute value.
Definition: Attributes.h:164
StringAttr getName() const
Return the name of the attribute.
Definition: Attributes.cpp:55
Attribute getValue() const
Return the value of the attribute.
Definition: Attributes.h:179
This class represents an operand of an operation.
Definition: Value.h:257
Set of flags used to control the behavior of the various IR print methods (e.g.
This class provides the API for ops that are known to be isolated from above.
This class provides the API for ops that are known to be terminators.
Definition: OpDefinition.h:773
Simple wrapper around a void* in order to express generically how to pass in op properties through AP...
Operation is the basic unit of execution within MLIR.
Definition: Operation.h:88
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Definition: Operation.h:749
unsigned getNumRegions()
Returns the number of regions held by this operation.
Definition: Operation.h:674
static Operation * create(Location location, OperationName name, TypeRange resultTypes, ValueRange operands, NamedAttrList &&attributes, OpaqueProperties properties, BlockRange successors, unsigned numRegions)
Create a new Operation with the specific fields.
Definition: Operation.cpp:66
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
Definition: Operation.h:234
Region & getRegion(unsigned index)
Returns the region held by this operation at position 'index'.
Definition: Operation.h:686
OpTy release()
Release the referenced op.
Definition: OwningOpRef.h:67
Implement a predecessor iterator for blocks.
Definition: BlockSupport.h:51
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition: Region.h:26
unsigned getRegionNumber()
Return the number of this region in the parent operation.
Definition: Region.cpp:62
Operation * getParentOp()
Return the parent operation this region is attached to.
Definition: Region.h:200
bool empty()
Definition: Region.h:60
iterator begin()
Definition: Region.h:55
BlockListType & getBlocks()
Definition: Region.h:45
Block & front()
Definition: Region.h:65
BlockListType::iterator iterator
Definition: Region.h:52
This class allows for representing and managing the symbol table used by operations with the 'SymbolT...
Definition: SymbolTable.h:24
static StringRef getSymbolAttrName()
Return the name of the attribute used for symbol names.
Definition: SymbolTable.h:76
static LogicalResult replaceAllSymbolUses(StringAttr oldSymbol, StringAttr newSymbol, Operation *from)
Attempt to replace all uses of the given symbol 'oldSymbol' with the provided symbol 'newSymbol' that...
static StringRef getVisibilityAttrName()
Return the name of the attribute used for symbol visibility.
Definition: SymbolTable.h:82
static void walkSymbolTables(Operation *op, bool allSymUsesVisible, function_ref< void(Operation *, bool)> callback)
Walks all symbol table operations nested within, and including, op.
OperandType * getOperand() const
Returns the current operands.
Definition: UseDefLists.h:314
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition: Value.h:96
bool use_empty() const
Returns true if this value has no uses.
Definition: Value.h:208
void replaceAllUsesExcept(Value newValue, const SmallPtrSetImpl< Operation * > &exceptions)
Replace all uses of 'this' value with 'newValue', updating anything in the IR that uses 'this' to use...
Definition: Value.cpp:71
void printAsOperand(raw_ostream &os, AsmState &state) const
Print this value as if it were an operand.
Location getLoc() const
Return the location of this value.
Definition: Value.cpp:24
use_iterator use_begin() const
Definition: Value.h:184
A utility result that is used to signal how to proceed with an ongoing walk:
Definition: WalkResult.h:29
static WalkResult skip()
Definition: WalkResult.h:48
static WalkResult advance()
Definition: WalkResult.h:47
static WalkResult interrupt()
Definition: WalkResult.h:46
A simple raw ostream subclass that forwards write_impl calls to the user-supplied callback together w...
Definition: Utils.h:30
MlirDiagnostic wrap(mlir::Diagnostic &diagnostic)
Definition: Diagnostics.h:24
MlirWalkResult(* MlirOperationWalkCallback)(MlirOperation, void *userData)
Operation walker type.
Definition: IR.h:838
MlirWalkOrder
Traversal order for operation walk.
Definition: IR.h:831
@ MlirWalkPreOrder
Definition: IR.h:832
@ MlirWalkPostOrder
Definition: IR.h:833
MlirWalkResult
Operation walk result.
Definition: IR.h:824
@ MlirWalkResultInterrupt
Definition: IR.h:826
@ MlirWalkResultSkip
Definition: IR.h:827
@ MlirWalkResultAdvance
Definition: IR.h:825
static bool mlirBlockIsNull(MlirBlock block)
Checks whether a block is null.
Definition: IR.h:920
static bool mlirLocationIsNull(MlirLocation location)
Checks if the location is null.
Definition: IR.h:370
static bool mlirOperationIsNull(MlirOperation op)
Checks whether the underlying operation is null.
Definition: IR.h:615
#define MLIR_CAPI_EXPORTED
Definition: Support.h:46
void(* MlirStringCallback)(MlirStringRef, void *)
A callback for returning string references.
Definition: Support.h:105
constexpr void enumerate(std::tuple< Tys... > &tuple, CallbackT &&callback)
Definition: Matchers.h:344
Include the generated interface declarations.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition: Utils.cpp:304
const FrozenRewritePatternSet GreedyRewriteConfig config
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
Attribute parseAttribute(llvm::StringRef attrStr, MLIRContext *context, Type type={}, size_t *numRead=nullptr, bool isKnownNullTerminated=false)
This parses a single MLIR attribute to an MLIR context if it was valid.
LogicalResult parseSourceString(llvm::StringRef sourceStr, Block *block, const ParserConfig &config, StringRef sourceName="", LocationAttr *sourceFileLoc=nullptr)
This parses the IR string and appends parsed operations to the given block.
Definition: Parser.cpp:108
Operation * clone(OpBuilder &b, Operation *op, TypeRange newResultTypes, ValueRange newOperands)
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
Type parseType(llvm::StringRef typeStr, MLIRContext *context, size_t *numRead=nullptr, bool isKnownNullTerminated=false)
This parses a single MLIR type to an MLIR context if it was valid.
LogicalResult writeBytecodeToFile(Operation *op, raw_ostream &os, const BytecodeWriterConfig &config={})
Write the bytecode for the given operation to the provided output stream.
LogicalResult verify(Operation *op, bool verifyRecursively=true)
Perform (potentially expensive) checks of invariants, used to detect compiler bugs,...
Definition: Verifier.cpp:423
A logical result value, essentially a boolean with named states.
Definition: Support.h:116
Named MLIR attribute.
Definition: IR.h:76
An auxiliary class for constructing operations.
Definition: IR.h:432
A pointer to a sized fragment of a string, not necessarily null-terminated.
Definition: Support.h:73
const char * data
Pointer to the first symbol.
Definition: Support.h:74
size_t length
Length of the fragment.
Definition: Support.h:75
This represents an operation in an abstracted form, suitable for use with the builder APIs.
void addOperands(ValueRange newOperands)
void addAttribute(StringRef name, Attribute attr)
Add an attribute with the specified name.
void addSuccessors(Block *successor)
Adds a successor to the operation sate. successor must not be null.
void addTypes(ArrayRef< Type > newTypes)
NamedAttrList attributes
SmallVector< Type, 4 > types
Types of the results of this operation.
Region * addRegion()
Create a region that should be attached to the operation.