blob: 556251092a2bb3e9953183aef628e3a67233bcf9 [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
Chandler Carruth6cc07df2014-03-06 03:42:23 +000014#include "llvm/Linker/Linker.h"
Rafael Espindolacaabe222015-12-10 14:19:35 +000015#include "LinkDiagnosticInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm-c/Linker.h"
Bill Wendling66f02412012-02-11 11:38:06 +000017#include "llvm/ADT/SetVector.h"
Rafael Espindolacaabe222015-12-10 14:19:35 +000018#include "llvm/ADT/StringSet.h"
Rafael Espindolad12b4a32014-10-25 04:06:10 +000019#include "llvm/IR/DiagnosticPrinter.h"
Rafael Espindola9d2bfc42015-12-14 23:17:03 +000020#include "llvm/IR/LLVMContext.h"
Reid Spencer361e5132004-11-12 20:37:43 +000021using namespace llvm;
22
Chris Lattnereee6f992008-06-16 21:00:18 +000023namespace {
Rafael Espindolac84f6082014-11-25 06:11:24 +000024
25/// This is an implementation class for the LinkModules function, which is the
26/// entrypoint for this file.
27class ModuleLinker {
Rafael Espindolacaabe222015-12-10 14:19:35 +000028 IRMover &Mover;
Rafael Espindola0e309fe2015-12-01 19:50:54 +000029 Module &SrcM;
Rafael Espindolac84f6082014-11-25 06:11:24 +000030
Rafael Espindola4b5ec262015-12-02 22:59:04 +000031 SetVector<GlobalValue *> ValuesToLink;
Rafael Espindolacaabe222015-12-10 14:19:35 +000032 StringSet<> Internalize;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000033
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +000034 /// For symbol clashes, prefer those from Src.
Artem Belevich020d4fb2015-09-01 17:55:55 +000035 unsigned Flags;
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +000036
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +000037 /// Function index passed into ModuleLinker for using in function
38 /// importing/exporting handling.
Mehdi Amini8220e8a2015-11-23 01:59:16 +000039 const FunctionInfoIndex *ImportIndex;
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +000040
41 /// Function to import from source module, all other functions are
42 /// imported as declarations instead of definitions.
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +000043 DenseSet<const GlobalValue *> *ImportFunction;
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +000044
45 /// Set to true if the given FunctionInfoIndex contains any functions
46 /// from this source module, in which case we must conservatively assume
47 /// that any of its functions may be imported into another module
48 /// as part of a different backend compilation process.
Rafael Espindolaaf714762015-12-01 23:06:26 +000049 bool HasExportedFunctions = false;
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +000050
Teresa Johnsone5a61912015-12-17 17:14:09 +000051 /// Association between metadata value id and temporary metadata that
52 /// remains unmapped after function importing. Saved during function
53 /// importing and consumed during the metadata linking postpass.
54 DenseMap<unsigned, MDNode *> *ValIDToTempMDMap;
55
Rafael Espindolacaabe222015-12-10 14:19:35 +000056 /// Used as the callback for lazy linking.
57 /// The mover has just hit GV and we have to decide if it, and other members
58 /// of the same comdat, should be linked. Every member to be linked is passed
59 /// to Add.
60 void addLazyFor(GlobalValue &GV, IRMover::ValueAdder Add);
Rafael Espindolabaa3bf82015-12-01 15:19:48 +000061
Artem Belevich020d4fb2015-09-01 17:55:55 +000062 bool shouldOverrideFromSrc() { return Flags & Linker::OverrideFromSrc; }
63 bool shouldLinkOnlyNeeded() { return Flags & Linker::LinkOnlyNeeded; }
64 bool shouldInternalizeLinkedSymbols() {
65 return Flags & Linker::InternalizeLinkedSymbols;
66 }
67
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +000068 /// Check if we should promote the given local value to global scope.
69 bool doPromoteLocalToGlobal(const GlobalValue *SGV);
70
Rafael Espindolac84f6082014-11-25 06:11:24 +000071 bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
72 const GlobalValue &Src);
Rafael Espindolaed6dc372014-05-09 14:39:25 +000073
Rafael Espindolacaabe222015-12-10 14:19:35 +000074 /// Should we have mover and linker error diag info?
Rafael Espindolac84f6082014-11-25 06:11:24 +000075 bool emitError(const Twine &Message) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +000076 SrcM.getContext().diagnose(LinkDiagnosticInfo(DS_Error, Message));
Rafael Espindolac84f6082014-11-25 06:11:24 +000077 return true;
78 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +000079
Rafael Espindola0e309fe2015-12-01 19:50:54 +000080 bool getComdatLeader(Module &M, StringRef ComdatName,
Rafael Espindolac84f6082014-11-25 06:11:24 +000081 const GlobalVariable *&GVar);
82 bool computeResultingSelectionKind(StringRef ComdatName,
83 Comdat::SelectionKind Src,
84 Comdat::SelectionKind Dst,
85 Comdat::SelectionKind &Result,
86 bool &LinkFromSrc);
87 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
88 ComdatsChosen;
89 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
90 bool &LinkFromSrc);
Teresa Johnson2d5fb8c2015-11-10 21:09:06 +000091 // Keep track of the global value members of each comdat in source.
92 DenseMap<const Comdat *, std::vector<GlobalValue *>> ComdatMembers;
Rafael Espindola4160f5d2014-10-27 23:02:10 +000093
Rafael Espindolac84f6082014-11-25 06:11:24 +000094 /// Given a global in the source module, return the global in the
95 /// destination module that is being linked to, if any.
96 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
Rafael Espindolacaabe222015-12-10 14:19:35 +000097 Module &DstM = Mover.getModule();
Rafael Espindolac84f6082014-11-25 06:11:24 +000098 // If the source has no name it can't link. If it has local linkage,
99 // there is no name match-up going on.
Teresa Johnsonb098f0c2015-11-24 19:46:58 +0000100 if (!SrcGV->hasName() || GlobalValue::isLocalLinkage(getLinkage(SrcGV)))
Rafael Espindolac84f6082014-11-25 06:11:24 +0000101 return nullptr;
Eli Bendersky7da92ed2014-02-20 22:19:24 +0000102
Rafael Espindolac84f6082014-11-25 06:11:24 +0000103 // Otherwise see if we have a match in the destination module's symtab.
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000104 GlobalValue *DGV = DstM.getNamedValue(getName(SrcGV));
Rafael Espindolac84f6082014-11-25 06:11:24 +0000105 if (!DGV)
106 return nullptr;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000107
Rafael Espindolac84f6082014-11-25 06:11:24 +0000108 // If we found a global with the same name in the dest module, but it has
109 // internal linkage, we are really not doing any linkage here.
110 if (DGV->hasLocalLinkage())
111 return nullptr;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000112
Rafael Espindolac84f6082014-11-25 06:11:24 +0000113 // Otherwise, we do in fact link to the destination global.
114 return DGV;
115 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000116
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000117 bool linkIfNeeded(GlobalValue &GV);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000118
119 /// Helper methods to check if we are importing from or potentially
120 /// exporting from the current source module.
Teresa Johnson4a9bf582015-12-17 16:34:53 +0000121 bool isPerformingImport() const { return ImportFunction != nullptr; }
122 bool isModuleExporting() const { return HasExportedFunctions; }
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000123
124 /// If we are importing from the source module, checks if we should
125 /// import SGV as a definition, otherwise import as a declaration.
126 bool doImportAsDefinition(const GlobalValue *SGV);
127
128 /// Get the name for SGV that should be used in the linked destination
129 /// module. Specifically, this handles the case where we need to rename
130 /// a local that is being promoted to global scope.
131 std::string getName(const GlobalValue *SGV);
132
Rafael Espindolacaabe222015-12-10 14:19:35 +0000133 /// Process globals so that they can be used in ThinLTO. This includes
134 /// promoting local variables so that they can be reference externally by
135 /// thin lto imported globals and converting strong external globals to
136 /// available_externally.
137 void processGlobalsForThinLTO();
138 void processGlobalForThinLTO(GlobalValue &GV);
139
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000140 /// Get the new linkage for SGV that should be used in the linked destination
141 /// module. Specifically, for ThinLTO importing or exporting it may need
142 /// to be adjusted.
143 GlobalValue::LinkageTypes getLinkage(const GlobalValue *SGV);
144
145 /// Copies the necessary global value attributes and name from the source
146 /// to the newly cloned global value.
147 void copyGVAttributes(GlobalValue *NewGV, const GlobalValue *SrcGV);
148
149 /// Updates the visibility for the new global cloned from the source
150 /// and, if applicable, linked with an existing destination global.
151 /// Handles visibility change required for promoted locals.
152 void setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
153 const GlobalValue *DGV = nullptr);
154
Rafael Espindolad57f9f02015-12-08 14:54:49 +0000155public:
Rafael Espindolacaabe222015-12-10 14:19:35 +0000156 ModuleLinker(IRMover &Mover, Module &SrcM, unsigned Flags,
Rafael Espindolad57f9f02015-12-08 14:54:49 +0000157 const FunctionInfoIndex *Index = nullptr,
Teresa Johnsone5a61912015-12-17 17:14:09 +0000158 DenseSet<const GlobalValue *> *FunctionsToImport = nullptr,
159 DenseMap<unsigned, MDNode *> *ValIDToTempMDMap = nullptr)
Rafael Espindolacaabe222015-12-10 14:19:35 +0000160 : Mover(Mover), SrcM(SrcM), Flags(Flags), ImportIndex(Index),
Teresa Johnsone5a61912015-12-17 17:14:09 +0000161 ImportFunction(FunctionsToImport), ValIDToTempMDMap(ValIDToTempMDMap) {
Rafael Espindolad57f9f02015-12-08 14:54:49 +0000162 assert((ImportIndex || !ImportFunction) &&
163 "Expect a FunctionInfoIndex when importing");
164 // If we have a FunctionInfoIndex but no function to import,
165 // then this is the primary module being compiled in a ThinLTO
166 // backend compilation, and we need to see if it has functions that
167 // may be exported to another backend compilation.
168 if (ImportIndex && !ImportFunction)
169 HasExportedFunctions = ImportIndex->hasExportedFunctions(SrcM);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000170 assert((ValIDToTempMDMap || !ImportFunction) &&
171 "Function importing must provide a ValIDToTempMDMap");
Rafael Espindolad57f9f02015-12-08 14:54:49 +0000172 }
173
174 bool run();
Rafael Espindolac84f6082014-11-25 06:11:24 +0000175};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000176}
Bill Wendlingd48b7782012-02-28 04:01:21 +0000177
Rafael Espindola18c89412014-10-27 02:35:46 +0000178/// The LLVM SymbolTable class autorenames globals that conflict in the symbol
179/// table. This is good for all clients except for us. Go through the trouble
180/// to force this back.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000181static void forceRenaming(GlobalValue *GV, StringRef Name) {
182 // If the global doesn't force its name or if it already has the right name,
183 // there is nothing for us to do.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000184 // Note that any required local to global promotion should already be done,
185 // so promoted locals will not skip this handling as their linkage is no
186 // longer local.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000187 if (GV->hasLocalLinkage() || GV->getName() == Name)
188 return;
189
190 Module *M = GV->getParent();
Reid Spencer361e5132004-11-12 20:37:43 +0000191
192 // If there is a conflict, rename the conflict.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000193 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
Chris Lattner2a8d2e02007-02-11 00:39:38 +0000194 GV->takeName(ConflictGV);
Rafael Espindolae3a933a2015-12-01 20:11:43 +0000195 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000196 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
Chris Lattner2a8d2e02007-02-11 00:39:38 +0000197 } else {
Rafael Espindolae3a933a2015-12-01 20:11:43 +0000198 GV->setName(Name); // Force the name back
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000199 }
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000200}
Reid Spencer90246aa2007-02-04 04:29:21 +0000201
Rafael Espindola18c89412014-10-27 02:35:46 +0000202/// copy additional attributes (those not needed to construct a GlobalValue)
203/// from the SrcGV to the DestGV.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000204void ModuleLinker::copyGVAttributes(GlobalValue *NewGV,
205 const GlobalValue *SrcGV) {
Rafael Espindola769efe62015-12-02 20:03:17 +0000206 NewGV->copyAttributesFrom(SrcGV);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000207 forceRenaming(NewGV, getName(SrcGV));
Reid Spencer361e5132004-11-12 20:37:43 +0000208}
209
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000210bool ModuleLinker::doImportAsDefinition(const GlobalValue *SGV) {
211 if (!isPerformingImport())
212 return false;
Teresa Johnson3cd81612015-11-10 18:20:11 +0000213 auto *GA = dyn_cast<GlobalAlias>(SGV);
214 if (GA) {
215 if (GA->hasWeakAnyLinkage())
216 return false;
Rafael Espindola89345772015-11-26 19:22:59 +0000217 const GlobalObject *GO = GA->getBaseObject();
218 if (!GO->hasLinkOnceODRLinkage())
219 return false;
220 return doImportAsDefinition(GO);
Teresa Johnson3cd81612015-11-10 18:20:11 +0000221 }
Teresa Johnsondfbebc32015-11-10 18:26:31 +0000222 // Always import GlobalVariable definitions, except for the special
223 // case of WeakAny which are imported as ExternalWeak declarations
224 // (see comments in ModuleLinker::getLinkage). The linkage changes
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000225 // described in ModuleLinker::getLinkage ensure the correct behavior (e.g.
226 // global variables with external linkage are transformed to
Teresa Johnson3cd81612015-11-10 18:20:11 +0000227 // available_externally definitions, which are ultimately turned into
228 // declarations after the EliminateAvailableExternally pass).
Craig Topper66059c92015-11-18 07:07:59 +0000229 if (isa<GlobalVariable>(SGV) && !SGV->isDeclaration() &&
Teresa Johnson3cd81612015-11-10 18:20:11 +0000230 !SGV->hasWeakAnyLinkage())
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000231 return true;
232 // Only import the function requested for importing.
233 auto *SF = dyn_cast<Function>(SGV);
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000234 if (SF && ImportFunction->count(SF))
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000235 return true;
236 // Otherwise no.
237 return false;
238}
239
240bool ModuleLinker::doPromoteLocalToGlobal(const GlobalValue *SGV) {
241 assert(SGV->hasLocalLinkage());
242 // Both the imported references and the original local variable must
243 // be promoted.
244 if (!isPerformingImport() && !isModuleExporting())
245 return false;
246
247 // Local const variables never need to be promoted unless they are address
248 // taken. The imported uses can simply use the clone created in this module.
249 // For now we are conservative in determining which variables are not
250 // address taken by checking the unnamed addr flag. To be more aggressive,
251 // the address taken information must be checked earlier during parsing
252 // of the module and recorded in the function index for use when importing
253 // from that module.
254 auto *GVar = dyn_cast<GlobalVariable>(SGV);
255 if (GVar && GVar->isConstant() && GVar->hasUnnamedAddr())
256 return false;
257
258 // Eventually we only need to promote functions in the exporting module that
259 // are referenced by a potentially exported function (i.e. one that is in the
260 // function index).
261 return true;
262}
263
264std::string ModuleLinker::getName(const GlobalValue *SGV) {
265 // For locals that must be promoted to global scope, ensure that
266 // the promoted name uniquely identifies the copy in the original module,
267 // using the ID assigned during combined index creation. When importing,
268 // we rename all locals (not just those that are promoted) in order to
269 // avoid naming conflicts between locals imported from different modules.
270 if (SGV->hasLocalLinkage() &&
271 (doPromoteLocalToGlobal(SGV) || isPerformingImport()))
272 return FunctionInfoIndex::getGlobalNameForLocal(
273 SGV->getName(),
274 ImportIndex->getModuleId(SGV->getParent()->getModuleIdentifier()));
275 return SGV->getName();
276}
277
278GlobalValue::LinkageTypes ModuleLinker::getLinkage(const GlobalValue *SGV) {
279 // Any local variable that is referenced by an exported function needs
280 // to be promoted to global scope. Since we don't currently know which
281 // functions reference which local variables/functions, we must treat
282 // all as potentially exported if this module is exporting anything.
283 if (isModuleExporting()) {
284 if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
285 return GlobalValue::ExternalLinkage;
286 return SGV->getLinkage();
287 }
288
289 // Otherwise, if we aren't importing, no linkage change is needed.
290 if (!isPerformingImport())
291 return SGV->getLinkage();
292
293 switch (SGV->getLinkage()) {
294 case GlobalValue::ExternalLinkage:
295 // External defnitions are converted to available_externally
296 // definitions upon import, so that they are available for inlining
297 // and/or optimization, but are turned into declarations later
298 // during the EliminateAvailableExternally pass.
Teresa Johnson3cd81612015-11-10 18:20:11 +0000299 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000300 return GlobalValue::AvailableExternallyLinkage;
301 // An imported external declaration stays external.
302 return SGV->getLinkage();
303
304 case GlobalValue::AvailableExternallyLinkage:
305 // An imported available_externally definition converts
306 // to external if imported as a declaration.
307 if (!doImportAsDefinition(SGV))
308 return GlobalValue::ExternalLinkage;
309 // An imported available_externally declaration stays that way.
310 return SGV->getLinkage();
311
312 case GlobalValue::LinkOnceAnyLinkage:
313 case GlobalValue::LinkOnceODRLinkage:
314 // These both stay the same when importing the definition.
315 // The ThinLTO pass will eventually force-import their definitions.
316 return SGV->getLinkage();
317
318 case GlobalValue::WeakAnyLinkage:
319 // Can't import weak_any definitions correctly, or we might change the
320 // program semantics, since the linker will pick the first weak_any
321 // definition and importing would change the order they are seen by the
322 // linker. The module linking caller needs to enforce this.
323 assert(!doImportAsDefinition(SGV));
324 // If imported as a declaration, it becomes external_weak.
325 return GlobalValue::ExternalWeakLinkage;
326
327 case GlobalValue::WeakODRLinkage:
328 // For weak_odr linkage, there is a guarantee that all copies will be
329 // equivalent, so the issue described above for weak_any does not exist,
330 // and the definition can be imported. It can be treated similarly
331 // to an imported externally visible global value.
Teresa Johnson3cd81612015-11-10 18:20:11 +0000332 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000333 return GlobalValue::AvailableExternallyLinkage;
334 else
335 return GlobalValue::ExternalLinkage;
336
337 case GlobalValue::AppendingLinkage:
338 // It would be incorrect to import an appending linkage variable,
339 // since it would cause global constructors/destructors to be
340 // executed multiple times. This should have already been handled
Teresa Johnson1e20a652015-12-03 18:20:05 +0000341 // by linkIfNeeded, and we will assert in shouldLinkFromSource
342 // if we try to import, so we simply return AppendingLinkage here
343 // as this helper is called more widely in getLinkedToGlobal.
344 return GlobalValue::AppendingLinkage;
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000345
346 case GlobalValue::InternalLinkage:
347 case GlobalValue::PrivateLinkage:
348 // If we are promoting the local to global scope, it is handled
349 // similarly to a normal externally visible global.
350 if (doPromoteLocalToGlobal(SGV)) {
Teresa Johnson3cd81612015-11-10 18:20:11 +0000351 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000352 return GlobalValue::AvailableExternallyLinkage;
353 else
354 return GlobalValue::ExternalLinkage;
355 }
356 // A non-promoted imported local definition stays local.
357 // The ThinLTO pass will eventually force-import their definitions.
358 return SGV->getLinkage();
359
360 case GlobalValue::ExternalWeakLinkage:
361 // External weak doesn't apply to definitions, must be a declaration.
362 assert(!doImportAsDefinition(SGV));
363 // Linkage stays external_weak.
364 return SGV->getLinkage();
365
366 case GlobalValue::CommonLinkage:
367 // Linkage stays common on definitions.
368 // The ThinLTO pass will eventually force-import their definitions.
369 return SGV->getLinkage();
370 }
371
372 llvm_unreachable("unknown linkage type");
373}
374
Rafael Espindolaeb5e0a72015-11-29 14:33:06 +0000375static GlobalValue::VisibilityTypes
376getMinVisibility(GlobalValue::VisibilityTypes A,
377 GlobalValue::VisibilityTypes B) {
378 if (A == GlobalValue::HiddenVisibility || B == GlobalValue::HiddenVisibility)
379 return GlobalValue::HiddenVisibility;
380 if (A == GlobalValue::ProtectedVisibility ||
381 B == GlobalValue::ProtectedVisibility)
382 return GlobalValue::ProtectedVisibility;
383 return GlobalValue::DefaultVisibility;
384}
385
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000386void ModuleLinker::setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
387 const GlobalValue *DGV) {
388 GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
389 if (DGV)
Rafael Espindolaeb5e0a72015-11-29 14:33:06 +0000390 Visibility = getMinVisibility(DGV->getVisibility(), Visibility);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000391 // For promoted locals, mark them hidden so that they can later be
392 // stripped from the symbol table to reduce bloat.
393 if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
394 Visibility = GlobalValue::HiddenVisibility;
395 NewGV->setVisibility(Visibility);
396}
397
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000398bool ModuleLinker::getComdatLeader(Module &M, StringRef ComdatName,
David Majnemerdad0a642014-06-27 18:19:56 +0000399 const GlobalVariable *&GVar) {
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000400 const GlobalValue *GVal = M.getNamedValue(ComdatName);
David Majnemerdad0a642014-06-27 18:19:56 +0000401 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
402 GVal = GA->getBaseObject();
403 if (!GVal)
404 // We cannot resolve the size of the aliasee yet.
405 return emitError("Linking COMDATs named '" + ComdatName +
406 "': COMDAT key involves incomputable alias size.");
407 }
408
409 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
410 if (!GVar)
411 return emitError(
412 "Linking COMDATs named '" + ComdatName +
413 "': GlobalVariable required for data dependent selection!");
414
415 return false;
416}
417
418bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
419 Comdat::SelectionKind Src,
420 Comdat::SelectionKind Dst,
421 Comdat::SelectionKind &Result,
422 bool &LinkFromSrc) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000423 Module &DstM = Mover.getModule();
David Majnemerdad0a642014-06-27 18:19:56 +0000424 // The ability to mix Comdat::SelectionKind::Any with
425 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
426 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
427 Dst == Comdat::SelectionKind::Largest;
428 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
429 Src == Comdat::SelectionKind::Largest;
430 if (DstAnyOrLargest && SrcAnyOrLargest) {
431 if (Dst == Comdat::SelectionKind::Largest ||
432 Src == Comdat::SelectionKind::Largest)
433 Result = Comdat::SelectionKind::Largest;
434 else
435 Result = Comdat::SelectionKind::Any;
436 } else if (Src == Dst) {
437 Result = Dst;
438 } else {
439 return emitError("Linking COMDATs named '" + ComdatName +
440 "': invalid selection kinds!");
441 }
442
443 switch (Result) {
444 case Comdat::SelectionKind::Any:
445 // Go with Dst.
446 LinkFromSrc = false;
447 break;
448 case Comdat::SelectionKind::NoDuplicates:
449 return emitError("Linking COMDATs named '" + ComdatName +
450 "': noduplicates has been violated!");
451 case Comdat::SelectionKind::ExactMatch:
452 case Comdat::SelectionKind::Largest:
453 case Comdat::SelectionKind::SameSize: {
454 const GlobalVariable *DstGV;
455 const GlobalVariable *SrcGV;
456 if (getComdatLeader(DstM, ComdatName, DstGV) ||
457 getComdatLeader(SrcM, ComdatName, SrcGV))
458 return true;
459
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000460 const DataLayout &DstDL = DstM.getDataLayout();
461 const DataLayout &SrcDL = SrcM.getDataLayout();
David Majnemerdad0a642014-06-27 18:19:56 +0000462 uint64_t DstSize =
Mehdi Amini46a43552015-03-04 18:43:29 +0000463 DstDL.getTypeAllocSize(DstGV->getType()->getPointerElementType());
David Majnemerdad0a642014-06-27 18:19:56 +0000464 uint64_t SrcSize =
Mehdi Amini46a43552015-03-04 18:43:29 +0000465 SrcDL.getTypeAllocSize(SrcGV->getType()->getPointerElementType());
David Majnemerdad0a642014-06-27 18:19:56 +0000466 if (Result == Comdat::SelectionKind::ExactMatch) {
467 if (SrcGV->getInitializer() != DstGV->getInitializer())
468 return emitError("Linking COMDATs named '" + ComdatName +
469 "': ExactMatch violated!");
470 LinkFromSrc = false;
471 } else if (Result == Comdat::SelectionKind::Largest) {
472 LinkFromSrc = SrcSize > DstSize;
473 } else if (Result == Comdat::SelectionKind::SameSize) {
474 if (SrcSize != DstSize)
475 return emitError("Linking COMDATs named '" + ComdatName +
476 "': SameSize violated!");
477 LinkFromSrc = false;
478 } else {
479 llvm_unreachable("unknown selection kind");
480 }
481 break;
482 }
483 }
484
485 return false;
486}
487
488bool ModuleLinker::getComdatResult(const Comdat *SrcC,
489 Comdat::SelectionKind &Result,
490 bool &LinkFromSrc) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000491 Module &DstM = Mover.getModule();
Rafael Espindolab16196a2014-08-11 17:07:34 +0000492 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
David Majnemerdad0a642014-06-27 18:19:56 +0000493 StringRef ComdatName = SrcC->getName();
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000494 Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
David Majnemerdad0a642014-06-27 18:19:56 +0000495 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000496
Rafael Espindolab16196a2014-08-11 17:07:34 +0000497 if (DstCI == ComdatSymTab.end()) {
498 // Use the comdat if it is only available in one of the modules.
499 LinkFromSrc = true;
500 Result = SSK;
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000501 return false;
Rafael Espindolab16196a2014-08-11 17:07:34 +0000502 }
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000503
504 const Comdat *DstC = &DstCI->second;
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000505 Comdat::SelectionKind DSK = DstC->getSelectionKind();
506 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
507 LinkFromSrc);
David Majnemerdad0a642014-06-27 18:19:56 +0000508}
James Molloyf6f121e2013-05-28 15:17:05 +0000509
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000510bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
511 const GlobalValue &Dest,
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000512 const GlobalValue &Src) {
Teresa Johnsone5a61912015-12-17 17:14:09 +0000513
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +0000514 // Should we unconditionally use the Src?
Artem Belevich020d4fb2015-09-01 17:55:55 +0000515 if (shouldOverrideFromSrc()) {
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +0000516 LinkFromSrc = true;
517 return false;
518 }
519
Rafael Espindola778fcc72014-11-02 13:28:57 +0000520 // We always have to add Src if it has appending linkage.
521 if (Src.hasAppendingLinkage()) {
Teresa Johnson1e20a652015-12-03 18:20:05 +0000522 // Should have prevented importing for appending linkage in linkIfNeeded.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000523 assert(!isPerformingImport());
Rafael Espindola778fcc72014-11-02 13:28:57 +0000524 LinkFromSrc = true;
525 return false;
526 }
527
Rafael Espindolad4bcefc2014-10-24 18:13:04 +0000528 bool SrcIsDeclaration = Src.isDeclarationForLinker();
529 bool DestIsDeclaration = Dest.isDeclarationForLinker();
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000530
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000531 if (isPerformingImport()) {
532 if (isa<Function>(&Src)) {
533 // For functions, LinkFromSrc iff this is the function requested
534 // for importing. For variables, decide below normally.
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000535 LinkFromSrc = ImportFunction->count(&Src);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000536 return false;
537 }
538
539 // Check if this is an alias with an already existing definition
540 // in Dest, which must have come from a prior importing pass from
541 // the same Src module. Unlike imported function and variable
542 // definitions, which are imported as available_externally and are
543 // not definitions for the linker, that is not a valid linkage for
544 // imported aliases which must be definitions. Simply use the existing
545 // Dest copy.
546 if (isa<GlobalAlias>(&Src) && !DestIsDeclaration) {
547 assert(isa<GlobalAlias>(&Dest));
548 LinkFromSrc = false;
549 return false;
550 }
551 }
552
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000553 if (SrcIsDeclaration) {
554 // If Src is external or if both Src & Dest are external.. Just link the
555 // external globals, we aren't adding anything.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000556 if (Src.hasDLLImportStorageClass()) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000557 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000558 LinkFromSrc = DestIsDeclaration;
559 return false;
560 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000561 // If the Dest is weak, use the source linkage.
Rafael Espindolaed11bd22015-12-09 22:44:00 +0000562 if (Dest.hasExternalWeakLinkage()) {
563 LinkFromSrc = true;
564 return false;
565 }
566 // Link an available_externally over a declaration.
567 LinkFromSrc = !Src.isDeclaration() && Dest.isDeclaration();
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000568 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000569 }
570
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000571 if (DestIsDeclaration) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000572 // If Dest is external but Src is not:
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000573 LinkFromSrc = true;
574 return false;
575 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000576
Rafael Espindola09106052014-09-09 15:59:12 +0000577 if (Src.hasCommonLinkage()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000578 if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
579 LinkFromSrc = true;
Rafael Espindola09106052014-09-09 15:59:12 +0000580 return false;
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000581 }
582
583 if (!Dest.hasCommonLinkage()) {
584 LinkFromSrc = false;
585 return false;
586 }
Rafael Espindola09106052014-09-09 15:59:12 +0000587
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000588 const DataLayout &DL = Dest.getParent()->getDataLayout();
Rafael Espindola09106052014-09-09 15:59:12 +0000589 uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
590 uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000591 LinkFromSrc = SrcSize > DestSize;
592 return false;
Rafael Espindola09106052014-09-09 15:59:12 +0000593 }
594
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000595 if (Src.isWeakForLinker()) {
596 assert(!Dest.hasExternalWeakLinkage());
597 assert(!Dest.hasAvailableExternallyLinkage());
Rafael Espindola09106052014-09-09 15:59:12 +0000598
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000599 if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
600 LinkFromSrc = true;
601 return false;
602 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000603
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000604 LinkFromSrc = false;
Rafael Espindola09106052014-09-09 15:59:12 +0000605 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000606 }
607
608 if (Dest.isWeakForLinker()) {
609 assert(Src.hasExternalLinkage());
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000610 LinkFromSrc = true;
611 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000612 }
613
614 assert(!Src.hasExternalWeakLinkage());
615 assert(!Dest.hasExternalWeakLinkage());
616 assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
617 "Unexpected linkage type!");
618 return emitError("Linking globals named '" + Src.getName() +
619 "': symbol multiply defined!");
620}
621
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000622bool ModuleLinker::linkIfNeeded(GlobalValue &GV) {
623 GlobalValue *DGV = getLinkedToGlobal(&GV);
624
625 if (shouldLinkOnlyNeeded() && !(DGV && DGV->isDeclaration()))
626 return false;
627
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000628 if (DGV && !GV.hasLocalLinkage() && !GV.hasAppendingLinkage()) {
629 auto *DGVar = dyn_cast<GlobalVariable>(DGV);
630 auto *SGVar = dyn_cast<GlobalVariable>(&GV);
631 if (DGVar && SGVar) {
632 if (DGVar->isDeclaration() && SGVar->isDeclaration() &&
633 (!DGVar->isConstant() || !SGVar->isConstant())) {
634 DGVar->setConstant(false);
635 SGVar->setConstant(false);
636 }
637 if (DGVar->hasCommonLinkage() && SGVar->hasCommonLinkage()) {
638 unsigned Align = std::max(DGVar->getAlignment(), SGVar->getAlignment());
639 SGVar->setAlignment(Align);
640 DGVar->setAlignment(Align);
641 }
642 }
643
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000644 GlobalValue::VisibilityTypes Visibility =
645 getMinVisibility(DGV->getVisibility(), GV.getVisibility());
646 DGV->setVisibility(Visibility);
647 GV.setVisibility(Visibility);
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000648
649 bool HasUnnamedAddr = GV.hasUnnamedAddr() && DGV->hasUnnamedAddr();
650 DGV->setUnnamedAddr(HasUnnamedAddr);
651 GV.setUnnamedAddr(HasUnnamedAddr);
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000652 }
653
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000654 // Don't want to append to global_ctors list, for example, when we
655 // are importing for ThinLTO, otherwise the global ctors and dtors
656 // get executed multiple times for local variables (the latter causing
657 // double frees).
658 if (GV.hasAppendingLinkage() && isPerformingImport())
659 return false;
660
661 if (isPerformingImport() && !doImportAsDefinition(&GV))
662 return false;
663
664 if (!DGV && !shouldOverrideFromSrc() &&
665 (GV.hasLocalLinkage() || GV.hasLinkOnceLinkage() ||
666 GV.hasAvailableExternallyLinkage()))
667 return false;
668
Rafael Espindolabd03c502015-12-07 16:31:41 +0000669 if (GV.isDeclaration())
670 return false;
671
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000672 if (const Comdat *SC = GV.getComdat()) {
673 bool LinkFromSrc;
674 Comdat::SelectionKind SK;
675 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000676 if (LinkFromSrc)
677 ValuesToLink.insert(&GV);
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000678 return false;
679 }
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000680
681 bool LinkFromSrc = true;
682 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, GV))
683 return true;
684 if (LinkFromSrc)
685 ValuesToLink.insert(&GV);
686 return false;
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000687}
688
Rafael Espindolacaabe222015-12-10 14:19:35 +0000689void ModuleLinker::addLazyFor(GlobalValue &GV, IRMover::ValueAdder Add) {
690 // Add these to the internalize list
691 if (!GV.hasLinkOnceLinkage())
692 return;
693
694 if (shouldInternalizeLinkedSymbols())
695 Internalize.insert(GV.getName());
696 Add(GV);
697
698 const Comdat *SC = GV.getComdat();
699 if (!SC)
700 return;
701 for (GlobalValue *GV2 : ComdatMembers[SC]) {
702 if (!GV2->hasLocalLinkage() && shouldInternalizeLinkedSymbols())
703 Internalize.insert(GV2->getName());
704 Add(*GV2);
705 }
706}
707
708void ModuleLinker::processGlobalForThinLTO(GlobalValue &GV) {
709 if (GV.hasLocalLinkage() &&
710 (doPromoteLocalToGlobal(&GV) || isPerformingImport())) {
711 GV.setName(getName(&GV));
712 GV.setLinkage(getLinkage(&GV));
713 if (!GV.hasLocalLinkage())
714 GV.setVisibility(GlobalValue::HiddenVisibility);
715 if (isModuleExporting())
716 ValuesToLink.insert(&GV);
717 return;
718 }
719 GV.setLinkage(getLinkage(&GV));
720}
721
722void ModuleLinker::processGlobalsForThinLTO() {
723 for (GlobalVariable &GV : SrcM.globals())
724 processGlobalForThinLTO(GV);
725 for (Function &SF : SrcM)
726 processGlobalForThinLTO(SF);
727 for (GlobalAlias &GA : SrcM.aliases())
728 processGlobalForThinLTO(GA);
729}
730
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000731bool ModuleLinker::run() {
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000732 for (const auto &SMEC : SrcM.getComdatSymbolTable()) {
David Majnemerdad0a642014-06-27 18:19:56 +0000733 const Comdat &C = SMEC.getValue();
734 if (ComdatsChosen.count(&C))
735 continue;
736 Comdat::SelectionKind SK;
737 bool LinkFromSrc;
738 if (getComdatResult(&C, SK, LinkFromSrc))
739 return true;
740 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
741 }
742
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000743 for (GlobalVariable &GV : SrcM.globals())
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000744 if (const Comdat *SC = GV.getComdat())
745 ComdatMembers[SC].push_back(&GV);
746
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000747 for (Function &SF : SrcM)
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000748 if (const Comdat *SC = SF.getComdat())
749 ComdatMembers[SC].push_back(&SF);
750
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000751 for (GlobalAlias &GA : SrcM.aliases())
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000752 if (const Comdat *SC = GA.getComdat())
753 ComdatMembers[SC].push_back(&GA);
754
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000755 // Insert all of the globals in src into the DstM module... without linking
756 // initializers (which could refer to functions not yet mapped over).
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000757 for (GlobalVariable &GV : SrcM.globals())
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000758 if (linkIfNeeded(GV))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000759 return true;
760
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000761 for (Function &SF : SrcM)
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000762 if (linkIfNeeded(SF))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000763 return true;
764
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000765 for (GlobalAlias &GA : SrcM.aliases())
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000766 if (linkIfNeeded(GA))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000767 return true;
768
Rafael Espindolacaabe222015-12-10 14:19:35 +0000769 processGlobalsForThinLTO();
770
771 for (unsigned I = 0; I < ValuesToLink.size(); ++I) {
772 GlobalValue *GV = ValuesToLink[I];
773 const Comdat *SC = GV->getComdat();
774 if (!SC)
775 continue;
776 for (GlobalValue *GV2 : ComdatMembers[SC])
777 ValuesToLink.insert(GV2);
Rafael Espindolabeadd562014-12-08 18:05:48 +0000778 }
779
Rafael Espindolacaabe222015-12-10 14:19:35 +0000780 if (shouldInternalizeLinkedSymbols()) {
781 for (GlobalValue *GV : ValuesToLink)
782 Internalize.insert(GV->getName());
783 }
Teresa Johnson10632932015-11-06 17:50:53 +0000784
Rafael Espindolaf81c7b02015-12-10 16:35:06 +0000785 if (Mover.move(SrcM, ValuesToLink.getArrayRef(),
Rafael Espindolacaabe222015-12-10 14:19:35 +0000786 [this](GlobalValue &GV, IRMover::ValueAdder Add) {
787 addLazyFor(GV, Add);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000788 },
789 ValIDToTempMDMap, false))
Teresa Johnson189b2522015-11-06 17:50:48 +0000790 return true;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000791 Module &DstM = Mover.getModule();
792 for (auto &P : Internalize) {
793 GlobalValue *GV = DstM.getNamedValue(P.first());
794 GV->setLinkage(GlobalValue::InternalLinkage);
795 }
Teresa Johnson189b2522015-11-06 17:50:48 +0000796
Anton Korobeynikov26098882008-03-05 23:21:39 +0000797 return false;
798}
Reid Spencer361e5132004-11-12 20:37:43 +0000799
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000800Linker::Linker(Module &M) : Mover(M) {}
Rafael Espindola3df61b72013-05-04 03:48:37 +0000801
Rafael Espindola434e9562015-12-16 23:16:33 +0000802bool Linker::linkInModule(std::unique_ptr<Module> Src, unsigned Flags,
Mehdi Amini8220e8a2015-11-23 01:59:16 +0000803 const FunctionInfoIndex *Index,
Teresa Johnsone5a61912015-12-17 17:14:09 +0000804 DenseSet<const GlobalValue *> *FunctionsToImport,
805 DenseMap<unsigned, MDNode *> *ValIDToTempMDMap) {
806 ModuleLinker TheLinker(Mover, *Src, Flags, Index, FunctionsToImport,
807 ValIDToTempMDMap);
Rafael Espindola434e9562015-12-16 23:16:33 +0000808 return TheLinker.run();
809}
810
811bool Linker::linkInModuleForCAPI(Module &Src) {
812 ModuleLinker TheLinker(Mover, Src, 0, nullptr, nullptr);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000813 return TheLinker.run();
Rafael Espindola3df61b72013-05-04 03:48:37 +0000814}
815
Teresa Johnsone5a61912015-12-17 17:14:09 +0000816bool Linker::linkInMetadata(Module &Src,
817 DenseMap<unsigned, MDNode *> *ValIDToTempMDMap) {
818 SetVector<GlobalValue *> ValuesToLink;
819 if (Mover.move(
820 Src, ValuesToLink.getArrayRef(),
821 [this](GlobalValue &GV, IRMover::ValueAdder Add) { assert(false); },
822 ValIDToTempMDMap, true))
823 return true;
824 return false;
825}
826
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000827//===----------------------------------------------------------------------===//
828// LinkModules entrypoint.
829//===----------------------------------------------------------------------===//
830
Rafael Espindola18c89412014-10-27 02:35:46 +0000831/// This function links two modules together, with the resulting Dest module
832/// modified to be the composite of the two input modules. If an error occurs,
833/// true is returned and ErrorMsg (if not null) is set to indicate the problem.
834/// Upon failure, the Dest module could be in a modified state, and shouldn't be
835/// relied on to be consistent.
Rafael Espindola434e9562015-12-16 23:16:33 +0000836bool Linker::linkModules(Module &Dest, std::unique_ptr<Module> Src,
837 unsigned Flags) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000838 Linker L(Dest);
Rafael Espindola434e9562015-12-16 23:16:33 +0000839 return L.linkInModule(std::move(Src), Flags);
Rafael Espindola4160f5d2014-10-27 23:02:10 +0000840}
841
Teresa Johnsonbae7e752015-12-04 23:40:22 +0000842std::unique_ptr<Module>
Rafael Espindola434e9562015-12-16 23:16:33 +0000843llvm::renameModuleForThinLTO(std::unique_ptr<Module> M,
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000844 const FunctionInfoIndex *Index) {
Teresa Johnsonbae7e752015-12-04 23:40:22 +0000845 std::unique_ptr<llvm::Module> RenamedModule(
846 new llvm::Module(M->getModuleIdentifier(), M->getContext()));
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000847 Linker L(*RenamedModule.get());
Rafael Espindola434e9562015-12-16 23:16:33 +0000848 if (L.linkInModule(std::move(M), llvm::Linker::Flags::None, Index))
Teresa Johnsonbae7e752015-12-04 23:40:22 +0000849 return nullptr;
850 return RenamedModule;
851}
852
Bill Wendlinga3aeb982012-05-09 08:55:40 +0000853//===----------------------------------------------------------------------===//
854// C API.
855//===----------------------------------------------------------------------===//
856
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000857static void diagnosticHandler(const DiagnosticInfo &DI, void *C) {
858 auto *Message = reinterpret_cast<std::string *>(C);
859 raw_string_ostream Stream(*Message);
860 DiagnosticPrinterRawOStream DP(Stream);
861 DI.print(DP);
862}
863
Bill Wendlinga3aeb982012-05-09 08:55:40 +0000864LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
Juergen Ributzkaa57d5882015-03-02 18:59:38 +0000865 LLVMLinkerMode Unused, char **OutMessages) {
Rafael Espindola98ab63c2014-10-25 04:31:08 +0000866 Module *D = unwrap(Dest);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000867 LLVMContext &Ctx = D->getContext();
868
869 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
870 Ctx.getDiagnosticHandler();
871 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
Rafael Espindola98ab63c2014-10-25 04:31:08 +0000872 std::string Message;
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000873 Ctx.setDiagnosticHandler(diagnosticHandler, &Message, true);
Rafael Espindola4160f5d2014-10-27 23:02:10 +0000874
Rafael Espindola434e9562015-12-16 23:16:33 +0000875 Linker L(*D);
876 Module *M = unwrap(Src);
877 LLVMBool Result = L.linkInModuleForCAPI(*M);
Rafael Espindola98ab63c2014-10-25 04:31:08 +0000878
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000879 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext, true);
880
881 if (OutMessages && Result)
Rafael Espindola98ab63c2014-10-25 04:31:08 +0000882 *OutMessages = strdup(Message.c_str());
Bill Wendlinga3aeb982012-05-09 08:55:40 +0000883 return Result;
884}
Rafael Espindola434e9562015-12-16 23:16:33 +0000885
886LLVMBool LLVMLinkModules2(LLVMModuleRef Dest, LLVMModuleRef Src) {
887 Module *D = unwrap(Dest);
888 std::unique_ptr<Module> M(unwrap(Src));
889 return Linker::linkModules(*D, std::move(M));
890}