blob: 50936fa55f738d0b3a5e35914f9e493e84446ee6 [file] [log] [blame]
Mikhail Glushenkov59a5afa2009-03-03 10:04:23 +00001//===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
Misha Brukman10468d82005-04-21 22:55:34 +00002//
Reid Spencer361e5132004-11-12 20:37:43 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman10468d82005-04-21 22:55:34 +00007//
Reid Spencer361e5132004-11-12 20:37:43 +00008//===----------------------------------------------------------------------===//
9//
10// This file implements the LLVM module linker.
11//
Reid Spencer361e5132004-11-12 20:37:43 +000012//===----------------------------------------------------------------------===//
13
Rafael Espindolacaabe222015-12-10 14:19:35 +000014#include "LinkDiagnosticInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm-c/Linker.h"
Bill Wendling66f02412012-02-11 11:38:06 +000016#include "llvm/ADT/SetVector.h"
Rafael Espindolacaabe222015-12-10 14:19:35 +000017#include "llvm/ADT/StringSet.h"
Peter Collingbourne7c702112017-02-03 16:58:19 +000018#include "llvm/IR/Comdat.h"
Rafael Espindolad12b4a32014-10-25 04:06:10 +000019#include "llvm/IR/DiagnosticPrinter.h"
Peter Collingbourne7c702112017-02-03 16:58:19 +000020#include "llvm/IR/GlobalValue.h"
Rafael Espindola9d2bfc42015-12-14 23:17:03 +000021#include "llvm/IR/LLVMContext.h"
Peter Collingbourne7c702112017-02-03 16:58:19 +000022#include "llvm/IR/Module.h"
Teresa Johnson488a8002016-02-10 18:11:31 +000023#include "llvm/Linker/Linker.h"
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +000024#include "llvm/Support/Error.h"
Reid Spencer361e5132004-11-12 20:37:43 +000025using namespace llvm;
26
Chris Lattnereee6f992008-06-16 21:00:18 +000027namespace {
Rafael Espindolac84f6082014-11-25 06:11:24 +000028
29/// This is an implementation class for the LinkModules function, which is the
30/// entrypoint for this file.
31class ModuleLinker {
Rafael Espindolacaabe222015-12-10 14:19:35 +000032 IRMover &Mover;
Rafael Espindola40358fb2016-02-16 18:50:12 +000033 std::unique_ptr<Module> SrcM;
Rafael Espindolac84f6082014-11-25 06:11:24 +000034
Rafael Espindola4b5ec262015-12-02 22:59:04 +000035 SetVector<GlobalValue *> ValuesToLink;
Rafael Espindolacaabe222015-12-10 14:19:35 +000036 StringSet<> Internalize;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000037
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +000038 /// For symbol clashes, prefer those from Src.
Artem Belevich020d4fb2015-09-01 17:55:55 +000039 unsigned Flags;
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +000040
Rafael Espindolacaabe222015-12-10 14:19:35 +000041 /// Used as the callback for lazy linking.
42 /// The mover has just hit GV and we have to decide if it, and other members
43 /// of the same comdat, should be linked. Every member to be linked is passed
44 /// to Add.
Benjamin Kramerc321e532016-06-08 19:09:22 +000045 void addLazyFor(GlobalValue &GV, const IRMover::ValueAdder &Add);
Rafael Espindolabaa3bf82015-12-01 15:19:48 +000046
Artem Belevich020d4fb2015-09-01 17:55:55 +000047 bool shouldOverrideFromSrc() { return Flags & Linker::OverrideFromSrc; }
48 bool shouldLinkOnlyNeeded() { return Flags & Linker::LinkOnlyNeeded; }
49 bool shouldInternalizeLinkedSymbols() {
50 return Flags & Linker::InternalizeLinkedSymbols;
51 }
52
Rafael Espindolac84f6082014-11-25 06:11:24 +000053 bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
54 const GlobalValue &Src);
Rafael Espindolaed6dc372014-05-09 14:39:25 +000055
Rafael Espindolacaabe222015-12-10 14:19:35 +000056 /// Should we have mover and linker error diag info?
Rafael Espindolac84f6082014-11-25 06:11:24 +000057 bool emitError(const Twine &Message) {
Rafael Espindola40358fb2016-02-16 18:50:12 +000058 SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Error, Message));
Rafael Espindolac84f6082014-11-25 06:11:24 +000059 return true;
60 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +000061
Rafael Espindola0e309fe2015-12-01 19:50:54 +000062 bool getComdatLeader(Module &M, StringRef ComdatName,
Rafael Espindolac84f6082014-11-25 06:11:24 +000063 const GlobalVariable *&GVar);
64 bool computeResultingSelectionKind(StringRef ComdatName,
65 Comdat::SelectionKind Src,
66 Comdat::SelectionKind Dst,
67 Comdat::SelectionKind &Result,
68 bool &LinkFromSrc);
69 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
70 ComdatsChosen;
71 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
72 bool &LinkFromSrc);
Rafael Espindola1ee9fbd2016-03-24 00:06:03 +000073 // Keep track of the lazy linked global members of each comdat in source.
74 DenseMap<const Comdat *, std::vector<GlobalValue *>> LazyComdatMembers;
Rafael Espindola4160f5d2014-10-27 23:02:10 +000075
Rafael Espindolac84f6082014-11-25 06:11:24 +000076 /// Given a global in the source module, return the global in the
77 /// destination module that is being linked to, if any.
78 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
Rafael Espindolacaabe222015-12-10 14:19:35 +000079 Module &DstM = Mover.getModule();
Rafael Espindolac84f6082014-11-25 06:11:24 +000080 // If the source has no name it can't link. If it has local linkage,
81 // there is no name match-up going on.
Teresa Johnson4504c1b2016-01-08 15:00:00 +000082 if (!SrcGV->hasName() || GlobalValue::isLocalLinkage(SrcGV->getLinkage()))
Rafael Espindolac84f6082014-11-25 06:11:24 +000083 return nullptr;
Eli Bendersky7da92ed2014-02-20 22:19:24 +000084
Rafael Espindolac84f6082014-11-25 06:11:24 +000085 // Otherwise see if we have a match in the destination module's symtab.
Teresa Johnson4504c1b2016-01-08 15:00:00 +000086 GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName());
Rafael Espindolac84f6082014-11-25 06:11:24 +000087 if (!DGV)
88 return nullptr;
Rafael Espindolaed6dc372014-05-09 14:39:25 +000089
Rafael Espindolac84f6082014-11-25 06:11:24 +000090 // If we found a global with the same name in the dest module, but it has
91 // internal linkage, we are really not doing any linkage here.
92 if (DGV->hasLocalLinkage())
93 return nullptr;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +000094
Rafael Espindolac84f6082014-11-25 06:11:24 +000095 // Otherwise, we do in fact link to the destination global.
96 return DGV;
97 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +000098
Rafael Espindola370d5282016-03-22 21:35:47 +000099 /// Drop GV if it is a member of a comdat that we are dropping.
100 /// This can happen with COFF's largest selection kind.
101 void dropReplacedComdat(GlobalValue &GV,
102 const DenseSet<const Comdat *> &ReplacedDstComdats);
103
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000104 bool linkIfNeeded(GlobalValue &GV);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000105
Teresa Johnson4504c1b2016-01-08 15:00:00 +0000106public:
Peter Collingbourne7c702112017-02-03 16:58:19 +0000107 ModuleLinker(IRMover &Mover, std::unique_ptr<Module> SrcM, unsigned Flags)
108 : Mover(Mover), SrcM(std::move(SrcM)), Flags(Flags) {}
Teresa Johnson4504c1b2016-01-08 15:00:00 +0000109
110 bool run();
111};
Teresa Johnson4504c1b2016-01-08 15:00:00 +0000112}
113
Rafael Espindolaeb5e0a72015-11-29 14:33:06 +0000114static GlobalValue::VisibilityTypes
115getMinVisibility(GlobalValue::VisibilityTypes A,
116 GlobalValue::VisibilityTypes B) {
117 if (A == GlobalValue::HiddenVisibility || B == GlobalValue::HiddenVisibility)
118 return GlobalValue::HiddenVisibility;
119 if (A == GlobalValue::ProtectedVisibility ||
120 B == GlobalValue::ProtectedVisibility)
121 return GlobalValue::ProtectedVisibility;
122 return GlobalValue::DefaultVisibility;
123}
124
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000125bool ModuleLinker::getComdatLeader(Module &M, StringRef ComdatName,
David Majnemerdad0a642014-06-27 18:19:56 +0000126 const GlobalVariable *&GVar) {
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000127 const GlobalValue *GVal = M.getNamedValue(ComdatName);
David Majnemerdad0a642014-06-27 18:19:56 +0000128 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
129 GVal = GA->getBaseObject();
130 if (!GVal)
131 // We cannot resolve the size of the aliasee yet.
132 return emitError("Linking COMDATs named '" + ComdatName +
133 "': COMDAT key involves incomputable alias size.");
134 }
135
136 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
137 if (!GVar)
138 return emitError(
139 "Linking COMDATs named '" + ComdatName +
140 "': GlobalVariable required for data dependent selection!");
141
142 return false;
143}
144
145bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
146 Comdat::SelectionKind Src,
147 Comdat::SelectionKind Dst,
148 Comdat::SelectionKind &Result,
149 bool &LinkFromSrc) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000150 Module &DstM = Mover.getModule();
David Majnemerdad0a642014-06-27 18:19:56 +0000151 // The ability to mix Comdat::SelectionKind::Any with
152 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
153 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
154 Dst == Comdat::SelectionKind::Largest;
155 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
156 Src == Comdat::SelectionKind::Largest;
157 if (DstAnyOrLargest && SrcAnyOrLargest) {
158 if (Dst == Comdat::SelectionKind::Largest ||
159 Src == Comdat::SelectionKind::Largest)
160 Result = Comdat::SelectionKind::Largest;
161 else
162 Result = Comdat::SelectionKind::Any;
163 } else if (Src == Dst) {
164 Result = Dst;
165 } else {
166 return emitError("Linking COMDATs named '" + ComdatName +
167 "': invalid selection kinds!");
168 }
169
170 switch (Result) {
171 case Comdat::SelectionKind::Any:
172 // Go with Dst.
173 LinkFromSrc = false;
174 break;
175 case Comdat::SelectionKind::NoDuplicates:
176 return emitError("Linking COMDATs named '" + ComdatName +
177 "': noduplicates has been violated!");
178 case Comdat::SelectionKind::ExactMatch:
179 case Comdat::SelectionKind::Largest:
180 case Comdat::SelectionKind::SameSize: {
181 const GlobalVariable *DstGV;
182 const GlobalVariable *SrcGV;
183 if (getComdatLeader(DstM, ComdatName, DstGV) ||
Rafael Espindola40358fb2016-02-16 18:50:12 +0000184 getComdatLeader(*SrcM, ComdatName, SrcGV))
David Majnemerdad0a642014-06-27 18:19:56 +0000185 return true;
186
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000187 const DataLayout &DstDL = DstM.getDataLayout();
Rafael Espindola40358fb2016-02-16 18:50:12 +0000188 const DataLayout &SrcDL = SrcM->getDataLayout();
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000189 uint64_t DstSize = DstDL.getTypeAllocSize(DstGV->getValueType());
190 uint64_t SrcSize = SrcDL.getTypeAllocSize(SrcGV->getValueType());
David Majnemerdad0a642014-06-27 18:19:56 +0000191 if (Result == Comdat::SelectionKind::ExactMatch) {
192 if (SrcGV->getInitializer() != DstGV->getInitializer())
193 return emitError("Linking COMDATs named '" + ComdatName +
194 "': ExactMatch violated!");
195 LinkFromSrc = false;
196 } else if (Result == Comdat::SelectionKind::Largest) {
197 LinkFromSrc = SrcSize > DstSize;
198 } else if (Result == Comdat::SelectionKind::SameSize) {
199 if (SrcSize != DstSize)
200 return emitError("Linking COMDATs named '" + ComdatName +
201 "': SameSize violated!");
202 LinkFromSrc = false;
203 } else {
204 llvm_unreachable("unknown selection kind");
205 }
206 break;
207 }
208 }
209
210 return false;
211}
212
213bool ModuleLinker::getComdatResult(const Comdat *SrcC,
214 Comdat::SelectionKind &Result,
215 bool &LinkFromSrc) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000216 Module &DstM = Mover.getModule();
Rafael Espindolab16196a2014-08-11 17:07:34 +0000217 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
David Majnemerdad0a642014-06-27 18:19:56 +0000218 StringRef ComdatName = SrcC->getName();
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000219 Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
David Majnemerdad0a642014-06-27 18:19:56 +0000220 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000221
Rafael Espindolab16196a2014-08-11 17:07:34 +0000222 if (DstCI == ComdatSymTab.end()) {
223 // Use the comdat if it is only available in one of the modules.
224 LinkFromSrc = true;
225 Result = SSK;
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000226 return false;
Rafael Espindolab16196a2014-08-11 17:07:34 +0000227 }
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000228
229 const Comdat *DstC = &DstCI->second;
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000230 Comdat::SelectionKind DSK = DstC->getSelectionKind();
231 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
232 LinkFromSrc);
David Majnemerdad0a642014-06-27 18:19:56 +0000233}
James Molloyf6f121e2013-05-28 15:17:05 +0000234
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000235bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
236 const GlobalValue &Dest,
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000237 const GlobalValue &Src) {
Teresa Johnsone5a61912015-12-17 17:14:09 +0000238
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +0000239 // Should we unconditionally use the Src?
Artem Belevich020d4fb2015-09-01 17:55:55 +0000240 if (shouldOverrideFromSrc()) {
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +0000241 LinkFromSrc = true;
242 return false;
243 }
244
Rafael Espindola778fcc72014-11-02 13:28:57 +0000245 // We always have to add Src if it has appending linkage.
246 if (Src.hasAppendingLinkage()) {
247 LinkFromSrc = true;
248 return false;
249 }
250
Rafael Espindolad4bcefc2014-10-24 18:13:04 +0000251 bool SrcIsDeclaration = Src.isDeclarationForLinker();
252 bool DestIsDeclaration = Dest.isDeclarationForLinker();
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000253
254 if (SrcIsDeclaration) {
255 // If Src is external or if both Src & Dest are external.. Just link the
256 // external globals, we aren't adding anything.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000257 if (Src.hasDLLImportStorageClass()) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000258 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000259 LinkFromSrc = DestIsDeclaration;
260 return false;
261 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000262 // If the Dest is weak, use the source linkage.
Rafael Espindolaed11bd22015-12-09 22:44:00 +0000263 if (Dest.hasExternalWeakLinkage()) {
264 LinkFromSrc = true;
265 return false;
266 }
267 // Link an available_externally over a declaration.
268 LinkFromSrc = !Src.isDeclaration() && Dest.isDeclaration();
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000269 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000270 }
271
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000272 if (DestIsDeclaration) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000273 // If Dest is external but Src is not:
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000274 LinkFromSrc = true;
275 return false;
276 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000277
Rafael Espindola09106052014-09-09 15:59:12 +0000278 if (Src.hasCommonLinkage()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000279 if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
280 LinkFromSrc = true;
Rafael Espindola09106052014-09-09 15:59:12 +0000281 return false;
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000282 }
283
284 if (!Dest.hasCommonLinkage()) {
285 LinkFromSrc = false;
286 return false;
287 }
Rafael Espindola09106052014-09-09 15:59:12 +0000288
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000289 const DataLayout &DL = Dest.getParent()->getDataLayout();
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000290 uint64_t DestSize = DL.getTypeAllocSize(Dest.getValueType());
291 uint64_t SrcSize = DL.getTypeAllocSize(Src.getValueType());
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000292 LinkFromSrc = SrcSize > DestSize;
293 return false;
Rafael Espindola09106052014-09-09 15:59:12 +0000294 }
295
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000296 if (Src.isWeakForLinker()) {
297 assert(!Dest.hasExternalWeakLinkage());
298 assert(!Dest.hasAvailableExternallyLinkage());
Rafael Espindola09106052014-09-09 15:59:12 +0000299
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000300 if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
301 LinkFromSrc = true;
302 return false;
303 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000304
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000305 LinkFromSrc = false;
Rafael Espindola09106052014-09-09 15:59:12 +0000306 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000307 }
308
309 if (Dest.isWeakForLinker()) {
310 assert(Src.hasExternalLinkage());
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000311 LinkFromSrc = true;
312 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000313 }
314
315 assert(!Src.hasExternalWeakLinkage());
316 assert(!Dest.hasExternalWeakLinkage());
317 assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
318 "Unexpected linkage type!");
319 return emitError("Linking globals named '" + Src.getName() +
320 "': symbol multiply defined!");
321}
322
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000323bool ModuleLinker::linkIfNeeded(GlobalValue &GV) {
324 GlobalValue *DGV = getLinkedToGlobal(&GV);
325
326 if (shouldLinkOnlyNeeded() && !(DGV && DGV->isDeclaration()))
327 return false;
328
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000329 if (DGV && !GV.hasLocalLinkage() && !GV.hasAppendingLinkage()) {
330 auto *DGVar = dyn_cast<GlobalVariable>(DGV);
331 auto *SGVar = dyn_cast<GlobalVariable>(&GV);
332 if (DGVar && SGVar) {
333 if (DGVar->isDeclaration() && SGVar->isDeclaration() &&
334 (!DGVar->isConstant() || !SGVar->isConstant())) {
335 DGVar->setConstant(false);
336 SGVar->setConstant(false);
337 }
338 if (DGVar->hasCommonLinkage() && SGVar->hasCommonLinkage()) {
339 unsigned Align = std::max(DGVar->getAlignment(), SGVar->getAlignment());
340 SGVar->setAlignment(Align);
341 DGVar->setAlignment(Align);
342 }
343 }
344
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000345 GlobalValue::VisibilityTypes Visibility =
346 getMinVisibility(DGV->getVisibility(), GV.getVisibility());
347 DGV->setVisibility(Visibility);
348 GV.setVisibility(Visibility);
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000349
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000350 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::getMinUnnamedAddr(
351 DGV->getUnnamedAddr(), GV.getUnnamedAddr());
352 DGV->setUnnamedAddr(UnnamedAddr);
353 GV.setUnnamedAddr(UnnamedAddr);
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000354 }
355
Peter Collingbourne7c702112017-02-03 16:58:19 +0000356 if (!DGV && !shouldOverrideFromSrc() &&
357 (GV.hasLocalLinkage() || GV.hasLinkOnceLinkage() ||
358 GV.hasAvailableExternallyLinkage()))
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000359 return false;
360
Rafael Espindolabd03c502015-12-07 16:31:41 +0000361 if (GV.isDeclaration())
362 return false;
363
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000364 if (const Comdat *SC = GV.getComdat()) {
365 bool LinkFromSrc;
366 Comdat::SelectionKind SK;
367 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
Rafael Espindolaf2e71242016-03-23 21:16:33 +0000368 if (!LinkFromSrc)
369 return false;
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000370 }
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000371
372 bool LinkFromSrc = true;
373 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, GV))
374 return true;
375 if (LinkFromSrc)
376 ValuesToLink.insert(&GV);
377 return false;
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000378}
379
Benjamin Kramerc321e532016-06-08 19:09:22 +0000380void ModuleLinker::addLazyFor(GlobalValue &GV, const IRMover::ValueAdder &Add) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000381 // Add these to the internalize list
Peter Collingbournec387e702017-02-02 05:12:15 +0000382 if (!GV.hasLinkOnceLinkage() && !GV.hasAvailableExternallyLinkage() &&
383 !shouldLinkOnlyNeeded())
Rafael Espindolacaabe222015-12-10 14:19:35 +0000384 return;
385
386 if (shouldInternalizeLinkedSymbols())
387 Internalize.insert(GV.getName());
388 Add(GV);
389
390 const Comdat *SC = GV.getComdat();
391 if (!SC)
392 return;
Rafael Espindola1ee9fbd2016-03-24 00:06:03 +0000393 for (GlobalValue *GV2 : LazyComdatMembers[SC]) {
Rafael Espindolae1c42ac2016-03-24 15:23:01 +0000394 GlobalValue *DGV = getLinkedToGlobal(GV2);
395 bool LinkFromSrc = true;
396 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, *GV2))
397 return;
398 if (!LinkFromSrc)
399 continue;
Rafael Espindola1ee9fbd2016-03-24 00:06:03 +0000400 if (shouldInternalizeLinkedSymbols())
Rafael Espindolacaabe222015-12-10 14:19:35 +0000401 Internalize.insert(GV2->getName());
402 Add(*GV2);
403 }
404}
405
Rafael Espindola370d5282016-03-22 21:35:47 +0000406void ModuleLinker::dropReplacedComdat(
407 GlobalValue &GV, const DenseSet<const Comdat *> &ReplacedDstComdats) {
408 Comdat *C = GV.getComdat();
409 if (!C)
410 return;
411 if (!ReplacedDstComdats.count(C))
412 return;
413 if (GV.use_empty()) {
414 GV.eraseFromParent();
415 return;
416 }
417
418 if (auto *F = dyn_cast<Function>(&GV)) {
419 F->deleteBody();
420 } else if (auto *Var = dyn_cast<GlobalVariable>(&GV)) {
421 Var->setInitializer(nullptr);
422 } else {
423 auto &Alias = cast<GlobalAlias>(GV);
424 Module &M = *Alias.getParent();
425 PointerType &Ty = *cast<PointerType>(Alias.getType());
426 GlobalValue *Declaration;
427 if (auto *FTy = dyn_cast<FunctionType>(Alias.getValueType())) {
428 Declaration = Function::Create(FTy, GlobalValue::ExternalLinkage, "", &M);
429 } else {
430 Declaration =
431 new GlobalVariable(M, Ty.getElementType(), /*isConstant*/ false,
432 GlobalValue::ExternalLinkage,
433 /*Initializer*/ nullptr);
434 }
435 Declaration->takeName(&Alias);
436 Alias.replaceAllUsesWith(Declaration);
437 Alias.eraseFromParent();
438 }
439}
440
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000441bool ModuleLinker::run() {
Rafael Espindola370d5282016-03-22 21:35:47 +0000442 Module &DstM = Mover.getModule();
443 DenseSet<const Comdat *> ReplacedDstComdats;
444
Rafael Espindola40358fb2016-02-16 18:50:12 +0000445 for (const auto &SMEC : SrcM->getComdatSymbolTable()) {
David Majnemerdad0a642014-06-27 18:19:56 +0000446 const Comdat &C = SMEC.getValue();
447 if (ComdatsChosen.count(&C))
448 continue;
449 Comdat::SelectionKind SK;
450 bool LinkFromSrc;
451 if (getComdatResult(&C, SK, LinkFromSrc))
452 return true;
453 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
Rafael Espindola370d5282016-03-22 21:35:47 +0000454
455 if (!LinkFromSrc)
456 continue;
457
458 Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
459 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(C.getName());
460 if (DstCI == ComdatSymTab.end())
461 continue;
462
463 // The source comdat is replacing the dest one.
464 const Comdat *DstC = &DstCI->second;
465 ReplacedDstComdats.insert(DstC);
466 }
467
468 // Alias have to go first, since we are not able to find their comdats
469 // otherwise.
470 for (auto I = DstM.alias_begin(), E = DstM.alias_end(); I != E;) {
471 GlobalAlias &GV = *I++;
472 dropReplacedComdat(GV, ReplacedDstComdats);
473 }
474
475 for (auto I = DstM.global_begin(), E = DstM.global_end(); I != E;) {
476 GlobalVariable &GV = *I++;
477 dropReplacedComdat(GV, ReplacedDstComdats);
478 }
479
480 for (auto I = DstM.begin(), E = DstM.end(); I != E;) {
481 Function &GV = *I++;
482 dropReplacedComdat(GV, ReplacedDstComdats);
David Majnemerdad0a642014-06-27 18:19:56 +0000483 }
484
Rafael Espindola40358fb2016-02-16 18:50:12 +0000485 for (GlobalVariable &GV : SrcM->globals())
Rafael Espindola1ee9fbd2016-03-24 00:06:03 +0000486 if (GV.hasLinkOnceLinkage())
487 if (const Comdat *SC = GV.getComdat())
488 LazyComdatMembers[SC].push_back(&GV);
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000489
Rafael Espindola40358fb2016-02-16 18:50:12 +0000490 for (Function &SF : *SrcM)
Rafael Espindola1ee9fbd2016-03-24 00:06:03 +0000491 if (SF.hasLinkOnceLinkage())
492 if (const Comdat *SC = SF.getComdat())
493 LazyComdatMembers[SC].push_back(&SF);
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000494
Rafael Espindola40358fb2016-02-16 18:50:12 +0000495 for (GlobalAlias &GA : SrcM->aliases())
Rafael Espindola1ee9fbd2016-03-24 00:06:03 +0000496 if (GA.hasLinkOnceLinkage())
497 if (const Comdat *SC = GA.getComdat())
498 LazyComdatMembers[SC].push_back(&GA);
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000499
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000500 // Insert all of the globals in src into the DstM module... without linking
501 // initializers (which could refer to functions not yet mapped over).
Rafael Espindola40358fb2016-02-16 18:50:12 +0000502 for (GlobalVariable &GV : SrcM->globals())
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000503 if (linkIfNeeded(GV))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000504 return true;
505
Rafael Espindola40358fb2016-02-16 18:50:12 +0000506 for (Function &SF : *SrcM)
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000507 if (linkIfNeeded(SF))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000508 return true;
509
Rafael Espindola40358fb2016-02-16 18:50:12 +0000510 for (GlobalAlias &GA : SrcM->aliases())
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000511 if (linkIfNeeded(GA))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000512 return true;
513
Rafael Espindolacaabe222015-12-10 14:19:35 +0000514 for (unsigned I = 0; I < ValuesToLink.size(); ++I) {
515 GlobalValue *GV = ValuesToLink[I];
516 const Comdat *SC = GV->getComdat();
517 if (!SC)
518 continue;
Rafael Espindola42e03232016-03-24 14:58:44 +0000519 for (GlobalValue *GV2 : LazyComdatMembers[SC]) {
520 GlobalValue *DGV = getLinkedToGlobal(GV2);
521 bool LinkFromSrc = true;
522 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, *GV2))
523 return true;
524 if (LinkFromSrc)
525 ValuesToLink.insert(GV2);
526 }
Rafael Espindolabeadd562014-12-08 18:05:48 +0000527 }
528
Rafael Espindolacaabe222015-12-10 14:19:35 +0000529 if (shouldInternalizeLinkedSymbols()) {
530 for (GlobalValue *GV : ValuesToLink)
531 Internalize.insert(GV->getName());
532 }
Teresa Johnson10632932015-11-06 17:50:53 +0000533
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000534 // FIXME: Propagate Errors through to the caller instead of emitting
535 // diagnostics.
536 bool HasErrors = false;
537 if (Error E = Mover.move(std::move(SrcM), ValuesToLink.getArrayRef(),
538 [this](GlobalValue &GV, IRMover::ValueAdder Add) {
539 addLazyFor(GV, Add);
Teresa Johnson4b9b3792016-10-12 18:39:29 +0000540 },
Peter Collingbourne7c702112017-02-03 16:58:19 +0000541 /* LinkModuleInlineAsm */ true,
542 /* IsPerformingImport */ false)) {
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000543 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
544 DstM.getContext().diagnose(LinkDiagnosticInfo(DS_Error, EIB.message()));
545 HasErrors = true;
546 });
547 }
548 if (HasErrors)
Teresa Johnson189b2522015-11-06 17:50:48 +0000549 return true;
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000550
Rafael Espindolacaabe222015-12-10 14:19:35 +0000551 for (auto &P : Internalize) {
552 GlobalValue *GV = DstM.getNamedValue(P.first());
553 GV->setLinkage(GlobalValue::InternalLinkage);
554 }
Teresa Johnson189b2522015-11-06 17:50:48 +0000555
Anton Korobeynikov26098882008-03-05 23:21:39 +0000556 return false;
557}
Reid Spencer361e5132004-11-12 20:37:43 +0000558
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000559Linker::Linker(Module &M) : Mover(M) {}
Rafael Espindola3df61b72013-05-04 03:48:37 +0000560
Peter Collingbourne7c702112017-02-03 16:58:19 +0000561bool Linker::linkInModule(std::unique_ptr<Module> Src, unsigned Flags) {
562 ModuleLinker ModLinker(Mover, std::move(Src), Flags);
Teresa Johnsonbef54362015-12-18 19:28:59 +0000563 return ModLinker.run();
Rafael Espindola434e9562015-12-16 23:16:33 +0000564}
565
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000566//===----------------------------------------------------------------------===//
567// LinkModules entrypoint.
568//===----------------------------------------------------------------------===//
569
Rafael Espindola18c89412014-10-27 02:35:46 +0000570/// This function links two modules together, with the resulting Dest module
571/// modified to be the composite of the two input modules. If an error occurs,
572/// true is returned and ErrorMsg (if not null) is set to indicate the problem.
573/// Upon failure, the Dest module could be in a modified state, and shouldn't be
574/// relied on to be consistent.
Rafael Espindola434e9562015-12-16 23:16:33 +0000575bool Linker::linkModules(Module &Dest, std::unique_ptr<Module> Src,
576 unsigned Flags) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000577 Linker L(Dest);
Rafael Espindola434e9562015-12-16 23:16:33 +0000578 return L.linkInModule(std::move(Src), Flags);
Rafael Espindola4160f5d2014-10-27 23:02:10 +0000579}
580
Bill Wendlinga3aeb982012-05-09 08:55:40 +0000581//===----------------------------------------------------------------------===//
582// C API.
583//===----------------------------------------------------------------------===//
584
Rafael Espindola434e9562015-12-16 23:16:33 +0000585LLVMBool LLVMLinkModules2(LLVMModuleRef Dest, LLVMModuleRef Src) {
586 Module *D = unwrap(Dest);
587 std::unique_ptr<Module> M(unwrap(Src));
588 return Linker::linkModules(*D, std::move(M));
589}