xref: /llvm-project/mlir/test/CAPI/translation.c (revision 7fb89bfb0f93d5cfe3cf661253bbb2e2ef19359a)
1 //===- translation.c - Test MLIR Target translations ----------------------===//
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-translation-test 2>&1 | FileCheck %s
11 
12 #include "llvm-c/Core.h"
13 #include "llvm-c/Support.h"
14 #include "llvm-c/Types.h"
15 
16 #include "mlir-c/BuiltinTypes.h"
17 #include "mlir-c/Dialect/LLVM.h"
18 #include "mlir-c/IR.h"
19 #include "mlir-c/RegisterEverything.h"
20 #include "mlir-c/Support.h"
21 #include "mlir-c/Target/LLVMIR.h"
22 
23 #include <assert.h>
24 #include <math.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 
29 // CHECK-LABEL: testToLLVMIR()
testToLLVMIR(MlirContext ctx)30 static void testToLLVMIR(MlirContext ctx) {
31   fprintf(stderr, "testToLLVMIR()\n");
32   LLVMContextRef llvmCtx = LLVMContextCreate();
33 
34   const char *moduleString = "llvm.func @add(%arg0: i64, %arg1: i64) -> i64 { \
35                                 %0 = llvm.add %arg0, %arg1  : i64 \
36                                 llvm.return %0 : i64 \
37                              }";
38 
39   mlirRegisterAllLLVMTranslations(ctx);
40 
41   MlirModule module =
42       mlirModuleCreateParse(ctx, mlirStringRefCreateFromCString(moduleString));
43 
44   MlirOperation operation = mlirModuleGetOperation(module);
45 
46   LLVMModuleRef llvmModule = mlirTranslateModuleToLLVMIR(operation, llvmCtx);
47 
48   // clang-format off
49   // CHECK: define i64 @add(i64 %[[arg1:.*]], i64 %[[arg2:.*]]) {
50   // CHECK-NEXT:   %[[arg3:.*]] = add i64 %[[arg1]], %[[arg2]]
51   // CHECK-NEXT:   ret i64 %[[arg3]]
52   // CHECK-NEXT: }
53   // clang-format on
54   LLVMDumpModule(llvmModule);
55 
56   LLVMDisposeModule(llvmModule);
57   mlirModuleDestroy(module);
58   LLVMContextDispose(llvmCtx);
59 }
60 
main(void)61 int main(void) {
62   MlirContext ctx = mlirContextCreate();
63   mlirDialectHandleRegisterDialect(mlirGetDialectHandle__llvm__(), ctx);
64   mlirContextGetOrLoadDialect(ctx, mlirStringRefCreateFromCString("llvm"));
65   testToLLVMIR(ctx);
66   mlirContextDestroy(ctx);
67   return 0;
68 }
69