1 //===- execution_engine.c - Test for the C bindings for the MLIR JIT-------===// 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-execution-engine-test 2>&1 | FileCheck %s 11 */ 12 13 #include "mlir-c/Conversion.h" 14 #include "mlir-c/ExecutionEngine.h" 15 #include "mlir-c/IR.h" 16 #include "mlir-c/Registration.h" 17 18 #include <assert.h> 19 #include <math.h> 20 #include <stdio.h> 21 #include <stdlib.h> 22 #include <string.h> 23 24 void lowerModuleToLLVM(MlirContext ctx, MlirModule module) { 25 MlirPassManager pm = mlirPassManagerCreate(ctx); 26 mlirPassManagerAddOwnedPass(pm, mlirCreateConversionConvertStandardToLLVM()); 27 MlirLogicalResult status = mlirPassManagerRun(pm, module); 28 if (mlirLogicalResultIsFailure(status)) { 29 fprintf(stderr, "Unexpected failure running pass pipeline\n"); 30 exit(2); 31 } 32 mlirPassManagerDestroy(pm); 33 } 34 35 // CHECK-LABEL: Running test 'testSimpleExecution' 36 void testSimpleExecution() { 37 MlirContext ctx = mlirContextCreate(); 38 mlirRegisterAllDialects(ctx); 39 MlirModule module = mlirModuleCreateParse( 40 ctx, mlirStringRefCreateFromCString( 41 // clang-format off 42 "module { \n" 43 " func @add(%arg0 : i32) -> i32 attributes { llvm.emit_c_interface } { \n" 44 " %res = std.addi %arg0, %arg0 : i32 \n" 45 " return %res : i32 \n" 46 " } \n" 47 "}")); 48 // clang-format on 49 lowerModuleToLLVM(ctx, module); 50 mlirRegisterAllLLVMTranslations(ctx); 51 MlirExecutionEngine jit = mlirExecutionEngineCreate( 52 module, /*optLevel=*/2, /*numPaths=*/0, /*sharedLibPaths=*/NULL); 53 if (mlirExecutionEngineIsNull(jit)) { 54 fprintf(stderr, "Execution engine creation failed"); 55 exit(2); 56 } 57 int input = 42; 58 int result = -1; 59 void *args[2] = {&input, &result}; 60 if (mlirLogicalResultIsFailure(mlirExecutionEngineInvokePacked( 61 jit, mlirStringRefCreateFromCString("add"), args))) { 62 fprintf(stderr, "Execution engine creation failed"); 63 abort(); 64 } 65 // CHECK: Input: 42 Result: 84 66 printf("Input: %d Result: %d\n", input, result); 67 mlirExecutionEngineDestroy(jit); 68 mlirModuleDestroy(module); 69 mlirContextDestroy(ctx); 70 } 71 72 int main() { 73 74 #define _STRINGIFY(x) #x 75 #define STRINGIFY(x) _STRINGIFY(x) 76 #define TEST(test) \ 77 printf("Running test '" STRINGIFY(test) "'\n"); \ 78 test(); 79 80 TEST(testSimpleExecution); 81 return 0; 82 } 83