blob: 8f2200e4ea2e88572de5d64bc96f883e0cb3eb71 [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
Reid Spencer9b0ddbb2004-11-14 23:27:04 +000014#include "llvm/Linker.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm-c/Linker.h"
Rafael Espindola23f8d642012-01-05 23:02:01 +000016#include "llvm/ADT/Optional.h"
Bill Wendling66f02412012-02-11 11:38:06 +000017#include "llvm/ADT/SetVector.h"
Eli Bendersky0f7fd362013-03-19 15:26:24 +000018#include "llvm/ADT/SmallString.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000019#include "llvm/IR/Constants.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000020#include "llvm/IR/Module.h"
Chandler Carruthdcb603f2013-01-07 15:43:51 +000021#include "llvm/IR/TypeFinder.h"
Bill Wendlingb6af2f32012-03-22 20:28:27 +000022#include "llvm/Support/Debug.h"
Bill Wendlingb6af2f32012-03-22 20:28:27 +000023#include "llvm/Support/raw_ostream.h"
Tanya Lattnercbb91402011-10-11 00:24:54 +000024#include "llvm/Transforms/Utils/Cloning.h"
Will Dietz981af002013-10-12 00:55:57 +000025#include <cctype>
Reid Spencer361e5132004-11-12 20:37:43 +000026using namespace llvm;
27
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000028//===----------------------------------------------------------------------===//
29// TypeMap implementation.
30//===----------------------------------------------------------------------===//
Reid Spencer361e5132004-11-12 20:37:43 +000031
Chris Lattnereee6f992008-06-16 21:00:18 +000032namespace {
Rafael Espindolaaa9918a2013-05-04 05:05:18 +000033 typedef SmallPtrSet<StructType*, 32> TypeSet;
34
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000035class TypeMapTy : public ValueMapTypeRemapper {
36 /// MappedTypes - This is a mapping from a source type to a destination type
37 /// to use.
38 DenseMap<Type*, Type*> MappedTypes;
Mikhail Glushenkov766d4892009-03-03 07:22:23 +000039
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000040 /// SpeculativeTypes - When checking to see if two subgraphs are isomorphic,
41 /// we speculatively add types to MappedTypes, but keep track of them here in
42 /// case we need to roll back.
43 SmallVector<Type*, 16> SpeculativeTypes;
44
Chris Lattner5e3bd972011-12-20 00:03:52 +000045 /// SrcDefinitionsToResolve - This is a list of non-opaque structs in the
46 /// source module that are mapped to an opaque struct in the destination
47 /// module.
48 SmallVector<StructType*, 16> SrcDefinitionsToResolve;
49
50 /// DstResolvedOpaqueTypes - This is the set of opaque types in the
51 /// destination modules who are getting a body from the source module.
52 SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
Bill Wendling8c2cc412012-03-22 20:30:41 +000053
Chris Lattner56cdea62008-06-16 23:06:51 +000054public:
Rafael Espindolaaa9918a2013-05-04 05:05:18 +000055 TypeMapTy(TypeSet &Set) : DstStructTypesSet(Set) {}
56
57 TypeSet &DstStructTypesSet;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000058 /// addTypeMapping - Indicate that the specified type in the destination
59 /// module is conceptually equivalent to the specified type in the source
60 /// module.
61 void addTypeMapping(Type *DstTy, Type *SrcTy);
62
63 /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
64 /// module from a type definition in the source module.
65 void linkDefinedTypeBodies();
66
67 /// get - Return the mapped type to use for the specified input type from the
68 /// source module.
69 Type *get(Type *SrcTy);
70
71 FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*)T));}
72
Bill Wendlingb6af2f32012-03-22 20:28:27 +000073 /// dump - Dump out the type map for debugging purposes.
74 void dump() const {
75 for (DenseMap<Type*, Type*>::const_iterator
76 I = MappedTypes.begin(), E = MappedTypes.end(); I != E; ++I) {
77 dbgs() << "TypeMap: ";
78 I->first->dump();
79 dbgs() << " => ";
80 I->second->dump();
81 dbgs() << '\n';
82 }
83 }
Bill Wendlingb6af2f32012-03-22 20:28:27 +000084
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000085private:
86 Type *getImpl(Type *T);
87 /// remapType - Implement the ValueMapTypeRemapper interface.
88 Type *remapType(Type *SrcTy) {
89 return get(SrcTy);
Chris Lattnereee6f992008-06-16 21:00:18 +000090 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000091
92 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
Chris Lattnereee6f992008-06-16 21:00:18 +000093};
94}
95
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000096void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
97 Type *&Entry = MappedTypes[SrcTy];
98 if (Entry) return;
99
100 if (DstTy == SrcTy) {
101 Entry = DstTy;
102 return;
103 }
Bill Wendlingd48b7782012-02-28 04:01:21 +0000104
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000105 // Check to see if these types are recursively isomorphic and establish a
106 // mapping between them if so.
Bill Wendlingd48b7782012-02-28 04:01:21 +0000107 if (!areTypesIsomorphic(DstTy, SrcTy)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000108 // Oops, they aren't isomorphic. Just discard this request by rolling out
109 // any speculative mappings we've established.
110 for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i)
111 MappedTypes.erase(SpeculativeTypes[i]);
Bill Wendlingd48b7782012-02-28 04:01:21 +0000112 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000113 SpeculativeTypes.clear();
114}
Chris Lattnereee6f992008-06-16 21:00:18 +0000115
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000116/// areTypesIsomorphic - Recursively walk this pair of types, returning true
117/// if they are isomorphic, false if they are not.
118bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
119 // Two types with differing kinds are clearly not isomorphic.
120 if (DstTy->getTypeID() != SrcTy->getTypeID()) return false;
Misha Brukman10468d82005-04-21 22:55:34 +0000121
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000122 // If we have an entry in the MappedTypes table, then we have our answer.
123 Type *&Entry = MappedTypes[SrcTy];
124 if (Entry)
125 return Entry == DstTy;
Misha Brukman10468d82005-04-21 22:55:34 +0000126
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000127 // Two identical types are clearly isomorphic. Remember this
128 // non-speculatively.
129 if (DstTy == SrcTy) {
130 Entry = DstTy;
Chris Lattnerfe677e92008-06-16 20:03:01 +0000131 return true;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000132 }
Bill Wendlingd48b7782012-02-28 04:01:21 +0000133
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000134 // Okay, we have two types with identical kinds that we haven't seen before.
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000135
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000136 // If this is an opaque struct type, special case it.
137 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
138 // Mapping an opaque type to any struct, just keep the dest struct.
139 if (SSTy->isOpaque()) {
140 Entry = DstTy;
141 SpeculativeTypes.push_back(SrcTy);
Reid Spencer361e5132004-11-12 20:37:43 +0000142 return true;
Chris Lattner9be15892008-06-16 21:17:12 +0000143 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000144
Chris Lattner5e3bd972011-12-20 00:03:52 +0000145 // Mapping a non-opaque source type to an opaque dest. If this is the first
146 // type that we're mapping onto this destination type then we succeed. Keep
147 // the dest, but fill it in later. This doesn't need to be speculative. If
148 // this is the second (different) type that we're trying to map onto the
149 // same opaque type then we fail.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000150 if (cast<StructType>(DstTy)->isOpaque()) {
Chris Lattner5e3bd972011-12-20 00:03:52 +0000151 // We can only map one source type onto the opaque destination type.
152 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)))
153 return false;
154 SrcDefinitionsToResolve.push_back(SSTy);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000155 Entry = DstTy;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000156 return true;
157 }
158 }
159
160 // If the number of subtypes disagree between the two types, then we fail.
161 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
Reid Spencer361e5132004-11-12 20:37:43 +0000162 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000163
164 // Fail if any of the extra properties (e.g. array size) of the type disagree.
165 if (isa<IntegerType>(DstTy))
166 return false; // bitwidth disagrees.
167 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
168 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
169 return false;
Chris Lattnereaf9b762011-12-20 23:14:57 +0000170
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000171 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
172 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
173 return false;
174 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
175 StructType *SSTy = cast<StructType>(SrcTy);
Chris Lattner44f7ab42011-08-12 18:07:26 +0000176 if (DSTy->isLiteral() != SSTy->isLiteral() ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000177 DSTy->isPacked() != SSTy->isPacked())
178 return false;
179 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
180 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
181 return false;
182 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
Joey Gouly5fad3e92013-01-10 10:49:36 +0000183 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000184 return false;
Reid Spencer361e5132004-11-12 20:37:43 +0000185 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000186
187 // Otherwise, we speculate that these two types will line up and recursively
188 // check the subelements.
189 Entry = DstTy;
190 SpeculativeTypes.push_back(SrcTy);
191
Bill Wendlingd48b7782012-02-28 04:01:21 +0000192 for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i)
193 if (!areTypesIsomorphic(DstTy->getContainedType(i),
194 SrcTy->getContainedType(i)))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000195 return false;
196
197 // If everything seems to have lined up, then everything is great.
198 return true;
199}
200
201/// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
202/// module from a type definition in the source module.
203void TypeMapTy::linkDefinedTypeBodies() {
204 SmallVector<Type*, 16> Elements;
205 SmallString<16> TmpName;
206
207 // Note that processing entries in this loop (calling 'get') can add new
Chris Lattner5e3bd972011-12-20 00:03:52 +0000208 // entries to the SrcDefinitionsToResolve vector.
209 while (!SrcDefinitionsToResolve.empty()) {
210 StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000211 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
212
213 // TypeMap is a many-to-one mapping, if there were multiple types that
214 // provide a body for DstSTy then previous iterations of this loop may have
215 // already handled it. Just ignore this case.
216 if (!DstSTy->isOpaque()) continue;
217 assert(!SrcSTy->isOpaque() && "Not resolving a definition?");
218
219 // Map the body of the source type over to a new body for the dest type.
220 Elements.resize(SrcSTy->getNumElements());
221 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
222 Elements[i] = getImpl(SrcSTy->getElementType(i));
223
224 DstSTy->setBody(Elements, SrcSTy->isPacked());
225
226 // If DstSTy has no name or has a longer name than STy, then viciously steal
227 // STy's name.
228 if (!SrcSTy->hasName()) continue;
229 StringRef SrcName = SrcSTy->getName();
230
231 if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
232 TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
233 SrcSTy->setName("");
234 DstSTy->setName(TmpName.str());
235 TmpName.clear();
236 }
237 }
Chris Lattner5e3bd972011-12-20 00:03:52 +0000238
239 DstResolvedOpaqueTypes.clear();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000240}
241
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000242/// get - Return the mapped type to use for the specified input type from the
243/// source module.
244Type *TypeMapTy::get(Type *Ty) {
245 Type *Result = getImpl(Ty);
246
247 // If this caused a reference to any struct type, resolve it before returning.
Chris Lattner5e3bd972011-12-20 00:03:52 +0000248 if (!SrcDefinitionsToResolve.empty())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000249 linkDefinedTypeBodies();
250 return Result;
251}
252
253/// getImpl - This is the recursive version of get().
254Type *TypeMapTy::getImpl(Type *Ty) {
255 // If we already have an entry for this type, return it.
256 Type **Entry = &MappedTypes[Ty];
257 if (*Entry) return *Entry;
Bill Wendlingd48b7782012-02-28 04:01:21 +0000258
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000259 // If this is not a named struct type, then just map all of the elements and
260 // then rebuild the type from inside out.
Chris Lattner44f7ab42011-08-12 18:07:26 +0000261 if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000262 // If there are no element types to map, then the type is itself. This is
263 // true for the anonymous {} struct, things like 'float', integers, etc.
264 if (Ty->getNumContainedTypes() == 0)
265 return *Entry = Ty;
266
267 // Remap all of the elements, keeping track of whether any of them change.
268 bool AnyChange = false;
269 SmallVector<Type*, 4> ElementTypes;
270 ElementTypes.resize(Ty->getNumContainedTypes());
271 for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) {
272 ElementTypes[i] = getImpl(Ty->getContainedType(i));
273 AnyChange |= ElementTypes[i] != Ty->getContainedType(i);
274 }
275
276 // If we found our type while recursively processing stuff, just use it.
277 Entry = &MappedTypes[Ty];
278 if (*Entry) return *Entry;
279
280 // If all of the element types mapped directly over, then the type is usable
281 // as-is.
282 if (!AnyChange)
283 return *Entry = Ty;
284
285 // Otherwise, rebuild a modified type.
286 switch (Ty->getTypeID()) {
Craig Toppera2886c22012-02-07 05:05:23 +0000287 default: llvm_unreachable("unknown derived type to remap");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000288 case Type::ArrayTyID:
289 return *Entry = ArrayType::get(ElementTypes[0],
290 cast<ArrayType>(Ty)->getNumElements());
291 case Type::VectorTyID:
292 return *Entry = VectorType::get(ElementTypes[0],
293 cast<VectorType>(Ty)->getNumElements());
294 case Type::PointerTyID:
295 return *Entry = PointerType::get(ElementTypes[0],
296 cast<PointerType>(Ty)->getAddressSpace());
297 case Type::FunctionTyID:
298 return *Entry = FunctionType::get(ElementTypes[0],
Frits van Bommel717d7ed2011-07-18 12:00:32 +0000299 makeArrayRef(ElementTypes).slice(1),
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000300 cast<FunctionType>(Ty)->isVarArg());
301 case Type::StructTyID:
302 // Note that this is only reached for anonymous structs.
303 return *Entry = StructType::get(Ty->getContext(), ElementTypes,
304 cast<StructType>(Ty)->isPacked());
305 }
306 }
307
308 // Otherwise, this is an unmapped named struct. If the struct can be directly
309 // mapped over, just use it as-is. This happens in a case when the linked-in
310 // module has something like:
311 // %T = type {%T*, i32}
312 // @GV = global %T* null
313 // where T does not exist at all in the destination module.
314 //
315 // The other case we watch for is when the type is not in the destination
316 // module, but that it has to be rebuilt because it refers to something that
317 // is already mapped. For example, if the destination module has:
318 // %A = type { i32 }
319 // and the source module has something like
320 // %A' = type { i32 }
321 // %B = type { %A'* }
322 // @GV = global %B* null
323 // then we want to create a new type: "%B = type { %A*}" and have it take the
324 // pristine "%B" name from the source module.
325 //
326 // To determine which case this is, we have to recursively walk the type graph
327 // speculating that we'll be able to reuse it unmodified. Only if this is
328 // safe would we map the entire thing over. Because this is an optimization,
329 // and is not required for the prettiness of the linked module, we just skip
330 // it and always rebuild a type here.
331 StructType *STy = cast<StructType>(Ty);
332
333 // If the type is opaque, we can just use it directly.
Rafael Espindolaaa9918a2013-05-04 05:05:18 +0000334 if (STy->isOpaque()) {
335 // A named structure type from src module is used. Add it to the Set of
336 // identified structs in the destination module.
337 DstStructTypesSet.insert(STy);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000338 return *Entry = STy;
Rafael Espindolaaa9918a2013-05-04 05:05:18 +0000339 }
Bill Wendlingd48b7782012-02-28 04:01:21 +0000340
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000341 // Otherwise we create a new type and resolve its body later. This will be
342 // resolved by the top level of get().
Chris Lattner5e3bd972011-12-20 00:03:52 +0000343 SrcDefinitionsToResolve.push_back(STy);
344 StructType *DTy = StructType::create(STy->getContext());
Rafael Espindolaaa9918a2013-05-04 05:05:18 +0000345 // A new identified structure type was created. Add it to the set of
346 // identified structs in the destination module.
347 DstStructTypesSet.insert(DTy);
Chris Lattner5e3bd972011-12-20 00:03:52 +0000348 DstResolvedOpaqueTypes.insert(DTy);
349 return *Entry = DTy;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000350}
351
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000352//===----------------------------------------------------------------------===//
353// ModuleLinker implementation.
354//===----------------------------------------------------------------------===//
355
356namespace {
James Molloyf6f121e2013-05-28 15:17:05 +0000357 class ModuleLinker;
358
359 /// ValueMaterializerTy - Creates prototypes for functions that are lazily
360 /// linked on the fly. This speeds up linking for modules with many
361 /// lazily linked functions of which few get used.
362 class ValueMaterializerTy : public ValueMaterializer {
363 TypeMapTy &TypeMap;
364 Module *DstM;
365 std::vector<Function*> &LazilyLinkFunctions;
366 public:
367 ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
368 std::vector<Function*> &LazilyLinkFunctions) :
369 ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
370 LazilyLinkFunctions(LazilyLinkFunctions) {
371 }
372
373 virtual Value *materializeValueFor(Value *V);
374 };
375
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000376 /// ModuleLinker - This is an implementation class for the LinkModules
377 /// function, which is the entrypoint for this file.
378 class ModuleLinker {
379 Module *DstM, *SrcM;
380
381 TypeMapTy TypeMap;
James Molloyf6f121e2013-05-28 15:17:05 +0000382 ValueMaterializerTy ValMaterializer;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000383
384 /// ValueMap - Mapping of values from what they used to be in Src, to what
385 /// they are now in DstM. ValueToValueMapTy is a ValueMap, which involves
386 /// some overhead due to the use of Value handles which the Linker doesn't
387 /// actually need, but this allows us to reuse the ValueMapper code.
388 ValueToValueMapTy ValueMap;
389
390 struct AppendingVarInfo {
391 GlobalVariable *NewGV; // New aggregate global in dest module.
392 Constant *DstInit; // Old initializer from dest module.
393 Constant *SrcInit; // Old initializer from src module.
394 };
395
396 std::vector<AppendingVarInfo> AppendingVars;
397
Tanya Lattnercbb91402011-10-11 00:24:54 +0000398 unsigned Mode; // Mode to treat source module.
399
400 // Set of items not to link in from source.
401 SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
402
Tanya Lattner0a48b872011-11-02 00:24:56 +0000403 // Vector of functions to lazily link in.
Bill Wendlingfa2287822013-03-27 17:54:41 +0000404 std::vector<Function*> LazilyLinkFunctions;
Tanya Lattner0a48b872011-11-02 00:24:56 +0000405
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000406 public:
407 std::string ErrorMsg;
408
Rafael Espindolaaa9918a2013-05-04 05:05:18 +0000409 ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM, unsigned mode)
James Molloyf6f121e2013-05-28 15:17:05 +0000410 : DstM(dstM), SrcM(srcM), TypeMap(Set),
411 ValMaterializer(TypeMap, DstM, LazilyLinkFunctions),
412 Mode(mode) { }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000413
414 bool run();
415
416 private:
417 /// emitError - Helper method for setting a message and returning an error
418 /// code.
419 bool emitError(const Twine &Message) {
420 ErrorMsg = Message.str();
Chris Lattner99953022008-06-16 18:27:53 +0000421 return true;
Chris Lattner9be15892008-06-16 21:17:12 +0000422 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000423
424 /// getLinkageResult - This analyzes the two global values and determines
425 /// what the result will look like in the destination module.
426 bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Rafael Espindola23f8d642012-01-05 23:02:01 +0000427 GlobalValue::LinkageTypes &LT,
428 GlobalValue::VisibilityTypes &Vis,
429 bool &LinkFromSrc);
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000430
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000431 /// getLinkedToGlobal - Given a global in the source module, return the
432 /// global in the destination module that is being linked to, if any.
433 GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
434 // If the source has no name it can't link. If it has local linkage,
435 // there is no name match-up going on.
436 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
437 return 0;
Bill Wendlingd48b7782012-02-28 04:01:21 +0000438
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000439 // Otherwise see if we have a match in the destination module's symtab.
440 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
441 if (DGV == 0) return 0;
Bill Wendlingd48b7782012-02-28 04:01:21 +0000442
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000443 // If we found a global with the same name in the dest module, but it has
444 // internal linkage, we are really not doing any linkage here.
445 if (DGV->hasLocalLinkage())
446 return 0;
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000447
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000448 // Otherwise, we do in fact link to the destination global.
449 return DGV;
450 }
451
452 void computeTypeMapping();
453
454 bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
455 bool linkGlobalProto(GlobalVariable *SrcGV);
456 bool linkFunctionProto(Function *SrcF);
457 bool linkAliasProto(GlobalAlias *SrcA);
Bill Wendling66f02412012-02-11 11:38:06 +0000458 bool linkModuleFlagsMetadata();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000459
460 void linkAppendingVarInit(const AppendingVarInfo &AVI);
461 void linkGlobalInits();
462 void linkFunctionBody(Function *Dst, Function *Src);
463 void linkAliasBodies();
464 void linkNamedMDNodes();
465 };
Bill Wendlingd48b7782012-02-28 04:01:21 +0000466}
467
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000468/// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
Reid Spencer90246aa2007-02-04 04:29:21 +0000469/// in the symbol table. This is good for all clients except for us. Go
470/// through the trouble to force this back.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000471static void forceRenaming(GlobalValue *GV, StringRef Name) {
472 // If the global doesn't force its name or if it already has the right name,
473 // there is nothing for us to do.
474 if (GV->hasLocalLinkage() || GV->getName() == Name)
475 return;
476
477 Module *M = GV->getParent();
Reid Spencer361e5132004-11-12 20:37:43 +0000478
479 // If there is a conflict, rename the conflict.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000480 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
Chris Lattner2a8d2e02007-02-11 00:39:38 +0000481 GV->takeName(ConflictGV);
482 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000483 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
Chris Lattner2a8d2e02007-02-11 00:39:38 +0000484 } else {
485 GV->setName(Name); // Force the name back
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000486 }
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000487}
Reid Spencer90246aa2007-02-04 04:29:21 +0000488
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000489/// copyGVAttributes - copy additional attributes (those not needed to construct
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000490/// a GlobalValue) from the SrcGV to the DestGV.
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000491static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
Duncan Sandsdd7daee2008-05-26 19:58:59 +0000492 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
493 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
494 DestGV->copyAttributesFrom(SrcGV);
495 DestGV->setAlignment(Alignment);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000496
497 forceRenaming(DestGV, SrcGV->getName());
Reid Spencer361e5132004-11-12 20:37:43 +0000498}
499
Rafael Espindola23f8d642012-01-05 23:02:01 +0000500static bool isLessConstraining(GlobalValue::VisibilityTypes a,
501 GlobalValue::VisibilityTypes b) {
502 if (a == GlobalValue::HiddenVisibility)
503 return false;
504 if (b == GlobalValue::HiddenVisibility)
505 return true;
506 if (a == GlobalValue::ProtectedVisibility)
507 return false;
508 if (b == GlobalValue::ProtectedVisibility)
509 return true;
510 return false;
511}
512
James Molloyf6f121e2013-05-28 15:17:05 +0000513Value *ValueMaterializerTy::materializeValueFor(Value *V) {
514 Function *SF = dyn_cast<Function>(V);
515 if (!SF)
516 return NULL;
517
518 Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()),
519 SF->getLinkage(), SF->getName(), DstM);
520 copyGVAttributes(DF, SF);
521
522 LazilyLinkFunctions.push_back(SF);
523 return DF;
524}
525
526
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000527/// getLinkageResult - This analyzes the two global values and determines what
Chris Lattnerfc61de32004-12-03 22:18:41 +0000528/// the result will look like in the destination module. In particular, it
Rafael Espindola23f8d642012-01-05 23:02:01 +0000529/// computes the resultant linkage type and visibility, computes whether the
530/// global in the source should be copied over to the destination (replacing
531/// the existing one), and computes whether this linkage is an error or not.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000532bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Rafael Espindola23f8d642012-01-05 23:02:01 +0000533 GlobalValue::LinkageTypes &LT,
534 GlobalValue::VisibilityTypes &Vis,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000535 bool &LinkFromSrc) {
536 assert(Dest && "Must have two globals being queried");
537 assert(!Src->hasLocalLinkage() &&
Chris Lattnerfc61de32004-12-03 22:18:41 +0000538 "If Src has internal linkage, Dest shouldn't be set!");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000539
Peter Collingbourne8bb15d82011-10-30 17:46:34 +0000540 bool SrcIsDeclaration = Src->isDeclaration() && !Src->isMaterializable();
Chris Lattner0c134b52011-07-14 20:23:05 +0000541 bool DestIsDeclaration = Dest->isDeclaration();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000542
543 if (SrcIsDeclaration) {
Anton Korobeynikov1f93c502008-03-10 22:33:22 +0000544 // If Src is external or if both Src & Dest are external.. Just link the
Chris Lattnerfc61de32004-12-03 22:18:41 +0000545 // external globals, we aren't adding anything.
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +0000546 if (Src->hasDLLImportLinkage()) {
Anton Korobeynikov12c94942006-12-01 00:25:12 +0000547 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000548 if (DestIsDeclaration) {
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +0000549 LinkFromSrc = true;
550 LT = Src->getLinkage();
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000551 }
Andrew Lenharthe06036d2006-12-15 17:35:32 +0000552 } else if (Dest->hasExternalWeakLinkage()) {
Duncan Sands12da8ce2009-03-07 15:45:40 +0000553 // If the Dest is weak, use the source linkage.
Andrew Lenharthe06036d2006-12-15 17:35:32 +0000554 LinkFromSrc = true;
555 LT = Src->getLinkage();
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +0000556 } else {
557 LinkFromSrc = false;
558 LT = Dest->getLinkage();
559 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000560 } else if (DestIsDeclaration && !Dest->hasDLLImportLinkage()) {
Chris Lattnerfc61de32004-12-03 22:18:41 +0000561 // If Dest is external but Src is not:
562 LinkFromSrc = true;
563 LT = Src->getLinkage();
Duncan Sandsd725c992009-03-08 13:35:23 +0000564 } else if (Src->isWeakForLinker()) {
Dale Johannesence4396b2008-05-14 20:12:51 +0000565 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
566 // or DLL* linkage.
Chris Lattner184f1be2009-04-13 05:44:34 +0000567 if (Dest->hasExternalWeakLinkage() ||
568 Dest->hasAvailableExternallyLinkage() ||
569 (Dest->hasLinkOnceLinkage() &&
570 (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
Chris Lattnerfc61de32004-12-03 22:18:41 +0000571 LinkFromSrc = true;
572 LT = Src->getLinkage();
573 } else {
574 LinkFromSrc = false;
575 LT = Dest->getLinkage();
576 }
Duncan Sandsd725c992009-03-08 13:35:23 +0000577 } else if (Dest->isWeakForLinker()) {
Anton Korobeynikov12c94942006-12-01 00:25:12 +0000578 // At this point we know that Src has External* or DLL* linkage.
579 if (Src->hasExternalWeakLinkage()) {
580 LinkFromSrc = false;
581 LT = Dest->getLinkage();
582 } else {
583 LinkFromSrc = true;
584 LT = GlobalValue::ExternalLinkage;
585 }
Chris Lattnerfc61de32004-12-03 22:18:41 +0000586 } else {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000587 assert((Dest->hasExternalLinkage() || Dest->hasDLLImportLinkage() ||
588 Dest->hasDLLExportLinkage() || Dest->hasExternalWeakLinkage()) &&
589 (Src->hasExternalLinkage() || Src->hasDLLImportLinkage() ||
590 Src->hasDLLExportLinkage() || Src->hasExternalWeakLinkage()) &&
Chris Lattnerfc61de32004-12-03 22:18:41 +0000591 "Unexpected linkage type!");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000592 return emitError("Linking globals named '" + Src->getName() +
Chris Lattnerfc61de32004-12-03 22:18:41 +0000593 "': symbol multiply defined!");
594 }
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000595
Rafael Espindola23f8d642012-01-05 23:02:01 +0000596 // Compute the visibility. We follow the rules in the System V Application
597 // Binary Interface.
598 Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
599 Dest->getVisibility() : Src->getVisibility();
Chris Lattnerfc61de32004-12-03 22:18:41 +0000600 return false;
601}
Reid Spencer361e5132004-11-12 20:37:43 +0000602
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000603/// computeTypeMapping - Loop over all of the linked values to compute type
604/// mappings. For example, if we link "extern Foo *x" and "Foo *x = NULL", then
605/// we have two struct types 'Foo' but one got renamed when the module was
606/// loaded into the same LLVMContext.
607void ModuleLinker::computeTypeMapping() {
608 // Incorporate globals.
609 for (Module::global_iterator I = SrcM->global_begin(),
610 E = SrcM->global_end(); I != E; ++I) {
611 GlobalValue *DGV = getLinkedToGlobal(I);
612 if (DGV == 0) continue;
613
614 if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
615 TypeMap.addTypeMapping(DGV->getType(), I->getType());
616 continue;
617 }
618
619 // Unify the element type of appending arrays.
620 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
621 ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
622 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
Devang Patel5c310be2009-08-11 18:01:24 +0000623 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000624
625 // Incorporate functions.
626 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
627 if (GlobalValue *DGV = getLinkedToGlobal(I))
628 TypeMap.addTypeMapping(DGV->getType(), I->getType());
629 }
Bill Wendling7b464612012-02-27 22:34:19 +0000630
Bill Wendlingd48b7782012-02-28 04:01:21 +0000631 // Incorporate types by name, scanning all the types in the source module.
632 // At this point, the destination module may have a type "%foo = { i32 }" for
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000633 // example. When the source module got loaded into the same LLVMContext, if
634 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
Bill Wendling8555a372012-08-03 00:30:35 +0000635 TypeFinder SrcStructTypes;
636 SrcStructTypes.run(*SrcM, true);
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000637 SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
638 SrcStructTypes.end());
Bill Wendling87374802012-03-23 23:17:38 +0000639
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000640 for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
641 StructType *ST = SrcStructTypes[i];
642 if (!ST->hasName()) continue;
643
644 // Check to see if there is a dot in the name followed by a digit.
Bill Wendlingd48b7782012-02-28 04:01:21 +0000645 size_t DotPos = ST->getName().rfind('.');
646 if (DotPos == 0 || DotPos == StringRef::npos ||
Guy Benyei83c74e92013-02-12 21:21:59 +0000647 ST->getName().back() == '.' ||
648 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
Bill Wendlingd48b7782012-02-28 04:01:21 +0000649 continue;
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000650
651 // Check to see if the destination module has a struct with the prefix name.
Bill Wendlingd48b7782012-02-28 04:01:21 +0000652 if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
Bill Wendling87374802012-03-23 23:17:38 +0000653 // Don't use it if this actually came from the source module. They're in
654 // the same LLVMContext after all. Also don't use it unless the type is
655 // actually used in the destination module. This can happen in situations
656 // like this:
657 //
658 // Module A Module B
659 // -------- --------
660 // %Z = type { %A } %B = type { %C.1 }
661 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
662 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
663 // %C = type { i8* } %B.3 = type { %C.1 }
664 //
665 // When we link Module B with Module A, the '%B' in Module B is
666 // used. However, that would then use '%C.1'. But when we process '%C.1',
667 // we prefer to take the '%C' version. So we are then left with both
668 // '%C.1' and '%C' being used for the same types. This leads to some
669 // variables using one type and some using the other.
Rafael Espindolaaa9918a2013-05-04 05:05:18 +0000670 if (!SrcStructTypesSet.count(DST) && TypeMap.DstStructTypesSet.count(DST))
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000671 TypeMap.addTypeMapping(DST, ST);
672 }
673
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000674 // Don't bother incorporating aliases, they aren't generally typed well.
Bill Wendlingd48b7782012-02-28 04:01:21 +0000675
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000676 // Now that we have discovered all of the type equivalences, get a body for
677 // any 'opaque' types in the dest module that are now resolved.
678 TypeMap.linkDefinedTypeBodies();
Devang Patel5c310be2009-08-11 18:01:24 +0000679}
680
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000681/// linkAppendingVarProto - If there were any appending global variables, link
682/// them together now. Return true on error.
683bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
684 GlobalVariable *SrcGV) {
Bill Wendlingd48b7782012-02-28 04:01:21 +0000685
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000686 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
687 return emitError("Linking globals named '" + SrcGV->getName() +
688 "': can only link appending global with another appending global!");
689
690 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
691 ArrayType *SrcTy =
692 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
693 Type *EltTy = DstTy->getElementType();
694
695 // Check to see that they two arrays agree on type.
696 if (EltTy != SrcTy->getElementType())
697 return emitError("Appending variables with different element types!");
698 if (DstGV->isConstant() != SrcGV->isConstant())
699 return emitError("Appending variables linked with different const'ness!");
700
701 if (DstGV->getAlignment() != SrcGV->getAlignment())
702 return emitError(
703 "Appending variables with different alignment need to be linked!");
704
705 if (DstGV->getVisibility() != SrcGV->getVisibility())
706 return emitError(
707 "Appending variables with different visibility need to be linked!");
Rafael Espindolafac3a012013-09-04 15:33:34 +0000708
709 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
710 return emitError(
711 "Appending variables with different unnamed_addr need to be linked!");
712
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000713 if (DstGV->getSection() != SrcGV->getSection())
714 return emitError(
715 "Appending variables with different section name need to be linked!");
716
717 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
718 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
719
720 // Create the new global variable.
721 GlobalVariable *NG =
722 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
723 DstGV->getLinkage(), /*init*/0, /*name*/"", DstGV,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000724 DstGV->getThreadLocalMode(),
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000725 DstGV->getType()->getAddressSpace());
726
727 // Propagate alignment, visibility and section info.
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000728 copyGVAttributes(NG, DstGV);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000729
730 AppendingVarInfo AVI;
731 AVI.NewGV = NG;
732 AVI.DstInit = DstGV->getInitializer();
733 AVI.SrcInit = SrcGV->getInitializer();
734 AppendingVars.push_back(AVI);
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000735
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000736 // Replace any uses of the two global variables with uses of the new
737 // global.
738 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
Anton Korobeynikove79f4c72008-03-10 22:34:28 +0000739
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000740 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
741 DstGV->eraseFromParent();
742
Tanya Lattnercbb91402011-10-11 00:24:54 +0000743 // Track the source variable so we don't try to link it.
744 DoNotLinkFromSource.insert(SrcGV);
745
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000746 return false;
747}
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000748
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000749/// linkGlobalProto - Loop through the global variables in the src module and
750/// merge them into the dest module.
751bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
752 GlobalValue *DGV = getLinkedToGlobal(SGV);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000753 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Rafael Espindolad4885da2013-09-04 14:05:09 +0000754 bool HasUnnamedAddr = SGV->hasUnnamedAddr();
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000755
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000756 if (DGV) {
757 // Concatenation of appending linkage variables is magic and handled later.
758 if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
759 return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
760
761 // Determine whether linkage of these two globals follows the source
762 // module's definition or the destination module's definition.
Chris Lattner1b9633d2006-11-09 05:18:12 +0000763 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
Rafael Espindola23f8d642012-01-05 23:02:01 +0000764 GlobalValue::VisibilityTypes NV;
Chris Lattner1b9633d2006-11-09 05:18:12 +0000765 bool LinkFromSrc = false;
Rafael Espindola23f8d642012-01-05 23:02:01 +0000766 if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
Chris Lattnerfc61de32004-12-03 22:18:41 +0000767 return true;
Rafael Espindola23f8d642012-01-05 23:02:01 +0000768 NewVisibility = NV;
Rafael Espindolafd9a9412013-09-04 14:59:03 +0000769 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
Reid Spencer361e5132004-11-12 20:37:43 +0000770
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000771 // If we're not linking from the source, then keep the definition that we
772 // have.
773 if (!LinkFromSrc) {
774 // Special case for const propagation.
775 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
776 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
777 DGVar->setConstant(true);
Rafael Espindolad4885da2013-09-04 14:05:09 +0000778
779 // Set calculated linkage, visibility and unnamed_addr.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000780 DGV->setLinkage(NewLinkage);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000781 DGV->setVisibility(*NewVisibility);
Rafael Espindolad4885da2013-09-04 14:05:09 +0000782 DGV->setUnnamedAddr(HasUnnamedAddr);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000783
Chris Lattner0ead7a52008-07-14 07:23:24 +0000784 // Make sure to remember this mapping.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000785 ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
786
Tanya Lattnercbb91402011-10-11 00:24:54 +0000787 // Track the source global so that we don't attempt to copy it over when
788 // processing global initializers.
789 DoNotLinkFromSource.insert(SGV);
790
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000791 return false;
Chris Lattner0ead7a52008-07-14 07:23:24 +0000792 }
Reid Spencer361e5132004-11-12 20:37:43 +0000793 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000794
795 // No linking to be performed or linking from the source: simply create an
796 // identical version of the symbol over in the dest module... the
797 // initializer will be filled in later by LinkGlobalInits.
798 GlobalVariable *NewDGV =
799 new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
800 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
801 SGV->getName(), /*insertbefore*/0,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000802 SGV->getThreadLocalMode(),
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000803 SGV->getType()->getAddressSpace());
804 // Propagate alignment, visibility and section info.
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000805 copyGVAttributes(NewDGV, SGV);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000806 if (NewVisibility)
807 NewDGV->setVisibility(*NewVisibility);
Rafael Espindolad4885da2013-09-04 14:05:09 +0000808 NewDGV->setUnnamedAddr(HasUnnamedAddr);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000809
810 if (DGV) {
811 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
812 DGV->eraseFromParent();
813 }
814
815 // Make sure to remember this mapping.
816 ValueMap[SGV] = NewDGV;
Reid Spencer361e5132004-11-12 20:37:43 +0000817 return false;
818}
819
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000820/// linkFunctionProto - Link the function in the source module into the
821/// destination module if needed, setting up mapping information.
822bool ModuleLinker::linkFunctionProto(Function *SF) {
823 GlobalValue *DGV = getLinkedToGlobal(SF);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000824 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Rafael Espindolafd9a9412013-09-04 14:59:03 +0000825 bool HasUnnamedAddr = SF->hasUnnamedAddr();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000826
827 if (DGV) {
828 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
829 bool LinkFromSrc = false;
Rafael Espindola23f8d642012-01-05 23:02:01 +0000830 GlobalValue::VisibilityTypes NV;
831 if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000832 return true;
Rafael Espindola23f8d642012-01-05 23:02:01 +0000833 NewVisibility = NV;
Rafael Espindolafd9a9412013-09-04 14:59:03 +0000834 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
Rafael Espindola23f8d642012-01-05 23:02:01 +0000835
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000836 if (!LinkFromSrc) {
837 // Set calculated linkage
838 DGV->setLinkage(NewLinkage);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000839 DGV->setVisibility(*NewVisibility);
Rafael Espindolafd9a9412013-09-04 14:59:03 +0000840 DGV->setUnnamedAddr(HasUnnamedAddr);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000841
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000842 // Make sure to remember this mapping.
843 ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
844
Tanya Lattnercbb91402011-10-11 00:24:54 +0000845 // Track the function from the source module so we don't attempt to remap
846 // it.
847 DoNotLinkFromSource.insert(SF);
848
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000849 return false;
850 }
Anton Korobeynikovdac5fa92008-03-05 22:22:46 +0000851 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000852
James Molloyf6f121e2013-05-28 15:17:05 +0000853 // If the function is to be lazily linked, don't create it just yet.
854 // The ValueMaterializerTy will deal with creating it if it's used.
855 if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
856 SF->hasAvailableExternallyLinkage())) {
857 DoNotLinkFromSource.insert(SF);
858 return false;
859 }
860
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000861 // If there is no linkage to be performed or we are linking from the source,
862 // bring SF over.
863 Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
864 SF->getLinkage(), SF->getName(), DstM);
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000865 copyGVAttributes(NewDF, SF);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000866 if (NewVisibility)
867 NewDF->setVisibility(*NewVisibility);
Rafael Espindolafd9a9412013-09-04 14:59:03 +0000868 NewDF->setUnnamedAddr(HasUnnamedAddr);
Anton Korobeynikovdac5fa92008-03-05 22:22:46 +0000869
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000870 if (DGV) {
871 // Any uses of DF need to change to NewDF, with cast.
872 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
873 DGV->eraseFromParent();
Lauro Ramos Venanciob00c9c02007-06-28 19:02:54 +0000874 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000875
876 ValueMap[SF] = NewDF;
Lauro Ramos Venanciob00c9c02007-06-28 19:02:54 +0000877 return false;
878}
879
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000880/// LinkAliasProto - Set up prototypes for any aliases that come over from the
881/// source module.
882bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
883 GlobalValue *DGV = getLinkedToGlobal(SGA);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000884 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
885
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000886 if (DGV) {
887 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
Rafael Espindola23f8d642012-01-05 23:02:01 +0000888 GlobalValue::VisibilityTypes NV;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000889 bool LinkFromSrc = false;
Rafael Espindola23f8d642012-01-05 23:02:01 +0000890 if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000891 return true;
Rafael Espindola23f8d642012-01-05 23:02:01 +0000892 NewVisibility = NV;
893
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000894 if (!LinkFromSrc) {
895 // Set calculated linkage.
896 DGV->setLinkage(NewLinkage);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000897 DGV->setVisibility(*NewVisibility);
898
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000899 // Make sure to remember this mapping.
900 ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
901
Tanya Lattnercbb91402011-10-11 00:24:54 +0000902 // Track the alias from the source module so we don't attempt to remap it.
903 DoNotLinkFromSource.insert(SGA);
904
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000905 return false;
906 }
907 }
908
909 // If there is no linkage to be performed or we're linking from the source,
910 // bring over SGA.
911 GlobalAlias *NewDA = new GlobalAlias(TypeMap.get(SGA->getType()),
912 SGA->getLinkage(), SGA->getName(),
913 /*aliasee*/0, DstM);
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000914 copyGVAttributes(NewDA, SGA);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000915 if (NewVisibility)
916 NewDA->setVisibility(*NewVisibility);
Reid Spencer361e5132004-11-12 20:37:43 +0000917
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000918 if (DGV) {
919 // Any uses of DGV need to change to NewDA, with cast.
920 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
921 DGV->eraseFromParent();
922 }
923
924 ValueMap[SGA] = NewDA;
925 return false;
926}
927
Chris Lattner00245f42012-01-24 13:41:11 +0000928static void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest) {
Chris Lattner67058832012-01-25 06:48:06 +0000929 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
930
931 for (unsigned i = 0; i != NumElements; ++i)
932 Dest.push_back(C->getAggregateElement(i));
Chris Lattner00245f42012-01-24 13:41:11 +0000933}
934
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000935void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
936 // Merge the initializer.
937 SmallVector<Constant*, 16> Elements;
Chris Lattner00245f42012-01-24 13:41:11 +0000938 getArrayElements(AVI.DstInit, Elements);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000939
James Molloyf6f121e2013-05-28 15:17:05 +0000940 Constant *SrcInit = MapValue(AVI.SrcInit, ValueMap, RF_None, &TypeMap, &ValMaterializer);
Chris Lattner00245f42012-01-24 13:41:11 +0000941 getArrayElements(SrcInit, Elements);
942
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000943 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
944 AVI.NewGV->setInitializer(ConstantArray::get(NewType, Elements));
945}
946
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000947/// linkGlobalInits - Update the initializers in the Dest module now that all
948/// globals that may be referenced are in Dest.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000949void ModuleLinker::linkGlobalInits() {
Reid Spencer361e5132004-11-12 20:37:43 +0000950 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000951 for (Module::const_global_iterator I = SrcM->global_begin(),
952 E = SrcM->global_end(); I != E; ++I) {
Tanya Lattnercbb91402011-10-11 00:24:54 +0000953
954 // Only process initialized GV's or ones not already in dest.
955 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000956
957 // Grab destination global variable.
958 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
959 // Figure out what the initializer looks like in the dest module.
960 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
James Molloyf6f121e2013-05-28 15:17:05 +0000961 RF_None, &TypeMap, &ValMaterializer));
Reid Spencer361e5132004-11-12 20:37:43 +0000962 }
Reid Spencer361e5132004-11-12 20:37:43 +0000963}
964
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000965/// linkFunctionBody - Copy the source function over into the dest function and
966/// fix up references to values. At this point we know that Dest is an external
967/// function, and that Src is not.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000968void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
969 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
Reid Spencer361e5132004-11-12 20:37:43 +0000970
Chris Lattner7391dde2004-11-16 17:12:38 +0000971 // Go through and convert function arguments over, remembering the mapping.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000972 Function::arg_iterator DI = Dst->arg_begin();
Chris Lattner531f9e92005-03-15 04:54:21 +0000973 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
Reid Spencer361e5132004-11-12 20:37:43 +0000974 I != E; ++I, ++DI) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000975 DI->setName(I->getName()); // Copy the name over.
Reid Spencer361e5132004-11-12 20:37:43 +0000976
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000977 // Add a mapping to our mapping.
Anton Korobeynikov66a62712008-03-10 22:36:08 +0000978 ValueMap[I] = DI;
Reid Spencer361e5132004-11-12 20:37:43 +0000979 }
980
Tanya Lattnercbb91402011-10-11 00:24:54 +0000981 if (Mode == Linker::DestroySource) {
982 // Splice the body of the source function into the dest function.
983 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
984
985 // At this point, all of the instructions and values of the function are now
986 // copied over. The only problem is that they are still referencing values in
987 // the Source function as operands. Loop through all of the operands of the
988 // functions and patch them up to point to the local versions.
989 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
990 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
James Molloyf6f121e2013-05-28 15:17:05 +0000991 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries,
992 &TypeMap, &ValMaterializer);
Tanya Lattnercbb91402011-10-11 00:24:54 +0000993
994 } else {
995 // Clone the body of the function into the dest function.
996 SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
James Molloyf6f121e2013-05-28 15:17:05 +0000997 CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", NULL,
998 &TypeMap, &ValMaterializer);
Tanya Lattnercbb91402011-10-11 00:24:54 +0000999 }
1000
Chris Lattner7391dde2004-11-16 17:12:38 +00001001 // There is no need to map the arguments anymore.
Chris Lattner44ab8ae2006-06-16 01:24:04 +00001002 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1003 I != E; ++I)
Reid Spencer3aaaa0b2007-02-05 20:47:22 +00001004 ValueMap.erase(I);
Tanya Lattnercbb91402011-10-11 00:24:54 +00001005
Reid Spencer361e5132004-11-12 20:37:43 +00001006}
1007
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001008/// linkAliasBodies - Insert all of the aliases in Src into the Dest module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001009void ModuleLinker::linkAliasBodies() {
1010 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
Tanya Lattnercbb91402011-10-11 00:24:54 +00001011 I != E; ++I) {
1012 if (DoNotLinkFromSource.count(I))
1013 continue;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001014 if (Constant *Aliasee = I->getAliasee()) {
1015 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
James Molloyf6f121e2013-05-28 15:17:05 +00001016 DA->setAliasee(MapValue(Aliasee, ValueMap, RF_None,
1017 &TypeMap, &ValMaterializer));
David Chisnall2c4a34a2010-01-09 16:27:31 +00001018 }
Tanya Lattnercbb91402011-10-11 00:24:54 +00001019 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001020}
Anton Korobeynikov26098882008-03-05 23:21:39 +00001021
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001022/// linkNamedMDNodes - Insert all of the named MDNodes in Src into the Dest
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001023/// module.
1024void ModuleLinker::linkNamedMDNodes() {
Bill Wendling66f02412012-02-11 11:38:06 +00001025 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001026 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1027 E = SrcM->named_metadata_end(); I != E; ++I) {
Bill Wendling66f02412012-02-11 11:38:06 +00001028 // Don't link module flags here. Do them separately.
1029 if (&*I == SrcModFlags) continue;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001030 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1031 // Add Src elements into Dest node.
1032 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1033 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
James Molloyf6f121e2013-05-28 15:17:05 +00001034 RF_None, &TypeMap, &ValMaterializer));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001035 }
1036}
Bill Wendling66f02412012-02-11 11:38:06 +00001037
Bill Wendling66f02412012-02-11 11:38:06 +00001038/// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest
1039/// module.
1040bool ModuleLinker::linkModuleFlagsMetadata() {
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001041 // If the source module has no module flags, we are done.
Bill Wendling66f02412012-02-11 11:38:06 +00001042 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1043 if (!SrcModFlags) return false;
1044
Bill Wendling66f02412012-02-11 11:38:06 +00001045 // If the destination module doesn't have module flags yet, then just copy
1046 // over the source module's flags.
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001047 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
Bill Wendling66f02412012-02-11 11:38:06 +00001048 if (DstModFlags->getNumOperands() == 0) {
1049 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1050 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1051
1052 return false;
1053 }
1054
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001055 // First build a map of the existing module flags and requirements.
1056 DenseMap<MDString*, MDNode*> Flags;
1057 SmallSetVector<MDNode*, 16> Requirements;
1058 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1059 MDNode *Op = DstModFlags->getOperand(I);
1060 ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1061 MDString *ID = cast<MDString>(Op->getOperand(1));
Bill Wendling66f02412012-02-11 11:38:06 +00001062
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001063 if (Behavior->getZExtValue() == Module::Require) {
1064 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1065 } else {
1066 Flags[ID] = Op;
1067 }
Bill Wendling66f02412012-02-11 11:38:06 +00001068 }
1069
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001070 // Merge in the flags from the source module, and also collect its set of
1071 // requirements.
1072 bool HasErr = false;
1073 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1074 MDNode *SrcOp = SrcModFlags->getOperand(I);
1075 ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1076 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1077 MDNode *DstOp = Flags.lookup(ID);
1078 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
Bill Wendling66f02412012-02-11 11:38:06 +00001079
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001080 // If this is a requirement, add it and continue.
1081 if (SrcBehaviorValue == Module::Require) {
1082 // If the destination module does not already have this requirement, add
1083 // it.
1084 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1085 DstModFlags->addOperand(SrcOp);
1086 }
1087 continue;
Bill Wendling66f02412012-02-11 11:38:06 +00001088 }
1089
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001090 // If there is no existing flag with this ID, just add it.
1091 if (!DstOp) {
1092 Flags[ID] = SrcOp;
1093 DstModFlags->addOperand(SrcOp);
1094 continue;
1095 }
1096
1097 // Otherwise, perform a merge.
1098 ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1099 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1100
1101 // If either flag has override behavior, handle it first.
1102 if (DstBehaviorValue == Module::Override) {
1103 // Diagnose inconsistent flags which both have override behavior.
1104 if (SrcBehaviorValue == Module::Override &&
1105 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1106 HasErr |= emitError("linking module flags '" + ID->getString() +
1107 "': IDs have conflicting override values");
1108 }
1109 continue;
1110 } else if (SrcBehaviorValue == Module::Override) {
1111 // Update the destination flag to that of the source.
1112 DstOp->replaceOperandWith(0, SrcBehavior);
1113 DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1114 continue;
1115 }
1116
1117 // Diagnose inconsistent merge behavior types.
1118 if (SrcBehaviorValue != DstBehaviorValue) {
1119 HasErr |= emitError("linking module flags '" + ID->getString() +
1120 "': IDs have conflicting behaviors");
1121 continue;
1122 }
1123
1124 // Perform the merge for standard behavior types.
1125 switch (SrcBehaviorValue) {
1126 case Module::Require:
1127 case Module::Override: assert(0 && "not possible"); break;
1128 case Module::Error: {
1129 // Emit an error if the values differ.
1130 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1131 HasErr |= emitError("linking module flags '" + ID->getString() +
1132 "': IDs have conflicting values");
1133 }
1134 continue;
1135 }
1136 case Module::Warning: {
1137 // Emit a warning if the values differ.
1138 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1139 errs() << "WARNING: linking module flags '" << ID->getString()
1140 << "': IDs have conflicting values";
1141 }
1142 continue;
1143 }
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001144 case Module::Append: {
1145 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1146 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1147 unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1148 Value **VP, **Values = VP = new Value*[NumOps];
1149 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1150 *VP = DstValue->getOperand(i);
1151 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1152 *VP = SrcValue->getOperand(i);
1153 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1154 ArrayRef<Value*>(Values,
1155 NumOps)));
1156 delete[] Values;
1157 break;
1158 }
1159 case Module::AppendUnique: {
1160 SmallSetVector<Value*, 16> Elts;
1161 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1162 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1163 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1164 Elts.insert(DstValue->getOperand(i));
1165 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1166 Elts.insert(SrcValue->getOperand(i));
1167 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1168 ArrayRef<Value*>(Elts.begin(),
1169 Elts.end())));
1170 break;
1171 }
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001172 }
Bill Wendling66f02412012-02-11 11:38:06 +00001173 }
1174
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001175 // Check all of the requirements.
1176 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1177 MDNode *Requirement = Requirements[I];
1178 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1179 Value *ReqValue = Requirement->getOperand(1);
Bill Wendling66f02412012-02-11 11:38:06 +00001180
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001181 MDNode *Op = Flags[Flag];
1182 if (!Op || Op->getOperand(2) != ReqValue) {
1183 HasErr |= emitError("linking module flags '" + Flag->getString() +
1184 "': does not have the required value");
1185 continue;
Bill Wendling66f02412012-02-11 11:38:06 +00001186 }
1187 }
1188
1189 return HasErr;
1190}
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001191
1192bool ModuleLinker::run() {
Bill Wendling66f02412012-02-11 11:38:06 +00001193 assert(DstM && "Null destination module");
1194 assert(SrcM && "Null source module");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001195
1196 // Inherit the target data from the source module if the destination module
1197 // doesn't have one already.
1198 if (DstM->getDataLayout().empty() && !SrcM->getDataLayout().empty())
1199 DstM->setDataLayout(SrcM->getDataLayout());
1200
1201 // Copy the target triple from the source to dest if the dest's is empty.
1202 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1203 DstM->setTargetTriple(SrcM->getTargetTriple());
1204
1205 if (!SrcM->getDataLayout().empty() && !DstM->getDataLayout().empty() &&
1206 SrcM->getDataLayout() != DstM->getDataLayout())
1207 errs() << "WARNING: Linking two modules of different data layouts!\n";
1208 if (!SrcM->getTargetTriple().empty() &&
1209 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1210 errs() << "WARNING: Linking two modules of different target triples: ";
1211 if (!SrcM->getModuleIdentifier().empty())
1212 errs() << SrcM->getModuleIdentifier() << ": ";
1213 errs() << "'" << SrcM->getTargetTriple() << "' and '"
1214 << DstM->getTargetTriple() << "'\n";
1215 }
1216
1217 // Append the module inline asm string.
1218 if (!SrcM->getModuleInlineAsm().empty()) {
1219 if (DstM->getModuleInlineAsm().empty())
1220 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1221 else
1222 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1223 SrcM->getModuleInlineAsm());
1224 }
1225
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001226 // Loop over all of the linked values to compute type mappings.
1227 computeTypeMapping();
1228
1229 // Insert all of the globals in src into the DstM module... without linking
1230 // initializers (which could refer to functions not yet mapped over).
1231 for (Module::global_iterator I = SrcM->global_begin(),
1232 E = SrcM->global_end(); I != E; ++I)
1233 if (linkGlobalProto(I))
1234 return true;
1235
1236 // Link the functions together between the two modules, without doing function
1237 // bodies... this just adds external function prototypes to the DstM
1238 // function... We do this so that when we begin processing function bodies,
1239 // all of the global values that may be referenced are available in our
1240 // ValueMap.
1241 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1242 if (linkFunctionProto(I))
1243 return true;
1244
1245 // If there were any aliases, link them now.
1246 for (Module::alias_iterator I = SrcM->alias_begin(),
1247 E = SrcM->alias_end(); I != E; ++I)
1248 if (linkAliasProto(I))
1249 return true;
1250
1251 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1252 linkAppendingVarInit(AppendingVars[i]);
1253
Adrian Prantla473a2b2013-11-09 00:43:18 +00001254 // Update the initializers in the DstM module now that all globals that may
1255 // be referenced are in DstM.
1256 linkGlobalInits();
1257
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001258 // Link in the function bodies that are defined in the source module into
1259 // DstM.
1260 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
Tanya Lattnerea166d42011-10-14 22:17:46 +00001261 // Skip if not linking from source.
1262 if (DoNotLinkFromSource.count(SF)) continue;
1263
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001264 Function *DF = cast<Function>(ValueMap[SF]);
1265 if (SF->hasPrefixData()) {
1266 // Link in the prefix data.
1267 DF->setPrefixData(MapValue(
1268 SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
1269 }
1270
Tanya Lattnerea166d42011-10-14 22:17:46 +00001271 // Skip if no body (function is external) or materialize.
1272 if (SF->isDeclaration()) {
1273 if (!SF->isMaterializable())
1274 continue;
1275 if (SF->Materialize(&ErrorMsg))
1276 return true;
1277 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001278
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001279 linkFunctionBody(DF, SF);
Bill Wendling00623782012-03-23 07:22:49 +00001280 SF->Dematerialize();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001281 }
1282
1283 // Resolve all uses of aliases with aliasees.
1284 linkAliasBodies();
1285
Bill Wendling66f02412012-02-11 11:38:06 +00001286 // Remap all of the named MDNodes in Src into the DstM module. We do this
Devang Patel6ddbb2e2011-08-04 19:44:28 +00001287 // after linking GlobalValues so that MDNodes that reference GlobalValues
1288 // are properly remapped.
1289 linkNamedMDNodes();
1290
Bill Wendling66f02412012-02-11 11:38:06 +00001291 // Merge the module flags into the DstM module.
1292 if (linkModuleFlagsMetadata())
1293 return true;
1294
Tanya Lattner0a48b872011-11-02 00:24:56 +00001295 // Process vector of lazily linked in functions.
1296 bool LinkedInAnyFunctions;
1297 do {
1298 LinkedInAnyFunctions = false;
1299
Bill Wendlingfa2287822013-03-27 17:54:41 +00001300 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
James Molloyf6f121e2013-05-28 15:17:05 +00001301 E = LazilyLinkFunctions.end(); I != E; ++I) {
Bill Wendlingfa2287822013-03-27 17:54:41 +00001302 Function *SF = *I;
James Molloyf6f121e2013-05-28 15:17:05 +00001303 if (!SF)
1304 continue;
Bill Wendling00623782012-03-23 07:22:49 +00001305
James Molloyf6f121e2013-05-28 15:17:05 +00001306 Function *DF = cast<Function>(ValueMap[SF]);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001307 if (SF->hasPrefixData()) {
1308 // Link in the prefix data.
1309 DF->setPrefixData(MapValue(SF->getPrefixData(),
1310 ValueMap,
1311 RF_None,
1312 &TypeMap,
1313 &ValMaterializer));
1314 }
James Molloyf6f121e2013-05-28 15:17:05 +00001315
1316 // Materialize if necessary.
1317 if (SF->isDeclaration()) {
1318 if (!SF->isMaterializable())
1319 continue;
1320 if (SF->Materialize(&ErrorMsg))
1321 return true;
Tanya Lattner0a48b872011-11-02 00:24:56 +00001322 }
James Molloyf6f121e2013-05-28 15:17:05 +00001323
1324 // Erase from vector *before* the function body is linked - linkFunctionBody could
1325 // invalidate I.
1326 LazilyLinkFunctions.erase(I);
1327
1328 // Link in function body.
1329 linkFunctionBody(DF, SF);
1330 SF->Dematerialize();
1331
1332 // Set flag to indicate we may have more functions to lazily link in
1333 // since we linked in a function.
1334 LinkedInAnyFunctions = true;
1335 break;
Tanya Lattner0a48b872011-11-02 00:24:56 +00001336 }
1337 } while (LinkedInAnyFunctions);
1338
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001339 // Now that all of the types from the source are used, resolve any structs
1340 // copied over to the dest that didn't exist there.
1341 TypeMap.linkDefinedTypeBodies();
1342
Anton Korobeynikov26098882008-03-05 23:21:39 +00001343 return false;
1344}
Reid Spencer361e5132004-11-12 20:37:43 +00001345
Rafael Espindolaaa9918a2013-05-04 05:05:18 +00001346Linker::Linker(Module *M) : Composite(M) {
1347 TypeFinder StructTypes;
1348 StructTypes.run(*M, true);
1349 IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end());
1350}
Rafael Espindola3df61b72013-05-04 03:48:37 +00001351
1352Linker::~Linker() {
1353}
1354
Bill Wendling91e6f6e2013-10-16 08:59:57 +00001355void Linker::deleteModule() {
1356 delete Composite;
1357 Composite = NULL;
1358}
1359
Rafael Espindola3df61b72013-05-04 03:48:37 +00001360bool Linker::linkInModule(Module *Src, unsigned Mode, std::string *ErrorMsg) {
Rafael Espindolaaa9918a2013-05-04 05:05:18 +00001361 ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src, Mode);
Rafael Espindola287f18b2013-05-04 04:08:02 +00001362 if (TheLinker.run()) {
1363 if (ErrorMsg)
1364 *ErrorMsg = TheLinker.ErrorMsg;
1365 return true;
1366 }
1367 return false;
Rafael Espindola3df61b72013-05-04 03:48:37 +00001368}
1369
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001370//===----------------------------------------------------------------------===//
1371// LinkModules entrypoint.
1372//===----------------------------------------------------------------------===//
1373
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001374/// LinkModules - This function links two modules together, with the resulting
Eli Bendersky970cc632013-03-08 22:29:44 +00001375/// Dest module modified to be the composite of the two input modules. If an
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001376/// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1377/// the problem. Upon failure, the Dest module could be in a modified state,
1378/// and shouldn't be relied on to be consistent.
Tanya Lattnercbb91402011-10-11 00:24:54 +00001379bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode,
1380 std::string *ErrorMsg) {
Rafael Espindola287f18b2013-05-04 04:08:02 +00001381 Linker L(Dest);
1382 return L.linkInModule(Src, Mode, ErrorMsg);
Reid Spencer361e5132004-11-12 20:37:43 +00001383}
Bill Wendlinga3aeb982012-05-09 08:55:40 +00001384
1385//===----------------------------------------------------------------------===//
1386// C API.
1387//===----------------------------------------------------------------------===//
1388
1389LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1390 LLVMLinkerMode Mode, char **OutMessages) {
1391 std::string Messages;
1392 LLVMBool Result = Linker::LinkModules(unwrap(Dest), unwrap(Src),
1393 Mode, OutMessages? &Messages : 0);
1394 if (OutMessages)
1395 *OutMessages = strdup(Messages.c_str());
1396 return Result;
1397}