1 //===- llvm/unittest/Linker/LinkModulesTest.cpp - IRBuilder tests ---------===//
3 // Part of the LLVM Project, 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
7 //===----------------------------------------------------------------------===//
9 #include "llvm-c/Core.h"
10 #include "llvm-c/Linker.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/AsmParser/Parser.h"
13 #include "llvm/IR/BasicBlock.h"
14 #include "llvm/IR/DataLayout.h"
15 #include "llvm/IR/Function.h"
16 #include "llvm/IR/IRBuilder.h"
17 #include "llvm/IR/Module.h"
18 #include "llvm/Linker/Linker.h"
19 #include "llvm/Support/SourceMgr.h"
20 #include "gtest/gtest.h"
26 class LinkModuleTest
: public testing::Test
{
28 void SetUp() override
{
29 M
.reset(new Module("MyModule", Ctx
));
30 FunctionType
*FTy
= FunctionType::get(
31 Type::getInt8PtrTy(Ctx
), Type::getInt32Ty(Ctx
), false /*=isVarArg*/);
32 F
= Function::Create(FTy
, Function::ExternalLinkage
, "ba_func", M
.get());
33 F
->setCallingConv(CallingConv::C
);
35 EntryBB
= BasicBlock::Create(Ctx
, "entry", F
);
36 SwitchCase1BB
= BasicBlock::Create(Ctx
, "switch.case.1", F
);
37 SwitchCase2BB
= BasicBlock::Create(Ctx
, "switch.case.2", F
);
38 ExitBB
= BasicBlock::Create(Ctx
, "exit", F
);
40 AT
= ArrayType::get(Type::getInt8PtrTy(Ctx
), 3);
42 GV
= new GlobalVariable(*M
.get(), AT
, false /*=isConstant*/,
43 GlobalValue::InternalLinkage
, nullptr,"switch.bas");
46 std::vector
<Constant
*> Init
;
47 Constant
*SwitchCase1BA
= BlockAddress::get(SwitchCase1BB
);
48 Init
.push_back(SwitchCase1BA
);
50 Constant
*SwitchCase2BA
= BlockAddress::get(SwitchCase2BB
);
51 Init
.push_back(SwitchCase2BA
);
53 ConstantInt
*One
= ConstantInt::get(Type::getInt32Ty(Ctx
), 1);
54 Constant
*OnePtr
= ConstantExpr::getIntToPtr(One
, Type::getInt8PtrTy(Ctx
));
55 Init
.push_back(OnePtr
);
57 GV
->setInitializer(ConstantArray::get(AT
, Init
));
60 void TearDown() override
{ M
.reset(); }
63 std::unique_ptr
<Module
> M
;
68 BasicBlock
*SwitchCase1BB
;
69 BasicBlock
*SwitchCase2BB
;
73 static void expectNoDiags(const DiagnosticInfo
&DI
, void *C
) {
74 llvm_unreachable("expectNoDiags called!");
77 TEST_F(LinkModuleTest
, BlockAddress
) {
78 IRBuilder
<> Builder(EntryBB
);
80 std::vector
<Value
*> GEPIndices
;
81 GEPIndices
.push_back(ConstantInt::get(Type::getInt32Ty(Ctx
), 0));
82 GEPIndices
.push_back(&*F
->arg_begin());
84 Value
*GEP
= Builder
.CreateGEP(AT
, GV
, GEPIndices
, "switch.gep");
85 Value
*Load
= Builder
.CreateLoad(AT
->getElementType(), GEP
, "switch.load");
87 Builder
.CreateRet(Load
);
89 Builder
.SetInsertPoint(SwitchCase1BB
);
90 Builder
.CreateBr(ExitBB
);
92 Builder
.SetInsertPoint(SwitchCase2BB
);
93 Builder
.CreateBr(ExitBB
);
95 Builder
.SetInsertPoint(ExitBB
);
96 Builder
.CreateRet(ConstantPointerNull::get(Type::getInt8PtrTy(Ctx
)));
98 Module
*LinkedModule
= new Module("MyModuleLinked", Ctx
);
99 Ctx
.setDiagnosticHandlerCallBack(expectNoDiags
);
100 Linker::linkModules(*LinkedModule
, std::move(M
));
102 // Check that the global "@switch.bas" is well-formed.
103 const GlobalVariable
*LinkedGV
= LinkedModule
->getNamedGlobal("switch.bas");
104 const Constant
*Init
= LinkedGV
->getInitializer();
106 // @switch.bas = internal global [3 x i8*]
107 // [i8* blockaddress(@ba_func, %switch.case.1),
108 // i8* blockaddress(@ba_func, %switch.case.2),
109 // i8* inttoptr (i32 1 to i8*)]
111 ArrayType
*AT
= ArrayType::get(Type::getInt8PtrTy(Ctx
), 3);
112 EXPECT_EQ(AT
, Init
->getType());
114 Value
*Elem
= Init
->getOperand(0);
115 ASSERT_TRUE(isa
<BlockAddress
>(Elem
));
116 EXPECT_EQ(cast
<BlockAddress
>(Elem
)->getFunction(),
117 LinkedModule
->getFunction("ba_func"));
118 EXPECT_EQ(cast
<BlockAddress
>(Elem
)->getBasicBlock()->getParent(),
119 LinkedModule
->getFunction("ba_func"));
121 Elem
= Init
->getOperand(1);
122 ASSERT_TRUE(isa
<BlockAddress
>(Elem
));
123 EXPECT_EQ(cast
<BlockAddress
>(Elem
)->getFunction(),
124 LinkedModule
->getFunction("ba_func"));
125 EXPECT_EQ(cast
<BlockAddress
>(Elem
)->getBasicBlock()->getParent(),
126 LinkedModule
->getFunction("ba_func"));
131 static Module
*getExternal(LLVMContext
&Ctx
, StringRef FuncName
) {
132 // Create a module with an empty externally-linked function
133 Module
*M
= new Module("ExternalModule", Ctx
);
134 FunctionType
*FTy
= FunctionType::get(
135 Type::getVoidTy(Ctx
), Type::getInt8PtrTy(Ctx
), false /*=isVarArgs*/);
138 Function::Create(FTy
, Function::ExternalLinkage
, FuncName
, M
);
139 F
->setCallingConv(CallingConv::C
);
141 BasicBlock
*BB
= BasicBlock::Create(Ctx
, "", F
);
142 IRBuilder
<> Builder(BB
);
143 Builder
.CreateRetVoid();
147 static Module
*getInternal(LLVMContext
&Ctx
) {
148 Module
*InternalM
= new Module("InternalModule", Ctx
);
149 FunctionType
*FTy
= FunctionType::get(
150 Type::getVoidTy(Ctx
), Type::getInt8PtrTy(Ctx
), false /*=isVarArgs*/);
153 Function::Create(FTy
, Function::InternalLinkage
, "bar", InternalM
);
154 F
->setCallingConv(CallingConv::C
);
156 BasicBlock
*BB
= BasicBlock::Create(Ctx
, "", F
);
157 IRBuilder
<> Builder(BB
);
158 Builder
.CreateRetVoid();
160 StructType
*STy
= StructType::create(Ctx
, PointerType::get(FTy
, 0));
163 new GlobalVariable(*InternalM
, STy
, false /*=isConstant*/,
164 GlobalValue::InternalLinkage
, nullptr, "g");
166 GV
->setInitializer(ConstantStruct::get(STy
, F
));
170 TEST_F(LinkModuleTest
, EmptyModule
) {
171 std::unique_ptr
<Module
> InternalM(getInternal(Ctx
));
172 std::unique_ptr
<Module
> EmptyM(new Module("EmptyModule1", Ctx
));
173 Ctx
.setDiagnosticHandlerCallBack(expectNoDiags
);
174 Linker::linkModules(*EmptyM
, std::move(InternalM
));
177 TEST_F(LinkModuleTest
, EmptyModule2
) {
178 std::unique_ptr
<Module
> InternalM(getInternal(Ctx
));
179 std::unique_ptr
<Module
> EmptyM(new Module("EmptyModule1", Ctx
));
180 Ctx
.setDiagnosticHandlerCallBack(expectNoDiags
);
181 Linker::linkModules(*InternalM
, std::move(EmptyM
));
184 TEST_F(LinkModuleTest
, TypeMerge
) {
188 const char *M1Str
= "%t = type {i32}\n"
189 "@t1 = weak global %t zeroinitializer\n";
190 std::unique_ptr
<Module
> M1
= parseAssemblyString(M1Str
, Err
, C
);
192 const char *M2Str
= "%t = type {i32}\n"
193 "@t2 = weak global %t zeroinitializer\n";
194 std::unique_ptr
<Module
> M2
= parseAssemblyString(M2Str
, Err
, C
);
196 Ctx
.setDiagnosticHandlerCallBack(expectNoDiags
);
197 Linker::linkModules(*M1
, std::move(M2
));
199 EXPECT_EQ(M1
->getNamedGlobal("t1")->getType(),
200 M1
->getNamedGlobal("t2")->getType());
203 TEST_F(LinkModuleTest
, NewCAPISuccess
) {
204 std::unique_ptr
<Module
> DestM(getExternal(Ctx
, "foo"));
205 std::unique_ptr
<Module
> SourceM(getExternal(Ctx
, "bar"));
207 LLVMLinkModules2(wrap(DestM
.get()), wrap(SourceM
.release()));
208 EXPECT_EQ(0, Result
);
209 // "bar" is present in destination module
210 EXPECT_NE(nullptr, DestM
->getFunction("bar"));
213 static void diagnosticHandler(LLVMDiagnosticInfoRef DI
, void *C
) {
214 auto *Err
= reinterpret_cast<std::string
*>(C
);
215 char *CErr
= LLVMGetDiagInfoDescription(DI
);
217 LLVMDisposeMessage(CErr
);
220 TEST_F(LinkModuleTest
, NewCAPIFailure
) {
221 // Symbol clash between two modules
224 LLVMContextSetDiagnosticHandler(wrap(&Ctx
), diagnosticHandler
, &Err
);
226 std::unique_ptr
<Module
> DestM(getExternal(Ctx
, "foo"));
227 std::unique_ptr
<Module
> SourceM(getExternal(Ctx
, "foo"));
229 LLVMLinkModules2(wrap(DestM
.get()), wrap(SourceM
.release()));
230 EXPECT_EQ(1, Result
);
231 EXPECT_EQ("Linking globals named 'foo': symbol multiply defined!", Err
);
234 TEST_F(LinkModuleTest
, MoveDistinctMDs
) {
238 const char *SrcStr
= "define void @foo() !attach !0 {\n"
240 " call void @llvm.md(metadata !1)\n"
241 " ret void, !attach !2\n"
243 "declare void @llvm.md(metadata)\n"
244 "!named = !{!3, !4}\n"
245 "!0 = distinct !{}\n"
246 "!1 = distinct !{}\n"
247 "!2 = distinct !{}\n"
248 "!3 = distinct !{}\n"
251 std::unique_ptr
<Module
> Src
= parseAssemblyString(SrcStr
, Err
, C
);
253 ASSERT_TRUE(Src
.get());
255 // Get the addresses of the Metadata before merging.
256 Function
*F
= &*Src
->begin();
257 ASSERT_EQ("foo", F
->getName());
258 BasicBlock
*BB
= &F
->getEntryBlock();
259 auto *CI
= cast
<CallInst
>(&BB
->front());
260 auto *RI
= cast
<ReturnInst
>(BB
->getTerminator());
261 NamedMDNode
*NMD
= &*Src
->named_metadata_begin();
263 MDNode
*M0
= F
->getMetadata("attach");
265 cast
<MDNode
>(cast
<MetadataAsValue
>(CI
->getArgOperand(0))->getMetadata());
266 MDNode
*M2
= RI
->getMetadata("attach");
267 MDNode
*M3
= NMD
->getOperand(0);
268 MDNode
*M4
= NMD
->getOperand(1);
270 // Confirm a few things about the IR.
271 EXPECT_TRUE(M0
->isDistinct());
272 EXPECT_TRUE(M1
->isDistinct());
273 EXPECT_TRUE(M2
->isDistinct());
274 EXPECT_TRUE(M3
->isDistinct());
275 EXPECT_TRUE(M4
->isUniqued());
276 EXPECT_EQ(M3
, M4
->getOperand(0));
278 // Link into destination module.
279 auto Dst
= std::make_unique
<Module
>("Linked", C
);
280 ASSERT_TRUE(Dst
.get());
281 Ctx
.setDiagnosticHandlerCallBack(expectNoDiags
);
282 Linker::linkModules(*Dst
, std::move(Src
));
284 // Check that distinct metadata was moved, not cloned. Even !4, the uniqued
285 // node, should effectively be moved, since its only operand hasn't changed.
287 BB
= &F
->getEntryBlock();
288 CI
= cast
<CallInst
>(&BB
->front());
289 RI
= cast
<ReturnInst
>(BB
->getTerminator());
290 NMD
= &*Dst
->named_metadata_begin();
292 EXPECT_EQ(M0
, F
->getMetadata("attach"));
293 EXPECT_EQ(M1
, cast
<MetadataAsValue
>(CI
->getArgOperand(0))->getMetadata());
294 EXPECT_EQ(M2
, RI
->getMetadata("attach"));
295 EXPECT_EQ(M3
, NMD
->getOperand(0));
296 EXPECT_EQ(M4
, NMD
->getOperand(1));
298 // Confirm a few things about the IR. This shouldn't have changed.
299 EXPECT_TRUE(M0
->isDistinct());
300 EXPECT_TRUE(M1
->isDistinct());
301 EXPECT_TRUE(M2
->isDistinct());
302 EXPECT_TRUE(M3
->isDistinct());
303 EXPECT_TRUE(M4
->isUniqued());
304 EXPECT_EQ(M3
, M4
->getOperand(0));
307 TEST_F(LinkModuleTest
, RemangleIntrinsics
) {
311 // We load two modules inside the same context C. In both modules there is a
312 // "struct.rtx_def" type. In the module loaded the second (Bar) this type will
313 // be renamed to "struct.rtx_def.0". Check that the intrinsics which have this
314 // type in the signature are properly remangled.
316 "%struct.rtx_def = type { i16 }\n"
317 "define void @foo(%struct.rtx_def %a) {\n"
318 " call %struct.rtx_def @llvm.ssa.copy.s_struct.rtx_defs(%struct.rtx_def %a)\n"
321 "declare %struct.rtx_def @llvm.ssa.copy.s_struct.rtx_defs(%struct.rtx_def)\n";
324 "%struct.rtx_def = type { i16 }\n"
325 "define void @bar(%struct.rtx_def %a) {\n"
326 " call %struct.rtx_def @llvm.ssa.copy.s_struct.rtx_defs(%struct.rtx_def %a)\n"
329 "declare %struct.rtx_def @llvm.ssa.copy.s_struct.rtx_defs(%struct.rtx_def)\n";
331 std::unique_ptr
<Module
> Foo
= parseAssemblyString(FooStr
, Err
, C
);
333 ASSERT_TRUE(Foo
.get());
334 // Foo is loaded first, so the type and the intrinsic have theis original
336 ASSERT_TRUE(Foo
->getFunction("llvm.ssa.copy.s_struct.rtx_defs"));
337 ASSERT_FALSE(Foo
->getFunction("llvm.ssa.copy.s_struct.rtx_defs.0"));
339 std::unique_ptr
<Module
> Bar
= parseAssemblyString(BarStr
, Err
, C
);
341 ASSERT_TRUE(Bar
.get());
342 // Bar is loaded after Foo, so the type is renamed to struct.rtx_def.0. Check
343 // that the intrinsic is also renamed.
344 ASSERT_FALSE(Bar
->getFunction("llvm.ssa.copy.s_struct.rtx_defs"));
345 ASSERT_TRUE(Bar
->getFunction("llvm.ssa.copy.s_struct.rtx_def.0s"));
347 // Link two modules together.
348 auto Dst
= std::make_unique
<Module
>("Linked", C
);
349 ASSERT_TRUE(Dst
.get());
350 Ctx
.setDiagnosticHandlerCallBack(expectNoDiags
);
351 bool Failed
= Linker::linkModules(*Foo
, std::move(Bar
));
352 ASSERT_FALSE(Failed
);
354 // "struct.rtx_def" from Foo and "struct.rtx_def.0" from Bar are isomorphic
355 // types, so they must be uniquified by linker. Check that they use the same
356 // intrinsic definition.
357 Function
*F
= Foo
->getFunction("llvm.ssa.copy.s_struct.rtx_defs");
358 ASSERT_EQ(F
->getNumUses(), (unsigned)2);
361 } // end anonymous namespace