1 | //===- SerializeToLLVMBitcode.cpp -------------------------------*- C++ -*-===// |
---|---|
2 | // |
3 | // This file is licensed under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | |
9 | #include "mlir/IR/BuiltinOps.h" |
10 | #include "mlir/IR/MLIRContext.h" |
11 | #include "mlir/Parser/Parser.h" |
12 | #include "mlir/Target/LLVM/ModuleToObject.h" |
13 | #include "mlir/Target/LLVMIR/Dialect/Builtin/BuiltinToLLVMIRTranslation.h" |
14 | #include "mlir/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.h" |
15 | |
16 | #include "llvm/IRReader/IRReader.h" |
17 | #include "llvm/Support/MemoryBufferRef.h" |
18 | #include "llvm/Support/TargetSelect.h" |
19 | #include "llvm/Support/raw_ostream.h" |
20 | #include "llvm/TargetParser/Host.h" |
21 | |
22 | #include "gmock/gmock.h" |
23 | |
24 | using namespace mlir; |
25 | |
26 | // Skip the test if the native target was not built. |
27 | #if LLVM_NATIVE_TARGET_TEST_ENABLED == 0 |
28 | #define SKIP_WITHOUT_NATIVE(x) DISABLED_##x |
29 | #else |
30 | #define SKIP_WITHOUT_NATIVE(x) x |
31 | #endif |
32 | |
33 | class MLIRTargetLLVM : public ::testing::Test { |
34 | protected: |
35 | void SetUp() override { |
36 | llvm::InitializeNativeTarget(); |
37 | llvm::InitializeNativeTargetAsmPrinter(); |
38 | } |
39 | }; |
40 | |
41 | TEST_F(MLIRTargetLLVM, SKIP_WITHOUT_NATIVE(SerializeToLLVMBitcode)) { |
42 | std::string moduleStr = R"mlir( |
43 | llvm.func @foo(%arg0 : i32) { |
44 | llvm.return |
45 | } |
46 | )mlir"; |
47 | |
48 | DialectRegistry registry; |
49 | registerBuiltinDialectTranslation(registry); |
50 | registerLLVMDialectTranslation(registry); |
51 | MLIRContext context(registry); |
52 | |
53 | OwningOpRef<ModuleOp> module = |
54 | parseSourceString<ModuleOp>(moduleStr, &context); |
55 | ASSERT_TRUE(!!module); |
56 | |
57 | // Serialize the module. |
58 | std::string targetTriple = llvm::sys::getProcessTriple(); |
59 | LLVM::ModuleToObject serializer(*(module->getOperation()), targetTriple, "", |
60 | ""); |
61 | std::optional<SmallVector<char, 0>> serializedModule = serializer.run(); |
62 | ASSERT_TRUE(!!serializedModule); |
63 | ASSERT_TRUE(!serializedModule->empty()); |
64 | |
65 | // Read the serialized module. |
66 | llvm::MemoryBufferRef buffer( |
67 | StringRef(serializedModule->data(), serializedModule->size()), "module"); |
68 | llvm::LLVMContext llvmContext; |
69 | llvm::Expected<std::unique_ptr<llvm::Module>> llvmModule = |
70 | llvm::getLazyBitcodeModule(Buffer: buffer, Context&: llvmContext); |
71 | ASSERT_TRUE(!!llvmModule); |
72 | ASSERT_TRUE(!!*llvmModule); |
73 | |
74 | // Check that it has a function named `foo`. |
75 | ASSERT_TRUE((*llvmModule)->getFunction("foo") != nullptr); |
76 | } |
77 |