blob: 738791d7e5691378abe0af6c9b3a76ad6ab04ee8 [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"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/Constants.h"
Rafael Espindolad12b4a32014-10-25 04:06:10 +000022#include "llvm/IR/DiagnosticInfo.h"
23#include "llvm/IR/DiagnosticPrinter.h"
24#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Module.h"
Chandler Carruthdcb603f2013-01-07 15:43:51 +000026#include "llvm/IR/TypeFinder.h"
Eli Benderskye17f3702014-02-06 18:01:56 +000027#include "llvm/Support/CommandLine.h"
Bill Wendlingb6af2f32012-03-22 20:28:27 +000028#include "llvm/Support/Debug.h"
Bill Wendlingb6af2f32012-03-22 20:28:27 +000029#include "llvm/Support/raw_ostream.h"
Tanya Lattnercbb91402011-10-11 00:24:54 +000030#include "llvm/Transforms/Utils/Cloning.h"
Will Dietz981af002013-10-12 00:55:57 +000031#include <cctype>
David Majnemer82d6ff62014-06-27 18:38:12 +000032#include <tuple>
Reid Spencer361e5132004-11-12 20:37:43 +000033using namespace llvm;
34
Eli Benderskye17f3702014-02-06 18:01:56 +000035
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000036//===----------------------------------------------------------------------===//
37// TypeMap implementation.
38//===----------------------------------------------------------------------===//
Reid Spencer361e5132004-11-12 20:37:43 +000039
Chris Lattnereee6f992008-06-16 21:00:18 +000040namespace {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000041class TypeMapTy : public ValueMapTypeRemapper {
Rafael Espindola18c89412014-10-27 02:35:46 +000042 /// This is a mapping from a source type to a destination type to use.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000043 DenseMap<Type*, Type*> MappedTypes;
Mikhail Glushenkov766d4892009-03-03 07:22:23 +000044
Rafael Espindola18c89412014-10-27 02:35:46 +000045 /// When checking to see if two subgraphs are isomorphic, we speculatively
46 /// add types to MappedTypes, but keep track of them here in case we need to
47 /// roll back.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000048 SmallVector<Type*, 16> SpeculativeTypes;
Rafael Espindolaed6dc372014-05-09 14:39:25 +000049
Rafael Espindolaa96f2352014-11-28 16:41:24 +000050 SmallVector<StructType*, 16> SpeculativeDstOpaqueTypes;
51
Rafael Espindola18c89412014-10-27 02:35:46 +000052 /// This is a list of non-opaque structs in the source module that are mapped
53 /// to an opaque struct in the destination module.
Chris Lattner5e3bd972011-12-20 00:03:52 +000054 SmallVector<StructType*, 16> SrcDefinitionsToResolve;
Rafael Espindolaed6dc372014-05-09 14:39:25 +000055
Rafael Espindola18c89412014-10-27 02:35:46 +000056 /// This is the set of opaque types in the destination modules who are
57 /// getting a body from the source module.
Chris Lattner5e3bd972011-12-20 00:03:52 +000058 SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
Bill Wendling8c2cc412012-03-22 20:30:41 +000059
Chris Lattner56cdea62008-06-16 23:06:51 +000060public:
Rafael Espindola31ad4682014-12-03 22:36:37 +000061 TypeMapTy(Linker::IdentifiedStructTypeSet &DstStructTypesSet)
62 : DstStructTypesSet(DstStructTypesSet) {}
Rafael Espindolaaa9918a2013-05-04 05:05:18 +000063
Rafael Espindola31ad4682014-12-03 22:36:37 +000064 Linker::IdentifiedStructTypeSet &DstStructTypesSet;
Rafael Espindola18c89412014-10-27 02:35:46 +000065 /// Indicate that the specified type in the destination module is conceptually
66 /// equivalent to the specified type in the source module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000067 void addTypeMapping(Type *DstTy, Type *SrcTy);
68
Rafael Espindolad2a13a22014-11-25 04:28:31 +000069 /// Produce a body for an opaque type in the dest module from a type
70 /// definition in the source module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000071 void linkDefinedTypeBodies();
Rafael Espindolaed6dc372014-05-09 14:39:25 +000072
Rafael Espindola18c89412014-10-27 02:35:46 +000073 /// Return the mapped type to use for the specified input type from the
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000074 /// source module.
75 Type *get(Type *SrcTy);
Rafael Espindola31ad4682014-12-03 22:36:37 +000076 Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
77
78 void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000079
Rafael Espindola290e2cc2014-11-25 14:35:53 +000080 FunctionType *get(FunctionType *T) {
81 return cast<FunctionType>(get((Type *)T));
82 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000083
Rafael Espindola18c89412014-10-27 02:35:46 +000084 /// Dump out the type map for debugging purposes.
Bill Wendlingb6af2f32012-03-22 20:28:27 +000085 void dump() const {
Rafael Espindola8f144712014-11-25 06:16:27 +000086 for (auto &Pair : MappedTypes) {
Bill Wendlingb6af2f32012-03-22 20:28:27 +000087 dbgs() << "TypeMap: ";
Rafael Espindola8f144712014-11-25 06:16:27 +000088 Pair.first->print(dbgs());
Bill Wendlingb6af2f32012-03-22 20:28:27 +000089 dbgs() << " => ";
Rafael Espindola8f144712014-11-25 06:16:27 +000090 Pair.second->print(dbgs());
Bill Wendlingb6af2f32012-03-22 20:28:27 +000091 dbgs() << '\n';
92 }
93 }
Bill Wendlingb6af2f32012-03-22 20:28:27 +000094
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000095private:
Rafael Espindola290e2cc2014-11-25 14:35:53 +000096 Type *remapType(Type *SrcTy) override { return get(SrcTy); }
Rafael Espindolaed6dc372014-05-09 14:39:25 +000097
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000098 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
Chris Lattnereee6f992008-06-16 21:00:18 +000099};
100}
101
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000102void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
Rafael Espindola3d097412014-11-28 16:26:14 +0000103 assert(SpeculativeTypes.empty());
Rafael Espindolaa96f2352014-11-28 16:41:24 +0000104 assert(SpeculativeDstOpaqueTypes.empty());
Rafael Espindola3d097412014-11-28 16:26:14 +0000105
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000106 // Check to see if these types are recursively isomorphic and establish a
107 // mapping between them if so.
Duncan P. N. Exon Smithc586eaa2014-11-27 17:01:10 +0000108 if (!areTypesIsomorphic(DstTy, SrcTy)) {
109 // Oops, they aren't isomorphic. Just discard this request by rolling out
110 // any speculative mappings we've established.
Rafael Espindola3d097412014-11-28 16:26:14 +0000111 for (Type *Ty : SpeculativeTypes)
112 MappedTypes.erase(Ty);
Rafael Espindolaa96f2352014-11-28 16:41:24 +0000113
114 SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
115 SpeculativeDstOpaqueTypes.size());
116 for (StructType *Ty : SpeculativeDstOpaqueTypes)
117 DstResolvedOpaqueTypes.erase(Ty);
Rafael Espindola04a74af2014-12-01 04:15:59 +0000118 } else {
119 for (Type *Ty : SpeculativeTypes)
120 if (auto *STy = dyn_cast<StructType>(Ty))
121 if (STy->hasName())
122 STy->setName("");
Bill Wendlingd48b7782012-02-28 04:01:21 +0000123 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000124 SpeculativeTypes.clear();
Rafael Espindolaa96f2352014-11-28 16:41:24 +0000125 SpeculativeDstOpaqueTypes.clear();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000126}
Chris Lattnereee6f992008-06-16 21:00:18 +0000127
Rafael Espindola18c89412014-10-27 02:35:46 +0000128/// Recursively walk this pair of types, returning true if they are isomorphic,
129/// false if they are not.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000130bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
131 // Two types with differing kinds are clearly not isomorphic.
Rafael Espindola290e2cc2014-11-25 14:35:53 +0000132 if (DstTy->getTypeID() != SrcTy->getTypeID())
133 return false;
Misha Brukman10468d82005-04-21 22:55:34 +0000134
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000135 // If we have an entry in the MappedTypes table, then we have our answer.
136 Type *&Entry = MappedTypes[SrcTy];
137 if (Entry)
138 return Entry == DstTy;
Misha Brukman10468d82005-04-21 22:55:34 +0000139
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000140 // Two identical types are clearly isomorphic. Remember this
141 // non-speculatively.
142 if (DstTy == SrcTy) {
143 Entry = DstTy;
Chris Lattnerfe677e92008-06-16 20:03:01 +0000144 return true;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000145 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000146
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000147 // Okay, we have two types with identical kinds that we haven't seen before.
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000148
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000149 // If this is an opaque struct type, special case it.
150 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
151 // Mapping an opaque type to any struct, just keep the dest struct.
152 if (SSTy->isOpaque()) {
153 Entry = DstTy;
154 SpeculativeTypes.push_back(SrcTy);
Reid Spencer361e5132004-11-12 20:37:43 +0000155 return true;
Chris Lattner9be15892008-06-16 21:17:12 +0000156 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000157
Chris Lattner5e3bd972011-12-20 00:03:52 +0000158 // Mapping a non-opaque source type to an opaque dest. If this is the first
159 // type that we're mapping onto this destination type then we succeed. Keep
Rafael Espindolaa96f2352014-11-28 16:41:24 +0000160 // the dest, but fill it in later. If this is the second (different) type
161 // that we're trying to map onto the same opaque type then we fail.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000162 if (cast<StructType>(DstTy)->isOpaque()) {
Chris Lattner5e3bd972011-12-20 00:03:52 +0000163 // We can only map one source type onto the opaque destination type.
David Blaikie70573dc2014-11-19 07:49:26 +0000164 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
Chris Lattner5e3bd972011-12-20 00:03:52 +0000165 return false;
166 SrcDefinitionsToResolve.push_back(SSTy);
Rafael Espindolaa96f2352014-11-28 16:41:24 +0000167 SpeculativeTypes.push_back(SrcTy);
168 SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000169 Entry = DstTy;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000170 return true;
171 }
172 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000173
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000174 // If the number of subtypes disagree between the two types, then we fail.
175 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
Reid Spencer361e5132004-11-12 20:37:43 +0000176 return false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000177
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000178 // Fail if any of the extra properties (e.g. array size) of the type disagree.
179 if (isa<IntegerType>(DstTy))
180 return false; // bitwidth disagrees.
181 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
182 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
183 return false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000184
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000185 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
186 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
187 return false;
188 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
189 StructType *SSTy = cast<StructType>(SrcTy);
Chris Lattner44f7ab42011-08-12 18:07:26 +0000190 if (DSTy->isLiteral() != SSTy->isLiteral() ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000191 DSTy->isPacked() != SSTy->isPacked())
192 return false;
193 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
194 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
195 return false;
196 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
Joey Gouly5fad3e92013-01-10 10:49:36 +0000197 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000198 return false;
Reid Spencer361e5132004-11-12 20:37:43 +0000199 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000200
201 // Otherwise, we speculate that these two types will line up and recursively
202 // check the subelements.
203 Entry = DstTy;
204 SpeculativeTypes.push_back(SrcTy);
205
Rafael Espindola290e2cc2014-11-25 14:35:53 +0000206 for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
207 if (!areTypesIsomorphic(DstTy->getContainedType(I),
208 SrcTy->getContainedType(I)))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000209 return false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000210
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000211 // If everything seems to have lined up, then everything is great.
212 return true;
213}
214
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000215void TypeMapTy::linkDefinedTypeBodies() {
216 SmallVector<Type*, 16> Elements;
Rafael Espindolac81c3f52014-11-25 15:33:40 +0000217 for (StructType *SrcSTy : SrcDefinitionsToResolve) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000218 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
Rafael Espindolac81c3f52014-11-25 15:33:40 +0000219 assert(DstSTy->isOpaque());
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000220
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000221 // Map the body of the source type over to a new body for the dest type.
222 Elements.resize(SrcSTy->getNumElements());
Rafael Espindola290e2cc2014-11-25 14:35:53 +0000223 for (unsigned I = 0, E = Elements.size(); I != E; ++I)
Rafael Espindolac81c3f52014-11-25 15:33:40 +0000224 Elements[I] = get(SrcSTy->getElementType(I));
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000225
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000226 DstSTy->setBody(Elements, SrcSTy->isPacked());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000227 }
Rafael Espindolac81c3f52014-11-25 15:33:40 +0000228 SrcDefinitionsToResolve.clear();
Chris Lattner5e3bd972011-12-20 00:03:52 +0000229 DstResolvedOpaqueTypes.clear();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000230}
231
Rafael Espindola31ad4682014-12-03 22:36:37 +0000232void TypeMapTy::finishType(StructType *DTy, StructType *STy,
233 ArrayRef<Type *> ETypes) {
234 DTy->setBody(ETypes, STy->isPacked());
Rafael Espindolac81c3f52014-11-25 15:33:40 +0000235
236 // Steal STy's name.
237 if (STy->hasName()) {
238 SmallString<16> TmpName = STy->getName();
239 STy->setName("");
240 DTy->setName(TmpName);
241 }
242
Rafael Espindola31ad4682014-12-03 22:36:37 +0000243 DstStructTypesSet.addNonOpaque(DTy);
244}
245
246Type *TypeMapTy::get(Type *Ty) {
247 SmallPtrSet<StructType *, 8> Visited;
248 return get(Ty, Visited);
249}
250
251Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
252 // If we already have an entry for this type, return it.
253 Type **Entry = &MappedTypes[Ty];
254 if (*Entry)
255 return *Entry;
256
257 // These are types that LLVM itself will unique.
258 bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
259
260#ifndef NDEBUG
261 if (!IsUniqued) {
262 for (auto &Pair : MappedTypes) {
263 assert(!(Pair.first != Ty && Pair.second == Ty) &&
264 "mapping to a source type");
265 }
266 }
267#endif
268
269 if (!IsUniqued && !Visited.insert(cast<StructType>(Ty)).second) {
270 StructType *DTy = StructType::create(Ty->getContext());
271 return *Entry = DTy;
272 }
273
274 // If this is not a recursive type, then just map all of the elements and
275 // then rebuild the type from inside out.
276 SmallVector<Type *, 4> ElementTypes;
277
278 // If there are no element types to map, then the type is itself. This is
279 // true for the anonymous {} struct, things like 'float', integers, etc.
280 if (Ty->getNumContainedTypes() == 0 && IsUniqued)
281 return *Entry = Ty;
282
283 // Remap all of the elements, keeping track of whether any of them change.
284 bool AnyChange = false;
285 ElementTypes.resize(Ty->getNumContainedTypes());
286 for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
287 ElementTypes[I] = get(Ty->getContainedType(I), Visited);
288 AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
289 }
290
291 // If we found our type while recursively processing stuff, just use it.
292 Entry = &MappedTypes[Ty];
293 if (*Entry) {
294 if (auto *DTy = dyn_cast<StructType>(*Entry)) {
295 if (DTy->isOpaque()) {
296 auto *STy = cast<StructType>(Ty);
297 finishType(DTy, STy, ElementTypes);
298 }
299 }
300 return *Entry;
301 }
302
303 // If all of the element types mapped directly over and the type is not
304 // a nomed struct, then the type is usable as-is.
305 if (!AnyChange && IsUniqued)
306 return *Entry = Ty;
307
308 // Otherwise, rebuild a modified type.
309 switch (Ty->getTypeID()) {
310 default:
311 llvm_unreachable("unknown derived type to remap");
312 case Type::ArrayTyID:
313 return *Entry = ArrayType::get(ElementTypes[0],
314 cast<ArrayType>(Ty)->getNumElements());
315 case Type::VectorTyID:
316 return *Entry = VectorType::get(ElementTypes[0],
317 cast<VectorType>(Ty)->getNumElements());
318 case Type::PointerTyID:
319 return *Entry = PointerType::get(ElementTypes[0],
320 cast<PointerType>(Ty)->getAddressSpace());
321 case Type::FunctionTyID:
322 return *Entry = FunctionType::get(ElementTypes[0],
323 makeArrayRef(ElementTypes).slice(1),
324 cast<FunctionType>(Ty)->isVarArg());
325 case Type::StructTyID: {
326 auto *STy = cast<StructType>(Ty);
327 bool IsPacked = STy->isPacked();
328 if (IsUniqued)
329 return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
330
331 // If the type is opaque, we can just use it directly.
332 if (STy->isOpaque()) {
333 DstStructTypesSet.addOpaque(STy);
334 return *Entry = Ty;
335 }
336
337 if (StructType *OldT =
338 DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
339 STy->setName("");
340 return *Entry = OldT;
341 }
342
343 if (!AnyChange) {
344 DstStructTypesSet.addNonOpaque(STy);
345 return *Entry = Ty;
346 }
347
348 StructType *DTy = StructType::create(Ty->getContext());
349 finishType(DTy, STy, ElementTypes);
350 return *Entry = DTy;
351 }
352 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000353}
354
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000355//===----------------------------------------------------------------------===//
356// ModuleLinker implementation.
357//===----------------------------------------------------------------------===//
358
359namespace {
Rafael Espindolac84f6082014-11-25 06:11:24 +0000360class ModuleLinker;
James Molloyf6f121e2013-05-28 15:17:05 +0000361
Rafael Espindolac84f6082014-11-25 06:11:24 +0000362/// Creates prototypes for functions that are lazily linked on the fly. This
363/// speeds up linking for modules with many/ lazily linked functions of which
364/// few get used.
365class ValueMaterializerTy : public ValueMaterializer {
366 TypeMapTy &TypeMap;
367 Module *DstM;
368 std::vector<Function *> &LazilyLinkFunctions;
James Molloyf6f121e2013-05-28 15:17:05 +0000369
Rafael Espindolac84f6082014-11-25 06:11:24 +0000370public:
371 ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
372 std::vector<Function *> &LazilyLinkFunctions)
373 : ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
374 LazilyLinkFunctions(LazilyLinkFunctions) {}
375
376 Value *materializeValueFor(Value *V) override;
377};
378
379class LinkDiagnosticInfo : public DiagnosticInfo {
380 const Twine &Msg;
381
382public:
383 LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg);
384 void print(DiagnosticPrinter &DP) const override;
385};
386LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
387 const Twine &Msg)
388 : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
389void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
390
391/// This is an implementation class for the LinkModules function, which is the
392/// entrypoint for this file.
393class ModuleLinker {
394 Module *DstM, *SrcM;
395
396 TypeMapTy TypeMap;
397 ValueMaterializerTy ValMaterializer;
398
399 /// Mapping of values from what they used to be in Src, to what they are now
400 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
401 /// due to the use of Value handles which the Linker doesn't actually need,
402 /// but this allows us to reuse the ValueMapper code.
403 ValueToValueMapTy ValueMap;
404
405 struct AppendingVarInfo {
406 GlobalVariable *NewGV; // New aggregate global in dest module.
407 const Constant *DstInit; // Old initializer from dest module.
408 const Constant *SrcInit; // Old initializer from src module.
James Molloyf6f121e2013-05-28 15:17:05 +0000409 };
410
Rafael Espindolac84f6082014-11-25 06:11:24 +0000411 std::vector<AppendingVarInfo> AppendingVars;
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000412
Rafael Espindolac84f6082014-11-25 06:11:24 +0000413 // Set of items not to link in from source.
414 SmallPtrSet<const Value *, 16> DoNotLinkFromSource;
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000415
Rafael Espindolac84f6082014-11-25 06:11:24 +0000416 // Vector of functions to lazily link in.
417 std::vector<Function *> LazilyLinkFunctions;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000418
Rafael Espindolac84f6082014-11-25 06:11:24 +0000419 Linker::DiagnosticHandlerFunction DiagnosticHandler;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000420
Rafael Espindolac84f6082014-11-25 06:11:24 +0000421public:
Rafael Espindola31ad4682014-12-03 22:36:37 +0000422 ModuleLinker(Module *dstM, Linker::IdentifiedStructTypeSet &Set, Module *srcM,
Rafael Espindolac84f6082014-11-25 06:11:24 +0000423 Linker::DiagnosticHandlerFunction DiagnosticHandler)
Rafael Espindolaa4e85e32014-12-01 16:32:20 +0000424 : DstM(dstM), SrcM(srcM), TypeMap(Set),
Rafael Espindolac84f6082014-11-25 06:11:24 +0000425 ValMaterializer(TypeMap, DstM, LazilyLinkFunctions),
426 DiagnosticHandler(DiagnosticHandler) {}
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000427
Rafael Espindolac84f6082014-11-25 06:11:24 +0000428 bool run();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000429
Rafael Espindolac84f6082014-11-25 06:11:24 +0000430private:
431 bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
432 const GlobalValue &Src);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000433
Rafael Espindolac84f6082014-11-25 06:11:24 +0000434 /// Helper method for setting a message and returning an error code.
435 bool emitError(const Twine &Message) {
436 DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
437 return true;
438 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000439
Rafael Espindolac84f6082014-11-25 06:11:24 +0000440 void emitWarning(const Twine &Message) {
441 DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
442 }
Eli Bendersky7da92ed2014-02-20 22:19:24 +0000443
Rafael Espindolac84f6082014-11-25 06:11:24 +0000444 bool getComdatLeader(Module *M, StringRef ComdatName,
445 const GlobalVariable *&GVar);
446 bool computeResultingSelectionKind(StringRef ComdatName,
447 Comdat::SelectionKind Src,
448 Comdat::SelectionKind Dst,
449 Comdat::SelectionKind &Result,
450 bool &LinkFromSrc);
451 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
452 ComdatsChosen;
453 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
454 bool &LinkFromSrc);
Rafael Espindola4160f5d2014-10-27 23:02:10 +0000455
Rafael Espindolac84f6082014-11-25 06:11:24 +0000456 /// Given a global in the source module, return the global in the
457 /// destination module that is being linked to, if any.
458 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
459 // If the source has no name it can't link. If it has local linkage,
460 // there is no name match-up going on.
461 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
462 return nullptr;
Eli Bendersky7da92ed2014-02-20 22:19:24 +0000463
Rafael Espindolac84f6082014-11-25 06:11:24 +0000464 // Otherwise see if we have a match in the destination module's symtab.
465 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
466 if (!DGV)
467 return nullptr;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000468
Rafael Espindolac84f6082014-11-25 06:11:24 +0000469 // If we found a global with the same name in the dest module, but it has
470 // internal linkage, we are really not doing any linkage here.
471 if (DGV->hasLocalLinkage())
472 return nullptr;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000473
Rafael Espindolac84f6082014-11-25 06:11:24 +0000474 // Otherwise, we do in fact link to the destination global.
475 return DGV;
476 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000477
Rafael Espindolac84f6082014-11-25 06:11:24 +0000478 void computeTypeMapping();
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000479
Rafael Espindolac84f6082014-11-25 06:11:24 +0000480 void upgradeMismatchedGlobalArray(StringRef Name);
481 void upgradeMismatchedGlobals();
David Majnemerdad0a642014-06-27 18:19:56 +0000482
Rafael Espindolac84f6082014-11-25 06:11:24 +0000483 bool linkAppendingVarProto(GlobalVariable *DstGV,
484 const GlobalVariable *SrcGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000485
Rafael Espindolac84f6082014-11-25 06:11:24 +0000486 bool linkGlobalValueProto(GlobalValue *GV);
487 GlobalValue *linkGlobalVariableProto(const GlobalVariable *SGVar,
488 GlobalValue *DGV, bool LinkFromSrc);
489 GlobalValue *linkFunctionProto(const Function *SF, GlobalValue *DGV,
490 bool LinkFromSrc);
491 GlobalValue *linkGlobalAliasProto(const GlobalAlias *SGA, GlobalValue *DGV,
492 bool LinkFromSrc);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000493
Rafael Espindolac84f6082014-11-25 06:11:24 +0000494 bool linkModuleFlagsMetadata();
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000495
Rafael Espindolac84f6082014-11-25 06:11:24 +0000496 void linkAppendingVarInit(const AppendingVarInfo &AVI);
497 void linkGlobalInits();
498 void linkFunctionBody(Function *Dst, Function *Src);
499 void linkAliasBodies();
500 void linkNamedMDNodes();
501};
Bill Wendlingd48b7782012-02-28 04:01:21 +0000502}
503
Rafael Espindola18c89412014-10-27 02:35:46 +0000504/// The LLVM SymbolTable class autorenames globals that conflict in the symbol
505/// table. This is good for all clients except for us. Go through the trouble
506/// to force this back.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000507static void forceRenaming(GlobalValue *GV, StringRef Name) {
508 // If the global doesn't force its name or if it already has the right name,
509 // there is nothing for us to do.
510 if (GV->hasLocalLinkage() || GV->getName() == Name)
511 return;
512
513 Module *M = GV->getParent();
Reid Spencer361e5132004-11-12 20:37:43 +0000514
515 // If there is a conflict, rename the conflict.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000516 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
Chris Lattner2a8d2e02007-02-11 00:39:38 +0000517 GV->takeName(ConflictGV);
518 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000519 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
Chris Lattner2a8d2e02007-02-11 00:39:38 +0000520 } else {
521 GV->setName(Name); // Force the name back
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000522 }
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000523}
Reid Spencer90246aa2007-02-04 04:29:21 +0000524
Rafael Espindola18c89412014-10-27 02:35:46 +0000525/// copy additional attributes (those not needed to construct a GlobalValue)
526/// from the SrcGV to the DestGV.
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000527static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
Duncan Sandsdd7daee2008-05-26 19:58:59 +0000528 DestGV->copyAttributesFrom(SrcGV);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000529 forceRenaming(DestGV, SrcGV->getName());
Reid Spencer361e5132004-11-12 20:37:43 +0000530}
531
Rafael Espindola23f8d642012-01-05 23:02:01 +0000532static bool isLessConstraining(GlobalValue::VisibilityTypes a,
533 GlobalValue::VisibilityTypes b) {
534 if (a == GlobalValue::HiddenVisibility)
535 return false;
536 if (b == GlobalValue::HiddenVisibility)
537 return true;
538 if (a == GlobalValue::ProtectedVisibility)
539 return false;
540 if (b == GlobalValue::ProtectedVisibility)
541 return true;
542 return false;
543}
544
James Molloyf6f121e2013-05-28 15:17:05 +0000545Value *ValueMaterializerTy::materializeValueFor(Value *V) {
546 Function *SF = dyn_cast<Function>(V);
547 if (!SF)
Craig Topper2617dcc2014-04-15 06:32:26 +0000548 return nullptr;
James Molloyf6f121e2013-05-28 15:17:05 +0000549
550 Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()),
551 SF->getLinkage(), SF->getName(), DstM);
552 copyGVAttributes(DF, SF);
553
Rafael Espindola3931c282014-08-15 20:17:08 +0000554 if (Comdat *SC = SF->getComdat()) {
555 Comdat *DC = DstM->getOrInsertComdat(SC->getName());
556 DF->setComdat(DC);
557 }
558
James Molloyf6f121e2013-05-28 15:17:05 +0000559 LazilyLinkFunctions.push_back(SF);
560 return DF;
561}
562
David Majnemerdad0a642014-06-27 18:19:56 +0000563bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName,
564 const GlobalVariable *&GVar) {
565 const GlobalValue *GVal = M->getNamedValue(ComdatName);
566 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
567 GVal = GA->getBaseObject();
568 if (!GVal)
569 // We cannot resolve the size of the aliasee yet.
570 return emitError("Linking COMDATs named '" + ComdatName +
571 "': COMDAT key involves incomputable alias size.");
572 }
573
574 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
575 if (!GVar)
576 return emitError(
577 "Linking COMDATs named '" + ComdatName +
578 "': GlobalVariable required for data dependent selection!");
579
580 return false;
581}
582
583bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
584 Comdat::SelectionKind Src,
585 Comdat::SelectionKind Dst,
586 Comdat::SelectionKind &Result,
587 bool &LinkFromSrc) {
588 // The ability to mix Comdat::SelectionKind::Any with
589 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
590 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
591 Dst == Comdat::SelectionKind::Largest;
592 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
593 Src == Comdat::SelectionKind::Largest;
594 if (DstAnyOrLargest && SrcAnyOrLargest) {
595 if (Dst == Comdat::SelectionKind::Largest ||
596 Src == Comdat::SelectionKind::Largest)
597 Result = Comdat::SelectionKind::Largest;
598 else
599 Result = Comdat::SelectionKind::Any;
600 } else if (Src == Dst) {
601 Result = Dst;
602 } else {
603 return emitError("Linking COMDATs named '" + ComdatName +
604 "': invalid selection kinds!");
605 }
606
607 switch (Result) {
608 case Comdat::SelectionKind::Any:
609 // Go with Dst.
610 LinkFromSrc = false;
611 break;
612 case Comdat::SelectionKind::NoDuplicates:
613 return emitError("Linking COMDATs named '" + ComdatName +
614 "': noduplicates has been violated!");
615 case Comdat::SelectionKind::ExactMatch:
616 case Comdat::SelectionKind::Largest:
617 case Comdat::SelectionKind::SameSize: {
618 const GlobalVariable *DstGV;
619 const GlobalVariable *SrcGV;
620 if (getComdatLeader(DstM, ComdatName, DstGV) ||
621 getComdatLeader(SrcM, ComdatName, SrcGV))
622 return true;
623
624 const DataLayout *DstDL = DstM->getDataLayout();
625 const DataLayout *SrcDL = SrcM->getDataLayout();
626 if (!DstDL || !SrcDL) {
627 return emitError(
628 "Linking COMDATs named '" + ComdatName +
629 "': can't do size dependent selection without DataLayout!");
630 }
631 uint64_t DstSize =
632 DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType());
633 uint64_t SrcSize =
634 SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType());
635 if (Result == Comdat::SelectionKind::ExactMatch) {
636 if (SrcGV->getInitializer() != DstGV->getInitializer())
637 return emitError("Linking COMDATs named '" + ComdatName +
638 "': ExactMatch violated!");
639 LinkFromSrc = false;
640 } else if (Result == Comdat::SelectionKind::Largest) {
641 LinkFromSrc = SrcSize > DstSize;
642 } else if (Result == Comdat::SelectionKind::SameSize) {
643 if (SrcSize != DstSize)
644 return emitError("Linking COMDATs named '" + ComdatName +
645 "': SameSize violated!");
646 LinkFromSrc = false;
647 } else {
648 llvm_unreachable("unknown selection kind");
649 }
650 break;
651 }
652 }
653
654 return false;
655}
656
657bool ModuleLinker::getComdatResult(const Comdat *SrcC,
658 Comdat::SelectionKind &Result,
659 bool &LinkFromSrc) {
Rafael Espindolab16196a2014-08-11 17:07:34 +0000660 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
David Majnemerdad0a642014-06-27 18:19:56 +0000661 StringRef ComdatName = SrcC->getName();
662 Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable();
663 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000664
Rafael Espindolab16196a2014-08-11 17:07:34 +0000665 if (DstCI == ComdatSymTab.end()) {
666 // Use the comdat if it is only available in one of the modules.
667 LinkFromSrc = true;
668 Result = SSK;
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000669 return false;
Rafael Espindolab16196a2014-08-11 17:07:34 +0000670 }
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000671
672 const Comdat *DstC = &DstCI->second;
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000673 Comdat::SelectionKind DSK = DstC->getSelectionKind();
674 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
675 LinkFromSrc);
David Majnemerdad0a642014-06-27 18:19:56 +0000676}
James Molloyf6f121e2013-05-28 15:17:05 +0000677
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000678bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
679 const GlobalValue &Dest,
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000680 const GlobalValue &Src) {
Rafael Espindola778fcc72014-11-02 13:28:57 +0000681 // We always have to add Src if it has appending linkage.
682 if (Src.hasAppendingLinkage()) {
683 LinkFromSrc = true;
684 return false;
685 }
686
Rafael Espindolad4bcefc2014-10-24 18:13:04 +0000687 bool SrcIsDeclaration = Src.isDeclarationForLinker();
688 bool DestIsDeclaration = Dest.isDeclarationForLinker();
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000689
690 if (SrcIsDeclaration) {
691 // If Src is external or if both Src & Dest are external.. Just link the
692 // external globals, we aren't adding anything.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000693 if (Src.hasDLLImportStorageClass()) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000694 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000695 LinkFromSrc = DestIsDeclaration;
696 return false;
697 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000698 // If the Dest is weak, use the source linkage.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000699 LinkFromSrc = Dest.hasExternalWeakLinkage();
700 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000701 }
702
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000703 if (DestIsDeclaration) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000704 // If Dest is external but Src is not:
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000705 LinkFromSrc = true;
706 return false;
707 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000708
Rafael Espindola09106052014-09-09 15:59:12 +0000709 if (Src.hasCommonLinkage()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000710 if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
711 LinkFromSrc = true;
Rafael Espindola09106052014-09-09 15:59:12 +0000712 return false;
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000713 }
714
715 if (!Dest.hasCommonLinkage()) {
716 LinkFromSrc = false;
717 return false;
718 }
Rafael Espindola09106052014-09-09 15:59:12 +0000719
Rafael Espindola0ae225b2014-10-31 04:46:38 +0000720 // FIXME: Make datalayout mandatory and just use getDataLayout().
721 DataLayout DL(Dest.getParent());
722
Rafael Espindola09106052014-09-09 15:59:12 +0000723 uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
724 uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000725 LinkFromSrc = SrcSize > DestSize;
726 return false;
Rafael Espindola09106052014-09-09 15:59:12 +0000727 }
728
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000729 if (Src.isWeakForLinker()) {
730 assert(!Dest.hasExternalWeakLinkage());
731 assert(!Dest.hasAvailableExternallyLinkage());
Rafael Espindola09106052014-09-09 15:59:12 +0000732
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000733 if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
734 LinkFromSrc = true;
735 return false;
736 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000737
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000738 LinkFromSrc = false;
Rafael Espindola09106052014-09-09 15:59:12 +0000739 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000740 }
741
742 if (Dest.isWeakForLinker()) {
743 assert(Src.hasExternalLinkage());
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000744 LinkFromSrc = true;
745 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000746 }
747
748 assert(!Src.hasExternalWeakLinkage());
749 assert(!Dest.hasExternalWeakLinkage());
750 assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
751 "Unexpected linkage type!");
752 return emitError("Linking globals named '" + Src.getName() +
753 "': symbol multiply defined!");
754}
755
Rafael Espindola18c89412014-10-27 02:35:46 +0000756/// Loop over all of the linked values to compute type mappings. For example,
757/// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
758/// types 'Foo' but one got renamed when the module was loaded into the same
759/// LLVMContext.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000760void ModuleLinker::computeTypeMapping() {
Rafael Espindolac8a476e2014-11-25 04:26:19 +0000761 for (GlobalValue &SGV : SrcM->globals()) {
762 GlobalValue *DGV = getLinkedToGlobal(&SGV);
763 if (!DGV)
764 continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000765
Rafael Espindolac8a476e2014-11-25 04:26:19 +0000766 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
767 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000768 continue;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000769 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000770
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000771 // Unify the element type of appending arrays.
772 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
Rafael Espindolac8a476e2014-11-25 04:26:19 +0000773 ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000774 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
Devang Patel5c310be2009-08-11 18:01:24 +0000775 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000776
Rafael Espindolac8a476e2014-11-25 04:26:19 +0000777 for (GlobalValue &SGV : *SrcM) {
778 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
779 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000780 }
Bill Wendling7b464612012-02-27 22:34:19 +0000781
Rafael Espindolae96d7eb2014-11-25 04:43:59 +0000782 for (GlobalValue &SGV : SrcM->aliases()) {
783 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
784 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
785 }
786
Bill Wendlingd48b7782012-02-28 04:01:21 +0000787 // Incorporate types by name, scanning all the types in the source module.
788 // At this point, the destination module may have a type "%foo = { i32 }" for
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000789 // example. When the source module got loaded into the same LLVMContext, if
790 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
Rafael Espindola2fa1e432014-12-03 07:18:23 +0000791 std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
792 for (StructType *ST : Types) {
Rafael Espindola4d4c9382014-12-01 19:08:07 +0000793 if (!ST->hasName())
794 continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000795
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000796 // Check to see if there is a dot in the name followed by a digit.
Bill Wendlingd48b7782012-02-28 04:01:21 +0000797 size_t DotPos = ST->getName().rfind('.');
798 if (DotPos == 0 || DotPos == StringRef::npos ||
Guy Benyei83c74e92013-02-12 21:21:59 +0000799 ST->getName().back() == '.' ||
Rafael Espindola973b3612014-12-01 19:17:46 +0000800 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
Bill Wendlingd48b7782012-02-28 04:01:21 +0000801 continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000802
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000803 // Check to see if the destination module has a struct with the prefix name.
Rafael Espindola973b3612014-12-01 19:17:46 +0000804 StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos));
805 if (!DST)
806 continue;
807
808 // Don't use it if this actually came from the source module. They're in
809 // the same LLVMContext after all. Also don't use it unless the type is
810 // actually used in the destination module. This can happen in situations
811 // like this:
812 //
813 // Module A Module B
814 // -------- --------
815 // %Z = type { %A } %B = type { %C.1 }
816 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
817 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
818 // %C = type { i8* } %B.3 = type { %C.1 }
819 //
820 // When we link Module B with Module A, the '%B' in Module B is
821 // used. However, that would then use '%C.1'. But when we process '%C.1',
822 // we prefer to take the '%C' version. So we are then left with both
823 // '%C.1' and '%C' being used for the same types. This leads to some
824 // variables using one type and some using the other.
Rafael Espindola31ad4682014-12-03 22:36:37 +0000825 if (TypeMap.DstStructTypesSet.hasType(DST))
Rafael Espindola973b3612014-12-01 19:17:46 +0000826 TypeMap.addTypeMapping(DST, ST);
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000827 }
828
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000829 // Now that we have discovered all of the type equivalences, get a body for
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000830 // any 'opaque' types in the dest module that are now resolved.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000831 TypeMap.linkDefinedTypeBodies();
Devang Patel5c310be2009-08-11 18:01:24 +0000832}
833
Duncan P. N. Exon Smith09d84ad2014-08-12 16:46:37 +0000834static void upgradeGlobalArray(GlobalVariable *GV) {
835 ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
836 StructType *OldTy = cast<StructType>(ATy->getElementType());
837 assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
838
839 // Get the upgraded 3 element type.
840 PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
841 Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
842 VoidPtrTy};
843 StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
844
845 // Build new constants with a null third field filled in.
846 Constant *OldInitC = GV->getInitializer();
847 ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
848 if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
849 // Invalid initializer; give up.
850 return;
851 std::vector<Constant *> Initializers;
852 if (OldInit && OldInit->getNumOperands()) {
853 Value *Null = Constant::getNullValue(VoidPtrTy);
854 for (Use &U : OldInit->operands()) {
855 ConstantStruct *Init = cast<ConstantStruct>(U.get());
856 Initializers.push_back(ConstantStruct::get(
857 NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
858 }
859 }
860 assert(Initializers.size() == ATy->getNumElements() &&
861 "Failed to copy all array elements");
862
863 // Replace the old GV with a new one.
864 ATy = ArrayType::get(NewTy, Initializers.size());
865 Constant *NewInit = ConstantArray::get(ATy, Initializers);
866 GlobalVariable *NewGV = new GlobalVariable(
867 *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
868 GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
869 GV->isExternallyInitialized());
870 NewGV->copyAttributesFrom(GV);
871 NewGV->takeName(GV);
872 assert(GV->use_empty() && "program cannot use initializer list");
873 GV->eraseFromParent();
874}
875
876void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
877 // Look for the global arrays.
878 auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name));
879 if (!DstGV)
880 return;
881 auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name));
882 if (!SrcGV)
883 return;
884
885 // Check if the types already match.
886 auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
887 auto *SrcTy =
888 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
889 if (DstTy == SrcTy)
890 return;
891
892 // Grab the element types. We can only upgrade an array of a two-field
893 // struct. Only bother if the other one has three-fields.
894 auto *DstEltTy = cast<StructType>(DstTy->getElementType());
895 auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
896 if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
897 upgradeGlobalArray(DstGV);
898 return;
899 }
900 if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
901 upgradeGlobalArray(SrcGV);
902
903 // We can't upgrade any other differences.
904}
905
906void ModuleLinker::upgradeMismatchedGlobals() {
907 upgradeMismatchedGlobalArray("llvm.global_ctors");
908 upgradeMismatchedGlobalArray("llvm.global_dtors");
909}
910
Rafael Espindola18c89412014-10-27 02:35:46 +0000911/// If there were any appending global variables, link them together now.
912/// Return true on error.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000913bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
Rafael Espindola3e8bc6a2014-10-31 16:08:17 +0000914 const GlobalVariable *SrcGV) {
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000915
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000916 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
917 return emitError("Linking globals named '" + SrcGV->getName() +
918 "': can only link appending global with another appending global!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000919
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000920 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
921 ArrayType *SrcTy =
922 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
923 Type *EltTy = DstTy->getElementType();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000924
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000925 // Check to see that they two arrays agree on type.
926 if (EltTy != SrcTy->getElementType())
927 return emitError("Appending variables with different element types!");
928 if (DstGV->isConstant() != SrcGV->isConstant())
929 return emitError("Appending variables linked with different const'ness!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000930
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000931 if (DstGV->getAlignment() != SrcGV->getAlignment())
932 return emitError(
933 "Appending variables with different alignment need to be linked!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000934
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000935 if (DstGV->getVisibility() != SrcGV->getVisibility())
936 return emitError(
937 "Appending variables with different visibility need to be linked!");
Rafael Espindolafac3a012013-09-04 15:33:34 +0000938
939 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
940 return emitError(
941 "Appending variables with different unnamed_addr need to be linked!");
942
Rafael Espindola64c1e182014-06-03 02:41:57 +0000943 if (StringRef(DstGV->getSection()) != SrcGV->getSection())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000944 return emitError(
945 "Appending variables with different section name need to be linked!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000946
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000947 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
948 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000949
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000950 // Create the new global variable.
951 GlobalVariable *NG =
952 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
Craig Topper2617dcc2014-04-15 06:32:26 +0000953 DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000954 DstGV->getThreadLocalMode(),
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000955 DstGV->getType()->getAddressSpace());
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000956
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000957 // Propagate alignment, visibility and section info.
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000958 copyGVAttributes(NG, DstGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000959
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000960 AppendingVarInfo AVI;
961 AVI.NewGV = NG;
962 AVI.DstInit = DstGV->getInitializer();
963 AVI.SrcInit = SrcGV->getInitializer();
964 AppendingVars.push_back(AVI);
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000965
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000966 // Replace any uses of the two global variables with uses of the new
967 // global.
968 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
Anton Korobeynikove79f4c72008-03-10 22:34:28 +0000969
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000970 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
971 DstGV->eraseFromParent();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000972
Tanya Lattnercbb91402011-10-11 00:24:54 +0000973 // Track the source variable so we don't try to link it.
974 DoNotLinkFromSource.insert(SrcGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000975
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000976 return false;
977}
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000978
Rafael Espindola778fcc72014-11-02 13:28:57 +0000979bool ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000980 GlobalValue *DGV = getLinkedToGlobal(SGV);
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000981
Rafael Espindola778fcc72014-11-02 13:28:57 +0000982 // Handle the ultra special appending linkage case first.
983 if (DGV && DGV->hasAppendingLinkage())
984 return linkAppendingVarProto(cast<GlobalVariable>(DGV),
985 cast<GlobalVariable>(SGV));
986
987 bool LinkFromSrc = true;
988 Comdat *C = nullptr;
989 GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
990 bool HasUnnamedAddr = SGV->hasUnnamedAddr();
991
David Majnemerdad0a642014-06-27 18:19:56 +0000992 if (const Comdat *SC = SGV->getComdat()) {
993 Comdat::SelectionKind SK;
994 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
Rafael Espindola778fcc72014-11-02 13:28:57 +0000995 C = DstM->getOrInsertComdat(SC->getName());
996 C->setSelectionKind(SK);
997 } else if (DGV) {
998 if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
999 return true;
1000 }
1001
1002 if (!LinkFromSrc) {
1003 // Track the source global so that we don't attempt to copy it over when
1004 // processing global initializers.
1005 DoNotLinkFromSource.insert(SGV);
1006
1007 if (DGV)
1008 // Make sure to remember this mapping.
1009 ValueMap[SGV] =
1010 ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->getType()));
David Majnemerdad0a642014-06-27 18:19:56 +00001011 }
1012
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001013 if (DGV) {
Rafael Espindola778fcc72014-11-02 13:28:57 +00001014 Visibility = isLessConstraining(Visibility, DGV->getVisibility())
1015 ? DGV->getVisibility()
1016 : Visibility;
1017 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1018 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001019
Rafael Espindola778fcc72014-11-02 13:28:57 +00001020 if (!LinkFromSrc && !DGV)
1021 return false;
Reid Spencer361e5132004-11-12 20:37:43 +00001022
Rafael Espindola778fcc72014-11-02 13:28:57 +00001023 GlobalValue *NewGV;
1024 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
1025 NewGV = linkGlobalVariableProto(SGVar, DGV, LinkFromSrc);
1026 if (!NewGV)
1027 return true;
1028 } else if (auto *SF = dyn_cast<Function>(SGV)) {
1029 NewGV = linkFunctionProto(SF, DGV, LinkFromSrc);
1030 } else {
1031 NewGV = linkGlobalAliasProto(cast<GlobalAlias>(SGV), DGV, LinkFromSrc);
1032 }
Rafael Espindolafe3842c2014-09-09 17:48:18 +00001033
Rafael Espindola778fcc72014-11-02 13:28:57 +00001034 if (NewGV) {
1035 if (NewGV != DGV)
1036 copyGVAttributes(NewGV, SGV);
David Majnemerdad0a642014-06-27 18:19:56 +00001037
Rafael Espindola778fcc72014-11-02 13:28:57 +00001038 NewGV->setUnnamedAddr(HasUnnamedAddr);
1039 NewGV->setVisibility(Visibility);
1040
1041 if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
1042 if (C)
1043 NewGO->setComdat(C);
Rafael Espindola439835a2014-12-05 00:09:02 +00001044
1045 if (DGV && DGV->hasCommonLinkage() && SGV->hasCommonLinkage())
1046 NewGO->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment()));
Chandler Carruthfd38af22014-11-02 09:10:31 +00001047 }
1048
Rafael Espindola778fcc72014-11-02 13:28:57 +00001049 // Make sure to remember this mapping.
1050 if (NewGV != DGV) {
1051 if (DGV) {
1052 DGV->replaceAllUsesWith(
1053 ConstantExpr::getBitCast(NewGV, DGV->getType()));
1054 DGV->eraseFromParent();
1055 }
1056 ValueMap[SGV] = NewGV;
Chris Lattner0ead7a52008-07-14 07:23:24 +00001057 }
Reid Spencer361e5132004-11-12 20:37:43 +00001058 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001059
Rafael Espindola778fcc72014-11-02 13:28:57 +00001060 return false;
1061}
1062
1063/// Loop through the global variables in the src module and merge them into the
1064/// dest module.
1065GlobalValue *ModuleLinker::linkGlobalVariableProto(const GlobalVariable *SGVar,
1066 GlobalValue *DGV,
1067 bool LinkFromSrc) {
Rafael Espindola778fcc72014-11-02 13:28:57 +00001068 bool ClearConstant = false;
1069
1070 if (DGV) {
Rafael Espindola778fcc72014-11-02 13:28:57 +00001071 auto *DGVar = dyn_cast<GlobalVariable>(DGV);
1072 if (!SGVar->isConstant() || (DGVar && !DGVar->isConstant()))
1073 ClearConstant = true;
1074 }
1075
1076 if (!LinkFromSrc) {
1077 if (auto *NewGVar = dyn_cast<GlobalVariable>(DGV)) {
Rafael Espindola778fcc72014-11-02 13:28:57 +00001078 if (NewGVar->isDeclaration() && ClearConstant)
1079 NewGVar->setConstant(false);
1080 }
1081 return DGV;
David Majnemerdad0a642014-06-27 18:19:56 +00001082 }
1083
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001084 // No linking to be performed or linking from the source: simply create an
1085 // identical version of the symbol over in the dest module... the
1086 // initializer will be filled in later by LinkGlobalInits.
Rafael Espindola778fcc72014-11-02 13:28:57 +00001087 GlobalVariable *NewDGV = new GlobalVariable(
1088 *DstM, TypeMap.get(SGVar->getType()->getElementType()),
1089 SGVar->isConstant(), SGVar->getLinkage(), /*init*/ nullptr,
1090 SGVar->getName(), /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
1091 SGVar->getType()->getAddressSpace());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001092
Rafael Espindola778fcc72014-11-02 13:28:57 +00001093 return NewDGV;
Reid Spencer361e5132004-11-12 20:37:43 +00001094}
1095
Rafael Espindola18c89412014-10-27 02:35:46 +00001096/// Link the function in the source module into the destination module if
1097/// needed, setting up mapping information.
Rafael Espindola778fcc72014-11-02 13:28:57 +00001098GlobalValue *ModuleLinker::linkFunctionProto(const Function *SF,
1099 GlobalValue *DGV,
1100 bool LinkFromSrc) {
1101 if (!LinkFromSrc)
1102 return DGV;
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001103
James Molloyf6f121e2013-05-28 15:17:05 +00001104 // If the function is to be lazily linked, don't create it just yet.
1105 // The ValueMaterializerTy will deal with creating it if it's used.
1106 if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
1107 SF->hasAvailableExternallyLinkage())) {
1108 DoNotLinkFromSource.insert(SF);
Rafael Espindola778fcc72014-11-02 13:28:57 +00001109 return nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00001110 }
1111
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001112 // If there is no linkage to be performed or we are linking from the source,
1113 // bring SF over.
Rafael Espindola778fcc72014-11-02 13:28:57 +00001114 return Function::Create(TypeMap.get(SF->getFunctionType()), SF->getLinkage(),
1115 SF->getName(), DstM);
Lauro Ramos Venanciob00c9c02007-06-28 19:02:54 +00001116}
1117
Rafael Espindola18c89412014-10-27 02:35:46 +00001118/// Set up prototypes for any aliases that come over from the source module.
Rafael Espindola778fcc72014-11-02 13:28:57 +00001119GlobalValue *ModuleLinker::linkGlobalAliasProto(const GlobalAlias *SGA,
1120 GlobalValue *DGV,
1121 bool LinkFromSrc) {
1122 if (!LinkFromSrc)
1123 return DGV;
David Majnemerdad0a642014-06-27 18:19:56 +00001124
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001125 // If there is no linkage to be performed or we're linking from the source,
1126 // bring over SGA.
Rafael Espindola4fe00942014-05-16 13:34:04 +00001127 auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType()));
Rafael Espindola778fcc72014-11-02 13:28:57 +00001128 return GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
1129 SGA->getLinkage(), SGA->getName(), DstM);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001130}
1131
Rafael Espindola3e8bc6a2014-10-31 16:08:17 +00001132static void getArrayElements(const Constant *C,
1133 SmallVectorImpl<Constant *> &Dest) {
Chris Lattner67058832012-01-25 06:48:06 +00001134 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
1135
1136 for (unsigned i = 0; i != NumElements; ++i)
1137 Dest.push_back(C->getAggregateElement(i));
Chris Lattner00245f42012-01-24 13:41:11 +00001138}
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001139
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001140void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
1141 // Merge the initializer.
Rafael Espindolad31dc042014-09-05 21:27:52 +00001142 SmallVector<Constant *, 16> DstElements;
1143 getArrayElements(AVI.DstInit, DstElements);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001144
Rafael Espindolad31dc042014-09-05 21:27:52 +00001145 SmallVector<Constant *, 16> SrcElements;
1146 getArrayElements(AVI.SrcInit, SrcElements);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001147
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001148 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
Rafael Espindolad31dc042014-09-05 21:27:52 +00001149
1150 StringRef Name = AVI.NewGV->getName();
1151 bool IsNewStructor =
1152 (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
1153 cast<StructType>(NewType->getElementType())->getNumElements() == 3;
1154
1155 for (auto *V : SrcElements) {
1156 if (IsNewStructor) {
1157 Constant *Key = V->getAggregateElement(2);
1158 if (DoNotLinkFromSource.count(Key))
1159 continue;
1160 }
1161 DstElements.push_back(
1162 MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer));
1163 }
1164 if (IsNewStructor) {
1165 NewType = ArrayType::get(NewType->getElementType(), DstElements.size());
1166 AVI.NewGV->mutateType(PointerType::get(NewType, 0));
1167 }
1168
1169 AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001170}
1171
Rafael Espindola18c89412014-10-27 02:35:46 +00001172/// Update the initializers in the Dest module now that all globals that may be
1173/// referenced are in Dest.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001174void ModuleLinker::linkGlobalInits() {
Reid Spencer361e5132004-11-12 20:37:43 +00001175 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001176 for (Module::const_global_iterator I = SrcM->global_begin(),
1177 E = SrcM->global_end(); I != E; ++I) {
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001178
Tanya Lattnercbb91402011-10-11 00:24:54 +00001179 // Only process initialized GV's or ones not already in dest.
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001180 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
1181
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001182 // Grab destination global variable.
1183 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
1184 // Figure out what the initializer looks like in the dest module.
1185 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
James Molloyf6f121e2013-05-28 15:17:05 +00001186 RF_None, &TypeMap, &ValMaterializer));
Reid Spencer361e5132004-11-12 20:37:43 +00001187 }
Reid Spencer361e5132004-11-12 20:37:43 +00001188}
1189
Rafael Espindola18c89412014-10-27 02:35:46 +00001190/// Copy the source function over into the dest function and fix up references
1191/// to values. At this point we know that Dest is an external function, and
1192/// that Src is not.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001193void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
1194 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
Reid Spencer361e5132004-11-12 20:37:43 +00001195
Chris Lattner7391dde2004-11-16 17:12:38 +00001196 // Go through and convert function arguments over, remembering the mapping.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001197 Function::arg_iterator DI = Dst->arg_begin();
Chris Lattner531f9e92005-03-15 04:54:21 +00001198 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
Reid Spencer361e5132004-11-12 20:37:43 +00001199 I != E; ++I, ++DI) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001200 DI->setName(I->getName()); // Copy the name over.
Reid Spencer361e5132004-11-12 20:37:43 +00001201
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001202 // Add a mapping to our mapping.
Anton Korobeynikov66a62712008-03-10 22:36:08 +00001203 ValueMap[I] = DI;
Reid Spencer361e5132004-11-12 20:37:43 +00001204 }
1205
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001206 // Splice the body of the source function into the dest function.
1207 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001208
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001209 // At this point, all of the instructions and values of the function are now
1210 // copied over. The only problem is that they are still referencing values in
1211 // the Source function as operands. Loop through all of the operands of the
1212 // functions and patch them up to point to the local versions.
1213 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
1214 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1215 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap,
1216 &ValMaterializer);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001217
Chris Lattner7391dde2004-11-16 17:12:38 +00001218 // There is no need to map the arguments anymore.
Chris Lattner44ab8ae2006-06-16 01:24:04 +00001219 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1220 I != E; ++I)
Reid Spencer3aaaa0b2007-02-05 20:47:22 +00001221 ValueMap.erase(I);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001222
Reid Spencer361e5132004-11-12 20:37:43 +00001223}
1224
Rafael Espindola18c89412014-10-27 02:35:46 +00001225/// Insert all of the aliases in Src into the Dest module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001226void ModuleLinker::linkAliasBodies() {
1227 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
Tanya Lattnercbb91402011-10-11 00:24:54 +00001228 I != E; ++I) {
1229 if (DoNotLinkFromSource.count(I))
1230 continue;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001231 if (Constant *Aliasee = I->getAliasee()) {
1232 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
Rafael Espindola6b238632014-05-16 19:35:39 +00001233 Constant *Val =
1234 MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer);
Rafael Espindola64c1e182014-06-03 02:41:57 +00001235 DA->setAliasee(Val);
David Chisnall2c4a34a2010-01-09 16:27:31 +00001236 }
Tanya Lattnercbb91402011-10-11 00:24:54 +00001237 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001238}
Anton Korobeynikov26098882008-03-05 23:21:39 +00001239
Rafael Espindola18c89412014-10-27 02:35:46 +00001240/// Insert all of the named MDNodes in Src into the Dest module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001241void ModuleLinker::linkNamedMDNodes() {
Bill Wendling66f02412012-02-11 11:38:06 +00001242 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001243 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1244 E = SrcM->named_metadata_end(); I != E; ++I) {
Bill Wendling66f02412012-02-11 11:38:06 +00001245 // Don't link module flags here. Do them separately.
1246 if (&*I == SrcModFlags) continue;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001247 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1248 // Add Src elements into Dest node.
1249 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1250 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
James Molloyf6f121e2013-05-28 15:17:05 +00001251 RF_None, &TypeMap, &ValMaterializer));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001252 }
1253}
Bill Wendling66f02412012-02-11 11:38:06 +00001254
Rafael Espindola18c89412014-10-27 02:35:46 +00001255/// Merge the linker flags in Src into the Dest module.
Bill Wendling66f02412012-02-11 11:38:06 +00001256bool ModuleLinker::linkModuleFlagsMetadata() {
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001257 // If the source module has no module flags, we are done.
Bill Wendling66f02412012-02-11 11:38:06 +00001258 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1259 if (!SrcModFlags) return false;
1260
Bill Wendling66f02412012-02-11 11:38:06 +00001261 // If the destination module doesn't have module flags yet, then just copy
1262 // over the source module's flags.
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001263 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
Bill Wendling66f02412012-02-11 11:38:06 +00001264 if (DstModFlags->getNumOperands() == 0) {
1265 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1266 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1267
1268 return false;
1269 }
1270
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001271 // First build a map of the existing module flags and requirements.
1272 DenseMap<MDString*, MDNode*> Flags;
1273 SmallSetVector<MDNode*, 16> Requirements;
1274 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001275 MDNode *Op = DstModFlags->getOperand(I);
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001276 ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1277 MDString *ID = cast<MDString>(Op->getOperand(1));
Bill Wendling66f02412012-02-11 11:38:06 +00001278
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001279 if (Behavior->getZExtValue() == Module::Require) {
1280 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1281 } else {
1282 Flags[ID] = Op;
1283 }
Bill Wendling66f02412012-02-11 11:38:06 +00001284 }
1285
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001286 // Merge in the flags from the source module, and also collect its set of
1287 // requirements.
1288 bool HasErr = false;
1289 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001290 MDNode *SrcOp = SrcModFlags->getOperand(I);
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001291 ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1292 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1293 MDNode *DstOp = Flags.lookup(ID);
1294 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
Bill Wendling66f02412012-02-11 11:38:06 +00001295
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001296 // If this is a requirement, add it and continue.
1297 if (SrcBehaviorValue == Module::Require) {
1298 // If the destination module does not already have this requirement, add
1299 // it.
1300 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1301 DstModFlags->addOperand(SrcOp);
1302 }
1303 continue;
Bill Wendling66f02412012-02-11 11:38:06 +00001304 }
1305
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001306 // If there is no existing flag with this ID, just add it.
1307 if (!DstOp) {
1308 Flags[ID] = SrcOp;
1309 DstModFlags->addOperand(SrcOp);
1310 continue;
1311 }
1312
1313 // Otherwise, perform a merge.
1314 ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1315 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1316
1317 // If either flag has override behavior, handle it first.
1318 if (DstBehaviorValue == Module::Override) {
1319 // Diagnose inconsistent flags which both have override behavior.
1320 if (SrcBehaviorValue == Module::Override &&
1321 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1322 HasErr |= emitError("linking module flags '" + ID->getString() +
1323 "': IDs have conflicting override values");
1324 }
1325 continue;
1326 } else if (SrcBehaviorValue == Module::Override) {
1327 // Update the destination flag to that of the source.
1328 DstOp->replaceOperandWith(0, SrcBehavior);
1329 DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1330 continue;
1331 }
1332
1333 // Diagnose inconsistent merge behavior types.
1334 if (SrcBehaviorValue != DstBehaviorValue) {
1335 HasErr |= emitError("linking module flags '" + ID->getString() +
1336 "': IDs have conflicting behaviors");
1337 continue;
1338 }
1339
1340 // Perform the merge for standard behavior types.
1341 switch (SrcBehaviorValue) {
1342 case Module::Require:
Craig Topper2a30d782014-06-18 05:05:13 +00001343 case Module::Override: llvm_unreachable("not possible");
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001344 case Module::Error: {
1345 // Emit an error if the values differ.
1346 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1347 HasErr |= emitError("linking module flags '" + ID->getString() +
1348 "': IDs have conflicting values");
1349 }
1350 continue;
1351 }
1352 case Module::Warning: {
1353 // Emit a warning if the values differ.
1354 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001355 emitWarning("linking module flags '" + ID->getString() +
1356 "': IDs have conflicting values");
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001357 }
1358 continue;
1359 }
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001360 case Module::Append: {
1361 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1362 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1363 unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1364 Value **VP, **Values = VP = new Value*[NumOps];
1365 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1366 *VP = DstValue->getOperand(i);
1367 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1368 *VP = SrcValue->getOperand(i);
1369 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1370 ArrayRef<Value*>(Values,
1371 NumOps)));
1372 delete[] Values;
1373 break;
1374 }
1375 case Module::AppendUnique: {
1376 SmallSetVector<Value*, 16> Elts;
1377 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1378 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1379 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1380 Elts.insert(DstValue->getOperand(i));
1381 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1382 Elts.insert(SrcValue->getOperand(i));
1383 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1384 ArrayRef<Value*>(Elts.begin(),
1385 Elts.end())));
1386 break;
1387 }
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001388 }
Bill Wendling66f02412012-02-11 11:38:06 +00001389 }
1390
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001391 // Check all of the requirements.
1392 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1393 MDNode *Requirement = Requirements[I];
1394 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1395 Value *ReqValue = Requirement->getOperand(1);
Bill Wendling66f02412012-02-11 11:38:06 +00001396
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001397 MDNode *Op = Flags[Flag];
1398 if (!Op || Op->getOperand(2) != ReqValue) {
1399 HasErr |= emitError("linking module flags '" + Flag->getString() +
1400 "': does not have the required value");
1401 continue;
Bill Wendling66f02412012-02-11 11:38:06 +00001402 }
1403 }
1404
1405 return HasErr;
1406}
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001407
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001408bool ModuleLinker::run() {
Bill Wendling66f02412012-02-11 11:38:06 +00001409 assert(DstM && "Null destination module");
1410 assert(SrcM && "Null source module");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001411
1412 // Inherit the target data from the source module if the destination module
1413 // doesn't have one already.
Rafael Espindolaf863ee22014-02-25 20:01:08 +00001414 if (!DstM->getDataLayout() && SrcM->getDataLayout())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001415 DstM->setDataLayout(SrcM->getDataLayout());
1416
1417 // Copy the target triple from the source to dest if the dest's is empty.
1418 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1419 DstM->setTargetTriple(SrcM->getTargetTriple());
1420
Rafael Espindolaf863ee22014-02-25 20:01:08 +00001421 if (SrcM->getDataLayout() && DstM->getDataLayout() &&
Rafael Espindolaae593f12014-02-26 17:02:08 +00001422 *SrcM->getDataLayout() != *DstM->getDataLayout()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001423 emitWarning("Linking two modules of different data layouts: '" +
1424 SrcM->getModuleIdentifier() + "' is '" +
1425 SrcM->getDataLayoutStr() + "' whereas '" +
1426 DstM->getModuleIdentifier() + "' is '" +
1427 DstM->getDataLayoutStr() + "'\n");
Eli Benderskye17f3702014-02-06 18:01:56 +00001428 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001429 if (!SrcM->getTargetTriple().empty() &&
1430 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001431 emitWarning("Linking two modules of different target triples: " +
1432 SrcM->getModuleIdentifier() + "' is '" +
1433 SrcM->getTargetTriple() + "' whereas '" +
1434 DstM->getModuleIdentifier() + "' is '" +
1435 DstM->getTargetTriple() + "'\n");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001436 }
1437
1438 // Append the module inline asm string.
1439 if (!SrcM->getModuleInlineAsm().empty()) {
1440 if (DstM->getModuleInlineAsm().empty())
1441 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1442 else
1443 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1444 SrcM->getModuleInlineAsm());
1445 }
1446
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001447 // Loop over all of the linked values to compute type mappings.
1448 computeTypeMapping();
1449
David Majnemerdad0a642014-06-27 18:19:56 +00001450 ComdatsChosen.clear();
David Blaikie5106ce72014-11-19 05:49:42 +00001451 for (const auto &SMEC : SrcM->getComdatSymbolTable()) {
David Majnemerdad0a642014-06-27 18:19:56 +00001452 const Comdat &C = SMEC.getValue();
1453 if (ComdatsChosen.count(&C))
1454 continue;
1455 Comdat::SelectionKind SK;
1456 bool LinkFromSrc;
1457 if (getComdatResult(&C, SK, LinkFromSrc))
1458 return true;
1459 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1460 }
1461
Duncan P. N. Exon Smith09d84ad2014-08-12 16:46:37 +00001462 // Upgrade mismatched global arrays.
1463 upgradeMismatchedGlobals();
1464
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001465 // Insert all of the globals in src into the DstM module... without linking
1466 // initializers (which could refer to functions not yet mapped over).
1467 for (Module::global_iterator I = SrcM->global_begin(),
1468 E = SrcM->global_end(); I != E; ++I)
Rafael Espindola778fcc72014-11-02 13:28:57 +00001469 if (linkGlobalValueProto(I))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001470 return true;
1471
1472 // Link the functions together between the two modules, without doing function
1473 // bodies... this just adds external function prototypes to the DstM
1474 // function... We do this so that when we begin processing function bodies,
1475 // all of the global values that may be referenced are available in our
1476 // ValueMap.
1477 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
Rafael Espindola778fcc72014-11-02 13:28:57 +00001478 if (linkGlobalValueProto(I))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001479 return true;
1480
1481 // If there were any aliases, link them now.
1482 for (Module::alias_iterator I = SrcM->alias_begin(),
1483 E = SrcM->alias_end(); I != E; ++I)
Rafael Espindola778fcc72014-11-02 13:28:57 +00001484 if (linkGlobalValueProto(I))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001485 return true;
1486
1487 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1488 linkAppendingVarInit(AppendingVars[i]);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001489
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001490 // Link in the function bodies that are defined in the source module into
1491 // DstM.
1492 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
Tanya Lattnerea166d42011-10-14 22:17:46 +00001493 // Skip if not linking from source.
1494 if (DoNotLinkFromSource.count(SF)) continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001495
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001496 Function *DF = cast<Function>(ValueMap[SF]);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001497
1498 // Link in the prefix data.
1499 if (SF->hasPrefixData())
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001500 DF->setPrefixData(MapValue(
1501 SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001502
1503 // Link in the prologue data.
1504 if (SF->hasPrologueData())
1505 DF->setPrologueData(MapValue(
1506 SF->getPrologueData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001507
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00001508 // Materialize if needed.
Rafael Espindola246c4fb2014-11-01 16:46:18 +00001509 if (std::error_code EC = SF->materialize())
1510 return emitError(EC.message());
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001511
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00001512 // Skip if no body (function is external).
1513 if (SF->isDeclaration())
1514 continue;
1515
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001516 linkFunctionBody(DF, SF);
Bill Wendling00623782012-03-23 07:22:49 +00001517 SF->Dematerialize();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001518 }
1519
1520 // Resolve all uses of aliases with aliasees.
1521 linkAliasBodies();
1522
Bill Wendling66f02412012-02-11 11:38:06 +00001523 // Remap all of the named MDNodes in Src into the DstM module. We do this
Devang Patel6ddbb2e2011-08-04 19:44:28 +00001524 // after linking GlobalValues so that MDNodes that reference GlobalValues
1525 // are properly remapped.
1526 linkNamedMDNodes();
1527
Bill Wendling66f02412012-02-11 11:38:06 +00001528 // Merge the module flags into the DstM module.
1529 if (linkModuleFlagsMetadata())
1530 return true;
1531
Bill Wendling91686d62014-01-16 06:29:36 +00001532 // Update the initializers in the DstM module now that all globals that may
1533 // be referenced are in DstM.
1534 linkGlobalInits();
1535
Tanya Lattner0a48b872011-11-02 00:24:56 +00001536 // Process vector of lazily linked in functions.
1537 bool LinkedInAnyFunctions;
1538 do {
1539 LinkedInAnyFunctions = false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001540
Bill Wendlingfa2287822013-03-27 17:54:41 +00001541 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001542 E = LazilyLinkFunctions.end(); I != E; ++I) {
Bill Wendlingfa2287822013-03-27 17:54:41 +00001543 Function *SF = *I;
James Molloyf6f121e2013-05-28 15:17:05 +00001544 if (!SF)
1545 continue;
Bill Wendling00623782012-03-23 07:22:49 +00001546
James Molloyf6f121e2013-05-28 15:17:05 +00001547 Function *DF = cast<Function>(ValueMap[SF]);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001548 if (SF->hasPrefixData()) {
1549 // Link in the prefix data.
1550 DF->setPrefixData(MapValue(SF->getPrefixData(),
1551 ValueMap,
1552 RF_None,
1553 &TypeMap,
1554 &ValMaterializer));
1555 }
James Molloyf6f121e2013-05-28 15:17:05 +00001556
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00001557 // Materialize if needed.
Rafael Espindola246c4fb2014-11-01 16:46:18 +00001558 if (std::error_code EC = SF->materialize())
1559 return emitError(EC.message());
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001560
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00001561 // Skip if no body (function is external).
1562 if (SF->isDeclaration())
1563 continue;
1564
James Molloyf6f121e2013-05-28 15:17:05 +00001565 // Erase from vector *before* the function body is linked - linkFunctionBody could
1566 // invalidate I.
1567 LazilyLinkFunctions.erase(I);
1568
1569 // Link in function body.
1570 linkFunctionBody(DF, SF);
1571 SF->Dematerialize();
1572
1573 // Set flag to indicate we may have more functions to lazily link in
1574 // since we linked in a function.
1575 LinkedInAnyFunctions = true;
1576 break;
Tanya Lattner0a48b872011-11-02 00:24:56 +00001577 }
1578 } while (LinkedInAnyFunctions);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001579
Anton Korobeynikov26098882008-03-05 23:21:39 +00001580 return false;
1581}
Reid Spencer361e5132004-11-12 20:37:43 +00001582
Rafael Espindola31ad4682014-12-03 22:36:37 +00001583Linker::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
1584 : ETypes(E), IsPacked(P) {}
1585
1586Linker::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
1587 : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1588
1589bool Linker::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
1590 if (IsPacked != That.IsPacked)
1591 return false;
1592 if (ETypes != That.ETypes)
1593 return false;
1594 return true;
1595}
1596
1597bool Linker::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
1598 return !this->operator==(That);
1599}
1600
1601StructType *Linker::StructTypeKeyInfo::getEmptyKey() {
1602 return DenseMapInfo<StructType *>::getEmptyKey();
1603}
1604
1605StructType *Linker::StructTypeKeyInfo::getTombstoneKey() {
1606 return DenseMapInfo<StructType *>::getTombstoneKey();
1607}
1608
1609unsigned Linker::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1610 return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1611 Key.IsPacked);
1612}
1613
1614unsigned Linker::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1615 return getHashValue(KeyTy(ST));
1616}
1617
1618bool Linker::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1619 const StructType *RHS) {
1620 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1621 return false;
1622 return LHS == KeyTy(RHS);
1623}
1624
1625bool Linker::StructTypeKeyInfo::isEqual(const StructType *LHS,
1626 const StructType *RHS) {
1627 if (RHS == getEmptyKey())
1628 return LHS == getEmptyKey();
1629
1630 if (RHS == getTombstoneKey())
1631 return LHS == getTombstoneKey();
1632
1633 return KeyTy(LHS) == KeyTy(RHS);
1634}
1635
1636void Linker::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
1637 assert(!Ty->isOpaque());
1638 bool &Entry = NonOpaqueStructTypes[Ty];
1639 Entry = true;
1640}
1641
1642void Linker::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
1643 assert(Ty->isOpaque());
1644 OpaqueStructTypes.insert(Ty);
1645}
1646
1647StructType *
1648Linker::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
1649 bool IsPacked) {
1650 Linker::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
1651 auto I = NonOpaqueStructTypes.find_as(Key);
1652 if (I == NonOpaqueStructTypes.end())
1653 return nullptr;
1654 return I->first;
1655}
1656
1657bool Linker::IdentifiedStructTypeSet::hasType(StructType *Ty) {
1658 if (Ty->isOpaque())
1659 return OpaqueStructTypes.count(Ty);
1660 auto I = NonOpaqueStructTypes.find(Ty);
1661 if (I == NonOpaqueStructTypes.end())
1662 return false;
1663 return I->first == Ty;
1664}
1665
Rafael Espindola5cb9c822014-11-17 20:51:01 +00001666void Linker::init(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
1667 this->Composite = M;
1668 this->DiagnosticHandler = DiagnosticHandler;
Rafael Espindolaa4e85e32014-12-01 16:32:20 +00001669
1670 TypeFinder StructTypes;
1671 StructTypes.run(*M, true);
Rafael Espindola31ad4682014-12-03 22:36:37 +00001672 for (StructType *Ty : StructTypes) {
1673 if (Ty->isOpaque())
1674 IdentifiedStructTypes.addOpaque(Ty);
1675 else
1676 IdentifiedStructTypes.addNonOpaque(Ty);
1677 }
Rafael Espindolaaa9918a2013-05-04 05:05:18 +00001678}
Rafael Espindola3df61b72013-05-04 03:48:37 +00001679
Rafael Espindola5cb9c822014-11-17 20:51:01 +00001680Linker::Linker(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
1681 init(M, DiagnosticHandler);
1682}
1683
1684Linker::Linker(Module *M) {
1685 init(M, [this](const DiagnosticInfo &DI) {
1686 Composite->getContext().diagnose(DI);
1687 });
1688}
1689
Rafael Espindola3df61b72013-05-04 03:48:37 +00001690Linker::~Linker() {
1691}
1692
Bill Wendling91e6f6e2013-10-16 08:59:57 +00001693void Linker::deleteModule() {
1694 delete Composite;
Craig Topper2617dcc2014-04-15 06:32:26 +00001695 Composite = nullptr;
Bill Wendling91e6f6e2013-10-16 08:59:57 +00001696}
1697
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001698bool Linker::linkInModule(Module *Src) {
Rafael Espindolaa4e85e32014-12-01 16:32:20 +00001699 ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src,
1700 DiagnosticHandler);
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001701 return TheLinker.run();
Rafael Espindola3df61b72013-05-04 03:48:37 +00001702}
1703
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001704//===----------------------------------------------------------------------===//
1705// LinkModules entrypoint.
1706//===----------------------------------------------------------------------===//
1707
Rafael Espindola18c89412014-10-27 02:35:46 +00001708/// This function links two modules together, with the resulting Dest module
1709/// modified to be the composite of the two input modules. If an error occurs,
1710/// true is returned and ErrorMsg (if not null) is set to indicate the problem.
1711/// Upon failure, the Dest module could be in a modified state, and shouldn't be
1712/// relied on to be consistent.
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001713bool Linker::LinkModules(Module *Dest, Module *Src,
Rafael Espindola4160f5d2014-10-27 23:02:10 +00001714 DiagnosticHandlerFunction DiagnosticHandler) {
1715 Linker L(Dest, DiagnosticHandler);
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001716 return L.linkInModule(Src);
Rafael Espindola4160f5d2014-10-27 23:02:10 +00001717}
1718
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001719bool Linker::LinkModules(Module *Dest, Module *Src) {
Rafael Espindola287f18b2013-05-04 04:08:02 +00001720 Linker L(Dest);
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001721 return L.linkInModule(Src);
Reid Spencer361e5132004-11-12 20:37:43 +00001722}
Bill Wendlinga3aeb982012-05-09 08:55:40 +00001723
1724//===----------------------------------------------------------------------===//
1725// C API.
1726//===----------------------------------------------------------------------===//
1727
1728LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1729 LLVMLinkerMode Mode, char **OutMessages) {
Rafael Espindola98ab63c2014-10-25 04:31:08 +00001730 Module *D = unwrap(Dest);
Rafael Espindola98ab63c2014-10-25 04:31:08 +00001731 std::string Message;
Rafael Espindola4160f5d2014-10-27 23:02:10 +00001732 raw_string_ostream Stream(Message);
1733 DiagnosticPrinterRawOStream DP(Stream);
1734
1735 LLVMBool Result = Linker::LinkModules(
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001736 D, unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
Rafael Espindola98ab63c2014-10-25 04:31:08 +00001737
1738 if (OutMessages && Result)
1739 *OutMessages = strdup(Message.c_str());
Bill Wendlinga3aeb982012-05-09 08:55:40 +00001740 return Result;
1741}