xref: /llvm-project/mlir/test/CAPI/ir.c (revision a77250fd782530f42a90f8562bcef0eb26abb010)
1c7994bd9SMehdi Amini //===- ir.c - Simple test of C APIs ---------------------------------------===//
2c7994bd9SMehdi Amini //
3c7994bd9SMehdi Amini // Part of the LLVM Project, under the Apache License v2.0 with LLVM
4c7994bd9SMehdi Amini // Exceptions.
5c7994bd9SMehdi Amini // See https://llvm.org/LICENSE.txt for license information.
6c7994bd9SMehdi Amini // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7c7994bd9SMehdi Amini //
8c7994bd9SMehdi Amini //===----------------------------------------------------------------------===//
975f239e9SAlex Zinenko 
1075f239e9SAlex Zinenko /* RUN: mlir-capi-ir-test 2>&1 | FileCheck %s
1175f239e9SAlex Zinenko  */
1275f239e9SAlex Zinenko 
1374a58ec9SStella Laurenzo #include "mlir-c/IR.h"
14448f25c8Szhanghb97 #include "mlir-c/AffineExpr.h"
1576753a59SStella Laurenzo #include "mlir-c/AffineMap.h"
16c7cae0e4SRiver Riddle #include "mlir-c/BuiltinAttributes.h"
1709f7a55fSRiver Riddle #include "mlir-c/BuiltinTypes.h"
187b5dfb40SAlex Zinenko #include "mlir-c/Diagnostics.h"
1923aa5a74SRiver Riddle #include "mlir-c/Dialect/Func.h"
20f5c7c031SAlex Zinenko #include "mlir-c/IntegerSet.h"
215e83a5b4SStella Laurenzo #include "mlir-c/RegisterEverything.h"
22f7bf8a86SJacques Pienaar #include "mlir-c/Support.h"
2375f239e9SAlex Zinenko 
2475f239e9SAlex Zinenko #include <assert.h>
2509b5ebc0SMarkus Böck #include <inttypes.h>
26da562974SAlex Zinenko #include <math.h>
2775f239e9SAlex Zinenko #include <stdio.h>
2875f239e9SAlex Zinenko #include <stdlib.h>
29da562974SAlex Zinenko #include <string.h>
3075f239e9SAlex Zinenko 
315e83a5b4SStella Laurenzo static void registerAllUpstreamDialects(MlirContext ctx) {
325e83a5b4SStella Laurenzo   MlirDialectRegistry registry = mlirDialectRegistryCreate();
335e83a5b4SStella Laurenzo   mlirRegisterAllDialects(registry);
345e83a5b4SStella Laurenzo   mlirContextAppendDialectRegistry(ctx, registry);
355e83a5b4SStella Laurenzo   mlirDialectRegistryDestroy(registry);
365e83a5b4SStella Laurenzo }
375e83a5b4SStella Laurenzo 
38f66cd9e9SStella Laurenzo struct ResourceDeleteUserData {
39f66cd9e9SStella Laurenzo   const char *name;
40f66cd9e9SStella Laurenzo };
41f66cd9e9SStella Laurenzo static struct ResourceDeleteUserData resourceI64BlobUserData = {
42f66cd9e9SStella Laurenzo     "resource_i64_blob"};
43f66cd9e9SStella Laurenzo static void reportResourceDelete(void *userData, const void *data, size_t size,
44f66cd9e9SStella Laurenzo                                  size_t align) {
45f66cd9e9SStella Laurenzo   fprintf(stderr, "reportResourceDelete: %s\n",
46f66cd9e9SStella Laurenzo           ((struct ResourceDeleteUserData *)userData)->name);
47f66cd9e9SStella Laurenzo }
48f66cd9e9SStella Laurenzo 
4975f239e9SAlex Zinenko void populateLoopBody(MlirContext ctx, MlirBlock loopBody,
5075f239e9SAlex Zinenko                       MlirLocation location, MlirBlock funcBody) {
5175f239e9SAlex Zinenko   MlirValue iv = mlirBlockGetArgument(loopBody, 0);
5275f239e9SAlex Zinenko   MlirValue funcArg0 = mlirBlockGetArgument(funcBody, 0);
5375f239e9SAlex Zinenko   MlirValue funcArg1 = mlirBlockGetArgument(funcBody, 1);
54df9ae599SGeorge   MlirType f32Type =
55df9ae599SGeorge       mlirTypeParseGet(ctx, mlirStringRefCreateFromCString("f32"));
5675f239e9SAlex Zinenko 
57df9ae599SGeorge   MlirOperationState loadLHSState = mlirOperationStateGet(
58e2310704SJulian Gross       mlirStringRefCreateFromCString("memref.load"), location);
5975f239e9SAlex Zinenko   MlirValue loadLHSOperands[] = {funcArg0, iv};
6075f239e9SAlex Zinenko   mlirOperationStateAddOperands(&loadLHSState, 2, loadLHSOperands);
6175f239e9SAlex Zinenko   mlirOperationStateAddResults(&loadLHSState, 1, &f32Type);
6275f239e9SAlex Zinenko   MlirOperation loadLHS = mlirOperationCreate(&loadLHSState);
6375f239e9SAlex Zinenko   mlirBlockAppendOwnedOperation(loopBody, loadLHS);
6475f239e9SAlex Zinenko 
65df9ae599SGeorge   MlirOperationState loadRHSState = mlirOperationStateGet(
66e2310704SJulian Gross       mlirStringRefCreateFromCString("memref.load"), location);
6775f239e9SAlex Zinenko   MlirValue loadRHSOperands[] = {funcArg1, iv};
6875f239e9SAlex Zinenko   mlirOperationStateAddOperands(&loadRHSState, 2, loadRHSOperands);
6975f239e9SAlex Zinenko   mlirOperationStateAddResults(&loadRHSState, 1, &f32Type);
7075f239e9SAlex Zinenko   MlirOperation loadRHS = mlirOperationCreate(&loadRHSState);
7175f239e9SAlex Zinenko   mlirBlockAppendOwnedOperation(loopBody, loadRHS);
7275f239e9SAlex Zinenko 
73df9ae599SGeorge   MlirOperationState addState = mlirOperationStateGet(
74a54f4eaeSMogball       mlirStringRefCreateFromCString("arith.addf"), location);
7575f239e9SAlex Zinenko   MlirValue addOperands[] = {mlirOperationGetResult(loadLHS, 0),
7675f239e9SAlex Zinenko                              mlirOperationGetResult(loadRHS, 0)};
7775f239e9SAlex Zinenko   mlirOperationStateAddOperands(&addState, 2, addOperands);
7875f239e9SAlex Zinenko   mlirOperationStateAddResults(&addState, 1, &f32Type);
7975f239e9SAlex Zinenko   MlirOperation add = mlirOperationCreate(&addState);
8075f239e9SAlex Zinenko   mlirBlockAppendOwnedOperation(loopBody, add);
8175f239e9SAlex Zinenko 
82df9ae599SGeorge   MlirOperationState storeState = mlirOperationStateGet(
83e2310704SJulian Gross       mlirStringRefCreateFromCString("memref.store"), location);
8475f239e9SAlex Zinenko   MlirValue storeOperands[] = {mlirOperationGetResult(add, 0), funcArg0, iv};
8575f239e9SAlex Zinenko   mlirOperationStateAddOperands(&storeState, 3, storeOperands);
8675f239e9SAlex Zinenko   MlirOperation store = mlirOperationCreate(&storeState);
8775f239e9SAlex Zinenko   mlirBlockAppendOwnedOperation(loopBody, store);
8875f239e9SAlex Zinenko 
89df9ae599SGeorge   MlirOperationState yieldState = mlirOperationStateGet(
90df9ae599SGeorge       mlirStringRefCreateFromCString("scf.yield"), location);
9175f239e9SAlex Zinenko   MlirOperation yield = mlirOperationCreate(&yieldState);
9275f239e9SAlex Zinenko   mlirBlockAppendOwnedOperation(loopBody, yield);
9375f239e9SAlex Zinenko }
9475f239e9SAlex Zinenko 
95b715fa33SAlex Zinenko MlirModule makeAndDumpAdd(MlirContext ctx, MlirLocation location) {
9675f239e9SAlex Zinenko   MlirModule moduleOp = mlirModuleCreateEmpty(location);
9772023442SMehdi Amini   MlirBlock moduleBody = mlirModuleGetBody(moduleOp);
9875f239e9SAlex Zinenko 
99df9ae599SGeorge   MlirType memrefType =
100df9ae599SGeorge       mlirTypeParseGet(ctx, mlirStringRefCreateFromCString("memref<?xf32>"));
10175f239e9SAlex Zinenko   MlirType funcBodyArgTypes[] = {memrefType, memrefType};
102e084679fSRiver Riddle   MlirLocation funcBodyArgLocs[] = {location, location};
10375f239e9SAlex Zinenko   MlirRegion funcBodyRegion = mlirRegionCreate();
104e084679fSRiver Riddle   MlirBlock funcBody =
105e084679fSRiver Riddle       mlirBlockCreate(sizeof(funcBodyArgTypes) / sizeof(MlirType),
106e084679fSRiver Riddle                       funcBodyArgTypes, funcBodyArgLocs);
10775f239e9SAlex Zinenko   mlirRegionAppendOwnedBlock(funcBodyRegion, funcBody);
10875f239e9SAlex Zinenko 
109df9ae599SGeorge   MlirAttribute funcTypeAttr = mlirAttributeParseGet(
110df9ae599SGeorge       ctx,
111df9ae599SGeorge       mlirStringRefCreateFromCString("(memref<?xf32>, memref<?xf32>) -> ()"));
112df9ae599SGeorge   MlirAttribute funcNameAttr =
113df9ae599SGeorge       mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("\"add\""));
11475f239e9SAlex Zinenko   MlirNamedAttribute funcAttrs[] = {
115aadcb26eSMehdi Amini       mlirNamedAttributeGet(
1164a3460a7SRiver Riddle           mlirIdentifierGet(ctx,
1174a3460a7SRiver Riddle                             mlirStringRefCreateFromCString("function_type")),
118df9ae599SGeorge           funcTypeAttr),
119aadcb26eSMehdi Amini       mlirNamedAttributeGet(
120aadcb26eSMehdi Amini           mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("sym_name")),
121df9ae599SGeorge           funcNameAttr)};
122f8479d9dSRiver Riddle   MlirOperationState funcState = mlirOperationStateGet(
12336550692SRiver Riddle       mlirStringRefCreateFromCString("func.func"), location);
12475f239e9SAlex Zinenko   mlirOperationStateAddAttributes(&funcState, 2, funcAttrs);
12575f239e9SAlex Zinenko   mlirOperationStateAddOwnedRegions(&funcState, 1, &funcBodyRegion);
12675f239e9SAlex Zinenko   MlirOperation func = mlirOperationCreate(&funcState);
12775f239e9SAlex Zinenko   mlirBlockInsertOwnedOperation(moduleBody, 0, func);
12875f239e9SAlex Zinenko 
129fd527cefSmax   MlirType indexType =
130fd527cefSmax       mlirTypeParseGet(ctx, mlirStringRefCreateFromCString("index"));
131fd527cefSmax   MlirAttribute indexZeroLiteral =
132fd527cefSmax       mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("0 : index"));
133fd527cefSmax   MlirNamedAttribute indexZeroValueAttr = mlirNamedAttributeGet(
134fd527cefSmax       mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("value")),
135fd527cefSmax       indexZeroLiteral);
136fd527cefSmax   MlirOperationState constZeroState = mlirOperationStateGet(
137fd527cefSmax       mlirStringRefCreateFromCString("arith.constant"), location);
138fd527cefSmax   mlirOperationStateAddResults(&constZeroState, 1, &indexType);
139fd527cefSmax   mlirOperationStateAddAttributes(&constZeroState, 1, &indexZeroValueAttr);
140fd527cefSmax   MlirOperation constZero = mlirOperationCreate(&constZeroState);
14175f239e9SAlex Zinenko   mlirBlockAppendOwnedOperation(funcBody, constZero);
14275f239e9SAlex Zinenko 
14375f239e9SAlex Zinenko   MlirValue funcArg0 = mlirBlockGetArgument(funcBody, 0);
144fd527cefSmax   MlirValue constZeroValue = mlirOperationGetResult(constZero, 0);
14575f239e9SAlex Zinenko   MlirValue dimOperands[] = {funcArg0, constZeroValue};
146df9ae599SGeorge   MlirOperationState dimState = mlirOperationStateGet(
147e2310704SJulian Gross       mlirStringRefCreateFromCString("memref.dim"), location);
14875f239e9SAlex Zinenko   mlirOperationStateAddOperands(&dimState, 2, dimOperands);
14975f239e9SAlex Zinenko   mlirOperationStateAddResults(&dimState, 1, &indexType);
15075f239e9SAlex Zinenko   MlirOperation dim = mlirOperationCreate(&dimState);
15175f239e9SAlex Zinenko   mlirBlockAppendOwnedOperation(funcBody, dim);
15275f239e9SAlex Zinenko 
15375f239e9SAlex Zinenko   MlirRegion loopBodyRegion = mlirRegionCreate();
154e084679fSRiver Riddle   MlirBlock loopBody = mlirBlockCreate(0, NULL, NULL);
155e084679fSRiver Riddle   mlirBlockAddArgument(loopBody, indexType, location);
15675f239e9SAlex Zinenko   mlirRegionAppendOwnedBlock(loopBodyRegion, loopBody);
15775f239e9SAlex Zinenko 
158df9ae599SGeorge   MlirAttribute indexOneLiteral =
159df9ae599SGeorge       mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("1 : index"));
160df9ae599SGeorge   MlirNamedAttribute indexOneValueAttr = mlirNamedAttributeGet(
161aadcb26eSMehdi Amini       mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("value")),
162aadcb26eSMehdi Amini       indexOneLiteral);
163df9ae599SGeorge   MlirOperationState constOneState = mlirOperationStateGet(
164a54f4eaeSMogball       mlirStringRefCreateFromCString("arith.constant"), location);
16575f239e9SAlex Zinenko   mlirOperationStateAddResults(&constOneState, 1, &indexType);
16675f239e9SAlex Zinenko   mlirOperationStateAddAttributes(&constOneState, 1, &indexOneValueAttr);
167fd527cefSmax   MlirOperation constOne = mlirOperationCreate(&constOneState);
16875f239e9SAlex Zinenko   mlirBlockAppendOwnedOperation(funcBody, constOne);
16975f239e9SAlex Zinenko 
17075f239e9SAlex Zinenko   MlirValue dimValue = mlirOperationGetResult(dim, 0);
171fd527cefSmax   MlirValue constOneValue = mlirOperationGetResult(constOne, 0);
17275f239e9SAlex Zinenko   MlirValue loopOperands[] = {constZeroValue, dimValue, constOneValue};
173df9ae599SGeorge   MlirOperationState loopState = mlirOperationStateGet(
174df9ae599SGeorge       mlirStringRefCreateFromCString("scf.for"), location);
17575f239e9SAlex Zinenko   mlirOperationStateAddOperands(&loopState, 3, loopOperands);
17675f239e9SAlex Zinenko   mlirOperationStateAddOwnedRegions(&loopState, 1, &loopBodyRegion);
17775f239e9SAlex Zinenko   MlirOperation loop = mlirOperationCreate(&loopState);
17875f239e9SAlex Zinenko   mlirBlockAppendOwnedOperation(funcBody, loop);
17975f239e9SAlex Zinenko 
18075f239e9SAlex Zinenko   populateLoopBody(ctx, loopBody, location, funcBody);
18175f239e9SAlex Zinenko 
182df9ae599SGeorge   MlirOperationState retState = mlirOperationStateGet(
18323aa5a74SRiver Riddle       mlirStringRefCreateFromCString("func.return"), location);
18475f239e9SAlex Zinenko   MlirOperation ret = mlirOperationCreate(&retState);
18575f239e9SAlex Zinenko   mlirBlockAppendOwnedOperation(funcBody, ret);
18675f239e9SAlex Zinenko 
187b715fa33SAlex Zinenko   MlirOperation module = mlirModuleGetOperation(moduleOp);
188b715fa33SAlex Zinenko   mlirOperationDump(module);
189b715fa33SAlex Zinenko   // clang-format off
190b715fa33SAlex Zinenko   // CHECK: module {
191b715fa33SAlex Zinenko   // CHECK:   func @add(%[[ARG0:.*]]: memref<?xf32>, %[[ARG1:.*]]: memref<?xf32>) {
192a54f4eaeSMogball   // CHECK:     %[[C0:.*]] = arith.constant 0 : index
193e2310704SJulian Gross   // CHECK:     %[[DIM:.*]] = memref.dim %[[ARG0]], %[[C0]] : memref<?xf32>
194a54f4eaeSMogball   // CHECK:     %[[C1:.*]] = arith.constant 1 : index
195b715fa33SAlex Zinenko   // CHECK:     scf.for %[[I:.*]] = %[[C0]] to %[[DIM]] step %[[C1]] {
196e2310704SJulian Gross   // CHECK:       %[[LHS:.*]] = memref.load %[[ARG0]][%[[I]]] : memref<?xf32>
197e2310704SJulian Gross   // CHECK:       %[[RHS:.*]] = memref.load %[[ARG1]][%[[I]]] : memref<?xf32>
198a54f4eaeSMogball   // CHECK:       %[[SUM:.*]] = arith.addf %[[LHS]], %[[RHS]] : f32
199e2310704SJulian Gross   // CHECK:       memref.store %[[SUM]], %[[ARG0]][%[[I]]] : memref<?xf32>
200b715fa33SAlex Zinenko   // CHECK:     }
201b715fa33SAlex Zinenko   // CHECK:     return
202b715fa33SAlex Zinenko   // CHECK:   }
203b715fa33SAlex Zinenko   // CHECK: }
204b715fa33SAlex Zinenko   // clang-format on
205b715fa33SAlex Zinenko 
20675f239e9SAlex Zinenko   return moduleOp;
20775f239e9SAlex Zinenko }
20875f239e9SAlex Zinenko 
20975f239e9SAlex Zinenko struct OpListNode {
21075f239e9SAlex Zinenko   MlirOperation op;
21175f239e9SAlex Zinenko   struct OpListNode *next;
21275f239e9SAlex Zinenko };
21375f239e9SAlex Zinenko typedef struct OpListNode OpListNode;
21475f239e9SAlex Zinenko 
21575f239e9SAlex Zinenko struct ModuleStats {
21675f239e9SAlex Zinenko   unsigned numOperations;
21775f239e9SAlex Zinenko   unsigned numAttributes;
21875f239e9SAlex Zinenko   unsigned numBlocks;
21975f239e9SAlex Zinenko   unsigned numRegions;
22075f239e9SAlex Zinenko   unsigned numValues;
22139613c2cSAlex Zinenko   unsigned numBlockArguments;
22239613c2cSAlex Zinenko   unsigned numOpResults;
22375f239e9SAlex Zinenko };
22475f239e9SAlex Zinenko typedef struct ModuleStats ModuleStats;
22575f239e9SAlex Zinenko 
22639613c2cSAlex Zinenko int collectStatsSingle(OpListNode *head, ModuleStats *stats) {
22775f239e9SAlex Zinenko   MlirOperation operation = head->op;
22875f239e9SAlex Zinenko   stats->numOperations += 1;
22975f239e9SAlex Zinenko   stats->numValues += mlirOperationGetNumResults(operation);
23075f239e9SAlex Zinenko   stats->numAttributes += mlirOperationGetNumAttributes(operation);
23175f239e9SAlex Zinenko 
23275f239e9SAlex Zinenko   unsigned numRegions = mlirOperationGetNumRegions(operation);
23375f239e9SAlex Zinenko 
23475f239e9SAlex Zinenko   stats->numRegions += numRegions;
23575f239e9SAlex Zinenko 
23639613c2cSAlex Zinenko   intptr_t numResults = mlirOperationGetNumResults(operation);
23739613c2cSAlex Zinenko   for (intptr_t i = 0; i < numResults; ++i) {
23839613c2cSAlex Zinenko     MlirValue result = mlirOperationGetResult(operation, i);
23939613c2cSAlex Zinenko     if (!mlirValueIsAOpResult(result))
24039613c2cSAlex Zinenko       return 1;
24139613c2cSAlex Zinenko     if (mlirValueIsABlockArgument(result))
24239613c2cSAlex Zinenko       return 2;
24339613c2cSAlex Zinenko     if (!mlirOperationEqual(operation, mlirOpResultGetOwner(result)))
24439613c2cSAlex Zinenko       return 3;
24539613c2cSAlex Zinenko     if (i != mlirOpResultGetResultNumber(result))
24639613c2cSAlex Zinenko       return 4;
24739613c2cSAlex Zinenko     ++stats->numOpResults;
24839613c2cSAlex Zinenko   }
24939613c2cSAlex Zinenko 
250d1a688ceSJacques Pienaar   MlirRegion region = mlirOperationGetFirstRegion(operation);
251d1a688ceSJacques Pienaar   while (!mlirRegionIsNull(region)) {
25275f239e9SAlex Zinenko     for (MlirBlock block = mlirRegionGetFirstBlock(region);
25375f239e9SAlex Zinenko          !mlirBlockIsNull(block); block = mlirBlockGetNextInRegion(block)) {
25475f239e9SAlex Zinenko       ++stats->numBlocks;
25539613c2cSAlex Zinenko       intptr_t numArgs = mlirBlockGetNumArguments(block);
25639613c2cSAlex Zinenko       stats->numValues += numArgs;
25739613c2cSAlex Zinenko       for (intptr_t j = 0; j < numArgs; ++j) {
25839613c2cSAlex Zinenko         MlirValue arg = mlirBlockGetArgument(block, j);
25939613c2cSAlex Zinenko         if (!mlirValueIsABlockArgument(arg))
26039613c2cSAlex Zinenko           return 5;
26139613c2cSAlex Zinenko         if (mlirValueIsAOpResult(arg))
26239613c2cSAlex Zinenko           return 6;
26339613c2cSAlex Zinenko         if (!mlirBlockEqual(block, mlirBlockArgumentGetOwner(arg)))
26439613c2cSAlex Zinenko           return 7;
26539613c2cSAlex Zinenko         if (j != mlirBlockArgumentGetArgNumber(arg))
26639613c2cSAlex Zinenko           return 8;
26739613c2cSAlex Zinenko         ++stats->numBlockArguments;
26839613c2cSAlex Zinenko       }
26975f239e9SAlex Zinenko 
27075f239e9SAlex Zinenko       for (MlirOperation child = mlirBlockGetFirstOperation(block);
27175f239e9SAlex Zinenko            !mlirOperationIsNull(child);
27275f239e9SAlex Zinenko            child = mlirOperationGetNextInBlock(child)) {
27375f239e9SAlex Zinenko         OpListNode *node = malloc(sizeof(OpListNode));
27475f239e9SAlex Zinenko         node->op = child;
27575f239e9SAlex Zinenko         node->next = head->next;
27675f239e9SAlex Zinenko         head->next = node;
27775f239e9SAlex Zinenko       }
27875f239e9SAlex Zinenko     }
279d1a688ceSJacques Pienaar     region = mlirRegionGetNextInOperation(region);
28075f239e9SAlex Zinenko   }
28139613c2cSAlex Zinenko   return 0;
28275f239e9SAlex Zinenko }
28375f239e9SAlex Zinenko 
28439613c2cSAlex Zinenko int collectStats(MlirOperation operation) {
28575f239e9SAlex Zinenko   OpListNode *head = malloc(sizeof(OpListNode));
28675f239e9SAlex Zinenko   head->op = operation;
28775f239e9SAlex Zinenko   head->next = NULL;
28875f239e9SAlex Zinenko 
28975f239e9SAlex Zinenko   ModuleStats stats;
29075f239e9SAlex Zinenko   stats.numOperations = 0;
29175f239e9SAlex Zinenko   stats.numAttributes = 0;
29275f239e9SAlex Zinenko   stats.numBlocks = 0;
29375f239e9SAlex Zinenko   stats.numRegions = 0;
29475f239e9SAlex Zinenko   stats.numValues = 0;
29539613c2cSAlex Zinenko   stats.numBlockArguments = 0;
29639613c2cSAlex Zinenko   stats.numOpResults = 0;
29775f239e9SAlex Zinenko 
29875f239e9SAlex Zinenko   do {
29939613c2cSAlex Zinenko     int retval = collectStatsSingle(head, &stats);
30036a6e56bSMehdi Amini     if (retval) {
30136a6e56bSMehdi Amini       free(head);
30239613c2cSAlex Zinenko       return retval;
30336a6e56bSMehdi Amini     }
30475f239e9SAlex Zinenko     OpListNode *next = head->next;
30575f239e9SAlex Zinenko     free(head);
30675f239e9SAlex Zinenko     head = next;
30775f239e9SAlex Zinenko   } while (head);
30875f239e9SAlex Zinenko 
309b715fa33SAlex Zinenko   if (stats.numValues != stats.numBlockArguments + stats.numOpResults)
310b715fa33SAlex Zinenko     return 100;
311b715fa33SAlex Zinenko 
312b715fa33SAlex Zinenko   fprintf(stderr, "@stats\n");
313321aa19eSAlex Zinenko   fprintf(stderr, "Number of operations: %u\n", stats.numOperations);
314321aa19eSAlex Zinenko   fprintf(stderr, "Number of attributes: %u\n", stats.numAttributes);
315321aa19eSAlex Zinenko   fprintf(stderr, "Number of blocks: %u\n", stats.numBlocks);
316321aa19eSAlex Zinenko   fprintf(stderr, "Number of regions: %u\n", stats.numRegions);
317321aa19eSAlex Zinenko   fprintf(stderr, "Number of values: %u\n", stats.numValues);
31839613c2cSAlex Zinenko   fprintf(stderr, "Number of block arguments: %u\n", stats.numBlockArguments);
31939613c2cSAlex Zinenko   fprintf(stderr, "Number of op results: %u\n", stats.numOpResults);
320b715fa33SAlex Zinenko   // clang-format off
321b715fa33SAlex Zinenko   // CHECK-LABEL: @stats
322973ddb7dSMehdi Amini   // CHECK: Number of operations: 12
3236e2e4d44Slorenzo chelini   // CHECK: Number of attributes: 5
324b715fa33SAlex Zinenko   // CHECK: Number of blocks: 3
325b715fa33SAlex Zinenko   // CHECK: Number of regions: 3
326b715fa33SAlex Zinenko   // CHECK: Number of values: 9
327b715fa33SAlex Zinenko   // CHECK: Number of block arguments: 3
328b715fa33SAlex Zinenko   // CHECK: Number of op results: 6
329b715fa33SAlex Zinenko   // clang-format on
33039613c2cSAlex Zinenko   return 0;
331321aa19eSAlex Zinenko }
332321aa19eSAlex Zinenko 
333df9ae599SGeorge static void printToStderr(MlirStringRef str, void *userData) {
334321aa19eSAlex Zinenko   (void)userData;
335df9ae599SGeorge   fwrite(str.data, 1, str.length, stderr);
336321aa19eSAlex Zinenko }
337321aa19eSAlex Zinenko 
3384aa21716SStella Laurenzo static void printFirstOfEach(MlirContext ctx, MlirOperation operation) {
339321aa19eSAlex Zinenko   // Assuming we are given a module, go to the first operation of the first
340321aa19eSAlex Zinenko   // function.
341321aa19eSAlex Zinenko   MlirRegion region = mlirOperationGetRegion(operation, 0);
342321aa19eSAlex Zinenko   MlirBlock block = mlirRegionGetFirstBlock(region);
343abad8455SJonas Rickert   MlirOperation function = mlirBlockGetFirstOperation(block);
344abad8455SJonas Rickert   region = mlirOperationGetRegion(function, 0);
345abad8455SJonas Rickert   MlirOperation parentOperation = function;
346321aa19eSAlex Zinenko   block = mlirRegionGetFirstBlock(region);
347321aa19eSAlex Zinenko   operation = mlirBlockGetFirstOperation(block);
348d89602edSAdam Paszke   assert(mlirModuleIsNull(mlirModuleFromOperation(operation)));
349321aa19eSAlex Zinenko 
350c645ea5eSStella Laurenzo   // Verify that parent operation and block report correctly.
3518e6c55c9SStella Laurenzo   // CHECK: Parent operation eq: 1
352c645ea5eSStella Laurenzo   fprintf(stderr, "Parent operation eq: %d\n",
353c645ea5eSStella Laurenzo           mlirOperationEqual(mlirOperationGetParentOperation(operation),
354c645ea5eSStella Laurenzo                              parentOperation));
3558e6c55c9SStella Laurenzo   // CHECK: Block eq: 1
356c645ea5eSStella Laurenzo   fprintf(stderr, "Block eq: %d\n",
357c645ea5eSStella Laurenzo           mlirBlockEqual(mlirOperationGetBlock(operation), block));
3588e6c55c9SStella Laurenzo   // CHECK: Block parent operation eq: 1
3598e6c55c9SStella Laurenzo   fprintf(
3608e6c55c9SStella Laurenzo       stderr, "Block parent operation eq: %d\n",
3618e6c55c9SStella Laurenzo       mlirOperationEqual(mlirBlockGetParentOperation(block), parentOperation));
3628e6c55c9SStella Laurenzo   // CHECK: Block parent region eq: 1
3638e6c55c9SStella Laurenzo   fprintf(stderr, "Block parent region eq: %d\n",
3648e6c55c9SStella Laurenzo           mlirRegionEqual(mlirBlockGetParentRegion(block), region));
365c645ea5eSStella Laurenzo 
366c645ea5eSStella Laurenzo   // In the module we created, the first operation of the first function is
367e2310704SJulian Gross   // an "memref.dim", which has an attribute and a single result that we can
368c645ea5eSStella Laurenzo   // use to test the printing mechanism.
369321aa19eSAlex Zinenko   mlirBlockPrint(block, printToStderr, NULL);
370321aa19eSAlex Zinenko   fprintf(stderr, "\n");
3714aa21716SStella Laurenzo   fprintf(stderr, "First operation: ");
372321aa19eSAlex Zinenko   mlirOperationPrint(operation, printToStderr, NULL);
373321aa19eSAlex Zinenko   fprintf(stderr, "\n");
374b715fa33SAlex Zinenko   // clang-format off
375a54f4eaeSMogball   // CHECK:   %[[C0:.*]] = arith.constant 0 : index
376e2310704SJulian Gross   // CHECK:   %[[DIM:.*]] = memref.dim %{{.*}}, %[[C0]] : memref<?xf32>
377a54f4eaeSMogball   // CHECK:   %[[C1:.*]] = arith.constant 1 : index
378b715fa33SAlex Zinenko   // CHECK:   scf.for %[[I:.*]] = %[[C0]] to %[[DIM]] step %[[C1]] {
379e2310704SJulian Gross   // CHECK:     %[[LHS:.*]] = memref.load %{{.*}}[%[[I]]] : memref<?xf32>
380e2310704SJulian Gross   // CHECK:     %[[RHS:.*]] = memref.load %{{.*}}[%[[I]]] : memref<?xf32>
381a54f4eaeSMogball   // CHECK:     %[[SUM:.*]] = arith.addf %[[LHS]], %[[RHS]] : f32
382e2310704SJulian Gross   // CHECK:     memref.store %[[SUM]], %{{.*}}[%[[I]]] : memref<?xf32>
383b715fa33SAlex Zinenko   // CHECK:   }
384b715fa33SAlex Zinenko   // CHECK: return
385a54f4eaeSMogball   // CHECK: First operation: {{.*}} = arith.constant 0 : index
386b715fa33SAlex Zinenko   // clang-format on
387321aa19eSAlex Zinenko 
388b85f2f5cSStella Laurenzo   // Get the operation name and print it.
389b85f2f5cSStella Laurenzo   MlirIdentifier ident = mlirOperationGetName(operation);
390b85f2f5cSStella Laurenzo   MlirStringRef identStr = mlirIdentifierStr(ident);
391b85f2f5cSStella Laurenzo   fprintf(stderr, "Operation name: '");
392b85f2f5cSStella Laurenzo   for (size_t i = 0; i < identStr.length; ++i)
393b85f2f5cSStella Laurenzo     fputc(identStr.data[i], stderr);
394b85f2f5cSStella Laurenzo   fprintf(stderr, "'\n");
395a54f4eaeSMogball   // CHECK: Operation name: 'arith.constant'
396b85f2f5cSStella Laurenzo 
397b85f2f5cSStella Laurenzo   // Get the identifier again and verify equal.
398b85f2f5cSStella Laurenzo   MlirIdentifier identAgain = mlirIdentifierGet(ctx, identStr);
399b85f2f5cSStella Laurenzo   fprintf(stderr, "Identifier equal: %d\n",
400b85f2f5cSStella Laurenzo           mlirIdentifierEqual(ident, identAgain));
401b715fa33SAlex Zinenko   // CHECK: Identifier equal: 1
402b85f2f5cSStella Laurenzo 
403c645ea5eSStella Laurenzo   // Get the block terminator and print it.
404c645ea5eSStella Laurenzo   MlirOperation terminator = mlirBlockGetTerminator(block);
405c645ea5eSStella Laurenzo   fprintf(stderr, "Terminator: ");
406c645ea5eSStella Laurenzo   mlirOperationPrint(terminator, printToStderr, NULL);
407c645ea5eSStella Laurenzo   fprintf(stderr, "\n");
408a8308020SRiver Riddle   // CHECK: Terminator: func.return
409c645ea5eSStella Laurenzo 
4107675f541SMehdi Amini   // Get the attribute by name.
4117675f541SMehdi Amini   bool hasValueAttr = mlirOperationHasInherentAttributeByName(
4127675f541SMehdi Amini       operation, mlirStringRefCreateFromCString("value"));
4137675f541SMehdi Amini   if (hasValueAttr)
4147675f541SMehdi Amini     // CHECK: Has attr "value"
4157675f541SMehdi Amini     fprintf(stderr, "Has attr \"value\"");
416321aa19eSAlex Zinenko 
4177675f541SMehdi Amini   MlirAttribute valueAttr0 = mlirOperationGetInherentAttributeByName(
4187675f541SMehdi Amini       operation, mlirStringRefCreateFromCString("value"));
4197675f541SMehdi Amini   fprintf(stderr, "Get attr \"value\": ");
4207675f541SMehdi Amini   mlirAttributePrint(valueAttr0, printToStderr, NULL);
4214aa21716SStella Laurenzo   fprintf(stderr, "\n");
4227675f541SMehdi Amini   // CHECK: Get attr "value": 0 : index
4234aa21716SStella Laurenzo 
4244aa21716SStella Laurenzo   // Get a non-existing attribute and assert that it is null (sanity).
4254aa21716SStella Laurenzo   fprintf(stderr, "does_not_exist is null: %d\n",
4267675f541SMehdi Amini           mlirAttributeIsNull(mlirOperationGetDiscardableAttributeByName(
427df9ae599SGeorge               operation, mlirStringRefCreateFromCString("does_not_exist"))));
428b715fa33SAlex Zinenko   // CHECK: does_not_exist is null: 1
4294aa21716SStella Laurenzo 
4304aa21716SStella Laurenzo   // Get result 0 and its type.
431321aa19eSAlex Zinenko   MlirValue value = mlirOperationGetResult(operation, 0);
4324aa21716SStella Laurenzo   fprintf(stderr, "Result 0: ");
433321aa19eSAlex Zinenko   mlirValuePrint(value, printToStderr, NULL);
434321aa19eSAlex Zinenko   fprintf(stderr, "\n");
4354aa21716SStella Laurenzo   fprintf(stderr, "Value is null: %d\n", mlirValueIsNull(value));
436a54f4eaeSMogball   // CHECK: Result 0: {{.*}} = arith.constant 0 : index
437b715fa33SAlex Zinenko   // CHECK: Value is null: 0
438321aa19eSAlex Zinenko 
439321aa19eSAlex Zinenko   MlirType type = mlirValueGetType(value);
4404aa21716SStella Laurenzo   fprintf(stderr, "Result 0 type: ");
441321aa19eSAlex Zinenko   mlirTypePrint(type, printToStderr, NULL);
442321aa19eSAlex Zinenko   fprintf(stderr, "\n");
443b715fa33SAlex Zinenko   // CHECK: Result 0 type: index
4444aa21716SStella Laurenzo 
4457675f541SMehdi Amini   // Set a discardable attribute.
4467675f541SMehdi Amini   mlirOperationSetDiscardableAttributeByName(
4477675f541SMehdi Amini       operation, mlirStringRefCreateFromCString("custom_attr"),
4484aa21716SStella Laurenzo       mlirBoolAttrGet(ctx, 1));
4494aa21716SStella Laurenzo   fprintf(stderr, "Op with set attr: ");
4504aa21716SStella Laurenzo   mlirOperationPrint(operation, printToStderr, NULL);
4514aa21716SStella Laurenzo   fprintf(stderr, "\n");
452b715fa33SAlex Zinenko   // CHECK: Op with set attr: {{.*}} {custom_attr = true}
4534aa21716SStella Laurenzo 
4544aa21716SStella Laurenzo   // Remove the attribute.
4554aa21716SStella Laurenzo   fprintf(stderr, "Remove attr: %d\n",
4567675f541SMehdi Amini           mlirOperationRemoveDiscardableAttributeByName(
457df9ae599SGeorge               operation, mlirStringRefCreateFromCString("custom_attr")));
4584aa21716SStella Laurenzo   fprintf(stderr, "Remove attr again: %d\n",
4597675f541SMehdi Amini           mlirOperationRemoveDiscardableAttributeByName(
460df9ae599SGeorge               operation, mlirStringRefCreateFromCString("custom_attr")));
4614aa21716SStella Laurenzo   fprintf(stderr, "Removed attr is null: %d\n",
4627675f541SMehdi Amini           mlirAttributeIsNull(mlirOperationGetDiscardableAttributeByName(
463df9ae599SGeorge               operation, mlirStringRefCreateFromCString("custom_attr"))));
464b715fa33SAlex Zinenko   // CHECK: Remove attr: 1
465b715fa33SAlex Zinenko   // CHECK: Remove attr again: 0
466b715fa33SAlex Zinenko   // CHECK: Removed attr is null: 1
46774a58ec9SStella Laurenzo 
46874a58ec9SStella Laurenzo   // Add a large attribute to verify printing flags.
46974a58ec9SStella Laurenzo   int64_t eltsShape[] = {4};
47074a58ec9SStella Laurenzo   int32_t eltsData[] = {1, 2, 3, 4};
4717675f541SMehdi Amini   mlirOperationSetDiscardableAttributeByName(
472df9ae599SGeorge       operation, mlirStringRefCreateFromCString("elts"),
47374a58ec9SStella Laurenzo       mlirDenseElementsAttrInt32Get(
4747714b405SAart Bik           mlirRankedTensorTypeGet(1, eltsShape, mlirIntegerTypeGet(ctx, 32),
4758e6c55c9SStella Laurenzo                                   mlirAttributeGetNull()),
4768e6c55c9SStella Laurenzo           4, eltsData));
47774a58ec9SStella Laurenzo   MlirOpPrintingFlags flags = mlirOpPrintingFlagsCreate();
47874a58ec9SStella Laurenzo   mlirOpPrintingFlagsElideLargeElementsAttrs(flags, 2);
47974a58ec9SStella Laurenzo   mlirOpPrintingFlagsPrintGenericOpForm(flags);
480d0236611SRiver Riddle   mlirOpPrintingFlagsEnableDebugInfo(flags, /*enable=*/1, /*prettyForm=*/0);
48174a58ec9SStella Laurenzo   mlirOpPrintingFlagsUseLocalScope(flags);
48274a58ec9SStella Laurenzo   fprintf(stderr, "Op print with all flags: ");
48374a58ec9SStella Laurenzo   mlirOperationPrintWithFlags(operation, flags, printToStderr, NULL);
48474a58ec9SStella Laurenzo   fprintf(stderr, "\n");
485e0928abbSJacques Pienaar   fprintf(stderr, "Op print with state: ");
486e0928abbSJacques Pienaar   MlirAsmState state = mlirAsmStateCreateForOperation(parentOperation, flags);
487e0928abbSJacques Pienaar   mlirOperationPrintWithState(operation, state, printToStderr, NULL);
488e0928abbSJacques Pienaar   fprintf(stderr, "\n");
489df9ae599SGeorge   // clang-format off
4909fbe3b51SMehdi Amini   // CHECK: Op print with all flags: %{{.*}} = "arith.constant"() <{value = 0 : index}> {elts = dense_resource<__elided__> : tensor<4xi32>} : () -> index loc(unknown)
491df9ae599SGeorge   // clang-format on
49274a58ec9SStella Laurenzo 
493abad8455SJonas Rickert   mlirOpPrintingFlagsDestroy(flags);
494abad8455SJonas Rickert   flags = mlirOpPrintingFlagsCreate();
495abad8455SJonas Rickert   mlirOpPrintingFlagsSkipRegions(flags);
496abad8455SJonas Rickert   fprintf(stderr, "Op print with skip regions flag: ");
497abad8455SJonas Rickert   mlirOperationPrintWithFlags(function, flags, printToStderr, NULL);
498abad8455SJonas Rickert   fprintf(stderr, "\n");
499abad8455SJonas Rickert   // clang-format off
500abad8455SJonas Rickert   // CHECK: Op print with skip regions flag: func.func @add(%[[ARG0:.*]]: memref<?xf32>, %[[ARG1:.*]]: memref<?xf32>)
501abad8455SJonas Rickert   // CHECK-NOT: constant
502abad8455SJonas Rickert   // CHECK-NOT: return
503abad8455SJonas Rickert   // clang-format on
504abad8455SJonas Rickert 
50531ebe98eSJacques Pienaar   fprintf(stderr, "With state: |");
50631ebe98eSJacques Pienaar   mlirValuePrintAsOperand(value, state, printToStderr, NULL);
50731ebe98eSJacques Pienaar   // CHECK: With state: |%0|
50831ebe98eSJacques Pienaar   fprintf(stderr, "|\n");
50931ebe98eSJacques Pienaar   mlirAsmStateDestroy(state);
51031ebe98eSJacques Pienaar 
51174a58ec9SStella Laurenzo   mlirOpPrintingFlagsDestroy(flags);
51275f239e9SAlex Zinenko }
51375f239e9SAlex Zinenko 
514b715fa33SAlex Zinenko static int constructAndTraverseIr(MlirContext ctx) {
515b715fa33SAlex Zinenko   MlirLocation location = mlirLocationUnknownGet(ctx);
516b715fa33SAlex Zinenko 
517b715fa33SAlex Zinenko   MlirModule moduleOp = makeAndDumpAdd(ctx, location);
518b715fa33SAlex Zinenko   MlirOperation module = mlirModuleGetOperation(moduleOp);
519d89602edSAdam Paszke   assert(!mlirModuleIsNull(mlirModuleFromOperation(module)));
520b715fa33SAlex Zinenko 
521b715fa33SAlex Zinenko   int errcode = collectStats(module);
522b715fa33SAlex Zinenko   if (errcode)
523b715fa33SAlex Zinenko     return errcode;
524b715fa33SAlex Zinenko 
525b715fa33SAlex Zinenko   printFirstOfEach(ctx, module);
526b715fa33SAlex Zinenko 
527b715fa33SAlex Zinenko   mlirModuleDestroy(moduleOp);
528b715fa33SAlex Zinenko   return 0;
529b715fa33SAlex Zinenko }
530b715fa33SAlex Zinenko 
531c538169eSAlex Zinenko /// Creates an operation with a region containing multiple blocks with
532c538169eSAlex Zinenko /// operations and dumps it. The blocks and operations are inserted using
533c538169eSAlex Zinenko /// block/operation-relative API and their final order is checked.
534c538169eSAlex Zinenko static void buildWithInsertionsAndPrint(MlirContext ctx) {
535c538169eSAlex Zinenko   MlirLocation loc = mlirLocationUnknownGet(ctx);
5360f9e6451SMehdi Amini   mlirContextSetAllowUnregisteredDialects(ctx, true);
537c538169eSAlex Zinenko 
538c538169eSAlex Zinenko   MlirRegion owningRegion = mlirRegionCreate();
539c538169eSAlex Zinenko   MlirBlock nullBlock = mlirRegionGetFirstBlock(owningRegion);
540df9ae599SGeorge   MlirOperationState state = mlirOperationStateGet(
541df9ae599SGeorge       mlirStringRefCreateFromCString("insertion.order.test"), loc);
542c538169eSAlex Zinenko   mlirOperationStateAddOwnedRegions(&state, 1, &owningRegion);
543c538169eSAlex Zinenko   MlirOperation op = mlirOperationCreate(&state);
544c538169eSAlex Zinenko   MlirRegion region = mlirOperationGetRegion(op, 0);
545c538169eSAlex Zinenko 
546c538169eSAlex Zinenko   // Use integer types of different bitwidth as block arguments in order to
547c538169eSAlex Zinenko   // differentiate blocks.
548c538169eSAlex Zinenko   MlirType i1 = mlirIntegerTypeGet(ctx, 1);
549c538169eSAlex Zinenko   MlirType i2 = mlirIntegerTypeGet(ctx, 2);
550c538169eSAlex Zinenko   MlirType i3 = mlirIntegerTypeGet(ctx, 3);
551c538169eSAlex Zinenko   MlirType i4 = mlirIntegerTypeGet(ctx, 4);
5528d8738f6SJohn Demme   MlirType i5 = mlirIntegerTypeGet(ctx, 5);
553e084679fSRiver Riddle   MlirBlock block1 = mlirBlockCreate(1, &i1, &loc);
554e084679fSRiver Riddle   MlirBlock block2 = mlirBlockCreate(1, &i2, &loc);
555e084679fSRiver Riddle   MlirBlock block3 = mlirBlockCreate(1, &i3, &loc);
556e084679fSRiver Riddle   MlirBlock block4 = mlirBlockCreate(1, &i4, &loc);
5578d8738f6SJohn Demme   MlirBlock block5 = mlirBlockCreate(1, &i5, &loc);
558c538169eSAlex Zinenko   // Insert blocks so as to obtain the 1-2-3-4 order,
559c538169eSAlex Zinenko   mlirRegionInsertOwnedBlockBefore(region, nullBlock, block3);
560c538169eSAlex Zinenko   mlirRegionInsertOwnedBlockBefore(region, block3, block2);
561c538169eSAlex Zinenko   mlirRegionInsertOwnedBlockAfter(region, nullBlock, block1);
562c538169eSAlex Zinenko   mlirRegionInsertOwnedBlockAfter(region, block3, block4);
5638d8738f6SJohn Demme   mlirRegionInsertOwnedBlockBefore(region, block3, block5);
564c538169eSAlex Zinenko 
565df9ae599SGeorge   MlirOperationState op1State =
566df9ae599SGeorge       mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op1"), loc);
567df9ae599SGeorge   MlirOperationState op2State =
568df9ae599SGeorge       mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op2"), loc);
569df9ae599SGeorge   MlirOperationState op3State =
570df9ae599SGeorge       mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op3"), loc);
571df9ae599SGeorge   MlirOperationState op4State =
572df9ae599SGeorge       mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op4"), loc);
573df9ae599SGeorge   MlirOperationState op5State =
574df9ae599SGeorge       mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op5"), loc);
575df9ae599SGeorge   MlirOperationState op6State =
576df9ae599SGeorge       mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op6"), loc);
577df9ae599SGeorge   MlirOperationState op7State =
578df9ae599SGeorge       mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op7"), loc);
5798d8738f6SJohn Demme   MlirOperationState op8State =
5808d8738f6SJohn Demme       mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op8"), loc);
581c538169eSAlex Zinenko   MlirOperation op1 = mlirOperationCreate(&op1State);
582c538169eSAlex Zinenko   MlirOperation op2 = mlirOperationCreate(&op2State);
583c538169eSAlex Zinenko   MlirOperation op3 = mlirOperationCreate(&op3State);
584c538169eSAlex Zinenko   MlirOperation op4 = mlirOperationCreate(&op4State);
585c538169eSAlex Zinenko   MlirOperation op5 = mlirOperationCreate(&op5State);
586c538169eSAlex Zinenko   MlirOperation op6 = mlirOperationCreate(&op6State);
587c538169eSAlex Zinenko   MlirOperation op7 = mlirOperationCreate(&op7State);
5888d8738f6SJohn Demme   MlirOperation op8 = mlirOperationCreate(&op8State);
589c538169eSAlex Zinenko 
590c538169eSAlex Zinenko   // Insert operations in the first block so as to obtain the 1-2-3-4 order.
591c538169eSAlex Zinenko   MlirOperation nullOperation = mlirBlockGetFirstOperation(block1);
592c538169eSAlex Zinenko   assert(mlirOperationIsNull(nullOperation));
593c538169eSAlex Zinenko   mlirBlockInsertOwnedOperationBefore(block1, nullOperation, op3);
594c538169eSAlex Zinenko   mlirBlockInsertOwnedOperationBefore(block1, op3, op2);
595c538169eSAlex Zinenko   mlirBlockInsertOwnedOperationAfter(block1, nullOperation, op1);
596c538169eSAlex Zinenko   mlirBlockInsertOwnedOperationAfter(block1, op3, op4);
597c538169eSAlex Zinenko 
598c538169eSAlex Zinenko   // Append operations to the rest of blocks to make them non-empty and thus
599c538169eSAlex Zinenko   // printable.
600c538169eSAlex Zinenko   mlirBlockAppendOwnedOperation(block2, op5);
601c538169eSAlex Zinenko   mlirBlockAppendOwnedOperation(block3, op6);
602c538169eSAlex Zinenko   mlirBlockAppendOwnedOperation(block4, op7);
6038d8738f6SJohn Demme   mlirBlockAppendOwnedOperation(block5, op8);
6048d8738f6SJohn Demme 
6058d8738f6SJohn Demme   // Remove block5.
6068d8738f6SJohn Demme   mlirBlockDetach(block5);
6078d8738f6SJohn Demme   mlirBlockDestroy(block5);
608c538169eSAlex Zinenko 
609c538169eSAlex Zinenko   mlirOperationDump(op);
610c538169eSAlex Zinenko   mlirOperationDestroy(op);
6110f9e6451SMehdi Amini   mlirContextSetAllowUnregisteredDialects(ctx, false);
612b715fa33SAlex Zinenko   // clang-format off
613b715fa33SAlex Zinenko   // CHECK-LABEL:  "insertion.order.test"
614b715fa33SAlex Zinenko   // CHECK:      ^{{.*}}(%{{.*}}: i1
615b715fa33SAlex Zinenko   // CHECK:        "dummy.op1"
616b715fa33SAlex Zinenko   // CHECK-NEXT:   "dummy.op2"
617b715fa33SAlex Zinenko   // CHECK-NEXT:   "dummy.op3"
618b715fa33SAlex Zinenko   // CHECK-NEXT:   "dummy.op4"
619b715fa33SAlex Zinenko   // CHECK:      ^{{.*}}(%{{.*}}: i2
620b715fa33SAlex Zinenko   // CHECK:        "dummy.op5"
6218d8738f6SJohn Demme   // CHECK-NOT:  ^{{.*}}(%{{.*}}: i5
6228d8738f6SJohn Demme   // CHECK-NOT:    "dummy.op8"
623b715fa33SAlex Zinenko   // CHECK:      ^{{.*}}(%{{.*}}: i3
624b715fa33SAlex Zinenko   // CHECK:        "dummy.op6"
625b715fa33SAlex Zinenko   // CHECK:      ^{{.*}}(%{{.*}}: i4
626b715fa33SAlex Zinenko   // CHECK:        "dummy.op7"
627b715fa33SAlex Zinenko   // clang-format on
628c538169eSAlex Zinenko }
629c538169eSAlex Zinenko 
63052586c46SStella Laurenzo /// Creates operations with type inference and tests various failure modes.
63152586c46SStella Laurenzo static int createOperationWithTypeInference(MlirContext ctx) {
63252586c46SStella Laurenzo   MlirLocation loc = mlirLocationUnknownGet(ctx);
63352586c46SStella Laurenzo   MlirAttribute iAttr = mlirIntegerAttrGet(mlirIntegerTypeGet(ctx, 32), 4);
63452586c46SStella Laurenzo 
63552586c46SStella Laurenzo   // The shape.const_size op implements result type inference and is only used
63652586c46SStella Laurenzo   // for that reason.
63752586c46SStella Laurenzo   MlirOperationState state = mlirOperationStateGet(
63852586c46SStella Laurenzo       mlirStringRefCreateFromCString("shape.const_size"), loc);
63952586c46SStella Laurenzo   MlirNamedAttribute valueAttr = mlirNamedAttributeGet(
64052586c46SStella Laurenzo       mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("value")), iAttr);
64152586c46SStella Laurenzo   mlirOperationStateAddAttributes(&state, 1, &valueAttr);
64252586c46SStella Laurenzo   mlirOperationStateEnableResultTypeInference(&state);
64352586c46SStella Laurenzo 
64452586c46SStella Laurenzo   // Expect result type inference to succeed.
64552586c46SStella Laurenzo   MlirOperation op = mlirOperationCreate(&state);
64652586c46SStella Laurenzo   if (mlirOperationIsNull(op)) {
64752586c46SStella Laurenzo     fprintf(stderr, "ERROR: Result type inference unexpectedly failed");
64852586c46SStella Laurenzo     return 1;
64952586c46SStella Laurenzo   }
65052586c46SStella Laurenzo 
65152586c46SStella Laurenzo   // CHECK: RESULT_TYPE_INFERENCE: !shape.size
65252586c46SStella Laurenzo   fprintf(stderr, "RESULT_TYPE_INFERENCE: ");
65352586c46SStella Laurenzo   mlirTypeDump(mlirValueGetType(mlirOperationGetResult(op, 0)));
65452586c46SStella Laurenzo   fprintf(stderr, "\n");
65552586c46SStella Laurenzo   mlirOperationDestroy(op);
65652586c46SStella Laurenzo   return 0;
65752586c46SStella Laurenzo }
65852586c46SStella Laurenzo 
65909f7a55fSRiver Riddle /// Dumps instances of all builtin types to check that C API works correctly.
66009f7a55fSRiver Riddle /// Additionally, performs simple identity checks that a builtin type
66174f57784SAlex Zinenko /// constructed with C API can be inspected and has the expected type. The
66209f7a55fSRiver Riddle /// latter achieves full coverage of C API for builtin types. Returns 0 on
66374f57784SAlex Zinenko /// success and a non-zero error code on failure.
66409f7a55fSRiver Riddle static int printBuiltinTypes(MlirContext ctx) {
66574f57784SAlex Zinenko   // Integer types.
66674f57784SAlex Zinenko   MlirType i32 = mlirIntegerTypeGet(ctx, 32);
66774f57784SAlex Zinenko   MlirType si32 = mlirIntegerTypeSignedGet(ctx, 32);
66874f57784SAlex Zinenko   MlirType ui32 = mlirIntegerTypeUnsignedGet(ctx, 32);
66974f57784SAlex Zinenko   if (!mlirTypeIsAInteger(i32) || mlirTypeIsAF32(i32))
67074f57784SAlex Zinenko     return 1;
67174f57784SAlex Zinenko   if (!mlirTypeIsAInteger(si32) || !mlirIntegerTypeIsSigned(si32))
67274f57784SAlex Zinenko     return 2;
67374f57784SAlex Zinenko   if (!mlirTypeIsAInteger(ui32) || !mlirIntegerTypeIsUnsigned(ui32))
67474f57784SAlex Zinenko     return 3;
67574f57784SAlex Zinenko   if (mlirTypeEqual(i32, ui32) || mlirTypeEqual(i32, si32))
67674f57784SAlex Zinenko     return 4;
67774f57784SAlex Zinenko   if (mlirIntegerTypeGetWidth(i32) != mlirIntegerTypeGetWidth(si32))
67874f57784SAlex Zinenko     return 5;
679b715fa33SAlex Zinenko   fprintf(stderr, "@types\n");
68074f57784SAlex Zinenko   mlirTypeDump(i32);
68174f57784SAlex Zinenko   fprintf(stderr, "\n");
68274f57784SAlex Zinenko   mlirTypeDump(si32);
68374f57784SAlex Zinenko   fprintf(stderr, "\n");
68474f57784SAlex Zinenko   mlirTypeDump(ui32);
68574f57784SAlex Zinenko   fprintf(stderr, "\n");
686b715fa33SAlex Zinenko   // CHECK-LABEL: @types
687b715fa33SAlex Zinenko   // CHECK: i32
688b715fa33SAlex Zinenko   // CHECK: si32
689b715fa33SAlex Zinenko   // CHECK: ui32
69074f57784SAlex Zinenko 
69174f57784SAlex Zinenko   // Index type.
69274f57784SAlex Zinenko   MlirType index = mlirIndexTypeGet(ctx);
69374f57784SAlex Zinenko   if (!mlirTypeIsAIndex(index))
69474f57784SAlex Zinenko     return 6;
69574f57784SAlex Zinenko   mlirTypeDump(index);
69674f57784SAlex Zinenko   fprintf(stderr, "\n");
697b715fa33SAlex Zinenko   // CHECK: index
69874f57784SAlex Zinenko 
69974f57784SAlex Zinenko   // Floating-point types.
70074f57784SAlex Zinenko   MlirType bf16 = mlirBF16TypeGet(ctx);
70174f57784SAlex Zinenko   MlirType f16 = mlirF16TypeGet(ctx);
70274f57784SAlex Zinenko   MlirType f32 = mlirF32TypeGet(ctx);
70374f57784SAlex Zinenko   MlirType f64 = mlirF64TypeGet(ctx);
70474f57784SAlex Zinenko   if (!mlirTypeIsABF16(bf16))
70574f57784SAlex Zinenko     return 7;
70674f57784SAlex Zinenko   if (!mlirTypeIsAF16(f16))
70774f57784SAlex Zinenko     return 9;
70874f57784SAlex Zinenko   if (!mlirTypeIsAF32(f32))
70974f57784SAlex Zinenko     return 10;
71074f57784SAlex Zinenko   if (!mlirTypeIsAF64(f64))
71174f57784SAlex Zinenko     return 11;
71274f57784SAlex Zinenko   mlirTypeDump(bf16);
71374f57784SAlex Zinenko   fprintf(stderr, "\n");
71474f57784SAlex Zinenko   mlirTypeDump(f16);
71574f57784SAlex Zinenko   fprintf(stderr, "\n");
71674f57784SAlex Zinenko   mlirTypeDump(f32);
71774f57784SAlex Zinenko   fprintf(stderr, "\n");
71874f57784SAlex Zinenko   mlirTypeDump(f64);
71974f57784SAlex Zinenko   fprintf(stderr, "\n");
720b715fa33SAlex Zinenko   // CHECK: bf16
721b715fa33SAlex Zinenko   // CHECK: f16
722b715fa33SAlex Zinenko   // CHECK: f32
723b715fa33SAlex Zinenko   // CHECK: f64
72474f57784SAlex Zinenko 
72574f57784SAlex Zinenko   // None type.
72674f57784SAlex Zinenko   MlirType none = mlirNoneTypeGet(ctx);
72774f57784SAlex Zinenko   if (!mlirTypeIsANone(none))
72874f57784SAlex Zinenko     return 12;
72974f57784SAlex Zinenko   mlirTypeDump(none);
73074f57784SAlex Zinenko   fprintf(stderr, "\n");
731b715fa33SAlex Zinenko   // CHECK: none
73274f57784SAlex Zinenko 
73374f57784SAlex Zinenko   // Complex type.
73474f57784SAlex Zinenko   MlirType cplx = mlirComplexTypeGet(f32);
73574f57784SAlex Zinenko   if (!mlirTypeIsAComplex(cplx) ||
73674f57784SAlex Zinenko       !mlirTypeEqual(mlirComplexTypeGetElementType(cplx), f32))
73774f57784SAlex Zinenko     return 13;
73874f57784SAlex Zinenko   mlirTypeDump(cplx);
73974f57784SAlex Zinenko   fprintf(stderr, "\n");
740b715fa33SAlex Zinenko   // CHECK: complex<f32>
74174f57784SAlex Zinenko 
74274f57784SAlex Zinenko   // Vector (and Shaped) type. ShapedType is a common base class for vectors,
74374f57784SAlex Zinenko   // memrefs and tensors, one cannot create instances of this class so it is
74474f57784SAlex Zinenko   // tested on an instance of vector type.
74574f57784SAlex Zinenko   int64_t shape[] = {2, 3};
74674f57784SAlex Zinenko   MlirType vector =
74774f57784SAlex Zinenko       mlirVectorTypeGet(sizeof(shape) / sizeof(int64_t), shape, f32);
74874f57784SAlex Zinenko   if (!mlirTypeIsAVector(vector) || !mlirTypeIsAShaped(vector))
74974f57784SAlex Zinenko     return 14;
75074f57784SAlex Zinenko   if (!mlirTypeEqual(mlirShapedTypeGetElementType(vector), f32) ||
75174f57784SAlex Zinenko       !mlirShapedTypeHasRank(vector) || mlirShapedTypeGetRank(vector) != 2 ||
75274f57784SAlex Zinenko       mlirShapedTypeGetDimSize(vector, 0) != 2 ||
75374f57784SAlex Zinenko       mlirShapedTypeIsDynamicDim(vector, 0) ||
75474f57784SAlex Zinenko       mlirShapedTypeGetDimSize(vector, 1) != 3 ||
75574f57784SAlex Zinenko       !mlirShapedTypeHasStaticShape(vector))
75674f57784SAlex Zinenko     return 15;
75774f57784SAlex Zinenko   mlirTypeDump(vector);
75874f57784SAlex Zinenko   fprintf(stderr, "\n");
759b715fa33SAlex Zinenko   // CHECK: vector<2x3xf32>
76074f57784SAlex Zinenko 
76196dadc9fSOleksandr "Alex" Zinenko   // Scalable vector type.
76296dadc9fSOleksandr "Alex" Zinenko   bool scalable[] = {false, true};
76396dadc9fSOleksandr "Alex" Zinenko   MlirType scalableVector = mlirVectorTypeGetScalable(
76496dadc9fSOleksandr "Alex" Zinenko       sizeof(shape) / sizeof(int64_t), shape, scalable, f32);
76596dadc9fSOleksandr "Alex" Zinenko   if (!mlirTypeIsAVector(scalableVector))
76696dadc9fSOleksandr "Alex" Zinenko     return 16;
76796dadc9fSOleksandr "Alex" Zinenko   if (!mlirVectorTypeIsScalable(scalableVector) ||
76896dadc9fSOleksandr "Alex" Zinenko       mlirVectorTypeIsDimScalable(scalableVector, 0) ||
76996dadc9fSOleksandr "Alex" Zinenko       !mlirVectorTypeIsDimScalable(scalableVector, 1))
77096dadc9fSOleksandr "Alex" Zinenko     return 17;
77196dadc9fSOleksandr "Alex" Zinenko   mlirTypeDump(scalableVector);
77296dadc9fSOleksandr "Alex" Zinenko   fprintf(stderr, "\n");
77396dadc9fSOleksandr "Alex" Zinenko   // CHECK: vector<2x[3]xf32>
77496dadc9fSOleksandr "Alex" Zinenko 
77574f57784SAlex Zinenko   // Ranked tensor type.
7767714b405SAart Bik   MlirType rankedTensor = mlirRankedTensorTypeGet(
7777714b405SAart Bik       sizeof(shape) / sizeof(int64_t), shape, f32, mlirAttributeGetNull());
77874f57784SAlex Zinenko   if (!mlirTypeIsATensor(rankedTensor) ||
779a2c8aebdSStella Laurenzo       !mlirTypeIsARankedTensor(rankedTensor) ||
780a2c8aebdSStella Laurenzo       !mlirAttributeIsNull(mlirRankedTensorTypeGetEncoding(rankedTensor)))
78196dadc9fSOleksandr "Alex" Zinenko     return 18;
78274f57784SAlex Zinenko   mlirTypeDump(rankedTensor);
78374f57784SAlex Zinenko   fprintf(stderr, "\n");
784b715fa33SAlex Zinenko   // CHECK: tensor<2x3xf32>
78574f57784SAlex Zinenko 
78674f57784SAlex Zinenko   // Unranked tensor type.
78774f57784SAlex Zinenko   MlirType unrankedTensor = mlirUnrankedTensorTypeGet(f32);
78874f57784SAlex Zinenko   if (!mlirTypeIsATensor(unrankedTensor) ||
78974f57784SAlex Zinenko       !mlirTypeIsAUnrankedTensor(unrankedTensor) ||
79074f57784SAlex Zinenko       mlirShapedTypeHasRank(unrankedTensor))
79196dadc9fSOleksandr "Alex" Zinenko     return 19;
79274f57784SAlex Zinenko   mlirTypeDump(unrankedTensor);
79374f57784SAlex Zinenko   fprintf(stderr, "\n");
794b715fa33SAlex Zinenko   // CHECK: tensor<*xf32>
79574f57784SAlex Zinenko 
79674f57784SAlex Zinenko   // MemRef type.
797f3bf5c05SVladislav Vinogradov   MlirAttribute memSpace2 = mlirIntegerAttrGet(mlirIntegerTypeGet(ctx, 64), 2);
79874f57784SAlex Zinenko   MlirType memRef = mlirMemRefTypeContiguousGet(
799f3bf5c05SVladislav Vinogradov       f32, sizeof(shape) / sizeof(int64_t), shape, memSpace2);
80074f57784SAlex Zinenko   if (!mlirTypeIsAMemRef(memRef) ||
801f3bf5c05SVladislav Vinogradov       !mlirAttributeEqual(mlirMemRefTypeGetMemorySpace(memRef), memSpace2))
80296dadc9fSOleksandr "Alex" Zinenko     return 20;
80374f57784SAlex Zinenko   mlirTypeDump(memRef);
80474f57784SAlex Zinenko   fprintf(stderr, "\n");
805b715fa33SAlex Zinenko   // CHECK: memref<2x3xf32, 2>
80674f57784SAlex Zinenko 
80774f57784SAlex Zinenko   // Unranked MemRef type.
808f3bf5c05SVladislav Vinogradov   MlirAttribute memSpace4 = mlirIntegerAttrGet(mlirIntegerTypeGet(ctx, 64), 4);
809f3bf5c05SVladislav Vinogradov   MlirType unrankedMemRef = mlirUnrankedMemRefTypeGet(f32, memSpace4);
81074f57784SAlex Zinenko   if (!mlirTypeIsAUnrankedMemRef(unrankedMemRef) ||
81174f57784SAlex Zinenko       mlirTypeIsAMemRef(unrankedMemRef) ||
812f3bf5c05SVladislav Vinogradov       !mlirAttributeEqual(mlirUnrankedMemrefGetMemorySpace(unrankedMemRef),
813f3bf5c05SVladislav Vinogradov                           memSpace4))
81496dadc9fSOleksandr "Alex" Zinenko     return 21;
81574f57784SAlex Zinenko   mlirTypeDump(unrankedMemRef);
81674f57784SAlex Zinenko   fprintf(stderr, "\n");
817b715fa33SAlex Zinenko   // CHECK: memref<*xf32, 4>
81874f57784SAlex Zinenko 
81974f57784SAlex Zinenko   // Tuple type.
82074f57784SAlex Zinenko   MlirType types[] = {unrankedMemRef, f32};
82174f57784SAlex Zinenko   MlirType tuple = mlirTupleTypeGet(ctx, 2, types);
82274f57784SAlex Zinenko   if (!mlirTypeIsATuple(tuple) || mlirTupleTypeGetNumTypes(tuple) != 2 ||
82374f57784SAlex Zinenko       !mlirTypeEqual(mlirTupleTypeGetType(tuple, 0), unrankedMemRef) ||
82474f57784SAlex Zinenko       !mlirTypeEqual(mlirTupleTypeGetType(tuple, 1), f32))
82596dadc9fSOleksandr "Alex" Zinenko     return 22;
82674f57784SAlex Zinenko   mlirTypeDump(tuple);
82774f57784SAlex Zinenko   fprintf(stderr, "\n");
828b715fa33SAlex Zinenko   // CHECK: tuple<memref<*xf32, 4>, f32>
82974f57784SAlex Zinenko 
83076753a59SStella Laurenzo   // Function type.
83176753a59SStella Laurenzo   MlirType funcInputs[2] = {mlirIndexTypeGet(ctx), mlirIntegerTypeGet(ctx, 1)};
83276753a59SStella Laurenzo   MlirType funcResults[3] = {mlirIntegerTypeGet(ctx, 16),
83376753a59SStella Laurenzo                              mlirIntegerTypeGet(ctx, 32),
83476753a59SStella Laurenzo                              mlirIntegerTypeGet(ctx, 64)};
83576753a59SStella Laurenzo   MlirType funcType = mlirFunctionTypeGet(ctx, 2, funcInputs, 3, funcResults);
83676753a59SStella Laurenzo   if (mlirFunctionTypeGetNumInputs(funcType) != 2)
83796dadc9fSOleksandr "Alex" Zinenko     return 23;
83876753a59SStella Laurenzo   if (mlirFunctionTypeGetNumResults(funcType) != 3)
83996dadc9fSOleksandr "Alex" Zinenko     return 24;
84076753a59SStella Laurenzo   if (!mlirTypeEqual(funcInputs[0], mlirFunctionTypeGetInput(funcType, 0)) ||
84176753a59SStella Laurenzo       !mlirTypeEqual(funcInputs[1], mlirFunctionTypeGetInput(funcType, 1)))
84296dadc9fSOleksandr "Alex" Zinenko     return 25;
84376753a59SStella Laurenzo   if (!mlirTypeEqual(funcResults[0], mlirFunctionTypeGetResult(funcType, 0)) ||
84476753a59SStella Laurenzo       !mlirTypeEqual(funcResults[1], mlirFunctionTypeGetResult(funcType, 1)) ||
84576753a59SStella Laurenzo       !mlirTypeEqual(funcResults[2], mlirFunctionTypeGetResult(funcType, 2)))
84696dadc9fSOleksandr "Alex" Zinenko     return 26;
84776753a59SStella Laurenzo   mlirTypeDump(funcType);
84876753a59SStella Laurenzo   fprintf(stderr, "\n");
849b715fa33SAlex Zinenko   // CHECK: (index, i1) -> (i16, i32, i64)
85076753a59SStella Laurenzo 
8514f55ed5aSdime10   // Opaque type.
8524f55ed5aSdime10   MlirStringRef namespace = mlirStringRefCreate("dialect", 7);
8534f55ed5aSdime10   MlirStringRef data = mlirStringRefCreate("type", 4);
8544f55ed5aSdime10   mlirContextSetAllowUnregisteredDialects(ctx, true);
8554f55ed5aSdime10   MlirType opaque = mlirOpaqueTypeGet(ctx, namespace, data);
8564f55ed5aSdime10   mlirContextSetAllowUnregisteredDialects(ctx, false);
8574f55ed5aSdime10   if (!mlirTypeIsAOpaque(opaque) ||
8584f55ed5aSdime10       !mlirStringRefEqual(mlirOpaqueTypeGetDialectNamespace(opaque),
8594f55ed5aSdime10                           namespace) ||
8604f55ed5aSdime10       !mlirStringRefEqual(mlirOpaqueTypeGetData(opaque), data))
86196dadc9fSOleksandr "Alex" Zinenko     return 27;
8624f55ed5aSdime10   mlirTypeDump(opaque);
8634f55ed5aSdime10   fprintf(stderr, "\n");
8644f55ed5aSdime10   // CHECK: !dialect.type
8654f55ed5aSdime10 
86674f57784SAlex Zinenko   return 0;
86774f57784SAlex Zinenko }
86874f57784SAlex Zinenko 
869fd527cefSmax void callbackSetFixedLengthString(const char *data, intptr_t len,
870fd527cefSmax                                   void *userData) {
871fd527cefSmax   strncpy(userData, data, len);
872fd527cefSmax }
873fd527cefSmax 
8745f65c4a8SGeorge bool stringIsEqual(const char *lhs, MlirStringRef rhs) {
8755f65c4a8SGeorge   if (strlen(lhs) != rhs.length) {
8765f65c4a8SGeorge     return false;
8775f65c4a8SGeorge   }
8785f65c4a8SGeorge   return !strncmp(lhs, rhs.data, rhs.length);
8795f65c4a8SGeorge }
8805f65c4a8SGeorge 
881c7cae0e4SRiver Riddle int printBuiltinAttributes(MlirContext ctx) {
882da562974SAlex Zinenko   MlirAttribute floating =
883da562974SAlex Zinenko       mlirFloatAttrDoubleGet(ctx, mlirF64TypeGet(ctx), 2.0);
884da562974SAlex Zinenko   if (!mlirAttributeIsAFloat(floating) ||
885da562974SAlex Zinenko       fabs(mlirFloatAttrGetValueDouble(floating) - 2.0) > 1E-6)
886da562974SAlex Zinenko     return 1;
887b715fa33SAlex Zinenko   fprintf(stderr, "@attrs\n");
888da562974SAlex Zinenko   mlirAttributeDump(floating);
889b715fa33SAlex Zinenko   // CHECK-LABEL: @attrs
890b715fa33SAlex Zinenko   // CHECK: 2.000000e+00 : f64
891da562974SAlex Zinenko 
8926771b98cSStella Laurenzo   // Exercise mlirAttributeGetType() just for the first one.
8936771b98cSStella Laurenzo   MlirType floatingType = mlirAttributeGetType(floating);
8946771b98cSStella Laurenzo   mlirTypeDump(floatingType);
895b715fa33SAlex Zinenko   // CHECK: f64
8966771b98cSStella Laurenzo 
897da562974SAlex Zinenko   MlirAttribute integer = mlirIntegerAttrGet(mlirIntegerTypeGet(ctx, 32), 42);
898e9db306dSrkayaith   MlirAttribute signedInteger =
899e9db306dSrkayaith       mlirIntegerAttrGet(mlirIntegerTypeSignedGet(ctx, 8), -1);
900e9db306dSrkayaith   MlirAttribute unsignedInteger =
901e9db306dSrkayaith       mlirIntegerAttrGet(mlirIntegerTypeUnsignedGet(ctx, 8), 255);
902da562974SAlex Zinenko   if (!mlirAttributeIsAInteger(integer) ||
903e9db306dSrkayaith       mlirIntegerAttrGetValueInt(integer) != 42 ||
904e9db306dSrkayaith       mlirIntegerAttrGetValueSInt(signedInteger) != -1 ||
905e9db306dSrkayaith       mlirIntegerAttrGetValueUInt(unsignedInteger) != 255)
906da562974SAlex Zinenko     return 2;
907da562974SAlex Zinenko   mlirAttributeDump(integer);
908e9db306dSrkayaith   mlirAttributeDump(signedInteger);
909e9db306dSrkayaith   mlirAttributeDump(unsignedInteger);
910b715fa33SAlex Zinenko   // CHECK: 42 : i32
911e9db306dSrkayaith   // CHECK: -1 : si8
912e9db306dSrkayaith   // CHECK: 255 : ui8
913da562974SAlex Zinenko 
914da562974SAlex Zinenko   MlirAttribute boolean = mlirBoolAttrGet(ctx, 1);
915da562974SAlex Zinenko   if (!mlirAttributeIsABool(boolean) || !mlirBoolAttrGetValue(boolean))
916da562974SAlex Zinenko     return 3;
917da562974SAlex Zinenko   mlirAttributeDump(boolean);
918b715fa33SAlex Zinenko   // CHECK: true
919da562974SAlex Zinenko 
920da562974SAlex Zinenko   const char data[] = "abcdefghijklmnopqestuvwxyz";
921da562974SAlex Zinenko   MlirAttribute opaque =
92223aa5a74SRiver Riddle       mlirOpaqueAttrGet(ctx, mlirStringRefCreateFromCString("func"), 3, data,
9235f65c4a8SGeorge                         mlirNoneTypeGet(ctx));
924da562974SAlex Zinenko   if (!mlirAttributeIsAOpaque(opaque) ||
92523aa5a74SRiver Riddle       !stringIsEqual("func", mlirOpaqueAttrGetDialectNamespace(opaque)))
926da562974SAlex Zinenko     return 4;
927855ec517SAlex Zinenko 
928855ec517SAlex Zinenko   MlirStringRef opaqueData = mlirOpaqueAttrGetData(opaque);
929855ec517SAlex Zinenko   if (opaqueData.length != 3 ||
930855ec517SAlex Zinenko       strncmp(data, opaqueData.data, opaqueData.length))
931da562974SAlex Zinenko     return 5;
932da562974SAlex Zinenko   mlirAttributeDump(opaque);
93323aa5a74SRiver Riddle   // CHECK: #func.abc
934da562974SAlex Zinenko 
9355f65c4a8SGeorge   MlirAttribute string =
9365f65c4a8SGeorge       mlirStringAttrGet(ctx, mlirStringRefCreate(data + 3, 2));
937da562974SAlex Zinenko   if (!mlirAttributeIsAString(string))
938da562974SAlex Zinenko     return 6;
939855ec517SAlex Zinenko 
940855ec517SAlex Zinenko   MlirStringRef stringValue = mlirStringAttrGetValue(string);
941855ec517SAlex Zinenko   if (stringValue.length != 2 ||
942855ec517SAlex Zinenko       strncmp(data + 3, stringValue.data, stringValue.length))
943da562974SAlex Zinenko     return 7;
944da562974SAlex Zinenko   mlirAttributeDump(string);
945b715fa33SAlex Zinenko   // CHECK: "de"
946da562974SAlex Zinenko 
9475f65c4a8SGeorge   MlirAttribute flatSymbolRef =
9485f65c4a8SGeorge       mlirFlatSymbolRefAttrGet(ctx, mlirStringRefCreate(data + 5, 3));
949da562974SAlex Zinenko   if (!mlirAttributeIsAFlatSymbolRef(flatSymbolRef))
950da562974SAlex Zinenko     return 8;
951855ec517SAlex Zinenko 
952855ec517SAlex Zinenko   MlirStringRef flatSymbolRefValue =
953855ec517SAlex Zinenko       mlirFlatSymbolRefAttrGetValue(flatSymbolRef);
954855ec517SAlex Zinenko   if (flatSymbolRefValue.length != 3 ||
955855ec517SAlex Zinenko       strncmp(data + 5, flatSymbolRefValue.data, flatSymbolRefValue.length))
956da562974SAlex Zinenko     return 9;
957da562974SAlex Zinenko   mlirAttributeDump(flatSymbolRef);
958b715fa33SAlex Zinenko   // CHECK: @fgh
959da562974SAlex Zinenko 
960da562974SAlex Zinenko   MlirAttribute symbols[] = {flatSymbolRef, flatSymbolRef};
9615f65c4a8SGeorge   MlirAttribute symbolRef =
9625f65c4a8SGeorge       mlirSymbolRefAttrGet(ctx, mlirStringRefCreate(data + 8, 2), 2, symbols);
963da562974SAlex Zinenko   if (!mlirAttributeIsASymbolRef(symbolRef) ||
964da562974SAlex Zinenko       mlirSymbolRefAttrGetNumNestedReferences(symbolRef) != 2 ||
965da562974SAlex Zinenko       !mlirAttributeEqual(mlirSymbolRefAttrGetNestedReference(symbolRef, 0),
966da562974SAlex Zinenko                           flatSymbolRef) ||
967da562974SAlex Zinenko       !mlirAttributeEqual(mlirSymbolRefAttrGetNestedReference(symbolRef, 1),
968da562974SAlex Zinenko                           flatSymbolRef))
969da562974SAlex Zinenko     return 10;
970855ec517SAlex Zinenko 
971855ec517SAlex Zinenko   MlirStringRef symbolRefLeaf = mlirSymbolRefAttrGetLeafReference(symbolRef);
972855ec517SAlex Zinenko   MlirStringRef symbolRefRoot = mlirSymbolRefAttrGetRootReference(symbolRef);
973855ec517SAlex Zinenko   if (symbolRefLeaf.length != 3 ||
974855ec517SAlex Zinenko       strncmp(data + 5, symbolRefLeaf.data, symbolRefLeaf.length) ||
975855ec517SAlex Zinenko       symbolRefRoot.length != 2 ||
976855ec517SAlex Zinenko       strncmp(data + 8, symbolRefRoot.data, symbolRefRoot.length))
977da562974SAlex Zinenko     return 11;
978da562974SAlex Zinenko   mlirAttributeDump(symbolRef);
979b715fa33SAlex Zinenko   // CHECK: @ij::@fgh::@fgh
980da562974SAlex Zinenko 
981da562974SAlex Zinenko   MlirAttribute type = mlirTypeAttrGet(mlirF32TypeGet(ctx));
982da562974SAlex Zinenko   if (!mlirAttributeIsAType(type) ||
983da562974SAlex Zinenko       !mlirTypeEqual(mlirF32TypeGet(ctx), mlirTypeAttrGetValue(type)))
984da562974SAlex Zinenko     return 12;
985da562974SAlex Zinenko   mlirAttributeDump(type);
986b715fa33SAlex Zinenko   // CHECK: f32
987da562974SAlex Zinenko 
988da562974SAlex Zinenko   MlirAttribute unit = mlirUnitAttrGet(ctx);
989da562974SAlex Zinenko   if (!mlirAttributeIsAUnit(unit))
990da562974SAlex Zinenko     return 13;
991da562974SAlex Zinenko   mlirAttributeDump(unit);
992b715fa33SAlex Zinenko   // CHECK: unit
993da562974SAlex Zinenko 
994da562974SAlex Zinenko   int64_t shape[] = {1, 2};
995da562974SAlex Zinenko 
996da562974SAlex Zinenko   int bools[] = {0, 1};
99735454268SSean Silva   uint8_t uints8[] = {0u, 1u};
99835454268SSean Silva   int8_t ints8[] = {0, 1};
999308d8b8cSRahul Kayaith   uint16_t uints16[] = {0u, 1u};
1000308d8b8cSRahul Kayaith   int16_t ints16[] = {0, 1};
1001da562974SAlex Zinenko   uint32_t uints32[] = {0u, 1u};
1002da562974SAlex Zinenko   int32_t ints32[] = {0, 1};
1003da562974SAlex Zinenko   uint64_t uints64[] = {0u, 1u};
1004da562974SAlex Zinenko   int64_t ints64[] = {0, 1};
1005da562974SAlex Zinenko   float floats[] = {0.0f, 1.0f};
1006da562974SAlex Zinenko   double doubles[] = {0.0, 1.0};
100725c218beSAshay Rane   uint16_t bf16s[] = {0x0, 0x3f80};
10085b0d6bf2STanyo Kwok   uint16_t f16s[] = {0x0, 0x3c00};
10097714b405SAart Bik   MlirAttribute encoding = mlirAttributeGetNull();
1010da562974SAlex Zinenko   MlirAttribute boolElements = mlirDenseElementsAttrBoolGet(
10117714b405SAart Bik       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 1), encoding),
10127714b405SAart Bik       2, bools);
101335454268SSean Silva   MlirAttribute uint8Elements = mlirDenseElementsAttrUInt8Get(
101435454268SSean Silva       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 8),
101535454268SSean Silva                               encoding),
101635454268SSean Silva       2, uints8);
101735454268SSean Silva   MlirAttribute int8Elements = mlirDenseElementsAttrInt8Get(
101835454268SSean Silva       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 8), encoding),
101935454268SSean Silva       2, ints8);
1020308d8b8cSRahul Kayaith   MlirAttribute uint16Elements = mlirDenseElementsAttrUInt16Get(
1021308d8b8cSRahul Kayaith       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 16),
1022308d8b8cSRahul Kayaith                               encoding),
1023308d8b8cSRahul Kayaith       2, uints16);
1024308d8b8cSRahul Kayaith   MlirAttribute int16Elements = mlirDenseElementsAttrInt16Get(
1025308d8b8cSRahul Kayaith       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 16), encoding),
1026308d8b8cSRahul Kayaith       2, ints16);
1027da562974SAlex Zinenko   MlirAttribute uint32Elements = mlirDenseElementsAttrUInt32Get(
10288e6c55c9SStella Laurenzo       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 32),
10298e6c55c9SStella Laurenzo                               encoding),
10307714b405SAart Bik       2, uints32);
1031da562974SAlex Zinenko   MlirAttribute int32Elements = mlirDenseElementsAttrInt32Get(
10327714b405SAart Bik       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 32), encoding),
10337714b405SAart Bik       2, ints32);
1034da562974SAlex Zinenko   MlirAttribute uint64Elements = mlirDenseElementsAttrUInt64Get(
10358e6c55c9SStella Laurenzo       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 64),
10368e6c55c9SStella Laurenzo                               encoding),
10377714b405SAart Bik       2, uints64);
1038da562974SAlex Zinenko   MlirAttribute int64Elements = mlirDenseElementsAttrInt64Get(
10397714b405SAart Bik       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 64), encoding),
10407714b405SAart Bik       2, ints64);
1041da562974SAlex Zinenko   MlirAttribute floatElements = mlirDenseElementsAttrFloatGet(
10428e6c55c9SStella Laurenzo       mlirRankedTensorTypeGet(2, shape, mlirF32TypeGet(ctx), encoding), 2,
10438e6c55c9SStella Laurenzo       floats);
1044da562974SAlex Zinenko   MlirAttribute doubleElements = mlirDenseElementsAttrDoubleGet(
10458e6c55c9SStella Laurenzo       mlirRankedTensorTypeGet(2, shape, mlirF64TypeGet(ctx), encoding), 2,
10468e6c55c9SStella Laurenzo       doubles);
104725c218beSAshay Rane   MlirAttribute bf16Elements = mlirDenseElementsAttrBFloat16Get(
104825c218beSAshay Rane       mlirRankedTensorTypeGet(2, shape, mlirBF16TypeGet(ctx), encoding), 2,
104925c218beSAshay Rane       bf16s);
10505b0d6bf2STanyo Kwok   MlirAttribute f16Elements = mlirDenseElementsAttrFloat16Get(
10515b0d6bf2STanyo Kwok       mlirRankedTensorTypeGet(2, shape, mlirF16TypeGet(ctx), encoding), 2,
10525b0d6bf2STanyo Kwok       f16s);
1053da562974SAlex Zinenko 
1054da562974SAlex Zinenko   if (!mlirAttributeIsADenseElements(boolElements) ||
105535454268SSean Silva       !mlirAttributeIsADenseElements(uint8Elements) ||
105635454268SSean Silva       !mlirAttributeIsADenseElements(int8Elements) ||
1057da562974SAlex Zinenko       !mlirAttributeIsADenseElements(uint32Elements) ||
1058da562974SAlex Zinenko       !mlirAttributeIsADenseElements(int32Elements) ||
1059da562974SAlex Zinenko       !mlirAttributeIsADenseElements(uint64Elements) ||
1060da562974SAlex Zinenko       !mlirAttributeIsADenseElements(int64Elements) ||
1061da562974SAlex Zinenko       !mlirAttributeIsADenseElements(floatElements) ||
106225c218beSAshay Rane       !mlirAttributeIsADenseElements(doubleElements) ||
10635b0d6bf2STanyo Kwok       !mlirAttributeIsADenseElements(bf16Elements) ||
10645b0d6bf2STanyo Kwok       !mlirAttributeIsADenseElements(f16Elements))
1065da562974SAlex Zinenko     return 14;
1066da562974SAlex Zinenko 
1067da562974SAlex Zinenko   if (mlirDenseElementsAttrGetBoolValue(boolElements, 1) != 1 ||
106835454268SSean Silva       mlirDenseElementsAttrGetUInt8Value(uint8Elements, 1) != 1 ||
106935454268SSean Silva       mlirDenseElementsAttrGetInt8Value(int8Elements, 1) != 1 ||
1070308d8b8cSRahul Kayaith       mlirDenseElementsAttrGetUInt16Value(uint16Elements, 1) != 1 ||
1071308d8b8cSRahul Kayaith       mlirDenseElementsAttrGetInt16Value(int16Elements, 1) != 1 ||
1072da562974SAlex Zinenko       mlirDenseElementsAttrGetUInt32Value(uint32Elements, 1) != 1 ||
1073da562974SAlex Zinenko       mlirDenseElementsAttrGetInt32Value(int32Elements, 1) != 1 ||
1074da562974SAlex Zinenko       mlirDenseElementsAttrGetUInt64Value(uint64Elements, 1) != 1 ||
1075da562974SAlex Zinenko       mlirDenseElementsAttrGetInt64Value(int64Elements, 1) != 1 ||
1076da562974SAlex Zinenko       fabsf(mlirDenseElementsAttrGetFloatValue(floatElements, 1) - 1.0f) >
1077da562974SAlex Zinenko           1E-6f ||
1078da562974SAlex Zinenko       fabs(mlirDenseElementsAttrGetDoubleValue(doubleElements, 1) - 1.0) > 1E-6)
1079da562974SAlex Zinenko     return 15;
1080da562974SAlex Zinenko 
1081da562974SAlex Zinenko   mlirAttributeDump(boolElements);
108235454268SSean Silva   mlirAttributeDump(uint8Elements);
108335454268SSean Silva   mlirAttributeDump(int8Elements);
1084da562974SAlex Zinenko   mlirAttributeDump(uint32Elements);
1085da562974SAlex Zinenko   mlirAttributeDump(int32Elements);
1086da562974SAlex Zinenko   mlirAttributeDump(uint64Elements);
1087da562974SAlex Zinenko   mlirAttributeDump(int64Elements);
1088da562974SAlex Zinenko   mlirAttributeDump(floatElements);
1089da562974SAlex Zinenko   mlirAttributeDump(doubleElements);
109025c218beSAshay Rane   mlirAttributeDump(bf16Elements);
10915b0d6bf2STanyo Kwok   mlirAttributeDump(f16Elements);
1092b715fa33SAlex Zinenko   // CHECK: dense<{{\[}}[false, true]]> : tensor<1x2xi1>
109335454268SSean Silva   // CHECK: dense<{{\[}}[0, 1]]> : tensor<1x2xui8>
109435454268SSean Silva   // CHECK: dense<{{\[}}[0, 1]]> : tensor<1x2xi8>
1095b715fa33SAlex Zinenko   // CHECK: dense<{{\[}}[0, 1]]> : tensor<1x2xui32>
1096b715fa33SAlex Zinenko   // CHECK: dense<{{\[}}[0, 1]]> : tensor<1x2xi32>
1097b715fa33SAlex Zinenko   // CHECK: dense<{{\[}}[0, 1]]> : tensor<1x2xui64>
1098b715fa33SAlex Zinenko   // CHECK: dense<{{\[}}[0, 1]]> : tensor<1x2xi64>
1099b715fa33SAlex Zinenko   // CHECK: dense<{{\[}}[0.000000e+00, 1.000000e+00]]> : tensor<1x2xf32>
1100b715fa33SAlex Zinenko   // CHECK: dense<{{\[}}[0.000000e+00, 1.000000e+00]]> : tensor<1x2xf64>
110125c218beSAshay Rane   // CHECK: dense<{{\[}}[0.000000e+00, 1.000000e+00]]> : tensor<1x2xbf16>
11025b0d6bf2STanyo Kwok   // CHECK: dense<{{\[}}[0.000000e+00, 1.000000e+00]]> : tensor<1x2xf16>
1103da562974SAlex Zinenko 
1104da562974SAlex Zinenko   MlirAttribute splatBool = mlirDenseElementsAttrBoolSplatGet(
110535454268SSean Silva       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 1), encoding),
110635454268SSean Silva       1);
110735454268SSean Silva   MlirAttribute splatUInt8 = mlirDenseElementsAttrUInt8SplatGet(
110835454268SSean Silva       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 8),
110935454268SSean Silva                               encoding),
111035454268SSean Silva       1);
111135454268SSean Silva   MlirAttribute splatInt8 = mlirDenseElementsAttrInt8SplatGet(
111235454268SSean Silva       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 8), encoding),
111335454268SSean Silva       1);
1114da562974SAlex Zinenko   MlirAttribute splatUInt32 = mlirDenseElementsAttrUInt32SplatGet(
111535454268SSean Silva       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 32),
111635454268SSean Silva                               encoding),
111735454268SSean Silva       1);
1118da562974SAlex Zinenko   MlirAttribute splatInt32 = mlirDenseElementsAttrInt32SplatGet(
111935454268SSean Silva       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 32), encoding),
112035454268SSean Silva       1);
1121da562974SAlex Zinenko   MlirAttribute splatUInt64 = mlirDenseElementsAttrUInt64SplatGet(
112235454268SSean Silva       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 64),
112335454268SSean Silva                               encoding),
112435454268SSean Silva       1);
1125da562974SAlex Zinenko   MlirAttribute splatInt64 = mlirDenseElementsAttrInt64SplatGet(
112635454268SSean Silva       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 64), encoding),
112735454268SSean Silva       1);
1128da562974SAlex Zinenko   MlirAttribute splatFloat = mlirDenseElementsAttrFloatSplatGet(
11297714b405SAart Bik       mlirRankedTensorTypeGet(2, shape, mlirF32TypeGet(ctx), encoding), 1.0f);
1130da562974SAlex Zinenko   MlirAttribute splatDouble = mlirDenseElementsAttrDoubleSplatGet(
11317714b405SAart Bik       mlirRankedTensorTypeGet(2, shape, mlirF64TypeGet(ctx), encoding), 1.0);
1132da562974SAlex Zinenko 
1133da562974SAlex Zinenko   if (!mlirAttributeIsADenseElements(splatBool) ||
1134da562974SAlex Zinenko       !mlirDenseElementsAttrIsSplat(splatBool) ||
113535454268SSean Silva       !mlirAttributeIsADenseElements(splatUInt8) ||
113635454268SSean Silva       !mlirDenseElementsAttrIsSplat(splatUInt8) ||
113735454268SSean Silva       !mlirAttributeIsADenseElements(splatInt8) ||
113835454268SSean Silva       !mlirDenseElementsAttrIsSplat(splatInt8) ||
1139da562974SAlex Zinenko       !mlirAttributeIsADenseElements(splatUInt32) ||
1140da562974SAlex Zinenko       !mlirDenseElementsAttrIsSplat(splatUInt32) ||
1141da562974SAlex Zinenko       !mlirAttributeIsADenseElements(splatInt32) ||
1142da562974SAlex Zinenko       !mlirDenseElementsAttrIsSplat(splatInt32) ||
1143da562974SAlex Zinenko       !mlirAttributeIsADenseElements(splatUInt64) ||
1144da562974SAlex Zinenko       !mlirDenseElementsAttrIsSplat(splatUInt64) ||
1145da562974SAlex Zinenko       !mlirAttributeIsADenseElements(splatInt64) ||
1146da562974SAlex Zinenko       !mlirDenseElementsAttrIsSplat(splatInt64) ||
1147da562974SAlex Zinenko       !mlirAttributeIsADenseElements(splatFloat) ||
1148da562974SAlex Zinenko       !mlirDenseElementsAttrIsSplat(splatFloat) ||
1149da562974SAlex Zinenko       !mlirAttributeIsADenseElements(splatDouble) ||
1150da562974SAlex Zinenko       !mlirDenseElementsAttrIsSplat(splatDouble))
1151da562974SAlex Zinenko     return 16;
1152da562974SAlex Zinenko 
1153da562974SAlex Zinenko   if (mlirDenseElementsAttrGetBoolSplatValue(splatBool) != 1 ||
115435454268SSean Silva       mlirDenseElementsAttrGetUInt8SplatValue(splatUInt8) != 1 ||
115535454268SSean Silva       mlirDenseElementsAttrGetInt8SplatValue(splatInt8) != 1 ||
1156da562974SAlex Zinenko       mlirDenseElementsAttrGetUInt32SplatValue(splatUInt32) != 1 ||
1157da562974SAlex Zinenko       mlirDenseElementsAttrGetInt32SplatValue(splatInt32) != 1 ||
1158da562974SAlex Zinenko       mlirDenseElementsAttrGetUInt64SplatValue(splatUInt64) != 1 ||
1159da562974SAlex Zinenko       mlirDenseElementsAttrGetInt64SplatValue(splatInt64) != 1 ||
1160da562974SAlex Zinenko       fabsf(mlirDenseElementsAttrGetFloatSplatValue(splatFloat) - 1.0f) >
1161da562974SAlex Zinenko           1E-6f ||
1162da562974SAlex Zinenko       fabs(mlirDenseElementsAttrGetDoubleSplatValue(splatDouble) - 1.0) > 1E-6)
1163da562974SAlex Zinenko     return 17;
1164da562974SAlex Zinenko 
1165998f3e71SJie Fu   const uint8_t *uint8RawData =
1166998f3e71SJie Fu       (const uint8_t *)mlirDenseElementsAttrGetRawData(uint8Elements);
11677055df7bSStella Laurenzo   const int8_t *int8RawData =
11687055df7bSStella Laurenzo       (const int8_t *)mlirDenseElementsAttrGetRawData(int8Elements);
1169998f3e71SJie Fu   const uint32_t *uint32RawData =
1170998f3e71SJie Fu       (const uint32_t *)mlirDenseElementsAttrGetRawData(uint32Elements);
1171998f3e71SJie Fu   const int32_t *int32RawData =
1172998f3e71SJie Fu       (const int32_t *)mlirDenseElementsAttrGetRawData(int32Elements);
1173998f3e71SJie Fu   const uint64_t *uint64RawData =
1174998f3e71SJie Fu       (const uint64_t *)mlirDenseElementsAttrGetRawData(uint64Elements);
1175998f3e71SJie Fu   const int64_t *int64RawData =
1176998f3e71SJie Fu       (const int64_t *)mlirDenseElementsAttrGetRawData(int64Elements);
11777055df7bSStella Laurenzo   const float *floatRawData =
11787055df7bSStella Laurenzo       (const float *)mlirDenseElementsAttrGetRawData(floatElements);
1179998f3e71SJie Fu   const double *doubleRawData =
1180998f3e71SJie Fu       (const double *)mlirDenseElementsAttrGetRawData(doubleElements);
1181998f3e71SJie Fu   const uint16_t *bf16RawData =
1182998f3e71SJie Fu       (const uint16_t *)mlirDenseElementsAttrGetRawData(bf16Elements);
1183998f3e71SJie Fu   const uint16_t *f16RawData =
1184998f3e71SJie Fu       (const uint16_t *)mlirDenseElementsAttrGetRawData(f16Elements);
118535454268SSean Silva   if (uint8RawData[0] != 0u || uint8RawData[1] != 1u || int8RawData[0] != 0 ||
118635454268SSean Silva       int8RawData[1] != 1 || uint32RawData[0] != 0u || uint32RawData[1] != 1u ||
118752586c46SStella Laurenzo       int32RawData[0] != 0 || int32RawData[1] != 1 || uint64RawData[0] != 0u ||
118852586c46SStella Laurenzo       uint64RawData[1] != 1u || int64RawData[0] != 0 || int64RawData[1] != 1 ||
118977133b29Szhanghb97       floatRawData[0] != 0.0f || floatRawData[1] != 1.0f ||
119025c218beSAshay Rane       doubleRawData[0] != 0.0 || doubleRawData[1] != 1.0 ||
11915b0d6bf2STanyo Kwok       bf16RawData[0] != 0 || bf16RawData[1] != 0x3f80 || f16RawData[0] != 0 ||
11925b0d6bf2STanyo Kwok       f16RawData[1] != 0x3c00)
119377133b29Szhanghb97     return 18;
119477133b29Szhanghb97 
1195da562974SAlex Zinenko   mlirAttributeDump(splatBool);
119635454268SSean Silva   mlirAttributeDump(splatUInt8);
119735454268SSean Silva   mlirAttributeDump(splatInt8);
1198da562974SAlex Zinenko   mlirAttributeDump(splatUInt32);
1199da562974SAlex Zinenko   mlirAttributeDump(splatInt32);
1200da562974SAlex Zinenko   mlirAttributeDump(splatUInt64);
1201da562974SAlex Zinenko   mlirAttributeDump(splatInt64);
1202da562974SAlex Zinenko   mlirAttributeDump(splatFloat);
1203da562974SAlex Zinenko   mlirAttributeDump(splatDouble);
1204b715fa33SAlex Zinenko   // CHECK: dense<true> : tensor<1x2xi1>
120535454268SSean Silva   // CHECK: dense<1> : tensor<1x2xui8>
120635454268SSean Silva   // CHECK: dense<1> : tensor<1x2xi8>
120735454268SSean Silva   // CHECK: dense<1> : tensor<1x2xui32>
1208b715fa33SAlex Zinenko   // CHECK: dense<1> : tensor<1x2xi32>
120935454268SSean Silva   // CHECK: dense<1> : tensor<1x2xui64>
1210b715fa33SAlex Zinenko   // CHECK: dense<1> : tensor<1x2xi64>
1211b715fa33SAlex Zinenko   // CHECK: dense<1.000000e+00> : tensor<1x2xf32>
1212b715fa33SAlex Zinenko   // CHECK: dense<1.000000e+00> : tensor<1x2xf64>
1213da562974SAlex Zinenko 
1214da562974SAlex Zinenko   mlirAttributeDump(mlirElementsAttrGetValue(floatElements, 2, uints64));
1215da562974SAlex Zinenko   mlirAttributeDump(mlirElementsAttrGetValue(doubleElements, 2, uints64));
121625c218beSAshay Rane   mlirAttributeDump(mlirElementsAttrGetValue(bf16Elements, 2, uints64));
12175b0d6bf2STanyo Kwok   mlirAttributeDump(mlirElementsAttrGetValue(f16Elements, 2, uints64));
1218b715fa33SAlex Zinenko   // CHECK: 1.000000e+00 : f32
1219b715fa33SAlex Zinenko   // CHECK: 1.000000e+00 : f64
122025c218beSAshay Rane   // CHECK: 1.000000e+00 : bf16
12215b0d6bf2STanyo Kwok   // CHECK: 1.000000e+00 : f16
1222da562974SAlex Zinenko 
12234f21152aSRiver Riddle   int64_t indices[] = {0, 1};
12244f21152aSRiver Riddle   int64_t one = 1;
1225da562974SAlex Zinenko   MlirAttribute indicesAttr = mlirDenseElementsAttrInt64Get(
12264f21152aSRiver Riddle       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 64), encoding),
12277714b405SAart Bik       2, indices);
1228da562974SAlex Zinenko   MlirAttribute valuesAttr = mlirDenseElementsAttrFloatGet(
12294f21152aSRiver Riddle       mlirRankedTensorTypeGet(1, &one, mlirF32TypeGet(ctx), encoding), 1,
12308e6c55c9SStella Laurenzo       floats);
1231da562974SAlex Zinenko   MlirAttribute sparseAttr = mlirSparseElementsAttribute(
12327714b405SAart Bik       mlirRankedTensorTypeGet(2, shape, mlirF32TypeGet(ctx), encoding),
12337714b405SAart Bik       indicesAttr, valuesAttr);
1234da562974SAlex Zinenko   mlirAttributeDump(sparseAttr);
12354f21152aSRiver Riddle   // CHECK: sparse<{{\[}}[0, 1]], 0.000000e+00> : tensor<1x2xf32>
1236da562974SAlex Zinenko 
1237619fd8c2SJeff Niu   MlirAttribute boolArray = mlirDenseBoolArrayGet(ctx, 2, bools);
1238619fd8c2SJeff Niu   MlirAttribute int8Array = mlirDenseI8ArrayGet(ctx, 2, ints8);
1239619fd8c2SJeff Niu   MlirAttribute int16Array = mlirDenseI16ArrayGet(ctx, 2, ints16);
1240619fd8c2SJeff Niu   MlirAttribute int32Array = mlirDenseI32ArrayGet(ctx, 2, ints32);
1241619fd8c2SJeff Niu   MlirAttribute int64Array = mlirDenseI64ArrayGet(ctx, 2, ints64);
1242619fd8c2SJeff Niu   MlirAttribute floatArray = mlirDenseF32ArrayGet(ctx, 2, floats);
1243619fd8c2SJeff Niu   MlirAttribute doubleArray = mlirDenseF64ArrayGet(ctx, 2, doubles);
1244619fd8c2SJeff Niu   if (!mlirAttributeIsADenseBoolArray(boolArray) ||
1245619fd8c2SJeff Niu       !mlirAttributeIsADenseI8Array(int8Array) ||
1246619fd8c2SJeff Niu       !mlirAttributeIsADenseI16Array(int16Array) ||
1247619fd8c2SJeff Niu       !mlirAttributeIsADenseI32Array(int32Array) ||
1248619fd8c2SJeff Niu       !mlirAttributeIsADenseI64Array(int64Array) ||
1249619fd8c2SJeff Niu       !mlirAttributeIsADenseF32Array(floatArray) ||
1250619fd8c2SJeff Niu       !mlirAttributeIsADenseF64Array(doubleArray))
1251619fd8c2SJeff Niu     return 19;
1252619fd8c2SJeff Niu 
1253619fd8c2SJeff Niu   if (mlirDenseArrayGetNumElements(boolArray) != 2 ||
1254619fd8c2SJeff Niu       mlirDenseArrayGetNumElements(int8Array) != 2 ||
1255619fd8c2SJeff Niu       mlirDenseArrayGetNumElements(int16Array) != 2 ||
1256619fd8c2SJeff Niu       mlirDenseArrayGetNumElements(int32Array) != 2 ||
1257619fd8c2SJeff Niu       mlirDenseArrayGetNumElements(int64Array) != 2 ||
1258619fd8c2SJeff Niu       mlirDenseArrayGetNumElements(floatArray) != 2 ||
1259619fd8c2SJeff Niu       mlirDenseArrayGetNumElements(doubleArray) != 2)
1260619fd8c2SJeff Niu     return 20;
1261619fd8c2SJeff Niu 
1262619fd8c2SJeff Niu   if (mlirDenseBoolArrayGetElement(boolArray, 1) != 1 ||
1263619fd8c2SJeff Niu       mlirDenseI8ArrayGetElement(int8Array, 1) != 1 ||
1264619fd8c2SJeff Niu       mlirDenseI16ArrayGetElement(int16Array, 1) != 1 ||
1265619fd8c2SJeff Niu       mlirDenseI32ArrayGetElement(int32Array, 1) != 1 ||
1266619fd8c2SJeff Niu       mlirDenseI64ArrayGetElement(int64Array, 1) != 1 ||
1267619fd8c2SJeff Niu       fabsf(mlirDenseF32ArrayGetElement(floatArray, 1) - 1.0f) > 1E-6f ||
1268619fd8c2SJeff Niu       fabs(mlirDenseF64ArrayGetElement(doubleArray, 1) - 1.0) > 1E-6)
1269619fd8c2SJeff Niu     return 21;
1270619fd8c2SJeff Niu 
12710aced4e0SDenys Shabalin   int64_t layoutStrides[3] = {5, 7, 13};
12720aced4e0SDenys Shabalin   MlirAttribute stridedLayoutAttr =
12730aced4e0SDenys Shabalin       mlirStridedLayoutAttrGet(ctx, 42, 3, &layoutStrides[0]);
12740aced4e0SDenys Shabalin 
12750aced4e0SDenys Shabalin   // CHECK: strided<[5, 7, 13], offset: 42>
12760aced4e0SDenys Shabalin   mlirAttributeDump(stridedLayoutAttr);
12770aced4e0SDenys Shabalin 
12780aced4e0SDenys Shabalin   if (mlirStridedLayoutAttrGetOffset(stridedLayoutAttr) != 42 ||
12790aced4e0SDenys Shabalin       mlirStridedLayoutAttrGetNumStrides(stridedLayoutAttr) != 3 ||
12800aced4e0SDenys Shabalin       mlirStridedLayoutAttrGetStride(stridedLayoutAttr, 0) != 5 ||
12810aced4e0SDenys Shabalin       mlirStridedLayoutAttrGetStride(stridedLayoutAttr, 1) != 7 ||
12820aced4e0SDenys Shabalin       mlirStridedLayoutAttrGetStride(stridedLayoutAttr, 2) != 13)
12830aced4e0SDenys Shabalin     return 22;
12840aced4e0SDenys Shabalin 
1285fb5a64f0SJacques Pienaar   MlirAttribute uint8Blob = mlirUnmanagedDenseUInt8ResourceElementsAttrGet(
1286fb5a64f0SJacques Pienaar       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 8),
1287fb5a64f0SJacques Pienaar                               encoding),
1288fb5a64f0SJacques Pienaar       mlirStringRefCreateFromCString("resource_ui8"), 2, uints8);
1289fb5a64f0SJacques Pienaar   MlirAttribute uint16Blob = mlirUnmanagedDenseUInt16ResourceElementsAttrGet(
1290fb5a64f0SJacques Pienaar       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 16),
1291fb5a64f0SJacques Pienaar                               encoding),
1292fb5a64f0SJacques Pienaar       mlirStringRefCreateFromCString("resource_ui16"), 2, uints16);
1293fb5a64f0SJacques Pienaar   MlirAttribute uint32Blob = mlirUnmanagedDenseUInt32ResourceElementsAttrGet(
1294fb5a64f0SJacques Pienaar       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 32),
1295fb5a64f0SJacques Pienaar                               encoding),
1296fb5a64f0SJacques Pienaar       mlirStringRefCreateFromCString("resource_ui32"), 2, uints32);
1297fb5a64f0SJacques Pienaar   MlirAttribute uint64Blob = mlirUnmanagedDenseUInt64ResourceElementsAttrGet(
1298fb5a64f0SJacques Pienaar       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 64),
1299fb5a64f0SJacques Pienaar                               encoding),
1300fb5a64f0SJacques Pienaar       mlirStringRefCreateFromCString("resource_ui64"), 2, uints64);
1301fb5a64f0SJacques Pienaar   MlirAttribute int8Blob = mlirUnmanagedDenseInt8ResourceElementsAttrGet(
1302fb5a64f0SJacques Pienaar       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 8), encoding),
1303fb5a64f0SJacques Pienaar       mlirStringRefCreateFromCString("resource_i8"), 2, ints8);
1304fb5a64f0SJacques Pienaar   MlirAttribute int16Blob = mlirUnmanagedDenseInt16ResourceElementsAttrGet(
1305fb5a64f0SJacques Pienaar       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 16), encoding),
1306fb5a64f0SJacques Pienaar       mlirStringRefCreateFromCString("resource_i16"), 2, ints16);
1307fb5a64f0SJacques Pienaar   MlirAttribute int32Blob = mlirUnmanagedDenseInt32ResourceElementsAttrGet(
1308fb5a64f0SJacques Pienaar       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 32), encoding),
1309fb5a64f0SJacques Pienaar       mlirStringRefCreateFromCString("resource_i32"), 2, ints32);
1310fb5a64f0SJacques Pienaar   MlirAttribute int64Blob = mlirUnmanagedDenseInt64ResourceElementsAttrGet(
1311fb5a64f0SJacques Pienaar       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 64), encoding),
1312fb5a64f0SJacques Pienaar       mlirStringRefCreateFromCString("resource_i64"), 2, ints64);
1313fb5a64f0SJacques Pienaar   MlirAttribute floatsBlob = mlirUnmanagedDenseFloatResourceElementsAttrGet(
1314fb5a64f0SJacques Pienaar       mlirRankedTensorTypeGet(2, shape, mlirF32TypeGet(ctx), encoding),
1315fb5a64f0SJacques Pienaar       mlirStringRefCreateFromCString("resource_f32"), 2, floats);
1316fb5a64f0SJacques Pienaar   MlirAttribute doublesBlob = mlirUnmanagedDenseDoubleResourceElementsAttrGet(
1317fb5a64f0SJacques Pienaar       mlirRankedTensorTypeGet(2, shape, mlirF64TypeGet(ctx), encoding),
1318fb5a64f0SJacques Pienaar       mlirStringRefCreateFromCString("resource_f64"), 2, doubles);
1319f66cd9e9SStella Laurenzo   MlirAttribute blobBlob = mlirUnmanagedDenseResourceElementsAttrGet(
13207055df7bSStella Laurenzo       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 64), encoding),
1321f66cd9e9SStella Laurenzo       mlirStringRefCreateFromCString("resource_i64_blob"), /*data=*/uints64,
1322f66cd9e9SStella Laurenzo       /*dataLength=*/sizeof(uints64),
1323f66cd9e9SStella Laurenzo       /*dataAlignment=*/_Alignof(uint64_t),
1324f66cd9e9SStella Laurenzo       /*dataIsMutable=*/false,
1325f66cd9e9SStella Laurenzo       /*deleter=*/reportResourceDelete,
1326f66cd9e9SStella Laurenzo       /*userData=*/(void *)&resourceI64BlobUserData);
1327fb5a64f0SJacques Pienaar 
1328fb5a64f0SJacques Pienaar   mlirAttributeDump(uint8Blob);
1329fb5a64f0SJacques Pienaar   mlirAttributeDump(uint16Blob);
1330fb5a64f0SJacques Pienaar   mlirAttributeDump(uint32Blob);
1331fb5a64f0SJacques Pienaar   mlirAttributeDump(uint64Blob);
1332fb5a64f0SJacques Pienaar   mlirAttributeDump(int8Blob);
1333fb5a64f0SJacques Pienaar   mlirAttributeDump(int16Blob);
1334fb5a64f0SJacques Pienaar   mlirAttributeDump(int32Blob);
1335fb5a64f0SJacques Pienaar   mlirAttributeDump(int64Blob);
1336fb5a64f0SJacques Pienaar   mlirAttributeDump(floatsBlob);
1337fb5a64f0SJacques Pienaar   mlirAttributeDump(doublesBlob);
13387055df7bSStella Laurenzo   mlirAttributeDump(blobBlob);
1339fb5a64f0SJacques Pienaar   // CHECK: dense_resource<resource_ui8> : tensor<1x2xui8>
1340fb5a64f0SJacques Pienaar   // CHECK: dense_resource<resource_ui16> : tensor<1x2xui16>
1341fb5a64f0SJacques Pienaar   // CHECK: dense_resource<resource_ui32> : tensor<1x2xui32>
1342fb5a64f0SJacques Pienaar   // CHECK: dense_resource<resource_ui64> : tensor<1x2xui64>
1343fb5a64f0SJacques Pienaar   // CHECK: dense_resource<resource_i8> : tensor<1x2xi8>
1344fb5a64f0SJacques Pienaar   // CHECK: dense_resource<resource_i16> : tensor<1x2xi16>
1345fb5a64f0SJacques Pienaar   // CHECK: dense_resource<resource_i32> : tensor<1x2xi32>
1346fb5a64f0SJacques Pienaar   // CHECK: dense_resource<resource_i64> : tensor<1x2xi64>
1347fb5a64f0SJacques Pienaar   // CHECK: dense_resource<resource_f32> : tensor<1x2xf32>
1348fb5a64f0SJacques Pienaar   // CHECK: dense_resource<resource_f64> : tensor<1x2xf64>
13497055df7bSStella Laurenzo   // CHECK: dense_resource<resource_i64_blob> : tensor<1x2xi64>
1350fb5a64f0SJacques Pienaar 
1351fb5a64f0SJacques Pienaar   if (mlirDenseUInt8ResourceElementsAttrGetValue(uint8Blob, 1) != 1 ||
1352fb5a64f0SJacques Pienaar       mlirDenseUInt16ResourceElementsAttrGetValue(uint16Blob, 1) != 1 ||
1353fb5a64f0SJacques Pienaar       mlirDenseUInt32ResourceElementsAttrGetValue(uint32Blob, 1) != 1 ||
1354fb5a64f0SJacques Pienaar       mlirDenseUInt64ResourceElementsAttrGetValue(uint64Blob, 1) != 1 ||
1355fb5a64f0SJacques Pienaar       mlirDenseInt8ResourceElementsAttrGetValue(int8Blob, 1) != 1 ||
1356fb5a64f0SJacques Pienaar       mlirDenseInt16ResourceElementsAttrGetValue(int16Blob, 1) != 1 ||
1357fb5a64f0SJacques Pienaar       mlirDenseInt32ResourceElementsAttrGetValue(int32Blob, 1) != 1 ||
1358fb5a64f0SJacques Pienaar       mlirDenseInt64ResourceElementsAttrGetValue(int64Blob, 1) != 1 ||
1359fb5a64f0SJacques Pienaar       fabsf(mlirDenseF32ArrayGetElement(floatArray, 1) - 1.0f) > 1E-6f ||
1360fb5a64f0SJacques Pienaar       fabsf(mlirDenseFloatResourceElementsAttrGetValue(floatsBlob, 1) - 1.0f) >
1361fb5a64f0SJacques Pienaar           1e-6 ||
1362fb5a64f0SJacques Pienaar       fabs(mlirDenseDoubleResourceElementsAttrGetValue(doublesBlob, 1) - 1.0f) >
13637055df7bSStella Laurenzo           1e-6 ||
13647055df7bSStella Laurenzo       mlirDenseUInt64ResourceElementsAttrGetValue(blobBlob, 1) != 1)
1365fb5a64f0SJacques Pienaar     return 23;
1366fb5a64f0SJacques Pienaar 
13677bfdac0eSAndrew Young   MlirLocation loc = mlirLocationUnknownGet(ctx);
13687bfdac0eSAndrew Young   MlirAttribute locAttr = mlirLocationGetAttribute(loc);
13697bfdac0eSAndrew Young   if (!mlirAttributeIsALocation(locAttr))
13707bfdac0eSAndrew Young     return 24;
13717bfdac0eSAndrew Young 
1372da562974SAlex Zinenko   return 0;
1373da562974SAlex Zinenko }
1374da562974SAlex Zinenko 
1375b76f523bSzhanghb97 int printAffineMap(MlirContext ctx) {
1376b76f523bSzhanghb97   MlirAffineMap emptyAffineMap = mlirAffineMapEmptyGet(ctx);
1377e79bd0b4SAlex Zinenko   MlirAffineMap affineMap = mlirAffineMapZeroResultGet(ctx, 3, 2);
1378b76f523bSzhanghb97   MlirAffineMap constAffineMap = mlirAffineMapConstantGet(ctx, 2);
1379b76f523bSzhanghb97   MlirAffineMap multiDimIdentityAffineMap =
1380b76f523bSzhanghb97       mlirAffineMapMultiDimIdentityGet(ctx, 3);
1381b76f523bSzhanghb97   MlirAffineMap minorIdentityAffineMap =
1382b76f523bSzhanghb97       mlirAffineMapMinorIdentityGet(ctx, 3, 2);
1383b76f523bSzhanghb97   unsigned permutation[] = {1, 2, 0};
1384b76f523bSzhanghb97   MlirAffineMap permutationAffineMap = mlirAffineMapPermutationGet(
1385b76f523bSzhanghb97       ctx, sizeof(permutation) / sizeof(unsigned), permutation);
1386b76f523bSzhanghb97 
1387b715fa33SAlex Zinenko   fprintf(stderr, "@affineMap\n");
1388b76f523bSzhanghb97   mlirAffineMapDump(emptyAffineMap);
1389b76f523bSzhanghb97   mlirAffineMapDump(affineMap);
1390b76f523bSzhanghb97   mlirAffineMapDump(constAffineMap);
1391b76f523bSzhanghb97   mlirAffineMapDump(multiDimIdentityAffineMap);
1392b76f523bSzhanghb97   mlirAffineMapDump(minorIdentityAffineMap);
1393b76f523bSzhanghb97   mlirAffineMapDump(permutationAffineMap);
1394b715fa33SAlex Zinenko   // CHECK-LABEL: @affineMap
1395b715fa33SAlex Zinenko   // CHECK: () -> ()
1396b715fa33SAlex Zinenko   // CHECK: (d0, d1, d2)[s0, s1] -> ()
1397b715fa33SAlex Zinenko   // CHECK: () -> (2)
1398b715fa33SAlex Zinenko   // CHECK: (d0, d1, d2) -> (d0, d1, d2)
1399b715fa33SAlex Zinenko   // CHECK: (d0, d1, d2) -> (d1, d2)
1400b715fa33SAlex Zinenko   // CHECK: (d0, d1, d2) -> (d1, d2, d0)
1401b76f523bSzhanghb97 
1402b76f523bSzhanghb97   if (!mlirAffineMapIsIdentity(emptyAffineMap) ||
1403b76f523bSzhanghb97       mlirAffineMapIsIdentity(affineMap) ||
1404b76f523bSzhanghb97       mlirAffineMapIsIdentity(constAffineMap) ||
1405b76f523bSzhanghb97       !mlirAffineMapIsIdentity(multiDimIdentityAffineMap) ||
1406b76f523bSzhanghb97       mlirAffineMapIsIdentity(minorIdentityAffineMap) ||
1407b76f523bSzhanghb97       mlirAffineMapIsIdentity(permutationAffineMap))
1408b76f523bSzhanghb97     return 1;
1409b76f523bSzhanghb97 
1410b76f523bSzhanghb97   if (!mlirAffineMapIsMinorIdentity(emptyAffineMap) ||
1411b76f523bSzhanghb97       mlirAffineMapIsMinorIdentity(affineMap) ||
1412b76f523bSzhanghb97       !mlirAffineMapIsMinorIdentity(multiDimIdentityAffineMap) ||
1413b76f523bSzhanghb97       !mlirAffineMapIsMinorIdentity(minorIdentityAffineMap) ||
1414b76f523bSzhanghb97       mlirAffineMapIsMinorIdentity(permutationAffineMap))
1415b76f523bSzhanghb97     return 2;
1416b76f523bSzhanghb97 
1417b76f523bSzhanghb97   if (!mlirAffineMapIsEmpty(emptyAffineMap) ||
141876753a59SStella Laurenzo       mlirAffineMapIsEmpty(affineMap) || mlirAffineMapIsEmpty(constAffineMap) ||
1419b76f523bSzhanghb97       mlirAffineMapIsEmpty(multiDimIdentityAffineMap) ||
1420b76f523bSzhanghb97       mlirAffineMapIsEmpty(minorIdentityAffineMap) ||
1421b76f523bSzhanghb97       mlirAffineMapIsEmpty(permutationAffineMap))
1422b76f523bSzhanghb97     return 3;
1423b76f523bSzhanghb97 
1424b76f523bSzhanghb97   if (mlirAffineMapIsSingleConstant(emptyAffineMap) ||
1425b76f523bSzhanghb97       mlirAffineMapIsSingleConstant(affineMap) ||
1426b76f523bSzhanghb97       !mlirAffineMapIsSingleConstant(constAffineMap) ||
1427b76f523bSzhanghb97       mlirAffineMapIsSingleConstant(multiDimIdentityAffineMap) ||
1428b76f523bSzhanghb97       mlirAffineMapIsSingleConstant(minorIdentityAffineMap) ||
1429b76f523bSzhanghb97       mlirAffineMapIsSingleConstant(permutationAffineMap))
1430b76f523bSzhanghb97     return 4;
1431b76f523bSzhanghb97 
1432b76f523bSzhanghb97   if (mlirAffineMapGetSingleConstantResult(constAffineMap) != 2)
1433b76f523bSzhanghb97     return 5;
1434b76f523bSzhanghb97 
1435b76f523bSzhanghb97   if (mlirAffineMapGetNumDims(emptyAffineMap) != 0 ||
1436b76f523bSzhanghb97       mlirAffineMapGetNumDims(affineMap) != 3 ||
1437b76f523bSzhanghb97       mlirAffineMapGetNumDims(constAffineMap) != 0 ||
1438b76f523bSzhanghb97       mlirAffineMapGetNumDims(multiDimIdentityAffineMap) != 3 ||
1439b76f523bSzhanghb97       mlirAffineMapGetNumDims(minorIdentityAffineMap) != 3 ||
1440b76f523bSzhanghb97       mlirAffineMapGetNumDims(permutationAffineMap) != 3)
1441b76f523bSzhanghb97     return 6;
1442b76f523bSzhanghb97 
1443b76f523bSzhanghb97   if (mlirAffineMapGetNumSymbols(emptyAffineMap) != 0 ||
1444b76f523bSzhanghb97       mlirAffineMapGetNumSymbols(affineMap) != 2 ||
1445b76f523bSzhanghb97       mlirAffineMapGetNumSymbols(constAffineMap) != 0 ||
1446b76f523bSzhanghb97       mlirAffineMapGetNumSymbols(multiDimIdentityAffineMap) != 0 ||
1447b76f523bSzhanghb97       mlirAffineMapGetNumSymbols(minorIdentityAffineMap) != 0 ||
1448b76f523bSzhanghb97       mlirAffineMapGetNumSymbols(permutationAffineMap) != 0)
1449b76f523bSzhanghb97     return 7;
1450b76f523bSzhanghb97 
1451b76f523bSzhanghb97   if (mlirAffineMapGetNumResults(emptyAffineMap) != 0 ||
1452b76f523bSzhanghb97       mlirAffineMapGetNumResults(affineMap) != 0 ||
1453b76f523bSzhanghb97       mlirAffineMapGetNumResults(constAffineMap) != 1 ||
1454b76f523bSzhanghb97       mlirAffineMapGetNumResults(multiDimIdentityAffineMap) != 3 ||
1455b76f523bSzhanghb97       mlirAffineMapGetNumResults(minorIdentityAffineMap) != 2 ||
1456b76f523bSzhanghb97       mlirAffineMapGetNumResults(permutationAffineMap) != 3)
1457b76f523bSzhanghb97     return 8;
1458b76f523bSzhanghb97 
1459b76f523bSzhanghb97   if (mlirAffineMapGetNumInputs(emptyAffineMap) != 0 ||
1460b76f523bSzhanghb97       mlirAffineMapGetNumInputs(affineMap) != 5 ||
1461b76f523bSzhanghb97       mlirAffineMapGetNumInputs(constAffineMap) != 0 ||
1462b76f523bSzhanghb97       mlirAffineMapGetNumInputs(multiDimIdentityAffineMap) != 3 ||
1463b76f523bSzhanghb97       mlirAffineMapGetNumInputs(minorIdentityAffineMap) != 3 ||
1464b76f523bSzhanghb97       mlirAffineMapGetNumInputs(permutationAffineMap) != 3)
1465b76f523bSzhanghb97     return 9;
1466b76f523bSzhanghb97 
1467b76f523bSzhanghb97   if (!mlirAffineMapIsProjectedPermutation(emptyAffineMap) ||
1468b76f523bSzhanghb97       !mlirAffineMapIsPermutation(emptyAffineMap) ||
1469b76f523bSzhanghb97       mlirAffineMapIsProjectedPermutation(affineMap) ||
1470b76f523bSzhanghb97       mlirAffineMapIsPermutation(affineMap) ||
1471b76f523bSzhanghb97       mlirAffineMapIsProjectedPermutation(constAffineMap) ||
1472b76f523bSzhanghb97       mlirAffineMapIsPermutation(constAffineMap) ||
1473b76f523bSzhanghb97       !mlirAffineMapIsProjectedPermutation(multiDimIdentityAffineMap) ||
1474b76f523bSzhanghb97       !mlirAffineMapIsPermutation(multiDimIdentityAffineMap) ||
1475b76f523bSzhanghb97       !mlirAffineMapIsProjectedPermutation(minorIdentityAffineMap) ||
1476b76f523bSzhanghb97       mlirAffineMapIsPermutation(minorIdentityAffineMap) ||
1477b76f523bSzhanghb97       !mlirAffineMapIsProjectedPermutation(permutationAffineMap) ||
1478b76f523bSzhanghb97       !mlirAffineMapIsPermutation(permutationAffineMap))
1479b76f523bSzhanghb97     return 10;
1480b76f523bSzhanghb97 
1481b76f523bSzhanghb97   intptr_t sub[] = {1};
1482b76f523bSzhanghb97 
1483b76f523bSzhanghb97   MlirAffineMap subMap = mlirAffineMapGetSubMap(
1484b76f523bSzhanghb97       multiDimIdentityAffineMap, sizeof(sub) / sizeof(intptr_t), sub);
1485b76f523bSzhanghb97   MlirAffineMap majorSubMap =
1486b76f523bSzhanghb97       mlirAffineMapGetMajorSubMap(multiDimIdentityAffineMap, 1);
1487b76f523bSzhanghb97   MlirAffineMap minorSubMap =
1488b76f523bSzhanghb97       mlirAffineMapGetMinorSubMap(multiDimIdentityAffineMap, 1);
1489b76f523bSzhanghb97 
1490b76f523bSzhanghb97   mlirAffineMapDump(subMap);
1491b76f523bSzhanghb97   mlirAffineMapDump(majorSubMap);
1492b76f523bSzhanghb97   mlirAffineMapDump(minorSubMap);
1493b715fa33SAlex Zinenko   // CHECK: (d0, d1, d2) -> (d1)
1494b715fa33SAlex Zinenko   // CHECK: (d0, d1, d2) -> (d0)
1495b715fa33SAlex Zinenko   // CHECK: (d0, d1, d2) -> (d2)
1496b76f523bSzhanghb97 
14973714f937SEdgar   // CHECK: distinct[0]<"foo">
14983714f937SEdgar   mlirAttributeDump(mlirDisctinctAttrCreate(
14993714f937SEdgar       mlirStringAttrGet(ctx, mlirStringRefCreateFromCString("foo"))));
15003714f937SEdgar 
1501b76f523bSzhanghb97   return 0;
1502b76f523bSzhanghb97 }
1503b76f523bSzhanghb97 
1504448f25c8Szhanghb97 int printAffineExpr(MlirContext ctx) {
1505448f25c8Szhanghb97   MlirAffineExpr affineDimExpr = mlirAffineDimExprGet(ctx, 5);
1506448f25c8Szhanghb97   MlirAffineExpr affineSymbolExpr = mlirAffineSymbolExprGet(ctx, 5);
1507448f25c8Szhanghb97   MlirAffineExpr affineConstantExpr = mlirAffineConstantExprGet(ctx, 5);
1508448f25c8Szhanghb97   MlirAffineExpr affineAddExpr =
1509448f25c8Szhanghb97       mlirAffineAddExprGet(affineDimExpr, affineSymbolExpr);
1510448f25c8Szhanghb97   MlirAffineExpr affineMulExpr =
1511448f25c8Szhanghb97       mlirAffineMulExprGet(affineDimExpr, affineSymbolExpr);
1512448f25c8Szhanghb97   MlirAffineExpr affineModExpr =
1513448f25c8Szhanghb97       mlirAffineModExprGet(affineDimExpr, affineSymbolExpr);
1514448f25c8Szhanghb97   MlirAffineExpr affineFloorDivExpr =
1515448f25c8Szhanghb97       mlirAffineFloorDivExprGet(affineDimExpr, affineSymbolExpr);
1516448f25c8Szhanghb97   MlirAffineExpr affineCeilDivExpr =
1517448f25c8Szhanghb97       mlirAffineCeilDivExprGet(affineDimExpr, affineSymbolExpr);
1518448f25c8Szhanghb97 
1519448f25c8Szhanghb97   // Tests mlirAffineExprDump.
1520b715fa33SAlex Zinenko   fprintf(stderr, "@affineExpr\n");
1521448f25c8Szhanghb97   mlirAffineExprDump(affineDimExpr);
1522448f25c8Szhanghb97   mlirAffineExprDump(affineSymbolExpr);
1523448f25c8Szhanghb97   mlirAffineExprDump(affineConstantExpr);
1524448f25c8Szhanghb97   mlirAffineExprDump(affineAddExpr);
1525448f25c8Szhanghb97   mlirAffineExprDump(affineMulExpr);
1526448f25c8Szhanghb97   mlirAffineExprDump(affineModExpr);
1527448f25c8Szhanghb97   mlirAffineExprDump(affineFloorDivExpr);
1528448f25c8Szhanghb97   mlirAffineExprDump(affineCeilDivExpr);
1529b715fa33SAlex Zinenko   // CHECK-LABEL: @affineExpr
1530b715fa33SAlex Zinenko   // CHECK: d5
1531b715fa33SAlex Zinenko   // CHECK: s5
1532b715fa33SAlex Zinenko   // CHECK: 5
1533b715fa33SAlex Zinenko   // CHECK: d5 + s5
1534b715fa33SAlex Zinenko   // CHECK: d5 * s5
1535b715fa33SAlex Zinenko   // CHECK: d5 mod s5
1536b715fa33SAlex Zinenko   // CHECK: d5 floordiv s5
1537b715fa33SAlex Zinenko   // CHECK: d5 ceildiv s5
1538448f25c8Szhanghb97 
1539448f25c8Szhanghb97   // Tests methods of affine binary operation expression, takes add expression
1540448f25c8Szhanghb97   // as an example.
1541448f25c8Szhanghb97   mlirAffineExprDump(mlirAffineBinaryOpExprGetLHS(affineAddExpr));
1542448f25c8Szhanghb97   mlirAffineExprDump(mlirAffineBinaryOpExprGetRHS(affineAddExpr));
1543b715fa33SAlex Zinenko   // CHECK: d5
1544b715fa33SAlex Zinenko   // CHECK: s5
1545448f25c8Szhanghb97 
1546448f25c8Szhanghb97   // Tests methods of affine dimension expression.
1547448f25c8Szhanghb97   if (mlirAffineDimExprGetPosition(affineDimExpr) != 5)
1548448f25c8Szhanghb97     return 1;
1549448f25c8Szhanghb97 
1550448f25c8Szhanghb97   // Tests methods of affine symbol expression.
1551448f25c8Szhanghb97   if (mlirAffineSymbolExprGetPosition(affineSymbolExpr) != 5)
1552448f25c8Szhanghb97     return 2;
1553448f25c8Szhanghb97 
1554448f25c8Szhanghb97   // Tests methods of affine constant expression.
1555448f25c8Szhanghb97   if (mlirAffineConstantExprGetValue(affineConstantExpr) != 5)
1556448f25c8Szhanghb97     return 3;
1557448f25c8Szhanghb97 
1558448f25c8Szhanghb97   // Tests methods of affine expression.
1559448f25c8Szhanghb97   if (mlirAffineExprIsSymbolicOrConstant(affineDimExpr) ||
1560448f25c8Szhanghb97       !mlirAffineExprIsSymbolicOrConstant(affineSymbolExpr) ||
1561448f25c8Szhanghb97       !mlirAffineExprIsSymbolicOrConstant(affineConstantExpr) ||
1562448f25c8Szhanghb97       mlirAffineExprIsSymbolicOrConstant(affineAddExpr) ||
1563448f25c8Szhanghb97       mlirAffineExprIsSymbolicOrConstant(affineMulExpr) ||
1564448f25c8Szhanghb97       mlirAffineExprIsSymbolicOrConstant(affineModExpr) ||
1565448f25c8Szhanghb97       mlirAffineExprIsSymbolicOrConstant(affineFloorDivExpr) ||
1566448f25c8Szhanghb97       mlirAffineExprIsSymbolicOrConstant(affineCeilDivExpr))
1567448f25c8Szhanghb97     return 4;
1568448f25c8Szhanghb97 
1569448f25c8Szhanghb97   if (!mlirAffineExprIsPureAffine(affineDimExpr) ||
1570448f25c8Szhanghb97       !mlirAffineExprIsPureAffine(affineSymbolExpr) ||
1571448f25c8Szhanghb97       !mlirAffineExprIsPureAffine(affineConstantExpr) ||
1572448f25c8Szhanghb97       !mlirAffineExprIsPureAffine(affineAddExpr) ||
1573448f25c8Szhanghb97       mlirAffineExprIsPureAffine(affineMulExpr) ||
1574448f25c8Szhanghb97       mlirAffineExprIsPureAffine(affineModExpr) ||
1575448f25c8Szhanghb97       mlirAffineExprIsPureAffine(affineFloorDivExpr) ||
1576448f25c8Szhanghb97       mlirAffineExprIsPureAffine(affineCeilDivExpr))
1577448f25c8Szhanghb97     return 5;
1578448f25c8Szhanghb97 
1579448f25c8Szhanghb97   if (mlirAffineExprGetLargestKnownDivisor(affineDimExpr) != 1 ||
1580448f25c8Szhanghb97       mlirAffineExprGetLargestKnownDivisor(affineSymbolExpr) != 1 ||
1581448f25c8Szhanghb97       mlirAffineExprGetLargestKnownDivisor(affineConstantExpr) != 5 ||
1582448f25c8Szhanghb97       mlirAffineExprGetLargestKnownDivisor(affineAddExpr) != 1 ||
1583448f25c8Szhanghb97       mlirAffineExprGetLargestKnownDivisor(affineMulExpr) != 1 ||
1584448f25c8Szhanghb97       mlirAffineExprGetLargestKnownDivisor(affineModExpr) != 1 ||
1585448f25c8Szhanghb97       mlirAffineExprGetLargestKnownDivisor(affineFloorDivExpr) != 1 ||
1586448f25c8Szhanghb97       mlirAffineExprGetLargestKnownDivisor(affineCeilDivExpr) != 1)
1587448f25c8Szhanghb97     return 6;
1588448f25c8Szhanghb97 
1589448f25c8Szhanghb97   if (!mlirAffineExprIsMultipleOf(affineDimExpr, 1) ||
1590448f25c8Szhanghb97       !mlirAffineExprIsMultipleOf(affineSymbolExpr, 1) ||
1591448f25c8Szhanghb97       !mlirAffineExprIsMultipleOf(affineConstantExpr, 5) ||
1592448f25c8Szhanghb97       !mlirAffineExprIsMultipleOf(affineAddExpr, 1) ||
1593448f25c8Szhanghb97       !mlirAffineExprIsMultipleOf(affineMulExpr, 1) ||
1594448f25c8Szhanghb97       !mlirAffineExprIsMultipleOf(affineModExpr, 1) ||
1595448f25c8Szhanghb97       !mlirAffineExprIsMultipleOf(affineFloorDivExpr, 1) ||
1596448f25c8Szhanghb97       !mlirAffineExprIsMultipleOf(affineCeilDivExpr, 1))
1597448f25c8Szhanghb97     return 7;
1598448f25c8Szhanghb97 
1599448f25c8Szhanghb97   if (!mlirAffineExprIsFunctionOfDim(affineDimExpr, 5) ||
1600448f25c8Szhanghb97       mlirAffineExprIsFunctionOfDim(affineSymbolExpr, 5) ||
1601448f25c8Szhanghb97       mlirAffineExprIsFunctionOfDim(affineConstantExpr, 5) ||
1602448f25c8Szhanghb97       !mlirAffineExprIsFunctionOfDim(affineAddExpr, 5) ||
1603448f25c8Szhanghb97       !mlirAffineExprIsFunctionOfDim(affineMulExpr, 5) ||
1604448f25c8Szhanghb97       !mlirAffineExprIsFunctionOfDim(affineModExpr, 5) ||
1605448f25c8Szhanghb97       !mlirAffineExprIsFunctionOfDim(affineFloorDivExpr, 5) ||
1606448f25c8Szhanghb97       !mlirAffineExprIsFunctionOfDim(affineCeilDivExpr, 5))
1607448f25c8Szhanghb97     return 8;
1608448f25c8Szhanghb97 
160941b09f4eSKazuaki Ishizaki   // Tests 'IsA' methods of affine binary operation expression.
1610448f25c8Szhanghb97   if (!mlirAffineExprIsAAdd(affineAddExpr))
1611448f25c8Szhanghb97     return 9;
1612448f25c8Szhanghb97 
1613448f25c8Szhanghb97   if (!mlirAffineExprIsAMul(affineMulExpr))
1614448f25c8Szhanghb97     return 10;
1615448f25c8Szhanghb97 
1616448f25c8Szhanghb97   if (!mlirAffineExprIsAMod(affineModExpr))
1617448f25c8Szhanghb97     return 11;
1618448f25c8Szhanghb97 
1619448f25c8Szhanghb97   if (!mlirAffineExprIsAFloorDiv(affineFloorDivExpr))
1620448f25c8Szhanghb97     return 12;
1621448f25c8Szhanghb97 
1622448f25c8Szhanghb97   if (!mlirAffineExprIsACeilDiv(affineCeilDivExpr))
1623448f25c8Szhanghb97     return 13;
1624448f25c8Szhanghb97 
162574628c43SAlex Zinenko   if (!mlirAffineExprIsABinary(affineAddExpr))
162674628c43SAlex Zinenko     return 14;
162774628c43SAlex Zinenko 
162874628c43SAlex Zinenko   // Test other 'IsA' method on affine expressions.
162974628c43SAlex Zinenko   if (!mlirAffineExprIsAConstant(affineConstantExpr))
163074628c43SAlex Zinenko     return 15;
163174628c43SAlex Zinenko 
163274628c43SAlex Zinenko   if (!mlirAffineExprIsADim(affineDimExpr))
163374628c43SAlex Zinenko     return 16;
163474628c43SAlex Zinenko 
163574628c43SAlex Zinenko   if (!mlirAffineExprIsASymbol(affineSymbolExpr))
163674628c43SAlex Zinenko     return 17;
163774628c43SAlex Zinenko 
163874628c43SAlex Zinenko   // Test equality and nullity.
163974628c43SAlex Zinenko   MlirAffineExpr otherDimExpr = mlirAffineDimExprGet(ctx, 5);
164074628c43SAlex Zinenko   if (!mlirAffineExprEqual(affineDimExpr, otherDimExpr))
164174628c43SAlex Zinenko     return 18;
164274628c43SAlex Zinenko 
164374628c43SAlex Zinenko   if (mlirAffineExprIsNull(affineDimExpr))
164474628c43SAlex Zinenko     return 19;
164574628c43SAlex Zinenko 
1646448f25c8Szhanghb97   return 0;
1647448f25c8Szhanghb97 }
1648448f25c8Szhanghb97 
1649e79bd0b4SAlex Zinenko int affineMapFromExprs(MlirContext ctx) {
1650e79bd0b4SAlex Zinenko   MlirAffineExpr affineDimExpr = mlirAffineDimExprGet(ctx, 0);
1651e79bd0b4SAlex Zinenko   MlirAffineExpr affineSymbolExpr = mlirAffineSymbolExprGet(ctx, 1);
1652e79bd0b4SAlex Zinenko   MlirAffineExpr exprs[] = {affineDimExpr, affineSymbolExpr};
1653e79bd0b4SAlex Zinenko   MlirAffineMap map = mlirAffineMapGet(ctx, 3, 3, 2, exprs);
1654e79bd0b4SAlex Zinenko 
1655e79bd0b4SAlex Zinenko   // CHECK-LABEL: @affineMapFromExprs
1656e79bd0b4SAlex Zinenko   fprintf(stderr, "@affineMapFromExprs");
1657e79bd0b4SAlex Zinenko   // CHECK: (d0, d1, d2)[s0, s1, s2] -> (d0, s1)
1658e79bd0b4SAlex Zinenko   mlirAffineMapDump(map);
1659e79bd0b4SAlex Zinenko 
1660e79bd0b4SAlex Zinenko   if (mlirAffineMapGetNumResults(map) != 2)
1661e79bd0b4SAlex Zinenko     return 1;
1662e79bd0b4SAlex Zinenko 
1663e79bd0b4SAlex Zinenko   if (!mlirAffineExprEqual(mlirAffineMapGetResult(map, 0), affineDimExpr))
1664e79bd0b4SAlex Zinenko     return 2;
1665e79bd0b4SAlex Zinenko 
1666e79bd0b4SAlex Zinenko   if (!mlirAffineExprEqual(mlirAffineMapGetResult(map, 1), affineSymbolExpr))
1667e79bd0b4SAlex Zinenko     return 3;
1668e79bd0b4SAlex Zinenko 
1669fc7594ccSAlex Zinenko   MlirAffineExpr affineDim2Expr = mlirAffineDimExprGet(ctx, 1);
1670fc7594ccSAlex Zinenko   MlirAffineExpr composed = mlirAffineExprCompose(affineDim2Expr, map);
1671fc7594ccSAlex Zinenko   // CHECK: s1
1672fc7594ccSAlex Zinenko   mlirAffineExprDump(composed);
1673fc7594ccSAlex Zinenko   if (!mlirAffineExprEqual(composed, affineSymbolExpr))
1674fc7594ccSAlex Zinenko     return 4;
1675fc7594ccSAlex Zinenko 
1676e79bd0b4SAlex Zinenko   return 0;
1677e79bd0b4SAlex Zinenko }
1678e79bd0b4SAlex Zinenko 
1679f5c7c031SAlex Zinenko int printIntegerSet(MlirContext ctx) {
1680f5c7c031SAlex Zinenko   MlirIntegerSet emptySet = mlirIntegerSetEmptyGet(ctx, 2, 1);
1681f5c7c031SAlex Zinenko 
1682f5c7c031SAlex Zinenko   // CHECK-LABEL: @printIntegerSet
1683f5c7c031SAlex Zinenko   fprintf(stderr, "@printIntegerSet");
1684f5c7c031SAlex Zinenko 
1685f5c7c031SAlex Zinenko   // CHECK: (d0, d1)[s0] : (1 == 0)
1686f5c7c031SAlex Zinenko   mlirIntegerSetDump(emptySet);
1687f5c7c031SAlex Zinenko 
1688f5c7c031SAlex Zinenko   if (!mlirIntegerSetIsCanonicalEmpty(emptySet))
1689f5c7c031SAlex Zinenko     return 1;
1690f5c7c031SAlex Zinenko 
1691f5c7c031SAlex Zinenko   MlirIntegerSet anotherEmptySet = mlirIntegerSetEmptyGet(ctx, 2, 1);
1692f5c7c031SAlex Zinenko   if (!mlirIntegerSetEqual(emptySet, anotherEmptySet))
1693f5c7c031SAlex Zinenko     return 2;
1694f5c7c031SAlex Zinenko 
1695f5c7c031SAlex Zinenko   // Construct a set constrained by:
1696f5c7c031SAlex Zinenko   //   d0 - s0 == 0,
1697f5c7c031SAlex Zinenko   //   d1 - 42 >= 0.
1698f5c7c031SAlex Zinenko   MlirAffineExpr negOne = mlirAffineConstantExprGet(ctx, -1);
1699f5c7c031SAlex Zinenko   MlirAffineExpr negFortyTwo = mlirAffineConstantExprGet(ctx, -42);
1700f5c7c031SAlex Zinenko   MlirAffineExpr d0 = mlirAffineDimExprGet(ctx, 0);
1701f5c7c031SAlex Zinenko   MlirAffineExpr d1 = mlirAffineDimExprGet(ctx, 1);
1702f5c7c031SAlex Zinenko   MlirAffineExpr s0 = mlirAffineSymbolExprGet(ctx, 0);
1703f5c7c031SAlex Zinenko   MlirAffineExpr negS0 = mlirAffineMulExprGet(negOne, s0);
1704f5c7c031SAlex Zinenko   MlirAffineExpr d0minusS0 = mlirAffineAddExprGet(d0, negS0);
1705f5c7c031SAlex Zinenko   MlirAffineExpr d1minus42 = mlirAffineAddExprGet(d1, negFortyTwo);
1706f5c7c031SAlex Zinenko   MlirAffineExpr constraints[] = {d0minusS0, d1minus42};
1707f5c7c031SAlex Zinenko   bool flags[] = {true, false};
1708f5c7c031SAlex Zinenko 
1709f5c7c031SAlex Zinenko   MlirIntegerSet set = mlirIntegerSetGet(ctx, 2, 1, 2, constraints, flags);
1710f5c7c031SAlex Zinenko   // CHECK: (d0, d1)[s0] : (
1711f5c7c031SAlex Zinenko   // CHECK-DAG: d0 - s0 == 0
1712f5c7c031SAlex Zinenko   // CHECK-DAG: d1 - 42 >= 0
1713f5c7c031SAlex Zinenko   mlirIntegerSetDump(set);
1714f5c7c031SAlex Zinenko 
1715f5c7c031SAlex Zinenko   // Transform d1 into s0.
1716f5c7c031SAlex Zinenko   MlirAffineExpr s1 = mlirAffineSymbolExprGet(ctx, 1);
1717f5c7c031SAlex Zinenko   MlirAffineExpr repl[] = {d0, s1};
1718f5c7c031SAlex Zinenko   MlirIntegerSet replaced = mlirIntegerSetReplaceGet(set, repl, &s0, 1, 2);
1719f5c7c031SAlex Zinenko   // CHECK: (d0)[s0, s1] : (
1720f5c7c031SAlex Zinenko   // CHECK-DAG: d0 - s0 == 0
1721f5c7c031SAlex Zinenko   // CHECK-DAG: s1 - 42 >= 0
1722f5c7c031SAlex Zinenko   mlirIntegerSetDump(replaced);
1723f5c7c031SAlex Zinenko 
1724f5c7c031SAlex Zinenko   if (mlirIntegerSetGetNumDims(set) != 2)
1725f5c7c031SAlex Zinenko     return 3;
1726f5c7c031SAlex Zinenko   if (mlirIntegerSetGetNumDims(replaced) != 1)
1727f5c7c031SAlex Zinenko     return 4;
1728f5c7c031SAlex Zinenko 
1729f5c7c031SAlex Zinenko   if (mlirIntegerSetGetNumSymbols(set) != 1)
1730f5c7c031SAlex Zinenko     return 5;
1731f5c7c031SAlex Zinenko   if (mlirIntegerSetGetNumSymbols(replaced) != 2)
1732f5c7c031SAlex Zinenko     return 6;
1733f5c7c031SAlex Zinenko 
1734f5c7c031SAlex Zinenko   if (mlirIntegerSetGetNumInputs(set) != 3)
1735f5c7c031SAlex Zinenko     return 7;
1736f5c7c031SAlex Zinenko 
1737f5c7c031SAlex Zinenko   if (mlirIntegerSetGetNumConstraints(set) != 2)
1738f5c7c031SAlex Zinenko     return 8;
1739f5c7c031SAlex Zinenko 
1740f5c7c031SAlex Zinenko   if (mlirIntegerSetGetNumEqualities(set) != 1)
1741f5c7c031SAlex Zinenko     return 9;
1742f5c7c031SAlex Zinenko 
1743f5c7c031SAlex Zinenko   if (mlirIntegerSetGetNumInequalities(set) != 1)
1744f5c7c031SAlex Zinenko     return 10;
1745f5c7c031SAlex Zinenko 
1746f5c7c031SAlex Zinenko   MlirAffineExpr cstr1 = mlirIntegerSetGetConstraint(set, 0);
1747f5c7c031SAlex Zinenko   MlirAffineExpr cstr2 = mlirIntegerSetGetConstraint(set, 1);
1748f5c7c031SAlex Zinenko   bool isEq1 = mlirIntegerSetIsConstraintEq(set, 0);
1749f5c7c031SAlex Zinenko   bool isEq2 = mlirIntegerSetIsConstraintEq(set, 1);
1750f5c7c031SAlex Zinenko   if (!mlirAffineExprEqual(cstr1, isEq1 ? d0minusS0 : d1minus42))
1751f5c7c031SAlex Zinenko     return 11;
1752f5c7c031SAlex Zinenko   if (!mlirAffineExprEqual(cstr2, isEq2 ? d0minusS0 : d1minus42))
1753f5c7c031SAlex Zinenko     return 12;
1754f5c7c031SAlex Zinenko 
1755f5c7c031SAlex Zinenko   return 0;
1756f5c7c031SAlex Zinenko }
1757f5c7c031SAlex Zinenko 
17585d91f79fSTom Eccles int registerOnlyStd(void) {
175964c0c9f0SAlex Zinenko   MlirContext ctx = mlirContextCreate();
176064c0c9f0SAlex Zinenko   // The built-in dialect is always loaded.
176164c0c9f0SAlex Zinenko   if (mlirContextGetNumLoadedDialects(ctx) != 1)
176264c0c9f0SAlex Zinenko     return 1;
176364c0c9f0SAlex Zinenko 
176423aa5a74SRiver Riddle   MlirDialectHandle stdHandle = mlirGetDialectHandle__func__();
17655099a48aSGeorge 
17665099a48aSGeorge   MlirDialect std = mlirContextGetOrLoadDialect(
17675099a48aSGeorge       ctx, mlirDialectHandleGetNamespace(stdHandle));
176864c0c9f0SAlex Zinenko   if (!mlirDialectIsNull(std))
176964c0c9f0SAlex Zinenko     return 2;
177064c0c9f0SAlex Zinenko 
17715099a48aSGeorge   mlirDialectHandleRegisterDialect(stdHandle, ctx);
177264c0c9f0SAlex Zinenko 
17735099a48aSGeorge   std = mlirContextGetOrLoadDialect(ctx,
17745099a48aSGeorge                                     mlirDialectHandleGetNamespace(stdHandle));
177564c0c9f0SAlex Zinenko   if (mlirDialectIsNull(std))
1776444822d7SSean Silva     return 3;
177764c0c9f0SAlex Zinenko 
17785099a48aSGeorge   MlirDialect alsoStd = mlirDialectHandleLoadDialect(stdHandle, ctx);
177964c0c9f0SAlex Zinenko   if (!mlirDialectEqual(std, alsoStd))
1780444822d7SSean Silva     return 4;
178164c0c9f0SAlex Zinenko 
178264c0c9f0SAlex Zinenko   MlirStringRef stdNs = mlirDialectGetNamespace(std);
17835099a48aSGeorge   MlirStringRef alsoStdNs = mlirDialectHandleGetNamespace(stdHandle);
178464c0c9f0SAlex Zinenko   if (stdNs.length != alsoStdNs.length ||
178564c0c9f0SAlex Zinenko       strncmp(stdNs.data, alsoStdNs.data, stdNs.length))
1786444822d7SSean Silva     return 5;
178764c0c9f0SAlex Zinenko 
1788b715fa33SAlex Zinenko   fprintf(stderr, "@registration\n");
1789b715fa33SAlex Zinenko   // CHECK-LABEL: @registration
1790b715fa33SAlex Zinenko 
1791a5ef51d7SRiver Riddle   // CHECK: func.call is_registered: 1
1792a5ef51d7SRiver Riddle   fprintf(stderr, "func.call is_registered: %d\n",
17939a9214faSStella Laurenzo           mlirContextIsRegisteredOperation(
1794a5ef51d7SRiver Riddle               ctx, mlirStringRefCreateFromCString("func.call")));
17959a9214faSStella Laurenzo 
179623aa5a74SRiver Riddle   // CHECK: func.not_existing_op is_registered: 0
179723aa5a74SRiver Riddle   fprintf(stderr, "func.not_existing_op is_registered: %d\n",
17989a9214faSStella Laurenzo           mlirContextIsRegisteredOperation(
179923aa5a74SRiver Riddle               ctx, mlirStringRefCreateFromCString("func.not_existing_op")));
18009a9214faSStella Laurenzo 
18019a9214faSStella Laurenzo   // CHECK: not_existing_dialect.not_existing_op is_registered: 0
18029a9214faSStella Laurenzo   fprintf(stderr, "not_existing_dialect.not_existing_op is_registered: %d\n",
18039a9214faSStella Laurenzo           mlirContextIsRegisteredOperation(
18049a9214faSStella Laurenzo               ctx, mlirStringRefCreateFromCString(
18059a9214faSStella Laurenzo                        "not_existing_dialect.not_existing_op")));
18069a9214faSStella Laurenzo 
1807237d18a6SMehdi Amini   mlirContextDestroy(ctx);
180864c0c9f0SAlex Zinenko   return 0;
180964c0c9f0SAlex Zinenko }
181064c0c9f0SAlex Zinenko 
18118f130f10SGeorge /// Tests backreference APIs
18125d91f79fSTom Eccles static int testBackreferences(void) {
18138f130f10SGeorge   fprintf(stderr, "@test_backreferences\n");
18148f130f10SGeorge 
18158f130f10SGeorge   MlirContext ctx = mlirContextCreate();
18168f130f10SGeorge   mlirContextSetAllowUnregisteredDialects(ctx, true);
18178f130f10SGeorge   MlirLocation loc = mlirLocationUnknownGet(ctx);
18188f130f10SGeorge 
1819e2310704SJulian Gross   MlirOperationState opState =
1820e2310704SJulian Gross       mlirOperationStateGet(mlirStringRefCreateFromCString("invalid.op"), loc);
18218f130f10SGeorge   MlirRegion region = mlirRegionCreate();
1822e084679fSRiver Riddle   MlirBlock block = mlirBlockCreate(0, NULL, NULL);
18238f130f10SGeorge   mlirRegionAppendOwnedBlock(region, block);
18248f130f10SGeorge   mlirOperationStateAddOwnedRegions(&opState, 1, &region);
18258f130f10SGeorge   MlirOperation op = mlirOperationCreate(&opState);
1826e2310704SJulian Gross   MlirIdentifier ident =
1827e2310704SJulian Gross       mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("identifier"));
18288f130f10SGeorge 
18298f130f10SGeorge   if (!mlirContextEqual(ctx, mlirOperationGetContext(op))) {
18308f130f10SGeorge     fprintf(stderr, "ERROR: Getting context from operation failed\n");
18318f130f10SGeorge     return 1;
18328f130f10SGeorge   }
18338f130f10SGeorge   if (!mlirOperationEqual(op, mlirBlockGetParentOperation(block))) {
18348f130f10SGeorge     fprintf(stderr, "ERROR: Getting parent operation from block failed\n");
18358f130f10SGeorge     return 2;
18368f130f10SGeorge   }
18376962bd68SGeorge   if (!mlirContextEqual(ctx, mlirIdentifierGetContext(ident))) {
18386962bd68SGeorge     fprintf(stderr, "ERROR: Getting context from identifier failed\n");
18396962bd68SGeorge     return 3;
18406962bd68SGeorge   }
18418f130f10SGeorge 
18428f130f10SGeorge   mlirOperationDestroy(op);
18438f130f10SGeorge   mlirContextDestroy(ctx);
18448f130f10SGeorge 
18458f130f10SGeorge   // CHECK-LABEL: @test_backreferences
18468f130f10SGeorge   return 0;
18478f130f10SGeorge }
18488f130f10SGeorge 
184963d16d06SMike Urbach /// Tests operand APIs.
18505d91f79fSTom Eccles int testOperands(void) {
185163d16d06SMike Urbach   fprintf(stderr, "@testOperands\n");
185263d16d06SMike Urbach   // CHECK-LABEL: @testOperands
185363d16d06SMike Urbach 
185463d16d06SMike Urbach   MlirContext ctx = mlirContextCreate();
18555e83a5b4SStella Laurenzo   registerAllUpstreamDialects(ctx);
18565e83a5b4SStella Laurenzo 
18575e83a5b4SStella Laurenzo   mlirContextGetOrLoadDialect(ctx, mlirStringRefCreateFromCString("arith"));
18580f9e6451SMehdi Amini   mlirContextGetOrLoadDialect(ctx, mlirStringRefCreateFromCString("test"));
185963d16d06SMike Urbach   MlirLocation loc = mlirLocationUnknownGet(ctx);
1860fd527cefSmax   MlirType indexType = mlirIndexTypeGet(ctx);
186163d16d06SMike Urbach 
186263d16d06SMike Urbach   // Create some constants to use as operands.
1863fd527cefSmax   MlirAttribute indexZeroLiteral =
1864fd527cefSmax       mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("0 : index"));
1865fd527cefSmax   MlirNamedAttribute indexZeroValueAttr = mlirNamedAttributeGet(
1866fd527cefSmax       mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("value")),
1867fd527cefSmax       indexZeroLiteral);
1868fd527cefSmax   MlirOperationState constZeroState = mlirOperationStateGet(
1869fd527cefSmax       mlirStringRefCreateFromCString("arith.constant"), loc);
1870fd527cefSmax   mlirOperationStateAddResults(&constZeroState, 1, &indexType);
1871fd527cefSmax   mlirOperationStateAddAttributes(&constZeroState, 1, &indexZeroValueAttr);
1872fd527cefSmax   MlirOperation constZero = mlirOperationCreate(&constZeroState);
1873fd527cefSmax   MlirValue constZeroValue = mlirOperationGetResult(constZero, 0);
1874fd527cefSmax 
1875fd527cefSmax   MlirAttribute indexOneLiteral =
1876fd527cefSmax       mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("1 : index"));
1877fd527cefSmax   MlirNamedAttribute indexOneValueAttr = mlirNamedAttributeGet(
1878fd527cefSmax       mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("value")),
1879fd527cefSmax       indexOneLiteral);
1880fd527cefSmax   MlirOperationState constOneState = mlirOperationStateGet(
1881fd527cefSmax       mlirStringRefCreateFromCString("arith.constant"), loc);
1882fd527cefSmax   mlirOperationStateAddResults(&constOneState, 1, &indexType);
1883fd527cefSmax   mlirOperationStateAddAttributes(&constOneState, 1, &indexOneValueAttr);
1884fd527cefSmax   MlirOperation constOne = mlirOperationCreate(&constOneState);
1885fd527cefSmax   MlirValue constOneValue = mlirOperationGetResult(constOne, 0);
188663d16d06SMike Urbach 
188763d16d06SMike Urbach   // Create the operation under test.
18880f9e6451SMehdi Amini   mlirContextSetAllowUnregisteredDialects(ctx, true);
188963d16d06SMike Urbach   MlirOperationState opState =
189063d16d06SMike Urbach       mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op"), loc);
189163d16d06SMike Urbach   MlirValue initialOperands[] = {constZeroValue};
189263d16d06SMike Urbach   mlirOperationStateAddOperands(&opState, 1, initialOperands);
189363d16d06SMike Urbach   MlirOperation op = mlirOperationCreate(&opState);
189463d16d06SMike Urbach 
189563d16d06SMike Urbach   // Test operand APIs.
189663d16d06SMike Urbach   intptr_t numOperands = mlirOperationGetNumOperands(op);
189709b5ebc0SMarkus Böck   fprintf(stderr, "Num Operands: %" PRIdPTR "\n", numOperands);
189863d16d06SMike Urbach   // CHECK: Num Operands: 1
189963d16d06SMike Urbach 
1900dd8e4435SMike Urbach   MlirValue opOperand1 = mlirOperationGetOperand(op, 0);
190163d16d06SMike Urbach   fprintf(stderr, "Original operand: ");
1902dd8e4435SMike Urbach   mlirValuePrint(opOperand1, printToStderr, NULL);
1903a54f4eaeSMogball   // CHECK: Original operand: {{.+}} arith.constant 0 : index
190463d16d06SMike Urbach 
190563d16d06SMike Urbach   mlirOperationSetOperand(op, 0, constOneValue);
1906dd8e4435SMike Urbach   MlirValue opOperand2 = mlirOperationGetOperand(op, 0);
190763d16d06SMike Urbach   fprintf(stderr, "Updated operand: ");
1908dd8e4435SMike Urbach   mlirValuePrint(opOperand2, printToStderr, NULL);
1909a54f4eaeSMogball   // CHECK: Updated operand: {{.+}} arith.constant 1 : index
191063d16d06SMike Urbach 
1911dd8e4435SMike Urbach   // Test op operand APIs.
1912dd8e4435SMike Urbach   MlirOpOperand use1 = mlirValueGetFirstUse(opOperand1);
1913dd8e4435SMike Urbach   if (!mlirOpOperandIsNull(use1)) {
1914dd8e4435SMike Urbach     fprintf(stderr, "ERROR: Use should be null\n");
1915dd8e4435SMike Urbach     return 1;
1916dd8e4435SMike Urbach   }
1917dd8e4435SMike Urbach 
1918dd8e4435SMike Urbach   MlirOpOperand use2 = mlirValueGetFirstUse(opOperand2);
1919dd8e4435SMike Urbach   if (mlirOpOperandIsNull(use2)) {
1920dd8e4435SMike Urbach     fprintf(stderr, "ERROR: Use should not be null\n");
1921dd8e4435SMike Urbach     return 2;
1922dd8e4435SMike Urbach   }
1923dd8e4435SMike Urbach 
1924dd8e4435SMike Urbach   fprintf(stderr, "Use owner: ");
1925dd8e4435SMike Urbach   mlirOperationPrint(mlirOpOperandGetOwner(use2), printToStderr, NULL);
1926dd8e4435SMike Urbach   fprintf(stderr, "\n");
1927dd8e4435SMike Urbach   // CHECK: Use owner: "dummy.op"
1928dd8e4435SMike Urbach 
1929dd8e4435SMike Urbach   fprintf(stderr, "Use operandNumber: %d\n",
1930dd8e4435SMike Urbach           mlirOpOperandGetOperandNumber(use2));
1931dd8e4435SMike Urbach   // CHECK: Use operandNumber: 0
1932dd8e4435SMike Urbach 
1933dd8e4435SMike Urbach   use2 = mlirOpOperandGetNextUse(use2);
1934dd8e4435SMike Urbach   if (!mlirOpOperandIsNull(use2)) {
1935dd8e4435SMike Urbach     fprintf(stderr, "ERROR: Next use should be null\n");
1936dd8e4435SMike Urbach     return 3;
1937dd8e4435SMike Urbach   }
1938dd8e4435SMike Urbach 
19395b303f21Smax   MlirOperationState op2State =
19405b303f21Smax       mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op2"), loc);
19415b303f21Smax   MlirValue initialOperands2[] = {constOneValue};
19425b303f21Smax   mlirOperationStateAddOperands(&op2State, 1, initialOperands2);
19435b303f21Smax   MlirOperation op2 = mlirOperationCreate(&op2State);
19445b303f21Smax 
19455b303f21Smax   MlirOpOperand use3 = mlirValueGetFirstUse(constOneValue);
19465b303f21Smax   fprintf(stderr, "First use owner: ");
19475b303f21Smax   mlirOperationPrint(mlirOpOperandGetOwner(use3), printToStderr, NULL);
19485b303f21Smax   fprintf(stderr, "\n");
19495b303f21Smax   // CHECK: First use owner: "dummy.op2"
19505b303f21Smax 
19515b303f21Smax   use3 = mlirOpOperandGetNextUse(mlirValueGetFirstUse(constOneValue));
19525b303f21Smax   fprintf(stderr, "Second use owner: ");
19535b303f21Smax   mlirOperationPrint(mlirOpOperandGetOwner(use3), printToStderr, NULL);
19545b303f21Smax   fprintf(stderr, "\n");
19555b303f21Smax   // CHECK: Second use owner: "dummy.op"
19565b303f21Smax 
19575b303f21Smax   MlirAttribute indexTwoLiteral =
19585b303f21Smax       mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("2 : index"));
19595b303f21Smax   MlirNamedAttribute indexTwoValueAttr = mlirNamedAttributeGet(
19605b303f21Smax       mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("value")),
19615b303f21Smax       indexTwoLiteral);
19625b303f21Smax   MlirOperationState constTwoState = mlirOperationStateGet(
19635b303f21Smax       mlirStringRefCreateFromCString("arith.constant"), loc);
19645b303f21Smax   mlirOperationStateAddResults(&constTwoState, 1, &indexType);
19655b303f21Smax   mlirOperationStateAddAttributes(&constTwoState, 1, &indexTwoValueAttr);
19665b303f21Smax   MlirOperation constTwo = mlirOperationCreate(&constTwoState);
19675b303f21Smax   MlirValue constTwoValue = mlirOperationGetResult(constTwo, 0);
19685b303f21Smax 
19695b303f21Smax   mlirValueReplaceAllUsesOfWith(constOneValue, constTwoValue);
19705b303f21Smax 
19715b303f21Smax   use3 = mlirValueGetFirstUse(constOneValue);
19725b303f21Smax   if (!mlirOpOperandIsNull(use3)) {
19735b303f21Smax     fprintf(stderr, "ERROR: Use should be null\n");
19745b303f21Smax     return 4;
19755b303f21Smax   }
19765b303f21Smax 
19775b303f21Smax   MlirOpOperand use4 = mlirValueGetFirstUse(constTwoValue);
19785b303f21Smax   fprintf(stderr, "First replacement use owner: ");
19795b303f21Smax   mlirOperationPrint(mlirOpOperandGetOwner(use4), printToStderr, NULL);
19805b303f21Smax   fprintf(stderr, "\n");
19815b303f21Smax   // CHECK: First replacement use owner: "dummy.op"
19825b303f21Smax 
19835b303f21Smax   use4 = mlirOpOperandGetNextUse(mlirValueGetFirstUse(constTwoValue));
19845b303f21Smax   fprintf(stderr, "Second replacement use owner: ");
19855b303f21Smax   mlirOperationPrint(mlirOpOperandGetOwner(use4), printToStderr, NULL);
19865b303f21Smax   fprintf(stderr, "\n");
19875b303f21Smax   // CHECK: Second replacement use owner: "dummy.op2"
19885b303f21Smax 
1989dc2ce600SShenghang Tsai   MlirOpOperand use5 = mlirValueGetFirstUse(constTwoValue);
1990dc2ce600SShenghang Tsai   MlirOpOperand use6 = mlirOpOperandGetNextUse(use5);
1991dc2ce600SShenghang Tsai   if (!mlirValueEqual(mlirOpOperandGetValue(use5),
1992dc2ce600SShenghang Tsai                       mlirOpOperandGetValue(use6))) {
1993dc2ce600SShenghang Tsai     fprintf(stderr,
1994dc2ce600SShenghang Tsai             "ERROR: First and second operand should share the same value\n");
1995dc2ce600SShenghang Tsai     return 5;
1996dc2ce600SShenghang Tsai   }
1997dc2ce600SShenghang Tsai 
199863d16d06SMike Urbach   mlirOperationDestroy(op);
19995b303f21Smax   mlirOperationDestroy(op2);
2000fd527cefSmax   mlirOperationDestroy(constZero);
2001fd527cefSmax   mlirOperationDestroy(constOne);
20025b303f21Smax   mlirOperationDestroy(constTwo);
200363d16d06SMike Urbach   mlirContextDestroy(ctx);
200463d16d06SMike Urbach 
200563d16d06SMike Urbach   return 0;
200663d16d06SMike Urbach }
200763d16d06SMike Urbach 
2008d3e6c2ddSGeorge /// Tests clone APIs.
20095d91f79fSTom Eccles int testClone(void) {
2010d3e6c2ddSGeorge   fprintf(stderr, "@testClone\n");
2011d3e6c2ddSGeorge   // CHECK-LABEL: @testClone
2012d3e6c2ddSGeorge 
2013d3e6c2ddSGeorge   MlirContext ctx = mlirContextCreate();
20145e83a5b4SStella Laurenzo   registerAllUpstreamDialects(ctx);
20155e83a5b4SStella Laurenzo 
201623aa5a74SRiver Riddle   mlirContextGetOrLoadDialect(ctx, mlirStringRefCreateFromCString("func"));
2017a5ef51d7SRiver Riddle   mlirContextGetOrLoadDialect(ctx, mlirStringRefCreateFromCString("arith"));
2018fd527cefSmax   MlirLocation loc = mlirLocationUnknownGet(ctx);
2019fd527cefSmax   MlirType indexType = mlirIndexTypeGet(ctx);
2020d3e6c2ddSGeorge   MlirStringRef valueStringRef = mlirStringRefCreateFromCString("value");
2021d3e6c2ddSGeorge 
2022fd527cefSmax   MlirAttribute indexZeroLiteral =
2023fd527cefSmax       mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("0 : index"));
2024fd527cefSmax   MlirNamedAttribute indexZeroValueAttr = mlirNamedAttributeGet(
2025fd527cefSmax       mlirIdentifierGet(ctx, valueStringRef), indexZeroLiteral);
2026fd527cefSmax   MlirOperationState constZeroState = mlirOperationStateGet(
2027fd527cefSmax       mlirStringRefCreateFromCString("arith.constant"), loc);
2028fd527cefSmax   mlirOperationStateAddResults(&constZeroState, 1, &indexType);
2029fd527cefSmax   mlirOperationStateAddAttributes(&constZeroState, 1, &indexZeroValueAttr);
2030fd527cefSmax   MlirOperation constZero = mlirOperationCreate(&constZeroState);
2031d3e6c2ddSGeorge 
2032d3e6c2ddSGeorge   MlirAttribute indexOneLiteral =
2033d3e6c2ddSGeorge       mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("1 : index"));
2034d3e6c2ddSGeorge   MlirOperation constOne = mlirOperationClone(constZero);
2035d3e6c2ddSGeorge   mlirOperationSetAttributeByName(constOne, valueStringRef, indexOneLiteral);
2036d3e6c2ddSGeorge 
2037d3e6c2ddSGeorge   mlirOperationPrint(constZero, printToStderr, NULL);
2038d3e6c2ddSGeorge   mlirOperationPrint(constOne, printToStderr, NULL);
2039a54f4eaeSMogball   // CHECK: arith.constant 0 : index
2040a54f4eaeSMogball   // CHECK: arith.constant 1 : index
2041d3e6c2ddSGeorge 
2042237d18a6SMehdi Amini   mlirOperationDestroy(constZero);
2043237d18a6SMehdi Amini   mlirOperationDestroy(constOne);
2044237d18a6SMehdi Amini   mlirContextDestroy(ctx);
2045d3e6c2ddSGeorge   return 0;
2046d3e6c2ddSGeorge }
2047d3e6c2ddSGeorge 
20487b5dfb40SAlex Zinenko // Wraps a diagnostic into additional text we can match against.
20490c5cff30SGeorge MlirLogicalResult errorHandler(MlirDiagnostic diagnostic, void *userData) {
205009b5ebc0SMarkus Böck   fprintf(stderr, "processing diagnostic (userData: %" PRIdPTR ") <<\n",
205109b5ebc0SMarkus Böck           (intptr_t)userData);
20527b5dfb40SAlex Zinenko   mlirDiagnosticPrint(diagnostic, printToStderr, NULL);
20537b5dfb40SAlex Zinenko   fprintf(stderr, "\n");
20547b5dfb40SAlex Zinenko   MlirLocation loc = mlirDiagnosticGetLocation(diagnostic);
20557b5dfb40SAlex Zinenko   mlirLocationPrint(loc, printToStderr, NULL);
20567b5dfb40SAlex Zinenko   assert(mlirDiagnosticGetNumNotes(diagnostic) == 0);
205709b5ebc0SMarkus Böck   fprintf(stderr, "\n>> end of diagnostic (userData: %" PRIdPTR ")\n",
205809b5ebc0SMarkus Böck           (intptr_t)userData);
20597b5dfb40SAlex Zinenko   return mlirLogicalResultSuccess();
20607b5dfb40SAlex Zinenko }
20617b5dfb40SAlex Zinenko 
20620c5cff30SGeorge // Logs when the delete user data callback is called
20630c5cff30SGeorge static void deleteUserData(void *userData) {
206409b5ebc0SMarkus Böck   fprintf(stderr, "deleting user data (userData: %" PRIdPTR ")\n",
206509b5ebc0SMarkus Böck           (intptr_t)userData);
20660c5cff30SGeorge }
20670c5cff30SGeorge 
2068782a97a9SDaniel Resnick int testTypeID(MlirContext ctx) {
2069782a97a9SDaniel Resnick   fprintf(stderr, "@testTypeID\n");
2070782a97a9SDaniel Resnick 
2071782a97a9SDaniel Resnick   // Test getting and comparing type and attribute type ids.
2072782a97a9SDaniel Resnick   MlirType i32 = mlirIntegerTypeGet(ctx, 32);
2073782a97a9SDaniel Resnick   MlirTypeID i32ID = mlirTypeGetTypeID(i32);
2074782a97a9SDaniel Resnick   MlirType ui32 = mlirIntegerTypeUnsignedGet(ctx, 32);
2075782a97a9SDaniel Resnick   MlirTypeID ui32ID = mlirTypeGetTypeID(ui32);
2076782a97a9SDaniel Resnick   MlirType f32 = mlirF32TypeGet(ctx);
2077782a97a9SDaniel Resnick   MlirTypeID f32ID = mlirTypeGetTypeID(f32);
2078782a97a9SDaniel Resnick   MlirAttribute i32Attr = mlirIntegerAttrGet(i32, 1);
2079782a97a9SDaniel Resnick   MlirTypeID i32AttrID = mlirAttributeGetTypeID(i32Attr);
2080782a97a9SDaniel Resnick 
2081782a97a9SDaniel Resnick   if (mlirTypeIDIsNull(i32ID) || mlirTypeIDIsNull(ui32ID) ||
2082782a97a9SDaniel Resnick       mlirTypeIDIsNull(f32ID) || mlirTypeIDIsNull(i32AttrID)) {
2083782a97a9SDaniel Resnick     fprintf(stderr, "ERROR: Expected type ids to be present\n");
2084782a97a9SDaniel Resnick     return 1;
2085782a97a9SDaniel Resnick   }
2086782a97a9SDaniel Resnick 
2087782a97a9SDaniel Resnick   if (!mlirTypeIDEqual(i32ID, ui32ID) ||
2088782a97a9SDaniel Resnick       mlirTypeIDHashValue(i32ID) != mlirTypeIDHashValue(ui32ID)) {
2089782a97a9SDaniel Resnick     fprintf(
2090782a97a9SDaniel Resnick         stderr,
2091782a97a9SDaniel Resnick         "ERROR: Expected different integer types to have the same type id\n");
2092782a97a9SDaniel Resnick     return 2;
2093782a97a9SDaniel Resnick   }
2094782a97a9SDaniel Resnick 
20955e50dd04SRiver Riddle   if (mlirTypeIDEqual(i32ID, f32ID)) {
2096782a97a9SDaniel Resnick     fprintf(stderr,
2097782a97a9SDaniel Resnick             "ERROR: Expected integer type id to not equal float type id\n");
2098782a97a9SDaniel Resnick     return 3;
2099782a97a9SDaniel Resnick   }
2100782a97a9SDaniel Resnick 
21015e50dd04SRiver Riddle   if (mlirTypeIDEqual(i32ID, i32AttrID)) {
2102782a97a9SDaniel Resnick     fprintf(stderr, "ERROR: Expected integer type id to not equal integer "
2103782a97a9SDaniel Resnick                     "attribute type id\n");
2104782a97a9SDaniel Resnick     return 4;
2105782a97a9SDaniel Resnick   }
2106782a97a9SDaniel Resnick 
2107782a97a9SDaniel Resnick   MlirLocation loc = mlirLocationUnknownGet(ctx);
2108fd527cefSmax   MlirType indexType = mlirIndexTypeGet(ctx);
2109fd527cefSmax   MlirStringRef valueStringRef = mlirStringRefCreateFromCString("value");
2110782a97a9SDaniel Resnick 
2111782a97a9SDaniel Resnick   // Create a registered operation, which should have a type id.
2112fd527cefSmax   MlirAttribute indexZeroLiteral =
2113fd527cefSmax       mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("0 : index"));
2114fd527cefSmax   MlirNamedAttribute indexZeroValueAttr = mlirNamedAttributeGet(
2115fd527cefSmax       mlirIdentifierGet(ctx, valueStringRef), indexZeroLiteral);
2116fd527cefSmax   MlirOperationState constZeroState = mlirOperationStateGet(
2117fd527cefSmax       mlirStringRefCreateFromCString("arith.constant"), loc);
2118fd527cefSmax   mlirOperationStateAddResults(&constZeroState, 1, &indexType);
2119fd527cefSmax   mlirOperationStateAddAttributes(&constZeroState, 1, &indexZeroValueAttr);
2120fd527cefSmax   MlirOperation constZero = mlirOperationCreate(&constZeroState);
2121782a97a9SDaniel Resnick 
2122cb3aa49eSMogball   if (!mlirOperationVerify(constZero)) {
2123cb3aa49eSMogball     fprintf(stderr, "ERROR: Expected operation to verify correctly\n");
2124cb3aa49eSMogball     return 5;
2125cb3aa49eSMogball   }
2126cb3aa49eSMogball 
2127782a97a9SDaniel Resnick   if (mlirOperationIsNull(constZero)) {
2128782a97a9SDaniel Resnick     fprintf(stderr, "ERROR: Expected registered operation to be present\n");
2129cb3aa49eSMogball     return 6;
2130782a97a9SDaniel Resnick   }
2131782a97a9SDaniel Resnick 
2132782a97a9SDaniel Resnick   MlirTypeID registeredOpID = mlirOperationGetTypeID(constZero);
2133782a97a9SDaniel Resnick 
2134782a97a9SDaniel Resnick   if (mlirTypeIDIsNull(registeredOpID)) {
2135782a97a9SDaniel Resnick     fprintf(stderr,
2136782a97a9SDaniel Resnick             "ERROR: Expected registered operation type id to be present\n");
2137cb3aa49eSMogball     return 7;
2138782a97a9SDaniel Resnick   }
2139782a97a9SDaniel Resnick 
2140782a97a9SDaniel Resnick   // Create an unregistered operation, which should not have a type id.
2141782a97a9SDaniel Resnick   mlirContextSetAllowUnregisteredDialects(ctx, true);
2142782a97a9SDaniel Resnick   MlirOperationState opState =
2143782a97a9SDaniel Resnick       mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op"), loc);
2144782a97a9SDaniel Resnick   MlirOperation unregisteredOp = mlirOperationCreate(&opState);
2145782a97a9SDaniel Resnick   if (mlirOperationIsNull(unregisteredOp)) {
2146782a97a9SDaniel Resnick     fprintf(stderr, "ERROR: Expected unregistered operation to be present\n");
2147cb3aa49eSMogball     return 8;
2148782a97a9SDaniel Resnick   }
2149782a97a9SDaniel Resnick 
2150782a97a9SDaniel Resnick   MlirTypeID unregisteredOpID = mlirOperationGetTypeID(unregisteredOp);
2151782a97a9SDaniel Resnick 
2152782a97a9SDaniel Resnick   if (!mlirTypeIDIsNull(unregisteredOpID)) {
2153782a97a9SDaniel Resnick     fprintf(stderr,
2154782a97a9SDaniel Resnick             "ERROR: Expected unregistered operation type id to be null\n");
2155cb3aa49eSMogball     return 9;
2156782a97a9SDaniel Resnick   }
2157782a97a9SDaniel Resnick 
2158782a97a9SDaniel Resnick   mlirOperationDestroy(constZero);
2159782a97a9SDaniel Resnick   mlirOperationDestroy(unregisteredOp);
2160782a97a9SDaniel Resnick 
2161782a97a9SDaniel Resnick   return 0;
2162782a97a9SDaniel Resnick }
2163782a97a9SDaniel Resnick 
216430d61893SAlex Zinenko int testSymbolTable(MlirContext ctx) {
216530d61893SAlex Zinenko   fprintf(stderr, "@testSymbolTable\n");
216630d61893SAlex Zinenko 
2167a8308020SRiver Riddle   const char *moduleString = "func.func private @foo()"
2168a8308020SRiver Riddle                              "func.func private @bar()";
2169a8308020SRiver Riddle   const char *otherModuleString = "func.func private @qux()"
2170a8308020SRiver Riddle                                   "func.func private @foo()";
217130d61893SAlex Zinenko 
217230d61893SAlex Zinenko   MlirModule module =
217330d61893SAlex Zinenko       mlirModuleCreateParse(ctx, mlirStringRefCreateFromCString(moduleString));
217430d61893SAlex Zinenko   MlirModule otherModule = mlirModuleCreateParse(
217530d61893SAlex Zinenko       ctx, mlirStringRefCreateFromCString(otherModuleString));
217630d61893SAlex Zinenko 
217730d61893SAlex Zinenko   MlirSymbolTable symbolTable =
217830d61893SAlex Zinenko       mlirSymbolTableCreate(mlirModuleGetOperation(module));
217930d61893SAlex Zinenko 
218030d61893SAlex Zinenko   MlirOperation funcFoo =
218130d61893SAlex Zinenko       mlirSymbolTableLookup(symbolTable, mlirStringRefCreateFromCString("foo"));
218230d61893SAlex Zinenko   if (mlirOperationIsNull(funcFoo))
218330d61893SAlex Zinenko     return 1;
218430d61893SAlex Zinenko 
218530d61893SAlex Zinenko   MlirOperation funcBar =
218630d61893SAlex Zinenko       mlirSymbolTableLookup(symbolTable, mlirStringRefCreateFromCString("bar"));
218730d61893SAlex Zinenko   if (mlirOperationEqual(funcFoo, funcBar))
218830d61893SAlex Zinenko     return 2;
218930d61893SAlex Zinenko 
219030d61893SAlex Zinenko   MlirOperation missing =
219130d61893SAlex Zinenko       mlirSymbolTableLookup(symbolTable, mlirStringRefCreateFromCString("qux"));
219230d61893SAlex Zinenko   if (!mlirOperationIsNull(missing))
219330d61893SAlex Zinenko     return 3;
219430d61893SAlex Zinenko 
219530d61893SAlex Zinenko   MlirBlock moduleBody = mlirModuleGetBody(module);
219630d61893SAlex Zinenko   MlirBlock otherModuleBody = mlirModuleGetBody(otherModule);
219730d61893SAlex Zinenko   MlirOperation operation = mlirBlockGetFirstOperation(otherModuleBody);
219830d61893SAlex Zinenko   mlirOperationRemoveFromParent(operation);
219930d61893SAlex Zinenko   mlirBlockAppendOwnedOperation(moduleBody, operation);
220030d61893SAlex Zinenko 
220130d61893SAlex Zinenko   // At this moment, the operation is still missing from the symbol table.
220230d61893SAlex Zinenko   MlirOperation stillMissing =
220330d61893SAlex Zinenko       mlirSymbolTableLookup(symbolTable, mlirStringRefCreateFromCString("qux"));
220430d61893SAlex Zinenko   if (!mlirOperationIsNull(stillMissing))
220530d61893SAlex Zinenko     return 4;
220630d61893SAlex Zinenko 
220730d61893SAlex Zinenko   // After it is added to the symbol table, and not only the operation with
220830d61893SAlex Zinenko   // which the table is associated, it can be looked up.
220930d61893SAlex Zinenko   mlirSymbolTableInsert(symbolTable, operation);
221030d61893SAlex Zinenko   MlirOperation funcQux =
221130d61893SAlex Zinenko       mlirSymbolTableLookup(symbolTable, mlirStringRefCreateFromCString("qux"));
221230d61893SAlex Zinenko   if (!mlirOperationEqual(operation, funcQux))
221330d61893SAlex Zinenko     return 5;
221430d61893SAlex Zinenko 
221530d61893SAlex Zinenko   // Erasing from the symbol table also removes the operation.
221630d61893SAlex Zinenko   mlirSymbolTableErase(symbolTable, funcBar);
221730d61893SAlex Zinenko   MlirOperation nowMissing =
221830d61893SAlex Zinenko       mlirSymbolTableLookup(symbolTable, mlirStringRefCreateFromCString("bar"));
221930d61893SAlex Zinenko   if (!mlirOperationIsNull(nowMissing))
222030d61893SAlex Zinenko     return 6;
222130d61893SAlex Zinenko 
222230d61893SAlex Zinenko   // Adding a symbol with the same name to the table should rename.
222330d61893SAlex Zinenko   MlirOperation duplicateNameOp = mlirBlockGetFirstOperation(otherModuleBody);
222430d61893SAlex Zinenko   mlirOperationRemoveFromParent(duplicateNameOp);
222530d61893SAlex Zinenko   mlirBlockAppendOwnedOperation(moduleBody, duplicateNameOp);
222630d61893SAlex Zinenko   MlirAttribute newName = mlirSymbolTableInsert(symbolTable, duplicateNameOp);
222730d61893SAlex Zinenko   MlirStringRef newNameStr = mlirStringAttrGetValue(newName);
222830d61893SAlex Zinenko   if (mlirStringRefEqual(newNameStr, mlirStringRefCreateFromCString("foo")))
222930d61893SAlex Zinenko     return 7;
223030d61893SAlex Zinenko   MlirAttribute updatedName = mlirOperationGetAttributeByName(
223130d61893SAlex Zinenko       duplicateNameOp, mlirSymbolTableGetSymbolAttributeName());
223230d61893SAlex Zinenko   if (!mlirAttributeEqual(updatedName, newName))
223330d61893SAlex Zinenko     return 8;
223430d61893SAlex Zinenko 
223530d61893SAlex Zinenko   mlirOperationDump(mlirModuleGetOperation(module));
223630d61893SAlex Zinenko   mlirOperationDump(mlirModuleGetOperation(otherModule));
223730d61893SAlex Zinenko   // clang-format off
223830d61893SAlex Zinenko   // CHECK-LABEL: @testSymbolTable
223930d61893SAlex Zinenko   // CHECK: module
224030d61893SAlex Zinenko   // CHECK:   func private @foo
224130d61893SAlex Zinenko   // CHECK:   func private @qux
224230d61893SAlex Zinenko   // CHECK:   func private @foo{{.+}}
224330d61893SAlex Zinenko   // CHECK: module
224430d61893SAlex Zinenko   // CHECK-NOT: @qux
224530d61893SAlex Zinenko   // CHECK-NOT: @foo
224630d61893SAlex Zinenko   // clang-format on
224730d61893SAlex Zinenko 
224830d61893SAlex Zinenko   mlirSymbolTableDestroy(symbolTable);
224930d61893SAlex Zinenko   mlirModuleDestroy(module);
225030d61893SAlex Zinenko   mlirModuleDestroy(otherModule);
225130d61893SAlex Zinenko 
225230d61893SAlex Zinenko   return 0;
225330d61893SAlex Zinenko }
225430d61893SAlex Zinenko 
2255bdc3e6cbSMaksim Levental typedef struct {
2256bdc3e6cbSMaksim Levental   const char *x;
2257bdc3e6cbSMaksim Levental } callBackData;
2258bdc3e6cbSMaksim Levental 
225947148832SHideto Ueno MlirWalkResult walkCallBack(MlirOperation op, void *rootOpVoid) {
2260bdc3e6cbSMaksim Levental   fprintf(stderr, "%s: %s\n", ((callBackData *)(rootOpVoid))->x,
2261bdc3e6cbSMaksim Levental           mlirIdentifierStr(mlirOperationGetName(op)).data);
226247148832SHideto Ueno   return MlirWalkResultAdvance;
226347148832SHideto Ueno }
226447148832SHideto Ueno 
226547148832SHideto Ueno MlirWalkResult walkCallBackTestWalkResult(MlirOperation op, void *rootOpVoid) {
226647148832SHideto Ueno   fprintf(stderr, "%s: %s\n", ((callBackData *)(rootOpVoid))->x,
226747148832SHideto Ueno           mlirIdentifierStr(mlirOperationGetName(op)).data);
226847148832SHideto Ueno   if (strcmp(mlirIdentifierStr(mlirOperationGetName(op)).data, "func.func") ==
226947148832SHideto Ueno       0)
227047148832SHideto Ueno     return MlirWalkResultSkip;
227147148832SHideto Ueno   if (strcmp(mlirIdentifierStr(mlirOperationGetName(op)).data, "arith.addi") ==
227247148832SHideto Ueno       0)
227347148832SHideto Ueno     return MlirWalkResultInterrupt;
227447148832SHideto Ueno   return MlirWalkResultAdvance;
2275bdc3e6cbSMaksim Levental }
2276bdc3e6cbSMaksim Levental 
2277bdc3e6cbSMaksim Levental int testOperationWalk(MlirContext ctx) {
2278bdc3e6cbSMaksim Levental   // CHECK-LABEL: @testOperationWalk
2279bdc3e6cbSMaksim Levental   fprintf(stderr, "@testOperationWalk\n");
2280bdc3e6cbSMaksim Levental 
2281bdc3e6cbSMaksim Levental   const char *moduleString = "module {\n"
2282bdc3e6cbSMaksim Levental                              "  func.func @foo() {\n"
2283bdc3e6cbSMaksim Levental                              "    %1 = arith.constant 10: i32\n"
2284bdc3e6cbSMaksim Levental                              "    arith.addi %1, %1: i32\n"
2285bdc3e6cbSMaksim Levental                              "    return\n"
2286bdc3e6cbSMaksim Levental                              "  }\n"
228747148832SHideto Ueno                              "  func.func @bar() {\n"
228847148832SHideto Ueno                              "    return\n"
228947148832SHideto Ueno                              "  }\n"
2290bdc3e6cbSMaksim Levental                              "}";
2291bdc3e6cbSMaksim Levental   MlirModule module =
2292bdc3e6cbSMaksim Levental       mlirModuleCreateParse(ctx, mlirStringRefCreateFromCString(moduleString));
2293bdc3e6cbSMaksim Levental 
2294bdc3e6cbSMaksim Levental   callBackData data;
2295bdc3e6cbSMaksim Levental   data.x = "i love you";
2296bdc3e6cbSMaksim Levental 
229747148832SHideto Ueno   // CHECK-NEXT: i love you: arith.constant
229847148832SHideto Ueno   // CHECK-NEXT: i love you: arith.addi
229947148832SHideto Ueno   // CHECK-NEXT: i love you: func.return
230047148832SHideto Ueno   // CHECK-NEXT: i love you: func.func
230147148832SHideto Ueno   // CHECK-NEXT: i love you: func.return
230247148832SHideto Ueno   // CHECK-NEXT: i love you: func.func
230347148832SHideto Ueno   // CHECK-NEXT: i love you: builtin.module
2304bdc3e6cbSMaksim Levental   mlirOperationWalk(mlirModuleGetOperation(module), walkCallBack,
2305bdc3e6cbSMaksim Levental                     (void *)(&data), MlirWalkPostOrder);
2306bdc3e6cbSMaksim Levental 
2307bdc3e6cbSMaksim Levental   data.x = "i don't love you";
230847148832SHideto Ueno   // CHECK-NEXT: i don't love you: builtin.module
230947148832SHideto Ueno   // CHECK-NEXT: i don't love you: func.func
231047148832SHideto Ueno   // CHECK-NEXT: i don't love you: arith.constant
231147148832SHideto Ueno   // CHECK-NEXT: i don't love you: arith.addi
231247148832SHideto Ueno   // CHECK-NEXT: i don't love you: func.return
231347148832SHideto Ueno   // CHECK-NEXT: i don't love you: func.func
231447148832SHideto Ueno   // CHECK-NEXT: i don't love you: func.return
2315bdc3e6cbSMaksim Levental   mlirOperationWalk(mlirModuleGetOperation(module), walkCallBack,
2316bdc3e6cbSMaksim Levental                     (void *)(&data), MlirWalkPreOrder);
231747148832SHideto Ueno 
231847148832SHideto Ueno   data.x = "interrupt";
231947148832SHideto Ueno   // Interrupted at `arith.addi`
232047148832SHideto Ueno   // CHECK-NEXT: interrupt: arith.constant
232147148832SHideto Ueno   // CHECK-NEXT: interrupt: arith.addi
232247148832SHideto Ueno   mlirOperationWalk(mlirModuleGetOperation(module), walkCallBackTestWalkResult,
232347148832SHideto Ueno                     (void *)(&data), MlirWalkPostOrder);
232447148832SHideto Ueno 
232547148832SHideto Ueno   data.x = "skip";
232647148832SHideto Ueno   // Skip at `func.func`
232747148832SHideto Ueno   // CHECK-NEXT: skip: builtin.module
232847148832SHideto Ueno   // CHECK-NEXT: skip: func.func
232947148832SHideto Ueno   // CHECK-NEXT: skip: func.func
233047148832SHideto Ueno   mlirOperationWalk(mlirModuleGetOperation(module), walkCallBackTestWalkResult,
233147148832SHideto Ueno                     (void *)(&data), MlirWalkPreOrder);
233247148832SHideto Ueno 
2333d342843cSmax   mlirModuleDestroy(module);
2334bdc3e6cbSMaksim Levental   return 0;
2335bdc3e6cbSMaksim Levental }
2336bdc3e6cbSMaksim Levental 
23375d91f79fSTom Eccles int testDialectRegistry(void) {
233897fc5682SDaniel Resnick   fprintf(stderr, "@testDialectRegistry\n");
233997fc5682SDaniel Resnick 
234097fc5682SDaniel Resnick   MlirDialectRegistry registry = mlirDialectRegistryCreate();
234197fc5682SDaniel Resnick   if (mlirDialectRegistryIsNull(registry)) {
234297fc5682SDaniel Resnick     fprintf(stderr, "ERROR: Expected registry to be present\n");
234397fc5682SDaniel Resnick     return 1;
234497fc5682SDaniel Resnick   }
234597fc5682SDaniel Resnick 
234623aa5a74SRiver Riddle   MlirDialectHandle stdHandle = mlirGetDialectHandle__func__();
234797fc5682SDaniel Resnick   mlirDialectHandleInsertDialect(stdHandle, registry);
234897fc5682SDaniel Resnick 
234997fc5682SDaniel Resnick   MlirContext ctx = mlirContextCreate();
235097fc5682SDaniel Resnick   if (mlirContextGetNumRegisteredDialects(ctx) != 0) {
235197fc5682SDaniel Resnick     fprintf(stderr,
235297fc5682SDaniel Resnick             "ERROR: Expected no dialects to be registered to new context\n");
235397fc5682SDaniel Resnick   }
235497fc5682SDaniel Resnick 
235597fc5682SDaniel Resnick   mlirContextAppendDialectRegistry(ctx, registry);
235697fc5682SDaniel Resnick   if (mlirContextGetNumRegisteredDialects(ctx) != 1) {
235797fc5682SDaniel Resnick     fprintf(stderr, "ERROR: Expected the dialect in the registry to be "
235897fc5682SDaniel Resnick                     "registered to the context\n");
235997fc5682SDaniel Resnick   }
236097fc5682SDaniel Resnick 
236197fc5682SDaniel Resnick   mlirContextDestroy(ctx);
236297fc5682SDaniel Resnick   mlirDialectRegistryDestroy(registry);
236397fc5682SDaniel Resnick 
236497fc5682SDaniel Resnick   return 0;
236597fc5682SDaniel Resnick }
236697fc5682SDaniel Resnick 
2367d9e04b06SKrzysztof Drewniak void testExplicitThreadPools(void) {
2368d9e04b06SKrzysztof Drewniak   MlirLlvmThreadPool threadPool = mlirLlvmThreadPoolCreate();
2369d9e04b06SKrzysztof Drewniak   MlirDialectRegistry registry = mlirDialectRegistryCreate();
2370d9e04b06SKrzysztof Drewniak   mlirRegisterAllDialects(registry);
2371d9e04b06SKrzysztof Drewniak   MlirContext context =
2372d9e04b06SKrzysztof Drewniak       mlirContextCreateWithRegistry(registry, /*threadingEnabled=*/false);
2373d9e04b06SKrzysztof Drewniak   mlirContextSetThreadPool(context, threadPool);
2374d9e04b06SKrzysztof Drewniak   mlirContextDestroy(context);
2375d9e04b06SKrzysztof Drewniak   mlirDialectRegistryDestroy(registry);
2376d9e04b06SKrzysztof Drewniak   mlirLlvmThreadPoolDestroy(threadPool);
2377d9e04b06SKrzysztof Drewniak }
2378d9e04b06SKrzysztof Drewniak 
23795d91f79fSTom Eccles void testDiagnostics(void) {
238030d61893SAlex Zinenko   MlirContext ctx = mlirContextCreate();
238130d61893SAlex Zinenko   MlirDiagnosticHandlerID id = mlirContextAttachDiagnosticHandler(
238230d61893SAlex Zinenko       ctx, errorHandler, (void *)42, deleteUserData);
238330d61893SAlex Zinenko   fprintf(stderr, "@test_diagnostics\n");
238430d61893SAlex Zinenko   MlirLocation unknownLoc = mlirLocationUnknownGet(ctx);
238530d61893SAlex Zinenko   mlirEmitError(unknownLoc, "test diagnostics");
23867bfdac0eSAndrew Young   MlirAttribute unknownAttr = mlirLocationGetAttribute(unknownLoc);
23877bfdac0eSAndrew Young   MlirLocation unknownClone = mlirLocationFromAttribute(unknownAttr);
23887bfdac0eSAndrew Young   mlirEmitError(unknownClone, "test clone");
238930d61893SAlex Zinenko   MlirLocation fileLineColLoc = mlirLocationFileLineColGet(
239030d61893SAlex Zinenko       ctx, mlirStringRefCreateFromCString("file.c"), 1, 2);
239130d61893SAlex Zinenko   mlirEmitError(fileLineColLoc, "test diagnostics");
2392*a77250fdSJacques Pienaar   MlirLocation fileLineColRange = mlirLocationFileLineColRangeGet(
2393*a77250fdSJacques Pienaar       ctx, mlirStringRefCreateFromCString("other-file.c"), 1, 2, 3, 4);
2394*a77250fdSJacques Pienaar   mlirEmitError(fileLineColRange, "test diagnostics");
239530d61893SAlex Zinenko   MlirLocation callSiteLoc = mlirLocationCallSiteGet(
239630d61893SAlex Zinenko       mlirLocationFileLineColGet(
239730d61893SAlex Zinenko           ctx, mlirStringRefCreateFromCString("other-file.c"), 2, 3),
239830d61893SAlex Zinenko       fileLineColLoc);
239930d61893SAlex Zinenko   mlirEmitError(callSiteLoc, "test diagnostics");
240030d61893SAlex Zinenko   MlirLocation null = {0};
240130d61893SAlex Zinenko   MlirLocation nameLoc =
240230d61893SAlex Zinenko       mlirLocationNameGet(ctx, mlirStringRefCreateFromCString("named"), null);
240330d61893SAlex Zinenko   mlirEmitError(nameLoc, "test diagnostics");
240430d61893SAlex Zinenko   MlirLocation locs[2] = {nameLoc, callSiteLoc};
240530d61893SAlex Zinenko   MlirAttribute nullAttr = {0};
240630d61893SAlex Zinenko   MlirLocation fusedLoc = mlirLocationFusedGet(ctx, 2, locs, nullAttr);
240730d61893SAlex Zinenko   mlirEmitError(fusedLoc, "test diagnostics");
240830d61893SAlex Zinenko   mlirContextDetachDiagnosticHandler(ctx, id);
240930d61893SAlex Zinenko   mlirEmitError(unknownLoc, "more test diagnostics");
241030d61893SAlex Zinenko   // CHECK-LABEL: @test_diagnostics
241130d61893SAlex Zinenko   // CHECK: processing diagnostic (userData: 42) <<
241230d61893SAlex Zinenko   // CHECK:   test diagnostics
241330d61893SAlex Zinenko   // CHECK:   loc(unknown)
24147bfdac0eSAndrew Young   // CHECK: processing diagnostic (userData: 42) <<
24157bfdac0eSAndrew Young   // CHECK:   test clone
24167bfdac0eSAndrew Young   // CHECK:   loc(unknown)
241730d61893SAlex Zinenko   // CHECK: >> end of diagnostic (userData: 42)
241830d61893SAlex Zinenko   // CHECK: processing diagnostic (userData: 42) <<
241930d61893SAlex Zinenko   // CHECK:   test diagnostics
242030d61893SAlex Zinenko   // CHECK:   loc("file.c":1:2)
242130d61893SAlex Zinenko   // CHECK: >> end of diagnostic (userData: 42)
242230d61893SAlex Zinenko   // CHECK: processing diagnostic (userData: 42) <<
242330d61893SAlex Zinenko   // CHECK:   test diagnostics
2424*a77250fdSJacques Pienaar   // CHECK:   loc("other-file.c":1:2 to 3:4)
2425*a77250fdSJacques Pienaar   // CHECK: >> end of diagnostic (userData: 42)
2426*a77250fdSJacques Pienaar   // CHECK: processing diagnostic (userData: 42) <<
2427*a77250fdSJacques Pienaar   // CHECK:   test diagnostics
242830d61893SAlex Zinenko   // CHECK:   loc(callsite("other-file.c":2:3 at "file.c":1:2))
242930d61893SAlex Zinenko   // CHECK: >> end of diagnostic (userData: 42)
243030d61893SAlex Zinenko   // CHECK: processing diagnostic (userData: 42) <<
243130d61893SAlex Zinenko   // CHECK:   test diagnostics
243230d61893SAlex Zinenko   // CHECK:   loc("named")
243330d61893SAlex Zinenko   // CHECK: >> end of diagnostic (userData: 42)
243430d61893SAlex Zinenko   // CHECK: processing diagnostic (userData: 42) <<
243530d61893SAlex Zinenko   // CHECK:   test diagnostics
243630d61893SAlex Zinenko   // CHECK:   loc(fused["named", callsite("other-file.c":2:3 at "file.c":1:2)])
243730d61893SAlex Zinenko   // CHECK: deleting user data (userData: 42)
243830d61893SAlex Zinenko   // CHECK-NOT: processing diagnostic
243930d61893SAlex Zinenko   // CHECK:     more test diagnostics
244030d61893SAlex Zinenko   mlirContextDestroy(ctx);
244130d61893SAlex Zinenko }
244230d61893SAlex Zinenko 
24435d91f79fSTom Eccles int main(void) {
2444b715fa33SAlex Zinenko   MlirContext ctx = mlirContextCreate();
24455e83a5b4SStella Laurenzo   registerAllUpstreamDialects(ctx);
24465e83a5b4SStella Laurenzo   mlirContextGetOrLoadDialect(ctx, mlirStringRefCreateFromCString("func"));
24475e83a5b4SStella Laurenzo   mlirContextGetOrLoadDialect(ctx, mlirStringRefCreateFromCString("memref"));
24485e83a5b4SStella Laurenzo   mlirContextGetOrLoadDialect(ctx, mlirStringRefCreateFromCString("shape"));
24495e83a5b4SStella Laurenzo   mlirContextGetOrLoadDialect(ctx, mlirStringRefCreateFromCString("scf"));
24505e83a5b4SStella Laurenzo 
2451b715fa33SAlex Zinenko   if (constructAndTraverseIr(ctx))
2452b715fa33SAlex Zinenko     return 1;
2453b715fa33SAlex Zinenko   buildWithInsertionsAndPrint(ctx);
245452586c46SStella Laurenzo   if (createOperationWithTypeInference(ctx))
245552586c46SStella Laurenzo     return 2;
2456b715fa33SAlex Zinenko 
245709f7a55fSRiver Riddle   if (printBuiltinTypes(ctx))
2458b715fa33SAlex Zinenko     return 3;
245952586c46SStella Laurenzo   if (printBuiltinAttributes(ctx))
2460b715fa33SAlex Zinenko     return 4;
246152586c46SStella Laurenzo   if (printAffineMap(ctx))
2462b715fa33SAlex Zinenko     return 5;
246352586c46SStella Laurenzo   if (printAffineExpr(ctx))
2464b715fa33SAlex Zinenko     return 6;
246552586c46SStella Laurenzo   if (affineMapFromExprs(ctx))
2466e79bd0b4SAlex Zinenko     return 7;
2467f5c7c031SAlex Zinenko   if (printIntegerSet(ctx))
246852586c46SStella Laurenzo     return 8;
2469f5c7c031SAlex Zinenko   if (registerOnlyStd())
2470f5c7c031SAlex Zinenko     return 9;
24718f130f10SGeorge   if (testBackreferences())
24728f130f10SGeorge     return 10;
247363d16d06SMike Urbach   if (testOperands())
247463d16d06SMike Urbach     return 11;
2475d3e6c2ddSGeorge   if (testClone())
2476d3e6c2ddSGeorge     return 12;
247730d61893SAlex Zinenko   if (testTypeID(ctx))
2478782a97a9SDaniel Resnick     return 13;
247930d61893SAlex Zinenko   if (testSymbolTable(ctx))
248030d61893SAlex Zinenko     return 14;
248197fc5682SDaniel Resnick   if (testDialectRegistry())
248297fc5682SDaniel Resnick     return 15;
2483bdc3e6cbSMaksim Levental   if (testOperationWalk(ctx))
2484bdc3e6cbSMaksim Levental     return 16;
2485b715fa33SAlex Zinenko 
2486d9e04b06SKrzysztof Drewniak   testExplicitThreadPools();
2487b715fa33SAlex Zinenko   testDiagnostics();
2488f66cd9e9SStella Laurenzo 
2489f66cd9e9SStella Laurenzo   // CHECK: DESTROY MAIN CONTEXT
2490f66cd9e9SStella Laurenzo   // CHECK: reportResourceDelete: resource_i64_blob
2491f66cd9e9SStella Laurenzo   fprintf(stderr, "DESTROY MAIN CONTEXT\n");
2492f66cd9e9SStella Laurenzo   mlirContextDestroy(ctx);
2493f66cd9e9SStella Laurenzo 
249475f239e9SAlex Zinenko   return 0;
249575f239e9SAlex Zinenko }
2496