Always pass a diagnostic handler to the linker.
[oota-llvm.git] / unittests / Linker / LinkModulesTest.cpp
1 //===- llvm/unittest/Linker/LinkModulesTest.cpp - IRBuilder tests ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/ADT/STLExtras.h"
11 #include "llvm/AsmParser/Parser.h"
12 #include "llvm/IR/BasicBlock.h"
13 #include "llvm/IR/DataLayout.h"
14 #include "llvm/IR/Function.h"
15 #include "llvm/IR/IRBuilder.h"
16 #include "llvm/IR/Module.h"
17 #include "llvm/Linker/Linker.h"
18 #include "llvm/Support/SourceMgr.h"
19 #include "llvm-c/Linker.h"
20 #include "gtest/gtest.h"
21
22 using namespace llvm;
23
24 namespace {
25
26 class LinkModuleTest : public testing::Test {
27 protected:
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);
34
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);
39
40     AT = ArrayType::get(Type::getInt8PtrTy(Ctx), 3);
41
42     GV = new GlobalVariable(*M.get(), AT, false /*=isConstant*/,
43                             GlobalValue::InternalLinkage, nullptr,"switch.bas");
44
45     // Global Initializer
46     std::vector<Constant *> Init;
47     Constant *SwitchCase1BA = BlockAddress::get(SwitchCase1BB);
48     Init.push_back(SwitchCase1BA);
49
50     Constant *SwitchCase2BA = BlockAddress::get(SwitchCase2BB);
51     Init.push_back(SwitchCase2BA);
52
53     ConstantInt *One = ConstantInt::get(Type::getInt32Ty(Ctx), 1);
54     Constant *OnePtr = ConstantExpr::getCast(Instruction::IntToPtr, One,
55                                              Type::getInt8PtrTy(Ctx));
56     Init.push_back(OnePtr);
57
58     GV->setInitializer(ConstantArray::get(AT, Init));
59   }
60
61   void TearDown() override { M.reset(); }
62
63   LLVMContext Ctx;
64   std::unique_ptr<Module> M;
65   Function *F;
66   ArrayType *AT;
67   GlobalVariable *GV;
68   BasicBlock *EntryBB;
69   BasicBlock *SwitchCase1BB;
70   BasicBlock *SwitchCase2BB;
71   BasicBlock *ExitBB;
72 };
73
74 static void expectNoDiags(const DiagnosticInfo &DI) { EXPECT_TRUE(false); }
75
76 TEST_F(LinkModuleTest, BlockAddress) {
77   IRBuilder<> Builder(EntryBB);
78
79   std::vector<Value *> GEPIndices;
80   GEPIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ctx), 0));
81   GEPIndices.push_back(&*F->arg_begin());
82
83   Value *GEP = Builder.CreateGEP(AT, GV, GEPIndices, "switch.gep");
84   Value *Load = Builder.CreateLoad(GEP, "switch.load");
85
86   Builder.CreateRet(Load);
87
88   Builder.SetInsertPoint(SwitchCase1BB);
89   Builder.CreateBr(ExitBB);
90
91   Builder.SetInsertPoint(SwitchCase2BB);
92   Builder.CreateBr(ExitBB);
93
94   Builder.SetInsertPoint(ExitBB);
95   Builder.CreateRet(ConstantPointerNull::get(Type::getInt8PtrTy(Ctx)));
96
97   Module *LinkedModule = new Module("MyModuleLinked", Ctx);
98   Linker::linkModules(*LinkedModule, *M, expectNoDiags);
99
100   // Delete the original module.
101   M.reset();
102
103   // Check that the global "@switch.bas" is well-formed.
104   const GlobalVariable *LinkedGV = LinkedModule->getNamedGlobal("switch.bas");
105   const Constant *Init = LinkedGV->getInitializer();
106
107   // @switch.bas = internal global [3 x i8*]
108   //   [i8* blockaddress(@ba_func, %switch.case.1),
109   //    i8* blockaddress(@ba_func, %switch.case.2),
110   //    i8* inttoptr (i32 1 to i8*)]
111
112   ArrayType *AT = ArrayType::get(Type::getInt8PtrTy(Ctx), 3);
113   EXPECT_EQ(AT, Init->getType());
114
115   Value *Elem = Init->getOperand(0);
116   ASSERT_TRUE(isa<BlockAddress>(Elem));
117   EXPECT_EQ(cast<BlockAddress>(Elem)->getFunction(),
118             LinkedModule->getFunction("ba_func"));
119   EXPECT_EQ(cast<BlockAddress>(Elem)->getBasicBlock()->getParent(),
120             LinkedModule->getFunction("ba_func"));
121
122   Elem = Init->getOperand(1);
123   ASSERT_TRUE(isa<BlockAddress>(Elem));
124   EXPECT_EQ(cast<BlockAddress>(Elem)->getFunction(),
125             LinkedModule->getFunction("ba_func"));
126   EXPECT_EQ(cast<BlockAddress>(Elem)->getBasicBlock()->getParent(),
127             LinkedModule->getFunction("ba_func"));
128
129   delete LinkedModule;
130 }
131
132 static Module *getExternal(LLVMContext &Ctx, StringRef FuncName) {
133   // Create a module with an empty externally-linked function
134   Module *M = new Module("ExternalModule", Ctx);
135   FunctionType *FTy = FunctionType::get(
136       Type::getVoidTy(Ctx), Type::getInt8PtrTy(Ctx), false /*=isVarArgs*/);
137
138   Function *F =
139       Function::Create(FTy, Function::ExternalLinkage, FuncName, M);
140   F->setCallingConv(CallingConv::C);
141
142   BasicBlock *BB = BasicBlock::Create(Ctx, "", F);
143   IRBuilder<> Builder(BB);
144   Builder.CreateRetVoid();
145   return M;
146 }
147
148 static Module *getInternal(LLVMContext &Ctx) {
149   Module *InternalM = new Module("InternalModule", Ctx);
150   FunctionType *FTy = FunctionType::get(
151       Type::getVoidTy(Ctx), Type::getInt8PtrTy(Ctx), false /*=isVarArgs*/);
152
153   Function *F =
154       Function::Create(FTy, Function::InternalLinkage, "bar", InternalM);
155   F->setCallingConv(CallingConv::C);
156
157   BasicBlock *BB = BasicBlock::Create(Ctx, "", F);
158   IRBuilder<> Builder(BB);
159   Builder.CreateRetVoid();
160
161   StructType *STy = StructType::create(Ctx, PointerType::get(FTy, 0));
162
163   GlobalVariable *GV =
164       new GlobalVariable(*InternalM, STy, false /*=isConstant*/,
165                          GlobalValue::InternalLinkage, nullptr, "g");
166
167   GV->setInitializer(ConstantStruct::get(STy, F));
168   return InternalM;
169 }
170
171 TEST_F(LinkModuleTest, EmptyModule) {
172   std::unique_ptr<Module> InternalM(getInternal(Ctx));
173   std::unique_ptr<Module> EmptyM(new Module("EmptyModule1", Ctx));
174   Linker::linkModules(*EmptyM, *InternalM, expectNoDiags);
175 }
176
177 TEST_F(LinkModuleTest, EmptyModule2) {
178   std::unique_ptr<Module> InternalM(getInternal(Ctx));
179   std::unique_ptr<Module> EmptyM(new Module("EmptyModule1", Ctx));
180   Linker::linkModules(*InternalM, *EmptyM, expectNoDiags);
181 }
182
183 TEST_F(LinkModuleTest, TypeMerge) {
184   LLVMContext C;
185   SMDiagnostic Err;
186
187   const char *M1Str = "%t = type {i32}\n"
188                       "@t1 = weak global %t zeroinitializer\n";
189   std::unique_ptr<Module> M1 = parseAssemblyString(M1Str, Err, C);
190
191   const char *M2Str = "%t = type {i32}\n"
192                       "@t2 = weak global %t zeroinitializer\n";
193   std::unique_ptr<Module> M2 = parseAssemblyString(M2Str, Err, C);
194
195   Linker::linkModules(*M1, *M2, [](const llvm::DiagnosticInfo &) {});
196
197   EXPECT_EQ(M1->getNamedGlobal("t1")->getType(),
198             M1->getNamedGlobal("t2")->getType());
199 }
200
201 TEST_F(LinkModuleTest, CAPISuccess) {
202   std::unique_ptr<Module> DestM(getExternal(Ctx, "foo"));
203   std::unique_ptr<Module> SourceM(getExternal(Ctx, "bar"));
204   char *errout = nullptr;
205   LLVMBool result = LLVMLinkModules(wrap(DestM.get()), wrap(SourceM.get()),
206                                     LLVMLinkerDestroySource, &errout);
207   EXPECT_EQ(0, result);
208   EXPECT_EQ(nullptr, errout);
209   // "bar" is present in destination module
210   EXPECT_NE(nullptr, DestM->getFunction("bar"));
211 }
212
213 TEST_F(LinkModuleTest, CAPIFailure) {
214   // Symbol clash between two modules
215   std::unique_ptr<Module> DestM(getExternal(Ctx, "foo"));
216   std::unique_ptr<Module> SourceM(getExternal(Ctx, "foo"));
217   char *errout = nullptr;
218   LLVMBool result = LLVMLinkModules(wrap(DestM.get()), wrap(SourceM.get()),
219                                     LLVMLinkerDestroySource, &errout);
220   EXPECT_EQ(1, result);
221   EXPECT_STREQ("Linking globals named 'foo': symbol multiply defined!", errout);
222   LLVMDisposeMessage(errout);
223 }
224
225 TEST_F(LinkModuleTest, MoveDistinctMDs) {
226   LLVMContext C;
227   SMDiagnostic Err;
228
229   const char *SrcStr = "define void @foo() !attach !0 {\n"
230                        "entry:\n"
231                        "  call void @llvm.md(metadata !1)\n"
232                        "  ret void, !attach !2\n"
233                        "}\n"
234                        "declare void @llvm.md(metadata)\n"
235                        "!named = !{!3, !4}\n"
236                        "!0 = distinct !{}\n"
237                        "!1 = distinct !{}\n"
238                        "!2 = distinct !{}\n"
239                        "!3 = distinct !{}\n"
240                        "!4 = !{!3}\n";
241
242   std::unique_ptr<Module> Src = parseAssemblyString(SrcStr, Err, C);
243   assert(Src);
244   ASSERT_TRUE(Src.get());
245
246   // Get the addresses of the Metadata before merging.
247   Function *F = &*Src->begin();
248   ASSERT_EQ("foo", F->getName());
249   BasicBlock *BB = &F->getEntryBlock();
250   auto *CI = cast<CallInst>(&BB->front());
251   auto *RI = cast<ReturnInst>(BB->getTerminator());
252   NamedMDNode *NMD = &*Src->named_metadata_begin();
253
254   MDNode *M0 = F->getMetadata("attach");
255   MDNode *M1 =
256       cast<MDNode>(cast<MetadataAsValue>(CI->getArgOperand(0))->getMetadata());
257   MDNode *M2 = RI->getMetadata("attach");
258   MDNode *M3 = NMD->getOperand(0);
259   MDNode *M4 = NMD->getOperand(1);
260
261   // Confirm a few things about the IR.
262   EXPECT_TRUE(M0->isDistinct());
263   EXPECT_TRUE(M1->isDistinct());
264   EXPECT_TRUE(M2->isDistinct());
265   EXPECT_TRUE(M3->isDistinct());
266   EXPECT_TRUE(M4->isUniqued());
267   EXPECT_EQ(M3, M4->getOperand(0));
268
269   // Link into destination module.
270   auto Dst = llvm::make_unique<Module>("Linked", C);
271   ASSERT_TRUE(Dst.get());
272   Linker::linkModules(*Dst, *Src, [](const llvm::DiagnosticInfo &) {});
273
274   // Check that distinct metadata was moved, not cloned.  Even !4, the uniqued
275   // node, should effectively be moved, since its only operand hasn't changed.
276   F = &*Dst->begin();
277   BB = &F->getEntryBlock();
278   CI = cast<CallInst>(&BB->front());
279   RI = cast<ReturnInst>(BB->getTerminator());
280   NMD = &*Dst->named_metadata_begin();
281
282   EXPECT_EQ(M0, F->getMetadata("attach"));
283   EXPECT_EQ(M1, cast<MetadataAsValue>(CI->getArgOperand(0))->getMetadata());
284   EXPECT_EQ(M2, RI->getMetadata("attach"));
285   EXPECT_EQ(M3, NMD->getOperand(0));
286   EXPECT_EQ(M4, NMD->getOperand(1));
287
288   // Confirm a few things about the IR.  This shouldn't have changed.
289   EXPECT_TRUE(M0->isDistinct());
290   EXPECT_TRUE(M1->isDistinct());
291   EXPECT_TRUE(M2->isDistinct());
292   EXPECT_TRUE(M3->isDistinct());
293   EXPECT_TRUE(M4->isUniqued());
294   EXPECT_EQ(M3, M4->getOperand(0));
295 }
296
297 } // end anonymous namespace