blob: 74ca197ddb3cf38bad3466a7b5bedb7afbf18630 [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"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm-c/Linker.h"
Rafael Espindola31ad4682014-12-03 22:36:37 +000016#include "llvm/ADT/Hashing.h"
Rafael Espindola23f8d642012-01-05 23:02:01 +000017#include "llvm/ADT/Optional.h"
Bill Wendling66f02412012-02-11 11:38:06 +000018#include "llvm/ADT/SetVector.h"
Eli Bendersky0f7fd362013-03-19 15:26:24 +000019#include "llvm/ADT/SmallString.h"
Rafael Espindola31ad4682014-12-03 22:36:37 +000020#include "llvm/ADT/Statistic.h"
Akira Hatanakac43df512015-02-13 00:40:41 +000021#include "llvm/ADT/Triple.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smithfda0cee2014-12-18 01:05:33 +000023#include "llvm/IR/DebugInfo.h"
Rafael Espindolad12b4a32014-10-25 04:06:10 +000024#include "llvm/IR/DiagnosticInfo.h"
25#include "llvm/IR/DiagnosticPrinter.h"
26#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Module.h"
Chandler Carruthdcb603f2013-01-07 15:43:51 +000028#include "llvm/IR/TypeFinder.h"
Eli Benderskye17f3702014-02-06 18:01:56 +000029#include "llvm/Support/CommandLine.h"
Bill Wendlingb6af2f32012-03-22 20:28:27 +000030#include "llvm/Support/Debug.h"
Bill Wendlingb6af2f32012-03-22 20:28:27 +000031#include "llvm/Support/raw_ostream.h"
Tanya Lattnercbb91402011-10-11 00:24:54 +000032#include "llvm/Transforms/Utils/Cloning.h"
Will Dietz981af002013-10-12 00:55:57 +000033#include <cctype>
David Majnemer82d6ff62014-06-27 18:38:12 +000034#include <tuple>
Reid Spencer361e5132004-11-12 20:37:43 +000035using namespace llvm;
36
Eli Benderskye17f3702014-02-06 18:01:56 +000037
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000038//===----------------------------------------------------------------------===//
39// TypeMap implementation.
40//===----------------------------------------------------------------------===//
Reid Spencer361e5132004-11-12 20:37:43 +000041
Chris Lattnereee6f992008-06-16 21:00:18 +000042namespace {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000043class TypeMapTy : public ValueMapTypeRemapper {
Rafael Espindola18c89412014-10-27 02:35:46 +000044 /// This is a mapping from a source type to a destination type to use.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000045 DenseMap<Type*, Type*> MappedTypes;
Mikhail Glushenkov766d4892009-03-03 07:22:23 +000046
Rafael Espindola18c89412014-10-27 02:35:46 +000047 /// When checking to see if two subgraphs are isomorphic, we speculatively
48 /// add types to MappedTypes, but keep track of them here in case we need to
49 /// roll back.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000050 SmallVector<Type*, 16> SpeculativeTypes;
Rafael Espindolaed6dc372014-05-09 14:39:25 +000051
Rafael Espindolaa96f2352014-11-28 16:41:24 +000052 SmallVector<StructType*, 16> SpeculativeDstOpaqueTypes;
53
Rafael Espindola18c89412014-10-27 02:35:46 +000054 /// This is a list of non-opaque structs in the source module that are mapped
55 /// to an opaque struct in the destination module.
Chris Lattner5e3bd972011-12-20 00:03:52 +000056 SmallVector<StructType*, 16> SrcDefinitionsToResolve;
Rafael Espindolaed6dc372014-05-09 14:39:25 +000057
Rafael Espindola18c89412014-10-27 02:35:46 +000058 /// This is the set of opaque types in the destination modules who are
59 /// getting a body from the source module.
Chris Lattner5e3bd972011-12-20 00:03:52 +000060 SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
Bill Wendling8c2cc412012-03-22 20:30:41 +000061
Chris Lattner56cdea62008-06-16 23:06:51 +000062public:
Rafael Espindola31ad4682014-12-03 22:36:37 +000063 TypeMapTy(Linker::IdentifiedStructTypeSet &DstStructTypesSet)
64 : DstStructTypesSet(DstStructTypesSet) {}
Rafael Espindolaaa9918a2013-05-04 05:05:18 +000065
Rafael Espindola31ad4682014-12-03 22:36:37 +000066 Linker::IdentifiedStructTypeSet &DstStructTypesSet;
Rafael Espindola18c89412014-10-27 02:35:46 +000067 /// Indicate that the specified type in the destination module is conceptually
68 /// equivalent to the specified type in the source module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000069 void addTypeMapping(Type *DstTy, Type *SrcTy);
70
Rafael Espindolad2a13a22014-11-25 04:28:31 +000071 /// Produce a body for an opaque type in the dest module from a type
72 /// definition in the source module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000073 void linkDefinedTypeBodies();
Rafael Espindolaed6dc372014-05-09 14:39:25 +000074
Rafael Espindola18c89412014-10-27 02:35:46 +000075 /// Return the mapped type to use for the specified input type from the
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000076 /// source module.
77 Type *get(Type *SrcTy);
Rafael Espindola31ad4682014-12-03 22:36:37 +000078 Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
79
80 void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000081
Rafael Espindola290e2cc2014-11-25 14:35:53 +000082 FunctionType *get(FunctionType *T) {
83 return cast<FunctionType>(get((Type *)T));
84 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000085
Rafael Espindola18c89412014-10-27 02:35:46 +000086 /// Dump out the type map for debugging purposes.
Bill Wendlingb6af2f32012-03-22 20:28:27 +000087 void dump() const {
Rafael Espindola8f144712014-11-25 06:16:27 +000088 for (auto &Pair : MappedTypes) {
Bill Wendlingb6af2f32012-03-22 20:28:27 +000089 dbgs() << "TypeMap: ";
Rafael Espindola8f144712014-11-25 06:16:27 +000090 Pair.first->print(dbgs());
Bill Wendlingb6af2f32012-03-22 20:28:27 +000091 dbgs() << " => ";
Rafael Espindola8f144712014-11-25 06:16:27 +000092 Pair.second->print(dbgs());
Bill Wendlingb6af2f32012-03-22 20:28:27 +000093 dbgs() << '\n';
94 }
95 }
Bill Wendlingb6af2f32012-03-22 20:28:27 +000096
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000097private:
Rafael Espindola290e2cc2014-11-25 14:35:53 +000098 Type *remapType(Type *SrcTy) override { return get(SrcTy); }
Rafael Espindolaed6dc372014-05-09 14:39:25 +000099
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000100 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
Chris Lattnereee6f992008-06-16 21:00:18 +0000101};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000102}
Chris Lattnereee6f992008-06-16 21:00:18 +0000103
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000104void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
Rafael Espindola3d097412014-11-28 16:26:14 +0000105 assert(SpeculativeTypes.empty());
Rafael Espindolaa96f2352014-11-28 16:41:24 +0000106 assert(SpeculativeDstOpaqueTypes.empty());
Rafael Espindola3d097412014-11-28 16:26:14 +0000107
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000108 // Check to see if these types are recursively isomorphic and establish a
109 // mapping between them if so.
Duncan P. N. Exon Smithc586eaa2014-11-27 17:01:10 +0000110 if (!areTypesIsomorphic(DstTy, SrcTy)) {
111 // Oops, they aren't isomorphic. Just discard this request by rolling out
112 // any speculative mappings we've established.
Rafael Espindola3d097412014-11-28 16:26:14 +0000113 for (Type *Ty : SpeculativeTypes)
114 MappedTypes.erase(Ty);
Rafael Espindolaa96f2352014-11-28 16:41:24 +0000115
116 SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
117 SpeculativeDstOpaqueTypes.size());
118 for (StructType *Ty : SpeculativeDstOpaqueTypes)
119 DstResolvedOpaqueTypes.erase(Ty);
Rafael Espindola04a74af2014-12-01 04:15:59 +0000120 } else {
121 for (Type *Ty : SpeculativeTypes)
122 if (auto *STy = dyn_cast<StructType>(Ty))
123 if (STy->hasName())
124 STy->setName("");
Bill Wendlingd48b7782012-02-28 04:01:21 +0000125 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000126 SpeculativeTypes.clear();
Rafael Espindolaa96f2352014-11-28 16:41:24 +0000127 SpeculativeDstOpaqueTypes.clear();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000128}
Chris Lattnereee6f992008-06-16 21:00:18 +0000129
Rafael Espindola18c89412014-10-27 02:35:46 +0000130/// Recursively walk this pair of types, returning true if they are isomorphic,
131/// false if they are not.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000132bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
133 // Two types with differing kinds are clearly not isomorphic.
Rafael Espindola290e2cc2014-11-25 14:35:53 +0000134 if (DstTy->getTypeID() != SrcTy->getTypeID())
135 return false;
Misha Brukman10468d82005-04-21 22:55:34 +0000136
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000137 // If we have an entry in the MappedTypes table, then we have our answer.
138 Type *&Entry = MappedTypes[SrcTy];
139 if (Entry)
140 return Entry == DstTy;
Misha Brukman10468d82005-04-21 22:55:34 +0000141
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000142 // Two identical types are clearly isomorphic. Remember this
143 // non-speculatively.
144 if (DstTy == SrcTy) {
145 Entry = DstTy;
Chris Lattnerfe677e92008-06-16 20:03:01 +0000146 return true;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000147 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000148
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000149 // Okay, we have two types with identical kinds that we haven't seen before.
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000150
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000151 // If this is an opaque struct type, special case it.
152 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
153 // Mapping an opaque type to any struct, just keep the dest struct.
154 if (SSTy->isOpaque()) {
155 Entry = DstTy;
156 SpeculativeTypes.push_back(SrcTy);
Reid Spencer361e5132004-11-12 20:37:43 +0000157 return true;
Chris Lattner9be15892008-06-16 21:17:12 +0000158 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000159
Chris Lattner5e3bd972011-12-20 00:03:52 +0000160 // Mapping a non-opaque source type to an opaque dest. If this is the first
161 // type that we're mapping onto this destination type then we succeed. Keep
Rafael Espindolaa96f2352014-11-28 16:41:24 +0000162 // the dest, but fill it in later. If this is the second (different) type
163 // that we're trying to map onto the same opaque type then we fail.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000164 if (cast<StructType>(DstTy)->isOpaque()) {
Chris Lattner5e3bd972011-12-20 00:03:52 +0000165 // We can only map one source type onto the opaque destination type.
David Blaikie70573dc2014-11-19 07:49:26 +0000166 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
Chris Lattner5e3bd972011-12-20 00:03:52 +0000167 return false;
168 SrcDefinitionsToResolve.push_back(SSTy);
Rafael Espindolaa96f2352014-11-28 16:41:24 +0000169 SpeculativeTypes.push_back(SrcTy);
170 SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000171 Entry = DstTy;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000172 return true;
173 }
174 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000175
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000176 // If the number of subtypes disagree between the two types, then we fail.
177 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
Reid Spencer361e5132004-11-12 20:37:43 +0000178 return false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000179
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000180 // Fail if any of the extra properties (e.g. array size) of the type disagree.
181 if (isa<IntegerType>(DstTy))
182 return false; // bitwidth disagrees.
183 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
184 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
185 return false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000186
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000187 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
188 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
189 return false;
190 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
191 StructType *SSTy = cast<StructType>(SrcTy);
Chris Lattner44f7ab42011-08-12 18:07:26 +0000192 if (DSTy->isLiteral() != SSTy->isLiteral() ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000193 DSTy->isPacked() != SSTy->isPacked())
194 return false;
195 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
196 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
197 return false;
198 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
Joey Gouly5fad3e92013-01-10 10:49:36 +0000199 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000200 return false;
Reid Spencer361e5132004-11-12 20:37:43 +0000201 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000202
203 // Otherwise, we speculate that these two types will line up and recursively
204 // check the subelements.
205 Entry = DstTy;
206 SpeculativeTypes.push_back(SrcTy);
207
Rafael Espindola290e2cc2014-11-25 14:35:53 +0000208 for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
209 if (!areTypesIsomorphic(DstTy->getContainedType(I),
210 SrcTy->getContainedType(I)))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000211 return false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000212
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000213 // If everything seems to have lined up, then everything is great.
214 return true;
215}
216
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000217void TypeMapTy::linkDefinedTypeBodies() {
218 SmallVector<Type*, 16> Elements;
Rafael Espindolac81c3f52014-11-25 15:33:40 +0000219 for (StructType *SrcSTy : SrcDefinitionsToResolve) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000220 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
Rafael Espindolac81c3f52014-11-25 15:33:40 +0000221 assert(DstSTy->isOpaque());
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000222
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000223 // Map the body of the source type over to a new body for the dest type.
224 Elements.resize(SrcSTy->getNumElements());
Rafael Espindola290e2cc2014-11-25 14:35:53 +0000225 for (unsigned I = 0, E = Elements.size(); I != E; ++I)
Rafael Espindolac81c3f52014-11-25 15:33:40 +0000226 Elements[I] = get(SrcSTy->getElementType(I));
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000227
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000228 DstSTy->setBody(Elements, SrcSTy->isPacked());
Rafael Espindolaa5b9e1c2015-03-06 00:50:21 +0000229 DstStructTypesSet.switchToNonOpaque(DstSTy);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000230 }
Rafael Espindolac81c3f52014-11-25 15:33:40 +0000231 SrcDefinitionsToResolve.clear();
Chris Lattner5e3bd972011-12-20 00:03:52 +0000232 DstResolvedOpaqueTypes.clear();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000233}
234
Rafael Espindola31ad4682014-12-03 22:36:37 +0000235void TypeMapTy::finishType(StructType *DTy, StructType *STy,
236 ArrayRef<Type *> ETypes) {
237 DTy->setBody(ETypes, STy->isPacked());
Rafael Espindolac81c3f52014-11-25 15:33:40 +0000238
239 // Steal STy's name.
240 if (STy->hasName()) {
241 SmallString<16> TmpName = STy->getName();
242 STy->setName("");
243 DTy->setName(TmpName);
244 }
245
Rafael Espindola31ad4682014-12-03 22:36:37 +0000246 DstStructTypesSet.addNonOpaque(DTy);
247}
248
249Type *TypeMapTy::get(Type *Ty) {
250 SmallPtrSet<StructType *, 8> Visited;
251 return get(Ty, Visited);
252}
253
254Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
255 // If we already have an entry for this type, return it.
256 Type **Entry = &MappedTypes[Ty];
257 if (*Entry)
258 return *Entry;
259
260 // These are types that LLVM itself will unique.
261 bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
262
263#ifndef NDEBUG
264 if (!IsUniqued) {
265 for (auto &Pair : MappedTypes) {
266 assert(!(Pair.first != Ty && Pair.second == Ty) &&
267 "mapping to a source type");
268 }
269 }
270#endif
271
272 if (!IsUniqued && !Visited.insert(cast<StructType>(Ty)).second) {
273 StructType *DTy = StructType::create(Ty->getContext());
274 return *Entry = DTy;
275 }
276
277 // If this is not a recursive type, then just map all of the elements and
278 // then rebuild the type from inside out.
279 SmallVector<Type *, 4> ElementTypes;
280
281 // If there are no element types to map, then the type is itself. This is
282 // true for the anonymous {} struct, things like 'float', integers, etc.
283 if (Ty->getNumContainedTypes() == 0 && IsUniqued)
284 return *Entry = Ty;
285
286 // Remap all of the elements, keeping track of whether any of them change.
287 bool AnyChange = false;
288 ElementTypes.resize(Ty->getNumContainedTypes());
289 for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
290 ElementTypes[I] = get(Ty->getContainedType(I), Visited);
291 AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
292 }
293
294 // If we found our type while recursively processing stuff, just use it.
295 Entry = &MappedTypes[Ty];
296 if (*Entry) {
297 if (auto *DTy = dyn_cast<StructType>(*Entry)) {
298 if (DTy->isOpaque()) {
299 auto *STy = cast<StructType>(Ty);
300 finishType(DTy, STy, ElementTypes);
301 }
302 }
303 return *Entry;
304 }
305
306 // If all of the element types mapped directly over and the type is not
307 // a nomed struct, then the type is usable as-is.
308 if (!AnyChange && IsUniqued)
309 return *Entry = Ty;
310
311 // Otherwise, rebuild a modified type.
312 switch (Ty->getTypeID()) {
313 default:
314 llvm_unreachable("unknown derived type to remap");
315 case Type::ArrayTyID:
316 return *Entry = ArrayType::get(ElementTypes[0],
317 cast<ArrayType>(Ty)->getNumElements());
318 case Type::VectorTyID:
319 return *Entry = VectorType::get(ElementTypes[0],
320 cast<VectorType>(Ty)->getNumElements());
321 case Type::PointerTyID:
322 return *Entry = PointerType::get(ElementTypes[0],
323 cast<PointerType>(Ty)->getAddressSpace());
324 case Type::FunctionTyID:
325 return *Entry = FunctionType::get(ElementTypes[0],
326 makeArrayRef(ElementTypes).slice(1),
327 cast<FunctionType>(Ty)->isVarArg());
328 case Type::StructTyID: {
329 auto *STy = cast<StructType>(Ty);
330 bool IsPacked = STy->isPacked();
331 if (IsUniqued)
332 return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
333
334 // If the type is opaque, we can just use it directly.
335 if (STy->isOpaque()) {
336 DstStructTypesSet.addOpaque(STy);
337 return *Entry = Ty;
338 }
339
340 if (StructType *OldT =
341 DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
342 STy->setName("");
343 return *Entry = OldT;
344 }
345
346 if (!AnyChange) {
347 DstStructTypesSet.addNonOpaque(STy);
348 return *Entry = Ty;
349 }
350
351 StructType *DTy = StructType::create(Ty->getContext());
352 finishType(DTy, STy, ElementTypes);
353 return *Entry = DTy;
354 }
355 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000356}
357
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000358//===----------------------------------------------------------------------===//
359// ModuleLinker implementation.
360//===----------------------------------------------------------------------===//
361
362namespace {
Rafael Espindolac84f6082014-11-25 06:11:24 +0000363class ModuleLinker;
James Molloyf6f121e2013-05-28 15:17:05 +0000364
Rafael Espindolac84f6082014-11-25 06:11:24 +0000365/// Creates prototypes for functions that are lazily linked on the fly. This
366/// speeds up linking for modules with many/ lazily linked functions of which
367/// few get used.
David Blaikie437aafd2015-10-19 22:15:55 +0000368class ValueMaterializerTy final : public ValueMaterializer {
Rafael Espindolac84f6082014-11-25 06:11:24 +0000369 TypeMapTy &TypeMap;
370 Module *DstM;
Rafael Espindolaef237112014-12-08 18:45:16 +0000371 std::vector<GlobalValue *> &LazilyLinkGlobalValues;
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000372 ModuleLinker *ModLinker;
James Molloyf6f121e2013-05-28 15:17:05 +0000373
Rafael Espindolac84f6082014-11-25 06:11:24 +0000374public:
375 ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000376 std::vector<GlobalValue *> &LazilyLinkGlobalValues,
377 ModuleLinker *ModLinker)
Rafael Espindolac84f6082014-11-25 06:11:24 +0000378 : ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000379 LazilyLinkGlobalValues(LazilyLinkGlobalValues), ModLinker(ModLinker) {}
Rafael Espindolac84f6082014-11-25 06:11:24 +0000380
381 Value *materializeValueFor(Value *V) override;
382};
383
384class LinkDiagnosticInfo : public DiagnosticInfo {
385 const Twine &Msg;
386
387public:
388 LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg);
389 void print(DiagnosticPrinter &DP) const override;
390};
391LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
392 const Twine &Msg)
393 : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
394void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
395
396/// This is an implementation class for the LinkModules function, which is the
397/// entrypoint for this file.
398class ModuleLinker {
399 Module *DstM, *SrcM;
400
401 TypeMapTy TypeMap;
402 ValueMaterializerTy ValMaterializer;
403
404 /// Mapping of values from what they used to be in Src, to what they are now
405 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
406 /// due to the use of Value handles which the Linker doesn't actually need,
407 /// but this allows us to reuse the ValueMapper code.
408 ValueToValueMapTy ValueMap;
409
410 struct AppendingVarInfo {
411 GlobalVariable *NewGV; // New aggregate global in dest module.
412 const Constant *DstInit; // Old initializer from dest module.
413 const Constant *SrcInit; // Old initializer from src module.
James Molloyf6f121e2013-05-28 15:17:05 +0000414 };
415
Rafael Espindolac84f6082014-11-25 06:11:24 +0000416 std::vector<AppendingVarInfo> AppendingVars;
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000417
Rafael Espindolac84f6082014-11-25 06:11:24 +0000418 // Set of items not to link in from source.
419 SmallPtrSet<const Value *, 16> DoNotLinkFromSource;
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000420
Rafael Espindolaef237112014-12-08 18:45:16 +0000421 // Vector of GlobalValues to lazily link in.
422 std::vector<GlobalValue *> LazilyLinkGlobalValues;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000423
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000424 DiagnosticHandlerFunction DiagnosticHandler;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000425
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +0000426 /// For symbol clashes, prefer those from Src.
Artem Belevich020d4fb2015-09-01 17:55:55 +0000427 unsigned Flags;
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +0000428
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000429 /// Function index passed into ModuleLinker for using in function
430 /// importing/exporting handling.
431 FunctionInfoIndex *ImportIndex;
432
433 /// Function to import from source module, all other functions are
434 /// imported as declarations instead of definitions.
435 Function *ImportFunction;
436
437 /// Set to true if the given FunctionInfoIndex contains any functions
438 /// from this source module, in which case we must conservatively assume
439 /// that any of its functions may be imported into another module
440 /// as part of a different backend compilation process.
441 bool HasExportedFunctions;
442
Rafael Espindolac84f6082014-11-25 06:11:24 +0000443public:
Rafael Espindola31ad4682014-12-03 22:36:37 +0000444 ModuleLinker(Module *dstM, Linker::IdentifiedStructTypeSet &Set, Module *srcM,
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000445 DiagnosticHandlerFunction DiagnosticHandler, unsigned Flags,
446 FunctionInfoIndex *Index = nullptr,
447 Function *FuncToImport = nullptr)
Rafael Espindolaa4e85e32014-12-01 16:32:20 +0000448 : DstM(dstM), SrcM(srcM), TypeMap(Set),
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000449 ValMaterializer(TypeMap, DstM, LazilyLinkGlobalValues, this),
450 DiagnosticHandler(DiagnosticHandler), Flags(Flags), ImportIndex(Index),
451 ImportFunction(FuncToImport), HasExportedFunctions(false) {
452 assert((ImportIndex || !ImportFunction) &&
453 "Expect a FunctionInfoIndex when importing");
454 // If we have a FunctionInfoIndex but no function to import,
455 // then this is the primary module being compiled in a ThinLTO
456 // backend compilation, and we need to see if it has functions that
457 // may be exported to another backend compilation.
458 if (ImportIndex && !ImportFunction)
459 HasExportedFunctions = ImportIndex->hasExportedFunctions(SrcM);
460 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000461
Rafael Espindolac84f6082014-11-25 06:11:24 +0000462 bool run();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000463
Artem Belevich020d4fb2015-09-01 17:55:55 +0000464 bool shouldOverrideFromSrc() { return Flags & Linker::OverrideFromSrc; }
465 bool shouldLinkOnlyNeeded() { return Flags & Linker::LinkOnlyNeeded; }
466 bool shouldInternalizeLinkedSymbols() {
467 return Flags & Linker::InternalizeLinkedSymbols;
468 }
469
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000470 /// Handles cloning of a global values from the source module into
471 /// the destination module, including setting the attributes and visibility.
472 GlobalValue *copyGlobalValueProto(TypeMapTy &TypeMap, const GlobalValue *SGV,
473 const GlobalValue *DGV = nullptr);
474
475 /// Check if we should promote the given local value to global scope.
476 bool doPromoteLocalToGlobal(const GlobalValue *SGV);
477
Rafael Espindolac84f6082014-11-25 06:11:24 +0000478private:
479 bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
480 const GlobalValue &Src);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000481
Rafael Espindolac84f6082014-11-25 06:11:24 +0000482 /// Helper method for setting a message and returning an error code.
483 bool emitError(const Twine &Message) {
484 DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
485 return true;
486 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000487
Rafael Espindolac84f6082014-11-25 06:11:24 +0000488 void emitWarning(const Twine &Message) {
489 DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
490 }
Eli Bendersky7da92ed2014-02-20 22:19:24 +0000491
Rafael Espindolac84f6082014-11-25 06:11:24 +0000492 bool getComdatLeader(Module *M, StringRef ComdatName,
493 const GlobalVariable *&GVar);
494 bool computeResultingSelectionKind(StringRef ComdatName,
495 Comdat::SelectionKind Src,
496 Comdat::SelectionKind Dst,
497 Comdat::SelectionKind &Result,
498 bool &LinkFromSrc);
499 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
500 ComdatsChosen;
501 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
502 bool &LinkFromSrc);
Rafael Espindola4160f5d2014-10-27 23:02:10 +0000503
Rafael Espindolac84f6082014-11-25 06:11:24 +0000504 /// Given a global in the source module, return the global in the
505 /// destination module that is being linked to, if any.
506 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
507 // If the source has no name it can't link. If it has local linkage,
508 // there is no name match-up going on.
509 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
510 return nullptr;
Eli Bendersky7da92ed2014-02-20 22:19:24 +0000511
Rafael Espindolac84f6082014-11-25 06:11:24 +0000512 // Otherwise see if we have a match in the destination module's symtab.
513 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
514 if (!DGV)
515 return nullptr;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000516
Rafael Espindolac84f6082014-11-25 06:11:24 +0000517 // If we found a global with the same name in the dest module, but it has
518 // internal linkage, we are really not doing any linkage here.
519 if (DGV->hasLocalLinkage())
520 return nullptr;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000521
Rafael Espindolac84f6082014-11-25 06:11:24 +0000522 // Otherwise, we do in fact link to the destination global.
523 return DGV;
524 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000525
Rafael Espindolac84f6082014-11-25 06:11:24 +0000526 void computeTypeMapping();
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000527
Rafael Espindolac84f6082014-11-25 06:11:24 +0000528 void upgradeMismatchedGlobalArray(StringRef Name);
529 void upgradeMismatchedGlobals();
David Majnemerdad0a642014-06-27 18:19:56 +0000530
Rafael Espindolac84f6082014-11-25 06:11:24 +0000531 bool linkAppendingVarProto(GlobalVariable *DstGV,
532 const GlobalVariable *SrcGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000533
Rafael Espindolac84f6082014-11-25 06:11:24 +0000534 bool linkGlobalValueProto(GlobalValue *GV);
Rafael Espindolac84f6082014-11-25 06:11:24 +0000535 bool linkModuleFlagsMetadata();
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000536
Rafael Espindolac84f6082014-11-25 06:11:24 +0000537 void linkAppendingVarInit(const AppendingVarInfo &AVI);
Rafael Espindolaef237112014-12-08 18:45:16 +0000538
539 void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src);
540 bool linkFunctionBody(Function &Dst, Function &Src);
541 void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src);
542 bool linkGlobalValueBody(GlobalValue &Src);
543
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000544 /// Functions that take care of cloning a specific global value type
545 /// into the destination module.
546 GlobalVariable *copyGlobalVariableProto(TypeMapTy &TypeMap,
547 const GlobalVariable *SGVar);
548 Function *copyFunctionProto(TypeMapTy &TypeMap, const Function *SF);
549 GlobalValue *copyGlobalAliasProto(TypeMapTy &TypeMap, const GlobalAlias *SGA);
550
551 /// Helper methods to check if we are importing from or potentially
552 /// exporting from the current source module.
553 bool isPerformingImport() { return ImportFunction != nullptr; }
554 bool isModuleExporting() { return HasExportedFunctions; }
555
556 /// If we are importing from the source module, checks if we should
557 /// import SGV as a definition, otherwise import as a declaration.
558 bool doImportAsDefinition(const GlobalValue *SGV);
559
560 /// Get the name for SGV that should be used in the linked destination
561 /// module. Specifically, this handles the case where we need to rename
562 /// a local that is being promoted to global scope.
563 std::string getName(const GlobalValue *SGV);
564
565 /// Get the new linkage for SGV that should be used in the linked destination
566 /// module. Specifically, for ThinLTO importing or exporting it may need
567 /// to be adjusted.
568 GlobalValue::LinkageTypes getLinkage(const GlobalValue *SGV);
569
570 /// Copies the necessary global value attributes and name from the source
571 /// to the newly cloned global value.
572 void copyGVAttributes(GlobalValue *NewGV, const GlobalValue *SrcGV);
573
574 /// Updates the visibility for the new global cloned from the source
575 /// and, if applicable, linked with an existing destination global.
576 /// Handles visibility change required for promoted locals.
577 void setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
578 const GlobalValue *DGV = nullptr);
579
Rafael Espindolac84f6082014-11-25 06:11:24 +0000580 void linkNamedMDNodes();
581};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000582}
Bill Wendlingd48b7782012-02-28 04:01:21 +0000583
Rafael Espindola18c89412014-10-27 02:35:46 +0000584/// The LLVM SymbolTable class autorenames globals that conflict in the symbol
585/// table. This is good for all clients except for us. Go through the trouble
586/// to force this back.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000587static void forceRenaming(GlobalValue *GV, StringRef Name) {
588 // If the global doesn't force its name or if it already has the right name,
589 // there is nothing for us to do.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000590 // Note that any required local to global promotion should already be done,
591 // so promoted locals will not skip this handling as their linkage is no
592 // longer local.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000593 if (GV->hasLocalLinkage() || GV->getName() == Name)
594 return;
595
596 Module *M = GV->getParent();
Reid Spencer361e5132004-11-12 20:37:43 +0000597
598 // If there is a conflict, rename the conflict.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000599 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
Chris Lattner2a8d2e02007-02-11 00:39:38 +0000600 GV->takeName(ConflictGV);
601 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000602 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
Chris Lattner2a8d2e02007-02-11 00:39:38 +0000603 } else {
604 GV->setName(Name); // Force the name back
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000605 }
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000606}
Reid Spencer90246aa2007-02-04 04:29:21 +0000607
Rafael Espindola18c89412014-10-27 02:35:46 +0000608/// copy additional attributes (those not needed to construct a GlobalValue)
609/// from the SrcGV to the DestGV.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000610void ModuleLinker::copyGVAttributes(GlobalValue *NewGV,
611 const GlobalValue *SrcGV) {
612 auto *GA = dyn_cast<GlobalAlias>(SrcGV);
613 // Check for the special case of converting an alias (definition) to a
614 // non-alias (declaration). This can happen when we are importing and
615 // encounter a weak_any alias (weak_any defs may not be imported, see
616 // comments in ModuleLinker::getLinkage) or an alias whose base object is
617 // being imported as a declaration. In that case copy the attributes from the
618 // base object.
619 if (GA && !dyn_cast<GlobalAlias>(NewGV)) {
620 assert(isPerformingImport() &&
621 (GA->hasWeakAnyLinkage() ||
622 !doImportAsDefinition(GA->getBaseObject())));
623 NewGV->copyAttributesFrom(GA->getBaseObject());
624 } else
625 NewGV->copyAttributesFrom(SrcGV);
626 forceRenaming(NewGV, getName(SrcGV));
Reid Spencer361e5132004-11-12 20:37:43 +0000627}
628
Rafael Espindola23f8d642012-01-05 23:02:01 +0000629static bool isLessConstraining(GlobalValue::VisibilityTypes a,
630 GlobalValue::VisibilityTypes b) {
631 if (a == GlobalValue::HiddenVisibility)
632 return false;
633 if (b == GlobalValue::HiddenVisibility)
634 return true;
635 if (a == GlobalValue::ProtectedVisibility)
636 return false;
637 if (b == GlobalValue::ProtectedVisibility)
638 return true;
639 return false;
640}
641
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000642bool ModuleLinker::doImportAsDefinition(const GlobalValue *SGV) {
643 if (!isPerformingImport())
644 return false;
645 // Always import GlobalVariable definitions. The linkage changes
646 // described in ModuleLinker::getLinkage ensure the correct behavior (e.g.
647 // global variables with external linkage are transformed to
648 // available_externally defintions, which are ultimately turned into
649 // declaratios after the EliminateAvailableExternally pass).
650 if (dyn_cast<GlobalVariable>(SGV) && !SGV->isDeclaration())
651 return true;
652 // Only import the function requested for importing.
653 auto *SF = dyn_cast<Function>(SGV);
654 if (SF && SF == ImportFunction)
655 return true;
656 // Otherwise no.
657 return false;
658}
659
660bool ModuleLinker::doPromoteLocalToGlobal(const GlobalValue *SGV) {
661 assert(SGV->hasLocalLinkage());
662 // Both the imported references and the original local variable must
663 // be promoted.
664 if (!isPerformingImport() && !isModuleExporting())
665 return false;
666
667 // Local const variables never need to be promoted unless they are address
668 // taken. The imported uses can simply use the clone created in this module.
669 // For now we are conservative in determining which variables are not
670 // address taken by checking the unnamed addr flag. To be more aggressive,
671 // the address taken information must be checked earlier during parsing
672 // of the module and recorded in the function index for use when importing
673 // from that module.
674 auto *GVar = dyn_cast<GlobalVariable>(SGV);
675 if (GVar && GVar->isConstant() && GVar->hasUnnamedAddr())
676 return false;
677
678 // Eventually we only need to promote functions in the exporting module that
679 // are referenced by a potentially exported function (i.e. one that is in the
680 // function index).
681 return true;
682}
683
684std::string ModuleLinker::getName(const GlobalValue *SGV) {
685 // For locals that must be promoted to global scope, ensure that
686 // the promoted name uniquely identifies the copy in the original module,
687 // using the ID assigned during combined index creation. When importing,
688 // we rename all locals (not just those that are promoted) in order to
689 // avoid naming conflicts between locals imported from different modules.
690 if (SGV->hasLocalLinkage() &&
691 (doPromoteLocalToGlobal(SGV) || isPerformingImport()))
692 return FunctionInfoIndex::getGlobalNameForLocal(
693 SGV->getName(),
694 ImportIndex->getModuleId(SGV->getParent()->getModuleIdentifier()));
695 return SGV->getName();
696}
697
698GlobalValue::LinkageTypes ModuleLinker::getLinkage(const GlobalValue *SGV) {
699 // Any local variable that is referenced by an exported function needs
700 // to be promoted to global scope. Since we don't currently know which
701 // functions reference which local variables/functions, we must treat
702 // all as potentially exported if this module is exporting anything.
703 if (isModuleExporting()) {
704 if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
705 return GlobalValue::ExternalLinkage;
706 return SGV->getLinkage();
707 }
708
709 // Otherwise, if we aren't importing, no linkage change is needed.
710 if (!isPerformingImport())
711 return SGV->getLinkage();
712
713 switch (SGV->getLinkage()) {
714 case GlobalValue::ExternalLinkage:
715 // External defnitions are converted to available_externally
716 // definitions upon import, so that they are available for inlining
717 // and/or optimization, but are turned into declarations later
718 // during the EliminateAvailableExternally pass.
719 if (doImportAsDefinition(SGV))
720 return GlobalValue::AvailableExternallyLinkage;
721 // An imported external declaration stays external.
722 return SGV->getLinkage();
723
724 case GlobalValue::AvailableExternallyLinkage:
725 // An imported available_externally definition converts
726 // to external if imported as a declaration.
727 if (!doImportAsDefinition(SGV))
728 return GlobalValue::ExternalLinkage;
729 // An imported available_externally declaration stays that way.
730 return SGV->getLinkage();
731
732 case GlobalValue::LinkOnceAnyLinkage:
733 case GlobalValue::LinkOnceODRLinkage:
734 // These both stay the same when importing the definition.
735 // The ThinLTO pass will eventually force-import their definitions.
736 return SGV->getLinkage();
737
738 case GlobalValue::WeakAnyLinkage:
739 // Can't import weak_any definitions correctly, or we might change the
740 // program semantics, since the linker will pick the first weak_any
741 // definition and importing would change the order they are seen by the
742 // linker. The module linking caller needs to enforce this.
743 assert(!doImportAsDefinition(SGV));
744 // If imported as a declaration, it becomes external_weak.
745 return GlobalValue::ExternalWeakLinkage;
746
747 case GlobalValue::WeakODRLinkage:
748 // For weak_odr linkage, there is a guarantee that all copies will be
749 // equivalent, so the issue described above for weak_any does not exist,
750 // and the definition can be imported. It can be treated similarly
751 // to an imported externally visible global value.
752 if (doImportAsDefinition(SGV))
753 return GlobalValue::AvailableExternallyLinkage;
754 else
755 return GlobalValue::ExternalLinkage;
756
757 case GlobalValue::AppendingLinkage:
758 // It would be incorrect to import an appending linkage variable,
759 // since it would cause global constructors/destructors to be
760 // executed multiple times. This should have already been handled
761 // by linkGlobalValueProto.
762 assert(false && "Cannot import appending linkage variable");
763
764 case GlobalValue::InternalLinkage:
765 case GlobalValue::PrivateLinkage:
766 // If we are promoting the local to global scope, it is handled
767 // similarly to a normal externally visible global.
768 if (doPromoteLocalToGlobal(SGV)) {
769 if (doImportAsDefinition(SGV))
770 return GlobalValue::AvailableExternallyLinkage;
771 else
772 return GlobalValue::ExternalLinkage;
773 }
774 // A non-promoted imported local definition stays local.
775 // The ThinLTO pass will eventually force-import their definitions.
776 return SGV->getLinkage();
777
778 case GlobalValue::ExternalWeakLinkage:
779 // External weak doesn't apply to definitions, must be a declaration.
780 assert(!doImportAsDefinition(SGV));
781 // Linkage stays external_weak.
782 return SGV->getLinkage();
783
784 case GlobalValue::CommonLinkage:
785 // Linkage stays common on definitions.
786 // The ThinLTO pass will eventually force-import their definitions.
787 return SGV->getLinkage();
788 }
789
790 llvm_unreachable("unknown linkage type");
791}
792
Rafael Espindolaef237112014-12-08 18:45:16 +0000793/// Loop through the global variables in the src module and merge them into the
794/// dest module.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000795GlobalVariable *
796ModuleLinker::copyGlobalVariableProto(TypeMapTy &TypeMap,
797 const GlobalVariable *SGVar) {
Rafael Espindolaef237112014-12-08 18:45:16 +0000798 // No linking to be performed or linking from the source: simply create an
799 // identical version of the symbol over in the dest module... the
800 // initializer will be filled in later by LinkGlobalInits.
801 GlobalVariable *NewDGV = new GlobalVariable(
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000802 *DstM, TypeMap.get(SGVar->getType()->getElementType()),
803 SGVar->isConstant(), getLinkage(SGVar), /*init*/ nullptr, getName(SGVar),
804 /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
Rafael Espindolaef237112014-12-08 18:45:16 +0000805 SGVar->getType()->getAddressSpace());
806
807 return NewDGV;
808}
809
810/// Link the function in the source module into the destination module if
811/// needed, setting up mapping information.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000812Function *ModuleLinker::copyFunctionProto(TypeMapTy &TypeMap,
813 const Function *SF) {
Rafael Espindolaef237112014-12-08 18:45:16 +0000814 // If there is no linkage to be performed or we are linking from the source,
815 // bring SF over.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000816 return Function::Create(TypeMap.get(SF->getFunctionType()), getLinkage(SF),
817 getName(SF), DstM);
Rafael Espindolaef237112014-12-08 18:45:16 +0000818}
819
820/// Set up prototypes for any aliases that come over from the source module.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000821GlobalValue *ModuleLinker::copyGlobalAliasProto(TypeMapTy &TypeMap,
822 const GlobalAlias *SGA) {
823 // If we are importing and encounter a weak_any alias, or an alias to
824 // an object being imported as a declaration, we must import the alias
825 // as a declaration as well, which involves converting it to a non-alias.
826 // See comments in ModuleLinker::getLinkage for why we cannot import
827 // weak_any defintions.
828 if (isPerformingImport() && (SGA->hasWeakAnyLinkage() ||
829 !doImportAsDefinition(SGA->getBaseObject()))) {
830 // Need to convert to declaration. All aliases must be definitions.
831 const GlobalValue *GVal = SGA->getBaseObject();
832 GlobalValue *NewGV;
833 if (auto *GVar = dyn_cast<GlobalVariable>(GVal))
834 NewGV = copyGlobalVariableProto(TypeMap, GVar);
835 else {
836 auto *F = dyn_cast<Function>(GVal);
837 assert(F);
838 NewGV = copyFunctionProto(TypeMap, F);
839 }
Teresa Johnsonf1b0a6e2015-11-04 16:01:16 +0000840 // Set the linkage to External or ExternalWeak (see comments in
841 // ModuleLinker::getLinkage for why WeakAny is converted to ExternalWeak).
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000842 if (SGA->hasWeakAnyLinkage())
843 NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
Teresa Johnsonf1b0a6e2015-11-04 16:01:16 +0000844 else
845 NewGV->setLinkage(GlobalValue::ExternalLinkage);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000846 // Don't attempt to link body, needs to be a declaration.
847 DoNotLinkFromSource.insert(SGA);
848 return NewGV;
849 }
Rafael Espindolaef237112014-12-08 18:45:16 +0000850 // If there is no linkage to be performed or we're linking from the source,
851 // bring over SGA.
David Blaikie6614d8d2015-09-14 20:29:26 +0000852 auto *Ty = TypeMap.get(SGA->getValueType());
853 return GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(),
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000854 getLinkage(SGA), getName(SGA), DstM);
Rafael Espindolaef237112014-12-08 18:45:16 +0000855}
856
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000857void ModuleLinker::setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
858 const GlobalValue *DGV) {
859 GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
860 if (DGV)
861 Visibility = isLessConstraining(Visibility, DGV->getVisibility())
862 ? DGV->getVisibility()
863 : Visibility;
864 // For promoted locals, mark them hidden so that they can later be
865 // stripped from the symbol table to reduce bloat.
866 if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
867 Visibility = GlobalValue::HiddenVisibility;
868 NewGV->setVisibility(Visibility);
869}
870
871GlobalValue *ModuleLinker::copyGlobalValueProto(TypeMapTy &TypeMap,
872 const GlobalValue *SGV,
873 const GlobalValue *DGV) {
Rafael Espindolaef237112014-12-08 18:45:16 +0000874 GlobalValue *NewGV;
875 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV))
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000876 NewGV = copyGlobalVariableProto(TypeMap, SGVar);
Rafael Espindolaef237112014-12-08 18:45:16 +0000877 else if (auto *SF = dyn_cast<Function>(SGV))
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000878 NewGV = copyFunctionProto(TypeMap, SF);
Rafael Espindolaef237112014-12-08 18:45:16 +0000879 else
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000880 NewGV = copyGlobalAliasProto(TypeMap, cast<GlobalAlias>(SGV));
Rafael Espindolaef237112014-12-08 18:45:16 +0000881 copyGVAttributes(NewGV, SGV);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000882 setVisibility(NewGV, SGV, DGV);
Rafael Espindolaef237112014-12-08 18:45:16 +0000883 return NewGV;
884}
885
James Molloyf6f121e2013-05-28 15:17:05 +0000886Value *ValueMaterializerTy::materializeValueFor(Value *V) {
Rafael Espindolaef237112014-12-08 18:45:16 +0000887 auto *SGV = dyn_cast<GlobalValue>(V);
888 if (!SGV)
Craig Topper2617dcc2014-04-15 06:32:26 +0000889 return nullptr;
James Molloyf6f121e2013-05-28 15:17:05 +0000890
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000891 GlobalValue *DGV = ModLinker->copyGlobalValueProto(TypeMap, SGV);
James Molloyf6f121e2013-05-28 15:17:05 +0000892
Rafael Espindolaef237112014-12-08 18:45:16 +0000893 if (Comdat *SC = SGV->getComdat()) {
894 if (auto *DGO = dyn_cast<GlobalObject>(DGV)) {
895 Comdat *DC = DstM->getOrInsertComdat(SC->getName());
896 DGO->setComdat(DC);
897 }
Rafael Espindola3931c282014-08-15 20:17:08 +0000898 }
899
Rafael Espindolaef237112014-12-08 18:45:16 +0000900 LazilyLinkGlobalValues.push_back(SGV);
901 return DGV;
James Molloyf6f121e2013-05-28 15:17:05 +0000902}
903
David Majnemerdad0a642014-06-27 18:19:56 +0000904bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName,
905 const GlobalVariable *&GVar) {
906 const GlobalValue *GVal = M->getNamedValue(ComdatName);
907 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
908 GVal = GA->getBaseObject();
909 if (!GVal)
910 // We cannot resolve the size of the aliasee yet.
911 return emitError("Linking COMDATs named '" + ComdatName +
912 "': COMDAT key involves incomputable alias size.");
913 }
914
915 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
916 if (!GVar)
917 return emitError(
918 "Linking COMDATs named '" + ComdatName +
919 "': GlobalVariable required for data dependent selection!");
920
921 return false;
922}
923
924bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
925 Comdat::SelectionKind Src,
926 Comdat::SelectionKind Dst,
927 Comdat::SelectionKind &Result,
928 bool &LinkFromSrc) {
929 // The ability to mix Comdat::SelectionKind::Any with
930 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
931 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
932 Dst == Comdat::SelectionKind::Largest;
933 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
934 Src == Comdat::SelectionKind::Largest;
935 if (DstAnyOrLargest && SrcAnyOrLargest) {
936 if (Dst == Comdat::SelectionKind::Largest ||
937 Src == Comdat::SelectionKind::Largest)
938 Result = Comdat::SelectionKind::Largest;
939 else
940 Result = Comdat::SelectionKind::Any;
941 } else if (Src == Dst) {
942 Result = Dst;
943 } else {
944 return emitError("Linking COMDATs named '" + ComdatName +
945 "': invalid selection kinds!");
946 }
947
948 switch (Result) {
949 case Comdat::SelectionKind::Any:
950 // Go with Dst.
951 LinkFromSrc = false;
952 break;
953 case Comdat::SelectionKind::NoDuplicates:
954 return emitError("Linking COMDATs named '" + ComdatName +
955 "': noduplicates has been violated!");
956 case Comdat::SelectionKind::ExactMatch:
957 case Comdat::SelectionKind::Largest:
958 case Comdat::SelectionKind::SameSize: {
959 const GlobalVariable *DstGV;
960 const GlobalVariable *SrcGV;
961 if (getComdatLeader(DstM, ComdatName, DstGV) ||
962 getComdatLeader(SrcM, ComdatName, SrcGV))
963 return true;
964
Mehdi Amini46a43552015-03-04 18:43:29 +0000965 const DataLayout &DstDL = DstM->getDataLayout();
966 const DataLayout &SrcDL = SrcM->getDataLayout();
David Majnemerdad0a642014-06-27 18:19:56 +0000967 uint64_t DstSize =
Mehdi Amini46a43552015-03-04 18:43:29 +0000968 DstDL.getTypeAllocSize(DstGV->getType()->getPointerElementType());
David Majnemerdad0a642014-06-27 18:19:56 +0000969 uint64_t SrcSize =
Mehdi Amini46a43552015-03-04 18:43:29 +0000970 SrcDL.getTypeAllocSize(SrcGV->getType()->getPointerElementType());
David Majnemerdad0a642014-06-27 18:19:56 +0000971 if (Result == Comdat::SelectionKind::ExactMatch) {
972 if (SrcGV->getInitializer() != DstGV->getInitializer())
973 return emitError("Linking COMDATs named '" + ComdatName +
974 "': ExactMatch violated!");
975 LinkFromSrc = false;
976 } else if (Result == Comdat::SelectionKind::Largest) {
977 LinkFromSrc = SrcSize > DstSize;
978 } else if (Result == Comdat::SelectionKind::SameSize) {
979 if (SrcSize != DstSize)
980 return emitError("Linking COMDATs named '" + ComdatName +
981 "': SameSize violated!");
982 LinkFromSrc = false;
983 } else {
984 llvm_unreachable("unknown selection kind");
985 }
986 break;
987 }
988 }
989
990 return false;
991}
992
993bool ModuleLinker::getComdatResult(const Comdat *SrcC,
994 Comdat::SelectionKind &Result,
995 bool &LinkFromSrc) {
Rafael Espindolab16196a2014-08-11 17:07:34 +0000996 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
David Majnemerdad0a642014-06-27 18:19:56 +0000997 StringRef ComdatName = SrcC->getName();
998 Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable();
999 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
Rafael Espindola2ef3f292014-08-11 16:55:42 +00001000
Rafael Espindolab16196a2014-08-11 17:07:34 +00001001 if (DstCI == ComdatSymTab.end()) {
1002 // Use the comdat if it is only available in one of the modules.
1003 LinkFromSrc = true;
1004 Result = SSK;
Rafael Espindola2ef3f292014-08-11 16:55:42 +00001005 return false;
Rafael Espindolab16196a2014-08-11 17:07:34 +00001006 }
Rafael Espindola2ef3f292014-08-11 16:55:42 +00001007
1008 const Comdat *DstC = &DstCI->second;
Rafael Espindola2ef3f292014-08-11 16:55:42 +00001009 Comdat::SelectionKind DSK = DstC->getSelectionKind();
1010 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
1011 LinkFromSrc);
David Majnemerdad0a642014-06-27 18:19:56 +00001012}
James Molloyf6f121e2013-05-28 15:17:05 +00001013
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001014bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
1015 const GlobalValue &Dest,
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001016 const GlobalValue &Src) {
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +00001017 // Should we unconditionally use the Src?
Artem Belevich020d4fb2015-09-01 17:55:55 +00001018 if (shouldOverrideFromSrc()) {
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +00001019 LinkFromSrc = true;
1020 return false;
1021 }
1022
Rafael Espindola778fcc72014-11-02 13:28:57 +00001023 // We always have to add Src if it has appending linkage.
1024 if (Src.hasAppendingLinkage()) {
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +00001025 // Caller should have already determined that we can't link from source
1026 // when importing (see comments in linkGlobalValueProto).
1027 assert(!isPerformingImport());
Rafael Espindola778fcc72014-11-02 13:28:57 +00001028 LinkFromSrc = true;
1029 return false;
1030 }
1031
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00001032 bool SrcIsDeclaration = Src.isDeclarationForLinker();
1033 bool DestIsDeclaration = Dest.isDeclarationForLinker();
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001034
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +00001035 if (isPerformingImport()) {
1036 if (isa<Function>(&Src)) {
1037 // For functions, LinkFromSrc iff this is the function requested
1038 // for importing. For variables, decide below normally.
1039 LinkFromSrc = (&Src == ImportFunction);
1040 return false;
1041 }
1042
1043 // Check if this is an alias with an already existing definition
1044 // in Dest, which must have come from a prior importing pass from
1045 // the same Src module. Unlike imported function and variable
1046 // definitions, which are imported as available_externally and are
1047 // not definitions for the linker, that is not a valid linkage for
1048 // imported aliases which must be definitions. Simply use the existing
1049 // Dest copy.
1050 if (isa<GlobalAlias>(&Src) && !DestIsDeclaration) {
1051 assert(isa<GlobalAlias>(&Dest));
1052 LinkFromSrc = false;
1053 return false;
1054 }
1055 }
1056
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001057 if (SrcIsDeclaration) {
1058 // If Src is external or if both Src & Dest are external.. Just link the
1059 // external globals, we aren't adding anything.
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001060 if (Src.hasDLLImportStorageClass()) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001061 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001062 LinkFromSrc = DestIsDeclaration;
1063 return false;
1064 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001065 // If the Dest is weak, use the source linkage.
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001066 LinkFromSrc = Dest.hasExternalWeakLinkage();
1067 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001068 }
1069
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001070 if (DestIsDeclaration) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001071 // If Dest is external but Src is not:
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001072 LinkFromSrc = true;
1073 return false;
1074 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001075
Rafael Espindola09106052014-09-09 15:59:12 +00001076 if (Src.hasCommonLinkage()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001077 if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
1078 LinkFromSrc = true;
Rafael Espindola09106052014-09-09 15:59:12 +00001079 return false;
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001080 }
1081
1082 if (!Dest.hasCommonLinkage()) {
1083 LinkFromSrc = false;
1084 return false;
1085 }
Rafael Espindola09106052014-09-09 15:59:12 +00001086
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001087 const DataLayout &DL = Dest.getParent()->getDataLayout();
Rafael Espindola09106052014-09-09 15:59:12 +00001088 uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
1089 uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001090 LinkFromSrc = SrcSize > DestSize;
1091 return false;
Rafael Espindola09106052014-09-09 15:59:12 +00001092 }
1093
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001094 if (Src.isWeakForLinker()) {
1095 assert(!Dest.hasExternalWeakLinkage());
1096 assert(!Dest.hasAvailableExternallyLinkage());
Rafael Espindola09106052014-09-09 15:59:12 +00001097
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001098 if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
1099 LinkFromSrc = true;
1100 return false;
1101 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001102
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001103 LinkFromSrc = false;
Rafael Espindola09106052014-09-09 15:59:12 +00001104 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001105 }
1106
1107 if (Dest.isWeakForLinker()) {
1108 assert(Src.hasExternalLinkage());
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001109 LinkFromSrc = true;
1110 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001111 }
1112
1113 assert(!Src.hasExternalWeakLinkage());
1114 assert(!Dest.hasExternalWeakLinkage());
1115 assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
1116 "Unexpected linkage type!");
1117 return emitError("Linking globals named '" + Src.getName() +
1118 "': symbol multiply defined!");
1119}
1120
Rafael Espindola18c89412014-10-27 02:35:46 +00001121/// Loop over all of the linked values to compute type mappings. For example,
1122/// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
1123/// types 'Foo' but one got renamed when the module was loaded into the same
1124/// LLVMContext.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001125void ModuleLinker::computeTypeMapping() {
Rafael Espindolac8a476e2014-11-25 04:26:19 +00001126 for (GlobalValue &SGV : SrcM->globals()) {
1127 GlobalValue *DGV = getLinkedToGlobal(&SGV);
1128 if (!DGV)
1129 continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001130
Rafael Espindolac8a476e2014-11-25 04:26:19 +00001131 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
1132 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001133 continue;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001134 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001135
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001136 // Unify the element type of appending arrays.
1137 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
Rafael Espindolac8a476e2014-11-25 04:26:19 +00001138 ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001139 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
Devang Patel5c310be2009-08-11 18:01:24 +00001140 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001141
Rafael Espindolac8a476e2014-11-25 04:26:19 +00001142 for (GlobalValue &SGV : *SrcM) {
1143 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
1144 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001145 }
Bill Wendling7b464612012-02-27 22:34:19 +00001146
Rafael Espindolae96d7eb2014-11-25 04:43:59 +00001147 for (GlobalValue &SGV : SrcM->aliases()) {
1148 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
1149 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1150 }
1151
Bill Wendlingd48b7782012-02-28 04:01:21 +00001152 // Incorporate types by name, scanning all the types in the source module.
1153 // At this point, the destination module may have a type "%foo = { i32 }" for
Bill Wendling2b3f61a2012-02-27 23:48:30 +00001154 // example. When the source module got loaded into the same LLVMContext, if
1155 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001156 std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
1157 for (StructType *ST : Types) {
Rafael Espindola4d4c9382014-12-01 19:08:07 +00001158 if (!ST->hasName())
1159 continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001160
Bill Wendling2b3f61a2012-02-27 23:48:30 +00001161 // Check to see if there is a dot in the name followed by a digit.
Bill Wendlingd48b7782012-02-28 04:01:21 +00001162 size_t DotPos = ST->getName().rfind('.');
1163 if (DotPos == 0 || DotPos == StringRef::npos ||
Guy Benyei83c74e92013-02-12 21:21:59 +00001164 ST->getName().back() == '.' ||
Rafael Espindola973b3612014-12-01 19:17:46 +00001165 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
Bill Wendlingd48b7782012-02-28 04:01:21 +00001166 continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001167
Bill Wendling2b3f61a2012-02-27 23:48:30 +00001168 // Check to see if the destination module has a struct with the prefix name.
Rafael Espindola973b3612014-12-01 19:17:46 +00001169 StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos));
1170 if (!DST)
1171 continue;
1172
1173 // Don't use it if this actually came from the source module. They're in
1174 // the same LLVMContext after all. Also don't use it unless the type is
1175 // actually used in the destination module. This can happen in situations
1176 // like this:
1177 //
1178 // Module A Module B
1179 // -------- --------
1180 // %Z = type { %A } %B = type { %C.1 }
1181 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
1182 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
1183 // %C = type { i8* } %B.3 = type { %C.1 }
1184 //
1185 // When we link Module B with Module A, the '%B' in Module B is
1186 // used. However, that would then use '%C.1'. But when we process '%C.1',
1187 // we prefer to take the '%C' version. So we are then left with both
1188 // '%C.1' and '%C' being used for the same types. This leads to some
1189 // variables using one type and some using the other.
Rafael Espindola31ad4682014-12-03 22:36:37 +00001190 if (TypeMap.DstStructTypesSet.hasType(DST))
Rafael Espindola973b3612014-12-01 19:17:46 +00001191 TypeMap.addTypeMapping(DST, ST);
Bill Wendling2b3f61a2012-02-27 23:48:30 +00001192 }
1193
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001194 // Now that we have discovered all of the type equivalences, get a body for
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001195 // any 'opaque' types in the dest module that are now resolved.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001196 TypeMap.linkDefinedTypeBodies();
Devang Patel5c310be2009-08-11 18:01:24 +00001197}
1198
Duncan P. N. Exon Smith09d84ad2014-08-12 16:46:37 +00001199static void upgradeGlobalArray(GlobalVariable *GV) {
1200 ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
1201 StructType *OldTy = cast<StructType>(ATy->getElementType());
1202 assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
1203
1204 // Get the upgraded 3 element type.
1205 PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
1206 Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
1207 VoidPtrTy};
1208 StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
1209
1210 // Build new constants with a null third field filled in.
1211 Constant *OldInitC = GV->getInitializer();
1212 ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
1213 if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
1214 // Invalid initializer; give up.
1215 return;
1216 std::vector<Constant *> Initializers;
1217 if (OldInit && OldInit->getNumOperands()) {
1218 Value *Null = Constant::getNullValue(VoidPtrTy);
1219 for (Use &U : OldInit->operands()) {
1220 ConstantStruct *Init = cast<ConstantStruct>(U.get());
1221 Initializers.push_back(ConstantStruct::get(
1222 NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
1223 }
1224 }
1225 assert(Initializers.size() == ATy->getNumElements() &&
1226 "Failed to copy all array elements");
1227
1228 // Replace the old GV with a new one.
1229 ATy = ArrayType::get(NewTy, Initializers.size());
1230 Constant *NewInit = ConstantArray::get(ATy, Initializers);
1231 GlobalVariable *NewGV = new GlobalVariable(
1232 *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
1233 GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
1234 GV->isExternallyInitialized());
1235 NewGV->copyAttributesFrom(GV);
1236 NewGV->takeName(GV);
1237 assert(GV->use_empty() && "program cannot use initializer list");
1238 GV->eraseFromParent();
1239}
1240
1241void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
1242 // Look for the global arrays.
1243 auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name));
1244 if (!DstGV)
1245 return;
1246 auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name));
1247 if (!SrcGV)
1248 return;
1249
1250 // Check if the types already match.
1251 auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
1252 auto *SrcTy =
1253 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
1254 if (DstTy == SrcTy)
1255 return;
1256
1257 // Grab the element types. We can only upgrade an array of a two-field
1258 // struct. Only bother if the other one has three-fields.
1259 auto *DstEltTy = cast<StructType>(DstTy->getElementType());
1260 auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
1261 if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
1262 upgradeGlobalArray(DstGV);
1263 return;
1264 }
1265 if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
1266 upgradeGlobalArray(SrcGV);
1267
1268 // We can't upgrade any other differences.
1269}
1270
1271void ModuleLinker::upgradeMismatchedGlobals() {
1272 upgradeMismatchedGlobalArray("llvm.global_ctors");
1273 upgradeMismatchedGlobalArray("llvm.global_dtors");
1274}
1275
Rafael Espindola18c89412014-10-27 02:35:46 +00001276/// If there were any appending global variables, link them together now.
1277/// Return true on error.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001278bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
Rafael Espindola3e8bc6a2014-10-31 16:08:17 +00001279 const GlobalVariable *SrcGV) {
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001280
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001281 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
1282 return emitError("Linking globals named '" + SrcGV->getName() +
1283 "': can only link appending global with another appending global!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001284
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001285 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
1286 ArrayType *SrcTy =
1287 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
1288 Type *EltTy = DstTy->getElementType();
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001289
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001290 // Check to see that they two arrays agree on type.
1291 if (EltTy != SrcTy->getElementType())
1292 return emitError("Appending variables with different element types!");
1293 if (DstGV->isConstant() != SrcGV->isConstant())
1294 return emitError("Appending variables linked with different const'ness!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001295
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001296 if (DstGV->getAlignment() != SrcGV->getAlignment())
1297 return emitError(
1298 "Appending variables with different alignment need to be linked!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001299
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001300 if (DstGV->getVisibility() != SrcGV->getVisibility())
1301 return emitError(
1302 "Appending variables with different visibility need to be linked!");
Rafael Espindolafac3a012013-09-04 15:33:34 +00001303
1304 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
1305 return emitError(
1306 "Appending variables with different unnamed_addr need to be linked!");
1307
Rafael Espindola64c1e182014-06-03 02:41:57 +00001308 if (StringRef(DstGV->getSection()) != SrcGV->getSection())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001309 return emitError(
1310 "Appending variables with different section name need to be linked!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001311
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001312 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
1313 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001314
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001315 // Create the new global variable.
1316 GlobalVariable *NG =
1317 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
Craig Topper2617dcc2014-04-15 06:32:26 +00001318 DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001319 DstGV->getThreadLocalMode(),
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001320 DstGV->getType()->getAddressSpace());
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001321
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001322 // Propagate alignment, visibility and section info.
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001323 copyGVAttributes(NG, DstGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001324
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001325 AppendingVarInfo AVI;
1326 AVI.NewGV = NG;
1327 AVI.DstInit = DstGV->getInitializer();
1328 AVI.SrcInit = SrcGV->getInitializer();
1329 AppendingVars.push_back(AVI);
Mikhail Glushenkov766d4892009-03-03 07:22:23 +00001330
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001331 // Replace any uses of the two global variables with uses of the new
1332 // global.
1333 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
Anton Korobeynikove79f4c72008-03-10 22:34:28 +00001334
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001335 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
1336 DstGV->eraseFromParent();
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001337
Tanya Lattnercbb91402011-10-11 00:24:54 +00001338 // Track the source variable so we don't try to link it.
1339 DoNotLinkFromSource.insert(SrcGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001340
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001341 return false;
1342}
Mikhail Glushenkov766d4892009-03-03 07:22:23 +00001343
Rafael Espindola778fcc72014-11-02 13:28:57 +00001344bool ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001345 GlobalValue *DGV = getLinkedToGlobal(SGV);
Mikhail Glushenkov766d4892009-03-03 07:22:23 +00001346
Rafael Espindola778fcc72014-11-02 13:28:57 +00001347 // Handle the ultra special appending linkage case first.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +00001348 assert(!DGV || SGV->hasAppendingLinkage() == DGV->hasAppendingLinkage());
1349 if (SGV->hasAppendingLinkage() && isPerformingImport()) {
1350 // Don't want to append to global_ctors list, for example, when we
1351 // are importing for ThinLTO, otherwise the global ctors and dtors
1352 // get executed multiple times for local variables (the latter causing
1353 // double frees).
1354 DoNotLinkFromSource.insert(SGV);
1355 return false;
1356 }
Rafael Espindola778fcc72014-11-02 13:28:57 +00001357 if (DGV && DGV->hasAppendingLinkage())
1358 return linkAppendingVarProto(cast<GlobalVariable>(DGV),
1359 cast<GlobalVariable>(SGV));
1360
1361 bool LinkFromSrc = true;
1362 Comdat *C = nullptr;
Rafael Espindola778fcc72014-11-02 13:28:57 +00001363 bool HasUnnamedAddr = SGV->hasUnnamedAddr();
1364
David Majnemerdad0a642014-06-27 18:19:56 +00001365 if (const Comdat *SC = SGV->getComdat()) {
1366 Comdat::SelectionKind SK;
1367 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
Rafael Espindola778fcc72014-11-02 13:28:57 +00001368 C = DstM->getOrInsertComdat(SC->getName());
1369 C->setSelectionKind(SK);
1370 } else if (DGV) {
1371 if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
1372 return true;
1373 }
1374
1375 if (!LinkFromSrc) {
1376 // Track the source global so that we don't attempt to copy it over when
1377 // processing global initializers.
1378 DoNotLinkFromSource.insert(SGV);
1379
1380 if (DGV)
1381 // Make sure to remember this mapping.
1382 ValueMap[SGV] =
1383 ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->getType()));
David Majnemerdad0a642014-06-27 18:19:56 +00001384 }
1385
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +00001386 if (DGV)
Rafael Espindola778fcc72014-11-02 13:28:57 +00001387 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001388
Rafael Espindola778fcc72014-11-02 13:28:57 +00001389 if (!LinkFromSrc && !DGV)
1390 return false;
Reid Spencer361e5132004-11-12 20:37:43 +00001391
Rafael Espindola778fcc72014-11-02 13:28:57 +00001392 GlobalValue *NewGV;
Rafael Espindola26c29512014-12-05 17:53:15 +00001393 if (!LinkFromSrc) {
1394 NewGV = DGV;
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +00001395 // When linking from source we setVisibility from copyGlobalValueProto.
1396 setVisibility(NewGV, SGV, DGV);
Rafael Espindola26c29512014-12-05 17:53:15 +00001397 } else {
Rafael Espindolaef237112014-12-08 18:45:16 +00001398 // If the GV is to be lazily linked, don't create it just yet.
1399 // The ValueMaterializerTy will deal with creating it if it's used.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +00001400 if (!DGV && !shouldOverrideFromSrc() && SGV != ImportFunction &&
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +00001401 (SGV->hasLocalLinkage() || SGV->hasLinkOnceLinkage() ||
1402 SGV->hasAvailableExternallyLinkage())) {
Rafael Espindolaef237112014-12-08 18:45:16 +00001403 DoNotLinkFromSource.insert(SGV);
1404 return false;
1405 }
1406
Artem Belevich020d4fb2015-09-01 17:55:55 +00001407 // When we only want to link in unresolved dependencies, blacklist
1408 // the symbol unless unless DestM has a matching declaration (DGV).
1409 if (shouldLinkOnlyNeeded() && !(DGV && DGV->isDeclaration())) {
1410 DoNotLinkFromSource.insert(SGV);
1411 return false;
1412 }
1413
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +00001414 NewGV = copyGlobalValueProto(TypeMap, SGV, DGV);
Rafael Espindola26c29512014-12-05 17:53:15 +00001415 }
Rafael Espindolafe3842c2014-09-09 17:48:18 +00001416
Rafael Espindolaad9d0ca2014-12-05 15:42:30 +00001417 NewGV->setUnnamedAddr(HasUnnamedAddr);
Rafael Espindola439835a2014-12-05 00:09:02 +00001418
Rafael Espindolaad9d0ca2014-12-05 15:42:30 +00001419 if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
1420 if (C)
1421 NewGO->setComdat(C);
1422
1423 if (DGV && DGV->hasCommonLinkage() && SGV->hasCommonLinkage())
1424 NewGO->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment()));
1425 }
1426
Rafael Espindola879aeb72014-12-05 16:05:19 +00001427 if (auto *NewGVar = dyn_cast<GlobalVariable>(NewGV)) {
1428 auto *DGVar = dyn_cast_or_null<GlobalVariable>(DGV);
1429 auto *SGVar = dyn_cast<GlobalVariable>(SGV);
1430 if (DGVar && SGVar && DGVar->isDeclaration() && SGVar->isDeclaration() &&
1431 (!DGVar->isConstant() || !SGVar->isConstant()))
1432 NewGVar->setConstant(false);
1433 }
1434
Rafael Espindolaad9d0ca2014-12-05 15:42:30 +00001435 // Make sure to remember this mapping.
1436 if (NewGV != DGV) {
1437 if (DGV) {
1438 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
1439 DGV->eraseFromParent();
Chandler Carruthfd38af22014-11-02 09:10:31 +00001440 }
Rafael Espindolaad9d0ca2014-12-05 15:42:30 +00001441 ValueMap[SGV] = NewGV;
Reid Spencer361e5132004-11-12 20:37:43 +00001442 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001443
Rafael Espindola778fcc72014-11-02 13:28:57 +00001444 return false;
1445}
1446
Rafael Espindola3e8bc6a2014-10-31 16:08:17 +00001447static void getArrayElements(const Constant *C,
1448 SmallVectorImpl<Constant *> &Dest) {
Chris Lattner67058832012-01-25 06:48:06 +00001449 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
1450
1451 for (unsigned i = 0; i != NumElements; ++i)
1452 Dest.push_back(C->getAggregateElement(i));
Chris Lattner00245f42012-01-24 13:41:11 +00001453}
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001454
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001455void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
1456 // Merge the initializer.
Rafael Espindolad31dc042014-09-05 21:27:52 +00001457 SmallVector<Constant *, 16> DstElements;
1458 getArrayElements(AVI.DstInit, DstElements);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001459
Rafael Espindolad31dc042014-09-05 21:27:52 +00001460 SmallVector<Constant *, 16> SrcElements;
1461 getArrayElements(AVI.SrcInit, SrcElements);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001462
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001463 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
Rafael Espindolad31dc042014-09-05 21:27:52 +00001464
1465 StringRef Name = AVI.NewGV->getName();
1466 bool IsNewStructor =
1467 (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
1468 cast<StructType>(NewType->getElementType())->getNumElements() == 3;
1469
1470 for (auto *V : SrcElements) {
1471 if (IsNewStructor) {
1472 Constant *Key = V->getAggregateElement(2);
1473 if (DoNotLinkFromSource.count(Key))
1474 continue;
1475 }
1476 DstElements.push_back(
Duncan P. N. Exon Smith4fb46cb2015-08-03 17:09:38 +00001477 MapValue(V, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
Rafael Espindolad31dc042014-09-05 21:27:52 +00001478 }
1479 if (IsNewStructor) {
1480 NewType = ArrayType::get(NewType->getElementType(), DstElements.size());
1481 AVI.NewGV->mutateType(PointerType::get(NewType, 0));
1482 }
1483
1484 AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001485}
1486
Rafael Espindola18c89412014-10-27 02:35:46 +00001487/// Update the initializers in the Dest module now that all globals that may be
1488/// referenced are in Dest.
Rafael Espindolaef237112014-12-08 18:45:16 +00001489void ModuleLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) {
1490 // Figure out what the initializer looks like in the dest module.
Duncan P. N. Exon Smith4fb46cb2015-08-03 17:09:38 +00001491 Dst.setInitializer(MapValue(Src.getInitializer(), ValueMap,
1492 RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
Reid Spencer361e5132004-11-12 20:37:43 +00001493}
1494
Rafael Espindola18c89412014-10-27 02:35:46 +00001495/// Copy the source function over into the dest function and fix up references
1496/// to values. At this point we know that Dest is an external function, and
1497/// that Src is not.
Rafael Espindolaef237112014-12-08 18:45:16 +00001498bool ModuleLinker::linkFunctionBody(Function &Dst, Function &Src) {
1499 assert(Dst.isDeclaration() && !Src.isDeclaration());
Reid Spencer361e5132004-11-12 20:37:43 +00001500
Rafael Espindola40d7ebe2014-12-08 13:29:33 +00001501 // Materialize if needed.
Rafael Espindola3519da82014-12-08 14:25:26 +00001502 if (std::error_code EC = Src.materialize())
Rafael Espindola40d7ebe2014-12-08 13:29:33 +00001503 return emitError(EC.message());
1504
Rafael Espindola869d1ce2014-12-08 13:44:38 +00001505 // Link in the prefix data.
Rafael Espindola3519da82014-12-08 14:25:26 +00001506 if (Src.hasPrefixData())
Duncan P. N. Exon Smith4fb46cb2015-08-03 17:09:38 +00001507 Dst.setPrefixData(MapValue(Src.getPrefixData(), ValueMap,
1508 RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
Rafael Espindola869d1ce2014-12-08 13:44:38 +00001509
1510 // Link in the prologue data.
Rafael Espindola3519da82014-12-08 14:25:26 +00001511 if (Src.hasPrologueData())
Duncan P. N. Exon Smith4fb46cb2015-08-03 17:09:38 +00001512 Dst.setPrologueData(MapValue(Src.getPrologueData(), ValueMap,
1513 RF_MoveDistinctMDs, &TypeMap,
1514 &ValMaterializer));
Rafael Espindola869d1ce2014-12-08 13:44:38 +00001515
David Majnemer7fddecc2015-06-17 20:52:32 +00001516 // Link in the personality function.
1517 if (Src.hasPersonalityFn())
Duncan P. N. Exon Smith4fb46cb2015-08-03 17:09:38 +00001518 Dst.setPersonalityFn(MapValue(Src.getPersonalityFn(), ValueMap,
1519 RF_MoveDistinctMDs, &TypeMap,
1520 &ValMaterializer));
David Majnemer7fddecc2015-06-17 20:52:32 +00001521
Chris Lattner7391dde2004-11-16 17:12:38 +00001522 // Go through and convert function arguments over, remembering the mapping.
Rafael Espindolaef237112014-12-08 18:45:16 +00001523 Function::arg_iterator DI = Dst.arg_begin();
Rafael Espindola3519da82014-12-08 14:25:26 +00001524 for (Argument &Arg : Src.args()) {
Rafael Espindolaa314d1a2014-12-08 14:20:10 +00001525 DI->setName(Arg.getName()); // Copy the name over.
Reid Spencer361e5132004-11-12 20:37:43 +00001526
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001527 // Add a mapping to our mapping.
Duncan P. N. Exon Smith9934b262015-10-19 22:23:36 +00001528 ValueMap[&Arg] = &*DI;
Rafael Espindolaa314d1a2014-12-08 14:20:10 +00001529 ++DI;
Reid Spencer361e5132004-11-12 20:37:43 +00001530 }
1531
Duncan P. N. Exon Smithc8d987b2015-04-24 22:07:31 +00001532 // Copy over the metadata attachments.
1533 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
1534 Src.getAllMetadata(MDs);
1535 for (const auto &I : MDs)
Duncan P. N. Exon Smith4fb46cb2015-08-03 17:09:38 +00001536 Dst.setMetadata(I.first, MapMetadata(I.second, ValueMap, RF_MoveDistinctMDs,
1537 &TypeMap, &ValMaterializer));
Duncan P. N. Exon Smithc8d987b2015-04-24 22:07:31 +00001538
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001539 // Splice the body of the source function into the dest function.
Rafael Espindolaef237112014-12-08 18:45:16 +00001540 Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001541
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001542 // At this point, all of the instructions and values of the function are now
1543 // copied over. The only problem is that they are still referencing values in
1544 // the Source function as operands. Loop through all of the operands of the
1545 // functions and patch them up to point to the local versions.
Rafael Espindolaef237112014-12-08 18:45:16 +00001546 for (BasicBlock &BB : Dst)
Rafael Espindolaa314d1a2014-12-08 14:20:10 +00001547 for (Instruction &I : BB)
Duncan P. N. Exon Smith4fb46cb2015-08-03 17:09:38 +00001548 RemapInstruction(&I, ValueMap,
1549 RF_IgnoreMissingEntries | RF_MoveDistinctMDs, &TypeMap,
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001550 &ValMaterializer);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001551
Chris Lattner7391dde2004-11-16 17:12:38 +00001552 // There is no need to map the arguments anymore.
Rafael Espindola3519da82014-12-08 14:25:26 +00001553 for (Argument &Arg : Src.args())
Rafael Espindolaa314d1a2014-12-08 14:20:10 +00001554 ValueMap.erase(&Arg);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001555
Eric Christopher97cb5652015-05-15 18:20:14 +00001556 Src.dematerialize();
Rafael Espindola40d7ebe2014-12-08 13:29:33 +00001557 return false;
Reid Spencer361e5132004-11-12 20:37:43 +00001558}
1559
Rafael Espindolaef237112014-12-08 18:45:16 +00001560void ModuleLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
1561 Constant *Aliasee = Src.getAliasee();
Duncan P. N. Exon Smith4fb46cb2015-08-03 17:09:38 +00001562 Constant *Val = MapValue(Aliasee, ValueMap, RF_MoveDistinctMDs, &TypeMap,
1563 &ValMaterializer);
Rafael Espindolaef237112014-12-08 18:45:16 +00001564 Dst.setAliasee(Val);
1565}
1566
1567bool ModuleLinker::linkGlobalValueBody(GlobalValue &Src) {
1568 Value *Dst = ValueMap[&Src];
1569 assert(Dst);
Artem Belevich020d4fb2015-09-01 17:55:55 +00001570 if (shouldInternalizeLinkedSymbols())
1571 if (auto *DGV = dyn_cast<GlobalValue>(Dst))
1572 DGV->setLinkage(GlobalValue::InternalLinkage);
Rafael Espindolaef237112014-12-08 18:45:16 +00001573 if (auto *F = dyn_cast<Function>(&Src))
1574 return linkFunctionBody(cast<Function>(*Dst), *F);
1575 if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
1576 linkGlobalInit(cast<GlobalVariable>(*Dst), *GVar);
1577 return false;
Tanya Lattnercbb91402011-10-11 00:24:54 +00001578 }
Rafael Espindolaef237112014-12-08 18:45:16 +00001579 linkAliasBody(cast<GlobalAlias>(*Dst), cast<GlobalAlias>(Src));
1580 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001581}
Anton Korobeynikov26098882008-03-05 23:21:39 +00001582
Rafael Espindola18c89412014-10-27 02:35:46 +00001583/// Insert all of the named MDNodes in Src into the Dest module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001584void ModuleLinker::linkNamedMDNodes() {
Bill Wendling66f02412012-02-11 11:38:06 +00001585 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
Yaron Keren3bf3f1f2015-06-15 16:20:16 +00001586 for (const NamedMDNode &NMD : SrcM->named_metadata()) {
Bill Wendling66f02412012-02-11 11:38:06 +00001587 // Don't link module flags here. Do them separately.
Yaron Keren3bf3f1f2015-06-15 16:20:16 +00001588 if (&NMD == SrcModFlags)
1589 continue;
1590 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(NMD.getName());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001591 // Add Src elements into Dest node.
Yaron Keren3bf3f1f2015-06-15 16:20:16 +00001592 for (const MDNode *op : NMD.operands())
Duncan P. N. Exon Smith4fb46cb2015-08-03 17:09:38 +00001593 DestNMD->addOperand(MapMetadata(op, ValueMap, RF_MoveDistinctMDs,
1594 &TypeMap, &ValMaterializer));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001595 }
1596}
Bill Wendling66f02412012-02-11 11:38:06 +00001597
Rafael Espindola18c89412014-10-27 02:35:46 +00001598/// Merge the linker flags in Src into the Dest module.
Bill Wendling66f02412012-02-11 11:38:06 +00001599bool ModuleLinker::linkModuleFlagsMetadata() {
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001600 // If the source module has no module flags, we are done.
Bill Wendling66f02412012-02-11 11:38:06 +00001601 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1602 if (!SrcModFlags) return false;
1603
Bill Wendling66f02412012-02-11 11:38:06 +00001604 // If the destination module doesn't have module flags yet, then just copy
1605 // over the source module's flags.
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001606 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
Bill Wendling66f02412012-02-11 11:38:06 +00001607 if (DstModFlags->getNumOperands() == 0) {
1608 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1609 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1610
1611 return false;
1612 }
1613
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001614 // First build a map of the existing module flags and requirements.
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001615 DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001616 SmallSetVector<MDNode*, 16> Requirements;
1617 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001618 MDNode *Op = DstModFlags->getOperand(I);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001619 ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001620 MDString *ID = cast<MDString>(Op->getOperand(1));
Bill Wendling66f02412012-02-11 11:38:06 +00001621
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001622 if (Behavior->getZExtValue() == Module::Require) {
1623 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1624 } else {
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001625 Flags[ID] = std::make_pair(Op, I);
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001626 }
Bill Wendling66f02412012-02-11 11:38:06 +00001627 }
1628
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001629 // Merge in the flags from the source module, and also collect its set of
1630 // requirements.
1631 bool HasErr = false;
1632 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001633 MDNode *SrcOp = SrcModFlags->getOperand(I);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001634 ConstantInt *SrcBehavior =
1635 mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001636 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001637 MDNode *DstOp;
1638 unsigned DstIndex;
1639 std::tie(DstOp, DstIndex) = Flags.lookup(ID);
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001640 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
Bill Wendling66f02412012-02-11 11:38:06 +00001641
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001642 // If this is a requirement, add it and continue.
1643 if (SrcBehaviorValue == Module::Require) {
1644 // If the destination module does not already have this requirement, add
1645 // it.
1646 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1647 DstModFlags->addOperand(SrcOp);
1648 }
1649 continue;
Bill Wendling66f02412012-02-11 11:38:06 +00001650 }
1651
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001652 // If there is no existing flag with this ID, just add it.
1653 if (!DstOp) {
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001654 Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001655 DstModFlags->addOperand(SrcOp);
1656 continue;
1657 }
1658
1659 // Otherwise, perform a merge.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001660 ConstantInt *DstBehavior =
1661 mdconst::extract<ConstantInt>(DstOp->getOperand(0));
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001662 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1663
1664 // If either flag has override behavior, handle it first.
1665 if (DstBehaviorValue == Module::Override) {
1666 // Diagnose inconsistent flags which both have override behavior.
1667 if (SrcBehaviorValue == Module::Override &&
1668 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1669 HasErr |= emitError("linking module flags '" + ID->getString() +
1670 "': IDs have conflicting override values");
1671 }
1672 continue;
1673 } else if (SrcBehaviorValue == Module::Override) {
1674 // Update the destination flag to that of the source.
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001675 DstModFlags->setOperand(DstIndex, SrcOp);
1676 Flags[ID].first = SrcOp;
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001677 continue;
1678 }
1679
1680 // Diagnose inconsistent merge behavior types.
1681 if (SrcBehaviorValue != DstBehaviorValue) {
1682 HasErr |= emitError("linking module flags '" + ID->getString() +
1683 "': IDs have conflicting behaviors");
1684 continue;
1685 }
1686
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001687 auto replaceDstValue = [&](MDNode *New) {
1688 Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
1689 MDNode *Flag = MDNode::get(DstM->getContext(), FlagOps);
1690 DstModFlags->setOperand(DstIndex, Flag);
1691 Flags[ID].first = Flag;
1692 };
1693
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001694 // Perform the merge for standard behavior types.
1695 switch (SrcBehaviorValue) {
1696 case Module::Require:
Craig Topper2a30d782014-06-18 05:05:13 +00001697 case Module::Override: llvm_unreachable("not possible");
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001698 case Module::Error: {
1699 // Emit an error if the values differ.
1700 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1701 HasErr |= emitError("linking module flags '" + ID->getString() +
1702 "': IDs have conflicting values");
1703 }
1704 continue;
1705 }
1706 case Module::Warning: {
1707 // Emit a warning if the values differ.
1708 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001709 emitWarning("linking module flags '" + ID->getString() +
1710 "': IDs have conflicting values");
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001711 }
1712 continue;
1713 }
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001714 case Module::Append: {
1715 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1716 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001717 SmallVector<Metadata *, 8> MDs;
1718 MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001719 MDs.append(DstValue->op_begin(), DstValue->op_end());
1720 MDs.append(SrcValue->op_begin(), SrcValue->op_end());
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001721
1722 replaceDstValue(MDNode::get(DstM->getContext(), MDs));
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001723 break;
1724 }
1725 case Module::AppendUnique: {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001726 SmallSetVector<Metadata *, 16> Elts;
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001727 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1728 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001729 Elts.insert(DstValue->op_begin(), DstValue->op_end());
1730 Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001731
1732 replaceDstValue(MDNode::get(DstM->getContext(),
1733 makeArrayRef(Elts.begin(), Elts.end())));
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001734 break;
1735 }
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001736 }
Bill Wendling66f02412012-02-11 11:38:06 +00001737 }
1738
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001739 // Check all of the requirements.
1740 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1741 MDNode *Requirement = Requirements[I];
1742 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001743 Metadata *ReqValue = Requirement->getOperand(1);
Bill Wendling66f02412012-02-11 11:38:06 +00001744
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001745 MDNode *Op = Flags[Flag].first;
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001746 if (!Op || Op->getOperand(2) != ReqValue) {
1747 HasErr |= emitError("linking module flags '" + Flag->getString() +
1748 "': does not have the required value");
1749 continue;
Bill Wendling66f02412012-02-11 11:38:06 +00001750 }
1751 }
1752
1753 return HasErr;
1754}
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001755
Akira Hatanakac43df512015-02-13 00:40:41 +00001756// This function returns true if the triples match.
1757static bool triplesMatch(const Triple &T0, const Triple &T1) {
1758 // If vendor is apple, ignore the version number.
1759 if (T0.getVendor() == Triple::Apple)
1760 return T0.getArch() == T1.getArch() &&
1761 T0.getSubArch() == T1.getSubArch() &&
1762 T0.getVendor() == T1.getVendor() &&
1763 T0.getOS() == T1.getOS();
1764
1765 return T0 == T1;
1766}
1767
1768// This function returns the merged triple.
1769static std::string mergeTriples(const Triple &SrcTriple, const Triple &DstTriple) {
1770 // If vendor is apple, pick the triple with the larger version number.
1771 if (SrcTriple.getVendor() == Triple::Apple)
1772 if (DstTriple.isOSVersionLT(SrcTriple))
1773 return SrcTriple.str();
1774
1775 return DstTriple.str();
1776}
1777
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001778bool ModuleLinker::run() {
Bill Wendling66f02412012-02-11 11:38:06 +00001779 assert(DstM && "Null destination module");
1780 assert(SrcM && "Null source module");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001781
1782 // Inherit the target data from the source module if the destination module
1783 // doesn't have one already.
Mehdi Amini46a43552015-03-04 18:43:29 +00001784 if (DstM->getDataLayout().isDefault())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001785 DstM->setDataLayout(SrcM->getDataLayout());
1786
Mehdi Amini46a43552015-03-04 18:43:29 +00001787 if (SrcM->getDataLayout() != DstM->getDataLayout()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001788 emitWarning("Linking two modules of different data layouts: '" +
1789 SrcM->getModuleIdentifier() + "' is '" +
1790 SrcM->getDataLayoutStr() + "' whereas '" +
1791 DstM->getModuleIdentifier() + "' is '" +
1792 DstM->getDataLayoutStr() + "'\n");
Eli Benderskye17f3702014-02-06 18:01:56 +00001793 }
Akira Hatanakac43df512015-02-13 00:40:41 +00001794
1795 // Copy the target triple from the source to dest if the dest's is empty.
1796 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1797 DstM->setTargetTriple(SrcM->getTargetTriple());
1798
1799 Triple SrcTriple(SrcM->getTargetTriple()), DstTriple(DstM->getTargetTriple());
1800
1801 if (!SrcM->getTargetTriple().empty() && !triplesMatch(SrcTriple, DstTriple))
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001802 emitWarning("Linking two modules of different target triples: " +
1803 SrcM->getModuleIdentifier() + "' is '" +
1804 SrcM->getTargetTriple() + "' whereas '" +
1805 DstM->getModuleIdentifier() + "' is '" +
1806 DstM->getTargetTriple() + "'\n");
Akira Hatanakac43df512015-02-13 00:40:41 +00001807
1808 DstM->setTargetTriple(mergeTriples(SrcTriple, DstTriple));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001809
1810 // Append the module inline asm string.
1811 if (!SrcM->getModuleInlineAsm().empty()) {
1812 if (DstM->getModuleInlineAsm().empty())
1813 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1814 else
1815 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1816 SrcM->getModuleInlineAsm());
1817 }
1818
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001819 // Loop over all of the linked values to compute type mappings.
1820 computeTypeMapping();
1821
David Majnemerdad0a642014-06-27 18:19:56 +00001822 ComdatsChosen.clear();
David Blaikie5106ce72014-11-19 05:49:42 +00001823 for (const auto &SMEC : SrcM->getComdatSymbolTable()) {
David Majnemerdad0a642014-06-27 18:19:56 +00001824 const Comdat &C = SMEC.getValue();
1825 if (ComdatsChosen.count(&C))
1826 continue;
1827 Comdat::SelectionKind SK;
1828 bool LinkFromSrc;
1829 if (getComdatResult(&C, SK, LinkFromSrc))
1830 return true;
1831 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1832 }
1833
Duncan P. N. Exon Smith09d84ad2014-08-12 16:46:37 +00001834 // Upgrade mismatched global arrays.
1835 upgradeMismatchedGlobals();
1836
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001837 // Insert all of the globals in src into the DstM module... without linking
1838 // initializers (which could refer to functions not yet mapped over).
Yaron Keren3bf3f1f2015-06-15 16:20:16 +00001839 for (GlobalVariable &GV : SrcM->globals())
1840 if (linkGlobalValueProto(&GV))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001841 return true;
1842
1843 // Link the functions together between the two modules, without doing function
1844 // bodies... this just adds external function prototypes to the DstM
1845 // function... We do this so that when we begin processing function bodies,
1846 // all of the global values that may be referenced are available in our
1847 // ValueMap.
Yaron Keren3bf3f1f2015-06-15 16:20:16 +00001848 for (Function &F :*SrcM)
1849 if (linkGlobalValueProto(&F))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001850 return true;
1851
1852 // If there were any aliases, link them now.
Yaron Keren3bf3f1f2015-06-15 16:20:16 +00001853 for (GlobalAlias &GA : SrcM->aliases())
1854 if (linkGlobalValueProto(&GA))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001855 return true;
1856
Yaron Keren3bf3f1f2015-06-15 16:20:16 +00001857 for (const AppendingVarInfo &AppendingVar : AppendingVars)
1858 linkAppendingVarInit(AppendingVar);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001859
Rafael Espindolabeadd562014-12-08 18:05:48 +00001860 for (const auto &Entry : DstM->getComdatSymbolTable()) {
1861 const Comdat &C = Entry.getValue();
1862 if (C.getSelectionKind() == Comdat::Any)
1863 continue;
1864 const GlobalValue *GV = SrcM->getNamedValue(C.getName());
Peter Collingbourneea45d832015-06-22 21:46:51 +00001865 if (GV)
Duncan P. N. Exon Smith4fb46cb2015-08-03 17:09:38 +00001866 MapValue(GV, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
Rafael Espindolabeadd562014-12-08 18:05:48 +00001867 }
1868
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001869 // Link in the function bodies that are defined in the source module into
1870 // DstM.
Rafael Espindolaf97d0cb2014-12-08 13:35:09 +00001871 for (Function &SF : *SrcM) {
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00001872 // Skip if no body (function is external).
Rafael Espindolaf97d0cb2014-12-08 13:35:09 +00001873 if (SF.isDeclaration())
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00001874 continue;
1875
Rafael Espindolaf97d0cb2014-12-08 13:35:09 +00001876 // Skip if not linking from source.
1877 if (DoNotLinkFromSource.count(&SF))
1878 continue;
1879
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +00001880 // When importing, only materialize the function requested for import.
1881 if (isPerformingImport() && &SF != ImportFunction)
1882 continue;
1883
Rafael Espindolaef237112014-12-08 18:45:16 +00001884 if (linkGlobalValueBody(SF))
Rafael Espindola40d7ebe2014-12-08 13:29:33 +00001885 return true;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001886 }
1887
1888 // Resolve all uses of aliases with aliasees.
Rafael Espindolaef237112014-12-08 18:45:16 +00001889 for (GlobalAlias &Src : SrcM->aliases()) {
1890 if (DoNotLinkFromSource.count(&Src))
1891 continue;
1892 linkGlobalValueBody(Src);
1893 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001894
Bill Wendling91686d62014-01-16 06:29:36 +00001895 // Update the initializers in the DstM module now that all globals that may
1896 // be referenced are in DstM.
Rafael Espindolaef237112014-12-08 18:45:16 +00001897 for (GlobalVariable &Src : SrcM->globals()) {
1898 // Only process initialized GV's or ones not already in dest.
1899 if (!Src.hasInitializer() || DoNotLinkFromSource.count(&Src))
1900 continue;
1901 linkGlobalValueBody(Src);
1902 }
Bill Wendling91686d62014-01-16 06:29:36 +00001903
Tanya Lattner0a48b872011-11-02 00:24:56 +00001904 // Process vector of lazily linked in functions.
Rafael Espindolaef237112014-12-08 18:45:16 +00001905 while (!LazilyLinkGlobalValues.empty()) {
1906 GlobalValue *SGV = LazilyLinkGlobalValues.back();
1907 LazilyLinkGlobalValues.pop_back();
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +00001908 if (isPerformingImport() && !doImportAsDefinition(SGV))
1909 continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001910
Artem Belevich020d4fb2015-09-01 17:55:55 +00001911 // Skip declarations that ValueMaterializer may have created in
1912 // case we link in only some of SrcM.
1913 if (shouldLinkOnlyNeeded() && SGV->isDeclaration())
1914 continue;
1915
Rafael Espindola9573a9c2014-12-16 22:29:43 +00001916 assert(!SGV->isDeclaration() && "users should not pass down decls");
Rafael Espindolaef237112014-12-08 18:45:16 +00001917 if (linkGlobalValueBody(*SGV))
Rafael Espindola40d7ebe2014-12-08 13:29:33 +00001918 return true;
Rafael Espindola28a24512014-12-05 21:04:36 +00001919 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001920
Teresa Johnson189b2522015-11-06 17:50:48 +00001921 // Remap all of the named MDNodes in Src into the DstM module. We do this
1922 // after linking GlobalValues so that MDNodes that reference GlobalValues
1923 // are properly remapped.
1924 linkNamedMDNodes();
1925
1926 // Merge the module flags into the DstM module.
1927 if (linkModuleFlagsMetadata())
1928 return true;
1929
Anton Korobeynikov26098882008-03-05 23:21:39 +00001930 return false;
1931}
Reid Spencer361e5132004-11-12 20:37:43 +00001932
Rafael Espindola31ad4682014-12-03 22:36:37 +00001933Linker::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
1934 : ETypes(E), IsPacked(P) {}
1935
1936Linker::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
1937 : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1938
1939bool Linker::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
1940 if (IsPacked != That.IsPacked)
1941 return false;
1942 if (ETypes != That.ETypes)
1943 return false;
1944 return true;
1945}
1946
1947bool Linker::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
1948 return !this->operator==(That);
1949}
1950
1951StructType *Linker::StructTypeKeyInfo::getEmptyKey() {
1952 return DenseMapInfo<StructType *>::getEmptyKey();
1953}
1954
1955StructType *Linker::StructTypeKeyInfo::getTombstoneKey() {
1956 return DenseMapInfo<StructType *>::getTombstoneKey();
1957}
1958
1959unsigned Linker::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1960 return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1961 Key.IsPacked);
1962}
1963
1964unsigned Linker::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1965 return getHashValue(KeyTy(ST));
1966}
1967
1968bool Linker::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1969 const StructType *RHS) {
1970 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1971 return false;
1972 return LHS == KeyTy(RHS);
1973}
1974
1975bool Linker::StructTypeKeyInfo::isEqual(const StructType *LHS,
1976 const StructType *RHS) {
1977 if (RHS == getEmptyKey())
1978 return LHS == getEmptyKey();
1979
1980 if (RHS == getTombstoneKey())
1981 return LHS == getTombstoneKey();
1982
1983 return KeyTy(LHS) == KeyTy(RHS);
1984}
1985
1986void Linker::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
1987 assert(!Ty->isOpaque());
Benjamin Kramer3280a5d2014-12-06 19:22:54 +00001988 NonOpaqueStructTypes.insert(Ty);
Rafael Espindola31ad4682014-12-03 22:36:37 +00001989}
1990
Rafael Espindolaa5b9e1c2015-03-06 00:50:21 +00001991void Linker::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
1992 assert(!Ty->isOpaque());
1993 NonOpaqueStructTypes.insert(Ty);
1994 bool Removed = OpaqueStructTypes.erase(Ty);
1995 (void)Removed;
1996 assert(Removed);
1997}
1998
Rafael Espindola31ad4682014-12-03 22:36:37 +00001999void Linker::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
2000 assert(Ty->isOpaque());
2001 OpaqueStructTypes.insert(Ty);
2002}
2003
2004StructType *
2005Linker::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
2006 bool IsPacked) {
2007 Linker::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
2008 auto I = NonOpaqueStructTypes.find_as(Key);
2009 if (I == NonOpaqueStructTypes.end())
2010 return nullptr;
Benjamin Kramer3280a5d2014-12-06 19:22:54 +00002011 return *I;
Rafael Espindola31ad4682014-12-03 22:36:37 +00002012}
2013
2014bool Linker::IdentifiedStructTypeSet::hasType(StructType *Ty) {
2015 if (Ty->isOpaque())
2016 return OpaqueStructTypes.count(Ty);
2017 auto I = NonOpaqueStructTypes.find(Ty);
2018 if (I == NonOpaqueStructTypes.end())
2019 return false;
Benjamin Kramer3280a5d2014-12-06 19:22:54 +00002020 return *I == Ty;
Rafael Espindola31ad4682014-12-03 22:36:37 +00002021}
2022
Rafael Espindola5cb9c822014-11-17 20:51:01 +00002023void Linker::init(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
2024 this->Composite = M;
2025 this->DiagnosticHandler = DiagnosticHandler;
Rafael Espindolaa4e85e32014-12-01 16:32:20 +00002026
2027 TypeFinder StructTypes;
2028 StructTypes.run(*M, true);
Rafael Espindola31ad4682014-12-03 22:36:37 +00002029 for (StructType *Ty : StructTypes) {
2030 if (Ty->isOpaque())
2031 IdentifiedStructTypes.addOpaque(Ty);
2032 else
2033 IdentifiedStructTypes.addNonOpaque(Ty);
2034 }
Rafael Espindolaaa9918a2013-05-04 05:05:18 +00002035}
Rafael Espindola3df61b72013-05-04 03:48:37 +00002036
Rafael Espindola5cb9c822014-11-17 20:51:01 +00002037Linker::Linker(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
2038 init(M, DiagnosticHandler);
2039}
2040
2041Linker::Linker(Module *M) {
2042 init(M, [this](const DiagnosticInfo &DI) {
2043 Composite->getContext().diagnose(DI);
2044 });
2045}
2046
Bill Wendling91e6f6e2013-10-16 08:59:57 +00002047void Linker::deleteModule() {
2048 delete Composite;
Craig Topper2617dcc2014-04-15 06:32:26 +00002049 Composite = nullptr;
Bill Wendling91e6f6e2013-10-16 08:59:57 +00002050}
2051
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +00002052bool Linker::linkInModule(Module *Src, unsigned Flags, FunctionInfoIndex *Index,
2053 Function *FuncToImport) {
Rafael Espindolaa4e85e32014-12-01 16:32:20 +00002054 ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src,
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +00002055 DiagnosticHandler, Flags, Index, FuncToImport);
Manman Rendab999d2015-01-20 19:24:59 +00002056 bool RetCode = TheLinker.run();
2057 Composite->dropTriviallyDeadConstantArrays();
2058 return RetCode;
Rafael Espindola3df61b72013-05-04 03:48:37 +00002059}
2060
Manman Ren6487ce92015-02-24 00:45:56 +00002061void Linker::setModule(Module *Dst) {
2062 init(Dst, DiagnosticHandler);
2063}
2064
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002065//===----------------------------------------------------------------------===//
2066// LinkModules entrypoint.
2067//===----------------------------------------------------------------------===//
2068
Rafael Espindola18c89412014-10-27 02:35:46 +00002069/// This function links two modules together, with the resulting Dest module
2070/// modified to be the composite of the two input modules. If an error occurs,
2071/// true is returned and ErrorMsg (if not null) is set to indicate the problem.
2072/// Upon failure, the Dest module could be in a modified state, and shouldn't be
2073/// relied on to be consistent.
Rafael Espindola9f8eff32014-10-28 00:24:16 +00002074bool Linker::LinkModules(Module *Dest, Module *Src,
Artem Belevich020d4fb2015-09-01 17:55:55 +00002075 DiagnosticHandlerFunction DiagnosticHandler,
2076 unsigned Flags) {
Rafael Espindola4160f5d2014-10-27 23:02:10 +00002077 Linker L(Dest, DiagnosticHandler);
Artem Belevich020d4fb2015-09-01 17:55:55 +00002078 return L.linkInModule(Src, Flags);
Rafael Espindola4160f5d2014-10-27 23:02:10 +00002079}
2080
Artem Belevich020d4fb2015-09-01 17:55:55 +00002081bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Flags) {
Rafael Espindola287f18b2013-05-04 04:08:02 +00002082 Linker L(Dest);
Artem Belevich020d4fb2015-09-01 17:55:55 +00002083 return L.linkInModule(Src, Flags);
Reid Spencer361e5132004-11-12 20:37:43 +00002084}
Bill Wendlinga3aeb982012-05-09 08:55:40 +00002085
2086//===----------------------------------------------------------------------===//
2087// C API.
2088//===----------------------------------------------------------------------===//
2089
2090LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
Juergen Ributzkaa57d5882015-03-02 18:59:38 +00002091 LLVMLinkerMode Unused, char **OutMessages) {
Rafael Espindola98ab63c2014-10-25 04:31:08 +00002092 Module *D = unwrap(Dest);
Rafael Espindola98ab63c2014-10-25 04:31:08 +00002093 std::string Message;
Rafael Espindola4160f5d2014-10-27 23:02:10 +00002094 raw_string_ostream Stream(Message);
2095 DiagnosticPrinterRawOStream DP(Stream);
2096
2097 LLVMBool Result = Linker::LinkModules(
Rafael Espindola9f8eff32014-10-28 00:24:16 +00002098 D, unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
Rafael Espindola98ab63c2014-10-25 04:31:08 +00002099
Eli Benderskyff715e22015-06-12 23:26:42 +00002100 if (OutMessages && Result) {
2101 Stream.flush();
Rafael Espindola98ab63c2014-10-25 04:31:08 +00002102 *OutMessages = strdup(Message.c_str());
Eli Benderskyff715e22015-06-12 23:26:42 +00002103 }
Bill Wendlinga3aeb982012-05-09 08:55:40 +00002104 return Result;
2105}