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/Standard.h" 20 #include "mlir-c/IntegerSet.h" 21 #include "mlir-c/Registration.h" 22 23 #include <assert.h> 24 #include <math.h> 25 #include <stdio.h> 26 #include <stdlib.h> 27 #include <string.h> 28 29 void populateLoopBody(MlirContext ctx, MlirBlock loopBody, 30 MlirLocation location, MlirBlock funcBody) { 31 MlirValue iv = mlirBlockGetArgument(loopBody, 0); 32 MlirValue funcArg0 = mlirBlockGetArgument(funcBody, 0); 33 MlirValue funcArg1 = mlirBlockGetArgument(funcBody, 1); 34 MlirType f32Type = 35 mlirTypeParseGet(ctx, mlirStringRefCreateFromCString("f32")); 36 37 MlirOperationState loadLHSState = mlirOperationStateGet( 38 mlirStringRefCreateFromCString("std.load"), location); 39 MlirValue loadLHSOperands[] = {funcArg0, iv}; 40 mlirOperationStateAddOperands(&loadLHSState, 2, loadLHSOperands); 41 mlirOperationStateAddResults(&loadLHSState, 1, &f32Type); 42 MlirOperation loadLHS = mlirOperationCreate(&loadLHSState); 43 mlirBlockAppendOwnedOperation(loopBody, loadLHS); 44 45 MlirOperationState loadRHSState = mlirOperationStateGet( 46 mlirStringRefCreateFromCString("std.load"), location); 47 MlirValue loadRHSOperands[] = {funcArg1, iv}; 48 mlirOperationStateAddOperands(&loadRHSState, 2, loadRHSOperands); 49 mlirOperationStateAddResults(&loadRHSState, 1, &f32Type); 50 MlirOperation loadRHS = mlirOperationCreate(&loadRHSState); 51 mlirBlockAppendOwnedOperation(loopBody, loadRHS); 52 53 MlirOperationState addState = mlirOperationStateGet( 54 mlirStringRefCreateFromCString("std.addf"), location); 55 MlirValue addOperands[] = {mlirOperationGetResult(loadLHS, 0), 56 mlirOperationGetResult(loadRHS, 0)}; 57 mlirOperationStateAddOperands(&addState, 2, addOperands); 58 mlirOperationStateAddResults(&addState, 1, &f32Type); 59 MlirOperation add = mlirOperationCreate(&addState); 60 mlirBlockAppendOwnedOperation(loopBody, add); 61 62 MlirOperationState storeState = mlirOperationStateGet( 63 mlirStringRefCreateFromCString("std.store"), location); 64 MlirValue storeOperands[] = {mlirOperationGetResult(add, 0), funcArg0, iv}; 65 mlirOperationStateAddOperands(&storeState, 3, storeOperands); 66 MlirOperation store = mlirOperationCreate(&storeState); 67 mlirBlockAppendOwnedOperation(loopBody, store); 68 69 MlirOperationState yieldState = mlirOperationStateGet( 70 mlirStringRefCreateFromCString("scf.yield"), location); 71 MlirOperation yield = mlirOperationCreate(&yieldState); 72 mlirBlockAppendOwnedOperation(loopBody, yield); 73 } 74 75 MlirModule makeAndDumpAdd(MlirContext ctx, MlirLocation location) { 76 MlirModule moduleOp = mlirModuleCreateEmpty(location); 77 MlirBlock moduleBody = mlirModuleGetBody(moduleOp); 78 79 MlirType memrefType = 80 mlirTypeParseGet(ctx, mlirStringRefCreateFromCString("memref<?xf32>")); 81 MlirType funcBodyArgTypes[] = {memrefType, memrefType}; 82 MlirRegion funcBodyRegion = mlirRegionCreate(); 83 MlirBlock funcBody = mlirBlockCreate( 84 sizeof(funcBodyArgTypes) / sizeof(MlirType), funcBodyArgTypes); 85 mlirRegionAppendOwnedBlock(funcBodyRegion, funcBody); 86 87 MlirAttribute funcTypeAttr = mlirAttributeParseGet( 88 ctx, 89 mlirStringRefCreateFromCString("(memref<?xf32>, memref<?xf32>) -> ()")); 90 MlirAttribute funcNameAttr = 91 mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("\"add\"")); 92 MlirNamedAttribute funcAttrs[] = { 93 mlirNamedAttributeGet( 94 mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("type")), 95 funcTypeAttr), 96 mlirNamedAttributeGet( 97 mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("sym_name")), 98 funcNameAttr)}; 99 MlirOperationState funcState = 100 mlirOperationStateGet(mlirStringRefCreateFromCString("func"), location); 101 mlirOperationStateAddAttributes(&funcState, 2, funcAttrs); 102 mlirOperationStateAddOwnedRegions(&funcState, 1, &funcBodyRegion); 103 MlirOperation func = mlirOperationCreate(&funcState); 104 mlirBlockInsertOwnedOperation(moduleBody, 0, func); 105 106 MlirType indexType = 107 mlirTypeParseGet(ctx, mlirStringRefCreateFromCString("index")); 108 MlirAttribute indexZeroLiteral = 109 mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("0 : index")); 110 MlirNamedAttribute indexZeroValueAttr = mlirNamedAttributeGet( 111 mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("value")), 112 indexZeroLiteral); 113 MlirOperationState constZeroState = mlirOperationStateGet( 114 mlirStringRefCreateFromCString("std.constant"), location); 115 mlirOperationStateAddResults(&constZeroState, 1, &indexType); 116 mlirOperationStateAddAttributes(&constZeroState, 1, &indexZeroValueAttr); 117 MlirOperation constZero = mlirOperationCreate(&constZeroState); 118 mlirBlockAppendOwnedOperation(funcBody, constZero); 119 120 MlirValue funcArg0 = mlirBlockGetArgument(funcBody, 0); 121 MlirValue constZeroValue = mlirOperationGetResult(constZero, 0); 122 MlirValue dimOperands[] = {funcArg0, constZeroValue}; 123 MlirOperationState dimState = mlirOperationStateGet( 124 mlirStringRefCreateFromCString("std.dim"), location); 125 mlirOperationStateAddOperands(&dimState, 2, dimOperands); 126 mlirOperationStateAddResults(&dimState, 1, &indexType); 127 MlirOperation dim = mlirOperationCreate(&dimState); 128 mlirBlockAppendOwnedOperation(funcBody, dim); 129 130 MlirRegion loopBodyRegion = mlirRegionCreate(); 131 MlirBlock loopBody = mlirBlockCreate(0, NULL); 132 mlirBlockAddArgument(loopBody, indexType); 133 mlirRegionAppendOwnedBlock(loopBodyRegion, loopBody); 134 135 MlirAttribute indexOneLiteral = 136 mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("1 : index")); 137 MlirNamedAttribute indexOneValueAttr = mlirNamedAttributeGet( 138 mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("value")), 139 indexOneLiteral); 140 MlirOperationState constOneState = mlirOperationStateGet( 141 mlirStringRefCreateFromCString("std.constant"), location); 142 mlirOperationStateAddResults(&constOneState, 1, &indexType); 143 mlirOperationStateAddAttributes(&constOneState, 1, &indexOneValueAttr); 144 MlirOperation constOne = mlirOperationCreate(&constOneState); 145 mlirBlockAppendOwnedOperation(funcBody, constOne); 146 147 MlirValue dimValue = mlirOperationGetResult(dim, 0); 148 MlirValue constOneValue = mlirOperationGetResult(constOne, 0); 149 MlirValue loopOperands[] = {constZeroValue, dimValue, constOneValue}; 150 MlirOperationState loopState = mlirOperationStateGet( 151 mlirStringRefCreateFromCString("scf.for"), location); 152 mlirOperationStateAddOperands(&loopState, 3, loopOperands); 153 mlirOperationStateAddOwnedRegions(&loopState, 1, &loopBodyRegion); 154 MlirOperation loop = mlirOperationCreate(&loopState); 155 mlirBlockAppendOwnedOperation(funcBody, loop); 156 157 populateLoopBody(ctx, loopBody, location, funcBody); 158 159 MlirOperationState retState = mlirOperationStateGet( 160 mlirStringRefCreateFromCString("std.return"), location); 161 MlirOperation ret = mlirOperationCreate(&retState); 162 mlirBlockAppendOwnedOperation(funcBody, ret); 163 164 MlirOperation module = mlirModuleGetOperation(moduleOp); 165 mlirOperationDump(module); 166 // clang-format off 167 // CHECK: module { 168 // CHECK: func @add(%[[ARG0:.*]]: memref<?xf32>, %[[ARG1:.*]]: memref<?xf32>) { 169 // CHECK: %[[C0:.*]] = constant 0 : index 170 // CHECK: %[[DIM:.*]] = dim %[[ARG0]], %[[C0]] : memref<?xf32> 171 // CHECK: %[[C1:.*]] = constant 1 : index 172 // CHECK: scf.for %[[I:.*]] = %[[C0]] to %[[DIM]] step %[[C1]] { 173 // CHECK: %[[LHS:.*]] = load %[[ARG0]][%[[I]]] : memref<?xf32> 174 // CHECK: %[[RHS:.*]] = load %[[ARG1]][%[[I]]] : memref<?xf32> 175 // CHECK: %[[SUM:.*]] = addf %[[LHS]], %[[RHS]] : f32 176 // CHECK: store %[[SUM]], %[[ARG0]][%[[I]]] : memref<?xf32> 177 // CHECK: } 178 // CHECK: return 179 // CHECK: } 180 // CHECK: } 181 // clang-format on 182 183 return moduleOp; 184 } 185 186 struct OpListNode { 187 MlirOperation op; 188 struct OpListNode *next; 189 }; 190 typedef struct OpListNode OpListNode; 191 192 struct ModuleStats { 193 unsigned numOperations; 194 unsigned numAttributes; 195 unsigned numBlocks; 196 unsigned numRegions; 197 unsigned numValues; 198 unsigned numBlockArguments; 199 unsigned numOpResults; 200 }; 201 typedef struct ModuleStats ModuleStats; 202 203 int collectStatsSingle(OpListNode *head, ModuleStats *stats) { 204 MlirOperation operation = head->op; 205 stats->numOperations += 1; 206 stats->numValues += mlirOperationGetNumResults(operation); 207 stats->numAttributes += mlirOperationGetNumAttributes(operation); 208 209 unsigned numRegions = mlirOperationGetNumRegions(operation); 210 211 stats->numRegions += numRegions; 212 213 intptr_t numResults = mlirOperationGetNumResults(operation); 214 for (intptr_t i = 0; i < numResults; ++i) { 215 MlirValue result = mlirOperationGetResult(operation, i); 216 if (!mlirValueIsAOpResult(result)) 217 return 1; 218 if (mlirValueIsABlockArgument(result)) 219 return 2; 220 if (!mlirOperationEqual(operation, mlirOpResultGetOwner(result))) 221 return 3; 222 if (i != mlirOpResultGetResultNumber(result)) 223 return 4; 224 ++stats->numOpResults; 225 } 226 227 for (unsigned i = 0; i < numRegions; ++i) { 228 MlirRegion region = mlirOperationGetRegion(operation, i); 229 for (MlirBlock block = mlirRegionGetFirstBlock(region); 230 !mlirBlockIsNull(block); block = mlirBlockGetNextInRegion(block)) { 231 ++stats->numBlocks; 232 intptr_t numArgs = mlirBlockGetNumArguments(block); 233 stats->numValues += numArgs; 234 for (intptr_t j = 0; j < numArgs; ++j) { 235 MlirValue arg = mlirBlockGetArgument(block, j); 236 if (!mlirValueIsABlockArgument(arg)) 237 return 5; 238 if (mlirValueIsAOpResult(arg)) 239 return 6; 240 if (!mlirBlockEqual(block, mlirBlockArgumentGetOwner(arg))) 241 return 7; 242 if (j != mlirBlockArgumentGetArgNumber(arg)) 243 return 8; 244 ++stats->numBlockArguments; 245 } 246 247 for (MlirOperation child = mlirBlockGetFirstOperation(block); 248 !mlirOperationIsNull(child); 249 child = mlirOperationGetNextInBlock(child)) { 250 OpListNode *node = malloc(sizeof(OpListNode)); 251 node->op = child; 252 node->next = head->next; 253 head->next = node; 254 } 255 } 256 } 257 return 0; 258 } 259 260 int collectStats(MlirOperation operation) { 261 OpListNode *head = malloc(sizeof(OpListNode)); 262 head->op = operation; 263 head->next = NULL; 264 265 ModuleStats stats; 266 stats.numOperations = 0; 267 stats.numAttributes = 0; 268 stats.numBlocks = 0; 269 stats.numRegions = 0; 270 stats.numValues = 0; 271 stats.numBlockArguments = 0; 272 stats.numOpResults = 0; 273 274 do { 275 int retval = collectStatsSingle(head, &stats); 276 if (retval) 277 return retval; 278 OpListNode *next = head->next; 279 free(head); 280 head = next; 281 } while (head); 282 283 if (stats.numValues != stats.numBlockArguments + stats.numOpResults) 284 return 100; 285 286 fprintf(stderr, "@stats\n"); 287 fprintf(stderr, "Number of operations: %u\n", stats.numOperations); 288 fprintf(stderr, "Number of attributes: %u\n", stats.numAttributes); 289 fprintf(stderr, "Number of blocks: %u\n", stats.numBlocks); 290 fprintf(stderr, "Number of regions: %u\n", stats.numRegions); 291 fprintf(stderr, "Number of values: %u\n", stats.numValues); 292 fprintf(stderr, "Number of block arguments: %u\n", stats.numBlockArguments); 293 fprintf(stderr, "Number of op results: %u\n", stats.numOpResults); 294 // clang-format off 295 // CHECK-LABEL: @stats 296 // CHECK: Number of operations: 13 297 // CHECK: Number of attributes: 4 298 // CHECK: Number of blocks: 3 299 // CHECK: Number of regions: 3 300 // CHECK: Number of values: 9 301 // CHECK: Number of block arguments: 3 302 // CHECK: Number of op results: 6 303 // clang-format on 304 return 0; 305 } 306 307 static void printToStderr(MlirStringRef str, void *userData) { 308 (void)userData; 309 fwrite(str.data, 1, str.length, stderr); 310 } 311 312 static void printFirstOfEach(MlirContext ctx, MlirOperation operation) { 313 // Assuming we are given a module, go to the first operation of the first 314 // function. 315 MlirRegion region = mlirOperationGetRegion(operation, 0); 316 MlirBlock block = mlirRegionGetFirstBlock(region); 317 operation = mlirBlockGetFirstOperation(block); 318 region = mlirOperationGetRegion(operation, 0); 319 MlirOperation parentOperation = operation; 320 block = mlirRegionGetFirstBlock(region); 321 operation = mlirBlockGetFirstOperation(block); 322 323 // Verify that parent operation and block report correctly. 324 fprintf(stderr, "Parent operation eq: %d\n", 325 mlirOperationEqual(mlirOperationGetParentOperation(operation), 326 parentOperation)); 327 fprintf(stderr, "Block eq: %d\n", 328 mlirBlockEqual(mlirOperationGetBlock(operation), block)); 329 // CHECK: Parent operation eq: 1 330 // CHECK: Block eq: 1 331 332 // In the module we created, the first operation of the first function is 333 // an "std.dim", which has an attribute and a single result that we can 334 // use to test the printing mechanism. 335 mlirBlockPrint(block, printToStderr, NULL); 336 fprintf(stderr, "\n"); 337 fprintf(stderr, "First operation: "); 338 mlirOperationPrint(operation, printToStderr, NULL); 339 fprintf(stderr, "\n"); 340 // clang-format off 341 // CHECK: %[[C0:.*]] = constant 0 : index 342 // CHECK: %[[DIM:.*]] = dim %{{.*}}, %[[C0]] : memref<?xf32> 343 // CHECK: %[[C1:.*]] = constant 1 : index 344 // CHECK: scf.for %[[I:.*]] = %[[C0]] to %[[DIM]] step %[[C1]] { 345 // CHECK: %[[LHS:.*]] = load %{{.*}}[%[[I]]] : memref<?xf32> 346 // CHECK: %[[RHS:.*]] = load %{{.*}}[%[[I]]] : memref<?xf32> 347 // CHECK: %[[SUM:.*]] = addf %[[LHS]], %[[RHS]] : f32 348 // CHECK: store %[[SUM]], %{{.*}}[%[[I]]] : memref<?xf32> 349 // CHECK: } 350 // CHECK: return 351 // CHECK: First operation: {{.*}} = constant 0 : index 352 // clang-format on 353 354 // Get the operation name and print it. 355 MlirIdentifier ident = mlirOperationGetName(operation); 356 MlirStringRef identStr = mlirIdentifierStr(ident); 357 fprintf(stderr, "Operation name: '"); 358 for (size_t i = 0; i < identStr.length; ++i) 359 fputc(identStr.data[i], stderr); 360 fprintf(stderr, "'\n"); 361 // CHECK: Operation name: 'std.constant' 362 363 // Get the identifier again and verify equal. 364 MlirIdentifier identAgain = mlirIdentifierGet(ctx, identStr); 365 fprintf(stderr, "Identifier equal: %d\n", 366 mlirIdentifierEqual(ident, identAgain)); 367 // CHECK: Identifier equal: 1 368 369 // Get the block terminator and print it. 370 MlirOperation terminator = mlirBlockGetTerminator(block); 371 fprintf(stderr, "Terminator: "); 372 mlirOperationPrint(terminator, printToStderr, NULL); 373 fprintf(stderr, "\n"); 374 // CHECK: Terminator: return 375 376 // Get the attribute by index. 377 MlirNamedAttribute namedAttr0 = mlirOperationGetAttribute(operation, 0); 378 fprintf(stderr, "Get attr 0: "); 379 mlirAttributePrint(namedAttr0.attribute, printToStderr, NULL); 380 fprintf(stderr, "\n"); 381 // CHECK: Get attr 0: 0 : index 382 383 // Now re-get the attribute by name. 384 MlirAttribute attr0ByName = mlirOperationGetAttributeByName( 385 operation, mlirIdentifierStr(namedAttr0.name)); 386 fprintf(stderr, "Get attr 0 by name: "); 387 mlirAttributePrint(attr0ByName, printToStderr, NULL); 388 fprintf(stderr, "\n"); 389 // CHECK: Get attr 0 by name: 0 : index 390 391 // Get a non-existing attribute and assert that it is null (sanity). 392 fprintf(stderr, "does_not_exist is null: %d\n", 393 mlirAttributeIsNull(mlirOperationGetAttributeByName( 394 operation, mlirStringRefCreateFromCString("does_not_exist")))); 395 // CHECK: does_not_exist is null: 1 396 397 // Get result 0 and its type. 398 MlirValue value = mlirOperationGetResult(operation, 0); 399 fprintf(stderr, "Result 0: "); 400 mlirValuePrint(value, printToStderr, NULL); 401 fprintf(stderr, "\n"); 402 fprintf(stderr, "Value is null: %d\n", mlirValueIsNull(value)); 403 // CHECK: Result 0: {{.*}} = constant 0 : index 404 // CHECK: Value is null: 0 405 406 MlirType type = mlirValueGetType(value); 407 fprintf(stderr, "Result 0 type: "); 408 mlirTypePrint(type, printToStderr, NULL); 409 fprintf(stderr, "\n"); 410 // CHECK: Result 0 type: index 411 412 // Set a custom attribute. 413 mlirOperationSetAttributeByName(operation, 414 mlirStringRefCreateFromCString("custom_attr"), 415 mlirBoolAttrGet(ctx, 1)); 416 fprintf(stderr, "Op with set attr: "); 417 mlirOperationPrint(operation, printToStderr, NULL); 418 fprintf(stderr, "\n"); 419 // CHECK: Op with set attr: {{.*}} {custom_attr = true} 420 421 // Remove the attribute. 422 fprintf(stderr, "Remove attr: %d\n", 423 mlirOperationRemoveAttributeByName( 424 operation, mlirStringRefCreateFromCString("custom_attr"))); 425 fprintf(stderr, "Remove attr again: %d\n", 426 mlirOperationRemoveAttributeByName( 427 operation, mlirStringRefCreateFromCString("custom_attr"))); 428 fprintf(stderr, "Removed attr is null: %d\n", 429 mlirAttributeIsNull(mlirOperationGetAttributeByName( 430 operation, mlirStringRefCreateFromCString("custom_attr")))); 431 // CHECK: Remove attr: 1 432 // CHECK: Remove attr again: 0 433 // CHECK: Removed attr is null: 1 434 435 // Add a large attribute to verify printing flags. 436 int64_t eltsShape[] = {4}; 437 int32_t eltsData[] = {1, 2, 3, 4}; 438 mlirOperationSetAttributeByName( 439 operation, mlirStringRefCreateFromCString("elts"), 440 mlirDenseElementsAttrInt32Get( 441 mlirRankedTensorTypeGet(1, eltsShape, mlirIntegerTypeGet(ctx, 32)), 4, 442 eltsData)); 443 MlirOpPrintingFlags flags = mlirOpPrintingFlagsCreate(); 444 mlirOpPrintingFlagsElideLargeElementsAttrs(flags, 2); 445 mlirOpPrintingFlagsPrintGenericOpForm(flags); 446 mlirOpPrintingFlagsEnableDebugInfo(flags, /*prettyForm=*/0); 447 mlirOpPrintingFlagsUseLocalScope(flags); 448 fprintf(stderr, "Op print with all flags: "); 449 mlirOperationPrintWithFlags(operation, flags, printToStderr, NULL); 450 fprintf(stderr, "\n"); 451 // clang-format off 452 // CHECK: Op print with all flags: %{{.*}} = "std.constant"() {elts = opaque<"", "0xDEADBEEF"> : tensor<4xi32>, value = 0 : index} : () -> index loc(unknown) 453 // clang-format on 454 455 mlirOpPrintingFlagsDestroy(flags); 456 } 457 458 static int constructAndTraverseIr(MlirContext ctx) { 459 MlirLocation location = mlirLocationUnknownGet(ctx); 460 461 MlirModule moduleOp = makeAndDumpAdd(ctx, location); 462 MlirOperation module = mlirModuleGetOperation(moduleOp); 463 464 int errcode = collectStats(module); 465 if (errcode) 466 return errcode; 467 468 printFirstOfEach(ctx, module); 469 470 mlirModuleDestroy(moduleOp); 471 return 0; 472 } 473 474 /// Creates an operation with a region containing multiple blocks with 475 /// operations and dumps it. The blocks and operations are inserted using 476 /// block/operation-relative API and their final order is checked. 477 static void buildWithInsertionsAndPrint(MlirContext ctx) { 478 MlirLocation loc = mlirLocationUnknownGet(ctx); 479 480 MlirRegion owningRegion = mlirRegionCreate(); 481 MlirBlock nullBlock = mlirRegionGetFirstBlock(owningRegion); 482 MlirOperationState state = mlirOperationStateGet( 483 mlirStringRefCreateFromCString("insertion.order.test"), loc); 484 mlirOperationStateAddOwnedRegions(&state, 1, &owningRegion); 485 MlirOperation op = mlirOperationCreate(&state); 486 MlirRegion region = mlirOperationGetRegion(op, 0); 487 488 // Use integer types of different bitwidth as block arguments in order to 489 // differentiate blocks. 490 MlirType i1 = mlirIntegerTypeGet(ctx, 1); 491 MlirType i2 = mlirIntegerTypeGet(ctx, 2); 492 MlirType i3 = mlirIntegerTypeGet(ctx, 3); 493 MlirType i4 = mlirIntegerTypeGet(ctx, 4); 494 MlirBlock block1 = mlirBlockCreate(1, &i1); 495 MlirBlock block2 = mlirBlockCreate(1, &i2); 496 MlirBlock block3 = mlirBlockCreate(1, &i3); 497 MlirBlock block4 = mlirBlockCreate(1, &i4); 498 // Insert blocks so as to obtain the 1-2-3-4 order, 499 mlirRegionInsertOwnedBlockBefore(region, nullBlock, block3); 500 mlirRegionInsertOwnedBlockBefore(region, block3, block2); 501 mlirRegionInsertOwnedBlockAfter(region, nullBlock, block1); 502 mlirRegionInsertOwnedBlockAfter(region, block3, block4); 503 504 MlirOperationState op1State = 505 mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op1"), loc); 506 MlirOperationState op2State = 507 mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op2"), loc); 508 MlirOperationState op3State = 509 mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op3"), loc); 510 MlirOperationState op4State = 511 mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op4"), loc); 512 MlirOperationState op5State = 513 mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op5"), loc); 514 MlirOperationState op6State = 515 mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op6"), loc); 516 MlirOperationState op7State = 517 mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op7"), loc); 518 MlirOperation op1 = mlirOperationCreate(&op1State); 519 MlirOperation op2 = mlirOperationCreate(&op2State); 520 MlirOperation op3 = mlirOperationCreate(&op3State); 521 MlirOperation op4 = mlirOperationCreate(&op4State); 522 MlirOperation op5 = mlirOperationCreate(&op5State); 523 MlirOperation op6 = mlirOperationCreate(&op6State); 524 MlirOperation op7 = mlirOperationCreate(&op7State); 525 526 // Insert operations in the first block so as to obtain the 1-2-3-4 order. 527 MlirOperation nullOperation = mlirBlockGetFirstOperation(block1); 528 assert(mlirOperationIsNull(nullOperation)); 529 mlirBlockInsertOwnedOperationBefore(block1, nullOperation, op3); 530 mlirBlockInsertOwnedOperationBefore(block1, op3, op2); 531 mlirBlockInsertOwnedOperationAfter(block1, nullOperation, op1); 532 mlirBlockInsertOwnedOperationAfter(block1, op3, op4); 533 534 // Append operations to the rest of blocks to make them non-empty and thus 535 // printable. 536 mlirBlockAppendOwnedOperation(block2, op5); 537 mlirBlockAppendOwnedOperation(block3, op6); 538 mlirBlockAppendOwnedOperation(block4, op7); 539 540 mlirOperationDump(op); 541 mlirOperationDestroy(op); 542 // clang-format off 543 // CHECK-LABEL: "insertion.order.test" 544 // CHECK: ^{{.*}}(%{{.*}}: i1 545 // CHECK: "dummy.op1" 546 // CHECK-NEXT: "dummy.op2" 547 // CHECK-NEXT: "dummy.op3" 548 // CHECK-NEXT: "dummy.op4" 549 // CHECK: ^{{.*}}(%{{.*}}: i2 550 // CHECK: "dummy.op5" 551 // CHECK: ^{{.*}}(%{{.*}}: i3 552 // CHECK: "dummy.op6" 553 // CHECK: ^{{.*}}(%{{.*}}: i4 554 // CHECK: "dummy.op7" 555 // clang-format on 556 } 557 558 /// Creates operations with type inference and tests various failure modes. 559 static int createOperationWithTypeInference(MlirContext ctx) { 560 MlirLocation loc = mlirLocationUnknownGet(ctx); 561 MlirAttribute iAttr = mlirIntegerAttrGet(mlirIntegerTypeGet(ctx, 32), 4); 562 563 // The shape.const_size op implements result type inference and is only used 564 // for that reason. 565 MlirOperationState state = mlirOperationStateGet( 566 mlirStringRefCreateFromCString("shape.const_size"), loc); 567 MlirNamedAttribute valueAttr = mlirNamedAttributeGet( 568 mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("value")), iAttr); 569 mlirOperationStateAddAttributes(&state, 1, &valueAttr); 570 mlirOperationStateEnableResultTypeInference(&state); 571 572 // Expect result type inference to succeed. 573 MlirOperation op = mlirOperationCreate(&state); 574 if (mlirOperationIsNull(op)) { 575 fprintf(stderr, "ERROR: Result type inference unexpectedly failed"); 576 return 1; 577 } 578 579 // CHECK: RESULT_TYPE_INFERENCE: !shape.size 580 fprintf(stderr, "RESULT_TYPE_INFERENCE: "); 581 mlirTypeDump(mlirValueGetType(mlirOperationGetResult(op, 0))); 582 fprintf(stderr, "\n"); 583 mlirOperationDestroy(op); 584 return 0; 585 } 586 587 /// Dumps instances of all builtin types to check that C API works correctly. 588 /// Additionally, performs simple identity checks that a builtin type 589 /// constructed with C API can be inspected and has the expected type. The 590 /// latter achieves full coverage of C API for builtin types. Returns 0 on 591 /// success and a non-zero error code on failure. 592 static int printBuiltinTypes(MlirContext ctx) { 593 // Integer types. 594 MlirType i32 = mlirIntegerTypeGet(ctx, 32); 595 MlirType si32 = mlirIntegerTypeSignedGet(ctx, 32); 596 MlirType ui32 = mlirIntegerTypeUnsignedGet(ctx, 32); 597 if (!mlirTypeIsAInteger(i32) || mlirTypeIsAF32(i32)) 598 return 1; 599 if (!mlirTypeIsAInteger(si32) || !mlirIntegerTypeIsSigned(si32)) 600 return 2; 601 if (!mlirTypeIsAInteger(ui32) || !mlirIntegerTypeIsUnsigned(ui32)) 602 return 3; 603 if (mlirTypeEqual(i32, ui32) || mlirTypeEqual(i32, si32)) 604 return 4; 605 if (mlirIntegerTypeGetWidth(i32) != mlirIntegerTypeGetWidth(si32)) 606 return 5; 607 fprintf(stderr, "@types\n"); 608 mlirTypeDump(i32); 609 fprintf(stderr, "\n"); 610 mlirTypeDump(si32); 611 fprintf(stderr, "\n"); 612 mlirTypeDump(ui32); 613 fprintf(stderr, "\n"); 614 // CHECK-LABEL: @types 615 // CHECK: i32 616 // CHECK: si32 617 // CHECK: ui32 618 619 // Index type. 620 MlirType index = mlirIndexTypeGet(ctx); 621 if (!mlirTypeIsAIndex(index)) 622 return 6; 623 mlirTypeDump(index); 624 fprintf(stderr, "\n"); 625 // CHECK: index 626 627 // Floating-point types. 628 MlirType bf16 = mlirBF16TypeGet(ctx); 629 MlirType f16 = mlirF16TypeGet(ctx); 630 MlirType f32 = mlirF32TypeGet(ctx); 631 MlirType f64 = mlirF64TypeGet(ctx); 632 if (!mlirTypeIsABF16(bf16)) 633 return 7; 634 if (!mlirTypeIsAF16(f16)) 635 return 9; 636 if (!mlirTypeIsAF32(f32)) 637 return 10; 638 if (!mlirTypeIsAF64(f64)) 639 return 11; 640 mlirTypeDump(bf16); 641 fprintf(stderr, "\n"); 642 mlirTypeDump(f16); 643 fprintf(stderr, "\n"); 644 mlirTypeDump(f32); 645 fprintf(stderr, "\n"); 646 mlirTypeDump(f64); 647 fprintf(stderr, "\n"); 648 // CHECK: bf16 649 // CHECK: f16 650 // CHECK: f32 651 // CHECK: f64 652 653 // None type. 654 MlirType none = mlirNoneTypeGet(ctx); 655 if (!mlirTypeIsANone(none)) 656 return 12; 657 mlirTypeDump(none); 658 fprintf(stderr, "\n"); 659 // CHECK: none 660 661 // Complex type. 662 MlirType cplx = mlirComplexTypeGet(f32); 663 if (!mlirTypeIsAComplex(cplx) || 664 !mlirTypeEqual(mlirComplexTypeGetElementType(cplx), f32)) 665 return 13; 666 mlirTypeDump(cplx); 667 fprintf(stderr, "\n"); 668 // CHECK: complex<f32> 669 670 // Vector (and Shaped) type. ShapedType is a common base class for vectors, 671 // memrefs and tensors, one cannot create instances of this class so it is 672 // tested on an instance of vector type. 673 int64_t shape[] = {2, 3}; 674 MlirType vector = 675 mlirVectorTypeGet(sizeof(shape) / sizeof(int64_t), shape, f32); 676 if (!mlirTypeIsAVector(vector) || !mlirTypeIsAShaped(vector)) 677 return 14; 678 if (!mlirTypeEqual(mlirShapedTypeGetElementType(vector), f32) || 679 !mlirShapedTypeHasRank(vector) || mlirShapedTypeGetRank(vector) != 2 || 680 mlirShapedTypeGetDimSize(vector, 0) != 2 || 681 mlirShapedTypeIsDynamicDim(vector, 0) || 682 mlirShapedTypeGetDimSize(vector, 1) != 3 || 683 !mlirShapedTypeHasStaticShape(vector)) 684 return 15; 685 mlirTypeDump(vector); 686 fprintf(stderr, "\n"); 687 // CHECK: vector<2x3xf32> 688 689 // Ranked tensor type. 690 MlirType rankedTensor = 691 mlirRankedTensorTypeGet(sizeof(shape) / sizeof(int64_t), shape, f32); 692 if (!mlirTypeIsATensor(rankedTensor) || 693 !mlirTypeIsARankedTensor(rankedTensor)) 694 return 16; 695 mlirTypeDump(rankedTensor); 696 fprintf(stderr, "\n"); 697 // CHECK: tensor<2x3xf32> 698 699 // Unranked tensor type. 700 MlirType unrankedTensor = mlirUnrankedTensorTypeGet(f32); 701 if (!mlirTypeIsATensor(unrankedTensor) || 702 !mlirTypeIsAUnrankedTensor(unrankedTensor) || 703 mlirShapedTypeHasRank(unrankedTensor)) 704 return 17; 705 mlirTypeDump(unrankedTensor); 706 fprintf(stderr, "\n"); 707 // CHECK: tensor<*xf32> 708 709 // MemRef type. 710 MlirType memRef = mlirMemRefTypeContiguousGet( 711 f32, sizeof(shape) / sizeof(int64_t), shape, 2); 712 if (!mlirTypeIsAMemRef(memRef) || 713 mlirMemRefTypeGetNumAffineMaps(memRef) != 0 || 714 mlirMemRefTypeGetMemorySpace(memRef) != 2) 715 return 18; 716 mlirTypeDump(memRef); 717 fprintf(stderr, "\n"); 718 // CHECK: memref<2x3xf32, 2> 719 720 // Unranked MemRef type. 721 MlirType unrankedMemRef = mlirUnrankedMemRefTypeGet(f32, 4); 722 if (!mlirTypeIsAUnrankedMemRef(unrankedMemRef) || 723 mlirTypeIsAMemRef(unrankedMemRef) || 724 mlirUnrankedMemrefGetMemorySpace(unrankedMemRef) != 4) 725 return 19; 726 mlirTypeDump(unrankedMemRef); 727 fprintf(stderr, "\n"); 728 // CHECK: memref<*xf32, 4> 729 730 // Tuple type. 731 MlirType types[] = {unrankedMemRef, f32}; 732 MlirType tuple = mlirTupleTypeGet(ctx, 2, types); 733 if (!mlirTypeIsATuple(tuple) || mlirTupleTypeGetNumTypes(tuple) != 2 || 734 !mlirTypeEqual(mlirTupleTypeGetType(tuple, 0), unrankedMemRef) || 735 !mlirTypeEqual(mlirTupleTypeGetType(tuple, 1), f32)) 736 return 20; 737 mlirTypeDump(tuple); 738 fprintf(stderr, "\n"); 739 // CHECK: tuple<memref<*xf32, 4>, f32> 740 741 // Function type. 742 MlirType funcInputs[2] = {mlirIndexTypeGet(ctx), mlirIntegerTypeGet(ctx, 1)}; 743 MlirType funcResults[3] = {mlirIntegerTypeGet(ctx, 16), 744 mlirIntegerTypeGet(ctx, 32), 745 mlirIntegerTypeGet(ctx, 64)}; 746 MlirType funcType = mlirFunctionTypeGet(ctx, 2, funcInputs, 3, funcResults); 747 if (mlirFunctionTypeGetNumInputs(funcType) != 2) 748 return 21; 749 if (mlirFunctionTypeGetNumResults(funcType) != 3) 750 return 22; 751 if (!mlirTypeEqual(funcInputs[0], mlirFunctionTypeGetInput(funcType, 0)) || 752 !mlirTypeEqual(funcInputs[1], mlirFunctionTypeGetInput(funcType, 1))) 753 return 23; 754 if (!mlirTypeEqual(funcResults[0], mlirFunctionTypeGetResult(funcType, 0)) || 755 !mlirTypeEqual(funcResults[1], mlirFunctionTypeGetResult(funcType, 1)) || 756 !mlirTypeEqual(funcResults[2], mlirFunctionTypeGetResult(funcType, 2))) 757 return 24; 758 mlirTypeDump(funcType); 759 fprintf(stderr, "\n"); 760 // CHECK: (index, i1) -> (i16, i32, i64) 761 762 return 0; 763 } 764 765 void callbackSetFixedLengthString(const char *data, intptr_t len, 766 void *userData) { 767 strncpy(userData, data, len); 768 } 769 770 bool stringIsEqual(const char *lhs, MlirStringRef rhs) { 771 if (strlen(lhs) != rhs.length) { 772 return false; 773 } 774 return !strncmp(lhs, rhs.data, rhs.length); 775 } 776 777 int printBuiltinAttributes(MlirContext ctx) { 778 MlirAttribute floating = 779 mlirFloatAttrDoubleGet(ctx, mlirF64TypeGet(ctx), 2.0); 780 if (!mlirAttributeIsAFloat(floating) || 781 fabs(mlirFloatAttrGetValueDouble(floating) - 2.0) > 1E-6) 782 return 1; 783 fprintf(stderr, "@attrs\n"); 784 mlirAttributeDump(floating); 785 // CHECK-LABEL: @attrs 786 // CHECK: 2.000000e+00 : f64 787 788 // Exercise mlirAttributeGetType() just for the first one. 789 MlirType floatingType = mlirAttributeGetType(floating); 790 mlirTypeDump(floatingType); 791 // CHECK: f64 792 793 MlirAttribute integer = mlirIntegerAttrGet(mlirIntegerTypeGet(ctx, 32), 42); 794 if (!mlirAttributeIsAInteger(integer) || 795 mlirIntegerAttrGetValueInt(integer) != 42) 796 return 2; 797 mlirAttributeDump(integer); 798 // CHECK: 42 : i32 799 800 MlirAttribute boolean = mlirBoolAttrGet(ctx, 1); 801 if (!mlirAttributeIsABool(boolean) || !mlirBoolAttrGetValue(boolean)) 802 return 3; 803 mlirAttributeDump(boolean); 804 // CHECK: true 805 806 const char data[] = "abcdefghijklmnopqestuvwxyz"; 807 MlirAttribute opaque = 808 mlirOpaqueAttrGet(ctx, mlirStringRefCreateFromCString("std"), 3, data, 809 mlirNoneTypeGet(ctx)); 810 if (!mlirAttributeIsAOpaque(opaque) || 811 !stringIsEqual("std", mlirOpaqueAttrGetDialectNamespace(opaque))) 812 return 4; 813 814 MlirStringRef opaqueData = mlirOpaqueAttrGetData(opaque); 815 if (opaqueData.length != 3 || 816 strncmp(data, opaqueData.data, opaqueData.length)) 817 return 5; 818 mlirAttributeDump(opaque); 819 // CHECK: #std.abc 820 821 MlirAttribute string = 822 mlirStringAttrGet(ctx, mlirStringRefCreate(data + 3, 2)); 823 if (!mlirAttributeIsAString(string)) 824 return 6; 825 826 MlirStringRef stringValue = mlirStringAttrGetValue(string); 827 if (stringValue.length != 2 || 828 strncmp(data + 3, stringValue.data, stringValue.length)) 829 return 7; 830 mlirAttributeDump(string); 831 // CHECK: "de" 832 833 MlirAttribute flatSymbolRef = 834 mlirFlatSymbolRefAttrGet(ctx, mlirStringRefCreate(data + 5, 3)); 835 if (!mlirAttributeIsAFlatSymbolRef(flatSymbolRef)) 836 return 8; 837 838 MlirStringRef flatSymbolRefValue = 839 mlirFlatSymbolRefAttrGetValue(flatSymbolRef); 840 if (flatSymbolRefValue.length != 3 || 841 strncmp(data + 5, flatSymbolRefValue.data, flatSymbolRefValue.length)) 842 return 9; 843 mlirAttributeDump(flatSymbolRef); 844 // CHECK: @fgh 845 846 MlirAttribute symbols[] = {flatSymbolRef, flatSymbolRef}; 847 MlirAttribute symbolRef = 848 mlirSymbolRefAttrGet(ctx, mlirStringRefCreate(data + 8, 2), 2, symbols); 849 if (!mlirAttributeIsASymbolRef(symbolRef) || 850 mlirSymbolRefAttrGetNumNestedReferences(symbolRef) != 2 || 851 !mlirAttributeEqual(mlirSymbolRefAttrGetNestedReference(symbolRef, 0), 852 flatSymbolRef) || 853 !mlirAttributeEqual(mlirSymbolRefAttrGetNestedReference(symbolRef, 1), 854 flatSymbolRef)) 855 return 10; 856 857 MlirStringRef symbolRefLeaf = mlirSymbolRefAttrGetLeafReference(symbolRef); 858 MlirStringRef symbolRefRoot = mlirSymbolRefAttrGetRootReference(symbolRef); 859 if (symbolRefLeaf.length != 3 || 860 strncmp(data + 5, symbolRefLeaf.data, symbolRefLeaf.length) || 861 symbolRefRoot.length != 2 || 862 strncmp(data + 8, symbolRefRoot.data, symbolRefRoot.length)) 863 return 11; 864 mlirAttributeDump(symbolRef); 865 // CHECK: @ij::@fgh::@fgh 866 867 MlirAttribute type = mlirTypeAttrGet(mlirF32TypeGet(ctx)); 868 if (!mlirAttributeIsAType(type) || 869 !mlirTypeEqual(mlirF32TypeGet(ctx), mlirTypeAttrGetValue(type))) 870 return 12; 871 mlirAttributeDump(type); 872 // CHECK: f32 873 874 MlirAttribute unit = mlirUnitAttrGet(ctx); 875 if (!mlirAttributeIsAUnit(unit)) 876 return 13; 877 mlirAttributeDump(unit); 878 // CHECK: unit 879 880 int64_t shape[] = {1, 2}; 881 882 int bools[] = {0, 1}; 883 uint32_t uints32[] = {0u, 1u}; 884 int32_t ints32[] = {0, 1}; 885 uint64_t uints64[] = {0u, 1u}; 886 int64_t ints64[] = {0, 1}; 887 float floats[] = {0.0f, 1.0f}; 888 double doubles[] = {0.0, 1.0}; 889 MlirAttribute boolElements = mlirDenseElementsAttrBoolGet( 890 mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 1)), 2, bools); 891 MlirAttribute uint32Elements = mlirDenseElementsAttrUInt32Get( 892 mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 32)), 2, 893 uints32); 894 MlirAttribute int32Elements = mlirDenseElementsAttrInt32Get( 895 mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 32)), 2, 896 ints32); 897 MlirAttribute uint64Elements = mlirDenseElementsAttrUInt64Get( 898 mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 64)), 2, 899 uints64); 900 MlirAttribute int64Elements = mlirDenseElementsAttrInt64Get( 901 mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 64)), 2, 902 ints64); 903 MlirAttribute floatElements = mlirDenseElementsAttrFloatGet( 904 mlirRankedTensorTypeGet(2, shape, mlirF32TypeGet(ctx)), 2, floats); 905 MlirAttribute doubleElements = mlirDenseElementsAttrDoubleGet( 906 mlirRankedTensorTypeGet(2, shape, mlirF64TypeGet(ctx)), 2, doubles); 907 908 if (!mlirAttributeIsADenseElements(boolElements) || 909 !mlirAttributeIsADenseElements(uint32Elements) || 910 !mlirAttributeIsADenseElements(int32Elements) || 911 !mlirAttributeIsADenseElements(uint64Elements) || 912 !mlirAttributeIsADenseElements(int64Elements) || 913 !mlirAttributeIsADenseElements(floatElements) || 914 !mlirAttributeIsADenseElements(doubleElements)) 915 return 14; 916 917 if (mlirDenseElementsAttrGetBoolValue(boolElements, 1) != 1 || 918 mlirDenseElementsAttrGetUInt32Value(uint32Elements, 1) != 1 || 919 mlirDenseElementsAttrGetInt32Value(int32Elements, 1) != 1 || 920 mlirDenseElementsAttrGetUInt64Value(uint64Elements, 1) != 1 || 921 mlirDenseElementsAttrGetInt64Value(int64Elements, 1) != 1 || 922 fabsf(mlirDenseElementsAttrGetFloatValue(floatElements, 1) - 1.0f) > 923 1E-6f || 924 fabs(mlirDenseElementsAttrGetDoubleValue(doubleElements, 1) - 1.0) > 1E-6) 925 return 15; 926 927 mlirAttributeDump(boolElements); 928 mlirAttributeDump(uint32Elements); 929 mlirAttributeDump(int32Elements); 930 mlirAttributeDump(uint64Elements); 931 mlirAttributeDump(int64Elements); 932 mlirAttributeDump(floatElements); 933 mlirAttributeDump(doubleElements); 934 // CHECK: dense<{{\[}}[false, true]]> : tensor<1x2xi1> 935 // CHECK: dense<{{\[}}[0, 1]]> : tensor<1x2xui32> 936 // CHECK: dense<{{\[}}[0, 1]]> : tensor<1x2xi32> 937 // CHECK: dense<{{\[}}[0, 1]]> : tensor<1x2xui64> 938 // CHECK: dense<{{\[}}[0, 1]]> : tensor<1x2xi64> 939 // CHECK: dense<{{\[}}[0.000000e+00, 1.000000e+00]]> : tensor<1x2xf32> 940 // CHECK: dense<{{\[}}[0.000000e+00, 1.000000e+00]]> : tensor<1x2xf64> 941 942 MlirAttribute splatBool = mlirDenseElementsAttrBoolSplatGet( 943 mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 1)), 1); 944 MlirAttribute splatUInt32 = mlirDenseElementsAttrUInt32SplatGet( 945 mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 32)), 1); 946 MlirAttribute splatInt32 = mlirDenseElementsAttrInt32SplatGet( 947 mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 32)), 1); 948 MlirAttribute splatUInt64 = mlirDenseElementsAttrUInt64SplatGet( 949 mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 64)), 1); 950 MlirAttribute splatInt64 = mlirDenseElementsAttrInt64SplatGet( 951 mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 64)), 1); 952 MlirAttribute splatFloat = mlirDenseElementsAttrFloatSplatGet( 953 mlirRankedTensorTypeGet(2, shape, mlirF32TypeGet(ctx)), 1.0f); 954 MlirAttribute splatDouble = mlirDenseElementsAttrDoubleSplatGet( 955 mlirRankedTensorTypeGet(2, shape, mlirF64TypeGet(ctx)), 1.0); 956 957 if (!mlirAttributeIsADenseElements(splatBool) || 958 !mlirDenseElementsAttrIsSplat(splatBool) || 959 !mlirAttributeIsADenseElements(splatUInt32) || 960 !mlirDenseElementsAttrIsSplat(splatUInt32) || 961 !mlirAttributeIsADenseElements(splatInt32) || 962 !mlirDenseElementsAttrIsSplat(splatInt32) || 963 !mlirAttributeIsADenseElements(splatUInt64) || 964 !mlirDenseElementsAttrIsSplat(splatUInt64) || 965 !mlirAttributeIsADenseElements(splatInt64) || 966 !mlirDenseElementsAttrIsSplat(splatInt64) || 967 !mlirAttributeIsADenseElements(splatFloat) || 968 !mlirDenseElementsAttrIsSplat(splatFloat) || 969 !mlirAttributeIsADenseElements(splatDouble) || 970 !mlirDenseElementsAttrIsSplat(splatDouble)) 971 return 16; 972 973 if (mlirDenseElementsAttrGetBoolSplatValue(splatBool) != 1 || 974 mlirDenseElementsAttrGetUInt32SplatValue(splatUInt32) != 1 || 975 mlirDenseElementsAttrGetInt32SplatValue(splatInt32) != 1 || 976 mlirDenseElementsAttrGetUInt64SplatValue(splatUInt64) != 1 || 977 mlirDenseElementsAttrGetInt64SplatValue(splatInt64) != 1 || 978 fabsf(mlirDenseElementsAttrGetFloatSplatValue(splatFloat) - 1.0f) > 979 1E-6f || 980 fabs(mlirDenseElementsAttrGetDoubleSplatValue(splatDouble) - 1.0) > 1E-6) 981 return 17; 982 983 uint32_t *uint32RawData = 984 (uint32_t *)mlirDenseElementsAttrGetRawData(uint32Elements); 985 int32_t *int32RawData = 986 (int32_t *)mlirDenseElementsAttrGetRawData(int32Elements); 987 uint64_t *uint64RawData = 988 (uint64_t *)mlirDenseElementsAttrGetRawData(uint64Elements); 989 int64_t *int64RawData = 990 (int64_t *)mlirDenseElementsAttrGetRawData(int64Elements); 991 float *floatRawData = (float *)mlirDenseElementsAttrGetRawData(floatElements); 992 double *doubleRawData = 993 (double *)mlirDenseElementsAttrGetRawData(doubleElements); 994 if (uint32RawData[0] != 0u || uint32RawData[1] != 1u || 995 int32RawData[0] != 0 || int32RawData[1] != 1 || uint64RawData[0] != 0u || 996 uint64RawData[1] != 1u || int64RawData[0] != 0 || int64RawData[1] != 1 || 997 floatRawData[0] != 0.0f || floatRawData[1] != 1.0f || 998 doubleRawData[0] != 0.0 || doubleRawData[1] != 1.0) 999 return 18; 1000 1001 mlirAttributeDump(splatBool); 1002 mlirAttributeDump(splatUInt32); 1003 mlirAttributeDump(splatInt32); 1004 mlirAttributeDump(splatUInt64); 1005 mlirAttributeDump(splatInt64); 1006 mlirAttributeDump(splatFloat); 1007 mlirAttributeDump(splatDouble); 1008 // CHECK: dense<true> : tensor<1x2xi1> 1009 // CHECK: dense<1> : tensor<1x2xi32> 1010 // CHECK: dense<1> : tensor<1x2xi32> 1011 // CHECK: dense<1> : tensor<1x2xi64> 1012 // CHECK: dense<1> : tensor<1x2xi64> 1013 // CHECK: dense<1.000000e+00> : tensor<1x2xf32> 1014 // CHECK: dense<1.000000e+00> : tensor<1x2xf64> 1015 1016 mlirAttributeDump(mlirElementsAttrGetValue(floatElements, 2, uints64)); 1017 mlirAttributeDump(mlirElementsAttrGetValue(doubleElements, 2, uints64)); 1018 // CHECK: 1.000000e+00 : f32 1019 // CHECK: 1.000000e+00 : f64 1020 1021 int64_t indices[] = {4, 7}; 1022 int64_t two = 2; 1023 MlirAttribute indicesAttr = mlirDenseElementsAttrInt64Get( 1024 mlirRankedTensorTypeGet(1, &two, mlirIntegerTypeGet(ctx, 64)), 2, 1025 indices); 1026 MlirAttribute valuesAttr = mlirDenseElementsAttrFloatGet( 1027 mlirRankedTensorTypeGet(1, &two, mlirF32TypeGet(ctx)), 2, floats); 1028 MlirAttribute sparseAttr = mlirSparseElementsAttribute( 1029 mlirRankedTensorTypeGet(2, shape, mlirF32TypeGet(ctx)), indicesAttr, 1030 valuesAttr); 1031 mlirAttributeDump(sparseAttr); 1032 // CHECK: sparse<[4, 7], [0.000000e+00, 1.000000e+00]> : tensor<1x2xf32> 1033 1034 return 0; 1035 } 1036 1037 int printAffineMap(MlirContext ctx) { 1038 MlirAffineMap emptyAffineMap = mlirAffineMapEmptyGet(ctx); 1039 MlirAffineMap affineMap = mlirAffineMapZeroResultGet(ctx, 3, 2); 1040 MlirAffineMap constAffineMap = mlirAffineMapConstantGet(ctx, 2); 1041 MlirAffineMap multiDimIdentityAffineMap = 1042 mlirAffineMapMultiDimIdentityGet(ctx, 3); 1043 MlirAffineMap minorIdentityAffineMap = 1044 mlirAffineMapMinorIdentityGet(ctx, 3, 2); 1045 unsigned permutation[] = {1, 2, 0}; 1046 MlirAffineMap permutationAffineMap = mlirAffineMapPermutationGet( 1047 ctx, sizeof(permutation) / sizeof(unsigned), permutation); 1048 1049 fprintf(stderr, "@affineMap\n"); 1050 mlirAffineMapDump(emptyAffineMap); 1051 mlirAffineMapDump(affineMap); 1052 mlirAffineMapDump(constAffineMap); 1053 mlirAffineMapDump(multiDimIdentityAffineMap); 1054 mlirAffineMapDump(minorIdentityAffineMap); 1055 mlirAffineMapDump(permutationAffineMap); 1056 // CHECK-LABEL: @affineMap 1057 // CHECK: () -> () 1058 // CHECK: (d0, d1, d2)[s0, s1] -> () 1059 // CHECK: () -> (2) 1060 // CHECK: (d0, d1, d2) -> (d0, d1, d2) 1061 // CHECK: (d0, d1, d2) -> (d1, d2) 1062 // CHECK: (d0, d1, d2) -> (d1, d2, d0) 1063 1064 if (!mlirAffineMapIsIdentity(emptyAffineMap) || 1065 mlirAffineMapIsIdentity(affineMap) || 1066 mlirAffineMapIsIdentity(constAffineMap) || 1067 !mlirAffineMapIsIdentity(multiDimIdentityAffineMap) || 1068 mlirAffineMapIsIdentity(minorIdentityAffineMap) || 1069 mlirAffineMapIsIdentity(permutationAffineMap)) 1070 return 1; 1071 1072 if (!mlirAffineMapIsMinorIdentity(emptyAffineMap) || 1073 mlirAffineMapIsMinorIdentity(affineMap) || 1074 !mlirAffineMapIsMinorIdentity(multiDimIdentityAffineMap) || 1075 !mlirAffineMapIsMinorIdentity(minorIdentityAffineMap) || 1076 mlirAffineMapIsMinorIdentity(permutationAffineMap)) 1077 return 2; 1078 1079 if (!mlirAffineMapIsEmpty(emptyAffineMap) || 1080 mlirAffineMapIsEmpty(affineMap) || mlirAffineMapIsEmpty(constAffineMap) || 1081 mlirAffineMapIsEmpty(multiDimIdentityAffineMap) || 1082 mlirAffineMapIsEmpty(minorIdentityAffineMap) || 1083 mlirAffineMapIsEmpty(permutationAffineMap)) 1084 return 3; 1085 1086 if (mlirAffineMapIsSingleConstant(emptyAffineMap) || 1087 mlirAffineMapIsSingleConstant(affineMap) || 1088 !mlirAffineMapIsSingleConstant(constAffineMap) || 1089 mlirAffineMapIsSingleConstant(multiDimIdentityAffineMap) || 1090 mlirAffineMapIsSingleConstant(minorIdentityAffineMap) || 1091 mlirAffineMapIsSingleConstant(permutationAffineMap)) 1092 return 4; 1093 1094 if (mlirAffineMapGetSingleConstantResult(constAffineMap) != 2) 1095 return 5; 1096 1097 if (mlirAffineMapGetNumDims(emptyAffineMap) != 0 || 1098 mlirAffineMapGetNumDims(affineMap) != 3 || 1099 mlirAffineMapGetNumDims(constAffineMap) != 0 || 1100 mlirAffineMapGetNumDims(multiDimIdentityAffineMap) != 3 || 1101 mlirAffineMapGetNumDims(minorIdentityAffineMap) != 3 || 1102 mlirAffineMapGetNumDims(permutationAffineMap) != 3) 1103 return 6; 1104 1105 if (mlirAffineMapGetNumSymbols(emptyAffineMap) != 0 || 1106 mlirAffineMapGetNumSymbols(affineMap) != 2 || 1107 mlirAffineMapGetNumSymbols(constAffineMap) != 0 || 1108 mlirAffineMapGetNumSymbols(multiDimIdentityAffineMap) != 0 || 1109 mlirAffineMapGetNumSymbols(minorIdentityAffineMap) != 0 || 1110 mlirAffineMapGetNumSymbols(permutationAffineMap) != 0) 1111 return 7; 1112 1113 if (mlirAffineMapGetNumResults(emptyAffineMap) != 0 || 1114 mlirAffineMapGetNumResults(affineMap) != 0 || 1115 mlirAffineMapGetNumResults(constAffineMap) != 1 || 1116 mlirAffineMapGetNumResults(multiDimIdentityAffineMap) != 3 || 1117 mlirAffineMapGetNumResults(minorIdentityAffineMap) != 2 || 1118 mlirAffineMapGetNumResults(permutationAffineMap) != 3) 1119 return 8; 1120 1121 if (mlirAffineMapGetNumInputs(emptyAffineMap) != 0 || 1122 mlirAffineMapGetNumInputs(affineMap) != 5 || 1123 mlirAffineMapGetNumInputs(constAffineMap) != 0 || 1124 mlirAffineMapGetNumInputs(multiDimIdentityAffineMap) != 3 || 1125 mlirAffineMapGetNumInputs(minorIdentityAffineMap) != 3 || 1126 mlirAffineMapGetNumInputs(permutationAffineMap) != 3) 1127 return 9; 1128 1129 if (!mlirAffineMapIsProjectedPermutation(emptyAffineMap) || 1130 !mlirAffineMapIsPermutation(emptyAffineMap) || 1131 mlirAffineMapIsProjectedPermutation(affineMap) || 1132 mlirAffineMapIsPermutation(affineMap) || 1133 mlirAffineMapIsProjectedPermutation(constAffineMap) || 1134 mlirAffineMapIsPermutation(constAffineMap) || 1135 !mlirAffineMapIsProjectedPermutation(multiDimIdentityAffineMap) || 1136 !mlirAffineMapIsPermutation(multiDimIdentityAffineMap) || 1137 !mlirAffineMapIsProjectedPermutation(minorIdentityAffineMap) || 1138 mlirAffineMapIsPermutation(minorIdentityAffineMap) || 1139 !mlirAffineMapIsProjectedPermutation(permutationAffineMap) || 1140 !mlirAffineMapIsPermutation(permutationAffineMap)) 1141 return 10; 1142 1143 intptr_t sub[] = {1}; 1144 1145 MlirAffineMap subMap = mlirAffineMapGetSubMap( 1146 multiDimIdentityAffineMap, sizeof(sub) / sizeof(intptr_t), sub); 1147 MlirAffineMap majorSubMap = 1148 mlirAffineMapGetMajorSubMap(multiDimIdentityAffineMap, 1); 1149 MlirAffineMap minorSubMap = 1150 mlirAffineMapGetMinorSubMap(multiDimIdentityAffineMap, 1); 1151 1152 mlirAffineMapDump(subMap); 1153 mlirAffineMapDump(majorSubMap); 1154 mlirAffineMapDump(minorSubMap); 1155 // CHECK: (d0, d1, d2) -> (d1) 1156 // CHECK: (d0, d1, d2) -> (d0) 1157 // CHECK: (d0, d1, d2) -> (d2) 1158 1159 return 0; 1160 } 1161 1162 int printAffineExpr(MlirContext ctx) { 1163 MlirAffineExpr affineDimExpr = mlirAffineDimExprGet(ctx, 5); 1164 MlirAffineExpr affineSymbolExpr = mlirAffineSymbolExprGet(ctx, 5); 1165 MlirAffineExpr affineConstantExpr = mlirAffineConstantExprGet(ctx, 5); 1166 MlirAffineExpr affineAddExpr = 1167 mlirAffineAddExprGet(affineDimExpr, affineSymbolExpr); 1168 MlirAffineExpr affineMulExpr = 1169 mlirAffineMulExprGet(affineDimExpr, affineSymbolExpr); 1170 MlirAffineExpr affineModExpr = 1171 mlirAffineModExprGet(affineDimExpr, affineSymbolExpr); 1172 MlirAffineExpr affineFloorDivExpr = 1173 mlirAffineFloorDivExprGet(affineDimExpr, affineSymbolExpr); 1174 MlirAffineExpr affineCeilDivExpr = 1175 mlirAffineCeilDivExprGet(affineDimExpr, affineSymbolExpr); 1176 1177 // Tests mlirAffineExprDump. 1178 fprintf(stderr, "@affineExpr\n"); 1179 mlirAffineExprDump(affineDimExpr); 1180 mlirAffineExprDump(affineSymbolExpr); 1181 mlirAffineExprDump(affineConstantExpr); 1182 mlirAffineExprDump(affineAddExpr); 1183 mlirAffineExprDump(affineMulExpr); 1184 mlirAffineExprDump(affineModExpr); 1185 mlirAffineExprDump(affineFloorDivExpr); 1186 mlirAffineExprDump(affineCeilDivExpr); 1187 // CHECK-LABEL: @affineExpr 1188 // CHECK: d5 1189 // CHECK: s5 1190 // CHECK: 5 1191 // CHECK: d5 + s5 1192 // CHECK: d5 * s5 1193 // CHECK: d5 mod s5 1194 // CHECK: d5 floordiv s5 1195 // CHECK: d5 ceildiv s5 1196 1197 // Tests methods of affine binary operation expression, takes add expression 1198 // as an example. 1199 mlirAffineExprDump(mlirAffineBinaryOpExprGetLHS(affineAddExpr)); 1200 mlirAffineExprDump(mlirAffineBinaryOpExprGetRHS(affineAddExpr)); 1201 // CHECK: d5 1202 // CHECK: s5 1203 1204 // Tests methods of affine dimension expression. 1205 if (mlirAffineDimExprGetPosition(affineDimExpr) != 5) 1206 return 1; 1207 1208 // Tests methods of affine symbol expression. 1209 if (mlirAffineSymbolExprGetPosition(affineSymbolExpr) != 5) 1210 return 2; 1211 1212 // Tests methods of affine constant expression. 1213 if (mlirAffineConstantExprGetValue(affineConstantExpr) != 5) 1214 return 3; 1215 1216 // Tests methods of affine expression. 1217 if (mlirAffineExprIsSymbolicOrConstant(affineDimExpr) || 1218 !mlirAffineExprIsSymbolicOrConstant(affineSymbolExpr) || 1219 !mlirAffineExprIsSymbolicOrConstant(affineConstantExpr) || 1220 mlirAffineExprIsSymbolicOrConstant(affineAddExpr) || 1221 mlirAffineExprIsSymbolicOrConstant(affineMulExpr) || 1222 mlirAffineExprIsSymbolicOrConstant(affineModExpr) || 1223 mlirAffineExprIsSymbolicOrConstant(affineFloorDivExpr) || 1224 mlirAffineExprIsSymbolicOrConstant(affineCeilDivExpr)) 1225 return 4; 1226 1227 if (!mlirAffineExprIsPureAffine(affineDimExpr) || 1228 !mlirAffineExprIsPureAffine(affineSymbolExpr) || 1229 !mlirAffineExprIsPureAffine(affineConstantExpr) || 1230 !mlirAffineExprIsPureAffine(affineAddExpr) || 1231 mlirAffineExprIsPureAffine(affineMulExpr) || 1232 mlirAffineExprIsPureAffine(affineModExpr) || 1233 mlirAffineExprIsPureAffine(affineFloorDivExpr) || 1234 mlirAffineExprIsPureAffine(affineCeilDivExpr)) 1235 return 5; 1236 1237 if (mlirAffineExprGetLargestKnownDivisor(affineDimExpr) != 1 || 1238 mlirAffineExprGetLargestKnownDivisor(affineSymbolExpr) != 1 || 1239 mlirAffineExprGetLargestKnownDivisor(affineConstantExpr) != 5 || 1240 mlirAffineExprGetLargestKnownDivisor(affineAddExpr) != 1 || 1241 mlirAffineExprGetLargestKnownDivisor(affineMulExpr) != 1 || 1242 mlirAffineExprGetLargestKnownDivisor(affineModExpr) != 1 || 1243 mlirAffineExprGetLargestKnownDivisor(affineFloorDivExpr) != 1 || 1244 mlirAffineExprGetLargestKnownDivisor(affineCeilDivExpr) != 1) 1245 return 6; 1246 1247 if (!mlirAffineExprIsMultipleOf(affineDimExpr, 1) || 1248 !mlirAffineExprIsMultipleOf(affineSymbolExpr, 1) || 1249 !mlirAffineExprIsMultipleOf(affineConstantExpr, 5) || 1250 !mlirAffineExprIsMultipleOf(affineAddExpr, 1) || 1251 !mlirAffineExprIsMultipleOf(affineMulExpr, 1) || 1252 !mlirAffineExprIsMultipleOf(affineModExpr, 1) || 1253 !mlirAffineExprIsMultipleOf(affineFloorDivExpr, 1) || 1254 !mlirAffineExprIsMultipleOf(affineCeilDivExpr, 1)) 1255 return 7; 1256 1257 if (!mlirAffineExprIsFunctionOfDim(affineDimExpr, 5) || 1258 mlirAffineExprIsFunctionOfDim(affineSymbolExpr, 5) || 1259 mlirAffineExprIsFunctionOfDim(affineConstantExpr, 5) || 1260 !mlirAffineExprIsFunctionOfDim(affineAddExpr, 5) || 1261 !mlirAffineExprIsFunctionOfDim(affineMulExpr, 5) || 1262 !mlirAffineExprIsFunctionOfDim(affineModExpr, 5) || 1263 !mlirAffineExprIsFunctionOfDim(affineFloorDivExpr, 5) || 1264 !mlirAffineExprIsFunctionOfDim(affineCeilDivExpr, 5)) 1265 return 8; 1266 1267 // Tests 'IsA' methods of affine binary operation expression. 1268 if (!mlirAffineExprIsAAdd(affineAddExpr)) 1269 return 9; 1270 1271 if (!mlirAffineExprIsAMul(affineMulExpr)) 1272 return 10; 1273 1274 if (!mlirAffineExprIsAMod(affineModExpr)) 1275 return 11; 1276 1277 if (!mlirAffineExprIsAFloorDiv(affineFloorDivExpr)) 1278 return 12; 1279 1280 if (!mlirAffineExprIsACeilDiv(affineCeilDivExpr)) 1281 return 13; 1282 1283 if (!mlirAffineExprIsABinary(affineAddExpr)) 1284 return 14; 1285 1286 // Test other 'IsA' method on affine expressions. 1287 if (!mlirAffineExprIsAConstant(affineConstantExpr)) 1288 return 15; 1289 1290 if (!mlirAffineExprIsADim(affineDimExpr)) 1291 return 16; 1292 1293 if (!mlirAffineExprIsASymbol(affineSymbolExpr)) 1294 return 17; 1295 1296 // Test equality and nullity. 1297 MlirAffineExpr otherDimExpr = mlirAffineDimExprGet(ctx, 5); 1298 if (!mlirAffineExprEqual(affineDimExpr, otherDimExpr)) 1299 return 18; 1300 1301 if (mlirAffineExprIsNull(affineDimExpr)) 1302 return 19; 1303 1304 return 0; 1305 } 1306 1307 int affineMapFromExprs(MlirContext ctx) { 1308 MlirAffineExpr affineDimExpr = mlirAffineDimExprGet(ctx, 0); 1309 MlirAffineExpr affineSymbolExpr = mlirAffineSymbolExprGet(ctx, 1); 1310 MlirAffineExpr exprs[] = {affineDimExpr, affineSymbolExpr}; 1311 MlirAffineMap map = mlirAffineMapGet(ctx, 3, 3, 2, exprs); 1312 1313 // CHECK-LABEL: @affineMapFromExprs 1314 fprintf(stderr, "@affineMapFromExprs"); 1315 // CHECK: (d0, d1, d2)[s0, s1, s2] -> (d0, s1) 1316 mlirAffineMapDump(map); 1317 1318 if (mlirAffineMapGetNumResults(map) != 2) 1319 return 1; 1320 1321 if (!mlirAffineExprEqual(mlirAffineMapGetResult(map, 0), affineDimExpr)) 1322 return 2; 1323 1324 if (!mlirAffineExprEqual(mlirAffineMapGetResult(map, 1), affineSymbolExpr)) 1325 return 3; 1326 1327 return 0; 1328 } 1329 1330 int printIntegerSet(MlirContext ctx) { 1331 MlirIntegerSet emptySet = mlirIntegerSetEmptyGet(ctx, 2, 1); 1332 1333 // CHECK-LABEL: @printIntegerSet 1334 fprintf(stderr, "@printIntegerSet"); 1335 1336 // CHECK: (d0, d1)[s0] : (1 == 0) 1337 mlirIntegerSetDump(emptySet); 1338 1339 if (!mlirIntegerSetIsCanonicalEmpty(emptySet)) 1340 return 1; 1341 1342 MlirIntegerSet anotherEmptySet = mlirIntegerSetEmptyGet(ctx, 2, 1); 1343 if (!mlirIntegerSetEqual(emptySet, anotherEmptySet)) 1344 return 2; 1345 1346 // Construct a set constrained by: 1347 // d0 - s0 == 0, 1348 // d1 - 42 >= 0. 1349 MlirAffineExpr negOne = mlirAffineConstantExprGet(ctx, -1); 1350 MlirAffineExpr negFortyTwo = mlirAffineConstantExprGet(ctx, -42); 1351 MlirAffineExpr d0 = mlirAffineDimExprGet(ctx, 0); 1352 MlirAffineExpr d1 = mlirAffineDimExprGet(ctx, 1); 1353 MlirAffineExpr s0 = mlirAffineSymbolExprGet(ctx, 0); 1354 MlirAffineExpr negS0 = mlirAffineMulExprGet(negOne, s0); 1355 MlirAffineExpr d0minusS0 = mlirAffineAddExprGet(d0, negS0); 1356 MlirAffineExpr d1minus42 = mlirAffineAddExprGet(d1, negFortyTwo); 1357 MlirAffineExpr constraints[] = {d0minusS0, d1minus42}; 1358 bool flags[] = {true, false}; 1359 1360 MlirIntegerSet set = mlirIntegerSetGet(ctx, 2, 1, 2, constraints, flags); 1361 // CHECK: (d0, d1)[s0] : ( 1362 // CHECK-DAG: d0 - s0 == 0 1363 // CHECK-DAG: d1 - 42 >= 0 1364 mlirIntegerSetDump(set); 1365 1366 // Transform d1 into s0. 1367 MlirAffineExpr s1 = mlirAffineSymbolExprGet(ctx, 1); 1368 MlirAffineExpr repl[] = {d0, s1}; 1369 MlirIntegerSet replaced = mlirIntegerSetReplaceGet(set, repl, &s0, 1, 2); 1370 // CHECK: (d0)[s0, s1] : ( 1371 // CHECK-DAG: d0 - s0 == 0 1372 // CHECK-DAG: s1 - 42 >= 0 1373 mlirIntegerSetDump(replaced); 1374 1375 if (mlirIntegerSetGetNumDims(set) != 2) 1376 return 3; 1377 if (mlirIntegerSetGetNumDims(replaced) != 1) 1378 return 4; 1379 1380 if (mlirIntegerSetGetNumSymbols(set) != 1) 1381 return 5; 1382 if (mlirIntegerSetGetNumSymbols(replaced) != 2) 1383 return 6; 1384 1385 if (mlirIntegerSetGetNumInputs(set) != 3) 1386 return 7; 1387 1388 if (mlirIntegerSetGetNumConstraints(set) != 2) 1389 return 8; 1390 1391 if (mlirIntegerSetGetNumEqualities(set) != 1) 1392 return 9; 1393 1394 if (mlirIntegerSetGetNumInequalities(set) != 1) 1395 return 10; 1396 1397 MlirAffineExpr cstr1 = mlirIntegerSetGetConstraint(set, 0); 1398 MlirAffineExpr cstr2 = mlirIntegerSetGetConstraint(set, 1); 1399 bool isEq1 = mlirIntegerSetIsConstraintEq(set, 0); 1400 bool isEq2 = mlirIntegerSetIsConstraintEq(set, 1); 1401 if (!mlirAffineExprEqual(cstr1, isEq1 ? d0minusS0 : d1minus42)) 1402 return 11; 1403 if (!mlirAffineExprEqual(cstr2, isEq2 ? d0minusS0 : d1minus42)) 1404 return 12; 1405 1406 return 0; 1407 } 1408 1409 int registerOnlyStd() { 1410 MlirContext ctx = mlirContextCreate(); 1411 // The built-in dialect is always loaded. 1412 if (mlirContextGetNumLoadedDialects(ctx) != 1) 1413 return 1; 1414 1415 MlirDialectHandle stdHandle = mlirGetDialectHandle__std__(); 1416 1417 MlirDialect std = mlirContextGetOrLoadDialect( 1418 ctx, mlirDialectHandleGetNamespace(stdHandle)); 1419 if (!mlirDialectIsNull(std)) 1420 return 2; 1421 1422 mlirDialectHandleRegisterDialect(stdHandle, ctx); 1423 1424 std = mlirContextGetOrLoadDialect(ctx, 1425 mlirDialectHandleGetNamespace(stdHandle)); 1426 if (mlirDialectIsNull(std)) 1427 return 3; 1428 1429 MlirDialect alsoStd = mlirDialectHandleLoadDialect(stdHandle, ctx); 1430 if (!mlirDialectEqual(std, alsoStd)) 1431 return 4; 1432 1433 MlirStringRef stdNs = mlirDialectGetNamespace(std); 1434 MlirStringRef alsoStdNs = mlirDialectHandleGetNamespace(stdHandle); 1435 if (stdNs.length != alsoStdNs.length || 1436 strncmp(stdNs.data, alsoStdNs.data, stdNs.length)) 1437 return 5; 1438 1439 fprintf(stderr, "@registration\n"); 1440 // CHECK-LABEL: @registration 1441 1442 return 0; 1443 } 1444 1445 /// Tests backreference APIs 1446 static int testBackreferences() { 1447 fprintf(stderr, "@test_backreferences\n"); 1448 1449 MlirContext ctx = mlirContextCreate(); 1450 mlirContextSetAllowUnregisteredDialects(ctx, true); 1451 MlirLocation loc = mlirLocationUnknownGet(ctx); 1452 1453 MlirOperationState opState = mlirOperationStateGet(mlirStringRefCreateFromCString("invalid.op"), loc); 1454 MlirRegion region = mlirRegionCreate(); 1455 MlirBlock block = mlirBlockCreate(0, NULL); 1456 mlirRegionAppendOwnedBlock(region, block); 1457 mlirOperationStateAddOwnedRegions(&opState, 1, ®ion); 1458 MlirOperation op = mlirOperationCreate(&opState); 1459 MlirIdentifier ident = mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("identifier")); 1460 1461 if (!mlirContextEqual(ctx, mlirOperationGetContext(op))) { 1462 fprintf(stderr, "ERROR: Getting context from operation failed\n"); 1463 return 1; 1464 } 1465 if (!mlirOperationEqual(op, mlirBlockGetParentOperation(block))) { 1466 fprintf(stderr, "ERROR: Getting parent operation from block failed\n"); 1467 return 2; 1468 } 1469 if (!mlirContextEqual(ctx, mlirIdentifierGetContext(ident))) { 1470 fprintf(stderr, "ERROR: Getting context from identifier failed\n"); 1471 return 3; 1472 } 1473 1474 mlirOperationDestroy(op); 1475 mlirContextDestroy(ctx); 1476 1477 // CHECK-LABEL: @test_backreferences 1478 return 0; 1479 } 1480 1481 // Wraps a diagnostic into additional text we can match against. 1482 MlirLogicalResult errorHandler(MlirDiagnostic diagnostic, void *userData) { 1483 fprintf(stderr, "processing diagnostic (userData: %ld) <<\n", (long)userData); 1484 mlirDiagnosticPrint(diagnostic, printToStderr, NULL); 1485 fprintf(stderr, "\n"); 1486 MlirLocation loc = mlirDiagnosticGetLocation(diagnostic); 1487 mlirLocationPrint(loc, printToStderr, NULL); 1488 assert(mlirDiagnosticGetNumNotes(diagnostic) == 0); 1489 fprintf(stderr, "\n>> end of diagnostic (userData: %ld)\n", (long)userData); 1490 return mlirLogicalResultSuccess(); 1491 } 1492 1493 // Logs when the delete user data callback is called 1494 static void deleteUserData(void *userData) { 1495 fprintf(stderr, "deleting user data (userData: %ld)\n", (long)userData); 1496 } 1497 1498 void testDiagnostics() { 1499 MlirContext ctx = mlirContextCreate(); 1500 MlirDiagnosticHandlerID id = mlirContextAttachDiagnosticHandler( 1501 ctx, errorHandler, (void *)42, deleteUserData); 1502 fprintf(stderr, "@test_diagnostics\n"); 1503 MlirLocation unknownLoc = mlirLocationUnknownGet(ctx); 1504 mlirEmitError(unknownLoc, "test diagnostics"); 1505 MlirLocation fileLineColLoc = mlirLocationFileLineColGet( 1506 ctx, mlirStringRefCreateFromCString("file.c"), 1, 2); 1507 mlirEmitError(fileLineColLoc, "test diagnostics"); 1508 MlirLocation callSiteLoc = mlirLocationCallSiteGet( 1509 mlirLocationFileLineColGet( 1510 ctx, mlirStringRefCreateFromCString("other-file.c"), 2, 3), 1511 fileLineColLoc); 1512 mlirEmitError(callSiteLoc, "test diagnostics"); 1513 mlirContextDetachDiagnosticHandler(ctx, id); 1514 mlirEmitError(unknownLoc, "more test diagnostics"); 1515 // CHECK-LABEL: @test_diagnostics 1516 // CHECK: processing diagnostic (userData: 42) << 1517 // CHECK: test diagnostics 1518 // CHECK: loc(unknown) 1519 // CHECK: >> end of diagnostic (userData: 42) 1520 // CHECK: processing diagnostic (userData: 42) << 1521 // CHECK: test diagnostics 1522 // CHECK: loc("file.c":1:2) 1523 // CHECK: >> end of diagnostic (userData: 42) 1524 // CHECK: processing diagnostic (userData: 42) << 1525 // CHECK: test diagnostics 1526 // CHECK: loc(callsite("other-file.c":2:3 at "file.c":1:2)) 1527 // CHECK: >> end of diagnostic (userData: 42) 1528 // CHECK: deleting user data (userData: 42) 1529 // CHECK-NOT: processing diagnostic 1530 // CHECK: more test diagnostics 1531 } 1532 1533 int main() { 1534 MlirContext ctx = mlirContextCreate(); 1535 mlirRegisterAllDialects(ctx); 1536 if (constructAndTraverseIr(ctx)) 1537 return 1; 1538 buildWithInsertionsAndPrint(ctx); 1539 if (createOperationWithTypeInference(ctx)) 1540 return 2; 1541 1542 if (printBuiltinTypes(ctx)) 1543 return 3; 1544 if (printBuiltinAttributes(ctx)) 1545 return 4; 1546 if (printAffineMap(ctx)) 1547 return 5; 1548 if (printAffineExpr(ctx)) 1549 return 6; 1550 if (affineMapFromExprs(ctx)) 1551 return 7; 1552 if (printIntegerSet(ctx)) 1553 return 8; 1554 if (registerOnlyStd()) 1555 return 9; 1556 if (testBackreferences()) 1557 return 10; 1558 1559 mlirContextDestroy(ctx); 1560 1561 testDiagnostics(); 1562 return 0; 1563 } 1564