xref: /llvm-project-15.0.7/mlir/test/CAPI/ir.c (revision 2232d35f)
1 //===- ir.c - Simple test of C APIs ---------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM
4 // Exceptions.
5 // See https://llvm.org/LICENSE.txt for license information.
6 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //
8 //===----------------------------------------------------------------------===//
9 
10 /* RUN: mlir-capi-ir-test 2>&1 | FileCheck %s
11  */
12 
13 #include "mlir-c/IR.h"
14 #include "mlir-c/AffineExpr.h"
15 #include "mlir-c/AffineMap.h"
16 #include "mlir-c/BuiltinAttributes.h"
17 #include "mlir-c/BuiltinTypes.h"
18 #include "mlir-c/Diagnostics.h"
19 #include "mlir-c/Dialect/Func.h"
20 #include "mlir-c/IntegerSet.h"
21 #include "mlir-c/Registration.h"
22 #include "mlir-c/Support.h"
23 
24 #include <assert.h>
25 #include <inttypes.h>
26 #include <math.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 
31 void populateLoopBody(MlirContext ctx, MlirBlock loopBody,
32                       MlirLocation location, MlirBlock funcBody) {
33   MlirValue iv = mlirBlockGetArgument(loopBody, 0);
34   MlirValue funcArg0 = mlirBlockGetArgument(funcBody, 0);
35   MlirValue funcArg1 = mlirBlockGetArgument(funcBody, 1);
36   MlirType f32Type =
37       mlirTypeParseGet(ctx, mlirStringRefCreateFromCString("f32"));
38 
39   MlirOperationState loadLHSState = mlirOperationStateGet(
40       mlirStringRefCreateFromCString("memref.load"), location);
41   MlirValue loadLHSOperands[] = {funcArg0, iv};
42   mlirOperationStateAddOperands(&loadLHSState, 2, loadLHSOperands);
43   mlirOperationStateAddResults(&loadLHSState, 1, &f32Type);
44   MlirOperation loadLHS = mlirOperationCreate(&loadLHSState);
45   mlirBlockAppendOwnedOperation(loopBody, loadLHS);
46 
47   MlirOperationState loadRHSState = mlirOperationStateGet(
48       mlirStringRefCreateFromCString("memref.load"), location);
49   MlirValue loadRHSOperands[] = {funcArg1, iv};
50   mlirOperationStateAddOperands(&loadRHSState, 2, loadRHSOperands);
51   mlirOperationStateAddResults(&loadRHSState, 1, &f32Type);
52   MlirOperation loadRHS = mlirOperationCreate(&loadRHSState);
53   mlirBlockAppendOwnedOperation(loopBody, loadRHS);
54 
55   MlirOperationState addState = mlirOperationStateGet(
56       mlirStringRefCreateFromCString("arith.addf"), location);
57   MlirValue addOperands[] = {mlirOperationGetResult(loadLHS, 0),
58                              mlirOperationGetResult(loadRHS, 0)};
59   mlirOperationStateAddOperands(&addState, 2, addOperands);
60   mlirOperationStateAddResults(&addState, 1, &f32Type);
61   MlirOperation add = mlirOperationCreate(&addState);
62   mlirBlockAppendOwnedOperation(loopBody, add);
63 
64   MlirOperationState storeState = mlirOperationStateGet(
65       mlirStringRefCreateFromCString("memref.store"), location);
66   MlirValue storeOperands[] = {mlirOperationGetResult(add, 0), funcArg0, iv};
67   mlirOperationStateAddOperands(&storeState, 3, storeOperands);
68   MlirOperation store = mlirOperationCreate(&storeState);
69   mlirBlockAppendOwnedOperation(loopBody, store);
70 
71   MlirOperationState yieldState = mlirOperationStateGet(
72       mlirStringRefCreateFromCString("scf.yield"), location);
73   MlirOperation yield = mlirOperationCreate(&yieldState);
74   mlirBlockAppendOwnedOperation(loopBody, yield);
75 }
76 
77 MlirModule makeAndDumpAdd(MlirContext ctx, MlirLocation location) {
78   MlirModule moduleOp = mlirModuleCreateEmpty(location);
79   MlirBlock moduleBody = mlirModuleGetBody(moduleOp);
80 
81   MlirType memrefType =
82       mlirTypeParseGet(ctx, mlirStringRefCreateFromCString("memref<?xf32>"));
83   MlirType funcBodyArgTypes[] = {memrefType, memrefType};
84   MlirLocation funcBodyArgLocs[] = {location, location};
85   MlirRegion funcBodyRegion = mlirRegionCreate();
86   MlirBlock funcBody =
87       mlirBlockCreate(sizeof(funcBodyArgTypes) / sizeof(MlirType),
88                       funcBodyArgTypes, funcBodyArgLocs);
89   mlirRegionAppendOwnedBlock(funcBodyRegion, funcBody);
90 
91   MlirAttribute funcTypeAttr = mlirAttributeParseGet(
92       ctx,
93       mlirStringRefCreateFromCString("(memref<?xf32>, memref<?xf32>) -> ()"));
94   MlirAttribute funcNameAttr =
95       mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("\"add\""));
96   MlirNamedAttribute funcAttrs[] = {
97       mlirNamedAttributeGet(
98           mlirIdentifierGet(ctx,
99                             mlirStringRefCreateFromCString("function_type")),
100           funcTypeAttr),
101       mlirNamedAttributeGet(
102           mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("sym_name")),
103           funcNameAttr)};
104   MlirOperationState funcState = mlirOperationStateGet(
105       mlirStringRefCreateFromCString("func.func"), location);
106   mlirOperationStateAddAttributes(&funcState, 2, funcAttrs);
107   mlirOperationStateAddOwnedRegions(&funcState, 1, &funcBodyRegion);
108   MlirOperation func = mlirOperationCreate(&funcState);
109   mlirBlockInsertOwnedOperation(moduleBody, 0, func);
110 
111   MlirType indexType =
112       mlirTypeParseGet(ctx, mlirStringRefCreateFromCString("index"));
113   MlirAttribute indexZeroLiteral =
114       mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("0 : index"));
115   MlirNamedAttribute indexZeroValueAttr = mlirNamedAttributeGet(
116       mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("value")),
117       indexZeroLiteral);
118   MlirOperationState constZeroState = mlirOperationStateGet(
119       mlirStringRefCreateFromCString("arith.constant"), location);
120   mlirOperationStateAddResults(&constZeroState, 1, &indexType);
121   mlirOperationStateAddAttributes(&constZeroState, 1, &indexZeroValueAttr);
122   MlirOperation constZero = mlirOperationCreate(&constZeroState);
123   mlirBlockAppendOwnedOperation(funcBody, constZero);
124 
125   MlirValue funcArg0 = mlirBlockGetArgument(funcBody, 0);
126   MlirValue constZeroValue = mlirOperationGetResult(constZero, 0);
127   MlirValue dimOperands[] = {funcArg0, constZeroValue};
128   MlirOperationState dimState = mlirOperationStateGet(
129       mlirStringRefCreateFromCString("memref.dim"), location);
130   mlirOperationStateAddOperands(&dimState, 2, dimOperands);
131   mlirOperationStateAddResults(&dimState, 1, &indexType);
132   MlirOperation dim = mlirOperationCreate(&dimState);
133   mlirBlockAppendOwnedOperation(funcBody, dim);
134 
135   MlirRegion loopBodyRegion = mlirRegionCreate();
136   MlirBlock loopBody = mlirBlockCreate(0, NULL, NULL);
137   mlirBlockAddArgument(loopBody, indexType, location);
138   mlirRegionAppendOwnedBlock(loopBodyRegion, loopBody);
139 
140   MlirAttribute indexOneLiteral =
141       mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("1 : index"));
142   MlirNamedAttribute indexOneValueAttr = mlirNamedAttributeGet(
143       mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("value")),
144       indexOneLiteral);
145   MlirOperationState constOneState = mlirOperationStateGet(
146       mlirStringRefCreateFromCString("arith.constant"), location);
147   mlirOperationStateAddResults(&constOneState, 1, &indexType);
148   mlirOperationStateAddAttributes(&constOneState, 1, &indexOneValueAttr);
149   MlirOperation constOne = mlirOperationCreate(&constOneState);
150   mlirBlockAppendOwnedOperation(funcBody, constOne);
151 
152   MlirValue dimValue = mlirOperationGetResult(dim, 0);
153   MlirValue constOneValue = mlirOperationGetResult(constOne, 0);
154   MlirValue loopOperands[] = {constZeroValue, dimValue, constOneValue};
155   MlirOperationState loopState = mlirOperationStateGet(
156       mlirStringRefCreateFromCString("scf.for"), location);
157   mlirOperationStateAddOperands(&loopState, 3, loopOperands);
158   mlirOperationStateAddOwnedRegions(&loopState, 1, &loopBodyRegion);
159   MlirOperation loop = mlirOperationCreate(&loopState);
160   mlirBlockAppendOwnedOperation(funcBody, loop);
161 
162   populateLoopBody(ctx, loopBody, location, funcBody);
163 
164   MlirOperationState retState = mlirOperationStateGet(
165       mlirStringRefCreateFromCString("func.return"), location);
166   MlirOperation ret = mlirOperationCreate(&retState);
167   mlirBlockAppendOwnedOperation(funcBody, ret);
168 
169   MlirOperation module = mlirModuleGetOperation(moduleOp);
170   mlirOperationDump(module);
171   // clang-format off
172   // CHECK: module {
173   // CHECK:   func @add(%[[ARG0:.*]]: memref<?xf32>, %[[ARG1:.*]]: memref<?xf32>) {
174   // CHECK:     %[[C0:.*]] = arith.constant 0 : index
175   // CHECK:     %[[DIM:.*]] = memref.dim %[[ARG0]], %[[C0]] : memref<?xf32>
176   // CHECK:     %[[C1:.*]] = arith.constant 1 : index
177   // CHECK:     scf.for %[[I:.*]] = %[[C0]] to %[[DIM]] step %[[C1]] {
178   // CHECK:       %[[LHS:.*]] = memref.load %[[ARG0]][%[[I]]] : memref<?xf32>
179   // CHECK:       %[[RHS:.*]] = memref.load %[[ARG1]][%[[I]]] : memref<?xf32>
180   // CHECK:       %[[SUM:.*]] = arith.addf %[[LHS]], %[[RHS]] : f32
181   // CHECK:       memref.store %[[SUM]], %[[ARG0]][%[[I]]] : memref<?xf32>
182   // CHECK:     }
183   // CHECK:     return
184   // CHECK:   }
185   // CHECK: }
186   // clang-format on
187 
188   return moduleOp;
189 }
190 
191 struct OpListNode {
192   MlirOperation op;
193   struct OpListNode *next;
194 };
195 typedef struct OpListNode OpListNode;
196 
197 struct ModuleStats {
198   unsigned numOperations;
199   unsigned numAttributes;
200   unsigned numBlocks;
201   unsigned numRegions;
202   unsigned numValues;
203   unsigned numBlockArguments;
204   unsigned numOpResults;
205 };
206 typedef struct ModuleStats ModuleStats;
207 
208 int collectStatsSingle(OpListNode *head, ModuleStats *stats) {
209   MlirOperation operation = head->op;
210   stats->numOperations += 1;
211   stats->numValues += mlirOperationGetNumResults(operation);
212   stats->numAttributes += mlirOperationGetNumAttributes(operation);
213 
214   unsigned numRegions = mlirOperationGetNumRegions(operation);
215 
216   stats->numRegions += numRegions;
217 
218   intptr_t numResults = mlirOperationGetNumResults(operation);
219   for (intptr_t i = 0; i < numResults; ++i) {
220     MlirValue result = mlirOperationGetResult(operation, i);
221     if (!mlirValueIsAOpResult(result))
222       return 1;
223     if (mlirValueIsABlockArgument(result))
224       return 2;
225     if (!mlirOperationEqual(operation, mlirOpResultGetOwner(result)))
226       return 3;
227     if (i != mlirOpResultGetResultNumber(result))
228       return 4;
229     ++stats->numOpResults;
230   }
231 
232   MlirRegion region = mlirOperationGetFirstRegion(operation);
233   while (!mlirRegionIsNull(region)) {
234     for (MlirBlock block = mlirRegionGetFirstBlock(region);
235          !mlirBlockIsNull(block); block = mlirBlockGetNextInRegion(block)) {
236       ++stats->numBlocks;
237       intptr_t numArgs = mlirBlockGetNumArguments(block);
238       stats->numValues += numArgs;
239       for (intptr_t j = 0; j < numArgs; ++j) {
240         MlirValue arg = mlirBlockGetArgument(block, j);
241         if (!mlirValueIsABlockArgument(arg))
242           return 5;
243         if (mlirValueIsAOpResult(arg))
244           return 6;
245         if (!mlirBlockEqual(block, mlirBlockArgumentGetOwner(arg)))
246           return 7;
247         if (j != mlirBlockArgumentGetArgNumber(arg))
248           return 8;
249         ++stats->numBlockArguments;
250       }
251 
252       for (MlirOperation child = mlirBlockGetFirstOperation(block);
253            !mlirOperationIsNull(child);
254            child = mlirOperationGetNextInBlock(child)) {
255         OpListNode *node = malloc(sizeof(OpListNode));
256         node->op = child;
257         node->next = head->next;
258         head->next = node;
259       }
260     }
261     region = mlirRegionGetNextInOperation(region);
262   }
263   return 0;
264 }
265 
266 int collectStats(MlirOperation operation) {
267   OpListNode *head = malloc(sizeof(OpListNode));
268   head->op = operation;
269   head->next = NULL;
270 
271   ModuleStats stats;
272   stats.numOperations = 0;
273   stats.numAttributes = 0;
274   stats.numBlocks = 0;
275   stats.numRegions = 0;
276   stats.numValues = 0;
277   stats.numBlockArguments = 0;
278   stats.numOpResults = 0;
279 
280   do {
281     int retval = collectStatsSingle(head, &stats);
282     if (retval) {
283       free(head);
284       return retval;
285     }
286     OpListNode *next = head->next;
287     free(head);
288     head = next;
289   } while (head);
290 
291   if (stats.numValues != stats.numBlockArguments + stats.numOpResults)
292     return 100;
293 
294   fprintf(stderr, "@stats\n");
295   fprintf(stderr, "Number of operations: %u\n", stats.numOperations);
296   fprintf(stderr, "Number of attributes: %u\n", stats.numAttributes);
297   fprintf(stderr, "Number of blocks: %u\n", stats.numBlocks);
298   fprintf(stderr, "Number of regions: %u\n", stats.numRegions);
299   fprintf(stderr, "Number of values: %u\n", stats.numValues);
300   fprintf(stderr, "Number of block arguments: %u\n", stats.numBlockArguments);
301   fprintf(stderr, "Number of op results: %u\n", stats.numOpResults);
302   // clang-format off
303   // CHECK-LABEL: @stats
304   // CHECK: Number of operations: 12
305   // CHECK: Number of attributes: 4
306   // CHECK: Number of blocks: 3
307   // CHECK: Number of regions: 3
308   // CHECK: Number of values: 9
309   // CHECK: Number of block arguments: 3
310   // CHECK: Number of op results: 6
311   // clang-format on
312   return 0;
313 }
314 
315 static void printToStderr(MlirStringRef str, void *userData) {
316   (void)userData;
317   fwrite(str.data, 1, str.length, stderr);
318 }
319 
320 static void printFirstOfEach(MlirContext ctx, MlirOperation operation) {
321   // Assuming we are given a module, go to the first operation of the first
322   // function.
323   MlirRegion region = mlirOperationGetRegion(operation, 0);
324   MlirBlock block = mlirRegionGetFirstBlock(region);
325   operation = mlirBlockGetFirstOperation(block);
326   region = mlirOperationGetRegion(operation, 0);
327   MlirOperation parentOperation = operation;
328   block = mlirRegionGetFirstBlock(region);
329   operation = mlirBlockGetFirstOperation(block);
330   assert(mlirModuleIsNull(mlirModuleFromOperation(operation)));
331 
332   // Verify that parent operation and block report correctly.
333   // CHECK: Parent operation eq: 1
334   fprintf(stderr, "Parent operation eq: %d\n",
335           mlirOperationEqual(mlirOperationGetParentOperation(operation),
336                              parentOperation));
337   // CHECK: Block eq: 1
338   fprintf(stderr, "Block eq: %d\n",
339           mlirBlockEqual(mlirOperationGetBlock(operation), block));
340   // CHECK: Block parent operation eq: 1
341   fprintf(
342       stderr, "Block parent operation eq: %d\n",
343       mlirOperationEqual(mlirBlockGetParentOperation(block), parentOperation));
344   // CHECK: Block parent region eq: 1
345   fprintf(stderr, "Block parent region eq: %d\n",
346           mlirRegionEqual(mlirBlockGetParentRegion(block), region));
347 
348   // In the module we created, the first operation of the first function is
349   // an "memref.dim", which has an attribute and a single result that we can
350   // use to test the printing mechanism.
351   mlirBlockPrint(block, printToStderr, NULL);
352   fprintf(stderr, "\n");
353   fprintf(stderr, "First operation: ");
354   mlirOperationPrint(operation, printToStderr, NULL);
355   fprintf(stderr, "\n");
356   // clang-format off
357   // CHECK:   %[[C0:.*]] = arith.constant 0 : index
358   // CHECK:   %[[DIM:.*]] = memref.dim %{{.*}}, %[[C0]] : memref<?xf32>
359   // CHECK:   %[[C1:.*]] = arith.constant 1 : index
360   // CHECK:   scf.for %[[I:.*]] = %[[C0]] to %[[DIM]] step %[[C1]] {
361   // CHECK:     %[[LHS:.*]] = memref.load %{{.*}}[%[[I]]] : memref<?xf32>
362   // CHECK:     %[[RHS:.*]] = memref.load %{{.*}}[%[[I]]] : memref<?xf32>
363   // CHECK:     %[[SUM:.*]] = arith.addf %[[LHS]], %[[RHS]] : f32
364   // CHECK:     memref.store %[[SUM]], %{{.*}}[%[[I]]] : memref<?xf32>
365   // CHECK:   }
366   // CHECK: return
367   // CHECK: First operation: {{.*}} = arith.constant 0 : index
368   // clang-format on
369 
370   // Get the operation name and print it.
371   MlirIdentifier ident = mlirOperationGetName(operation);
372   MlirStringRef identStr = mlirIdentifierStr(ident);
373   fprintf(stderr, "Operation name: '");
374   for (size_t i = 0; i < identStr.length; ++i)
375     fputc(identStr.data[i], stderr);
376   fprintf(stderr, "'\n");
377   // CHECK: Operation name: 'arith.constant'
378 
379   // Get the identifier again and verify equal.
380   MlirIdentifier identAgain = mlirIdentifierGet(ctx, identStr);
381   fprintf(stderr, "Identifier equal: %d\n",
382           mlirIdentifierEqual(ident, identAgain));
383   // CHECK: Identifier equal: 1
384 
385   // Get the block terminator and print it.
386   MlirOperation terminator = mlirBlockGetTerminator(block);
387   fprintf(stderr, "Terminator: ");
388   mlirOperationPrint(terminator, printToStderr, NULL);
389   fprintf(stderr, "\n");
390   // CHECK: Terminator: return
391 
392   // Get the attribute by index.
393   MlirNamedAttribute namedAttr0 = mlirOperationGetAttribute(operation, 0);
394   fprintf(stderr, "Get attr 0: ");
395   mlirAttributePrint(namedAttr0.attribute, printToStderr, NULL);
396   fprintf(stderr, "\n");
397   // CHECK: Get attr 0: 0 : index
398 
399   // Now re-get the attribute by name.
400   MlirAttribute attr0ByName = mlirOperationGetAttributeByName(
401       operation, mlirIdentifierStr(namedAttr0.name));
402   fprintf(stderr, "Get attr 0 by name: ");
403   mlirAttributePrint(attr0ByName, printToStderr, NULL);
404   fprintf(stderr, "\n");
405   // CHECK: Get attr 0 by name: 0 : index
406 
407   // Get a non-existing attribute and assert that it is null (sanity).
408   fprintf(stderr, "does_not_exist is null: %d\n",
409           mlirAttributeIsNull(mlirOperationGetAttributeByName(
410               operation, mlirStringRefCreateFromCString("does_not_exist"))));
411   // CHECK: does_not_exist is null: 1
412 
413   // Get result 0 and its type.
414   MlirValue value = mlirOperationGetResult(operation, 0);
415   fprintf(stderr, "Result 0: ");
416   mlirValuePrint(value, printToStderr, NULL);
417   fprintf(stderr, "\n");
418   fprintf(stderr, "Value is null: %d\n", mlirValueIsNull(value));
419   // CHECK: Result 0: {{.*}} = arith.constant 0 : index
420   // CHECK: Value is null: 0
421 
422   MlirType type = mlirValueGetType(value);
423   fprintf(stderr, "Result 0 type: ");
424   mlirTypePrint(type, printToStderr, NULL);
425   fprintf(stderr, "\n");
426   // CHECK: Result 0 type: index
427 
428   // Set a custom attribute.
429   mlirOperationSetAttributeByName(operation,
430                                   mlirStringRefCreateFromCString("custom_attr"),
431                                   mlirBoolAttrGet(ctx, 1));
432   fprintf(stderr, "Op with set attr: ");
433   mlirOperationPrint(operation, printToStderr, NULL);
434   fprintf(stderr, "\n");
435   // CHECK: Op with set attr: {{.*}} {custom_attr = true}
436 
437   // Remove the attribute.
438   fprintf(stderr, "Remove attr: %d\n",
439           mlirOperationRemoveAttributeByName(
440               operation, mlirStringRefCreateFromCString("custom_attr")));
441   fprintf(stderr, "Remove attr again: %d\n",
442           mlirOperationRemoveAttributeByName(
443               operation, mlirStringRefCreateFromCString("custom_attr")));
444   fprintf(stderr, "Removed attr is null: %d\n",
445           mlirAttributeIsNull(mlirOperationGetAttributeByName(
446               operation, mlirStringRefCreateFromCString("custom_attr"))));
447   // CHECK: Remove attr: 1
448   // CHECK: Remove attr again: 0
449   // CHECK: Removed attr is null: 1
450 
451   // Add a large attribute to verify printing flags.
452   int64_t eltsShape[] = {4};
453   int32_t eltsData[] = {1, 2, 3, 4};
454   mlirOperationSetAttributeByName(
455       operation, mlirStringRefCreateFromCString("elts"),
456       mlirDenseElementsAttrInt32Get(
457           mlirRankedTensorTypeGet(1, eltsShape, mlirIntegerTypeGet(ctx, 32),
458                                   mlirAttributeGetNull()),
459           4, eltsData));
460   MlirOpPrintingFlags flags = mlirOpPrintingFlagsCreate();
461   mlirOpPrintingFlagsElideLargeElementsAttrs(flags, 2);
462   mlirOpPrintingFlagsPrintGenericOpForm(flags);
463   mlirOpPrintingFlagsEnableDebugInfo(flags, /*prettyForm=*/0);
464   mlirOpPrintingFlagsUseLocalScope(flags);
465   fprintf(stderr, "Op print with all flags: ");
466   mlirOperationPrintWithFlags(operation, flags, printToStderr, NULL);
467   fprintf(stderr, "\n");
468   // clang-format off
469   // CHECK: Op print with all flags: %{{.*}} = "arith.constant"() {elts = opaque<"elided_large_const", "0xDEADBEEF"> : tensor<4xi32>, value = 0 : index} : () -> index loc(unknown)
470   // clang-format on
471 
472   mlirOpPrintingFlagsDestroy(flags);
473 }
474 
475 static int constructAndTraverseIr(MlirContext ctx) {
476   MlirLocation location = mlirLocationUnknownGet(ctx);
477 
478   MlirModule moduleOp = makeAndDumpAdd(ctx, location);
479   MlirOperation module = mlirModuleGetOperation(moduleOp);
480   assert(!mlirModuleIsNull(mlirModuleFromOperation(module)));
481 
482   int errcode = collectStats(module);
483   if (errcode)
484     return errcode;
485 
486   printFirstOfEach(ctx, module);
487 
488   mlirModuleDestroy(moduleOp);
489   return 0;
490 }
491 
492 /// Creates an operation with a region containing multiple blocks with
493 /// operations and dumps it. The blocks and operations are inserted using
494 /// block/operation-relative API and their final order is checked.
495 static void buildWithInsertionsAndPrint(MlirContext ctx) {
496   MlirLocation loc = mlirLocationUnknownGet(ctx);
497   mlirContextSetAllowUnregisteredDialects(ctx, true);
498 
499   MlirRegion owningRegion = mlirRegionCreate();
500   MlirBlock nullBlock = mlirRegionGetFirstBlock(owningRegion);
501   MlirOperationState state = mlirOperationStateGet(
502       mlirStringRefCreateFromCString("insertion.order.test"), loc);
503   mlirOperationStateAddOwnedRegions(&state, 1, &owningRegion);
504   MlirOperation op = mlirOperationCreate(&state);
505   MlirRegion region = mlirOperationGetRegion(op, 0);
506 
507   // Use integer types of different bitwidth as block arguments in order to
508   // differentiate blocks.
509   MlirType i1 = mlirIntegerTypeGet(ctx, 1);
510   MlirType i2 = mlirIntegerTypeGet(ctx, 2);
511   MlirType i3 = mlirIntegerTypeGet(ctx, 3);
512   MlirType i4 = mlirIntegerTypeGet(ctx, 4);
513   MlirBlock block1 = mlirBlockCreate(1, &i1, &loc);
514   MlirBlock block2 = mlirBlockCreate(1, &i2, &loc);
515   MlirBlock block3 = mlirBlockCreate(1, &i3, &loc);
516   MlirBlock block4 = mlirBlockCreate(1, &i4, &loc);
517   // Insert blocks so as to obtain the 1-2-3-4 order,
518   mlirRegionInsertOwnedBlockBefore(region, nullBlock, block3);
519   mlirRegionInsertOwnedBlockBefore(region, block3, block2);
520   mlirRegionInsertOwnedBlockAfter(region, nullBlock, block1);
521   mlirRegionInsertOwnedBlockAfter(region, block3, block4);
522 
523   MlirOperationState op1State =
524       mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op1"), loc);
525   MlirOperationState op2State =
526       mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op2"), loc);
527   MlirOperationState op3State =
528       mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op3"), loc);
529   MlirOperationState op4State =
530       mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op4"), loc);
531   MlirOperationState op5State =
532       mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op5"), loc);
533   MlirOperationState op6State =
534       mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op6"), loc);
535   MlirOperationState op7State =
536       mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op7"), loc);
537   MlirOperation op1 = mlirOperationCreate(&op1State);
538   MlirOperation op2 = mlirOperationCreate(&op2State);
539   MlirOperation op3 = mlirOperationCreate(&op3State);
540   MlirOperation op4 = mlirOperationCreate(&op4State);
541   MlirOperation op5 = mlirOperationCreate(&op5State);
542   MlirOperation op6 = mlirOperationCreate(&op6State);
543   MlirOperation op7 = mlirOperationCreate(&op7State);
544 
545   // Insert operations in the first block so as to obtain the 1-2-3-4 order.
546   MlirOperation nullOperation = mlirBlockGetFirstOperation(block1);
547   assert(mlirOperationIsNull(nullOperation));
548   mlirBlockInsertOwnedOperationBefore(block1, nullOperation, op3);
549   mlirBlockInsertOwnedOperationBefore(block1, op3, op2);
550   mlirBlockInsertOwnedOperationAfter(block1, nullOperation, op1);
551   mlirBlockInsertOwnedOperationAfter(block1, op3, op4);
552 
553   // Append operations to the rest of blocks to make them non-empty and thus
554   // printable.
555   mlirBlockAppendOwnedOperation(block2, op5);
556   mlirBlockAppendOwnedOperation(block3, op6);
557   mlirBlockAppendOwnedOperation(block4, op7);
558 
559   mlirOperationDump(op);
560   mlirOperationDestroy(op);
561   mlirContextSetAllowUnregisteredDialects(ctx, false);
562   // clang-format off
563   // CHECK-LABEL:  "insertion.order.test"
564   // CHECK:      ^{{.*}}(%{{.*}}: i1
565   // CHECK:        "dummy.op1"
566   // CHECK-NEXT:   "dummy.op2"
567   // CHECK-NEXT:   "dummy.op3"
568   // CHECK-NEXT:   "dummy.op4"
569   // CHECK:      ^{{.*}}(%{{.*}}: i2
570   // CHECK:        "dummy.op5"
571   // CHECK:      ^{{.*}}(%{{.*}}: i3
572   // CHECK:        "dummy.op6"
573   // CHECK:      ^{{.*}}(%{{.*}}: i4
574   // CHECK:        "dummy.op7"
575   // clang-format on
576 }
577 
578 /// Creates operations with type inference and tests various failure modes.
579 static int createOperationWithTypeInference(MlirContext ctx) {
580   MlirLocation loc = mlirLocationUnknownGet(ctx);
581   MlirAttribute iAttr = mlirIntegerAttrGet(mlirIntegerTypeGet(ctx, 32), 4);
582 
583   // The shape.const_size op implements result type inference and is only used
584   // for that reason.
585   MlirOperationState state = mlirOperationStateGet(
586       mlirStringRefCreateFromCString("shape.const_size"), loc);
587   MlirNamedAttribute valueAttr = mlirNamedAttributeGet(
588       mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("value")), iAttr);
589   mlirOperationStateAddAttributes(&state, 1, &valueAttr);
590   mlirOperationStateEnableResultTypeInference(&state);
591 
592   // Expect result type inference to succeed.
593   MlirOperation op = mlirOperationCreate(&state);
594   if (mlirOperationIsNull(op)) {
595     fprintf(stderr, "ERROR: Result type inference unexpectedly failed");
596     return 1;
597   }
598 
599   // CHECK: RESULT_TYPE_INFERENCE: !shape.size
600   fprintf(stderr, "RESULT_TYPE_INFERENCE: ");
601   mlirTypeDump(mlirValueGetType(mlirOperationGetResult(op, 0)));
602   fprintf(stderr, "\n");
603   mlirOperationDestroy(op);
604   return 0;
605 }
606 
607 /// Dumps instances of all builtin types to check that C API works correctly.
608 /// Additionally, performs simple identity checks that a builtin type
609 /// constructed with C API can be inspected and has the expected type. The
610 /// latter achieves full coverage of C API for builtin types. Returns 0 on
611 /// success and a non-zero error code on failure.
612 static int printBuiltinTypes(MlirContext ctx) {
613   // Integer types.
614   MlirType i32 = mlirIntegerTypeGet(ctx, 32);
615   MlirType si32 = mlirIntegerTypeSignedGet(ctx, 32);
616   MlirType ui32 = mlirIntegerTypeUnsignedGet(ctx, 32);
617   if (!mlirTypeIsAInteger(i32) || mlirTypeIsAF32(i32))
618     return 1;
619   if (!mlirTypeIsAInteger(si32) || !mlirIntegerTypeIsSigned(si32))
620     return 2;
621   if (!mlirTypeIsAInteger(ui32) || !mlirIntegerTypeIsUnsigned(ui32))
622     return 3;
623   if (mlirTypeEqual(i32, ui32) || mlirTypeEqual(i32, si32))
624     return 4;
625   if (mlirIntegerTypeGetWidth(i32) != mlirIntegerTypeGetWidth(si32))
626     return 5;
627   fprintf(stderr, "@types\n");
628   mlirTypeDump(i32);
629   fprintf(stderr, "\n");
630   mlirTypeDump(si32);
631   fprintf(stderr, "\n");
632   mlirTypeDump(ui32);
633   fprintf(stderr, "\n");
634   // CHECK-LABEL: @types
635   // CHECK: i32
636   // CHECK: si32
637   // CHECK: ui32
638 
639   // Index type.
640   MlirType index = mlirIndexTypeGet(ctx);
641   if (!mlirTypeIsAIndex(index))
642     return 6;
643   mlirTypeDump(index);
644   fprintf(stderr, "\n");
645   // CHECK: index
646 
647   // Floating-point types.
648   MlirType bf16 = mlirBF16TypeGet(ctx);
649   MlirType f16 = mlirF16TypeGet(ctx);
650   MlirType f32 = mlirF32TypeGet(ctx);
651   MlirType f64 = mlirF64TypeGet(ctx);
652   if (!mlirTypeIsABF16(bf16))
653     return 7;
654   if (!mlirTypeIsAF16(f16))
655     return 9;
656   if (!mlirTypeIsAF32(f32))
657     return 10;
658   if (!mlirTypeIsAF64(f64))
659     return 11;
660   mlirTypeDump(bf16);
661   fprintf(stderr, "\n");
662   mlirTypeDump(f16);
663   fprintf(stderr, "\n");
664   mlirTypeDump(f32);
665   fprintf(stderr, "\n");
666   mlirTypeDump(f64);
667   fprintf(stderr, "\n");
668   // CHECK: bf16
669   // CHECK: f16
670   // CHECK: f32
671   // CHECK: f64
672 
673   // None type.
674   MlirType none = mlirNoneTypeGet(ctx);
675   if (!mlirTypeIsANone(none))
676     return 12;
677   mlirTypeDump(none);
678   fprintf(stderr, "\n");
679   // CHECK: none
680 
681   // Complex type.
682   MlirType cplx = mlirComplexTypeGet(f32);
683   if (!mlirTypeIsAComplex(cplx) ||
684       !mlirTypeEqual(mlirComplexTypeGetElementType(cplx), f32))
685     return 13;
686   mlirTypeDump(cplx);
687   fprintf(stderr, "\n");
688   // CHECK: complex<f32>
689 
690   // Vector (and Shaped) type. ShapedType is a common base class for vectors,
691   // memrefs and tensors, one cannot create instances of this class so it is
692   // tested on an instance of vector type.
693   int64_t shape[] = {2, 3};
694   MlirType vector =
695       mlirVectorTypeGet(sizeof(shape) / sizeof(int64_t), shape, f32);
696   if (!mlirTypeIsAVector(vector) || !mlirTypeIsAShaped(vector))
697     return 14;
698   if (!mlirTypeEqual(mlirShapedTypeGetElementType(vector), f32) ||
699       !mlirShapedTypeHasRank(vector) || mlirShapedTypeGetRank(vector) != 2 ||
700       mlirShapedTypeGetDimSize(vector, 0) != 2 ||
701       mlirShapedTypeIsDynamicDim(vector, 0) ||
702       mlirShapedTypeGetDimSize(vector, 1) != 3 ||
703       !mlirShapedTypeHasStaticShape(vector))
704     return 15;
705   mlirTypeDump(vector);
706   fprintf(stderr, "\n");
707   // CHECK: vector<2x3xf32>
708 
709   // Ranked tensor type.
710   MlirType rankedTensor = mlirRankedTensorTypeGet(
711       sizeof(shape) / sizeof(int64_t), shape, f32, mlirAttributeGetNull());
712   if (!mlirTypeIsATensor(rankedTensor) ||
713       !mlirTypeIsARankedTensor(rankedTensor) ||
714       !mlirAttributeIsNull(mlirRankedTensorTypeGetEncoding(rankedTensor)))
715     return 16;
716   mlirTypeDump(rankedTensor);
717   fprintf(stderr, "\n");
718   // CHECK: tensor<2x3xf32>
719 
720   // Unranked tensor type.
721   MlirType unrankedTensor = mlirUnrankedTensorTypeGet(f32);
722   if (!mlirTypeIsATensor(unrankedTensor) ||
723       !mlirTypeIsAUnrankedTensor(unrankedTensor) ||
724       mlirShapedTypeHasRank(unrankedTensor))
725     return 17;
726   mlirTypeDump(unrankedTensor);
727   fprintf(stderr, "\n");
728   // CHECK: tensor<*xf32>
729 
730   // MemRef type.
731   MlirAttribute memSpace2 = mlirIntegerAttrGet(mlirIntegerTypeGet(ctx, 64), 2);
732   MlirType memRef = mlirMemRefTypeContiguousGet(
733       f32, sizeof(shape) / sizeof(int64_t), shape, memSpace2);
734   if (!mlirTypeIsAMemRef(memRef) ||
735       !mlirAttributeEqual(mlirMemRefTypeGetMemorySpace(memRef), memSpace2))
736     return 18;
737   mlirTypeDump(memRef);
738   fprintf(stderr, "\n");
739   // CHECK: memref<2x3xf32, 2>
740 
741   // Unranked MemRef type.
742   MlirAttribute memSpace4 = mlirIntegerAttrGet(mlirIntegerTypeGet(ctx, 64), 4);
743   MlirType unrankedMemRef = mlirUnrankedMemRefTypeGet(f32, memSpace4);
744   if (!mlirTypeIsAUnrankedMemRef(unrankedMemRef) ||
745       mlirTypeIsAMemRef(unrankedMemRef) ||
746       !mlirAttributeEqual(mlirUnrankedMemrefGetMemorySpace(unrankedMemRef),
747                           memSpace4))
748     return 19;
749   mlirTypeDump(unrankedMemRef);
750   fprintf(stderr, "\n");
751   // CHECK: memref<*xf32, 4>
752 
753   // Tuple type.
754   MlirType types[] = {unrankedMemRef, f32};
755   MlirType tuple = mlirTupleTypeGet(ctx, 2, types);
756   if (!mlirTypeIsATuple(tuple) || mlirTupleTypeGetNumTypes(tuple) != 2 ||
757       !mlirTypeEqual(mlirTupleTypeGetType(tuple, 0), unrankedMemRef) ||
758       !mlirTypeEqual(mlirTupleTypeGetType(tuple, 1), f32))
759     return 20;
760   mlirTypeDump(tuple);
761   fprintf(stderr, "\n");
762   // CHECK: tuple<memref<*xf32, 4>, f32>
763 
764   // Function type.
765   MlirType funcInputs[2] = {mlirIndexTypeGet(ctx), mlirIntegerTypeGet(ctx, 1)};
766   MlirType funcResults[3] = {mlirIntegerTypeGet(ctx, 16),
767                              mlirIntegerTypeGet(ctx, 32),
768                              mlirIntegerTypeGet(ctx, 64)};
769   MlirType funcType = mlirFunctionTypeGet(ctx, 2, funcInputs, 3, funcResults);
770   if (mlirFunctionTypeGetNumInputs(funcType) != 2)
771     return 21;
772   if (mlirFunctionTypeGetNumResults(funcType) != 3)
773     return 22;
774   if (!mlirTypeEqual(funcInputs[0], mlirFunctionTypeGetInput(funcType, 0)) ||
775       !mlirTypeEqual(funcInputs[1], mlirFunctionTypeGetInput(funcType, 1)))
776     return 23;
777   if (!mlirTypeEqual(funcResults[0], mlirFunctionTypeGetResult(funcType, 0)) ||
778       !mlirTypeEqual(funcResults[1], mlirFunctionTypeGetResult(funcType, 1)) ||
779       !mlirTypeEqual(funcResults[2], mlirFunctionTypeGetResult(funcType, 2)))
780     return 24;
781   mlirTypeDump(funcType);
782   fprintf(stderr, "\n");
783   // CHECK: (index, i1) -> (i16, i32, i64)
784 
785   return 0;
786 }
787 
788 void callbackSetFixedLengthString(const char *data, intptr_t len,
789                                   void *userData) {
790   strncpy(userData, data, len);
791 }
792 
793 bool stringIsEqual(const char *lhs, MlirStringRef rhs) {
794   if (strlen(lhs) != rhs.length) {
795     return false;
796   }
797   return !strncmp(lhs, rhs.data, rhs.length);
798 }
799 
800 int printBuiltinAttributes(MlirContext ctx) {
801   MlirAttribute floating =
802       mlirFloatAttrDoubleGet(ctx, mlirF64TypeGet(ctx), 2.0);
803   if (!mlirAttributeIsAFloat(floating) ||
804       fabs(mlirFloatAttrGetValueDouble(floating) - 2.0) > 1E-6)
805     return 1;
806   fprintf(stderr, "@attrs\n");
807   mlirAttributeDump(floating);
808   // CHECK-LABEL: @attrs
809   // CHECK: 2.000000e+00 : f64
810 
811   // Exercise mlirAttributeGetType() just for the first one.
812   MlirType floatingType = mlirAttributeGetType(floating);
813   mlirTypeDump(floatingType);
814   // CHECK: f64
815 
816   MlirAttribute integer = mlirIntegerAttrGet(mlirIntegerTypeGet(ctx, 32), 42);
817   MlirAttribute signedInteger =
818       mlirIntegerAttrGet(mlirIntegerTypeSignedGet(ctx, 8), -1);
819   MlirAttribute unsignedInteger =
820       mlirIntegerAttrGet(mlirIntegerTypeUnsignedGet(ctx, 8), 255);
821   if (!mlirAttributeIsAInteger(integer) ||
822       mlirIntegerAttrGetValueInt(integer) != 42 ||
823       mlirIntegerAttrGetValueSInt(signedInteger) != -1 ||
824       mlirIntegerAttrGetValueUInt(unsignedInteger) != 255)
825     return 2;
826   mlirAttributeDump(integer);
827   mlirAttributeDump(signedInteger);
828   mlirAttributeDump(unsignedInteger);
829   // CHECK: 42 : i32
830   // CHECK: -1 : si8
831   // CHECK: 255 : ui8
832 
833   MlirAttribute boolean = mlirBoolAttrGet(ctx, 1);
834   if (!mlirAttributeIsABool(boolean) || !mlirBoolAttrGetValue(boolean))
835     return 3;
836   mlirAttributeDump(boolean);
837   // CHECK: true
838 
839   const char data[] = "abcdefghijklmnopqestuvwxyz";
840   MlirAttribute opaque =
841       mlirOpaqueAttrGet(ctx, mlirStringRefCreateFromCString("func"), 3, data,
842                         mlirNoneTypeGet(ctx));
843   if (!mlirAttributeIsAOpaque(opaque) ||
844       !stringIsEqual("func", mlirOpaqueAttrGetDialectNamespace(opaque)))
845     return 4;
846 
847   MlirStringRef opaqueData = mlirOpaqueAttrGetData(opaque);
848   if (opaqueData.length != 3 ||
849       strncmp(data, opaqueData.data, opaqueData.length))
850     return 5;
851   mlirAttributeDump(opaque);
852   // CHECK: #func.abc
853 
854   MlirAttribute string =
855       mlirStringAttrGet(ctx, mlirStringRefCreate(data + 3, 2));
856   if (!mlirAttributeIsAString(string))
857     return 6;
858 
859   MlirStringRef stringValue = mlirStringAttrGetValue(string);
860   if (stringValue.length != 2 ||
861       strncmp(data + 3, stringValue.data, stringValue.length))
862     return 7;
863   mlirAttributeDump(string);
864   // CHECK: "de"
865 
866   MlirAttribute flatSymbolRef =
867       mlirFlatSymbolRefAttrGet(ctx, mlirStringRefCreate(data + 5, 3));
868   if (!mlirAttributeIsAFlatSymbolRef(flatSymbolRef))
869     return 8;
870 
871   MlirStringRef flatSymbolRefValue =
872       mlirFlatSymbolRefAttrGetValue(flatSymbolRef);
873   if (flatSymbolRefValue.length != 3 ||
874       strncmp(data + 5, flatSymbolRefValue.data, flatSymbolRefValue.length))
875     return 9;
876   mlirAttributeDump(flatSymbolRef);
877   // CHECK: @fgh
878 
879   MlirAttribute symbols[] = {flatSymbolRef, flatSymbolRef};
880   MlirAttribute symbolRef =
881       mlirSymbolRefAttrGet(ctx, mlirStringRefCreate(data + 8, 2), 2, symbols);
882   if (!mlirAttributeIsASymbolRef(symbolRef) ||
883       mlirSymbolRefAttrGetNumNestedReferences(symbolRef) != 2 ||
884       !mlirAttributeEqual(mlirSymbolRefAttrGetNestedReference(symbolRef, 0),
885                           flatSymbolRef) ||
886       !mlirAttributeEqual(mlirSymbolRefAttrGetNestedReference(symbolRef, 1),
887                           flatSymbolRef))
888     return 10;
889 
890   MlirStringRef symbolRefLeaf = mlirSymbolRefAttrGetLeafReference(symbolRef);
891   MlirStringRef symbolRefRoot = mlirSymbolRefAttrGetRootReference(symbolRef);
892   if (symbolRefLeaf.length != 3 ||
893       strncmp(data + 5, symbolRefLeaf.data, symbolRefLeaf.length) ||
894       symbolRefRoot.length != 2 ||
895       strncmp(data + 8, symbolRefRoot.data, symbolRefRoot.length))
896     return 11;
897   mlirAttributeDump(symbolRef);
898   // CHECK: @ij::@fgh::@fgh
899 
900   MlirAttribute type = mlirTypeAttrGet(mlirF32TypeGet(ctx));
901   if (!mlirAttributeIsAType(type) ||
902       !mlirTypeEqual(mlirF32TypeGet(ctx), mlirTypeAttrGetValue(type)))
903     return 12;
904   mlirAttributeDump(type);
905   // CHECK: f32
906 
907   MlirAttribute unit = mlirUnitAttrGet(ctx);
908   if (!mlirAttributeIsAUnit(unit))
909     return 13;
910   mlirAttributeDump(unit);
911   // CHECK: unit
912 
913   int64_t shape[] = {1, 2};
914 
915   int bools[] = {0, 1};
916   uint8_t uints8[] = {0u, 1u};
917   int8_t ints8[] = {0, 1};
918   uint16_t uints16[] = {0u, 1u};
919   int16_t ints16[] = {0, 1};
920   uint32_t uints32[] = {0u, 1u};
921   int32_t ints32[] = {0, 1};
922   uint64_t uints64[] = {0u, 1u};
923   int64_t ints64[] = {0, 1};
924   float floats[] = {0.0f, 1.0f};
925   double doubles[] = {0.0, 1.0};
926   MlirAttribute encoding = mlirAttributeGetNull();
927   MlirAttribute boolElements = mlirDenseElementsAttrBoolGet(
928       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 1), encoding),
929       2, bools);
930   MlirAttribute uint8Elements = mlirDenseElementsAttrUInt8Get(
931       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 8),
932                               encoding),
933       2, uints8);
934   MlirAttribute int8Elements = mlirDenseElementsAttrInt8Get(
935       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 8), encoding),
936       2, ints8);
937   MlirAttribute uint16Elements = mlirDenseElementsAttrUInt16Get(
938       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 16),
939                               encoding),
940       2, uints16);
941   MlirAttribute int16Elements = mlirDenseElementsAttrInt16Get(
942       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 16), encoding),
943       2, ints16);
944   MlirAttribute uint32Elements = mlirDenseElementsAttrUInt32Get(
945       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 32),
946                               encoding),
947       2, uints32);
948   MlirAttribute int32Elements = mlirDenseElementsAttrInt32Get(
949       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 32), encoding),
950       2, ints32);
951   MlirAttribute uint64Elements = mlirDenseElementsAttrUInt64Get(
952       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 64),
953                               encoding),
954       2, uints64);
955   MlirAttribute int64Elements = mlirDenseElementsAttrInt64Get(
956       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 64), encoding),
957       2, ints64);
958   MlirAttribute floatElements = mlirDenseElementsAttrFloatGet(
959       mlirRankedTensorTypeGet(2, shape, mlirF32TypeGet(ctx), encoding), 2,
960       floats);
961   MlirAttribute doubleElements = mlirDenseElementsAttrDoubleGet(
962       mlirRankedTensorTypeGet(2, shape, mlirF64TypeGet(ctx), encoding), 2,
963       doubles);
964 
965   if (!mlirAttributeIsADenseElements(boolElements) ||
966       !mlirAttributeIsADenseElements(uint8Elements) ||
967       !mlirAttributeIsADenseElements(int8Elements) ||
968       !mlirAttributeIsADenseElements(uint32Elements) ||
969       !mlirAttributeIsADenseElements(int32Elements) ||
970       !mlirAttributeIsADenseElements(uint64Elements) ||
971       !mlirAttributeIsADenseElements(int64Elements) ||
972       !mlirAttributeIsADenseElements(floatElements) ||
973       !mlirAttributeIsADenseElements(doubleElements))
974     return 14;
975 
976   if (mlirDenseElementsAttrGetBoolValue(boolElements, 1) != 1 ||
977       mlirDenseElementsAttrGetUInt8Value(uint8Elements, 1) != 1 ||
978       mlirDenseElementsAttrGetInt8Value(int8Elements, 1) != 1 ||
979       mlirDenseElementsAttrGetUInt16Value(uint16Elements, 1) != 1 ||
980       mlirDenseElementsAttrGetInt16Value(int16Elements, 1) != 1 ||
981       mlirDenseElementsAttrGetUInt32Value(uint32Elements, 1) != 1 ||
982       mlirDenseElementsAttrGetInt32Value(int32Elements, 1) != 1 ||
983       mlirDenseElementsAttrGetUInt64Value(uint64Elements, 1) != 1 ||
984       mlirDenseElementsAttrGetInt64Value(int64Elements, 1) != 1 ||
985       fabsf(mlirDenseElementsAttrGetFloatValue(floatElements, 1) - 1.0f) >
986           1E-6f ||
987       fabs(mlirDenseElementsAttrGetDoubleValue(doubleElements, 1) - 1.0) > 1E-6)
988     return 15;
989 
990   mlirAttributeDump(boolElements);
991   mlirAttributeDump(uint8Elements);
992   mlirAttributeDump(int8Elements);
993   mlirAttributeDump(uint32Elements);
994   mlirAttributeDump(int32Elements);
995   mlirAttributeDump(uint64Elements);
996   mlirAttributeDump(int64Elements);
997   mlirAttributeDump(floatElements);
998   mlirAttributeDump(doubleElements);
999   // CHECK: dense<{{\[}}[false, true]]> : tensor<1x2xi1>
1000   // CHECK: dense<{{\[}}[0, 1]]> : tensor<1x2xui8>
1001   // CHECK: dense<{{\[}}[0, 1]]> : tensor<1x2xi8>
1002   // CHECK: dense<{{\[}}[0, 1]]> : tensor<1x2xui32>
1003   // CHECK: dense<{{\[}}[0, 1]]> : tensor<1x2xi32>
1004   // CHECK: dense<{{\[}}[0, 1]]> : tensor<1x2xui64>
1005   // CHECK: dense<{{\[}}[0, 1]]> : tensor<1x2xi64>
1006   // CHECK: dense<{{\[}}[0.000000e+00, 1.000000e+00]]> : tensor<1x2xf32>
1007   // CHECK: dense<{{\[}}[0.000000e+00, 1.000000e+00]]> : tensor<1x2xf64>
1008 
1009   MlirAttribute splatBool = mlirDenseElementsAttrBoolSplatGet(
1010       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 1), encoding),
1011       1);
1012   MlirAttribute splatUInt8 = mlirDenseElementsAttrUInt8SplatGet(
1013       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 8),
1014                               encoding),
1015       1);
1016   MlirAttribute splatInt8 = mlirDenseElementsAttrInt8SplatGet(
1017       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 8), encoding),
1018       1);
1019   MlirAttribute splatUInt32 = mlirDenseElementsAttrUInt32SplatGet(
1020       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 32),
1021                               encoding),
1022       1);
1023   MlirAttribute splatInt32 = mlirDenseElementsAttrInt32SplatGet(
1024       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 32), encoding),
1025       1);
1026   MlirAttribute splatUInt64 = mlirDenseElementsAttrUInt64SplatGet(
1027       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 64),
1028                               encoding),
1029       1);
1030   MlirAttribute splatInt64 = mlirDenseElementsAttrInt64SplatGet(
1031       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 64), encoding),
1032       1);
1033   MlirAttribute splatFloat = mlirDenseElementsAttrFloatSplatGet(
1034       mlirRankedTensorTypeGet(2, shape, mlirF32TypeGet(ctx), encoding), 1.0f);
1035   MlirAttribute splatDouble = mlirDenseElementsAttrDoubleSplatGet(
1036       mlirRankedTensorTypeGet(2, shape, mlirF64TypeGet(ctx), encoding), 1.0);
1037 
1038   if (!mlirAttributeIsADenseElements(splatBool) ||
1039       !mlirDenseElementsAttrIsSplat(splatBool) ||
1040       !mlirAttributeIsADenseElements(splatUInt8) ||
1041       !mlirDenseElementsAttrIsSplat(splatUInt8) ||
1042       !mlirAttributeIsADenseElements(splatInt8) ||
1043       !mlirDenseElementsAttrIsSplat(splatInt8) ||
1044       !mlirAttributeIsADenseElements(splatUInt32) ||
1045       !mlirDenseElementsAttrIsSplat(splatUInt32) ||
1046       !mlirAttributeIsADenseElements(splatInt32) ||
1047       !mlirDenseElementsAttrIsSplat(splatInt32) ||
1048       !mlirAttributeIsADenseElements(splatUInt64) ||
1049       !mlirDenseElementsAttrIsSplat(splatUInt64) ||
1050       !mlirAttributeIsADenseElements(splatInt64) ||
1051       !mlirDenseElementsAttrIsSplat(splatInt64) ||
1052       !mlirAttributeIsADenseElements(splatFloat) ||
1053       !mlirDenseElementsAttrIsSplat(splatFloat) ||
1054       !mlirAttributeIsADenseElements(splatDouble) ||
1055       !mlirDenseElementsAttrIsSplat(splatDouble))
1056     return 16;
1057 
1058   if (mlirDenseElementsAttrGetBoolSplatValue(splatBool) != 1 ||
1059       mlirDenseElementsAttrGetUInt8SplatValue(splatUInt8) != 1 ||
1060       mlirDenseElementsAttrGetInt8SplatValue(splatInt8) != 1 ||
1061       mlirDenseElementsAttrGetUInt32SplatValue(splatUInt32) != 1 ||
1062       mlirDenseElementsAttrGetInt32SplatValue(splatInt32) != 1 ||
1063       mlirDenseElementsAttrGetUInt64SplatValue(splatUInt64) != 1 ||
1064       mlirDenseElementsAttrGetInt64SplatValue(splatInt64) != 1 ||
1065       fabsf(mlirDenseElementsAttrGetFloatSplatValue(splatFloat) - 1.0f) >
1066           1E-6f ||
1067       fabs(mlirDenseElementsAttrGetDoubleSplatValue(splatDouble) - 1.0) > 1E-6)
1068     return 17;
1069 
1070   uint8_t *uint8RawData =
1071       (uint8_t *)mlirDenseElementsAttrGetRawData(uint8Elements);
1072   int8_t *int8RawData = (int8_t *)mlirDenseElementsAttrGetRawData(int8Elements);
1073   uint32_t *uint32RawData =
1074       (uint32_t *)mlirDenseElementsAttrGetRawData(uint32Elements);
1075   int32_t *int32RawData =
1076       (int32_t *)mlirDenseElementsAttrGetRawData(int32Elements);
1077   uint64_t *uint64RawData =
1078       (uint64_t *)mlirDenseElementsAttrGetRawData(uint64Elements);
1079   int64_t *int64RawData =
1080       (int64_t *)mlirDenseElementsAttrGetRawData(int64Elements);
1081   float *floatRawData = (float *)mlirDenseElementsAttrGetRawData(floatElements);
1082   double *doubleRawData =
1083       (double *)mlirDenseElementsAttrGetRawData(doubleElements);
1084   if (uint8RawData[0] != 0u || uint8RawData[1] != 1u || int8RawData[0] != 0 ||
1085       int8RawData[1] != 1 || uint32RawData[0] != 0u || uint32RawData[1] != 1u ||
1086       int32RawData[0] != 0 || int32RawData[1] != 1 || uint64RawData[0] != 0u ||
1087       uint64RawData[1] != 1u || int64RawData[0] != 0 || int64RawData[1] != 1 ||
1088       floatRawData[0] != 0.0f || floatRawData[1] != 1.0f ||
1089       doubleRawData[0] != 0.0 || doubleRawData[1] != 1.0)
1090     return 18;
1091 
1092   mlirAttributeDump(splatBool);
1093   mlirAttributeDump(splatUInt8);
1094   mlirAttributeDump(splatInt8);
1095   mlirAttributeDump(splatUInt32);
1096   mlirAttributeDump(splatInt32);
1097   mlirAttributeDump(splatUInt64);
1098   mlirAttributeDump(splatInt64);
1099   mlirAttributeDump(splatFloat);
1100   mlirAttributeDump(splatDouble);
1101   // CHECK: dense<true> : tensor<1x2xi1>
1102   // CHECK: dense<1> : tensor<1x2xui8>
1103   // CHECK: dense<1> : tensor<1x2xi8>
1104   // CHECK: dense<1> : tensor<1x2xui32>
1105   // CHECK: dense<1> : tensor<1x2xi32>
1106   // CHECK: dense<1> : tensor<1x2xui64>
1107   // CHECK: dense<1> : tensor<1x2xi64>
1108   // CHECK: dense<1.000000e+00> : tensor<1x2xf32>
1109   // CHECK: dense<1.000000e+00> : tensor<1x2xf64>
1110 
1111   mlirAttributeDump(mlirElementsAttrGetValue(floatElements, 2, uints64));
1112   mlirAttributeDump(mlirElementsAttrGetValue(doubleElements, 2, uints64));
1113   // CHECK: 1.000000e+00 : f32
1114   // CHECK: 1.000000e+00 : f64
1115 
1116   int64_t indices[] = {0, 1};
1117   int64_t one = 1;
1118   MlirAttribute indicesAttr = mlirDenseElementsAttrInt64Get(
1119       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 64), encoding),
1120       2, indices);
1121   MlirAttribute valuesAttr = mlirDenseElementsAttrFloatGet(
1122       mlirRankedTensorTypeGet(1, &one, mlirF32TypeGet(ctx), encoding), 1,
1123       floats);
1124   MlirAttribute sparseAttr = mlirSparseElementsAttribute(
1125       mlirRankedTensorTypeGet(2, shape, mlirF32TypeGet(ctx), encoding),
1126       indicesAttr, valuesAttr);
1127   mlirAttributeDump(sparseAttr);
1128   // CHECK: sparse<{{\[}}[0, 1]], 0.000000e+00> : tensor<1x2xf32>
1129 
1130   return 0;
1131 }
1132 
1133 int printAffineMap(MlirContext ctx) {
1134   MlirAffineMap emptyAffineMap = mlirAffineMapEmptyGet(ctx);
1135   MlirAffineMap affineMap = mlirAffineMapZeroResultGet(ctx, 3, 2);
1136   MlirAffineMap constAffineMap = mlirAffineMapConstantGet(ctx, 2);
1137   MlirAffineMap multiDimIdentityAffineMap =
1138       mlirAffineMapMultiDimIdentityGet(ctx, 3);
1139   MlirAffineMap minorIdentityAffineMap =
1140       mlirAffineMapMinorIdentityGet(ctx, 3, 2);
1141   unsigned permutation[] = {1, 2, 0};
1142   MlirAffineMap permutationAffineMap = mlirAffineMapPermutationGet(
1143       ctx, sizeof(permutation) / sizeof(unsigned), permutation);
1144 
1145   fprintf(stderr, "@affineMap\n");
1146   mlirAffineMapDump(emptyAffineMap);
1147   mlirAffineMapDump(affineMap);
1148   mlirAffineMapDump(constAffineMap);
1149   mlirAffineMapDump(multiDimIdentityAffineMap);
1150   mlirAffineMapDump(minorIdentityAffineMap);
1151   mlirAffineMapDump(permutationAffineMap);
1152   // CHECK-LABEL: @affineMap
1153   // CHECK: () -> ()
1154   // CHECK: (d0, d1, d2)[s0, s1] -> ()
1155   // CHECK: () -> (2)
1156   // CHECK: (d0, d1, d2) -> (d0, d1, d2)
1157   // CHECK: (d0, d1, d2) -> (d1, d2)
1158   // CHECK: (d0, d1, d2) -> (d1, d2, d0)
1159 
1160   if (!mlirAffineMapIsIdentity(emptyAffineMap) ||
1161       mlirAffineMapIsIdentity(affineMap) ||
1162       mlirAffineMapIsIdentity(constAffineMap) ||
1163       !mlirAffineMapIsIdentity(multiDimIdentityAffineMap) ||
1164       mlirAffineMapIsIdentity(minorIdentityAffineMap) ||
1165       mlirAffineMapIsIdentity(permutationAffineMap))
1166     return 1;
1167 
1168   if (!mlirAffineMapIsMinorIdentity(emptyAffineMap) ||
1169       mlirAffineMapIsMinorIdentity(affineMap) ||
1170       !mlirAffineMapIsMinorIdentity(multiDimIdentityAffineMap) ||
1171       !mlirAffineMapIsMinorIdentity(minorIdentityAffineMap) ||
1172       mlirAffineMapIsMinorIdentity(permutationAffineMap))
1173     return 2;
1174 
1175   if (!mlirAffineMapIsEmpty(emptyAffineMap) ||
1176       mlirAffineMapIsEmpty(affineMap) || mlirAffineMapIsEmpty(constAffineMap) ||
1177       mlirAffineMapIsEmpty(multiDimIdentityAffineMap) ||
1178       mlirAffineMapIsEmpty(minorIdentityAffineMap) ||
1179       mlirAffineMapIsEmpty(permutationAffineMap))
1180     return 3;
1181 
1182   if (mlirAffineMapIsSingleConstant(emptyAffineMap) ||
1183       mlirAffineMapIsSingleConstant(affineMap) ||
1184       !mlirAffineMapIsSingleConstant(constAffineMap) ||
1185       mlirAffineMapIsSingleConstant(multiDimIdentityAffineMap) ||
1186       mlirAffineMapIsSingleConstant(minorIdentityAffineMap) ||
1187       mlirAffineMapIsSingleConstant(permutationAffineMap))
1188     return 4;
1189 
1190   if (mlirAffineMapGetSingleConstantResult(constAffineMap) != 2)
1191     return 5;
1192 
1193   if (mlirAffineMapGetNumDims(emptyAffineMap) != 0 ||
1194       mlirAffineMapGetNumDims(affineMap) != 3 ||
1195       mlirAffineMapGetNumDims(constAffineMap) != 0 ||
1196       mlirAffineMapGetNumDims(multiDimIdentityAffineMap) != 3 ||
1197       mlirAffineMapGetNumDims(minorIdentityAffineMap) != 3 ||
1198       mlirAffineMapGetNumDims(permutationAffineMap) != 3)
1199     return 6;
1200 
1201   if (mlirAffineMapGetNumSymbols(emptyAffineMap) != 0 ||
1202       mlirAffineMapGetNumSymbols(affineMap) != 2 ||
1203       mlirAffineMapGetNumSymbols(constAffineMap) != 0 ||
1204       mlirAffineMapGetNumSymbols(multiDimIdentityAffineMap) != 0 ||
1205       mlirAffineMapGetNumSymbols(minorIdentityAffineMap) != 0 ||
1206       mlirAffineMapGetNumSymbols(permutationAffineMap) != 0)
1207     return 7;
1208 
1209   if (mlirAffineMapGetNumResults(emptyAffineMap) != 0 ||
1210       mlirAffineMapGetNumResults(affineMap) != 0 ||
1211       mlirAffineMapGetNumResults(constAffineMap) != 1 ||
1212       mlirAffineMapGetNumResults(multiDimIdentityAffineMap) != 3 ||
1213       mlirAffineMapGetNumResults(minorIdentityAffineMap) != 2 ||
1214       mlirAffineMapGetNumResults(permutationAffineMap) != 3)
1215     return 8;
1216 
1217   if (mlirAffineMapGetNumInputs(emptyAffineMap) != 0 ||
1218       mlirAffineMapGetNumInputs(affineMap) != 5 ||
1219       mlirAffineMapGetNumInputs(constAffineMap) != 0 ||
1220       mlirAffineMapGetNumInputs(multiDimIdentityAffineMap) != 3 ||
1221       mlirAffineMapGetNumInputs(minorIdentityAffineMap) != 3 ||
1222       mlirAffineMapGetNumInputs(permutationAffineMap) != 3)
1223     return 9;
1224 
1225   if (!mlirAffineMapIsProjectedPermutation(emptyAffineMap) ||
1226       !mlirAffineMapIsPermutation(emptyAffineMap) ||
1227       mlirAffineMapIsProjectedPermutation(affineMap) ||
1228       mlirAffineMapIsPermutation(affineMap) ||
1229       mlirAffineMapIsProjectedPermutation(constAffineMap) ||
1230       mlirAffineMapIsPermutation(constAffineMap) ||
1231       !mlirAffineMapIsProjectedPermutation(multiDimIdentityAffineMap) ||
1232       !mlirAffineMapIsPermutation(multiDimIdentityAffineMap) ||
1233       !mlirAffineMapIsProjectedPermutation(minorIdentityAffineMap) ||
1234       mlirAffineMapIsPermutation(minorIdentityAffineMap) ||
1235       !mlirAffineMapIsProjectedPermutation(permutationAffineMap) ||
1236       !mlirAffineMapIsPermutation(permutationAffineMap))
1237     return 10;
1238 
1239   intptr_t sub[] = {1};
1240 
1241   MlirAffineMap subMap = mlirAffineMapGetSubMap(
1242       multiDimIdentityAffineMap, sizeof(sub) / sizeof(intptr_t), sub);
1243   MlirAffineMap majorSubMap =
1244       mlirAffineMapGetMajorSubMap(multiDimIdentityAffineMap, 1);
1245   MlirAffineMap minorSubMap =
1246       mlirAffineMapGetMinorSubMap(multiDimIdentityAffineMap, 1);
1247 
1248   mlirAffineMapDump(subMap);
1249   mlirAffineMapDump(majorSubMap);
1250   mlirAffineMapDump(minorSubMap);
1251   // CHECK: (d0, d1, d2) -> (d1)
1252   // CHECK: (d0, d1, d2) -> (d0)
1253   // CHECK: (d0, d1, d2) -> (d2)
1254 
1255   return 0;
1256 }
1257 
1258 int printAffineExpr(MlirContext ctx) {
1259   MlirAffineExpr affineDimExpr = mlirAffineDimExprGet(ctx, 5);
1260   MlirAffineExpr affineSymbolExpr = mlirAffineSymbolExprGet(ctx, 5);
1261   MlirAffineExpr affineConstantExpr = mlirAffineConstantExprGet(ctx, 5);
1262   MlirAffineExpr affineAddExpr =
1263       mlirAffineAddExprGet(affineDimExpr, affineSymbolExpr);
1264   MlirAffineExpr affineMulExpr =
1265       mlirAffineMulExprGet(affineDimExpr, affineSymbolExpr);
1266   MlirAffineExpr affineModExpr =
1267       mlirAffineModExprGet(affineDimExpr, affineSymbolExpr);
1268   MlirAffineExpr affineFloorDivExpr =
1269       mlirAffineFloorDivExprGet(affineDimExpr, affineSymbolExpr);
1270   MlirAffineExpr affineCeilDivExpr =
1271       mlirAffineCeilDivExprGet(affineDimExpr, affineSymbolExpr);
1272 
1273   // Tests mlirAffineExprDump.
1274   fprintf(stderr, "@affineExpr\n");
1275   mlirAffineExprDump(affineDimExpr);
1276   mlirAffineExprDump(affineSymbolExpr);
1277   mlirAffineExprDump(affineConstantExpr);
1278   mlirAffineExprDump(affineAddExpr);
1279   mlirAffineExprDump(affineMulExpr);
1280   mlirAffineExprDump(affineModExpr);
1281   mlirAffineExprDump(affineFloorDivExpr);
1282   mlirAffineExprDump(affineCeilDivExpr);
1283   // CHECK-LABEL: @affineExpr
1284   // CHECK: d5
1285   // CHECK: s5
1286   // CHECK: 5
1287   // CHECK: d5 + s5
1288   // CHECK: d5 * s5
1289   // CHECK: d5 mod s5
1290   // CHECK: d5 floordiv s5
1291   // CHECK: d5 ceildiv s5
1292 
1293   // Tests methods of affine binary operation expression, takes add expression
1294   // as an example.
1295   mlirAffineExprDump(mlirAffineBinaryOpExprGetLHS(affineAddExpr));
1296   mlirAffineExprDump(mlirAffineBinaryOpExprGetRHS(affineAddExpr));
1297   // CHECK: d5
1298   // CHECK: s5
1299 
1300   // Tests methods of affine dimension expression.
1301   if (mlirAffineDimExprGetPosition(affineDimExpr) != 5)
1302     return 1;
1303 
1304   // Tests methods of affine symbol expression.
1305   if (mlirAffineSymbolExprGetPosition(affineSymbolExpr) != 5)
1306     return 2;
1307 
1308   // Tests methods of affine constant expression.
1309   if (mlirAffineConstantExprGetValue(affineConstantExpr) != 5)
1310     return 3;
1311 
1312   // Tests methods of affine expression.
1313   if (mlirAffineExprIsSymbolicOrConstant(affineDimExpr) ||
1314       !mlirAffineExprIsSymbolicOrConstant(affineSymbolExpr) ||
1315       !mlirAffineExprIsSymbolicOrConstant(affineConstantExpr) ||
1316       mlirAffineExprIsSymbolicOrConstant(affineAddExpr) ||
1317       mlirAffineExprIsSymbolicOrConstant(affineMulExpr) ||
1318       mlirAffineExprIsSymbolicOrConstant(affineModExpr) ||
1319       mlirAffineExprIsSymbolicOrConstant(affineFloorDivExpr) ||
1320       mlirAffineExprIsSymbolicOrConstant(affineCeilDivExpr))
1321     return 4;
1322 
1323   if (!mlirAffineExprIsPureAffine(affineDimExpr) ||
1324       !mlirAffineExprIsPureAffine(affineSymbolExpr) ||
1325       !mlirAffineExprIsPureAffine(affineConstantExpr) ||
1326       !mlirAffineExprIsPureAffine(affineAddExpr) ||
1327       mlirAffineExprIsPureAffine(affineMulExpr) ||
1328       mlirAffineExprIsPureAffine(affineModExpr) ||
1329       mlirAffineExprIsPureAffine(affineFloorDivExpr) ||
1330       mlirAffineExprIsPureAffine(affineCeilDivExpr))
1331     return 5;
1332 
1333   if (mlirAffineExprGetLargestKnownDivisor(affineDimExpr) != 1 ||
1334       mlirAffineExprGetLargestKnownDivisor(affineSymbolExpr) != 1 ||
1335       mlirAffineExprGetLargestKnownDivisor(affineConstantExpr) != 5 ||
1336       mlirAffineExprGetLargestKnownDivisor(affineAddExpr) != 1 ||
1337       mlirAffineExprGetLargestKnownDivisor(affineMulExpr) != 1 ||
1338       mlirAffineExprGetLargestKnownDivisor(affineModExpr) != 1 ||
1339       mlirAffineExprGetLargestKnownDivisor(affineFloorDivExpr) != 1 ||
1340       mlirAffineExprGetLargestKnownDivisor(affineCeilDivExpr) != 1)
1341     return 6;
1342 
1343   if (!mlirAffineExprIsMultipleOf(affineDimExpr, 1) ||
1344       !mlirAffineExprIsMultipleOf(affineSymbolExpr, 1) ||
1345       !mlirAffineExprIsMultipleOf(affineConstantExpr, 5) ||
1346       !mlirAffineExprIsMultipleOf(affineAddExpr, 1) ||
1347       !mlirAffineExprIsMultipleOf(affineMulExpr, 1) ||
1348       !mlirAffineExprIsMultipleOf(affineModExpr, 1) ||
1349       !mlirAffineExprIsMultipleOf(affineFloorDivExpr, 1) ||
1350       !mlirAffineExprIsMultipleOf(affineCeilDivExpr, 1))
1351     return 7;
1352 
1353   if (!mlirAffineExprIsFunctionOfDim(affineDimExpr, 5) ||
1354       mlirAffineExprIsFunctionOfDim(affineSymbolExpr, 5) ||
1355       mlirAffineExprIsFunctionOfDim(affineConstantExpr, 5) ||
1356       !mlirAffineExprIsFunctionOfDim(affineAddExpr, 5) ||
1357       !mlirAffineExprIsFunctionOfDim(affineMulExpr, 5) ||
1358       !mlirAffineExprIsFunctionOfDim(affineModExpr, 5) ||
1359       !mlirAffineExprIsFunctionOfDim(affineFloorDivExpr, 5) ||
1360       !mlirAffineExprIsFunctionOfDim(affineCeilDivExpr, 5))
1361     return 8;
1362 
1363   // Tests 'IsA' methods of affine binary operation expression.
1364   if (!mlirAffineExprIsAAdd(affineAddExpr))
1365     return 9;
1366 
1367   if (!mlirAffineExprIsAMul(affineMulExpr))
1368     return 10;
1369 
1370   if (!mlirAffineExprIsAMod(affineModExpr))
1371     return 11;
1372 
1373   if (!mlirAffineExprIsAFloorDiv(affineFloorDivExpr))
1374     return 12;
1375 
1376   if (!mlirAffineExprIsACeilDiv(affineCeilDivExpr))
1377     return 13;
1378 
1379   if (!mlirAffineExprIsABinary(affineAddExpr))
1380     return 14;
1381 
1382   // Test other 'IsA' method on affine expressions.
1383   if (!mlirAffineExprIsAConstant(affineConstantExpr))
1384     return 15;
1385 
1386   if (!mlirAffineExprIsADim(affineDimExpr))
1387     return 16;
1388 
1389   if (!mlirAffineExprIsASymbol(affineSymbolExpr))
1390     return 17;
1391 
1392   // Test equality and nullity.
1393   MlirAffineExpr otherDimExpr = mlirAffineDimExprGet(ctx, 5);
1394   if (!mlirAffineExprEqual(affineDimExpr, otherDimExpr))
1395     return 18;
1396 
1397   if (mlirAffineExprIsNull(affineDimExpr))
1398     return 19;
1399 
1400   return 0;
1401 }
1402 
1403 int affineMapFromExprs(MlirContext ctx) {
1404   MlirAffineExpr affineDimExpr = mlirAffineDimExprGet(ctx, 0);
1405   MlirAffineExpr affineSymbolExpr = mlirAffineSymbolExprGet(ctx, 1);
1406   MlirAffineExpr exprs[] = {affineDimExpr, affineSymbolExpr};
1407   MlirAffineMap map = mlirAffineMapGet(ctx, 3, 3, 2, exprs);
1408 
1409   // CHECK-LABEL: @affineMapFromExprs
1410   fprintf(stderr, "@affineMapFromExprs");
1411   // CHECK: (d0, d1, d2)[s0, s1, s2] -> (d0, s1)
1412   mlirAffineMapDump(map);
1413 
1414   if (mlirAffineMapGetNumResults(map) != 2)
1415     return 1;
1416 
1417   if (!mlirAffineExprEqual(mlirAffineMapGetResult(map, 0), affineDimExpr))
1418     return 2;
1419 
1420   if (!mlirAffineExprEqual(mlirAffineMapGetResult(map, 1), affineSymbolExpr))
1421     return 3;
1422 
1423   MlirAffineExpr affineDim2Expr = mlirAffineDimExprGet(ctx, 1);
1424   MlirAffineExpr composed = mlirAffineExprCompose(affineDim2Expr, map);
1425   // CHECK: s1
1426   mlirAffineExprDump(composed);
1427   if (!mlirAffineExprEqual(composed, affineSymbolExpr))
1428     return 4;
1429 
1430   return 0;
1431 }
1432 
1433 int printIntegerSet(MlirContext ctx) {
1434   MlirIntegerSet emptySet = mlirIntegerSetEmptyGet(ctx, 2, 1);
1435 
1436   // CHECK-LABEL: @printIntegerSet
1437   fprintf(stderr, "@printIntegerSet");
1438 
1439   // CHECK: (d0, d1)[s0] : (1 == 0)
1440   mlirIntegerSetDump(emptySet);
1441 
1442   if (!mlirIntegerSetIsCanonicalEmpty(emptySet))
1443     return 1;
1444 
1445   MlirIntegerSet anotherEmptySet = mlirIntegerSetEmptyGet(ctx, 2, 1);
1446   if (!mlirIntegerSetEqual(emptySet, anotherEmptySet))
1447     return 2;
1448 
1449   // Construct a set constrained by:
1450   //   d0 - s0 == 0,
1451   //   d1 - 42 >= 0.
1452   MlirAffineExpr negOne = mlirAffineConstantExprGet(ctx, -1);
1453   MlirAffineExpr negFortyTwo = mlirAffineConstantExprGet(ctx, -42);
1454   MlirAffineExpr d0 = mlirAffineDimExprGet(ctx, 0);
1455   MlirAffineExpr d1 = mlirAffineDimExprGet(ctx, 1);
1456   MlirAffineExpr s0 = mlirAffineSymbolExprGet(ctx, 0);
1457   MlirAffineExpr negS0 = mlirAffineMulExprGet(negOne, s0);
1458   MlirAffineExpr d0minusS0 = mlirAffineAddExprGet(d0, negS0);
1459   MlirAffineExpr d1minus42 = mlirAffineAddExprGet(d1, negFortyTwo);
1460   MlirAffineExpr constraints[] = {d0minusS0, d1minus42};
1461   bool flags[] = {true, false};
1462 
1463   MlirIntegerSet set = mlirIntegerSetGet(ctx, 2, 1, 2, constraints, flags);
1464   // CHECK: (d0, d1)[s0] : (
1465   // CHECK-DAG: d0 - s0 == 0
1466   // CHECK-DAG: d1 - 42 >= 0
1467   mlirIntegerSetDump(set);
1468 
1469   // Transform d1 into s0.
1470   MlirAffineExpr s1 = mlirAffineSymbolExprGet(ctx, 1);
1471   MlirAffineExpr repl[] = {d0, s1};
1472   MlirIntegerSet replaced = mlirIntegerSetReplaceGet(set, repl, &s0, 1, 2);
1473   // CHECK: (d0)[s0, s1] : (
1474   // CHECK-DAG: d0 - s0 == 0
1475   // CHECK-DAG: s1 - 42 >= 0
1476   mlirIntegerSetDump(replaced);
1477 
1478   if (mlirIntegerSetGetNumDims(set) != 2)
1479     return 3;
1480   if (mlirIntegerSetGetNumDims(replaced) != 1)
1481     return 4;
1482 
1483   if (mlirIntegerSetGetNumSymbols(set) != 1)
1484     return 5;
1485   if (mlirIntegerSetGetNumSymbols(replaced) != 2)
1486     return 6;
1487 
1488   if (mlirIntegerSetGetNumInputs(set) != 3)
1489     return 7;
1490 
1491   if (mlirIntegerSetGetNumConstraints(set) != 2)
1492     return 8;
1493 
1494   if (mlirIntegerSetGetNumEqualities(set) != 1)
1495     return 9;
1496 
1497   if (mlirIntegerSetGetNumInequalities(set) != 1)
1498     return 10;
1499 
1500   MlirAffineExpr cstr1 = mlirIntegerSetGetConstraint(set, 0);
1501   MlirAffineExpr cstr2 = mlirIntegerSetGetConstraint(set, 1);
1502   bool isEq1 = mlirIntegerSetIsConstraintEq(set, 0);
1503   bool isEq2 = mlirIntegerSetIsConstraintEq(set, 1);
1504   if (!mlirAffineExprEqual(cstr1, isEq1 ? d0minusS0 : d1minus42))
1505     return 11;
1506   if (!mlirAffineExprEqual(cstr2, isEq2 ? d0minusS0 : d1minus42))
1507     return 12;
1508 
1509   return 0;
1510 }
1511 
1512 int registerOnlyStd() {
1513   MlirContext ctx = mlirContextCreate();
1514   // The built-in dialect is always loaded.
1515   if (mlirContextGetNumLoadedDialects(ctx) != 1)
1516     return 1;
1517 
1518   MlirDialectHandle stdHandle = mlirGetDialectHandle__func__();
1519 
1520   MlirDialect std = mlirContextGetOrLoadDialect(
1521       ctx, mlirDialectHandleGetNamespace(stdHandle));
1522   if (!mlirDialectIsNull(std))
1523     return 2;
1524 
1525   mlirDialectHandleRegisterDialect(stdHandle, ctx);
1526 
1527   std = mlirContextGetOrLoadDialect(ctx,
1528                                     mlirDialectHandleGetNamespace(stdHandle));
1529   if (mlirDialectIsNull(std))
1530     return 3;
1531 
1532   MlirDialect alsoStd = mlirDialectHandleLoadDialect(stdHandle, ctx);
1533   if (!mlirDialectEqual(std, alsoStd))
1534     return 4;
1535 
1536   MlirStringRef stdNs = mlirDialectGetNamespace(std);
1537   MlirStringRef alsoStdNs = mlirDialectHandleGetNamespace(stdHandle);
1538   if (stdNs.length != alsoStdNs.length ||
1539       strncmp(stdNs.data, alsoStdNs.data, stdNs.length))
1540     return 5;
1541 
1542   fprintf(stderr, "@registration\n");
1543   // CHECK-LABEL: @registration
1544 
1545   // CHECK: cf.cond_br is_registered: 1
1546   fprintf(stderr, "cf.cond_br is_registered: %d\n",
1547           mlirContextIsRegisteredOperation(
1548               ctx, mlirStringRefCreateFromCString("cf.cond_br")));
1549 
1550   // CHECK: func.not_existing_op is_registered: 0
1551   fprintf(stderr, "func.not_existing_op is_registered: %d\n",
1552           mlirContextIsRegisteredOperation(
1553               ctx, mlirStringRefCreateFromCString("func.not_existing_op")));
1554 
1555   // CHECK: not_existing_dialect.not_existing_op is_registered: 0
1556   fprintf(stderr, "not_existing_dialect.not_existing_op is_registered: %d\n",
1557           mlirContextIsRegisteredOperation(
1558               ctx, mlirStringRefCreateFromCString(
1559                        "not_existing_dialect.not_existing_op")));
1560 
1561   mlirContextDestroy(ctx);
1562   return 0;
1563 }
1564 
1565 /// Tests backreference APIs
1566 static int testBackreferences() {
1567   fprintf(stderr, "@test_backreferences\n");
1568 
1569   MlirContext ctx = mlirContextCreate();
1570   mlirContextSetAllowUnregisteredDialects(ctx, true);
1571   MlirLocation loc = mlirLocationUnknownGet(ctx);
1572 
1573   MlirOperationState opState =
1574       mlirOperationStateGet(mlirStringRefCreateFromCString("invalid.op"), loc);
1575   MlirRegion region = mlirRegionCreate();
1576   MlirBlock block = mlirBlockCreate(0, NULL, NULL);
1577   mlirRegionAppendOwnedBlock(region, block);
1578   mlirOperationStateAddOwnedRegions(&opState, 1, &region);
1579   MlirOperation op = mlirOperationCreate(&opState);
1580   MlirIdentifier ident =
1581       mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("identifier"));
1582 
1583   if (!mlirContextEqual(ctx, mlirOperationGetContext(op))) {
1584     fprintf(stderr, "ERROR: Getting context from operation failed\n");
1585     return 1;
1586   }
1587   if (!mlirOperationEqual(op, mlirBlockGetParentOperation(block))) {
1588     fprintf(stderr, "ERROR: Getting parent operation from block failed\n");
1589     return 2;
1590   }
1591   if (!mlirContextEqual(ctx, mlirIdentifierGetContext(ident))) {
1592     fprintf(stderr, "ERROR: Getting context from identifier failed\n");
1593     return 3;
1594   }
1595 
1596   mlirOperationDestroy(op);
1597   mlirContextDestroy(ctx);
1598 
1599   // CHECK-LABEL: @test_backreferences
1600   return 0;
1601 }
1602 
1603 /// Tests operand APIs.
1604 int testOperands() {
1605   fprintf(stderr, "@testOperands\n");
1606   // CHECK-LABEL: @testOperands
1607 
1608   MlirContext ctx = mlirContextCreate();
1609   mlirRegisterAllDialects(ctx);
1610   mlirContextGetOrLoadDialect(ctx, mlirStringRefCreateFromCString("test"));
1611   MlirLocation loc = mlirLocationUnknownGet(ctx);
1612   MlirType indexType = mlirIndexTypeGet(ctx);
1613 
1614   // Create some constants to use as operands.
1615   MlirAttribute indexZeroLiteral =
1616       mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("0 : index"));
1617   MlirNamedAttribute indexZeroValueAttr = mlirNamedAttributeGet(
1618       mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("value")),
1619       indexZeroLiteral);
1620   MlirOperationState constZeroState = mlirOperationStateGet(
1621       mlirStringRefCreateFromCString("arith.constant"), loc);
1622   mlirOperationStateAddResults(&constZeroState, 1, &indexType);
1623   mlirOperationStateAddAttributes(&constZeroState, 1, &indexZeroValueAttr);
1624   MlirOperation constZero = mlirOperationCreate(&constZeroState);
1625   MlirValue constZeroValue = mlirOperationGetResult(constZero, 0);
1626 
1627   MlirAttribute indexOneLiteral =
1628       mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("1 : index"));
1629   MlirNamedAttribute indexOneValueAttr = mlirNamedAttributeGet(
1630       mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("value")),
1631       indexOneLiteral);
1632   MlirOperationState constOneState = mlirOperationStateGet(
1633       mlirStringRefCreateFromCString("arith.constant"), loc);
1634   mlirOperationStateAddResults(&constOneState, 1, &indexType);
1635   mlirOperationStateAddAttributes(&constOneState, 1, &indexOneValueAttr);
1636   MlirOperation constOne = mlirOperationCreate(&constOneState);
1637   MlirValue constOneValue = mlirOperationGetResult(constOne, 0);
1638 
1639   // Create the operation under test.
1640   mlirContextSetAllowUnregisteredDialects(ctx, true);
1641   MlirOperationState opState =
1642       mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op"), loc);
1643   MlirValue initialOperands[] = {constZeroValue};
1644   mlirOperationStateAddOperands(&opState, 1, initialOperands);
1645   MlirOperation op = mlirOperationCreate(&opState);
1646 
1647   // Test operand APIs.
1648   intptr_t numOperands = mlirOperationGetNumOperands(op);
1649   fprintf(stderr, "Num Operands: %" PRIdPTR "\n", numOperands);
1650   // CHECK: Num Operands: 1
1651 
1652   MlirValue opOperand = mlirOperationGetOperand(op, 0);
1653   fprintf(stderr, "Original operand: ");
1654   mlirValuePrint(opOperand, printToStderr, NULL);
1655   // CHECK: Original operand: {{.+}} arith.constant 0 : index
1656 
1657   mlirOperationSetOperand(op, 0, constOneValue);
1658   opOperand = mlirOperationGetOperand(op, 0);
1659   fprintf(stderr, "Updated operand: ");
1660   mlirValuePrint(opOperand, printToStderr, NULL);
1661   // CHECK: Updated operand: {{.+}} arith.constant 1 : index
1662 
1663   mlirOperationDestroy(op);
1664   mlirOperationDestroy(constZero);
1665   mlirOperationDestroy(constOne);
1666   mlirContextDestroy(ctx);
1667 
1668   return 0;
1669 }
1670 
1671 /// Tests clone APIs.
1672 int testClone() {
1673   fprintf(stderr, "@testClone\n");
1674   // CHECK-LABEL: @testClone
1675 
1676   MlirContext ctx = mlirContextCreate();
1677   mlirRegisterAllDialects(ctx);
1678   mlirContextGetOrLoadDialect(ctx, mlirStringRefCreateFromCString("func"));
1679   MlirLocation loc = mlirLocationUnknownGet(ctx);
1680   MlirType indexType = mlirIndexTypeGet(ctx);
1681   MlirStringRef valueStringRef = mlirStringRefCreateFromCString("value");
1682 
1683   MlirAttribute indexZeroLiteral =
1684       mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("0 : index"));
1685   MlirNamedAttribute indexZeroValueAttr = mlirNamedAttributeGet(
1686       mlirIdentifierGet(ctx, valueStringRef), indexZeroLiteral);
1687   MlirOperationState constZeroState = mlirOperationStateGet(
1688       mlirStringRefCreateFromCString("arith.constant"), loc);
1689   mlirOperationStateAddResults(&constZeroState, 1, &indexType);
1690   mlirOperationStateAddAttributes(&constZeroState, 1, &indexZeroValueAttr);
1691   MlirOperation constZero = mlirOperationCreate(&constZeroState);
1692 
1693   MlirAttribute indexOneLiteral =
1694       mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("1 : index"));
1695   MlirOperation constOne = mlirOperationClone(constZero);
1696   mlirOperationSetAttributeByName(constOne, valueStringRef, indexOneLiteral);
1697 
1698   mlirOperationPrint(constZero, printToStderr, NULL);
1699   mlirOperationPrint(constOne, printToStderr, NULL);
1700   // CHECK: arith.constant 0 : index
1701   // CHECK: arith.constant 1 : index
1702 
1703   mlirOperationDestroy(constZero);
1704   mlirOperationDestroy(constOne);
1705   mlirContextDestroy(ctx);
1706   return 0;
1707 }
1708 
1709 // Wraps a diagnostic into additional text we can match against.
1710 MlirLogicalResult errorHandler(MlirDiagnostic diagnostic, void *userData) {
1711   fprintf(stderr, "processing diagnostic (userData: %" PRIdPTR ") <<\n",
1712           (intptr_t)userData);
1713   mlirDiagnosticPrint(diagnostic, printToStderr, NULL);
1714   fprintf(stderr, "\n");
1715   MlirLocation loc = mlirDiagnosticGetLocation(diagnostic);
1716   mlirLocationPrint(loc, printToStderr, NULL);
1717   assert(mlirDiagnosticGetNumNotes(diagnostic) == 0);
1718   fprintf(stderr, "\n>> end of diagnostic (userData: %" PRIdPTR ")\n",
1719           (intptr_t)userData);
1720   return mlirLogicalResultSuccess();
1721 }
1722 
1723 // Logs when the delete user data callback is called
1724 static void deleteUserData(void *userData) {
1725   fprintf(stderr, "deleting user data (userData: %" PRIdPTR ")\n",
1726           (intptr_t)userData);
1727 }
1728 
1729 int testTypeID(MlirContext ctx) {
1730   fprintf(stderr, "@testTypeID\n");
1731 
1732   // Test getting and comparing type and attribute type ids.
1733   MlirType i32 = mlirIntegerTypeGet(ctx, 32);
1734   MlirTypeID i32ID = mlirTypeGetTypeID(i32);
1735   MlirType ui32 = mlirIntegerTypeUnsignedGet(ctx, 32);
1736   MlirTypeID ui32ID = mlirTypeGetTypeID(ui32);
1737   MlirType f32 = mlirF32TypeGet(ctx);
1738   MlirTypeID f32ID = mlirTypeGetTypeID(f32);
1739   MlirAttribute i32Attr = mlirIntegerAttrGet(i32, 1);
1740   MlirTypeID i32AttrID = mlirAttributeGetTypeID(i32Attr);
1741 
1742   if (mlirTypeIDIsNull(i32ID) || mlirTypeIDIsNull(ui32ID) ||
1743       mlirTypeIDIsNull(f32ID) || mlirTypeIDIsNull(i32AttrID)) {
1744     fprintf(stderr, "ERROR: Expected type ids to be present\n");
1745     return 1;
1746   }
1747 
1748   if (!mlirTypeIDEqual(i32ID, ui32ID) ||
1749       mlirTypeIDHashValue(i32ID) != mlirTypeIDHashValue(ui32ID)) {
1750     fprintf(
1751         stderr,
1752         "ERROR: Expected different integer types to have the same type id\n");
1753     return 2;
1754   }
1755 
1756   if (mlirTypeIDEqual(i32ID, f32ID)) {
1757     fprintf(stderr,
1758             "ERROR: Expected integer type id to not equal float type id\n");
1759     return 3;
1760   }
1761 
1762   if (mlirTypeIDEqual(i32ID, i32AttrID)) {
1763     fprintf(stderr, "ERROR: Expected integer type id to not equal integer "
1764                     "attribute type id\n");
1765     return 4;
1766   }
1767 
1768   MlirLocation loc = mlirLocationUnknownGet(ctx);
1769   MlirType indexType = mlirIndexTypeGet(ctx);
1770   MlirStringRef valueStringRef = mlirStringRefCreateFromCString("value");
1771 
1772   // Create a registered operation, which should have a type id.
1773   MlirAttribute indexZeroLiteral =
1774       mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("0 : index"));
1775   MlirNamedAttribute indexZeroValueAttr = mlirNamedAttributeGet(
1776       mlirIdentifierGet(ctx, valueStringRef), indexZeroLiteral);
1777   MlirOperationState constZeroState = mlirOperationStateGet(
1778       mlirStringRefCreateFromCString("arith.constant"), loc);
1779   mlirOperationStateAddResults(&constZeroState, 1, &indexType);
1780   mlirOperationStateAddAttributes(&constZeroState, 1, &indexZeroValueAttr);
1781   MlirOperation constZero = mlirOperationCreate(&constZeroState);
1782 
1783   if (!mlirOperationVerify(constZero)) {
1784     fprintf(stderr, "ERROR: Expected operation to verify correctly\n");
1785     return 5;
1786   }
1787 
1788   if (mlirOperationIsNull(constZero)) {
1789     fprintf(stderr, "ERROR: Expected registered operation to be present\n");
1790     return 6;
1791   }
1792 
1793   MlirTypeID registeredOpID = mlirOperationGetTypeID(constZero);
1794 
1795   if (mlirTypeIDIsNull(registeredOpID)) {
1796     fprintf(stderr,
1797             "ERROR: Expected registered operation type id to be present\n");
1798     return 7;
1799   }
1800 
1801   // Create an unregistered operation, which should not have a type id.
1802   mlirContextSetAllowUnregisteredDialects(ctx, true);
1803   MlirOperationState opState =
1804       mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op"), loc);
1805   MlirOperation unregisteredOp = mlirOperationCreate(&opState);
1806   if (mlirOperationIsNull(unregisteredOp)) {
1807     fprintf(stderr, "ERROR: Expected unregistered operation to be present\n");
1808     return 8;
1809   }
1810 
1811   MlirTypeID unregisteredOpID = mlirOperationGetTypeID(unregisteredOp);
1812 
1813   if (!mlirTypeIDIsNull(unregisteredOpID)) {
1814     fprintf(stderr,
1815             "ERROR: Expected unregistered operation type id to be null\n");
1816     return 9;
1817   }
1818 
1819   mlirOperationDestroy(constZero);
1820   mlirOperationDestroy(unregisteredOp);
1821 
1822   return 0;
1823 }
1824 
1825 int testSymbolTable(MlirContext ctx) {
1826   fprintf(stderr, "@testSymbolTable\n");
1827 
1828   const char *moduleString = "func private @foo()"
1829                              "func private @bar()";
1830   const char *otherModuleString = "func private @qux()"
1831                                   "func private @foo()";
1832 
1833   MlirModule module =
1834       mlirModuleCreateParse(ctx, mlirStringRefCreateFromCString(moduleString));
1835   MlirModule otherModule = mlirModuleCreateParse(
1836       ctx, mlirStringRefCreateFromCString(otherModuleString));
1837 
1838   MlirSymbolTable symbolTable =
1839       mlirSymbolTableCreate(mlirModuleGetOperation(module));
1840 
1841   MlirOperation funcFoo =
1842       mlirSymbolTableLookup(symbolTable, mlirStringRefCreateFromCString("foo"));
1843   if (mlirOperationIsNull(funcFoo))
1844     return 1;
1845 
1846   MlirOperation funcBar =
1847       mlirSymbolTableLookup(symbolTable, mlirStringRefCreateFromCString("bar"));
1848   if (mlirOperationEqual(funcFoo, funcBar))
1849     return 2;
1850 
1851   MlirOperation missing =
1852       mlirSymbolTableLookup(symbolTable, mlirStringRefCreateFromCString("qux"));
1853   if (!mlirOperationIsNull(missing))
1854     return 3;
1855 
1856   MlirBlock moduleBody = mlirModuleGetBody(module);
1857   MlirBlock otherModuleBody = mlirModuleGetBody(otherModule);
1858   MlirOperation operation = mlirBlockGetFirstOperation(otherModuleBody);
1859   mlirOperationRemoveFromParent(operation);
1860   mlirBlockAppendOwnedOperation(moduleBody, operation);
1861 
1862   // At this moment, the operation is still missing from the symbol table.
1863   MlirOperation stillMissing =
1864       mlirSymbolTableLookup(symbolTable, mlirStringRefCreateFromCString("qux"));
1865   if (!mlirOperationIsNull(stillMissing))
1866     return 4;
1867 
1868   // After it is added to the symbol table, and not only the operation with
1869   // which the table is associated, it can be looked up.
1870   mlirSymbolTableInsert(symbolTable, operation);
1871   MlirOperation funcQux =
1872       mlirSymbolTableLookup(symbolTable, mlirStringRefCreateFromCString("qux"));
1873   if (!mlirOperationEqual(operation, funcQux))
1874     return 5;
1875 
1876   // Erasing from the symbol table also removes the operation.
1877   mlirSymbolTableErase(symbolTable, funcBar);
1878   MlirOperation nowMissing =
1879       mlirSymbolTableLookup(symbolTable, mlirStringRefCreateFromCString("bar"));
1880   if (!mlirOperationIsNull(nowMissing))
1881     return 6;
1882 
1883   // Adding a symbol with the same name to the table should rename.
1884   MlirOperation duplicateNameOp = mlirBlockGetFirstOperation(otherModuleBody);
1885   mlirOperationRemoveFromParent(duplicateNameOp);
1886   mlirBlockAppendOwnedOperation(moduleBody, duplicateNameOp);
1887   MlirAttribute newName = mlirSymbolTableInsert(symbolTable, duplicateNameOp);
1888   MlirStringRef newNameStr = mlirStringAttrGetValue(newName);
1889   if (mlirStringRefEqual(newNameStr, mlirStringRefCreateFromCString("foo")))
1890     return 7;
1891   MlirAttribute updatedName = mlirOperationGetAttributeByName(
1892       duplicateNameOp, mlirSymbolTableGetSymbolAttributeName());
1893   if (!mlirAttributeEqual(updatedName, newName))
1894     return 8;
1895 
1896   mlirOperationDump(mlirModuleGetOperation(module));
1897   mlirOperationDump(mlirModuleGetOperation(otherModule));
1898   // clang-format off
1899   // CHECK-LABEL: @testSymbolTable
1900   // CHECK: module
1901   // CHECK:   func private @foo
1902   // CHECK:   func private @qux
1903   // CHECK:   func private @foo{{.+}}
1904   // CHECK: module
1905   // CHECK-NOT: @qux
1906   // CHECK-NOT: @foo
1907   // clang-format on
1908 
1909   mlirSymbolTableDestroy(symbolTable);
1910   mlirModuleDestroy(module);
1911   mlirModuleDestroy(otherModule);
1912 
1913   return 0;
1914 }
1915 
1916 int testDialectRegistry() {
1917   fprintf(stderr, "@testDialectRegistry\n");
1918 
1919   MlirDialectRegistry registry = mlirDialectRegistryCreate();
1920   if (mlirDialectRegistryIsNull(registry)) {
1921     fprintf(stderr, "ERROR: Expected registry to be present\n");
1922     return 1;
1923   }
1924 
1925   MlirDialectHandle stdHandle = mlirGetDialectHandle__func__();
1926   mlirDialectHandleInsertDialect(stdHandle, registry);
1927 
1928   MlirContext ctx = mlirContextCreate();
1929   if (mlirContextGetNumRegisteredDialects(ctx) != 0) {
1930     fprintf(stderr,
1931             "ERROR: Expected no dialects to be registered to new context\n");
1932   }
1933 
1934   mlirContextAppendDialectRegistry(ctx, registry);
1935   if (mlirContextGetNumRegisteredDialects(ctx) != 1) {
1936     fprintf(stderr, "ERROR: Expected the dialect in the registry to be "
1937                     "registered to the context\n");
1938   }
1939 
1940   mlirContextDestroy(ctx);
1941   mlirDialectRegistryDestroy(registry);
1942 
1943   return 0;
1944 }
1945 
1946 void testDiagnostics() {
1947   MlirContext ctx = mlirContextCreate();
1948   MlirDiagnosticHandlerID id = mlirContextAttachDiagnosticHandler(
1949       ctx, errorHandler, (void *)42, deleteUserData);
1950   fprintf(stderr, "@test_diagnostics\n");
1951   MlirLocation unknownLoc = mlirLocationUnknownGet(ctx);
1952   mlirEmitError(unknownLoc, "test diagnostics");
1953   MlirLocation fileLineColLoc = mlirLocationFileLineColGet(
1954       ctx, mlirStringRefCreateFromCString("file.c"), 1, 2);
1955   mlirEmitError(fileLineColLoc, "test diagnostics");
1956   MlirLocation callSiteLoc = mlirLocationCallSiteGet(
1957       mlirLocationFileLineColGet(
1958           ctx, mlirStringRefCreateFromCString("other-file.c"), 2, 3),
1959       fileLineColLoc);
1960   mlirEmitError(callSiteLoc, "test diagnostics");
1961   MlirLocation null = {0};
1962   MlirLocation nameLoc =
1963       mlirLocationNameGet(ctx, mlirStringRefCreateFromCString("named"), null);
1964   mlirEmitError(nameLoc, "test diagnostics");
1965   MlirLocation locs[2] = {nameLoc, callSiteLoc};
1966   MlirAttribute nullAttr = {0};
1967   MlirLocation fusedLoc = mlirLocationFusedGet(ctx, 2, locs, nullAttr);
1968   mlirEmitError(fusedLoc, "test diagnostics");
1969   mlirContextDetachDiagnosticHandler(ctx, id);
1970   mlirEmitError(unknownLoc, "more test diagnostics");
1971   // CHECK-LABEL: @test_diagnostics
1972   // CHECK: processing diagnostic (userData: 42) <<
1973   // CHECK:   test diagnostics
1974   // CHECK:   loc(unknown)
1975   // CHECK: >> end of diagnostic (userData: 42)
1976   // CHECK: processing diagnostic (userData: 42) <<
1977   // CHECK:   test diagnostics
1978   // CHECK:   loc("file.c":1:2)
1979   // CHECK: >> end of diagnostic (userData: 42)
1980   // CHECK: processing diagnostic (userData: 42) <<
1981   // CHECK:   test diagnostics
1982   // CHECK:   loc(callsite("other-file.c":2:3 at "file.c":1:2))
1983   // CHECK: >> end of diagnostic (userData: 42)
1984   // CHECK: processing diagnostic (userData: 42) <<
1985   // CHECK:   test diagnostics
1986   // CHECK:   loc("named")
1987   // CHECK: >> end of diagnostic (userData: 42)
1988   // CHECK: processing diagnostic (userData: 42) <<
1989   // CHECK:   test diagnostics
1990   // CHECK:   loc(fused["named", callsite("other-file.c":2:3 at "file.c":1:2)])
1991   // CHECK: deleting user data (userData: 42)
1992   // CHECK-NOT: processing diagnostic
1993   // CHECK:     more test diagnostics
1994   mlirContextDestroy(ctx);
1995 }
1996 
1997 int main() {
1998   MlirContext ctx = mlirContextCreate();
1999   mlirRegisterAllDialects(ctx);
2000   if (constructAndTraverseIr(ctx))
2001     return 1;
2002   buildWithInsertionsAndPrint(ctx);
2003   if (createOperationWithTypeInference(ctx))
2004     return 2;
2005 
2006   if (printBuiltinTypes(ctx))
2007     return 3;
2008   if (printBuiltinAttributes(ctx))
2009     return 4;
2010   if (printAffineMap(ctx))
2011     return 5;
2012   if (printAffineExpr(ctx))
2013     return 6;
2014   if (affineMapFromExprs(ctx))
2015     return 7;
2016   if (printIntegerSet(ctx))
2017     return 8;
2018   if (registerOnlyStd())
2019     return 9;
2020   if (testBackreferences())
2021     return 10;
2022   if (testOperands())
2023     return 11;
2024   if (testClone())
2025     return 12;
2026   if (testTypeID(ctx))
2027     return 13;
2028   if (testSymbolTable(ctx))
2029     return 14;
2030   if (testDialectRegistry())
2031     return 15;
2032 
2033   mlirContextDestroy(ctx);
2034 
2035   testDiagnostics();
2036   return 0;
2037 }
2038