blob: 767d465d1bee6da2d78e2e17cce041231bb53ddd [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"
Duncan P. N. Exon Smithfda0cee2014-12-18 01:05:33 +000022#include "llvm/IR/DebugInfo.h"
Rafael Espindolad12b4a32014-10-25 04:06:10 +000023#include "llvm/IR/DiagnosticInfo.h"
24#include "llvm/IR/DiagnosticPrinter.h"
25#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Module.h"
Chandler Carruthdcb603f2013-01-07 15:43:51 +000027#include "llvm/IR/TypeFinder.h"
Eli Benderskye17f3702014-02-06 18:01:56 +000028#include "llvm/Support/CommandLine.h"
Bill Wendlingb6af2f32012-03-22 20:28:27 +000029#include "llvm/Support/Debug.h"
Bill Wendlingb6af2f32012-03-22 20:28:27 +000030#include "llvm/Support/raw_ostream.h"
Tanya Lattnercbb91402011-10-11 00:24:54 +000031#include "llvm/Transforms/Utils/Cloning.h"
Will Dietz981af002013-10-12 00:55:57 +000032#include <cctype>
David Majnemer82d6ff62014-06-27 18:38:12 +000033#include <tuple>
Reid Spencer361e5132004-11-12 20:37:43 +000034using namespace llvm;
35
Eli Benderskye17f3702014-02-06 18:01:56 +000036
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000037//===----------------------------------------------------------------------===//
38// TypeMap implementation.
39//===----------------------------------------------------------------------===//
Reid Spencer361e5132004-11-12 20:37:43 +000040
Chris Lattnereee6f992008-06-16 21:00:18 +000041namespace {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000042class TypeMapTy : public ValueMapTypeRemapper {
Rafael Espindola18c89412014-10-27 02:35:46 +000043 /// This is a mapping from a source type to a destination type to use.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000044 DenseMap<Type*, Type*> MappedTypes;
Mikhail Glushenkov766d4892009-03-03 07:22:23 +000045
Rafael Espindola18c89412014-10-27 02:35:46 +000046 /// When checking to see if two subgraphs are isomorphic, we speculatively
47 /// add types to MappedTypes, but keep track of them here in case we need to
48 /// roll back.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000049 SmallVector<Type*, 16> SpeculativeTypes;
Rafael Espindolaed6dc372014-05-09 14:39:25 +000050
Rafael Espindolaa96f2352014-11-28 16:41:24 +000051 SmallVector<StructType*, 16> SpeculativeDstOpaqueTypes;
52
Rafael Espindola18c89412014-10-27 02:35:46 +000053 /// This is a list of non-opaque structs in the source module that are mapped
54 /// to an opaque struct in the destination module.
Chris Lattner5e3bd972011-12-20 00:03:52 +000055 SmallVector<StructType*, 16> SrcDefinitionsToResolve;
Rafael Espindolaed6dc372014-05-09 14:39:25 +000056
Rafael Espindola18c89412014-10-27 02:35:46 +000057 /// This is the set of opaque types in the destination modules who are
58 /// getting a body from the source module.
Chris Lattner5e3bd972011-12-20 00:03:52 +000059 SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
Bill Wendling8c2cc412012-03-22 20:30:41 +000060
Chris Lattner56cdea62008-06-16 23:06:51 +000061public:
Rafael Espindola31ad4682014-12-03 22:36:37 +000062 TypeMapTy(Linker::IdentifiedStructTypeSet &DstStructTypesSet)
63 : DstStructTypesSet(DstStructTypesSet) {}
Rafael Espindolaaa9918a2013-05-04 05:05:18 +000064
Rafael Espindola31ad4682014-12-03 22:36:37 +000065 Linker::IdentifiedStructTypeSet &DstStructTypesSet;
Rafael Espindola18c89412014-10-27 02:35:46 +000066 /// Indicate that the specified type in the destination module is conceptually
67 /// equivalent to the specified type in the source module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000068 void addTypeMapping(Type *DstTy, Type *SrcTy);
69
Rafael Espindolad2a13a22014-11-25 04:28:31 +000070 /// Produce a body for an opaque type in the dest module from a type
71 /// definition in the source module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000072 void linkDefinedTypeBodies();
Rafael Espindolaed6dc372014-05-09 14:39:25 +000073
Rafael Espindola18c89412014-10-27 02:35:46 +000074 /// Return the mapped type to use for the specified input type from the
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000075 /// source module.
76 Type *get(Type *SrcTy);
Rafael Espindola31ad4682014-12-03 22:36:37 +000077 Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
78
79 void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000080
Rafael Espindola290e2cc2014-11-25 14:35:53 +000081 FunctionType *get(FunctionType *T) {
82 return cast<FunctionType>(get((Type *)T));
83 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000084
Rafael Espindola18c89412014-10-27 02:35:46 +000085 /// Dump out the type map for debugging purposes.
Bill Wendlingb6af2f32012-03-22 20:28:27 +000086 void dump() const {
Rafael Espindola8f144712014-11-25 06:16:27 +000087 for (auto &Pair : MappedTypes) {
Bill Wendlingb6af2f32012-03-22 20:28:27 +000088 dbgs() << "TypeMap: ";
Rafael Espindola8f144712014-11-25 06:16:27 +000089 Pair.first->print(dbgs());
Bill Wendlingb6af2f32012-03-22 20:28:27 +000090 dbgs() << " => ";
Rafael Espindola8f144712014-11-25 06:16:27 +000091 Pair.second->print(dbgs());
Bill Wendlingb6af2f32012-03-22 20:28:27 +000092 dbgs() << '\n';
93 }
94 }
Bill Wendlingb6af2f32012-03-22 20:28:27 +000095
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000096private:
Rafael Espindola290e2cc2014-11-25 14:35:53 +000097 Type *remapType(Type *SrcTy) override { return get(SrcTy); }
Rafael Espindolaed6dc372014-05-09 14:39:25 +000098
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000099 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
Chris Lattnereee6f992008-06-16 21:00:18 +0000100};
101}
102
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000103void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
Rafael Espindola3d097412014-11-28 16:26:14 +0000104 assert(SpeculativeTypes.empty());
Rafael Espindolaa96f2352014-11-28 16:41:24 +0000105 assert(SpeculativeDstOpaqueTypes.empty());
Rafael Espindola3d097412014-11-28 16:26:14 +0000106
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000107 // Check to see if these types are recursively isomorphic and establish a
108 // mapping between them if so.
Duncan P. N. Exon Smithc586eaa2014-11-27 17:01:10 +0000109 if (!areTypesIsomorphic(DstTy, SrcTy)) {
110 // Oops, they aren't isomorphic. Just discard this request by rolling out
111 // any speculative mappings we've established.
Rafael Espindola3d097412014-11-28 16:26:14 +0000112 for (Type *Ty : SpeculativeTypes)
113 MappedTypes.erase(Ty);
Rafael Espindolaa96f2352014-11-28 16:41:24 +0000114
115 SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
116 SpeculativeDstOpaqueTypes.size());
117 for (StructType *Ty : SpeculativeDstOpaqueTypes)
118 DstResolvedOpaqueTypes.erase(Ty);
Rafael Espindola04a74af2014-12-01 04:15:59 +0000119 } else {
120 for (Type *Ty : SpeculativeTypes)
121 if (auto *STy = dyn_cast<StructType>(Ty))
122 if (STy->hasName())
123 STy->setName("");
Bill Wendlingd48b7782012-02-28 04:01:21 +0000124 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000125 SpeculativeTypes.clear();
Rafael Espindolaa96f2352014-11-28 16:41:24 +0000126 SpeculativeDstOpaqueTypes.clear();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000127}
Chris Lattnereee6f992008-06-16 21:00:18 +0000128
Rafael Espindola18c89412014-10-27 02:35:46 +0000129/// Recursively walk this pair of types, returning true if they are isomorphic,
130/// false if they are not.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000131bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
132 // Two types with differing kinds are clearly not isomorphic.
Rafael Espindola290e2cc2014-11-25 14:35:53 +0000133 if (DstTy->getTypeID() != SrcTy->getTypeID())
134 return false;
Misha Brukman10468d82005-04-21 22:55:34 +0000135
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000136 // If we have an entry in the MappedTypes table, then we have our answer.
137 Type *&Entry = MappedTypes[SrcTy];
138 if (Entry)
139 return Entry == DstTy;
Misha Brukman10468d82005-04-21 22:55:34 +0000140
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000141 // Two identical types are clearly isomorphic. Remember this
142 // non-speculatively.
143 if (DstTy == SrcTy) {
144 Entry = DstTy;
Chris Lattnerfe677e92008-06-16 20:03:01 +0000145 return true;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000146 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000147
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000148 // Okay, we have two types with identical kinds that we haven't seen before.
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000149
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000150 // If this is an opaque struct type, special case it.
151 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
152 // Mapping an opaque type to any struct, just keep the dest struct.
153 if (SSTy->isOpaque()) {
154 Entry = DstTy;
155 SpeculativeTypes.push_back(SrcTy);
Reid Spencer361e5132004-11-12 20:37:43 +0000156 return true;
Chris Lattner9be15892008-06-16 21:17:12 +0000157 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000158
Chris Lattner5e3bd972011-12-20 00:03:52 +0000159 // Mapping a non-opaque source type to an opaque dest. If this is the first
160 // type that we're mapping onto this destination type then we succeed. Keep
Rafael Espindolaa96f2352014-11-28 16:41:24 +0000161 // the dest, but fill it in later. If this is the second (different) type
162 // that we're trying to map onto the same opaque type then we fail.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000163 if (cast<StructType>(DstTy)->isOpaque()) {
Chris Lattner5e3bd972011-12-20 00:03:52 +0000164 // We can only map one source type onto the opaque destination type.
David Blaikie70573dc2014-11-19 07:49:26 +0000165 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
Chris Lattner5e3bd972011-12-20 00:03:52 +0000166 return false;
167 SrcDefinitionsToResolve.push_back(SSTy);
Rafael Espindolaa96f2352014-11-28 16:41:24 +0000168 SpeculativeTypes.push_back(SrcTy);
169 SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000170 Entry = DstTy;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000171 return true;
172 }
173 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000174
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000175 // If the number of subtypes disagree between the two types, then we fail.
176 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
Reid Spencer361e5132004-11-12 20:37:43 +0000177 return false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000178
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000179 // Fail if any of the extra properties (e.g. array size) of the type disagree.
180 if (isa<IntegerType>(DstTy))
181 return false; // bitwidth disagrees.
182 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
183 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
184 return false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000185
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000186 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
187 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
188 return false;
189 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
190 StructType *SSTy = cast<StructType>(SrcTy);
Chris Lattner44f7ab42011-08-12 18:07:26 +0000191 if (DSTy->isLiteral() != SSTy->isLiteral() ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000192 DSTy->isPacked() != SSTy->isPacked())
193 return false;
194 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
195 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
196 return false;
197 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
Joey Gouly5fad3e92013-01-10 10:49:36 +0000198 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000199 return false;
Reid Spencer361e5132004-11-12 20:37:43 +0000200 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000201
202 // Otherwise, we speculate that these two types will line up and recursively
203 // check the subelements.
204 Entry = DstTy;
205 SpeculativeTypes.push_back(SrcTy);
206
Rafael Espindola290e2cc2014-11-25 14:35:53 +0000207 for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
208 if (!areTypesIsomorphic(DstTy->getContainedType(I),
209 SrcTy->getContainedType(I)))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000210 return false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000211
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000212 // If everything seems to have lined up, then everything is great.
213 return true;
214}
215
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000216void TypeMapTy::linkDefinedTypeBodies() {
217 SmallVector<Type*, 16> Elements;
Rafael Espindolac81c3f52014-11-25 15:33:40 +0000218 for (StructType *SrcSTy : SrcDefinitionsToResolve) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000219 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
Rafael Espindolac81c3f52014-11-25 15:33:40 +0000220 assert(DstSTy->isOpaque());
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000221
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000222 // Map the body of the source type over to a new body for the dest type.
223 Elements.resize(SrcSTy->getNumElements());
Rafael Espindola290e2cc2014-11-25 14:35:53 +0000224 for (unsigned I = 0, E = Elements.size(); I != E; ++I)
Rafael Espindolac81c3f52014-11-25 15:33:40 +0000225 Elements[I] = get(SrcSTy->getElementType(I));
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000226
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000227 DstSTy->setBody(Elements, SrcSTy->isPacked());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000228 }
Rafael Espindolac81c3f52014-11-25 15:33:40 +0000229 SrcDefinitionsToResolve.clear();
Chris Lattner5e3bd972011-12-20 00:03:52 +0000230 DstResolvedOpaqueTypes.clear();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000231}
232
Rafael Espindola31ad4682014-12-03 22:36:37 +0000233void TypeMapTy::finishType(StructType *DTy, StructType *STy,
234 ArrayRef<Type *> ETypes) {
235 DTy->setBody(ETypes, STy->isPacked());
Rafael Espindolac81c3f52014-11-25 15:33:40 +0000236
237 // Steal STy's name.
238 if (STy->hasName()) {
239 SmallString<16> TmpName = STy->getName();
240 STy->setName("");
241 DTy->setName(TmpName);
242 }
243
Rafael Espindola31ad4682014-12-03 22:36:37 +0000244 DstStructTypesSet.addNonOpaque(DTy);
245}
246
247Type *TypeMapTy::get(Type *Ty) {
248 SmallPtrSet<StructType *, 8> Visited;
249 return get(Ty, Visited);
250}
251
252Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
253 // If we already have an entry for this type, return it.
254 Type **Entry = &MappedTypes[Ty];
255 if (*Entry)
256 return *Entry;
257
258 // These are types that LLVM itself will unique.
259 bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
260
261#ifndef NDEBUG
262 if (!IsUniqued) {
263 for (auto &Pair : MappedTypes) {
264 assert(!(Pair.first != Ty && Pair.second == Ty) &&
265 "mapping to a source type");
266 }
267 }
268#endif
269
270 if (!IsUniqued && !Visited.insert(cast<StructType>(Ty)).second) {
271 StructType *DTy = StructType::create(Ty->getContext());
272 return *Entry = DTy;
273 }
274
275 // If this is not a recursive type, then just map all of the elements and
276 // then rebuild the type from inside out.
277 SmallVector<Type *, 4> ElementTypes;
278
279 // If there are no element types to map, then the type is itself. This is
280 // true for the anonymous {} struct, things like 'float', integers, etc.
281 if (Ty->getNumContainedTypes() == 0 && IsUniqued)
282 return *Entry = Ty;
283
284 // Remap all of the elements, keeping track of whether any of them change.
285 bool AnyChange = false;
286 ElementTypes.resize(Ty->getNumContainedTypes());
287 for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
288 ElementTypes[I] = get(Ty->getContainedType(I), Visited);
289 AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
290 }
291
292 // If we found our type while recursively processing stuff, just use it.
293 Entry = &MappedTypes[Ty];
294 if (*Entry) {
295 if (auto *DTy = dyn_cast<StructType>(*Entry)) {
296 if (DTy->isOpaque()) {
297 auto *STy = cast<StructType>(Ty);
298 finishType(DTy, STy, ElementTypes);
299 }
300 }
301 return *Entry;
302 }
303
304 // If all of the element types mapped directly over and the type is not
305 // a nomed struct, then the type is usable as-is.
306 if (!AnyChange && IsUniqued)
307 return *Entry = Ty;
308
309 // Otherwise, rebuild a modified type.
310 switch (Ty->getTypeID()) {
311 default:
312 llvm_unreachable("unknown derived type to remap");
313 case Type::ArrayTyID:
314 return *Entry = ArrayType::get(ElementTypes[0],
315 cast<ArrayType>(Ty)->getNumElements());
316 case Type::VectorTyID:
317 return *Entry = VectorType::get(ElementTypes[0],
318 cast<VectorType>(Ty)->getNumElements());
319 case Type::PointerTyID:
320 return *Entry = PointerType::get(ElementTypes[0],
321 cast<PointerType>(Ty)->getAddressSpace());
322 case Type::FunctionTyID:
323 return *Entry = FunctionType::get(ElementTypes[0],
324 makeArrayRef(ElementTypes).slice(1),
325 cast<FunctionType>(Ty)->isVarArg());
326 case Type::StructTyID: {
327 auto *STy = cast<StructType>(Ty);
328 bool IsPacked = STy->isPacked();
329 if (IsUniqued)
330 return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
331
332 // If the type is opaque, we can just use it directly.
333 if (STy->isOpaque()) {
334 DstStructTypesSet.addOpaque(STy);
335 return *Entry = Ty;
336 }
337
338 if (StructType *OldT =
339 DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
340 STy->setName("");
341 return *Entry = OldT;
342 }
343
344 if (!AnyChange) {
345 DstStructTypesSet.addNonOpaque(STy);
346 return *Entry = Ty;
347 }
348
349 StructType *DTy = StructType::create(Ty->getContext());
350 finishType(DTy, STy, ElementTypes);
351 return *Entry = DTy;
352 }
353 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000354}
355
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000356//===----------------------------------------------------------------------===//
357// ModuleLinker implementation.
358//===----------------------------------------------------------------------===//
359
360namespace {
Rafael Espindolac84f6082014-11-25 06:11:24 +0000361class ModuleLinker;
James Molloyf6f121e2013-05-28 15:17:05 +0000362
Rafael Espindolac84f6082014-11-25 06:11:24 +0000363/// Creates prototypes for functions that are lazily linked on the fly. This
364/// speeds up linking for modules with many/ lazily linked functions of which
365/// few get used.
366class ValueMaterializerTy : public ValueMaterializer {
367 TypeMapTy &TypeMap;
368 Module *DstM;
Rafael Espindolaef237112014-12-08 18:45:16 +0000369 std::vector<GlobalValue *> &LazilyLinkGlobalValues;
James Molloyf6f121e2013-05-28 15:17:05 +0000370
Rafael Espindolac84f6082014-11-25 06:11:24 +0000371public:
372 ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
Rafael Espindolaef237112014-12-08 18:45:16 +0000373 std::vector<GlobalValue *> &LazilyLinkGlobalValues)
Rafael Espindolac84f6082014-11-25 06:11:24 +0000374 : ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
Rafael Espindolaef237112014-12-08 18:45:16 +0000375 LazilyLinkGlobalValues(LazilyLinkGlobalValues) {}
Rafael Espindolac84f6082014-11-25 06:11:24 +0000376
377 Value *materializeValueFor(Value *V) override;
378};
379
380class LinkDiagnosticInfo : public DiagnosticInfo {
381 const Twine &Msg;
382
383public:
384 LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg);
385 void print(DiagnosticPrinter &DP) const override;
386};
387LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
388 const Twine &Msg)
389 : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
390void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
391
392/// This is an implementation class for the LinkModules function, which is the
393/// entrypoint for this file.
394class ModuleLinker {
395 Module *DstM, *SrcM;
396
397 TypeMapTy TypeMap;
398 ValueMaterializerTy ValMaterializer;
399
400 /// Mapping of values from what they used to be in Src, to what they are now
401 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
402 /// due to the use of Value handles which the Linker doesn't actually need,
403 /// but this allows us to reuse the ValueMapper code.
404 ValueToValueMapTy ValueMap;
405
406 struct AppendingVarInfo {
407 GlobalVariable *NewGV; // New aggregate global in dest module.
408 const Constant *DstInit; // Old initializer from dest module.
409 const Constant *SrcInit; // Old initializer from src module.
James Molloyf6f121e2013-05-28 15:17:05 +0000410 };
411
Rafael Espindolac84f6082014-11-25 06:11:24 +0000412 std::vector<AppendingVarInfo> AppendingVars;
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000413
Rafael Espindolac84f6082014-11-25 06:11:24 +0000414 // Set of items not to link in from source.
415 SmallPtrSet<const Value *, 16> DoNotLinkFromSource;
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000416
Rafael Espindolaef237112014-12-08 18:45:16 +0000417 // Vector of GlobalValues to lazily link in.
418 std::vector<GlobalValue *> LazilyLinkGlobalValues;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000419
Duncan P. N. Exon Smithfda0cee2014-12-18 01:05:33 +0000420 /// Functions that have replaced other functions.
421 SmallPtrSet<const Function *, 16> OverridingFunctions;
422
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000423 DiagnosticHandlerFunction DiagnosticHandler;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000424
Rafael Espindolac84f6082014-11-25 06:11:24 +0000425public:
Rafael Espindola31ad4682014-12-03 22:36:37 +0000426 ModuleLinker(Module *dstM, Linker::IdentifiedStructTypeSet &Set, Module *srcM,
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000427 DiagnosticHandlerFunction DiagnosticHandler)
Rafael Espindolaa4e85e32014-12-01 16:32:20 +0000428 : DstM(dstM), SrcM(srcM), TypeMap(Set),
Rafael Espindolaef237112014-12-08 18:45:16 +0000429 ValMaterializer(TypeMap, DstM, LazilyLinkGlobalValues),
Rafael Espindolac84f6082014-11-25 06:11:24 +0000430 DiagnosticHandler(DiagnosticHandler) {}
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000431
Rafael Espindolac84f6082014-11-25 06:11:24 +0000432 bool run();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000433
Rafael Espindolac84f6082014-11-25 06:11:24 +0000434private:
435 bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
436 const GlobalValue &Src);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000437
Rafael Espindolac84f6082014-11-25 06:11:24 +0000438 /// Helper method for setting a message and returning an error code.
439 bool emitError(const Twine &Message) {
440 DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
441 return true;
442 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000443
Rafael Espindolac84f6082014-11-25 06:11:24 +0000444 void emitWarning(const Twine &Message) {
445 DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
446 }
Eli Bendersky7da92ed2014-02-20 22:19:24 +0000447
Rafael Espindolac84f6082014-11-25 06:11:24 +0000448 bool getComdatLeader(Module *M, StringRef ComdatName,
449 const GlobalVariable *&GVar);
450 bool computeResultingSelectionKind(StringRef ComdatName,
451 Comdat::SelectionKind Src,
452 Comdat::SelectionKind Dst,
453 Comdat::SelectionKind &Result,
454 bool &LinkFromSrc);
455 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
456 ComdatsChosen;
457 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
458 bool &LinkFromSrc);
Rafael Espindola4160f5d2014-10-27 23:02:10 +0000459
Rafael Espindolac84f6082014-11-25 06:11:24 +0000460 /// Given a global in the source module, return the global in the
461 /// destination module that is being linked to, if any.
462 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
463 // If the source has no name it can't link. If it has local linkage,
464 // there is no name match-up going on.
465 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
466 return nullptr;
Eli Bendersky7da92ed2014-02-20 22:19:24 +0000467
Rafael Espindolac84f6082014-11-25 06:11:24 +0000468 // Otherwise see if we have a match in the destination module's symtab.
469 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
470 if (!DGV)
471 return nullptr;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000472
Rafael Espindolac84f6082014-11-25 06:11:24 +0000473 // If we found a global with the same name in the dest module, but it has
474 // internal linkage, we are really not doing any linkage here.
475 if (DGV->hasLocalLinkage())
476 return nullptr;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000477
Rafael Espindolac84f6082014-11-25 06:11:24 +0000478 // Otherwise, we do in fact link to the destination global.
479 return DGV;
480 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000481
Rafael Espindolac84f6082014-11-25 06:11:24 +0000482 void computeTypeMapping();
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000483
Rafael Espindolac84f6082014-11-25 06:11:24 +0000484 void upgradeMismatchedGlobalArray(StringRef Name);
485 void upgradeMismatchedGlobals();
David Majnemerdad0a642014-06-27 18:19:56 +0000486
Rafael Espindolac84f6082014-11-25 06:11:24 +0000487 bool linkAppendingVarProto(GlobalVariable *DstGV,
488 const GlobalVariable *SrcGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000489
Rafael Espindolac84f6082014-11-25 06:11:24 +0000490 bool linkGlobalValueProto(GlobalValue *GV);
Rafael Espindolac84f6082014-11-25 06:11:24 +0000491 bool linkModuleFlagsMetadata();
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000492
Rafael Espindolac84f6082014-11-25 06:11:24 +0000493 void linkAppendingVarInit(const AppendingVarInfo &AVI);
Rafael Espindolaef237112014-12-08 18:45:16 +0000494
495 void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src);
496 bool linkFunctionBody(Function &Dst, Function &Src);
497 void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src);
498 bool linkGlobalValueBody(GlobalValue &Src);
499
Rafael Espindolac84f6082014-11-25 06:11:24 +0000500 void linkNamedMDNodes();
Duncan P. N. Exon Smithfda0cee2014-12-18 01:05:33 +0000501 void stripReplacedSubprograms();
Rafael Espindolac84f6082014-11-25 06:11:24 +0000502};
Bill Wendlingd48b7782012-02-28 04:01:21 +0000503}
504
Rafael Espindola18c89412014-10-27 02:35:46 +0000505/// The LLVM SymbolTable class autorenames globals that conflict in the symbol
506/// table. This is good for all clients except for us. Go through the trouble
507/// to force this back.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000508static void forceRenaming(GlobalValue *GV, StringRef Name) {
509 // If the global doesn't force its name or if it already has the right name,
510 // there is nothing for us to do.
511 if (GV->hasLocalLinkage() || GV->getName() == Name)
512 return;
513
514 Module *M = GV->getParent();
Reid Spencer361e5132004-11-12 20:37:43 +0000515
516 // If there is a conflict, rename the conflict.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000517 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
Chris Lattner2a8d2e02007-02-11 00:39:38 +0000518 GV->takeName(ConflictGV);
519 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000520 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
Chris Lattner2a8d2e02007-02-11 00:39:38 +0000521 } else {
522 GV->setName(Name); // Force the name back
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000523 }
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000524}
Reid Spencer90246aa2007-02-04 04:29:21 +0000525
Rafael Espindola18c89412014-10-27 02:35:46 +0000526/// copy additional attributes (those not needed to construct a GlobalValue)
527/// from the SrcGV to the DestGV.
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000528static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
Duncan Sandsdd7daee2008-05-26 19:58:59 +0000529 DestGV->copyAttributesFrom(SrcGV);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000530 forceRenaming(DestGV, SrcGV->getName());
Reid Spencer361e5132004-11-12 20:37:43 +0000531}
532
Rafael Espindola23f8d642012-01-05 23:02:01 +0000533static bool isLessConstraining(GlobalValue::VisibilityTypes a,
534 GlobalValue::VisibilityTypes b) {
535 if (a == GlobalValue::HiddenVisibility)
536 return false;
537 if (b == GlobalValue::HiddenVisibility)
538 return true;
539 if (a == GlobalValue::ProtectedVisibility)
540 return false;
541 if (b == GlobalValue::ProtectedVisibility)
542 return true;
543 return false;
544}
545
Rafael Espindolaef237112014-12-08 18:45:16 +0000546/// Loop through the global variables in the src module and merge them into the
547/// dest module.
548static GlobalVariable *copyGlobalVariableProto(TypeMapTy &TypeMap, Module &DstM,
549 const GlobalVariable *SGVar) {
550 // No linking to be performed or linking from the source: simply create an
551 // identical version of the symbol over in the dest module... the
552 // initializer will be filled in later by LinkGlobalInits.
553 GlobalVariable *NewDGV = new GlobalVariable(
554 DstM, TypeMap.get(SGVar->getType()->getElementType()),
555 SGVar->isConstant(), SGVar->getLinkage(), /*init*/ nullptr,
556 SGVar->getName(), /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
557 SGVar->getType()->getAddressSpace());
558
559 return NewDGV;
560}
561
562/// Link the function in the source module into the destination module if
563/// needed, setting up mapping information.
564static Function *copyFunctionProto(TypeMapTy &TypeMap, Module &DstM,
565 const Function *SF) {
566 // If there is no linkage to be performed or we are linking from the source,
567 // bring SF over.
568 return Function::Create(TypeMap.get(SF->getFunctionType()), SF->getLinkage(),
569 SF->getName(), &DstM);
570}
571
572/// Set up prototypes for any aliases that come over from the source module.
573static GlobalAlias *copyGlobalAliasProto(TypeMapTy &TypeMap, Module &DstM,
574 const GlobalAlias *SGA) {
575 // If there is no linkage to be performed or we're linking from the source,
576 // bring over SGA.
577 auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType()));
578 return GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
579 SGA->getLinkage(), SGA->getName(), &DstM);
580}
581
582static GlobalValue *copyGlobalValueProto(TypeMapTy &TypeMap, Module &DstM,
583 const GlobalValue *SGV) {
584 GlobalValue *NewGV;
585 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV))
586 NewGV = copyGlobalVariableProto(TypeMap, DstM, SGVar);
587 else if (auto *SF = dyn_cast<Function>(SGV))
588 NewGV = copyFunctionProto(TypeMap, DstM, SF);
589 else
590 NewGV = copyGlobalAliasProto(TypeMap, DstM, cast<GlobalAlias>(SGV));
591 copyGVAttributes(NewGV, SGV);
592 return NewGV;
593}
594
James Molloyf6f121e2013-05-28 15:17:05 +0000595Value *ValueMaterializerTy::materializeValueFor(Value *V) {
Rafael Espindolaef237112014-12-08 18:45:16 +0000596 auto *SGV = dyn_cast<GlobalValue>(V);
597 if (!SGV)
Craig Topper2617dcc2014-04-15 06:32:26 +0000598 return nullptr;
James Molloyf6f121e2013-05-28 15:17:05 +0000599
Rafael Espindolaef237112014-12-08 18:45:16 +0000600 GlobalValue *DGV = copyGlobalValueProto(TypeMap, *DstM, SGV);
James Molloyf6f121e2013-05-28 15:17:05 +0000601
Rafael Espindolaef237112014-12-08 18:45:16 +0000602 if (Comdat *SC = SGV->getComdat()) {
603 if (auto *DGO = dyn_cast<GlobalObject>(DGV)) {
604 Comdat *DC = DstM->getOrInsertComdat(SC->getName());
605 DGO->setComdat(DC);
606 }
Rafael Espindola3931c282014-08-15 20:17:08 +0000607 }
608
Rafael Espindolaef237112014-12-08 18:45:16 +0000609 LazilyLinkGlobalValues.push_back(SGV);
610 return DGV;
James Molloyf6f121e2013-05-28 15:17:05 +0000611}
612
David Majnemerdad0a642014-06-27 18:19:56 +0000613bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName,
614 const GlobalVariable *&GVar) {
615 const GlobalValue *GVal = M->getNamedValue(ComdatName);
616 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
617 GVal = GA->getBaseObject();
618 if (!GVal)
619 // We cannot resolve the size of the aliasee yet.
620 return emitError("Linking COMDATs named '" + ComdatName +
621 "': COMDAT key involves incomputable alias size.");
622 }
623
624 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
625 if (!GVar)
626 return emitError(
627 "Linking COMDATs named '" + ComdatName +
628 "': GlobalVariable required for data dependent selection!");
629
630 return false;
631}
632
633bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
634 Comdat::SelectionKind Src,
635 Comdat::SelectionKind Dst,
636 Comdat::SelectionKind &Result,
637 bool &LinkFromSrc) {
638 // The ability to mix Comdat::SelectionKind::Any with
639 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
640 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
641 Dst == Comdat::SelectionKind::Largest;
642 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
643 Src == Comdat::SelectionKind::Largest;
644 if (DstAnyOrLargest && SrcAnyOrLargest) {
645 if (Dst == Comdat::SelectionKind::Largest ||
646 Src == Comdat::SelectionKind::Largest)
647 Result = Comdat::SelectionKind::Largest;
648 else
649 Result = Comdat::SelectionKind::Any;
650 } else if (Src == Dst) {
651 Result = Dst;
652 } else {
653 return emitError("Linking COMDATs named '" + ComdatName +
654 "': invalid selection kinds!");
655 }
656
657 switch (Result) {
658 case Comdat::SelectionKind::Any:
659 // Go with Dst.
660 LinkFromSrc = false;
661 break;
662 case Comdat::SelectionKind::NoDuplicates:
663 return emitError("Linking COMDATs named '" + ComdatName +
664 "': noduplicates has been violated!");
665 case Comdat::SelectionKind::ExactMatch:
666 case Comdat::SelectionKind::Largest:
667 case Comdat::SelectionKind::SameSize: {
668 const GlobalVariable *DstGV;
669 const GlobalVariable *SrcGV;
670 if (getComdatLeader(DstM, ComdatName, DstGV) ||
671 getComdatLeader(SrcM, ComdatName, SrcGV))
672 return true;
673
674 const DataLayout *DstDL = DstM->getDataLayout();
675 const DataLayout *SrcDL = SrcM->getDataLayout();
676 if (!DstDL || !SrcDL) {
677 return emitError(
678 "Linking COMDATs named '" + ComdatName +
679 "': can't do size dependent selection without DataLayout!");
680 }
681 uint64_t DstSize =
682 DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType());
683 uint64_t SrcSize =
684 SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType());
685 if (Result == Comdat::SelectionKind::ExactMatch) {
686 if (SrcGV->getInitializer() != DstGV->getInitializer())
687 return emitError("Linking COMDATs named '" + ComdatName +
688 "': ExactMatch violated!");
689 LinkFromSrc = false;
690 } else if (Result == Comdat::SelectionKind::Largest) {
691 LinkFromSrc = SrcSize > DstSize;
692 } else if (Result == Comdat::SelectionKind::SameSize) {
693 if (SrcSize != DstSize)
694 return emitError("Linking COMDATs named '" + ComdatName +
695 "': SameSize violated!");
696 LinkFromSrc = false;
697 } else {
698 llvm_unreachable("unknown selection kind");
699 }
700 break;
701 }
702 }
703
704 return false;
705}
706
707bool ModuleLinker::getComdatResult(const Comdat *SrcC,
708 Comdat::SelectionKind &Result,
709 bool &LinkFromSrc) {
Rafael Espindolab16196a2014-08-11 17:07:34 +0000710 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
David Majnemerdad0a642014-06-27 18:19:56 +0000711 StringRef ComdatName = SrcC->getName();
712 Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable();
713 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000714
Rafael Espindolab16196a2014-08-11 17:07:34 +0000715 if (DstCI == ComdatSymTab.end()) {
716 // Use the comdat if it is only available in one of the modules.
717 LinkFromSrc = true;
718 Result = SSK;
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000719 return false;
Rafael Espindolab16196a2014-08-11 17:07:34 +0000720 }
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000721
722 const Comdat *DstC = &DstCI->second;
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000723 Comdat::SelectionKind DSK = DstC->getSelectionKind();
724 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
725 LinkFromSrc);
David Majnemerdad0a642014-06-27 18:19:56 +0000726}
James Molloyf6f121e2013-05-28 15:17:05 +0000727
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000728bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
729 const GlobalValue &Dest,
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000730 const GlobalValue &Src) {
Rafael Espindola778fcc72014-11-02 13:28:57 +0000731 // We always have to add Src if it has appending linkage.
732 if (Src.hasAppendingLinkage()) {
733 LinkFromSrc = true;
734 return false;
735 }
736
Rafael Espindolad4bcefc2014-10-24 18:13:04 +0000737 bool SrcIsDeclaration = Src.isDeclarationForLinker();
738 bool DestIsDeclaration = Dest.isDeclarationForLinker();
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000739
740 if (SrcIsDeclaration) {
741 // If Src is external or if both Src & Dest are external.. Just link the
742 // external globals, we aren't adding anything.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000743 if (Src.hasDLLImportStorageClass()) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000744 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000745 LinkFromSrc = DestIsDeclaration;
746 return false;
747 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000748 // If the Dest is weak, use the source linkage.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000749 LinkFromSrc = Dest.hasExternalWeakLinkage();
750 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000751 }
752
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000753 if (DestIsDeclaration) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000754 // If Dest is external but Src is not:
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000755 LinkFromSrc = true;
756 return false;
757 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000758
Rafael Espindola09106052014-09-09 15:59:12 +0000759 if (Src.hasCommonLinkage()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000760 if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
761 LinkFromSrc = true;
Rafael Espindola09106052014-09-09 15:59:12 +0000762 return false;
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000763 }
764
765 if (!Dest.hasCommonLinkage()) {
766 LinkFromSrc = false;
767 return false;
768 }
Rafael Espindola09106052014-09-09 15:59:12 +0000769
Rafael Espindola0ae225b2014-10-31 04:46:38 +0000770 // FIXME: Make datalayout mandatory and just use getDataLayout().
771 DataLayout DL(Dest.getParent());
772
Rafael Espindola09106052014-09-09 15:59:12 +0000773 uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
774 uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000775 LinkFromSrc = SrcSize > DestSize;
776 return false;
Rafael Espindola09106052014-09-09 15:59:12 +0000777 }
778
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000779 if (Src.isWeakForLinker()) {
780 assert(!Dest.hasExternalWeakLinkage());
781 assert(!Dest.hasAvailableExternallyLinkage());
Rafael Espindola09106052014-09-09 15:59:12 +0000782
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000783 if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
784 LinkFromSrc = true;
785 return false;
786 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000787
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000788 LinkFromSrc = false;
Rafael Espindola09106052014-09-09 15:59:12 +0000789 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000790 }
791
792 if (Dest.isWeakForLinker()) {
793 assert(Src.hasExternalLinkage());
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000794 LinkFromSrc = true;
795 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000796 }
797
798 assert(!Src.hasExternalWeakLinkage());
799 assert(!Dest.hasExternalWeakLinkage());
800 assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
801 "Unexpected linkage type!");
802 return emitError("Linking globals named '" + Src.getName() +
803 "': symbol multiply defined!");
804}
805
Rafael Espindola18c89412014-10-27 02:35:46 +0000806/// Loop over all of the linked values to compute type mappings. For example,
807/// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
808/// types 'Foo' but one got renamed when the module was loaded into the same
809/// LLVMContext.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000810void ModuleLinker::computeTypeMapping() {
Rafael Espindolac8a476e2014-11-25 04:26:19 +0000811 for (GlobalValue &SGV : SrcM->globals()) {
812 GlobalValue *DGV = getLinkedToGlobal(&SGV);
813 if (!DGV)
814 continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000815
Rafael Espindolac8a476e2014-11-25 04:26:19 +0000816 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
817 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000818 continue;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000819 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000820
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000821 // Unify the element type of appending arrays.
822 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
Rafael Espindolac8a476e2014-11-25 04:26:19 +0000823 ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000824 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
Devang Patel5c310be2009-08-11 18:01:24 +0000825 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000826
Rafael Espindolac8a476e2014-11-25 04:26:19 +0000827 for (GlobalValue &SGV : *SrcM) {
828 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
829 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000830 }
Bill Wendling7b464612012-02-27 22:34:19 +0000831
Rafael Espindolae96d7eb2014-11-25 04:43:59 +0000832 for (GlobalValue &SGV : SrcM->aliases()) {
833 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
834 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
835 }
836
Bill Wendlingd48b7782012-02-28 04:01:21 +0000837 // Incorporate types by name, scanning all the types in the source module.
838 // At this point, the destination module may have a type "%foo = { i32 }" for
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000839 // example. When the source module got loaded into the same LLVMContext, if
840 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
Rafael Espindola2fa1e432014-12-03 07:18:23 +0000841 std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
842 for (StructType *ST : Types) {
Rafael Espindola4d4c9382014-12-01 19:08:07 +0000843 if (!ST->hasName())
844 continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000845
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000846 // Check to see if there is a dot in the name followed by a digit.
Bill Wendlingd48b7782012-02-28 04:01:21 +0000847 size_t DotPos = ST->getName().rfind('.');
848 if (DotPos == 0 || DotPos == StringRef::npos ||
Guy Benyei83c74e92013-02-12 21:21:59 +0000849 ST->getName().back() == '.' ||
Rafael Espindola973b3612014-12-01 19:17:46 +0000850 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
Bill Wendlingd48b7782012-02-28 04:01:21 +0000851 continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000852
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000853 // Check to see if the destination module has a struct with the prefix name.
Rafael Espindola973b3612014-12-01 19:17:46 +0000854 StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos));
855 if (!DST)
856 continue;
857
858 // Don't use it if this actually came from the source module. They're in
859 // the same LLVMContext after all. Also don't use it unless the type is
860 // actually used in the destination module. This can happen in situations
861 // like this:
862 //
863 // Module A Module B
864 // -------- --------
865 // %Z = type { %A } %B = type { %C.1 }
866 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
867 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
868 // %C = type { i8* } %B.3 = type { %C.1 }
869 //
870 // When we link Module B with Module A, the '%B' in Module B is
871 // used. However, that would then use '%C.1'. But when we process '%C.1',
872 // we prefer to take the '%C' version. So we are then left with both
873 // '%C.1' and '%C' being used for the same types. This leads to some
874 // variables using one type and some using the other.
Rafael Espindola31ad4682014-12-03 22:36:37 +0000875 if (TypeMap.DstStructTypesSet.hasType(DST))
Rafael Espindola973b3612014-12-01 19:17:46 +0000876 TypeMap.addTypeMapping(DST, ST);
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000877 }
878
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000879 // Now that we have discovered all of the type equivalences, get a body for
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000880 // any 'opaque' types in the dest module that are now resolved.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000881 TypeMap.linkDefinedTypeBodies();
Devang Patel5c310be2009-08-11 18:01:24 +0000882}
883
Duncan P. N. Exon Smith09d84ad2014-08-12 16:46:37 +0000884static void upgradeGlobalArray(GlobalVariable *GV) {
885 ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
886 StructType *OldTy = cast<StructType>(ATy->getElementType());
887 assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
888
889 // Get the upgraded 3 element type.
890 PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
891 Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
892 VoidPtrTy};
893 StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
894
895 // Build new constants with a null third field filled in.
896 Constant *OldInitC = GV->getInitializer();
897 ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
898 if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
899 // Invalid initializer; give up.
900 return;
901 std::vector<Constant *> Initializers;
902 if (OldInit && OldInit->getNumOperands()) {
903 Value *Null = Constant::getNullValue(VoidPtrTy);
904 for (Use &U : OldInit->operands()) {
905 ConstantStruct *Init = cast<ConstantStruct>(U.get());
906 Initializers.push_back(ConstantStruct::get(
907 NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
908 }
909 }
910 assert(Initializers.size() == ATy->getNumElements() &&
911 "Failed to copy all array elements");
912
913 // Replace the old GV with a new one.
914 ATy = ArrayType::get(NewTy, Initializers.size());
915 Constant *NewInit = ConstantArray::get(ATy, Initializers);
916 GlobalVariable *NewGV = new GlobalVariable(
917 *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
918 GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
919 GV->isExternallyInitialized());
920 NewGV->copyAttributesFrom(GV);
921 NewGV->takeName(GV);
922 assert(GV->use_empty() && "program cannot use initializer list");
923 GV->eraseFromParent();
924}
925
926void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
927 // Look for the global arrays.
928 auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name));
929 if (!DstGV)
930 return;
931 auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name));
932 if (!SrcGV)
933 return;
934
935 // Check if the types already match.
936 auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
937 auto *SrcTy =
938 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
939 if (DstTy == SrcTy)
940 return;
941
942 // Grab the element types. We can only upgrade an array of a two-field
943 // struct. Only bother if the other one has three-fields.
944 auto *DstEltTy = cast<StructType>(DstTy->getElementType());
945 auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
946 if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
947 upgradeGlobalArray(DstGV);
948 return;
949 }
950 if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
951 upgradeGlobalArray(SrcGV);
952
953 // We can't upgrade any other differences.
954}
955
956void ModuleLinker::upgradeMismatchedGlobals() {
957 upgradeMismatchedGlobalArray("llvm.global_ctors");
958 upgradeMismatchedGlobalArray("llvm.global_dtors");
959}
960
Rafael Espindola18c89412014-10-27 02:35:46 +0000961/// If there were any appending global variables, link them together now.
962/// Return true on error.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000963bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
Rafael Espindola3e8bc6a2014-10-31 16:08:17 +0000964 const GlobalVariable *SrcGV) {
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000965
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000966 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
967 return emitError("Linking globals named '" + SrcGV->getName() +
968 "': can only link appending global with another appending global!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000969
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000970 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
971 ArrayType *SrcTy =
972 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
973 Type *EltTy = DstTy->getElementType();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000974
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000975 // Check to see that they two arrays agree on type.
976 if (EltTy != SrcTy->getElementType())
977 return emitError("Appending variables with different element types!");
978 if (DstGV->isConstant() != SrcGV->isConstant())
979 return emitError("Appending variables linked with different const'ness!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000980
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000981 if (DstGV->getAlignment() != SrcGV->getAlignment())
982 return emitError(
983 "Appending variables with different alignment need to be linked!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000984
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000985 if (DstGV->getVisibility() != SrcGV->getVisibility())
986 return emitError(
987 "Appending variables with different visibility need to be linked!");
Rafael Espindolafac3a012013-09-04 15:33:34 +0000988
989 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
990 return emitError(
991 "Appending variables with different unnamed_addr need to be linked!");
992
Rafael Espindola64c1e182014-06-03 02:41:57 +0000993 if (StringRef(DstGV->getSection()) != SrcGV->getSection())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000994 return emitError(
995 "Appending variables with different section name need to be linked!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000996
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000997 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
998 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000999
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001000 // Create the new global variable.
1001 GlobalVariable *NG =
1002 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
Craig Topper2617dcc2014-04-15 06:32:26 +00001003 DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001004 DstGV->getThreadLocalMode(),
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001005 DstGV->getType()->getAddressSpace());
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001006
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001007 // Propagate alignment, visibility and section info.
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001008 copyGVAttributes(NG, DstGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001009
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001010 AppendingVarInfo AVI;
1011 AVI.NewGV = NG;
1012 AVI.DstInit = DstGV->getInitializer();
1013 AVI.SrcInit = SrcGV->getInitializer();
1014 AppendingVars.push_back(AVI);
Mikhail Glushenkov766d4892009-03-03 07:22:23 +00001015
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001016 // Replace any uses of the two global variables with uses of the new
1017 // global.
1018 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
Anton Korobeynikove79f4c72008-03-10 22:34:28 +00001019
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001020 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
1021 DstGV->eraseFromParent();
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001022
Tanya Lattnercbb91402011-10-11 00:24:54 +00001023 // Track the source variable so we don't try to link it.
1024 DoNotLinkFromSource.insert(SrcGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001025
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001026 return false;
1027}
Mikhail Glushenkov766d4892009-03-03 07:22:23 +00001028
Rafael Espindola778fcc72014-11-02 13:28:57 +00001029bool ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001030 GlobalValue *DGV = getLinkedToGlobal(SGV);
Mikhail Glushenkov766d4892009-03-03 07:22:23 +00001031
Rafael Espindola778fcc72014-11-02 13:28:57 +00001032 // Handle the ultra special appending linkage case first.
1033 if (DGV && DGV->hasAppendingLinkage())
1034 return linkAppendingVarProto(cast<GlobalVariable>(DGV),
1035 cast<GlobalVariable>(SGV));
1036
1037 bool LinkFromSrc = true;
1038 Comdat *C = nullptr;
1039 GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
1040 bool HasUnnamedAddr = SGV->hasUnnamedAddr();
1041
David Majnemerdad0a642014-06-27 18:19:56 +00001042 if (const Comdat *SC = SGV->getComdat()) {
1043 Comdat::SelectionKind SK;
1044 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
Rafael Espindola778fcc72014-11-02 13:28:57 +00001045 C = DstM->getOrInsertComdat(SC->getName());
1046 C->setSelectionKind(SK);
1047 } else if (DGV) {
1048 if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
1049 return true;
1050 }
1051
1052 if (!LinkFromSrc) {
1053 // Track the source global so that we don't attempt to copy it over when
1054 // processing global initializers.
1055 DoNotLinkFromSource.insert(SGV);
1056
1057 if (DGV)
1058 // Make sure to remember this mapping.
1059 ValueMap[SGV] =
1060 ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->getType()));
David Majnemerdad0a642014-06-27 18:19:56 +00001061 }
1062
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001063 if (DGV) {
Rafael Espindola778fcc72014-11-02 13:28:57 +00001064 Visibility = isLessConstraining(Visibility, DGV->getVisibility())
1065 ? DGV->getVisibility()
1066 : Visibility;
1067 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1068 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001069
Rafael Espindola778fcc72014-11-02 13:28:57 +00001070 if (!LinkFromSrc && !DGV)
1071 return false;
Reid Spencer361e5132004-11-12 20:37:43 +00001072
Rafael Espindola778fcc72014-11-02 13:28:57 +00001073 GlobalValue *NewGV;
Rafael Espindola26c29512014-12-05 17:53:15 +00001074 if (!LinkFromSrc) {
1075 NewGV = DGV;
1076 } else {
Rafael Espindolaef237112014-12-08 18:45:16 +00001077 // If the GV is to be lazily linked, don't create it just yet.
1078 // The ValueMaterializerTy will deal with creating it if it's used.
1079 if (!DGV && (SGV->hasLocalLinkage() || SGV->hasLinkOnceLinkage() ||
1080 SGV->hasAvailableExternallyLinkage())) {
1081 DoNotLinkFromSource.insert(SGV);
1082 return false;
1083 }
1084
1085 NewGV = copyGlobalValueProto(TypeMap, *DstM, SGV);
Duncan P. N. Exon Smithfda0cee2014-12-18 01:05:33 +00001086
1087 if (DGV && isa<Function>(DGV))
1088 if (auto *NewF = dyn_cast<Function>(NewGV))
1089 OverridingFunctions.insert(NewF);
Rafael Espindola26c29512014-12-05 17:53:15 +00001090 }
Rafael Espindolafe3842c2014-09-09 17:48:18 +00001091
Rafael Espindolaad9d0ca2014-12-05 15:42:30 +00001092 NewGV->setUnnamedAddr(HasUnnamedAddr);
1093 NewGV->setVisibility(Visibility);
Rafael Espindola439835a2014-12-05 00:09:02 +00001094
Rafael Espindolaad9d0ca2014-12-05 15:42:30 +00001095 if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
1096 if (C)
1097 NewGO->setComdat(C);
1098
1099 if (DGV && DGV->hasCommonLinkage() && SGV->hasCommonLinkage())
1100 NewGO->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment()));
1101 }
1102
Rafael Espindola879aeb72014-12-05 16:05:19 +00001103 if (auto *NewGVar = dyn_cast<GlobalVariable>(NewGV)) {
1104 auto *DGVar = dyn_cast_or_null<GlobalVariable>(DGV);
1105 auto *SGVar = dyn_cast<GlobalVariable>(SGV);
1106 if (DGVar && SGVar && DGVar->isDeclaration() && SGVar->isDeclaration() &&
1107 (!DGVar->isConstant() || !SGVar->isConstant()))
1108 NewGVar->setConstant(false);
1109 }
1110
Rafael Espindolaad9d0ca2014-12-05 15:42:30 +00001111 // Make sure to remember this mapping.
1112 if (NewGV != DGV) {
1113 if (DGV) {
1114 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
1115 DGV->eraseFromParent();
Chandler Carruthfd38af22014-11-02 09:10:31 +00001116 }
Rafael Espindolaad9d0ca2014-12-05 15:42:30 +00001117 ValueMap[SGV] = NewGV;
Reid Spencer361e5132004-11-12 20:37:43 +00001118 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001119
Rafael Espindola778fcc72014-11-02 13:28:57 +00001120 return false;
1121}
1122
Rafael Espindola3e8bc6a2014-10-31 16:08:17 +00001123static void getArrayElements(const Constant *C,
1124 SmallVectorImpl<Constant *> &Dest) {
Chris Lattner67058832012-01-25 06:48:06 +00001125 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
1126
1127 for (unsigned i = 0; i != NumElements; ++i)
1128 Dest.push_back(C->getAggregateElement(i));
Chris Lattner00245f42012-01-24 13:41:11 +00001129}
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001130
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001131void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
1132 // Merge the initializer.
Rafael Espindolad31dc042014-09-05 21:27:52 +00001133 SmallVector<Constant *, 16> DstElements;
1134 getArrayElements(AVI.DstInit, DstElements);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001135
Rafael Espindolad31dc042014-09-05 21:27:52 +00001136 SmallVector<Constant *, 16> SrcElements;
1137 getArrayElements(AVI.SrcInit, SrcElements);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001138
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001139 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
Rafael Espindolad31dc042014-09-05 21:27:52 +00001140
1141 StringRef Name = AVI.NewGV->getName();
1142 bool IsNewStructor =
1143 (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
1144 cast<StructType>(NewType->getElementType())->getNumElements() == 3;
1145
1146 for (auto *V : SrcElements) {
1147 if (IsNewStructor) {
1148 Constant *Key = V->getAggregateElement(2);
1149 if (DoNotLinkFromSource.count(Key))
1150 continue;
1151 }
1152 DstElements.push_back(
1153 MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer));
1154 }
1155 if (IsNewStructor) {
1156 NewType = ArrayType::get(NewType->getElementType(), DstElements.size());
1157 AVI.NewGV->mutateType(PointerType::get(NewType, 0));
1158 }
1159
1160 AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001161}
1162
Rafael Espindola18c89412014-10-27 02:35:46 +00001163/// Update the initializers in the Dest module now that all globals that may be
1164/// referenced are in Dest.
Rafael Espindolaef237112014-12-08 18:45:16 +00001165void ModuleLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) {
1166 // Figure out what the initializer looks like in the dest module.
1167 Dst.setInitializer(MapValue(Src.getInitializer(), ValueMap, RF_None, &TypeMap,
1168 &ValMaterializer));
Reid Spencer361e5132004-11-12 20:37:43 +00001169}
1170
Rafael Espindola18c89412014-10-27 02:35:46 +00001171/// Copy the source function over into the dest function and fix up references
1172/// to values. At this point we know that Dest is an external function, and
1173/// that Src is not.
Rafael Espindolaef237112014-12-08 18:45:16 +00001174bool ModuleLinker::linkFunctionBody(Function &Dst, Function &Src) {
1175 assert(Dst.isDeclaration() && !Src.isDeclaration());
Reid Spencer361e5132004-11-12 20:37:43 +00001176
Rafael Espindola40d7ebe2014-12-08 13:29:33 +00001177 // Materialize if needed.
Rafael Espindola3519da82014-12-08 14:25:26 +00001178 if (std::error_code EC = Src.materialize())
Rafael Espindola40d7ebe2014-12-08 13:29:33 +00001179 return emitError(EC.message());
1180
Rafael Espindola869d1ce2014-12-08 13:44:38 +00001181 // Link in the prefix data.
Rafael Espindola3519da82014-12-08 14:25:26 +00001182 if (Src.hasPrefixData())
Rafael Espindolaef237112014-12-08 18:45:16 +00001183 Dst.setPrefixData(MapValue(Src.getPrefixData(), ValueMap, RF_None, &TypeMap,
1184 &ValMaterializer));
Rafael Espindola869d1ce2014-12-08 13:44:38 +00001185
1186 // Link in the prologue data.
Rafael Espindola3519da82014-12-08 14:25:26 +00001187 if (Src.hasPrologueData())
Rafael Espindolaef237112014-12-08 18:45:16 +00001188 Dst.setPrologueData(MapValue(Src.getPrologueData(), ValueMap, RF_None,
Rafael Espindola869d1ce2014-12-08 13:44:38 +00001189 &TypeMap, &ValMaterializer));
1190
Chris Lattner7391dde2004-11-16 17:12:38 +00001191 // Go through and convert function arguments over, remembering the mapping.
Rafael Espindolaef237112014-12-08 18:45:16 +00001192 Function::arg_iterator DI = Dst.arg_begin();
Rafael Espindola3519da82014-12-08 14:25:26 +00001193 for (Argument &Arg : Src.args()) {
Rafael Espindolaa314d1a2014-12-08 14:20:10 +00001194 DI->setName(Arg.getName()); // Copy the name over.
Reid Spencer361e5132004-11-12 20:37:43 +00001195
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001196 // Add a mapping to our mapping.
Rafael Espindolaa314d1a2014-12-08 14:20:10 +00001197 ValueMap[&Arg] = DI;
1198 ++DI;
Reid Spencer361e5132004-11-12 20:37:43 +00001199 }
1200
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001201 // Splice the body of the source function into the dest function.
Rafael Espindolaef237112014-12-08 18:45:16 +00001202 Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001203
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001204 // At this point, all of the instructions and values of the function are now
1205 // copied over. The only problem is that they are still referencing values in
1206 // the Source function as operands. Loop through all of the operands of the
1207 // functions and patch them up to point to the local versions.
Rafael Espindolaef237112014-12-08 18:45:16 +00001208 for (BasicBlock &BB : Dst)
Rafael Espindolaa314d1a2014-12-08 14:20:10 +00001209 for (Instruction &I : BB)
1210 RemapInstruction(&I, ValueMap, RF_IgnoreMissingEntries, &TypeMap,
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001211 &ValMaterializer);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001212
Chris Lattner7391dde2004-11-16 17:12:38 +00001213 // There is no need to map the arguments anymore.
Rafael Espindola3519da82014-12-08 14:25:26 +00001214 for (Argument &Arg : Src.args())
Rafael Espindolaa314d1a2014-12-08 14:20:10 +00001215 ValueMap.erase(&Arg);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001216
Rafael Espindola3519da82014-12-08 14:25:26 +00001217 Src.Dematerialize();
Rafael Espindola40d7ebe2014-12-08 13:29:33 +00001218 return false;
Reid Spencer361e5132004-11-12 20:37:43 +00001219}
1220
Rafael Espindolaef237112014-12-08 18:45:16 +00001221void ModuleLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
1222 Constant *Aliasee = Src.getAliasee();
1223 Constant *Val =
1224 MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer);
1225 Dst.setAliasee(Val);
1226}
1227
1228bool ModuleLinker::linkGlobalValueBody(GlobalValue &Src) {
1229 Value *Dst = ValueMap[&Src];
1230 assert(Dst);
1231 if (auto *F = dyn_cast<Function>(&Src))
1232 return linkFunctionBody(cast<Function>(*Dst), *F);
1233 if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
1234 linkGlobalInit(cast<GlobalVariable>(*Dst), *GVar);
1235 return false;
Tanya Lattnercbb91402011-10-11 00:24:54 +00001236 }
Rafael Espindolaef237112014-12-08 18:45:16 +00001237 linkAliasBody(cast<GlobalAlias>(*Dst), cast<GlobalAlias>(Src));
1238 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001239}
Anton Korobeynikov26098882008-03-05 23:21:39 +00001240
Rafael Espindola18c89412014-10-27 02:35:46 +00001241/// Insert all of the named MDNodes in Src into the Dest module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001242void ModuleLinker::linkNamedMDNodes() {
Bill Wendling66f02412012-02-11 11:38:06 +00001243 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001244 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1245 E = SrcM->named_metadata_end(); I != E; ++I) {
Bill Wendling66f02412012-02-11 11:38:06 +00001246 // Don't link module flags here. Do them separately.
1247 if (&*I == SrcModFlags) continue;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001248 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1249 // Add Src elements into Dest node.
1250 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
Duncan P. N. Exon Smith46d7af52014-12-19 06:06:18 +00001251 DestNMD->addOperand(MapMetadata(I->getOperand(i), ValueMap, RF_None,
1252 &TypeMap, &ValMaterializer));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001253 }
1254}
Bill Wendling66f02412012-02-11 11:38:06 +00001255
Duncan P. N. Exon Smithfda0cee2014-12-18 01:05:33 +00001256/// Drop DISubprograms that have been superseded.
1257///
1258/// FIXME: this creates an asymmetric result: we strip losing subprograms from
1259/// DstM, but leave losing subprograms in SrcM. Instead we should also strip
Duncan P. N. Exon Smith46d7af52014-12-19 06:06:18 +00001260/// losers from SrcM, but this requires extra plumbing in MapMetadata.
Duncan P. N. Exon Smithfda0cee2014-12-18 01:05:33 +00001261void ModuleLinker::stripReplacedSubprograms() {
1262 // Avoid quadratic runtime by returning early when there's nothing to do.
1263 if (OverridingFunctions.empty())
1264 return;
1265
1266 // Move the functions now, so the set gets cleared even on early returns.
1267 auto Functions = std::move(OverridingFunctions);
1268 OverridingFunctions.clear();
1269
1270 // Drop subprograms whose functions have been overridden by the new compile
1271 // unit.
1272 NamedMDNode *CompileUnits = DstM->getNamedMetadata("llvm.dbg.cu");
1273 if (!CompileUnits)
1274 return;
1275 for (unsigned I = 0, E = CompileUnits->getNumOperands(); I != E; ++I) {
1276 DICompileUnit CU(CompileUnits->getOperand(I));
1277 assert(CU && "Expected valid compile unit");
1278
1279 DITypedArray<DISubprogram> SPs(CU.getSubprograms());
1280 assert(SPs && "Expected valid subprogram array");
1281
1282 SmallVector<Metadata *, 16> NewSPs;
1283 NewSPs.reserve(SPs.getNumElements());
1284 for (unsigned S = 0, SE = SPs.getNumElements(); S != SE; ++S) {
1285 DISubprogram SP = SPs.getElement(S);
1286 if (SP && SP.getFunction() && Functions.count(SP.getFunction()))
1287 continue;
1288
1289 NewSPs.push_back(SP);
1290 }
1291
1292 // Redirect operand to the overriding subprogram.
1293 if (NewSPs.size() != SPs.getNumElements())
1294 CU.replaceSubprograms(DIArray(MDNode::get(DstM->getContext(), NewSPs)));
1295 }
1296}
1297
Rafael Espindola18c89412014-10-27 02:35:46 +00001298/// Merge the linker flags in Src into the Dest module.
Bill Wendling66f02412012-02-11 11:38:06 +00001299bool ModuleLinker::linkModuleFlagsMetadata() {
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001300 // If the source module has no module flags, we are done.
Bill Wendling66f02412012-02-11 11:38:06 +00001301 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1302 if (!SrcModFlags) return false;
1303
Bill Wendling66f02412012-02-11 11:38:06 +00001304 // If the destination module doesn't have module flags yet, then just copy
1305 // over the source module's flags.
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001306 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
Bill Wendling66f02412012-02-11 11:38:06 +00001307 if (DstModFlags->getNumOperands() == 0) {
1308 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1309 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1310
1311 return false;
1312 }
1313
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001314 // First build a map of the existing module flags and requirements.
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001315 DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001316 SmallSetVector<MDNode*, 16> Requirements;
1317 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001318 MDNode *Op = DstModFlags->getOperand(I);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001319 ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001320 MDString *ID = cast<MDString>(Op->getOperand(1));
Bill Wendling66f02412012-02-11 11:38:06 +00001321
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001322 if (Behavior->getZExtValue() == Module::Require) {
1323 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1324 } else {
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001325 Flags[ID] = std::make_pair(Op, I);
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001326 }
Bill Wendling66f02412012-02-11 11:38:06 +00001327 }
1328
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001329 // Merge in the flags from the source module, and also collect its set of
1330 // requirements.
1331 bool HasErr = false;
1332 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001333 MDNode *SrcOp = SrcModFlags->getOperand(I);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001334 ConstantInt *SrcBehavior =
1335 mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001336 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001337 MDNode *DstOp;
1338 unsigned DstIndex;
1339 std::tie(DstOp, DstIndex) = Flags.lookup(ID);
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001340 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
Bill Wendling66f02412012-02-11 11:38:06 +00001341
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001342 // If this is a requirement, add it and continue.
1343 if (SrcBehaviorValue == Module::Require) {
1344 // If the destination module does not already have this requirement, add
1345 // it.
1346 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1347 DstModFlags->addOperand(SrcOp);
1348 }
1349 continue;
Bill Wendling66f02412012-02-11 11:38:06 +00001350 }
1351
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001352 // If there is no existing flag with this ID, just add it.
1353 if (!DstOp) {
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001354 Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001355 DstModFlags->addOperand(SrcOp);
1356 continue;
1357 }
1358
1359 // Otherwise, perform a merge.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001360 ConstantInt *DstBehavior =
1361 mdconst::extract<ConstantInt>(DstOp->getOperand(0));
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001362 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1363
1364 // If either flag has override behavior, handle it first.
1365 if (DstBehaviorValue == Module::Override) {
1366 // Diagnose inconsistent flags which both have override behavior.
1367 if (SrcBehaviorValue == Module::Override &&
1368 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1369 HasErr |= emitError("linking module flags '" + ID->getString() +
1370 "': IDs have conflicting override values");
1371 }
1372 continue;
1373 } else if (SrcBehaviorValue == Module::Override) {
1374 // Update the destination flag to that of the source.
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001375 DstModFlags->setOperand(DstIndex, SrcOp);
1376 Flags[ID].first = SrcOp;
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001377 continue;
1378 }
1379
1380 // Diagnose inconsistent merge behavior types.
1381 if (SrcBehaviorValue != DstBehaviorValue) {
1382 HasErr |= emitError("linking module flags '" + ID->getString() +
1383 "': IDs have conflicting behaviors");
1384 continue;
1385 }
1386
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001387 auto replaceDstValue = [&](MDNode *New) {
1388 Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
1389 MDNode *Flag = MDNode::get(DstM->getContext(), FlagOps);
1390 DstModFlags->setOperand(DstIndex, Flag);
1391 Flags[ID].first = Flag;
1392 };
1393
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001394 // Perform the merge for standard behavior types.
1395 switch (SrcBehaviorValue) {
1396 case Module::Require:
Craig Topper2a30d782014-06-18 05:05:13 +00001397 case Module::Override: llvm_unreachable("not possible");
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001398 case Module::Error: {
1399 // Emit an error if the values differ.
1400 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1401 HasErr |= emitError("linking module flags '" + ID->getString() +
1402 "': IDs have conflicting values");
1403 }
1404 continue;
1405 }
1406 case Module::Warning: {
1407 // Emit a warning if the values differ.
1408 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001409 emitWarning("linking module flags '" + ID->getString() +
1410 "': IDs have conflicting values");
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001411 }
1412 continue;
1413 }
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001414 case Module::Append: {
1415 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1416 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001417 SmallVector<Metadata *, 8> MDs;
1418 MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
1419 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1420 MDs.push_back(DstValue->getOperand(i));
1421 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1422 MDs.push_back(SrcValue->getOperand(i));
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001423
1424 replaceDstValue(MDNode::get(DstM->getContext(), MDs));
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001425 break;
1426 }
1427 case Module::AppendUnique: {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001428 SmallSetVector<Metadata *, 16> Elts;
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001429 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1430 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1431 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1432 Elts.insert(DstValue->getOperand(i));
1433 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1434 Elts.insert(SrcValue->getOperand(i));
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001435
1436 replaceDstValue(MDNode::get(DstM->getContext(),
1437 makeArrayRef(Elts.begin(), Elts.end())));
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001438 break;
1439 }
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001440 }
Bill Wendling66f02412012-02-11 11:38:06 +00001441 }
1442
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001443 // Check all of the requirements.
1444 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1445 MDNode *Requirement = Requirements[I];
1446 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001447 Metadata *ReqValue = Requirement->getOperand(1);
Bill Wendling66f02412012-02-11 11:38:06 +00001448
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001449 MDNode *Op = Flags[Flag].first;
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001450 if (!Op || Op->getOperand(2) != ReqValue) {
1451 HasErr |= emitError("linking module flags '" + Flag->getString() +
1452 "': does not have the required value");
1453 continue;
Bill Wendling66f02412012-02-11 11:38:06 +00001454 }
1455 }
1456
1457 return HasErr;
1458}
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001459
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001460bool ModuleLinker::run() {
Bill Wendling66f02412012-02-11 11:38:06 +00001461 assert(DstM && "Null destination module");
1462 assert(SrcM && "Null source module");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001463
1464 // Inherit the target data from the source module if the destination module
1465 // doesn't have one already.
Rafael Espindolaf863ee22014-02-25 20:01:08 +00001466 if (!DstM->getDataLayout() && SrcM->getDataLayout())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001467 DstM->setDataLayout(SrcM->getDataLayout());
1468
1469 // Copy the target triple from the source to dest if the dest's is empty.
1470 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1471 DstM->setTargetTriple(SrcM->getTargetTriple());
1472
Rafael Espindolaf863ee22014-02-25 20:01:08 +00001473 if (SrcM->getDataLayout() && DstM->getDataLayout() &&
Rafael Espindolaae593f12014-02-26 17:02:08 +00001474 *SrcM->getDataLayout() != *DstM->getDataLayout()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001475 emitWarning("Linking two modules of different data layouts: '" +
1476 SrcM->getModuleIdentifier() + "' is '" +
1477 SrcM->getDataLayoutStr() + "' whereas '" +
1478 DstM->getModuleIdentifier() + "' is '" +
1479 DstM->getDataLayoutStr() + "'\n");
Eli Benderskye17f3702014-02-06 18:01:56 +00001480 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001481 if (!SrcM->getTargetTriple().empty() &&
1482 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001483 emitWarning("Linking two modules of different target triples: " +
1484 SrcM->getModuleIdentifier() + "' is '" +
1485 SrcM->getTargetTriple() + "' whereas '" +
1486 DstM->getModuleIdentifier() + "' is '" +
1487 DstM->getTargetTriple() + "'\n");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001488 }
1489
1490 // Append the module inline asm string.
1491 if (!SrcM->getModuleInlineAsm().empty()) {
1492 if (DstM->getModuleInlineAsm().empty())
1493 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1494 else
1495 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1496 SrcM->getModuleInlineAsm());
1497 }
1498
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001499 // Loop over all of the linked values to compute type mappings.
1500 computeTypeMapping();
1501
David Majnemerdad0a642014-06-27 18:19:56 +00001502 ComdatsChosen.clear();
David Blaikie5106ce72014-11-19 05:49:42 +00001503 for (const auto &SMEC : SrcM->getComdatSymbolTable()) {
David Majnemerdad0a642014-06-27 18:19:56 +00001504 const Comdat &C = SMEC.getValue();
1505 if (ComdatsChosen.count(&C))
1506 continue;
1507 Comdat::SelectionKind SK;
1508 bool LinkFromSrc;
1509 if (getComdatResult(&C, SK, LinkFromSrc))
1510 return true;
1511 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1512 }
1513
Duncan P. N. Exon Smith09d84ad2014-08-12 16:46:37 +00001514 // Upgrade mismatched global arrays.
1515 upgradeMismatchedGlobals();
1516
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001517 // Insert all of the globals in src into the DstM module... without linking
1518 // initializers (which could refer to functions not yet mapped over).
1519 for (Module::global_iterator I = SrcM->global_begin(),
1520 E = SrcM->global_end(); I != E; ++I)
Rafael Espindola778fcc72014-11-02 13:28:57 +00001521 if (linkGlobalValueProto(I))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001522 return true;
1523
1524 // Link the functions together between the two modules, without doing function
1525 // bodies... this just adds external function prototypes to the DstM
1526 // function... We do this so that when we begin processing function bodies,
1527 // all of the global values that may be referenced are available in our
1528 // ValueMap.
1529 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
Rafael Espindola778fcc72014-11-02 13:28:57 +00001530 if (linkGlobalValueProto(I))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001531 return true;
1532
1533 // If there were any aliases, link them now.
1534 for (Module::alias_iterator I = SrcM->alias_begin(),
1535 E = SrcM->alias_end(); I != E; ++I)
Rafael Espindola778fcc72014-11-02 13:28:57 +00001536 if (linkGlobalValueProto(I))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001537 return true;
1538
1539 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1540 linkAppendingVarInit(AppendingVars[i]);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001541
Rafael Espindolabeadd562014-12-08 18:05:48 +00001542 for (const auto &Entry : DstM->getComdatSymbolTable()) {
1543 const Comdat &C = Entry.getValue();
1544 if (C.getSelectionKind() == Comdat::Any)
1545 continue;
1546 const GlobalValue *GV = SrcM->getNamedValue(C.getName());
1547 assert(GV);
1548 MapValue(GV, ValueMap, RF_None, &TypeMap, &ValMaterializer);
1549 }
1550
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001551 // Link in the function bodies that are defined in the source module into
1552 // DstM.
Rafael Espindolaf97d0cb2014-12-08 13:35:09 +00001553 for (Function &SF : *SrcM) {
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00001554 // Skip if no body (function is external).
Rafael Espindolaf97d0cb2014-12-08 13:35:09 +00001555 if (SF.isDeclaration())
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00001556 continue;
1557
Rafael Espindolaf97d0cb2014-12-08 13:35:09 +00001558 // Skip if not linking from source.
1559 if (DoNotLinkFromSource.count(&SF))
1560 continue;
1561
Rafael Espindolaef237112014-12-08 18:45:16 +00001562 if (linkGlobalValueBody(SF))
Rafael Espindola40d7ebe2014-12-08 13:29:33 +00001563 return true;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001564 }
1565
1566 // Resolve all uses of aliases with aliasees.
Rafael Espindolaef237112014-12-08 18:45:16 +00001567 for (GlobalAlias &Src : SrcM->aliases()) {
1568 if (DoNotLinkFromSource.count(&Src))
1569 continue;
1570 linkGlobalValueBody(Src);
1571 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001572
Duncan P. N. Exon Smithfda0cee2014-12-18 01:05:33 +00001573 // Strip replaced subprograms before linking together compile units.
1574 stripReplacedSubprograms();
1575
Bill Wendling66f02412012-02-11 11:38:06 +00001576 // Remap all of the named MDNodes in Src into the DstM module. We do this
Devang Patel6ddbb2e2011-08-04 19:44:28 +00001577 // after linking GlobalValues so that MDNodes that reference GlobalValues
1578 // are properly remapped.
1579 linkNamedMDNodes();
1580
Bill Wendling66f02412012-02-11 11:38:06 +00001581 // Merge the module flags into the DstM module.
1582 if (linkModuleFlagsMetadata())
1583 return true;
1584
Bill Wendling91686d62014-01-16 06:29:36 +00001585 // Update the initializers in the DstM module now that all globals that may
1586 // be referenced are in DstM.
Rafael Espindolaef237112014-12-08 18:45:16 +00001587 for (GlobalVariable &Src : SrcM->globals()) {
1588 // Only process initialized GV's or ones not already in dest.
1589 if (!Src.hasInitializer() || DoNotLinkFromSource.count(&Src))
1590 continue;
1591 linkGlobalValueBody(Src);
1592 }
Bill Wendling91686d62014-01-16 06:29:36 +00001593
Tanya Lattner0a48b872011-11-02 00:24:56 +00001594 // Process vector of lazily linked in functions.
Rafael Espindolaef237112014-12-08 18:45:16 +00001595 while (!LazilyLinkGlobalValues.empty()) {
1596 GlobalValue *SGV = LazilyLinkGlobalValues.back();
1597 LazilyLinkGlobalValues.pop_back();
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001598
Rafael Espindola9573a9c2014-12-16 22:29:43 +00001599 assert(!SGV->isDeclaration() && "users should not pass down decls");
Rafael Espindolaef237112014-12-08 18:45:16 +00001600 if (linkGlobalValueBody(*SGV))
Rafael Espindola40d7ebe2014-12-08 13:29:33 +00001601 return true;
Rafael Espindola28a24512014-12-05 21:04:36 +00001602 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001603
Anton Korobeynikov26098882008-03-05 23:21:39 +00001604 return false;
1605}
Reid Spencer361e5132004-11-12 20:37:43 +00001606
Rafael Espindola31ad4682014-12-03 22:36:37 +00001607Linker::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
1608 : ETypes(E), IsPacked(P) {}
1609
1610Linker::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
1611 : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1612
1613bool Linker::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
1614 if (IsPacked != That.IsPacked)
1615 return false;
1616 if (ETypes != That.ETypes)
1617 return false;
1618 return true;
1619}
1620
1621bool Linker::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
1622 return !this->operator==(That);
1623}
1624
1625StructType *Linker::StructTypeKeyInfo::getEmptyKey() {
1626 return DenseMapInfo<StructType *>::getEmptyKey();
1627}
1628
1629StructType *Linker::StructTypeKeyInfo::getTombstoneKey() {
1630 return DenseMapInfo<StructType *>::getTombstoneKey();
1631}
1632
1633unsigned Linker::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1634 return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1635 Key.IsPacked);
1636}
1637
1638unsigned Linker::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1639 return getHashValue(KeyTy(ST));
1640}
1641
1642bool Linker::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1643 const StructType *RHS) {
1644 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1645 return false;
1646 return LHS == KeyTy(RHS);
1647}
1648
1649bool Linker::StructTypeKeyInfo::isEqual(const StructType *LHS,
1650 const StructType *RHS) {
1651 if (RHS == getEmptyKey())
1652 return LHS == getEmptyKey();
1653
1654 if (RHS == getTombstoneKey())
1655 return LHS == getTombstoneKey();
1656
1657 return KeyTy(LHS) == KeyTy(RHS);
1658}
1659
1660void Linker::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
1661 assert(!Ty->isOpaque());
Benjamin Kramer3280a5d2014-12-06 19:22:54 +00001662 NonOpaqueStructTypes.insert(Ty);
Rafael Espindola31ad4682014-12-03 22:36:37 +00001663}
1664
1665void Linker::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
1666 assert(Ty->isOpaque());
1667 OpaqueStructTypes.insert(Ty);
1668}
1669
1670StructType *
1671Linker::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
1672 bool IsPacked) {
1673 Linker::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
1674 auto I = NonOpaqueStructTypes.find_as(Key);
1675 if (I == NonOpaqueStructTypes.end())
1676 return nullptr;
Benjamin Kramer3280a5d2014-12-06 19:22:54 +00001677 return *I;
Rafael Espindola31ad4682014-12-03 22:36:37 +00001678}
1679
1680bool Linker::IdentifiedStructTypeSet::hasType(StructType *Ty) {
1681 if (Ty->isOpaque())
1682 return OpaqueStructTypes.count(Ty);
1683 auto I = NonOpaqueStructTypes.find(Ty);
1684 if (I == NonOpaqueStructTypes.end())
1685 return false;
Benjamin Kramer3280a5d2014-12-06 19:22:54 +00001686 return *I == Ty;
Rafael Espindola31ad4682014-12-03 22:36:37 +00001687}
1688
Rafael Espindola5cb9c822014-11-17 20:51:01 +00001689void Linker::init(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
1690 this->Composite = M;
1691 this->DiagnosticHandler = DiagnosticHandler;
Rafael Espindolaa4e85e32014-12-01 16:32:20 +00001692
1693 TypeFinder StructTypes;
1694 StructTypes.run(*M, true);
Rafael Espindola31ad4682014-12-03 22:36:37 +00001695 for (StructType *Ty : StructTypes) {
1696 if (Ty->isOpaque())
1697 IdentifiedStructTypes.addOpaque(Ty);
1698 else
1699 IdentifiedStructTypes.addNonOpaque(Ty);
1700 }
Rafael Espindolaaa9918a2013-05-04 05:05:18 +00001701}
Rafael Espindola3df61b72013-05-04 03:48:37 +00001702
Rafael Espindola5cb9c822014-11-17 20:51:01 +00001703Linker::Linker(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
1704 init(M, DiagnosticHandler);
1705}
1706
1707Linker::Linker(Module *M) {
1708 init(M, [this](const DiagnosticInfo &DI) {
1709 Composite->getContext().diagnose(DI);
1710 });
1711}
1712
Rafael Espindola3df61b72013-05-04 03:48:37 +00001713Linker::~Linker() {
1714}
1715
Bill Wendling91e6f6e2013-10-16 08:59:57 +00001716void Linker::deleteModule() {
1717 delete Composite;
Craig Topper2617dcc2014-04-15 06:32:26 +00001718 Composite = nullptr;
Bill Wendling91e6f6e2013-10-16 08:59:57 +00001719}
1720
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001721bool Linker::linkInModule(Module *Src) {
Rafael Espindolaa4e85e32014-12-01 16:32:20 +00001722 ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src,
1723 DiagnosticHandler);
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001724 return TheLinker.run();
Rafael Espindola3df61b72013-05-04 03:48:37 +00001725}
1726
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001727//===----------------------------------------------------------------------===//
1728// LinkModules entrypoint.
1729//===----------------------------------------------------------------------===//
1730
Rafael Espindola18c89412014-10-27 02:35:46 +00001731/// This function links two modules together, with the resulting Dest module
1732/// modified to be the composite of the two input modules. If an error occurs,
1733/// true is returned and ErrorMsg (if not null) is set to indicate the problem.
1734/// Upon failure, the Dest module could be in a modified state, and shouldn't be
1735/// relied on to be consistent.
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001736bool Linker::LinkModules(Module *Dest, Module *Src,
Rafael Espindola4160f5d2014-10-27 23:02:10 +00001737 DiagnosticHandlerFunction DiagnosticHandler) {
1738 Linker L(Dest, DiagnosticHandler);
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001739 return L.linkInModule(Src);
Rafael Espindola4160f5d2014-10-27 23:02:10 +00001740}
1741
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001742bool Linker::LinkModules(Module *Dest, Module *Src) {
Rafael Espindola287f18b2013-05-04 04:08:02 +00001743 Linker L(Dest);
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001744 return L.linkInModule(Src);
Reid Spencer361e5132004-11-12 20:37:43 +00001745}
Bill Wendlinga3aeb982012-05-09 08:55:40 +00001746
1747//===----------------------------------------------------------------------===//
1748// C API.
1749//===----------------------------------------------------------------------===//
1750
1751LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
Rafael Espindolac6c58d52014-12-23 19:16:45 +00001752 unsigned Unused, char **OutMessages) {
Rafael Espindola98ab63c2014-10-25 04:31:08 +00001753 Module *D = unwrap(Dest);
Rafael Espindola98ab63c2014-10-25 04:31:08 +00001754 std::string Message;
Rafael Espindola4160f5d2014-10-27 23:02:10 +00001755 raw_string_ostream Stream(Message);
1756 DiagnosticPrinterRawOStream DP(Stream);
1757
1758 LLVMBool Result = Linker::LinkModules(
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001759 D, unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
Rafael Espindola98ab63c2014-10-25 04:31:08 +00001760
1761 if (OutMessages && Result)
1762 *OutMessages = strdup(Message.c_str());
Bill Wendlinga3aeb982012-05-09 08:55:40 +00001763 return Result;
1764}