blob: 7ff84db07020a72a5bfe4763854c5909f1de13e8 [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"
Rafael Espindolad12b4a32014-10-25 04:06:10 +000018#include "llvm/IR/DiagnosticPrinter.h"
Rafael Espindola9d2bfc42015-12-14 23:17:03 +000019#include "llvm/IR/LLVMContext.h"
Teresa Johnson488a8002016-02-10 18:11:31 +000020#include "llvm/Linker/Linker.h"
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +000021#include "llvm/Support/Error.h"
Teresa Johnson488a8002016-02-10 18:11:31 +000022#include "llvm/Transforms/Utils/FunctionImportUtils.h"
Reid Spencer361e5132004-11-12 20:37:43 +000023using namespace llvm;
24
Chris Lattnereee6f992008-06-16 21:00:18 +000025namespace {
Rafael Espindolac84f6082014-11-25 06:11:24 +000026
27/// This is an implementation class for the LinkModules function, which is the
28/// entrypoint for this file.
29class ModuleLinker {
Rafael Espindolacaabe222015-12-10 14:19:35 +000030 IRMover &Mover;
Rafael Espindola40358fb2016-02-16 18:50:12 +000031 std::unique_ptr<Module> SrcM;
Rafael Espindolac84f6082014-11-25 06:11:24 +000032
Rafael Espindola4b5ec262015-12-02 22:59:04 +000033 SetVector<GlobalValue *> ValuesToLink;
Rafael Espindolacaabe222015-12-10 14:19:35 +000034 StringSet<> Internalize;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000035
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +000036 /// For symbol clashes, prefer those from Src.
Artem Belevich020d4fb2015-09-01 17:55:55 +000037 unsigned Flags;
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +000038
Teresa Johnson4f04d852015-12-21 17:33:24 +000039 /// Functions to import from source module, all other functions are
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +000040 /// imported as declarations instead of definitions.
Mehdi Amini8d051852016-03-19 00:40:31 +000041 DenseSet<const GlobalValue *> *GlobalsToImport;
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +000042
Rafael Espindolacaabe222015-12-10 14:19:35 +000043 /// Used as the callback for lazy linking.
44 /// The mover has just hit GV and we have to decide if it, and other members
45 /// of the same comdat, should be linked. Every member to be linked is passed
46 /// to Add.
Benjamin Kramerc321e532016-06-08 19:09:22 +000047 void addLazyFor(GlobalValue &GV, const IRMover::ValueAdder &Add);
Rafael Espindolabaa3bf82015-12-01 15:19:48 +000048
Mehdi Aminibda3c972016-04-21 01:59:39 +000049 bool shouldLinkReferencedLinkOnce() {
50 return !(Flags & Linker::DontForceLinkLinkonceODR);
51 }
Artem Belevich020d4fb2015-09-01 17:55:55 +000052 bool shouldOverrideFromSrc() { return Flags & Linker::OverrideFromSrc; }
53 bool shouldLinkOnlyNeeded() { return Flags & Linker::LinkOnlyNeeded; }
54 bool shouldInternalizeLinkedSymbols() {
55 return Flags & Linker::InternalizeLinkedSymbols;
56 }
57
Rafael Espindolac84f6082014-11-25 06:11:24 +000058 bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
59 const GlobalValue &Src);
Rafael Espindolaed6dc372014-05-09 14:39:25 +000060
Rafael Espindolacaabe222015-12-10 14:19:35 +000061 /// Should we have mover and linker error diag info?
Rafael Espindolac84f6082014-11-25 06:11:24 +000062 bool emitError(const Twine &Message) {
Rafael Espindola40358fb2016-02-16 18:50:12 +000063 SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Error, Message));
Rafael Espindolac84f6082014-11-25 06:11:24 +000064 return true;
65 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +000066
Rafael Espindola0e309fe2015-12-01 19:50:54 +000067 bool getComdatLeader(Module &M, StringRef ComdatName,
Rafael Espindolac84f6082014-11-25 06:11:24 +000068 const GlobalVariable *&GVar);
69 bool computeResultingSelectionKind(StringRef ComdatName,
70 Comdat::SelectionKind Src,
71 Comdat::SelectionKind Dst,
72 Comdat::SelectionKind &Result,
73 bool &LinkFromSrc);
74 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
75 ComdatsChosen;
76 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
77 bool &LinkFromSrc);
Rafael Espindola1ee9fbd2016-03-24 00:06:03 +000078 // Keep track of the lazy linked global members of each comdat in source.
79 DenseMap<const Comdat *, std::vector<GlobalValue *>> LazyComdatMembers;
Rafael Espindola4160f5d2014-10-27 23:02:10 +000080
Rafael Espindolac84f6082014-11-25 06:11:24 +000081 /// Given a global in the source module, return the global in the
82 /// destination module that is being linked to, if any.
83 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
Rafael Espindolacaabe222015-12-10 14:19:35 +000084 Module &DstM = Mover.getModule();
Rafael Espindolac84f6082014-11-25 06:11:24 +000085 // If the source has no name it can't link. If it has local linkage,
86 // there is no name match-up going on.
Teresa Johnson4504c1b2016-01-08 15:00:00 +000087 if (!SrcGV->hasName() || GlobalValue::isLocalLinkage(SrcGV->getLinkage()))
Rafael Espindolac84f6082014-11-25 06:11:24 +000088 return nullptr;
Eli Bendersky7da92ed2014-02-20 22:19:24 +000089
Rafael Espindolac84f6082014-11-25 06:11:24 +000090 // Otherwise see if we have a match in the destination module's symtab.
Teresa Johnson4504c1b2016-01-08 15:00:00 +000091 GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName());
Rafael Espindolac84f6082014-11-25 06:11:24 +000092 if (!DGV)
93 return nullptr;
Rafael Espindolaed6dc372014-05-09 14:39:25 +000094
Rafael Espindolac84f6082014-11-25 06:11:24 +000095 // If we found a global with the same name in the dest module, but it has
96 // internal linkage, we are really not doing any linkage here.
97 if (DGV->hasLocalLinkage())
98 return nullptr;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +000099
Rafael Espindolac84f6082014-11-25 06:11:24 +0000100 // Otherwise, we do in fact link to the destination global.
101 return DGV;
102 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000103
Rafael Espindola370d5282016-03-22 21:35:47 +0000104 /// Drop GV if it is a member of a comdat that we are dropping.
105 /// This can happen with COFF's largest selection kind.
106 void dropReplacedComdat(GlobalValue &GV,
107 const DenseSet<const Comdat *> &ReplacedDstComdats);
108
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000109 bool linkIfNeeded(GlobalValue &GV);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000110
Teresa Johnson4504c1b2016-01-08 15:00:00 +0000111 /// Helper method to check if we are importing from the current source
112 /// module.
Mehdi Amini8d051852016-03-19 00:40:31 +0000113 bool isPerformingImport() const { return GlobalsToImport != nullptr; }
Teresa Johnson4504c1b2016-01-08 15:00:00 +0000114
115 /// If we are importing from the source module, checks if we should
116 /// import SGV as a definition, otherwise import as a declaration.
117 bool doImportAsDefinition(const GlobalValue *SGV);
118
119public:
Rafael Espindola40358fb2016-02-16 18:50:12 +0000120 ModuleLinker(IRMover &Mover, std::unique_ptr<Module> SrcM, unsigned Flags,
Teresa Johnsonb703c772016-03-29 18:24:19 +0000121 DenseSet<const GlobalValue *> *GlobalsToImport = nullptr)
Mehdi Amini8d051852016-03-19 00:40:31 +0000122 : Mover(Mover), SrcM(std::move(SrcM)), Flags(Flags),
Teresa Johnsonb703c772016-03-29 18:24:19 +0000123 GlobalsToImport(GlobalsToImport) {}
Teresa Johnson4504c1b2016-01-08 15:00:00 +0000124
125 bool run();
126};
Teresa Johnson4504c1b2016-01-08 15:00:00 +0000127}
128
129bool ModuleLinker::doImportAsDefinition(const GlobalValue *SGV) {
130 if (!isPerformingImport())
131 return false;
Mehdi Amini8d051852016-03-19 00:40:31 +0000132 return FunctionImportGlobalProcessing::doImportAsDefinition(SGV,
133 GlobalsToImport);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000134}
135
Rafael Espindolaeb5e0a72015-11-29 14:33:06 +0000136static GlobalValue::VisibilityTypes
137getMinVisibility(GlobalValue::VisibilityTypes A,
138 GlobalValue::VisibilityTypes B) {
139 if (A == GlobalValue::HiddenVisibility || B == GlobalValue::HiddenVisibility)
140 return GlobalValue::HiddenVisibility;
141 if (A == GlobalValue::ProtectedVisibility ||
142 B == GlobalValue::ProtectedVisibility)
143 return GlobalValue::ProtectedVisibility;
144 return GlobalValue::DefaultVisibility;
145}
146
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000147bool ModuleLinker::getComdatLeader(Module &M, StringRef ComdatName,
David Majnemerdad0a642014-06-27 18:19:56 +0000148 const GlobalVariable *&GVar) {
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000149 const GlobalValue *GVal = M.getNamedValue(ComdatName);
David Majnemerdad0a642014-06-27 18:19:56 +0000150 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
151 GVal = GA->getBaseObject();
152 if (!GVal)
153 // We cannot resolve the size of the aliasee yet.
154 return emitError("Linking COMDATs named '" + ComdatName +
155 "': COMDAT key involves incomputable alias size.");
156 }
157
158 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
159 if (!GVar)
160 return emitError(
161 "Linking COMDATs named '" + ComdatName +
162 "': GlobalVariable required for data dependent selection!");
163
164 return false;
165}
166
167bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
168 Comdat::SelectionKind Src,
169 Comdat::SelectionKind Dst,
170 Comdat::SelectionKind &Result,
171 bool &LinkFromSrc) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000172 Module &DstM = Mover.getModule();
David Majnemerdad0a642014-06-27 18:19:56 +0000173 // The ability to mix Comdat::SelectionKind::Any with
174 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
175 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
176 Dst == Comdat::SelectionKind::Largest;
177 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
178 Src == Comdat::SelectionKind::Largest;
179 if (DstAnyOrLargest && SrcAnyOrLargest) {
180 if (Dst == Comdat::SelectionKind::Largest ||
181 Src == Comdat::SelectionKind::Largest)
182 Result = Comdat::SelectionKind::Largest;
183 else
184 Result = Comdat::SelectionKind::Any;
185 } else if (Src == Dst) {
186 Result = Dst;
187 } else {
188 return emitError("Linking COMDATs named '" + ComdatName +
189 "': invalid selection kinds!");
190 }
191
192 switch (Result) {
193 case Comdat::SelectionKind::Any:
194 // Go with Dst.
195 LinkFromSrc = false;
196 break;
197 case Comdat::SelectionKind::NoDuplicates:
198 return emitError("Linking COMDATs named '" + ComdatName +
199 "': noduplicates has been violated!");
200 case Comdat::SelectionKind::ExactMatch:
201 case Comdat::SelectionKind::Largest:
202 case Comdat::SelectionKind::SameSize: {
203 const GlobalVariable *DstGV;
204 const GlobalVariable *SrcGV;
205 if (getComdatLeader(DstM, ComdatName, DstGV) ||
Rafael Espindola40358fb2016-02-16 18:50:12 +0000206 getComdatLeader(*SrcM, ComdatName, SrcGV))
David Majnemerdad0a642014-06-27 18:19:56 +0000207 return true;
208
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000209 const DataLayout &DstDL = DstM.getDataLayout();
Rafael Espindola40358fb2016-02-16 18:50:12 +0000210 const DataLayout &SrcDL = SrcM->getDataLayout();
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000211 uint64_t DstSize = DstDL.getTypeAllocSize(DstGV->getValueType());
212 uint64_t SrcSize = SrcDL.getTypeAllocSize(SrcGV->getValueType());
David Majnemerdad0a642014-06-27 18:19:56 +0000213 if (Result == Comdat::SelectionKind::ExactMatch) {
214 if (SrcGV->getInitializer() != DstGV->getInitializer())
215 return emitError("Linking COMDATs named '" + ComdatName +
216 "': ExactMatch violated!");
217 LinkFromSrc = false;
218 } else if (Result == Comdat::SelectionKind::Largest) {
219 LinkFromSrc = SrcSize > DstSize;
220 } else if (Result == Comdat::SelectionKind::SameSize) {
221 if (SrcSize != DstSize)
222 return emitError("Linking COMDATs named '" + ComdatName +
223 "': SameSize violated!");
224 LinkFromSrc = false;
225 } else {
226 llvm_unreachable("unknown selection kind");
227 }
228 break;
229 }
230 }
231
232 return false;
233}
234
235bool ModuleLinker::getComdatResult(const Comdat *SrcC,
236 Comdat::SelectionKind &Result,
237 bool &LinkFromSrc) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000238 Module &DstM = Mover.getModule();
Rafael Espindolab16196a2014-08-11 17:07:34 +0000239 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
David Majnemerdad0a642014-06-27 18:19:56 +0000240 StringRef ComdatName = SrcC->getName();
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000241 Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
David Majnemerdad0a642014-06-27 18:19:56 +0000242 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000243
Rafael Espindolab16196a2014-08-11 17:07:34 +0000244 if (DstCI == ComdatSymTab.end()) {
245 // Use the comdat if it is only available in one of the modules.
246 LinkFromSrc = true;
247 Result = SSK;
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000248 return false;
Rafael Espindolab16196a2014-08-11 17:07:34 +0000249 }
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000250
251 const Comdat *DstC = &DstCI->second;
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000252 Comdat::SelectionKind DSK = DstC->getSelectionKind();
253 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
254 LinkFromSrc);
David Majnemerdad0a642014-06-27 18:19:56 +0000255}
James Molloyf6f121e2013-05-28 15:17:05 +0000256
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000257bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
258 const GlobalValue &Dest,
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000259 const GlobalValue &Src) {
Teresa Johnsone5a61912015-12-17 17:14:09 +0000260
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +0000261 // Should we unconditionally use the Src?
Artem Belevich020d4fb2015-09-01 17:55:55 +0000262 if (shouldOverrideFromSrc()) {
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +0000263 LinkFromSrc = true;
264 return false;
265 }
266
Rafael Espindola778fcc72014-11-02 13:28:57 +0000267 // We always have to add Src if it has appending linkage.
268 if (Src.hasAppendingLinkage()) {
Teresa Johnson1e20a652015-12-03 18:20:05 +0000269 // Should have prevented importing for appending linkage in linkIfNeeded.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000270 assert(!isPerformingImport());
Rafael Espindola778fcc72014-11-02 13:28:57 +0000271 LinkFromSrc = true;
272 return false;
273 }
274
Mehdi Aminid826bbb2016-04-20 17:47:42 +0000275 if (isPerformingImport()) {
276 // LinkFromSrc iff this is a global requested for importing.
277 LinkFromSrc = GlobalsToImport->count(&Src);
278 return false;
279 }
280
Rafael Espindolad4bcefc2014-10-24 18:13:04 +0000281 bool SrcIsDeclaration = Src.isDeclarationForLinker();
282 bool DestIsDeclaration = Dest.isDeclarationForLinker();
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000283
284 if (SrcIsDeclaration) {
285 // If Src is external or if both Src & Dest are external.. Just link the
286 // external globals, we aren't adding anything.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000287 if (Src.hasDLLImportStorageClass()) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000288 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000289 LinkFromSrc = DestIsDeclaration;
290 return false;
291 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000292 // If the Dest is weak, use the source linkage.
Rafael Espindolaed11bd22015-12-09 22:44:00 +0000293 if (Dest.hasExternalWeakLinkage()) {
294 LinkFromSrc = true;
295 return false;
296 }
297 // Link an available_externally over a declaration.
298 LinkFromSrc = !Src.isDeclaration() && Dest.isDeclaration();
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000299 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000300 }
301
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000302 if (DestIsDeclaration) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000303 // If Dest is external but Src is not:
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000304 LinkFromSrc = true;
305 return false;
306 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000307
Rafael Espindola09106052014-09-09 15:59:12 +0000308 if (Src.hasCommonLinkage()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000309 if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
310 LinkFromSrc = true;
Rafael Espindola09106052014-09-09 15:59:12 +0000311 return false;
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000312 }
313
314 if (!Dest.hasCommonLinkage()) {
315 LinkFromSrc = false;
316 return false;
317 }
Rafael Espindola09106052014-09-09 15:59:12 +0000318
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000319 const DataLayout &DL = Dest.getParent()->getDataLayout();
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000320 uint64_t DestSize = DL.getTypeAllocSize(Dest.getValueType());
321 uint64_t SrcSize = DL.getTypeAllocSize(Src.getValueType());
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000322 LinkFromSrc = SrcSize > DestSize;
323 return false;
Rafael Espindola09106052014-09-09 15:59:12 +0000324 }
325
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000326 if (Src.isWeakForLinker()) {
327 assert(!Dest.hasExternalWeakLinkage());
328 assert(!Dest.hasAvailableExternallyLinkage());
Rafael Espindola09106052014-09-09 15:59:12 +0000329
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000330 if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
331 LinkFromSrc = true;
332 return false;
333 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000334
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000335 LinkFromSrc = false;
Rafael Espindola09106052014-09-09 15:59:12 +0000336 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000337 }
338
339 if (Dest.isWeakForLinker()) {
340 assert(Src.hasExternalLinkage());
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000341 LinkFromSrc = true;
342 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000343 }
344
345 assert(!Src.hasExternalWeakLinkage());
346 assert(!Dest.hasExternalWeakLinkage());
347 assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
348 "Unexpected linkage type!");
349 return emitError("Linking globals named '" + Src.getName() +
350 "': symbol multiply defined!");
351}
352
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000353bool ModuleLinker::linkIfNeeded(GlobalValue &GV) {
354 GlobalValue *DGV = getLinkedToGlobal(&GV);
355
356 if (shouldLinkOnlyNeeded() && !(DGV && DGV->isDeclaration()))
357 return false;
358
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000359 if (DGV && !GV.hasLocalLinkage() && !GV.hasAppendingLinkage()) {
360 auto *DGVar = dyn_cast<GlobalVariable>(DGV);
361 auto *SGVar = dyn_cast<GlobalVariable>(&GV);
362 if (DGVar && SGVar) {
363 if (DGVar->isDeclaration() && SGVar->isDeclaration() &&
364 (!DGVar->isConstant() || !SGVar->isConstant())) {
365 DGVar->setConstant(false);
366 SGVar->setConstant(false);
367 }
368 if (DGVar->hasCommonLinkage() && SGVar->hasCommonLinkage()) {
369 unsigned Align = std::max(DGVar->getAlignment(), SGVar->getAlignment());
370 SGVar->setAlignment(Align);
371 DGVar->setAlignment(Align);
372 }
373 }
374
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000375 GlobalValue::VisibilityTypes Visibility =
376 getMinVisibility(DGV->getVisibility(), GV.getVisibility());
377 DGV->setVisibility(Visibility);
378 GV.setVisibility(Visibility);
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000379
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000380 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::getMinUnnamedAddr(
381 DGV->getUnnamedAddr(), GV.getUnnamedAddr());
382 DGV->setUnnamedAddr(UnnamedAddr);
383 GV.setUnnamedAddr(UnnamedAddr);
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000384 }
385
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000386 // Don't want to append to global_ctors list, for example, when we
387 // are importing for ThinLTO, otherwise the global ctors and dtors
388 // get executed multiple times for local variables (the latter causing
389 // double frees).
390 if (GV.hasAppendingLinkage() && isPerformingImport())
391 return false;
392
Mehdi Amini8d051852016-03-19 00:40:31 +0000393 if (isPerformingImport()) {
394 if (!doImportAsDefinition(&GV))
395 return false;
396 } else if (!DGV && !shouldOverrideFromSrc() &&
397 (GV.hasLocalLinkage() || GV.hasLinkOnceLinkage() ||
398 GV.hasAvailableExternallyLinkage()))
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000399 return false;
400
Rafael Espindolabd03c502015-12-07 16:31:41 +0000401 if (GV.isDeclaration())
402 return false;
403
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000404 if (const Comdat *SC = GV.getComdat()) {
405 bool LinkFromSrc;
406 Comdat::SelectionKind SK;
407 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
Rafael Espindolaf2e71242016-03-23 21:16:33 +0000408 if (!LinkFromSrc)
409 return false;
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000410 }
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000411
412 bool LinkFromSrc = true;
413 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, GV))
414 return true;
415 if (LinkFromSrc)
416 ValuesToLink.insert(&GV);
417 return false;
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000418}
419
Benjamin Kramerc321e532016-06-08 19:09:22 +0000420void ModuleLinker::addLazyFor(GlobalValue &GV, const IRMover::ValueAdder &Add) {
Mehdi Aminibda3c972016-04-21 01:59:39 +0000421 if (!shouldLinkReferencedLinkOnce())
422 // For ThinLTO we don't import more than what was required.
423 // The client has to guarantee that the linkonce will be availabe at link
424 // time (by promoting it to weak for instance).
425 return;
426
Rafael Espindolacaabe222015-12-10 14:19:35 +0000427 // Add these to the internalize list
Peter Collingbournec387e702017-02-02 05:12:15 +0000428 if (!GV.hasLinkOnceLinkage() && !GV.hasAvailableExternallyLinkage() &&
429 !shouldLinkOnlyNeeded())
Rafael Espindolacaabe222015-12-10 14:19:35 +0000430 return;
431
432 if (shouldInternalizeLinkedSymbols())
433 Internalize.insert(GV.getName());
434 Add(GV);
435
436 const Comdat *SC = GV.getComdat();
437 if (!SC)
438 return;
Rafael Espindola1ee9fbd2016-03-24 00:06:03 +0000439 for (GlobalValue *GV2 : LazyComdatMembers[SC]) {
Rafael Espindolae1c42ac2016-03-24 15:23:01 +0000440 GlobalValue *DGV = getLinkedToGlobal(GV2);
441 bool LinkFromSrc = true;
442 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, *GV2))
443 return;
444 if (!LinkFromSrc)
445 continue;
Rafael Espindola1ee9fbd2016-03-24 00:06:03 +0000446 if (shouldInternalizeLinkedSymbols())
Rafael Espindolacaabe222015-12-10 14:19:35 +0000447 Internalize.insert(GV2->getName());
448 Add(*GV2);
449 }
450}
451
Rafael Espindola370d5282016-03-22 21:35:47 +0000452void ModuleLinker::dropReplacedComdat(
453 GlobalValue &GV, const DenseSet<const Comdat *> &ReplacedDstComdats) {
454 Comdat *C = GV.getComdat();
455 if (!C)
456 return;
457 if (!ReplacedDstComdats.count(C))
458 return;
459 if (GV.use_empty()) {
460 GV.eraseFromParent();
461 return;
462 }
463
464 if (auto *F = dyn_cast<Function>(&GV)) {
465 F->deleteBody();
466 } else if (auto *Var = dyn_cast<GlobalVariable>(&GV)) {
467 Var->setInitializer(nullptr);
468 } else {
469 auto &Alias = cast<GlobalAlias>(GV);
470 Module &M = *Alias.getParent();
471 PointerType &Ty = *cast<PointerType>(Alias.getType());
472 GlobalValue *Declaration;
473 if (auto *FTy = dyn_cast<FunctionType>(Alias.getValueType())) {
474 Declaration = Function::Create(FTy, GlobalValue::ExternalLinkage, "", &M);
475 } else {
476 Declaration =
477 new GlobalVariable(M, Ty.getElementType(), /*isConstant*/ false,
478 GlobalValue::ExternalLinkage,
479 /*Initializer*/ nullptr);
480 }
481 Declaration->takeName(&Alias);
482 Alias.replaceAllUsesWith(Declaration);
483 Alias.eraseFromParent();
484 }
485}
486
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000487bool ModuleLinker::run() {
Rafael Espindola370d5282016-03-22 21:35:47 +0000488 Module &DstM = Mover.getModule();
489 DenseSet<const Comdat *> ReplacedDstComdats;
490
Rafael Espindola40358fb2016-02-16 18:50:12 +0000491 for (const auto &SMEC : SrcM->getComdatSymbolTable()) {
David Majnemerdad0a642014-06-27 18:19:56 +0000492 const Comdat &C = SMEC.getValue();
493 if (ComdatsChosen.count(&C))
494 continue;
495 Comdat::SelectionKind SK;
496 bool LinkFromSrc;
497 if (getComdatResult(&C, SK, LinkFromSrc))
498 return true;
499 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
Rafael Espindola370d5282016-03-22 21:35:47 +0000500
501 if (!LinkFromSrc)
502 continue;
503
504 Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
505 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(C.getName());
506 if (DstCI == ComdatSymTab.end())
507 continue;
508
509 // The source comdat is replacing the dest one.
510 const Comdat *DstC = &DstCI->second;
511 ReplacedDstComdats.insert(DstC);
512 }
513
514 // Alias have to go first, since we are not able to find their comdats
515 // otherwise.
516 for (auto I = DstM.alias_begin(), E = DstM.alias_end(); I != E;) {
517 GlobalAlias &GV = *I++;
518 dropReplacedComdat(GV, ReplacedDstComdats);
519 }
520
521 for (auto I = DstM.global_begin(), E = DstM.global_end(); I != E;) {
522 GlobalVariable &GV = *I++;
523 dropReplacedComdat(GV, ReplacedDstComdats);
524 }
525
526 for (auto I = DstM.begin(), E = DstM.end(); I != E;) {
527 Function &GV = *I++;
528 dropReplacedComdat(GV, ReplacedDstComdats);
David Majnemerdad0a642014-06-27 18:19:56 +0000529 }
530
Rafael Espindola40358fb2016-02-16 18:50:12 +0000531 for (GlobalVariable &GV : SrcM->globals())
Rafael Espindola1ee9fbd2016-03-24 00:06:03 +0000532 if (GV.hasLinkOnceLinkage())
533 if (const Comdat *SC = GV.getComdat())
534 LazyComdatMembers[SC].push_back(&GV);
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000535
Rafael Espindola40358fb2016-02-16 18:50:12 +0000536 for (Function &SF : *SrcM)
Rafael Espindola1ee9fbd2016-03-24 00:06:03 +0000537 if (SF.hasLinkOnceLinkage())
538 if (const Comdat *SC = SF.getComdat())
539 LazyComdatMembers[SC].push_back(&SF);
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000540
Rafael Espindola40358fb2016-02-16 18:50:12 +0000541 for (GlobalAlias &GA : SrcM->aliases())
Rafael Espindola1ee9fbd2016-03-24 00:06:03 +0000542 if (GA.hasLinkOnceLinkage())
543 if (const Comdat *SC = GA.getComdat())
544 LazyComdatMembers[SC].push_back(&GA);
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000545
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000546 // Insert all of the globals in src into the DstM module... without linking
547 // initializers (which could refer to functions not yet mapped over).
Rafael Espindola40358fb2016-02-16 18:50:12 +0000548 for (GlobalVariable &GV : SrcM->globals())
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000549 if (linkIfNeeded(GV))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000550 return true;
551
Rafael Espindola40358fb2016-02-16 18:50:12 +0000552 for (Function &SF : *SrcM)
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000553 if (linkIfNeeded(SF))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000554 return true;
555
Rafael Espindola40358fb2016-02-16 18:50:12 +0000556 for (GlobalAlias &GA : SrcM->aliases())
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000557 if (linkIfNeeded(GA))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000558 return true;
559
Rafael Espindolacaabe222015-12-10 14:19:35 +0000560 for (unsigned I = 0; I < ValuesToLink.size(); ++I) {
561 GlobalValue *GV = ValuesToLink[I];
562 const Comdat *SC = GV->getComdat();
563 if (!SC)
564 continue;
Rafael Espindola42e03232016-03-24 14:58:44 +0000565 for (GlobalValue *GV2 : LazyComdatMembers[SC]) {
566 GlobalValue *DGV = getLinkedToGlobal(GV2);
567 bool LinkFromSrc = true;
568 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, *GV2))
569 return true;
570 if (LinkFromSrc)
571 ValuesToLink.insert(GV2);
572 }
Rafael Espindolabeadd562014-12-08 18:05:48 +0000573 }
574
Rafael Espindolacaabe222015-12-10 14:19:35 +0000575 if (shouldInternalizeLinkedSymbols()) {
576 for (GlobalValue *GV : ValuesToLink)
577 Internalize.insert(GV->getName());
578 }
Teresa Johnson10632932015-11-06 17:50:53 +0000579
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000580 // FIXME: Propagate Errors through to the caller instead of emitting
581 // diagnostics.
582 bool HasErrors = false;
583 if (Error E = Mover.move(std::move(SrcM), ValuesToLink.getArrayRef(),
584 [this](GlobalValue &GV, IRMover::ValueAdder Add) {
585 addLazyFor(GV, Add);
Teresa Johnson4b9b3792016-10-12 18:39:29 +0000586 },
Teresa Johnson040cc162016-12-12 16:09:30 +0000587 /* LinkModuleInlineAsm */ !isPerformingImport(),
588 /* IsPerformingImport */ isPerformingImport())) {
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000589 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
590 DstM.getContext().diagnose(LinkDiagnosticInfo(DS_Error, EIB.message()));
591 HasErrors = true;
592 });
593 }
594 if (HasErrors)
Teresa Johnson189b2522015-11-06 17:50:48 +0000595 return true;
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000596
Rafael Espindolacaabe222015-12-10 14:19:35 +0000597 for (auto &P : Internalize) {
598 GlobalValue *GV = DstM.getNamedValue(P.first());
599 GV->setLinkage(GlobalValue::InternalLinkage);
600 }
Teresa Johnson189b2522015-11-06 17:50:48 +0000601
Anton Korobeynikov26098882008-03-05 23:21:39 +0000602 return false;
603}
Reid Spencer361e5132004-11-12 20:37:43 +0000604
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000605Linker::Linker(Module &M) : Mover(M) {}
Rafael Espindola3df61b72013-05-04 03:48:37 +0000606
Rafael Espindola434e9562015-12-16 23:16:33 +0000607bool Linker::linkInModule(std::unique_ptr<Module> Src, unsigned Flags,
Teresa Johnsonb703c772016-03-29 18:24:19 +0000608 DenseSet<const GlobalValue *> *GlobalsToImport) {
609 ModuleLinker ModLinker(Mover, std::move(Src), Flags, GlobalsToImport);
Teresa Johnsonbef54362015-12-18 19:28:59 +0000610 return ModLinker.run();
Rafael Espindola434e9562015-12-16 23:16:33 +0000611}
612
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000613//===----------------------------------------------------------------------===//
614// LinkModules entrypoint.
615//===----------------------------------------------------------------------===//
616
Rafael Espindola18c89412014-10-27 02:35:46 +0000617/// This function links two modules together, with the resulting Dest module
618/// modified to be the composite of the two input modules. If an error occurs,
619/// true is returned and ErrorMsg (if not null) is set to indicate the problem.
620/// Upon failure, the Dest module could be in a modified state, and shouldn't be
621/// relied on to be consistent.
Rafael Espindola434e9562015-12-16 23:16:33 +0000622bool Linker::linkModules(Module &Dest, std::unique_ptr<Module> Src,
623 unsigned Flags) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000624 Linker L(Dest);
Rafael Espindola434e9562015-12-16 23:16:33 +0000625 return L.linkInModule(std::move(Src), Flags);
Rafael Espindola4160f5d2014-10-27 23:02:10 +0000626}
627
Bill Wendlinga3aeb982012-05-09 08:55:40 +0000628//===----------------------------------------------------------------------===//
629// C API.
630//===----------------------------------------------------------------------===//
631
Rafael Espindola434e9562015-12-16 23:16:33 +0000632LLVMBool LLVMLinkModules2(LLVMModuleRef Dest, LLVMModuleRef Src) {
633 Module *D = unwrap(Dest);
634 std::unique_ptr<Module> M(unwrap(Src));
635 return Linker::linkModules(*D, std::move(M));
636}