blob: 9c9c0ef321f5f8e5449d8a67f75497dd049e63a0 [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
Rafael Espindolacaabe222015-12-10 14:19:35 +000051 /// Used as the callback for lazy linking.
52 /// The mover has just hit GV and we have to decide if it, and other members
53 /// of the same comdat, should be linked. Every member to be linked is passed
54 /// to Add.
55 void addLazyFor(GlobalValue &GV, IRMover::ValueAdder Add);
Rafael Espindolabaa3bf82015-12-01 15:19:48 +000056
Artem Belevich020d4fb2015-09-01 17:55:55 +000057 bool shouldOverrideFromSrc() { return Flags & Linker::OverrideFromSrc; }
58 bool shouldLinkOnlyNeeded() { return Flags & Linker::LinkOnlyNeeded; }
59 bool shouldInternalizeLinkedSymbols() {
60 return Flags & Linker::InternalizeLinkedSymbols;
61 }
62
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +000063 /// Check if we should promote the given local value to global scope.
64 bool doPromoteLocalToGlobal(const GlobalValue *SGV);
65
Rafael Espindolac84f6082014-11-25 06:11:24 +000066 bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
67 const GlobalValue &Src);
Rafael Espindolaed6dc372014-05-09 14:39:25 +000068
Rafael Espindolacaabe222015-12-10 14:19:35 +000069 /// Should we have mover and linker error diag info?
Rafael Espindolac84f6082014-11-25 06:11:24 +000070 bool emitError(const Twine &Message) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +000071 SrcM.getContext().diagnose(LinkDiagnosticInfo(DS_Error, Message));
Rafael Espindolac84f6082014-11-25 06:11:24 +000072 return true;
73 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +000074
Rafael Espindola0e309fe2015-12-01 19:50:54 +000075 bool getComdatLeader(Module &M, StringRef ComdatName,
Rafael Espindolac84f6082014-11-25 06:11:24 +000076 const GlobalVariable *&GVar);
77 bool computeResultingSelectionKind(StringRef ComdatName,
78 Comdat::SelectionKind Src,
79 Comdat::SelectionKind Dst,
80 Comdat::SelectionKind &Result,
81 bool &LinkFromSrc);
82 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
83 ComdatsChosen;
84 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
85 bool &LinkFromSrc);
Teresa Johnson2d5fb8c2015-11-10 21:09:06 +000086 // Keep track of the global value members of each comdat in source.
87 DenseMap<const Comdat *, std::vector<GlobalValue *>> ComdatMembers;
Rafael Espindola4160f5d2014-10-27 23:02:10 +000088
Rafael Espindolac84f6082014-11-25 06:11:24 +000089 /// Given a global in the source module, return the global in the
90 /// destination module that is being linked to, if any.
91 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
Rafael Espindolacaabe222015-12-10 14:19:35 +000092 Module &DstM = Mover.getModule();
Rafael Espindolac84f6082014-11-25 06:11:24 +000093 // If the source has no name it can't link. If it has local linkage,
94 // there is no name match-up going on.
Teresa Johnsonb098f0c2015-11-24 19:46:58 +000095 if (!SrcGV->hasName() || GlobalValue::isLocalLinkage(getLinkage(SrcGV)))
Rafael Espindolac84f6082014-11-25 06:11:24 +000096 return nullptr;
Eli Bendersky7da92ed2014-02-20 22:19:24 +000097
Rafael Espindolac84f6082014-11-25 06:11:24 +000098 // Otherwise see if we have a match in the destination module's symtab.
Rafael Espindola0e309fe2015-12-01 19:50:54 +000099 GlobalValue *DGV = DstM.getNamedValue(getName(SrcGV));
Rafael Espindolac84f6082014-11-25 06:11:24 +0000100 if (!DGV)
101 return nullptr;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000102
Rafael Espindolac84f6082014-11-25 06:11:24 +0000103 // If we found a global with the same name in the dest module, but it has
104 // internal linkage, we are really not doing any linkage here.
105 if (DGV->hasLocalLinkage())
106 return nullptr;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000107
Rafael Espindolac84f6082014-11-25 06:11:24 +0000108 // Otherwise, we do in fact link to the destination global.
109 return DGV;
110 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000111
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000112 bool linkIfNeeded(GlobalValue &GV);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000113
114 /// Helper methods to check if we are importing from or potentially
115 /// exporting from the current source module.
Teresa Johnson4a9bf582015-12-17 16:34:53 +0000116 bool isPerformingImport() const { return ImportFunction != nullptr; }
117 bool isModuleExporting() const { return HasExportedFunctions; }
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000118
119 /// If we are importing from the source module, checks if we should
120 /// import SGV as a definition, otherwise import as a declaration.
121 bool doImportAsDefinition(const GlobalValue *SGV);
122
123 /// Get the name for SGV that should be used in the linked destination
124 /// module. Specifically, this handles the case where we need to rename
125 /// a local that is being promoted to global scope.
126 std::string getName(const GlobalValue *SGV);
127
Rafael Espindolacaabe222015-12-10 14:19:35 +0000128 /// Process globals so that they can be used in ThinLTO. This includes
129 /// promoting local variables so that they can be reference externally by
130 /// thin lto imported globals and converting strong external globals to
131 /// available_externally.
132 void processGlobalsForThinLTO();
133 void processGlobalForThinLTO(GlobalValue &GV);
134
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000135 /// Get the new linkage for SGV that should be used in the linked destination
136 /// module. Specifically, for ThinLTO importing or exporting it may need
137 /// to be adjusted.
138 GlobalValue::LinkageTypes getLinkage(const GlobalValue *SGV);
139
140 /// Copies the necessary global value attributes and name from the source
141 /// to the newly cloned global value.
142 void copyGVAttributes(GlobalValue *NewGV, const GlobalValue *SrcGV);
143
144 /// Updates the visibility for the new global cloned from the source
145 /// and, if applicable, linked with an existing destination global.
146 /// Handles visibility change required for promoted locals.
147 void setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
148 const GlobalValue *DGV = nullptr);
149
Rafael Espindolad57f9f02015-12-08 14:54:49 +0000150public:
Rafael Espindolacaabe222015-12-10 14:19:35 +0000151 ModuleLinker(IRMover &Mover, Module &SrcM, unsigned Flags,
Rafael Espindolad57f9f02015-12-08 14:54:49 +0000152 const FunctionInfoIndex *Index = nullptr,
153 DenseSet<const GlobalValue *> *FunctionsToImport = nullptr)
Rafael Espindolacaabe222015-12-10 14:19:35 +0000154 : Mover(Mover), SrcM(SrcM), Flags(Flags), ImportIndex(Index),
Rafael Espindolad57f9f02015-12-08 14:54:49 +0000155 ImportFunction(FunctionsToImport) {
156 assert((ImportIndex || !ImportFunction) &&
157 "Expect a FunctionInfoIndex when importing");
158 // If we have a FunctionInfoIndex but no function to import,
159 // then this is the primary module being compiled in a ThinLTO
160 // backend compilation, and we need to see if it has functions that
161 // may be exported to another backend compilation.
162 if (ImportIndex && !ImportFunction)
163 HasExportedFunctions = ImportIndex->hasExportedFunctions(SrcM);
164 }
165
166 bool run();
Rafael Espindolac84f6082014-11-25 06:11:24 +0000167};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000168}
Bill Wendlingd48b7782012-02-28 04:01:21 +0000169
Rafael Espindola18c89412014-10-27 02:35:46 +0000170/// The LLVM SymbolTable class autorenames globals that conflict in the symbol
171/// table. This is good for all clients except for us. Go through the trouble
172/// to force this back.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000173static void forceRenaming(GlobalValue *GV, StringRef Name) {
174 // If the global doesn't force its name or if it already has the right name,
175 // there is nothing for us to do.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000176 // Note that any required local to global promotion should already be done,
177 // so promoted locals will not skip this handling as their linkage is no
178 // longer local.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000179 if (GV->hasLocalLinkage() || GV->getName() == Name)
180 return;
181
182 Module *M = GV->getParent();
Reid Spencer361e5132004-11-12 20:37:43 +0000183
184 // If there is a conflict, rename the conflict.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000185 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
Chris Lattner2a8d2e02007-02-11 00:39:38 +0000186 GV->takeName(ConflictGV);
Rafael Espindolae3a933a2015-12-01 20:11:43 +0000187 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000188 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
Chris Lattner2a8d2e02007-02-11 00:39:38 +0000189 } else {
Rafael Espindolae3a933a2015-12-01 20:11:43 +0000190 GV->setName(Name); // Force the name back
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000191 }
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000192}
Reid Spencer90246aa2007-02-04 04:29:21 +0000193
Rafael Espindola18c89412014-10-27 02:35:46 +0000194/// copy additional attributes (those not needed to construct a GlobalValue)
195/// from the SrcGV to the DestGV.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000196void ModuleLinker::copyGVAttributes(GlobalValue *NewGV,
197 const GlobalValue *SrcGV) {
Rafael Espindola769efe62015-12-02 20:03:17 +0000198 NewGV->copyAttributesFrom(SrcGV);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000199 forceRenaming(NewGV, getName(SrcGV));
Reid Spencer361e5132004-11-12 20:37:43 +0000200}
201
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000202bool ModuleLinker::doImportAsDefinition(const GlobalValue *SGV) {
203 if (!isPerformingImport())
204 return false;
Teresa Johnson3cd81612015-11-10 18:20:11 +0000205 auto *GA = dyn_cast<GlobalAlias>(SGV);
206 if (GA) {
207 if (GA->hasWeakAnyLinkage())
208 return false;
Rafael Espindola89345772015-11-26 19:22:59 +0000209 const GlobalObject *GO = GA->getBaseObject();
210 if (!GO->hasLinkOnceODRLinkage())
211 return false;
212 return doImportAsDefinition(GO);
Teresa Johnson3cd81612015-11-10 18:20:11 +0000213 }
Teresa Johnsondfbebc32015-11-10 18:26:31 +0000214 // Always import GlobalVariable definitions, except for the special
215 // case of WeakAny which are imported as ExternalWeak declarations
216 // (see comments in ModuleLinker::getLinkage). The linkage changes
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000217 // described in ModuleLinker::getLinkage ensure the correct behavior (e.g.
218 // global variables with external linkage are transformed to
Teresa Johnson3cd81612015-11-10 18:20:11 +0000219 // available_externally definitions, which are ultimately turned into
220 // declarations after the EliminateAvailableExternally pass).
Craig Topper66059c92015-11-18 07:07:59 +0000221 if (isa<GlobalVariable>(SGV) && !SGV->isDeclaration() &&
Teresa Johnson3cd81612015-11-10 18:20:11 +0000222 !SGV->hasWeakAnyLinkage())
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000223 return true;
224 // Only import the function requested for importing.
225 auto *SF = dyn_cast<Function>(SGV);
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000226 if (SF && ImportFunction->count(SF))
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000227 return true;
228 // Otherwise no.
229 return false;
230}
231
232bool ModuleLinker::doPromoteLocalToGlobal(const GlobalValue *SGV) {
233 assert(SGV->hasLocalLinkage());
234 // Both the imported references and the original local variable must
235 // be promoted.
236 if (!isPerformingImport() && !isModuleExporting())
237 return false;
238
239 // Local const variables never need to be promoted unless they are address
240 // taken. The imported uses can simply use the clone created in this module.
241 // For now we are conservative in determining which variables are not
242 // address taken by checking the unnamed addr flag. To be more aggressive,
243 // the address taken information must be checked earlier during parsing
244 // of the module and recorded in the function index for use when importing
245 // from that module.
246 auto *GVar = dyn_cast<GlobalVariable>(SGV);
247 if (GVar && GVar->isConstant() && GVar->hasUnnamedAddr())
248 return false;
249
250 // Eventually we only need to promote functions in the exporting module that
251 // are referenced by a potentially exported function (i.e. one that is in the
252 // function index).
253 return true;
254}
255
256std::string ModuleLinker::getName(const GlobalValue *SGV) {
257 // For locals that must be promoted to global scope, ensure that
258 // the promoted name uniquely identifies the copy in the original module,
259 // using the ID assigned during combined index creation. When importing,
260 // we rename all locals (not just those that are promoted) in order to
261 // avoid naming conflicts between locals imported from different modules.
262 if (SGV->hasLocalLinkage() &&
263 (doPromoteLocalToGlobal(SGV) || isPerformingImport()))
264 return FunctionInfoIndex::getGlobalNameForLocal(
265 SGV->getName(),
266 ImportIndex->getModuleId(SGV->getParent()->getModuleIdentifier()));
267 return SGV->getName();
268}
269
270GlobalValue::LinkageTypes ModuleLinker::getLinkage(const GlobalValue *SGV) {
271 // Any local variable that is referenced by an exported function needs
272 // to be promoted to global scope. Since we don't currently know which
273 // functions reference which local variables/functions, we must treat
274 // all as potentially exported if this module is exporting anything.
275 if (isModuleExporting()) {
276 if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
277 return GlobalValue::ExternalLinkage;
278 return SGV->getLinkage();
279 }
280
281 // Otherwise, if we aren't importing, no linkage change is needed.
282 if (!isPerformingImport())
283 return SGV->getLinkage();
284
285 switch (SGV->getLinkage()) {
286 case GlobalValue::ExternalLinkage:
287 // External defnitions are converted to available_externally
288 // definitions upon import, so that they are available for inlining
289 // and/or optimization, but are turned into declarations later
290 // during the EliminateAvailableExternally pass.
Teresa Johnson3cd81612015-11-10 18:20:11 +0000291 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000292 return GlobalValue::AvailableExternallyLinkage;
293 // An imported external declaration stays external.
294 return SGV->getLinkage();
295
296 case GlobalValue::AvailableExternallyLinkage:
297 // An imported available_externally definition converts
298 // to external if imported as a declaration.
299 if (!doImportAsDefinition(SGV))
300 return GlobalValue::ExternalLinkage;
301 // An imported available_externally declaration stays that way.
302 return SGV->getLinkage();
303
304 case GlobalValue::LinkOnceAnyLinkage:
305 case GlobalValue::LinkOnceODRLinkage:
306 // These both stay the same when importing the definition.
307 // The ThinLTO pass will eventually force-import their definitions.
308 return SGV->getLinkage();
309
310 case GlobalValue::WeakAnyLinkage:
311 // Can't import weak_any definitions correctly, or we might change the
312 // program semantics, since the linker will pick the first weak_any
313 // definition and importing would change the order they are seen by the
314 // linker. The module linking caller needs to enforce this.
315 assert(!doImportAsDefinition(SGV));
316 // If imported as a declaration, it becomes external_weak.
317 return GlobalValue::ExternalWeakLinkage;
318
319 case GlobalValue::WeakODRLinkage:
320 // For weak_odr linkage, there is a guarantee that all copies will be
321 // equivalent, so the issue described above for weak_any does not exist,
322 // and the definition can be imported. It can be treated similarly
323 // to an imported externally visible global value.
Teresa Johnson3cd81612015-11-10 18:20:11 +0000324 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000325 return GlobalValue::AvailableExternallyLinkage;
326 else
327 return GlobalValue::ExternalLinkage;
328
329 case GlobalValue::AppendingLinkage:
330 // It would be incorrect to import an appending linkage variable,
331 // since it would cause global constructors/destructors to be
332 // executed multiple times. This should have already been handled
Teresa Johnson1e20a652015-12-03 18:20:05 +0000333 // by linkIfNeeded, and we will assert in shouldLinkFromSource
334 // if we try to import, so we simply return AppendingLinkage here
335 // as this helper is called more widely in getLinkedToGlobal.
336 return GlobalValue::AppendingLinkage;
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000337
338 case GlobalValue::InternalLinkage:
339 case GlobalValue::PrivateLinkage:
340 // If we are promoting the local to global scope, it is handled
341 // similarly to a normal externally visible global.
342 if (doPromoteLocalToGlobal(SGV)) {
Teresa Johnson3cd81612015-11-10 18:20:11 +0000343 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000344 return GlobalValue::AvailableExternallyLinkage;
345 else
346 return GlobalValue::ExternalLinkage;
347 }
348 // A non-promoted imported local definition stays local.
349 // The ThinLTO pass will eventually force-import their definitions.
350 return SGV->getLinkage();
351
352 case GlobalValue::ExternalWeakLinkage:
353 // External weak doesn't apply to definitions, must be a declaration.
354 assert(!doImportAsDefinition(SGV));
355 // Linkage stays external_weak.
356 return SGV->getLinkage();
357
358 case GlobalValue::CommonLinkage:
359 // Linkage stays common on definitions.
360 // The ThinLTO pass will eventually force-import their definitions.
361 return SGV->getLinkage();
362 }
363
364 llvm_unreachable("unknown linkage type");
365}
366
Rafael Espindolaeb5e0a72015-11-29 14:33:06 +0000367static GlobalValue::VisibilityTypes
368getMinVisibility(GlobalValue::VisibilityTypes A,
369 GlobalValue::VisibilityTypes B) {
370 if (A == GlobalValue::HiddenVisibility || B == GlobalValue::HiddenVisibility)
371 return GlobalValue::HiddenVisibility;
372 if (A == GlobalValue::ProtectedVisibility ||
373 B == GlobalValue::ProtectedVisibility)
374 return GlobalValue::ProtectedVisibility;
375 return GlobalValue::DefaultVisibility;
376}
377
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000378void ModuleLinker::setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
379 const GlobalValue *DGV) {
380 GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
381 if (DGV)
Rafael Espindolaeb5e0a72015-11-29 14:33:06 +0000382 Visibility = getMinVisibility(DGV->getVisibility(), Visibility);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000383 // For promoted locals, mark them hidden so that they can later be
384 // stripped from the symbol table to reduce bloat.
385 if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
386 Visibility = GlobalValue::HiddenVisibility;
387 NewGV->setVisibility(Visibility);
388}
389
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000390bool ModuleLinker::getComdatLeader(Module &M, StringRef ComdatName,
David Majnemerdad0a642014-06-27 18:19:56 +0000391 const GlobalVariable *&GVar) {
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000392 const GlobalValue *GVal = M.getNamedValue(ComdatName);
David Majnemerdad0a642014-06-27 18:19:56 +0000393 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
394 GVal = GA->getBaseObject();
395 if (!GVal)
396 // We cannot resolve the size of the aliasee yet.
397 return emitError("Linking COMDATs named '" + ComdatName +
398 "': COMDAT key involves incomputable alias size.");
399 }
400
401 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
402 if (!GVar)
403 return emitError(
404 "Linking COMDATs named '" + ComdatName +
405 "': GlobalVariable required for data dependent selection!");
406
407 return false;
408}
409
410bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
411 Comdat::SelectionKind Src,
412 Comdat::SelectionKind Dst,
413 Comdat::SelectionKind &Result,
414 bool &LinkFromSrc) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000415 Module &DstM = Mover.getModule();
David Majnemerdad0a642014-06-27 18:19:56 +0000416 // The ability to mix Comdat::SelectionKind::Any with
417 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
418 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
419 Dst == Comdat::SelectionKind::Largest;
420 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
421 Src == Comdat::SelectionKind::Largest;
422 if (DstAnyOrLargest && SrcAnyOrLargest) {
423 if (Dst == Comdat::SelectionKind::Largest ||
424 Src == Comdat::SelectionKind::Largest)
425 Result = Comdat::SelectionKind::Largest;
426 else
427 Result = Comdat::SelectionKind::Any;
428 } else if (Src == Dst) {
429 Result = Dst;
430 } else {
431 return emitError("Linking COMDATs named '" + ComdatName +
432 "': invalid selection kinds!");
433 }
434
435 switch (Result) {
436 case Comdat::SelectionKind::Any:
437 // Go with Dst.
438 LinkFromSrc = false;
439 break;
440 case Comdat::SelectionKind::NoDuplicates:
441 return emitError("Linking COMDATs named '" + ComdatName +
442 "': noduplicates has been violated!");
443 case Comdat::SelectionKind::ExactMatch:
444 case Comdat::SelectionKind::Largest:
445 case Comdat::SelectionKind::SameSize: {
446 const GlobalVariable *DstGV;
447 const GlobalVariable *SrcGV;
448 if (getComdatLeader(DstM, ComdatName, DstGV) ||
449 getComdatLeader(SrcM, ComdatName, SrcGV))
450 return true;
451
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000452 const DataLayout &DstDL = DstM.getDataLayout();
453 const DataLayout &SrcDL = SrcM.getDataLayout();
David Majnemerdad0a642014-06-27 18:19:56 +0000454 uint64_t DstSize =
Mehdi Amini46a43552015-03-04 18:43:29 +0000455 DstDL.getTypeAllocSize(DstGV->getType()->getPointerElementType());
David Majnemerdad0a642014-06-27 18:19:56 +0000456 uint64_t SrcSize =
Mehdi Amini46a43552015-03-04 18:43:29 +0000457 SrcDL.getTypeAllocSize(SrcGV->getType()->getPointerElementType());
David Majnemerdad0a642014-06-27 18:19:56 +0000458 if (Result == Comdat::SelectionKind::ExactMatch) {
459 if (SrcGV->getInitializer() != DstGV->getInitializer())
460 return emitError("Linking COMDATs named '" + ComdatName +
461 "': ExactMatch violated!");
462 LinkFromSrc = false;
463 } else if (Result == Comdat::SelectionKind::Largest) {
464 LinkFromSrc = SrcSize > DstSize;
465 } else if (Result == Comdat::SelectionKind::SameSize) {
466 if (SrcSize != DstSize)
467 return emitError("Linking COMDATs named '" + ComdatName +
468 "': SameSize violated!");
469 LinkFromSrc = false;
470 } else {
471 llvm_unreachable("unknown selection kind");
472 }
473 break;
474 }
475 }
476
477 return false;
478}
479
480bool ModuleLinker::getComdatResult(const Comdat *SrcC,
481 Comdat::SelectionKind &Result,
482 bool &LinkFromSrc) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000483 Module &DstM = Mover.getModule();
Rafael Espindolab16196a2014-08-11 17:07:34 +0000484 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
David Majnemerdad0a642014-06-27 18:19:56 +0000485 StringRef ComdatName = SrcC->getName();
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000486 Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
David Majnemerdad0a642014-06-27 18:19:56 +0000487 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000488
Rafael Espindolab16196a2014-08-11 17:07:34 +0000489 if (DstCI == ComdatSymTab.end()) {
490 // Use the comdat if it is only available in one of the modules.
491 LinkFromSrc = true;
492 Result = SSK;
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000493 return false;
Rafael Espindolab16196a2014-08-11 17:07:34 +0000494 }
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000495
496 const Comdat *DstC = &DstCI->second;
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000497 Comdat::SelectionKind DSK = DstC->getSelectionKind();
498 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
499 LinkFromSrc);
David Majnemerdad0a642014-06-27 18:19:56 +0000500}
James Molloyf6f121e2013-05-28 15:17:05 +0000501
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000502bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
503 const GlobalValue &Dest,
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000504 const GlobalValue &Src) {
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +0000505 // Should we unconditionally use the Src?
Artem Belevich020d4fb2015-09-01 17:55:55 +0000506 if (shouldOverrideFromSrc()) {
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +0000507 LinkFromSrc = true;
508 return false;
509 }
510
Rafael Espindola778fcc72014-11-02 13:28:57 +0000511 // We always have to add Src if it has appending linkage.
512 if (Src.hasAppendingLinkage()) {
Teresa Johnson1e20a652015-12-03 18:20:05 +0000513 // Should have prevented importing for appending linkage in linkIfNeeded.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000514 assert(!isPerformingImport());
Rafael Espindola778fcc72014-11-02 13:28:57 +0000515 LinkFromSrc = true;
516 return false;
517 }
518
Rafael Espindolad4bcefc2014-10-24 18:13:04 +0000519 bool SrcIsDeclaration = Src.isDeclarationForLinker();
520 bool DestIsDeclaration = Dest.isDeclarationForLinker();
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000521
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000522 if (isPerformingImport()) {
523 if (isa<Function>(&Src)) {
524 // For functions, LinkFromSrc iff this is the function requested
525 // for importing. For variables, decide below normally.
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000526 LinkFromSrc = ImportFunction->count(&Src);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000527 return false;
528 }
529
530 // Check if this is an alias with an already existing definition
531 // in Dest, which must have come from a prior importing pass from
532 // the same Src module. Unlike imported function and variable
533 // definitions, which are imported as available_externally and are
534 // not definitions for the linker, that is not a valid linkage for
535 // imported aliases which must be definitions. Simply use the existing
536 // Dest copy.
537 if (isa<GlobalAlias>(&Src) && !DestIsDeclaration) {
538 assert(isa<GlobalAlias>(&Dest));
539 LinkFromSrc = false;
540 return false;
541 }
542 }
543
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000544 if (SrcIsDeclaration) {
545 // If Src is external or if both Src & Dest are external.. Just link the
546 // external globals, we aren't adding anything.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000547 if (Src.hasDLLImportStorageClass()) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000548 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000549 LinkFromSrc = DestIsDeclaration;
550 return false;
551 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000552 // If the Dest is weak, use the source linkage.
Rafael Espindolaed11bd22015-12-09 22:44:00 +0000553 if (Dest.hasExternalWeakLinkage()) {
554 LinkFromSrc = true;
555 return false;
556 }
557 // Link an available_externally over a declaration.
558 LinkFromSrc = !Src.isDeclaration() && Dest.isDeclaration();
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000559 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000560 }
561
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000562 if (DestIsDeclaration) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000563 // If Dest is external but Src is not:
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000564 LinkFromSrc = true;
565 return false;
566 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000567
Rafael Espindola09106052014-09-09 15:59:12 +0000568 if (Src.hasCommonLinkage()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000569 if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
570 LinkFromSrc = true;
Rafael Espindola09106052014-09-09 15:59:12 +0000571 return false;
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000572 }
573
574 if (!Dest.hasCommonLinkage()) {
575 LinkFromSrc = false;
576 return false;
577 }
Rafael Espindola09106052014-09-09 15:59:12 +0000578
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000579 const DataLayout &DL = Dest.getParent()->getDataLayout();
Rafael Espindola09106052014-09-09 15:59:12 +0000580 uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
581 uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000582 LinkFromSrc = SrcSize > DestSize;
583 return false;
Rafael Espindola09106052014-09-09 15:59:12 +0000584 }
585
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000586 if (Src.isWeakForLinker()) {
587 assert(!Dest.hasExternalWeakLinkage());
588 assert(!Dest.hasAvailableExternallyLinkage());
Rafael Espindola09106052014-09-09 15:59:12 +0000589
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000590 if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
591 LinkFromSrc = true;
592 return false;
593 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000594
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000595 LinkFromSrc = false;
Rafael Espindola09106052014-09-09 15:59:12 +0000596 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000597 }
598
599 if (Dest.isWeakForLinker()) {
600 assert(Src.hasExternalLinkage());
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000601 LinkFromSrc = true;
602 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000603 }
604
605 assert(!Src.hasExternalWeakLinkage());
606 assert(!Dest.hasExternalWeakLinkage());
607 assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
608 "Unexpected linkage type!");
609 return emitError("Linking globals named '" + Src.getName() +
610 "': symbol multiply defined!");
611}
612
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000613bool ModuleLinker::linkIfNeeded(GlobalValue &GV) {
614 GlobalValue *DGV = getLinkedToGlobal(&GV);
615
616 if (shouldLinkOnlyNeeded() && !(DGV && DGV->isDeclaration()))
617 return false;
618
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000619 if (DGV && !GV.hasLocalLinkage() && !GV.hasAppendingLinkage()) {
620 auto *DGVar = dyn_cast<GlobalVariable>(DGV);
621 auto *SGVar = dyn_cast<GlobalVariable>(&GV);
622 if (DGVar && SGVar) {
623 if (DGVar->isDeclaration() && SGVar->isDeclaration() &&
624 (!DGVar->isConstant() || !SGVar->isConstant())) {
625 DGVar->setConstant(false);
626 SGVar->setConstant(false);
627 }
628 if (DGVar->hasCommonLinkage() && SGVar->hasCommonLinkage()) {
629 unsigned Align = std::max(DGVar->getAlignment(), SGVar->getAlignment());
630 SGVar->setAlignment(Align);
631 DGVar->setAlignment(Align);
632 }
633 }
634
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000635 GlobalValue::VisibilityTypes Visibility =
636 getMinVisibility(DGV->getVisibility(), GV.getVisibility());
637 DGV->setVisibility(Visibility);
638 GV.setVisibility(Visibility);
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000639
640 bool HasUnnamedAddr = GV.hasUnnamedAddr() && DGV->hasUnnamedAddr();
641 DGV->setUnnamedAddr(HasUnnamedAddr);
642 GV.setUnnamedAddr(HasUnnamedAddr);
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000643 }
644
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000645 // Don't want to append to global_ctors list, for example, when we
646 // are importing for ThinLTO, otherwise the global ctors and dtors
647 // get executed multiple times for local variables (the latter causing
648 // double frees).
649 if (GV.hasAppendingLinkage() && isPerformingImport())
650 return false;
651
652 if (isPerformingImport() && !doImportAsDefinition(&GV))
653 return false;
654
655 if (!DGV && !shouldOverrideFromSrc() &&
656 (GV.hasLocalLinkage() || GV.hasLinkOnceLinkage() ||
657 GV.hasAvailableExternallyLinkage()))
658 return false;
659
Rafael Espindolabd03c502015-12-07 16:31:41 +0000660 if (GV.isDeclaration())
661 return false;
662
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000663 if (const Comdat *SC = GV.getComdat()) {
664 bool LinkFromSrc;
665 Comdat::SelectionKind SK;
666 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000667 if (LinkFromSrc)
668 ValuesToLink.insert(&GV);
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000669 return false;
670 }
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000671
672 bool LinkFromSrc = true;
673 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, GV))
674 return true;
675 if (LinkFromSrc)
676 ValuesToLink.insert(&GV);
677 return false;
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000678}
679
Rafael Espindolacaabe222015-12-10 14:19:35 +0000680void ModuleLinker::addLazyFor(GlobalValue &GV, IRMover::ValueAdder Add) {
681 // Add these to the internalize list
682 if (!GV.hasLinkOnceLinkage())
683 return;
684
685 if (shouldInternalizeLinkedSymbols())
686 Internalize.insert(GV.getName());
687 Add(GV);
688
689 const Comdat *SC = GV.getComdat();
690 if (!SC)
691 return;
692 for (GlobalValue *GV2 : ComdatMembers[SC]) {
693 if (!GV2->hasLocalLinkage() && shouldInternalizeLinkedSymbols())
694 Internalize.insert(GV2->getName());
695 Add(*GV2);
696 }
697}
698
699void ModuleLinker::processGlobalForThinLTO(GlobalValue &GV) {
700 if (GV.hasLocalLinkage() &&
701 (doPromoteLocalToGlobal(&GV) || isPerformingImport())) {
702 GV.setName(getName(&GV));
703 GV.setLinkage(getLinkage(&GV));
704 if (!GV.hasLocalLinkage())
705 GV.setVisibility(GlobalValue::HiddenVisibility);
706 if (isModuleExporting())
707 ValuesToLink.insert(&GV);
708 return;
709 }
710 GV.setLinkage(getLinkage(&GV));
711}
712
713void ModuleLinker::processGlobalsForThinLTO() {
714 for (GlobalVariable &GV : SrcM.globals())
715 processGlobalForThinLTO(GV);
716 for (Function &SF : SrcM)
717 processGlobalForThinLTO(SF);
718 for (GlobalAlias &GA : SrcM.aliases())
719 processGlobalForThinLTO(GA);
720}
721
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000722bool ModuleLinker::run() {
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000723 for (const auto &SMEC : SrcM.getComdatSymbolTable()) {
David Majnemerdad0a642014-06-27 18:19:56 +0000724 const Comdat &C = SMEC.getValue();
725 if (ComdatsChosen.count(&C))
726 continue;
727 Comdat::SelectionKind SK;
728 bool LinkFromSrc;
729 if (getComdatResult(&C, SK, LinkFromSrc))
730 return true;
731 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
732 }
733
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000734 for (GlobalVariable &GV : SrcM.globals())
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000735 if (const Comdat *SC = GV.getComdat())
736 ComdatMembers[SC].push_back(&GV);
737
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000738 for (Function &SF : SrcM)
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000739 if (const Comdat *SC = SF.getComdat())
740 ComdatMembers[SC].push_back(&SF);
741
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000742 for (GlobalAlias &GA : SrcM.aliases())
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000743 if (const Comdat *SC = GA.getComdat())
744 ComdatMembers[SC].push_back(&GA);
745
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000746 // Insert all of the globals in src into the DstM module... without linking
747 // initializers (which could refer to functions not yet mapped over).
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000748 for (GlobalVariable &GV : SrcM.globals())
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000749 if (linkIfNeeded(GV))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000750 return true;
751
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000752 for (Function &SF : SrcM)
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000753 if (linkIfNeeded(SF))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000754 return true;
755
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000756 for (GlobalAlias &GA : SrcM.aliases())
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000757 if (linkIfNeeded(GA))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000758 return true;
759
Rafael Espindolacaabe222015-12-10 14:19:35 +0000760 processGlobalsForThinLTO();
761
762 for (unsigned I = 0; I < ValuesToLink.size(); ++I) {
763 GlobalValue *GV = ValuesToLink[I];
764 const Comdat *SC = GV->getComdat();
765 if (!SC)
766 continue;
767 for (GlobalValue *GV2 : ComdatMembers[SC])
768 ValuesToLink.insert(GV2);
Rafael Espindolabeadd562014-12-08 18:05:48 +0000769 }
770
Rafael Espindolacaabe222015-12-10 14:19:35 +0000771 if (shouldInternalizeLinkedSymbols()) {
772 for (GlobalValue *GV : ValuesToLink)
773 Internalize.insert(GV->getName());
774 }
Teresa Johnson10632932015-11-06 17:50:53 +0000775
Rafael Espindolaf81c7b02015-12-10 16:35:06 +0000776 if (Mover.move(SrcM, ValuesToLink.getArrayRef(),
Rafael Espindolacaabe222015-12-10 14:19:35 +0000777 [this](GlobalValue &GV, IRMover::ValueAdder Add) {
778 addLazyFor(GV, Add);
779 }))
Teresa Johnson189b2522015-11-06 17:50:48 +0000780 return true;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000781 Module &DstM = Mover.getModule();
782 for (auto &P : Internalize) {
783 GlobalValue *GV = DstM.getNamedValue(P.first());
784 GV->setLinkage(GlobalValue::InternalLinkage);
785 }
Teresa Johnson189b2522015-11-06 17:50:48 +0000786
Anton Korobeynikov26098882008-03-05 23:21:39 +0000787 return false;
788}
Reid Spencer361e5132004-11-12 20:37:43 +0000789
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000790Linker::Linker(Module &M) : Mover(M) {}
Rafael Espindola3df61b72013-05-04 03:48:37 +0000791
Rafael Espindola434e9562015-12-16 23:16:33 +0000792bool Linker::linkInModule(std::unique_ptr<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 Espindola434e9562015-12-16 23:16:33 +0000795 ModuleLinker TheLinker(Mover, *Src, Flags, Index, FunctionsToImport);
796 return TheLinker.run();
797}
798
799bool Linker::linkInModuleForCAPI(Module &Src) {
800 ModuleLinker TheLinker(Mover, Src, 0, nullptr, nullptr);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000801 return TheLinker.run();
Rafael Espindola3df61b72013-05-04 03:48:37 +0000802}
803
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000804//===----------------------------------------------------------------------===//
805// LinkModules entrypoint.
806//===----------------------------------------------------------------------===//
807
Rafael Espindola18c89412014-10-27 02:35:46 +0000808/// This function links two modules together, with the resulting Dest module
809/// modified to be the composite of the two input modules. If an error occurs,
810/// true is returned and ErrorMsg (if not null) is set to indicate the problem.
811/// Upon failure, the Dest module could be in a modified state, and shouldn't be
812/// relied on to be consistent.
Rafael Espindola434e9562015-12-16 23:16:33 +0000813bool Linker::linkModules(Module &Dest, std::unique_ptr<Module> Src,
814 unsigned Flags) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000815 Linker L(Dest);
Rafael Espindola434e9562015-12-16 23:16:33 +0000816 return L.linkInModule(std::move(Src), Flags);
Rafael Espindola4160f5d2014-10-27 23:02:10 +0000817}
818
Teresa Johnsonbae7e752015-12-04 23:40:22 +0000819std::unique_ptr<Module>
Rafael Espindola434e9562015-12-16 23:16:33 +0000820llvm::renameModuleForThinLTO(std::unique_ptr<Module> M,
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000821 const FunctionInfoIndex *Index) {
Teresa Johnsonbae7e752015-12-04 23:40:22 +0000822 std::unique_ptr<llvm::Module> RenamedModule(
823 new llvm::Module(M->getModuleIdentifier(), M->getContext()));
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000824 Linker L(*RenamedModule.get());
Rafael Espindola434e9562015-12-16 23:16:33 +0000825 if (L.linkInModule(std::move(M), llvm::Linker::Flags::None, Index))
Teresa Johnsonbae7e752015-12-04 23:40:22 +0000826 return nullptr;
827 return RenamedModule;
828}
829
Bill Wendlinga3aeb982012-05-09 08:55:40 +0000830//===----------------------------------------------------------------------===//
831// C API.
832//===----------------------------------------------------------------------===//
833
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000834static void diagnosticHandler(const DiagnosticInfo &DI, void *C) {
835 auto *Message = reinterpret_cast<std::string *>(C);
836 raw_string_ostream Stream(*Message);
837 DiagnosticPrinterRawOStream DP(Stream);
838 DI.print(DP);
839}
840
Bill Wendlinga3aeb982012-05-09 08:55:40 +0000841LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
Juergen Ributzkaa57d5882015-03-02 18:59:38 +0000842 LLVMLinkerMode Unused, char **OutMessages) {
Rafael Espindola98ab63c2014-10-25 04:31:08 +0000843 Module *D = unwrap(Dest);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000844 LLVMContext &Ctx = D->getContext();
845
846 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
847 Ctx.getDiagnosticHandler();
848 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
Rafael Espindola98ab63c2014-10-25 04:31:08 +0000849 std::string Message;
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000850 Ctx.setDiagnosticHandler(diagnosticHandler, &Message, true);
Rafael Espindola4160f5d2014-10-27 23:02:10 +0000851
Rafael Espindola434e9562015-12-16 23:16:33 +0000852 Linker L(*D);
853 Module *M = unwrap(Src);
854 LLVMBool Result = L.linkInModuleForCAPI(*M);
Rafael Espindola98ab63c2014-10-25 04:31:08 +0000855
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000856 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext, true);
857
858 if (OutMessages && Result)
Rafael Espindola98ab63c2014-10-25 04:31:08 +0000859 *OutMessages = strdup(Message.c_str());
Bill Wendlinga3aeb982012-05-09 08:55:40 +0000860 return Result;
861}
Rafael Espindola434e9562015-12-16 23:16:33 +0000862
863LLVMBool LLVMLinkModules2(LLVMModuleRef Dest, LLVMModuleRef Src) {
864 Module *D = unwrap(Dest);
865 std::unique_ptr<Module> M(unwrap(Src));
866 return Linker::linkModules(*D, std::move(M));
867}