blob: a596697e8f516994c5ba56b182454421b744809e [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"
Reid Spencer361e5132004-11-12 20:37:43 +000020using namespace llvm;
21
Chris Lattnereee6f992008-06-16 21:00:18 +000022namespace {
Rafael Espindolac84f6082014-11-25 06:11:24 +000023
24/// This is an implementation class for the LinkModules function, which is the
25/// entrypoint for this file.
26class ModuleLinker {
Rafael Espindolacaabe222015-12-10 14:19:35 +000027 IRMover &Mover;
Rafael Espindola0e309fe2015-12-01 19:50:54 +000028 Module &SrcM;
Rafael Espindolac84f6082014-11-25 06:11:24 +000029
Rafael Espindola4b5ec262015-12-02 22:59:04 +000030 SetVector<GlobalValue *> ValuesToLink;
Rafael Espindolacaabe222015-12-10 14:19:35 +000031 StringSet<> Internalize;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000032
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +000033 /// For symbol clashes, prefer those from Src.
Artem Belevich020d4fb2015-09-01 17:55:55 +000034 unsigned Flags;
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +000035
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +000036 /// Function index passed into ModuleLinker for using in function
37 /// importing/exporting handling.
Mehdi Amini8220e8a2015-11-23 01:59:16 +000038 const FunctionInfoIndex *ImportIndex;
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +000039
40 /// Function to import from source module, all other functions are
41 /// imported as declarations instead of definitions.
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +000042 DenseSet<const GlobalValue *> *ImportFunction;
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +000043
44 /// Set to true if the given FunctionInfoIndex contains any functions
45 /// from this source module, in which case we must conservatively assume
46 /// that any of its functions may be imported into another module
47 /// as part of a different backend compilation process.
Rafael Espindolaaf714762015-12-01 23:06:26 +000048 bool HasExportedFunctions = false;
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +000049
Rafael Espindolacaabe222015-12-10 14:19:35 +000050 /// Used as the callback for lazy linking.
51 /// The mover has just hit GV and we have to decide if it, and other members
52 /// of the same comdat, should be linked. Every member to be linked is passed
53 /// to Add.
54 void addLazyFor(GlobalValue &GV, IRMover::ValueAdder Add);
Rafael Espindolabaa3bf82015-12-01 15:19:48 +000055
Artem Belevich020d4fb2015-09-01 17:55:55 +000056 bool shouldOverrideFromSrc() { return Flags & Linker::OverrideFromSrc; }
57 bool shouldLinkOnlyNeeded() { return Flags & Linker::LinkOnlyNeeded; }
58 bool shouldInternalizeLinkedSymbols() {
59 return Flags & Linker::InternalizeLinkedSymbols;
60 }
61
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +000062 /// Check if we should promote the given local value to global scope.
63 bool doPromoteLocalToGlobal(const GlobalValue *SGV);
64
Rafael Espindolac84f6082014-11-25 06:11:24 +000065 bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
66 const GlobalValue &Src);
Rafael Espindolaed6dc372014-05-09 14:39:25 +000067
Rafael Espindolacaabe222015-12-10 14:19:35 +000068 /// Should we have mover and linker error diag info?
Rafael Espindolac84f6082014-11-25 06:11:24 +000069 bool emitError(const Twine &Message) {
Rafael Espindolacaabe222015-12-10 14:19:35 +000070 Mover.getDiagnosticHandler()(LinkDiagnosticInfo(DS_Error, Message));
Rafael Espindolac84f6082014-11-25 06:11:24 +000071 return true;
72 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +000073
Rafael Espindola0e309fe2015-12-01 19:50:54 +000074 bool getComdatLeader(Module &M, StringRef ComdatName,
Rafael Espindolac84f6082014-11-25 06:11:24 +000075 const GlobalVariable *&GVar);
76 bool computeResultingSelectionKind(StringRef ComdatName,
77 Comdat::SelectionKind Src,
78 Comdat::SelectionKind Dst,
79 Comdat::SelectionKind &Result,
80 bool &LinkFromSrc);
81 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
82 ComdatsChosen;
83 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
84 bool &LinkFromSrc);
Teresa Johnson2d5fb8c2015-11-10 21:09:06 +000085 // Keep track of the global value members of each comdat in source.
86 DenseMap<const Comdat *, std::vector<GlobalValue *>> ComdatMembers;
Rafael Espindola4160f5d2014-10-27 23:02:10 +000087
Rafael Espindolac84f6082014-11-25 06:11:24 +000088 /// Given a global in the source module, return the global in the
89 /// destination module that is being linked to, if any.
90 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
Rafael Espindolacaabe222015-12-10 14:19:35 +000091 Module &DstM = Mover.getModule();
Rafael Espindolac84f6082014-11-25 06:11:24 +000092 // If the source has no name it can't link. If it has local linkage,
93 // there is no name match-up going on.
Teresa Johnsonb098f0c2015-11-24 19:46:58 +000094 if (!SrcGV->hasName() || GlobalValue::isLocalLinkage(getLinkage(SrcGV)))
Rafael Espindolac84f6082014-11-25 06:11:24 +000095 return nullptr;
Eli Bendersky7da92ed2014-02-20 22:19:24 +000096
Rafael Espindolac84f6082014-11-25 06:11:24 +000097 // Otherwise see if we have a match in the destination module's symtab.
Rafael Espindola0e309fe2015-12-01 19:50:54 +000098 GlobalValue *DGV = DstM.getNamedValue(getName(SrcGV));
Rafael Espindolac84f6082014-11-25 06:11:24 +000099 if (!DGV)
100 return nullptr;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000101
Rafael Espindolac84f6082014-11-25 06:11:24 +0000102 // If we found a global with the same name in the dest module, but it has
103 // internal linkage, we are really not doing any linkage here.
104 if (DGV->hasLocalLinkage())
105 return nullptr;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000106
Rafael Espindolac84f6082014-11-25 06:11:24 +0000107 // Otherwise, we do in fact link to the destination global.
108 return DGV;
109 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000110
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000111 bool linkIfNeeded(GlobalValue &GV);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000112
113 /// Helper methods to check if we are importing from or potentially
114 /// exporting from the current source module.
115 bool isPerformingImport() { return ImportFunction != nullptr; }
116 bool isModuleExporting() { return HasExportedFunctions; }
117
118 /// If we are importing from the source module, checks if we should
119 /// import SGV as a definition, otherwise import as a declaration.
120 bool doImportAsDefinition(const GlobalValue *SGV);
121
122 /// Get the name for SGV that should be used in the linked destination
123 /// module. Specifically, this handles the case where we need to rename
124 /// a local that is being promoted to global scope.
125 std::string getName(const GlobalValue *SGV);
126
Rafael Espindolacaabe222015-12-10 14:19:35 +0000127 /// Process globals so that they can be used in ThinLTO. This includes
128 /// promoting local variables so that they can be reference externally by
129 /// thin lto imported globals and converting strong external globals to
130 /// available_externally.
131 void processGlobalsForThinLTO();
132 void processGlobalForThinLTO(GlobalValue &GV);
133
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000134 /// Get the new linkage for SGV that should be used in the linked destination
135 /// module. Specifically, for ThinLTO importing or exporting it may need
136 /// to be adjusted.
137 GlobalValue::LinkageTypes getLinkage(const GlobalValue *SGV);
138
139 /// Copies the necessary global value attributes and name from the source
140 /// to the newly cloned global value.
141 void copyGVAttributes(GlobalValue *NewGV, const GlobalValue *SrcGV);
142
143 /// Updates the visibility for the new global cloned from the source
144 /// and, if applicable, linked with an existing destination global.
145 /// Handles visibility change required for promoted locals.
146 void setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
147 const GlobalValue *DGV = nullptr);
148
Rafael Espindolad57f9f02015-12-08 14:54:49 +0000149public:
Rafael Espindolacaabe222015-12-10 14:19:35 +0000150 ModuleLinker(IRMover &Mover, Module &SrcM, unsigned Flags,
Rafael Espindolad57f9f02015-12-08 14:54:49 +0000151 const FunctionInfoIndex *Index = nullptr,
152 DenseSet<const GlobalValue *> *FunctionsToImport = nullptr)
Rafael Espindolacaabe222015-12-10 14:19:35 +0000153 : Mover(Mover), SrcM(SrcM), Flags(Flags), ImportIndex(Index),
Rafael Espindolad57f9f02015-12-08 14:54:49 +0000154 ImportFunction(FunctionsToImport) {
155 assert((ImportIndex || !ImportFunction) &&
156 "Expect a FunctionInfoIndex when importing");
157 // If we have a FunctionInfoIndex but no function to import,
158 // then this is the primary module being compiled in a ThinLTO
159 // backend compilation, and we need to see if it has functions that
160 // may be exported to another backend compilation.
161 if (ImportIndex && !ImportFunction)
162 HasExportedFunctions = ImportIndex->hasExportedFunctions(SrcM);
163 }
164
165 bool run();
Rafael Espindolac84f6082014-11-25 06:11:24 +0000166};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000167}
Bill Wendlingd48b7782012-02-28 04:01:21 +0000168
Rafael Espindola18c89412014-10-27 02:35:46 +0000169/// The LLVM SymbolTable class autorenames globals that conflict in the symbol
170/// table. This is good for all clients except for us. Go through the trouble
171/// to force this back.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000172static void forceRenaming(GlobalValue *GV, StringRef Name) {
173 // If the global doesn't force its name or if it already has the right name,
174 // there is nothing for us to do.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000175 // Note that any required local to global promotion should already be done,
176 // so promoted locals will not skip this handling as their linkage is no
177 // longer local.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000178 if (GV->hasLocalLinkage() || GV->getName() == Name)
179 return;
180
181 Module *M = GV->getParent();
Reid Spencer361e5132004-11-12 20:37:43 +0000182
183 // If there is a conflict, rename the conflict.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000184 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
Chris Lattner2a8d2e02007-02-11 00:39:38 +0000185 GV->takeName(ConflictGV);
Rafael Espindolae3a933a2015-12-01 20:11:43 +0000186 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000187 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
Chris Lattner2a8d2e02007-02-11 00:39:38 +0000188 } else {
Rafael Espindolae3a933a2015-12-01 20:11:43 +0000189 GV->setName(Name); // Force the name back
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000190 }
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000191}
Reid Spencer90246aa2007-02-04 04:29:21 +0000192
Rafael Espindola18c89412014-10-27 02:35:46 +0000193/// copy additional attributes (those not needed to construct a GlobalValue)
194/// from the SrcGV to the DestGV.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000195void ModuleLinker::copyGVAttributes(GlobalValue *NewGV,
196 const GlobalValue *SrcGV) {
Rafael Espindola769efe62015-12-02 20:03:17 +0000197 NewGV->copyAttributesFrom(SrcGV);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000198 forceRenaming(NewGV, getName(SrcGV));
Reid Spencer361e5132004-11-12 20:37:43 +0000199}
200
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000201bool ModuleLinker::doImportAsDefinition(const GlobalValue *SGV) {
202 if (!isPerformingImport())
203 return false;
Teresa Johnson3cd81612015-11-10 18:20:11 +0000204 auto *GA = dyn_cast<GlobalAlias>(SGV);
205 if (GA) {
206 if (GA->hasWeakAnyLinkage())
207 return false;
Rafael Espindola89345772015-11-26 19:22:59 +0000208 const GlobalObject *GO = GA->getBaseObject();
209 if (!GO->hasLinkOnceODRLinkage())
210 return false;
211 return doImportAsDefinition(GO);
Teresa Johnson3cd81612015-11-10 18:20:11 +0000212 }
Teresa Johnsondfbebc32015-11-10 18:26:31 +0000213 // Always import GlobalVariable definitions, except for the special
214 // case of WeakAny which are imported as ExternalWeak declarations
215 // (see comments in ModuleLinker::getLinkage). The linkage changes
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000216 // described in ModuleLinker::getLinkage ensure the correct behavior (e.g.
217 // global variables with external linkage are transformed to
Teresa Johnson3cd81612015-11-10 18:20:11 +0000218 // available_externally definitions, which are ultimately turned into
219 // declarations after the EliminateAvailableExternally pass).
Craig Topper66059c92015-11-18 07:07:59 +0000220 if (isa<GlobalVariable>(SGV) && !SGV->isDeclaration() &&
Teresa Johnson3cd81612015-11-10 18:20:11 +0000221 !SGV->hasWeakAnyLinkage())
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000222 return true;
223 // Only import the function requested for importing.
224 auto *SF = dyn_cast<Function>(SGV);
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000225 if (SF && ImportFunction->count(SF))
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000226 return true;
227 // Otherwise no.
228 return false;
229}
230
231bool ModuleLinker::doPromoteLocalToGlobal(const GlobalValue *SGV) {
232 assert(SGV->hasLocalLinkage());
233 // Both the imported references and the original local variable must
234 // be promoted.
235 if (!isPerformingImport() && !isModuleExporting())
236 return false;
237
238 // Local const variables never need to be promoted unless they are address
239 // taken. The imported uses can simply use the clone created in this module.
240 // For now we are conservative in determining which variables are not
241 // address taken by checking the unnamed addr flag. To be more aggressive,
242 // the address taken information must be checked earlier during parsing
243 // of the module and recorded in the function index for use when importing
244 // from that module.
245 auto *GVar = dyn_cast<GlobalVariable>(SGV);
246 if (GVar && GVar->isConstant() && GVar->hasUnnamedAddr())
247 return false;
248
249 // Eventually we only need to promote functions in the exporting module that
250 // are referenced by a potentially exported function (i.e. one that is in the
251 // function index).
252 return true;
253}
254
255std::string ModuleLinker::getName(const GlobalValue *SGV) {
256 // For locals that must be promoted to global scope, ensure that
257 // the promoted name uniquely identifies the copy in the original module,
258 // using the ID assigned during combined index creation. When importing,
259 // we rename all locals (not just those that are promoted) in order to
260 // avoid naming conflicts between locals imported from different modules.
261 if (SGV->hasLocalLinkage() &&
262 (doPromoteLocalToGlobal(SGV) || isPerformingImport()))
263 return FunctionInfoIndex::getGlobalNameForLocal(
264 SGV->getName(),
265 ImportIndex->getModuleId(SGV->getParent()->getModuleIdentifier()));
266 return SGV->getName();
267}
268
269GlobalValue::LinkageTypes ModuleLinker::getLinkage(const GlobalValue *SGV) {
270 // Any local variable that is referenced by an exported function needs
271 // to be promoted to global scope. Since we don't currently know which
272 // functions reference which local variables/functions, we must treat
273 // all as potentially exported if this module is exporting anything.
274 if (isModuleExporting()) {
275 if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
276 return GlobalValue::ExternalLinkage;
277 return SGV->getLinkage();
278 }
279
280 // Otherwise, if we aren't importing, no linkage change is needed.
281 if (!isPerformingImport())
282 return SGV->getLinkage();
283
284 switch (SGV->getLinkage()) {
285 case GlobalValue::ExternalLinkage:
286 // External defnitions are converted to available_externally
287 // definitions upon import, so that they are available for inlining
288 // and/or optimization, but are turned into declarations later
289 // during the EliminateAvailableExternally pass.
Teresa Johnson3cd81612015-11-10 18:20:11 +0000290 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000291 return GlobalValue::AvailableExternallyLinkage;
292 // An imported external declaration stays external.
293 return SGV->getLinkage();
294
295 case GlobalValue::AvailableExternallyLinkage:
296 // An imported available_externally definition converts
297 // to external if imported as a declaration.
298 if (!doImportAsDefinition(SGV))
299 return GlobalValue::ExternalLinkage;
300 // An imported available_externally declaration stays that way.
301 return SGV->getLinkage();
302
303 case GlobalValue::LinkOnceAnyLinkage:
304 case GlobalValue::LinkOnceODRLinkage:
305 // These both stay the same when importing the definition.
306 // The ThinLTO pass will eventually force-import their definitions.
307 return SGV->getLinkage();
308
309 case GlobalValue::WeakAnyLinkage:
310 // Can't import weak_any definitions correctly, or we might change the
311 // program semantics, since the linker will pick the first weak_any
312 // definition and importing would change the order they are seen by the
313 // linker. The module linking caller needs to enforce this.
314 assert(!doImportAsDefinition(SGV));
315 // If imported as a declaration, it becomes external_weak.
316 return GlobalValue::ExternalWeakLinkage;
317
318 case GlobalValue::WeakODRLinkage:
319 // For weak_odr linkage, there is a guarantee that all copies will be
320 // equivalent, so the issue described above for weak_any does not exist,
321 // and the definition can be imported. It can be treated similarly
322 // to an imported externally visible global value.
Teresa Johnson3cd81612015-11-10 18:20:11 +0000323 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000324 return GlobalValue::AvailableExternallyLinkage;
325 else
326 return GlobalValue::ExternalLinkage;
327
328 case GlobalValue::AppendingLinkage:
329 // It would be incorrect to import an appending linkage variable,
330 // since it would cause global constructors/destructors to be
331 // executed multiple times. This should have already been handled
Teresa Johnson1e20a652015-12-03 18:20:05 +0000332 // by linkIfNeeded, and we will assert in shouldLinkFromSource
333 // if we try to import, so we simply return AppendingLinkage here
334 // as this helper is called more widely in getLinkedToGlobal.
335 return GlobalValue::AppendingLinkage;
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000336
337 case GlobalValue::InternalLinkage:
338 case GlobalValue::PrivateLinkage:
339 // If we are promoting the local to global scope, it is handled
340 // similarly to a normal externally visible global.
341 if (doPromoteLocalToGlobal(SGV)) {
Teresa Johnson3cd81612015-11-10 18:20:11 +0000342 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000343 return GlobalValue::AvailableExternallyLinkage;
344 else
345 return GlobalValue::ExternalLinkage;
346 }
347 // A non-promoted imported local definition stays local.
348 // The ThinLTO pass will eventually force-import their definitions.
349 return SGV->getLinkage();
350
351 case GlobalValue::ExternalWeakLinkage:
352 // External weak doesn't apply to definitions, must be a declaration.
353 assert(!doImportAsDefinition(SGV));
354 // Linkage stays external_weak.
355 return SGV->getLinkage();
356
357 case GlobalValue::CommonLinkage:
358 // Linkage stays common on definitions.
359 // The ThinLTO pass will eventually force-import their definitions.
360 return SGV->getLinkage();
361 }
362
363 llvm_unreachable("unknown linkage type");
364}
365
Rafael Espindolaeb5e0a72015-11-29 14:33:06 +0000366static GlobalValue::VisibilityTypes
367getMinVisibility(GlobalValue::VisibilityTypes A,
368 GlobalValue::VisibilityTypes B) {
369 if (A == GlobalValue::HiddenVisibility || B == GlobalValue::HiddenVisibility)
370 return GlobalValue::HiddenVisibility;
371 if (A == GlobalValue::ProtectedVisibility ||
372 B == GlobalValue::ProtectedVisibility)
373 return GlobalValue::ProtectedVisibility;
374 return GlobalValue::DefaultVisibility;
375}
376
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000377void ModuleLinker::setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
378 const GlobalValue *DGV) {
379 GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
380 if (DGV)
Rafael Espindolaeb5e0a72015-11-29 14:33:06 +0000381 Visibility = getMinVisibility(DGV->getVisibility(), Visibility);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000382 // For promoted locals, mark them hidden so that they can later be
383 // stripped from the symbol table to reduce bloat.
384 if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
385 Visibility = GlobalValue::HiddenVisibility;
386 NewGV->setVisibility(Visibility);
387}
388
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000389bool ModuleLinker::getComdatLeader(Module &M, StringRef ComdatName,
David Majnemerdad0a642014-06-27 18:19:56 +0000390 const GlobalVariable *&GVar) {
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000391 const GlobalValue *GVal = M.getNamedValue(ComdatName);
David Majnemerdad0a642014-06-27 18:19:56 +0000392 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
393 GVal = GA->getBaseObject();
394 if (!GVal)
395 // We cannot resolve the size of the aliasee yet.
396 return emitError("Linking COMDATs named '" + ComdatName +
397 "': COMDAT key involves incomputable alias size.");
398 }
399
400 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
401 if (!GVar)
402 return emitError(
403 "Linking COMDATs named '" + ComdatName +
404 "': GlobalVariable required for data dependent selection!");
405
406 return false;
407}
408
409bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
410 Comdat::SelectionKind Src,
411 Comdat::SelectionKind Dst,
412 Comdat::SelectionKind &Result,
413 bool &LinkFromSrc) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000414 Module &DstM = Mover.getModule();
David Majnemerdad0a642014-06-27 18:19:56 +0000415 // The ability to mix Comdat::SelectionKind::Any with
416 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
417 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
418 Dst == Comdat::SelectionKind::Largest;
419 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
420 Src == Comdat::SelectionKind::Largest;
421 if (DstAnyOrLargest && SrcAnyOrLargest) {
422 if (Dst == Comdat::SelectionKind::Largest ||
423 Src == Comdat::SelectionKind::Largest)
424 Result = Comdat::SelectionKind::Largest;
425 else
426 Result = Comdat::SelectionKind::Any;
427 } else if (Src == Dst) {
428 Result = Dst;
429 } else {
430 return emitError("Linking COMDATs named '" + ComdatName +
431 "': invalid selection kinds!");
432 }
433
434 switch (Result) {
435 case Comdat::SelectionKind::Any:
436 // Go with Dst.
437 LinkFromSrc = false;
438 break;
439 case Comdat::SelectionKind::NoDuplicates:
440 return emitError("Linking COMDATs named '" + ComdatName +
441 "': noduplicates has been violated!");
442 case Comdat::SelectionKind::ExactMatch:
443 case Comdat::SelectionKind::Largest:
444 case Comdat::SelectionKind::SameSize: {
445 const GlobalVariable *DstGV;
446 const GlobalVariable *SrcGV;
447 if (getComdatLeader(DstM, ComdatName, DstGV) ||
448 getComdatLeader(SrcM, ComdatName, SrcGV))
449 return true;
450
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000451 const DataLayout &DstDL = DstM.getDataLayout();
452 const DataLayout &SrcDL = SrcM.getDataLayout();
David Majnemerdad0a642014-06-27 18:19:56 +0000453 uint64_t DstSize =
Mehdi Amini46a43552015-03-04 18:43:29 +0000454 DstDL.getTypeAllocSize(DstGV->getType()->getPointerElementType());
David Majnemerdad0a642014-06-27 18:19:56 +0000455 uint64_t SrcSize =
Mehdi Amini46a43552015-03-04 18:43:29 +0000456 SrcDL.getTypeAllocSize(SrcGV->getType()->getPointerElementType());
David Majnemerdad0a642014-06-27 18:19:56 +0000457 if (Result == Comdat::SelectionKind::ExactMatch) {
458 if (SrcGV->getInitializer() != DstGV->getInitializer())
459 return emitError("Linking COMDATs named '" + ComdatName +
460 "': ExactMatch violated!");
461 LinkFromSrc = false;
462 } else if (Result == Comdat::SelectionKind::Largest) {
463 LinkFromSrc = SrcSize > DstSize;
464 } else if (Result == Comdat::SelectionKind::SameSize) {
465 if (SrcSize != DstSize)
466 return emitError("Linking COMDATs named '" + ComdatName +
467 "': SameSize violated!");
468 LinkFromSrc = false;
469 } else {
470 llvm_unreachable("unknown selection kind");
471 }
472 break;
473 }
474 }
475
476 return false;
477}
478
479bool ModuleLinker::getComdatResult(const Comdat *SrcC,
480 Comdat::SelectionKind &Result,
481 bool &LinkFromSrc) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000482 Module &DstM = Mover.getModule();
Rafael Espindolab16196a2014-08-11 17:07:34 +0000483 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
David Majnemerdad0a642014-06-27 18:19:56 +0000484 StringRef ComdatName = SrcC->getName();
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000485 Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
David Majnemerdad0a642014-06-27 18:19:56 +0000486 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000487
Rafael Espindolab16196a2014-08-11 17:07:34 +0000488 if (DstCI == ComdatSymTab.end()) {
489 // Use the comdat if it is only available in one of the modules.
490 LinkFromSrc = true;
491 Result = SSK;
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000492 return false;
Rafael Espindolab16196a2014-08-11 17:07:34 +0000493 }
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000494
495 const Comdat *DstC = &DstCI->second;
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000496 Comdat::SelectionKind DSK = DstC->getSelectionKind();
497 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
498 LinkFromSrc);
David Majnemerdad0a642014-06-27 18:19:56 +0000499}
James Molloyf6f121e2013-05-28 15:17:05 +0000500
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000501bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
502 const GlobalValue &Dest,
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000503 const GlobalValue &Src) {
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +0000504 // Should we unconditionally use the Src?
Artem Belevich020d4fb2015-09-01 17:55:55 +0000505 if (shouldOverrideFromSrc()) {
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +0000506 LinkFromSrc = true;
507 return false;
508 }
509
Rafael Espindola778fcc72014-11-02 13:28:57 +0000510 // We always have to add Src if it has appending linkage.
511 if (Src.hasAppendingLinkage()) {
Teresa Johnson1e20a652015-12-03 18:20:05 +0000512 // Should have prevented importing for appending linkage in linkIfNeeded.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000513 assert(!isPerformingImport());
Rafael Espindola778fcc72014-11-02 13:28:57 +0000514 LinkFromSrc = true;
515 return false;
516 }
517
Rafael Espindolad4bcefc2014-10-24 18:13:04 +0000518 bool SrcIsDeclaration = Src.isDeclarationForLinker();
519 bool DestIsDeclaration = Dest.isDeclarationForLinker();
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000520
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000521 if (isPerformingImport()) {
522 if (isa<Function>(&Src)) {
523 // For functions, LinkFromSrc iff this is the function requested
524 // for importing. For variables, decide below normally.
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000525 LinkFromSrc = ImportFunction->count(&Src);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000526 return false;
527 }
528
529 // Check if this is an alias with an already existing definition
530 // in Dest, which must have come from a prior importing pass from
531 // the same Src module. Unlike imported function and variable
532 // definitions, which are imported as available_externally and are
533 // not definitions for the linker, that is not a valid linkage for
534 // imported aliases which must be definitions. Simply use the existing
535 // Dest copy.
536 if (isa<GlobalAlias>(&Src) && !DestIsDeclaration) {
537 assert(isa<GlobalAlias>(&Dest));
538 LinkFromSrc = false;
539 return false;
540 }
541 }
542
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000543 if (SrcIsDeclaration) {
544 // If Src is external or if both Src & Dest are external.. Just link the
545 // external globals, we aren't adding anything.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000546 if (Src.hasDLLImportStorageClass()) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000547 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000548 LinkFromSrc = DestIsDeclaration;
549 return false;
550 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000551 // If the Dest is weak, use the source linkage.
Rafael Espindolaed11bd22015-12-09 22:44:00 +0000552 if (Dest.hasExternalWeakLinkage()) {
553 LinkFromSrc = true;
554 return false;
555 }
556 // Link an available_externally over a declaration.
557 LinkFromSrc = !Src.isDeclaration() && Dest.isDeclaration();
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000558 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000559 }
560
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000561 if (DestIsDeclaration) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000562 // If Dest is external but Src is not:
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000563 LinkFromSrc = true;
564 return false;
565 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000566
Rafael Espindola09106052014-09-09 15:59:12 +0000567 if (Src.hasCommonLinkage()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000568 if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
569 LinkFromSrc = true;
Rafael Espindola09106052014-09-09 15:59:12 +0000570 return false;
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000571 }
572
573 if (!Dest.hasCommonLinkage()) {
574 LinkFromSrc = false;
575 return false;
576 }
Rafael Espindola09106052014-09-09 15:59:12 +0000577
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000578 const DataLayout &DL = Dest.getParent()->getDataLayout();
Rafael Espindola09106052014-09-09 15:59:12 +0000579 uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
580 uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000581 LinkFromSrc = SrcSize > DestSize;
582 return false;
Rafael Espindola09106052014-09-09 15:59:12 +0000583 }
584
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000585 if (Src.isWeakForLinker()) {
586 assert(!Dest.hasExternalWeakLinkage());
587 assert(!Dest.hasAvailableExternallyLinkage());
Rafael Espindola09106052014-09-09 15:59:12 +0000588
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000589 if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
590 LinkFromSrc = true;
591 return false;
592 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000593
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000594 LinkFromSrc = false;
Rafael Espindola09106052014-09-09 15:59:12 +0000595 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000596 }
597
598 if (Dest.isWeakForLinker()) {
599 assert(Src.hasExternalLinkage());
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000600 LinkFromSrc = true;
601 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000602 }
603
604 assert(!Src.hasExternalWeakLinkage());
605 assert(!Dest.hasExternalWeakLinkage());
606 assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
607 "Unexpected linkage type!");
608 return emitError("Linking globals named '" + Src.getName() +
609 "': symbol multiply defined!");
610}
611
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000612bool ModuleLinker::linkIfNeeded(GlobalValue &GV) {
613 GlobalValue *DGV = getLinkedToGlobal(&GV);
614
615 if (shouldLinkOnlyNeeded() && !(DGV && DGV->isDeclaration()))
616 return false;
617
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000618 if (DGV && !GV.hasLocalLinkage() && !GV.hasAppendingLinkage()) {
619 auto *DGVar = dyn_cast<GlobalVariable>(DGV);
620 auto *SGVar = dyn_cast<GlobalVariable>(&GV);
621 if (DGVar && SGVar) {
622 if (DGVar->isDeclaration() && SGVar->isDeclaration() &&
623 (!DGVar->isConstant() || !SGVar->isConstant())) {
624 DGVar->setConstant(false);
625 SGVar->setConstant(false);
626 }
627 if (DGVar->hasCommonLinkage() && SGVar->hasCommonLinkage()) {
628 unsigned Align = std::max(DGVar->getAlignment(), SGVar->getAlignment());
629 SGVar->setAlignment(Align);
630 DGVar->setAlignment(Align);
631 }
632 }
633
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000634 GlobalValue::VisibilityTypes Visibility =
635 getMinVisibility(DGV->getVisibility(), GV.getVisibility());
636 DGV->setVisibility(Visibility);
637 GV.setVisibility(Visibility);
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000638
639 bool HasUnnamedAddr = GV.hasUnnamedAddr() && DGV->hasUnnamedAddr();
640 DGV->setUnnamedAddr(HasUnnamedAddr);
641 GV.setUnnamedAddr(HasUnnamedAddr);
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000642 }
643
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000644 // Don't want to append to global_ctors list, for example, when we
645 // are importing for ThinLTO, otherwise the global ctors and dtors
646 // get executed multiple times for local variables (the latter causing
647 // double frees).
648 if (GV.hasAppendingLinkage() && isPerformingImport())
649 return false;
650
651 if (isPerformingImport() && !doImportAsDefinition(&GV))
652 return false;
653
654 if (!DGV && !shouldOverrideFromSrc() &&
655 (GV.hasLocalLinkage() || GV.hasLinkOnceLinkage() ||
656 GV.hasAvailableExternallyLinkage()))
657 return false;
658
Rafael Espindolabd03c502015-12-07 16:31:41 +0000659 if (GV.isDeclaration())
660 return false;
661
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000662 if (const Comdat *SC = GV.getComdat()) {
663 bool LinkFromSrc;
664 Comdat::SelectionKind SK;
665 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000666 if (LinkFromSrc)
667 ValuesToLink.insert(&GV);
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000668 return false;
669 }
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000670
671 bool LinkFromSrc = true;
672 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, GV))
673 return true;
674 if (LinkFromSrc)
675 ValuesToLink.insert(&GV);
676 return false;
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000677}
678
Rafael Espindolacaabe222015-12-10 14:19:35 +0000679void ModuleLinker::addLazyFor(GlobalValue &GV, IRMover::ValueAdder Add) {
680 // Add these to the internalize list
681 if (!GV.hasLinkOnceLinkage())
682 return;
683
684 if (shouldInternalizeLinkedSymbols())
685 Internalize.insert(GV.getName());
686 Add(GV);
687
688 const Comdat *SC = GV.getComdat();
689 if (!SC)
690 return;
691 for (GlobalValue *GV2 : ComdatMembers[SC]) {
692 if (!GV2->hasLocalLinkage() && shouldInternalizeLinkedSymbols())
693 Internalize.insert(GV2->getName());
694 Add(*GV2);
695 }
696}
697
698void ModuleLinker::processGlobalForThinLTO(GlobalValue &GV) {
699 if (GV.hasLocalLinkage() &&
700 (doPromoteLocalToGlobal(&GV) || isPerformingImport())) {
701 GV.setName(getName(&GV));
702 GV.setLinkage(getLinkage(&GV));
703 if (!GV.hasLocalLinkage())
704 GV.setVisibility(GlobalValue::HiddenVisibility);
705 if (isModuleExporting())
706 ValuesToLink.insert(&GV);
707 return;
708 }
709 GV.setLinkage(getLinkage(&GV));
710}
711
712void ModuleLinker::processGlobalsForThinLTO() {
713 for (GlobalVariable &GV : SrcM.globals())
714 processGlobalForThinLTO(GV);
715 for (Function &SF : SrcM)
716 processGlobalForThinLTO(SF);
717 for (GlobalAlias &GA : SrcM.aliases())
718 processGlobalForThinLTO(GA);
719}
720
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000721bool ModuleLinker::run() {
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000722 for (const auto &SMEC : SrcM.getComdatSymbolTable()) {
David Majnemerdad0a642014-06-27 18:19:56 +0000723 const Comdat &C = SMEC.getValue();
724 if (ComdatsChosen.count(&C))
725 continue;
726 Comdat::SelectionKind SK;
727 bool LinkFromSrc;
728 if (getComdatResult(&C, SK, LinkFromSrc))
729 return true;
730 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
731 }
732
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000733 for (GlobalVariable &GV : SrcM.globals())
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000734 if (const Comdat *SC = GV.getComdat())
735 ComdatMembers[SC].push_back(&GV);
736
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000737 for (Function &SF : SrcM)
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000738 if (const Comdat *SC = SF.getComdat())
739 ComdatMembers[SC].push_back(&SF);
740
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000741 for (GlobalAlias &GA : SrcM.aliases())
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000742 if (const Comdat *SC = GA.getComdat())
743 ComdatMembers[SC].push_back(&GA);
744
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000745 // Insert all of the globals in src into the DstM module... without linking
746 // initializers (which could refer to functions not yet mapped over).
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000747 for (GlobalVariable &GV : SrcM.globals())
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000748 if (linkIfNeeded(GV))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000749 return true;
750
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000751 for (Function &SF : SrcM)
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000752 if (linkIfNeeded(SF))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000753 return true;
754
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000755 for (GlobalAlias &GA : SrcM.aliases())
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000756 if (linkIfNeeded(GA))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000757 return true;
758
Rafael Espindolacaabe222015-12-10 14:19:35 +0000759 processGlobalsForThinLTO();
760
761 for (unsigned I = 0; I < ValuesToLink.size(); ++I) {
762 GlobalValue *GV = ValuesToLink[I];
763 const Comdat *SC = GV->getComdat();
764 if (!SC)
765 continue;
766 for (GlobalValue *GV2 : ComdatMembers[SC])
767 ValuesToLink.insert(GV2);
Rafael Espindolabeadd562014-12-08 18:05:48 +0000768 }
769
Rafael Espindolacaabe222015-12-10 14:19:35 +0000770 if (shouldInternalizeLinkedSymbols()) {
771 for (GlobalValue *GV : ValuesToLink)
772 Internalize.insert(GV->getName());
773 }
Teresa Johnson10632932015-11-06 17:50:53 +0000774
Rafael Espindolaf81c7b02015-12-10 16:35:06 +0000775 if (Mover.move(SrcM, ValuesToLink.getArrayRef(),
Rafael Espindolacaabe222015-12-10 14:19:35 +0000776 [this](GlobalValue &GV, IRMover::ValueAdder Add) {
777 addLazyFor(GV, Add);
778 }))
Teresa Johnson189b2522015-11-06 17:50:48 +0000779 return true;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000780 Module &DstM = Mover.getModule();
781 for (auto &P : Internalize) {
782 GlobalValue *GV = DstM.getNamedValue(P.first());
783 GV->setLinkage(GlobalValue::InternalLinkage);
784 }
Teresa Johnson189b2522015-11-06 17:50:48 +0000785
Anton Korobeynikov26098882008-03-05 23:21:39 +0000786 return false;
787}
Reid Spencer361e5132004-11-12 20:37:43 +0000788
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000789Linker::Linker(Module &M, DiagnosticHandlerFunction DiagnosticHandler)
Rafael Espindolacaabe222015-12-10 14:19:35 +0000790 : Mover(M, DiagnosticHandler) {}
Rafael Espindola3df61b72013-05-04 03:48:37 +0000791
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000792bool Linker::linkInModule(Module &Src, unsigned Flags,
Mehdi Amini8220e8a2015-11-23 01:59:16 +0000793 const FunctionInfoIndex *Index,
Mehdi Amini7471cf82015-12-03 02:37:30 +0000794 DenseSet<const GlobalValue *> *FunctionsToImport) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000795 ModuleLinker TheLinker(Mover, Src, Flags, Index, FunctionsToImport);
796 return TheLinker.run();
Rafael Espindola3df61b72013-05-04 03:48:37 +0000797}
798
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000799//===----------------------------------------------------------------------===//
800// LinkModules entrypoint.
801//===----------------------------------------------------------------------===//
802
Rafael Espindola18c89412014-10-27 02:35:46 +0000803/// This function links two modules together, with the resulting Dest module
804/// modified to be the composite of the two input modules. If an error occurs,
805/// true is returned and ErrorMsg (if not null) is set to indicate the problem.
806/// Upon failure, the Dest module could be in a modified state, and shouldn't be
807/// relied on to be consistent.
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000808bool Linker::linkModules(Module &Dest, Module &Src,
Artem Belevich020d4fb2015-09-01 17:55:55 +0000809 DiagnosticHandlerFunction DiagnosticHandler,
810 unsigned Flags) {
Rafael Espindola4160f5d2014-10-27 23:02:10 +0000811 Linker L(Dest, DiagnosticHandler);
Artem Belevich020d4fb2015-09-01 17:55:55 +0000812 return L.linkInModule(Src, Flags);
Rafael Espindola4160f5d2014-10-27 23:02:10 +0000813}
814
Teresa Johnsonbae7e752015-12-04 23:40:22 +0000815std::unique_ptr<Module>
816llvm::renameModuleForThinLTO(std::unique_ptr<Module> &M,
817 const FunctionInfoIndex *Index,
818 DiagnosticHandlerFunction DiagnosticHandler) {
819 std::unique_ptr<llvm::Module> RenamedModule(
820 new llvm::Module(M->getModuleIdentifier(), M->getContext()));
821 Linker L(*RenamedModule.get(), DiagnosticHandler);
822 if (L.linkInModule(*M.get(), llvm::Linker::Flags::None, Index))
823 return nullptr;
824 return RenamedModule;
825}
826
Bill Wendlinga3aeb982012-05-09 08:55:40 +0000827//===----------------------------------------------------------------------===//
828// C API.
829//===----------------------------------------------------------------------===//
830
831LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
Juergen Ributzkaa57d5882015-03-02 18:59:38 +0000832 LLVMLinkerMode Unused, char **OutMessages) {
Rafael Espindola98ab63c2014-10-25 04:31:08 +0000833 Module *D = unwrap(Dest);
Rafael Espindola98ab63c2014-10-25 04:31:08 +0000834 std::string Message;
Rafael Espindola4160f5d2014-10-27 23:02:10 +0000835 raw_string_ostream Stream(Message);
836 DiagnosticPrinterRawOStream DP(Stream);
837
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000838 LLVMBool Result = Linker::linkModules(
839 *D, *unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
Rafael Espindola98ab63c2014-10-25 04:31:08 +0000840
Eli Benderskyff715e22015-06-12 23:26:42 +0000841 if (OutMessages && Result) {
842 Stream.flush();
Rafael Espindola98ab63c2014-10-25 04:31:08 +0000843 *OutMessages = strdup(Message.c_str());
Eli Benderskyff715e22015-06-12 23:26:42 +0000844 }
Bill Wendlinga3aeb982012-05-09 08:55:40 +0000845 return Result;
846}