blob: c3bcbcf8f35b6a5cc1ff3e7c73a603ca3ce3a2ab [file] [log] [blame]
Mikhail Glushenkovc834bbf2009-03-03 10:04:23 +00001//===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
Misha Brukmanf976c852005-04-21 22:55:34 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Brukmanf976c852005-04-21 22:55:34 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner52f7e902001-10-13 07:03:50 +00009//
10// This file implements the LLVM module linker.
11//
Chris Lattner52f7e902001-10-13 07:03:50 +000012//===----------------------------------------------------------------------===//
13
Reid Spencer7cc371a2004-11-14 23:27:04 +000014#include "llvm/Linker.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000015#include "llvm-c/Linker.h"
Rafael Espindola3ed88152012-01-05 23:02:01 +000016#include "llvm/ADT/Optional.h"
Bill Wendlingd34cb1e2012-02-11 11:38:06 +000017#include "llvm/ADT/SetVector.h"
Eli Bendersky58890d52013-03-19 15:26:24 +000018#include "llvm/ADT/SmallString.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000019#include "llvm/IR/Constants.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000020#include "llvm/IR/Module.h"
Chandler Carruth4068e1a2013-01-07 15:43:51 +000021#include "llvm/IR/TypeFinder.h"
Bill Wendlingcd7193f2012-03-22 20:28:27 +000022#include "llvm/Support/Debug.h"
Bill Wendlingcd7193f2012-03-22 20:28:27 +000023#include "llvm/Support/raw_ostream.h"
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +000024#include "llvm/Transforms/Utils/Cloning.h"
Chris Lattnerf7703df2004-01-09 06:12:26 +000025using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000026
Chris Lattner1afcace2011-07-09 17:41:24 +000027//===----------------------------------------------------------------------===//
28// TypeMap implementation.
29//===----------------------------------------------------------------------===//
Chris Lattner5c377c52001-10-14 23:29:15 +000030
Chris Lattner62a81a12008-06-16 21:00:18 +000031namespace {
Rafael Espindolacfb320f2013-05-04 05:05:18 +000032 typedef SmallPtrSet<StructType*, 32> TypeSet;
33
Chris Lattner1afcace2011-07-09 17:41:24 +000034class TypeMapTy : public ValueMapTypeRemapper {
35 /// MappedTypes - This is a mapping from a source type to a destination type
36 /// to use.
37 DenseMap<Type*, Type*> MappedTypes;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +000038
Chris Lattner1afcace2011-07-09 17:41:24 +000039 /// SpeculativeTypes - When checking to see if two subgraphs are isomorphic,
40 /// we speculatively add types to MappedTypes, but keep track of them here in
41 /// case we need to roll back.
42 SmallVector<Type*, 16> SpeculativeTypes;
43
Chris Lattner68910502011-12-20 00:03:52 +000044 /// SrcDefinitionsToResolve - This is a list of non-opaque structs in the
45 /// source module that are mapped to an opaque struct in the destination
46 /// module.
47 SmallVector<StructType*, 16> SrcDefinitionsToResolve;
48
49 /// DstResolvedOpaqueTypes - This is the set of opaque types in the
50 /// destination modules who are getting a body from the source module.
51 SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
Bill Wendling6d6c6d72012-03-22 20:30:41 +000052
Chris Lattnerfc196f92008-06-16 23:06:51 +000053public:
Rafael Espindolacfb320f2013-05-04 05:05:18 +000054 TypeMapTy(TypeSet &Set) : DstStructTypesSet(Set) {}
55
56 TypeSet &DstStructTypesSet;
Chris Lattner1afcace2011-07-09 17:41:24 +000057 /// addTypeMapping - Indicate that the specified type in the destination
58 /// module is conceptually equivalent to the specified type in the source
59 /// module.
60 void addTypeMapping(Type *DstTy, Type *SrcTy);
61
62 /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
63 /// module from a type definition in the source module.
64 void linkDefinedTypeBodies();
65
66 /// get - Return the mapped type to use for the specified input type from the
67 /// source module.
68 Type *get(Type *SrcTy);
69
70 FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*)T));}
71
Bill Wendlingcd7193f2012-03-22 20:28:27 +000072 /// dump - Dump out the type map for debugging purposes.
73 void dump() const {
74 for (DenseMap<Type*, Type*>::const_iterator
75 I = MappedTypes.begin(), E = MappedTypes.end(); I != E; ++I) {
76 dbgs() << "TypeMap: ";
77 I->first->dump();
78 dbgs() << " => ";
79 I->second->dump();
80 dbgs() << '\n';
81 }
82 }
Bill Wendlingcd7193f2012-03-22 20:28:27 +000083
Chris Lattner1afcace2011-07-09 17:41:24 +000084private:
85 Type *getImpl(Type *T);
86 /// remapType - Implement the ValueMapTypeRemapper interface.
87 Type *remapType(Type *SrcTy) {
88 return get(SrcTy);
Chris Lattner62a81a12008-06-16 21:00:18 +000089 }
Chris Lattner1afcace2011-07-09 17:41:24 +000090
91 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
Chris Lattner62a81a12008-06-16 21:00:18 +000092};
93}
94
Chris Lattner1afcace2011-07-09 17:41:24 +000095void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
96 Type *&Entry = MappedTypes[SrcTy];
97 if (Entry) return;
98
99 if (DstTy == SrcTy) {
100 Entry = DstTy;
101 return;
102 }
Bill Wendling601c0942012-02-28 04:01:21 +0000103
Chris Lattner1afcace2011-07-09 17:41:24 +0000104 // Check to see if these types are recursively isomorphic and establish a
105 // mapping between them if so.
Bill Wendling601c0942012-02-28 04:01:21 +0000106 if (!areTypesIsomorphic(DstTy, SrcTy)) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000107 // Oops, they aren't isomorphic. Just discard this request by rolling out
108 // any speculative mappings we've established.
109 for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i)
110 MappedTypes.erase(SpeculativeTypes[i]);
Bill Wendling601c0942012-02-28 04:01:21 +0000111 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000112 SpeculativeTypes.clear();
113}
Chris Lattner62a81a12008-06-16 21:00:18 +0000114
Chris Lattner1afcace2011-07-09 17:41:24 +0000115/// areTypesIsomorphic - Recursively walk this pair of types, returning true
116/// if they are isomorphic, false if they are not.
117bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
118 // Two types with differing kinds are clearly not isomorphic.
119 if (DstTy->getTypeID() != SrcTy->getTypeID()) return false;
Misha Brukmanf976c852005-04-21 22:55:34 +0000120
Chris Lattner1afcace2011-07-09 17:41:24 +0000121 // If we have an entry in the MappedTypes table, then we have our answer.
122 Type *&Entry = MappedTypes[SrcTy];
123 if (Entry)
124 return Entry == DstTy;
Misha Brukmanf976c852005-04-21 22:55:34 +0000125
Chris Lattner1afcace2011-07-09 17:41:24 +0000126 // Two identical types are clearly isomorphic. Remember this
127 // non-speculatively.
128 if (DstTy == SrcTy) {
129 Entry = DstTy;
Chris Lattner56539652008-06-16 20:03:01 +0000130 return true;
Chris Lattner1afcace2011-07-09 17:41:24 +0000131 }
Bill Wendling601c0942012-02-28 04:01:21 +0000132
Chris Lattner1afcace2011-07-09 17:41:24 +0000133 // Okay, we have two types with identical kinds that we haven't seen before.
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000134
Chris Lattner1afcace2011-07-09 17:41:24 +0000135 // If this is an opaque struct type, special case it.
136 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
137 // Mapping an opaque type to any struct, just keep the dest struct.
138 if (SSTy->isOpaque()) {
139 Entry = DstTy;
140 SpeculativeTypes.push_back(SrcTy);
Chris Lattner43f4ba82003-08-22 19:12:55 +0000141 return true;
Chris Lattnera4477f92008-06-16 21:17:12 +0000142 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000143
Chris Lattner68910502011-12-20 00:03:52 +0000144 // Mapping a non-opaque source type to an opaque dest. If this is the first
145 // type that we're mapping onto this destination type then we succeed. Keep
146 // the dest, but fill it in later. This doesn't need to be speculative. If
147 // this is the second (different) type that we're trying to map onto the
148 // same opaque type then we fail.
Chris Lattner1afcace2011-07-09 17:41:24 +0000149 if (cast<StructType>(DstTy)->isOpaque()) {
Chris Lattner68910502011-12-20 00:03:52 +0000150 // We can only map one source type onto the opaque destination type.
151 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)))
152 return false;
153 SrcDefinitionsToResolve.push_back(SSTy);
Chris Lattner1afcace2011-07-09 17:41:24 +0000154 Entry = DstTy;
Chris Lattner1afcace2011-07-09 17:41:24 +0000155 return true;
156 }
157 }
158
159 // If the number of subtypes disagree between the two types, then we fail.
160 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
Chris Lattnere76c57a2003-08-22 06:07:12 +0000161 return false;
Chris Lattner1afcace2011-07-09 17:41:24 +0000162
163 // Fail if any of the extra properties (e.g. array size) of the type disagree.
164 if (isa<IntegerType>(DstTy))
165 return false; // bitwidth disagrees.
166 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
167 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
168 return false;
Chris Lattner1a31f3b2011-12-20 23:14:57 +0000169
Chris Lattner1afcace2011-07-09 17:41:24 +0000170 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
171 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
172 return false;
173 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
174 StructType *SSTy = cast<StructType>(SrcTy);
Chris Lattner1bcbf852011-08-12 18:07:26 +0000175 if (DSTy->isLiteral() != SSTy->isLiteral() ||
Chris Lattner1afcace2011-07-09 17:41:24 +0000176 DSTy->isPacked() != SSTy->isPacked())
177 return false;
178 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
179 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
180 return false;
181 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
Joey Gouly2b8f6ae2013-01-10 10:49:36 +0000182 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
Chris Lattner1afcace2011-07-09 17:41:24 +0000183 return false;
Chris Lattnere76c57a2003-08-22 06:07:12 +0000184 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000185
186 // Otherwise, we speculate that these two types will line up and recursively
187 // check the subelements.
188 Entry = DstTy;
189 SpeculativeTypes.push_back(SrcTy);
190
Bill Wendling601c0942012-02-28 04:01:21 +0000191 for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i)
192 if (!areTypesIsomorphic(DstTy->getContainedType(i),
193 SrcTy->getContainedType(i)))
Chris Lattner1afcace2011-07-09 17:41:24 +0000194 return false;
195
196 // If everything seems to have lined up, then everything is great.
197 return true;
198}
199
200/// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
201/// module from a type definition in the source module.
202void TypeMapTy::linkDefinedTypeBodies() {
203 SmallVector<Type*, 16> Elements;
204 SmallString<16> TmpName;
205
206 // Note that processing entries in this loop (calling 'get') can add new
Chris Lattner68910502011-12-20 00:03:52 +0000207 // entries to the SrcDefinitionsToResolve vector.
208 while (!SrcDefinitionsToResolve.empty()) {
209 StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val();
Chris Lattner1afcace2011-07-09 17:41:24 +0000210 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
211
212 // TypeMap is a many-to-one mapping, if there were multiple types that
213 // provide a body for DstSTy then previous iterations of this loop may have
214 // already handled it. Just ignore this case.
215 if (!DstSTy->isOpaque()) continue;
216 assert(!SrcSTy->isOpaque() && "Not resolving a definition?");
217
218 // Map the body of the source type over to a new body for the dest type.
219 Elements.resize(SrcSTy->getNumElements());
220 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
221 Elements[i] = getImpl(SrcSTy->getElementType(i));
222
223 DstSTy->setBody(Elements, SrcSTy->isPacked());
224
225 // If DstSTy has no name or has a longer name than STy, then viciously steal
226 // STy's name.
227 if (!SrcSTy->hasName()) continue;
228 StringRef SrcName = SrcSTy->getName();
229
230 if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
231 TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
232 SrcSTy->setName("");
233 DstSTy->setName(TmpName.str());
234 TmpName.clear();
235 }
236 }
Chris Lattner68910502011-12-20 00:03:52 +0000237
238 DstResolvedOpaqueTypes.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000239}
240
Chris Lattner1afcace2011-07-09 17:41:24 +0000241/// get - Return the mapped type to use for the specified input type from the
242/// source module.
243Type *TypeMapTy::get(Type *Ty) {
244 Type *Result = getImpl(Ty);
245
246 // If this caused a reference to any struct type, resolve it before returning.
Chris Lattner68910502011-12-20 00:03:52 +0000247 if (!SrcDefinitionsToResolve.empty())
Chris Lattner1afcace2011-07-09 17:41:24 +0000248 linkDefinedTypeBodies();
249 return Result;
250}
251
252/// getImpl - This is the recursive version of get().
253Type *TypeMapTy::getImpl(Type *Ty) {
254 // If we already have an entry for this type, return it.
255 Type **Entry = &MappedTypes[Ty];
256 if (*Entry) return *Entry;
Bill Wendling601c0942012-02-28 04:01:21 +0000257
Chris Lattner1afcace2011-07-09 17:41:24 +0000258 // If this is not a named struct type, then just map all of the elements and
259 // then rebuild the type from inside out.
Chris Lattner1bcbf852011-08-12 18:07:26 +0000260 if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000261 // If there are no element types to map, then the type is itself. This is
262 // true for the anonymous {} struct, things like 'float', integers, etc.
263 if (Ty->getNumContainedTypes() == 0)
264 return *Entry = Ty;
265
266 // Remap all of the elements, keeping track of whether any of them change.
267 bool AnyChange = false;
268 SmallVector<Type*, 4> ElementTypes;
269 ElementTypes.resize(Ty->getNumContainedTypes());
270 for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) {
271 ElementTypes[i] = getImpl(Ty->getContainedType(i));
272 AnyChange |= ElementTypes[i] != Ty->getContainedType(i);
273 }
274
275 // If we found our type while recursively processing stuff, just use it.
276 Entry = &MappedTypes[Ty];
277 if (*Entry) return *Entry;
278
279 // If all of the element types mapped directly over, then the type is usable
280 // as-is.
281 if (!AnyChange)
282 return *Entry = Ty;
283
284 // Otherwise, rebuild a modified type.
285 switch (Ty->getTypeID()) {
Craig Topper85814382012-02-07 05:05:23 +0000286 default: llvm_unreachable("unknown derived type to remap");
Chris Lattner1afcace2011-07-09 17:41:24 +0000287 case Type::ArrayTyID:
288 return *Entry = ArrayType::get(ElementTypes[0],
289 cast<ArrayType>(Ty)->getNumElements());
290 case Type::VectorTyID:
291 return *Entry = VectorType::get(ElementTypes[0],
292 cast<VectorType>(Ty)->getNumElements());
293 case Type::PointerTyID:
294 return *Entry = PointerType::get(ElementTypes[0],
295 cast<PointerType>(Ty)->getAddressSpace());
296 case Type::FunctionTyID:
297 return *Entry = FunctionType::get(ElementTypes[0],
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000298 makeArrayRef(ElementTypes).slice(1),
Chris Lattner1afcace2011-07-09 17:41:24 +0000299 cast<FunctionType>(Ty)->isVarArg());
300 case Type::StructTyID:
301 // Note that this is only reached for anonymous structs.
302 return *Entry = StructType::get(Ty->getContext(), ElementTypes,
303 cast<StructType>(Ty)->isPacked());
304 }
305 }
306
307 // Otherwise, this is an unmapped named struct. If the struct can be directly
308 // mapped over, just use it as-is. This happens in a case when the linked-in
309 // module has something like:
310 // %T = type {%T*, i32}
311 // @GV = global %T* null
312 // where T does not exist at all in the destination module.
313 //
314 // The other case we watch for is when the type is not in the destination
315 // module, but that it has to be rebuilt because it refers to something that
316 // is already mapped. For example, if the destination module has:
317 // %A = type { i32 }
318 // and the source module has something like
319 // %A' = type { i32 }
320 // %B = type { %A'* }
321 // @GV = global %B* null
322 // then we want to create a new type: "%B = type { %A*}" and have it take the
323 // pristine "%B" name from the source module.
324 //
325 // To determine which case this is, we have to recursively walk the type graph
326 // speculating that we'll be able to reuse it unmodified. Only if this is
327 // safe would we map the entire thing over. Because this is an optimization,
328 // and is not required for the prettiness of the linked module, we just skip
329 // it and always rebuild a type here.
330 StructType *STy = cast<StructType>(Ty);
331
332 // If the type is opaque, we can just use it directly.
Rafael Espindolacfb320f2013-05-04 05:05:18 +0000333 if (STy->isOpaque()) {
334 // A named structure type from src module is used. Add it to the Set of
335 // identified structs in the destination module.
336 DstStructTypesSet.insert(STy);
Chris Lattner1afcace2011-07-09 17:41:24 +0000337 return *Entry = STy;
Rafael Espindolacfb320f2013-05-04 05:05:18 +0000338 }
Bill Wendling601c0942012-02-28 04:01:21 +0000339
Chris Lattner1afcace2011-07-09 17:41:24 +0000340 // Otherwise we create a new type and resolve its body later. This will be
341 // resolved by the top level of get().
Chris Lattner68910502011-12-20 00:03:52 +0000342 SrcDefinitionsToResolve.push_back(STy);
343 StructType *DTy = StructType::create(STy->getContext());
Rafael Espindolacfb320f2013-05-04 05:05:18 +0000344 // A new identified structure type was created. Add it to the set of
345 // identified structs in the destination module.
346 DstStructTypesSet.insert(DTy);
Chris Lattner68910502011-12-20 00:03:52 +0000347 DstResolvedOpaqueTypes.insert(DTy);
348 return *Entry = DTy;
Chris Lattner1afcace2011-07-09 17:41:24 +0000349}
350
Chris Lattner1afcace2011-07-09 17:41:24 +0000351//===----------------------------------------------------------------------===//
352// ModuleLinker implementation.
353//===----------------------------------------------------------------------===//
354
355namespace {
James Molloya84a83b2013-05-28 15:17:05 +0000356 class ModuleLinker;
357
358 /// ValueMaterializerTy - Creates prototypes for functions that are lazily
359 /// linked on the fly. This speeds up linking for modules with many
360 /// lazily linked functions of which few get used.
361 class ValueMaterializerTy : public ValueMaterializer {
362 TypeMapTy &TypeMap;
363 Module *DstM;
364 std::vector<Function*> &LazilyLinkFunctions;
365 public:
366 ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
367 std::vector<Function*> &LazilyLinkFunctions) :
368 ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
369 LazilyLinkFunctions(LazilyLinkFunctions) {
370 }
371
372 virtual Value *materializeValueFor(Value *V);
373 };
374
Chris Lattner1afcace2011-07-09 17:41:24 +0000375 /// ModuleLinker - This is an implementation class for the LinkModules
376 /// function, which is the entrypoint for this file.
377 class ModuleLinker {
378 Module *DstM, *SrcM;
379
380 TypeMapTy TypeMap;
James Molloya84a83b2013-05-28 15:17:05 +0000381 ValueMaterializerTy ValMaterializer;
Chris Lattner1afcace2011-07-09 17:41:24 +0000382
383 /// ValueMap - Mapping of values from what they used to be in Src, to what
384 /// they are now in DstM. ValueToValueMapTy is a ValueMap, which involves
385 /// some overhead due to the use of Value handles which the Linker doesn't
386 /// actually need, but this allows us to reuse the ValueMapper code.
387 ValueToValueMapTy ValueMap;
388
389 struct AppendingVarInfo {
390 GlobalVariable *NewGV; // New aggregate global in dest module.
391 Constant *DstInit; // Old initializer from dest module.
392 Constant *SrcInit; // Old initializer from src module.
393 };
394
395 std::vector<AppendingVarInfo> AppendingVars;
396
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000397 unsigned Mode; // Mode to treat source module.
398
399 // Set of items not to link in from source.
400 SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
401
Tanya Lattner9af37a32011-11-02 00:24:56 +0000402 // Vector of functions to lazily link in.
Bill Wendlingd99a29e2013-03-27 17:54:41 +0000403 std::vector<Function*> LazilyLinkFunctions;
Tanya Lattner9af37a32011-11-02 00:24:56 +0000404
Chris Lattner1afcace2011-07-09 17:41:24 +0000405 public:
406 std::string ErrorMsg;
407
Rafael Espindolacfb320f2013-05-04 05:05:18 +0000408 ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM, unsigned mode)
James Molloya84a83b2013-05-28 15:17:05 +0000409 : DstM(dstM), SrcM(srcM), TypeMap(Set),
410 ValMaterializer(TypeMap, DstM, LazilyLinkFunctions),
411 Mode(mode) { }
Chris Lattner1afcace2011-07-09 17:41:24 +0000412
413 bool run();
414
415 private:
416 /// emitError - Helper method for setting a message and returning an error
417 /// code.
418 bool emitError(const Twine &Message) {
419 ErrorMsg = Message.str();
Chris Lattnerf6f4f7a2008-06-16 18:27:53 +0000420 return true;
Chris Lattnera4477f92008-06-16 21:17:12 +0000421 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000422
423 /// getLinkageResult - This analyzes the two global values and determines
424 /// what the result will look like in the destination module.
425 bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Rafael Espindola3ed88152012-01-05 23:02:01 +0000426 GlobalValue::LinkageTypes &LT,
427 GlobalValue::VisibilityTypes &Vis,
428 bool &LinkFromSrc);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000429
Chris Lattner1afcace2011-07-09 17:41:24 +0000430 /// getLinkedToGlobal - Given a global in the source module, return the
431 /// global in the destination module that is being linked to, if any.
432 GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
433 // If the source has no name it can't link. If it has local linkage,
434 // there is no name match-up going on.
435 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
436 return 0;
Bill Wendling601c0942012-02-28 04:01:21 +0000437
Chris Lattner1afcace2011-07-09 17:41:24 +0000438 // Otherwise see if we have a match in the destination module's symtab.
439 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
440 if (DGV == 0) return 0;
Bill Wendling601c0942012-02-28 04:01:21 +0000441
Chris Lattner1afcace2011-07-09 17:41:24 +0000442 // If we found a global with the same name in the dest module, but it has
443 // internal linkage, we are really not doing any linkage here.
444 if (DGV->hasLocalLinkage())
445 return 0;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000446
Chris Lattner1afcace2011-07-09 17:41:24 +0000447 // Otherwise, we do in fact link to the destination global.
448 return DGV;
449 }
450
451 void computeTypeMapping();
452
453 bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
454 bool linkGlobalProto(GlobalVariable *SrcGV);
455 bool linkFunctionProto(Function *SrcF);
456 bool linkAliasProto(GlobalAlias *SrcA);
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000457 bool linkModuleFlagsMetadata();
Chris Lattner1afcace2011-07-09 17:41:24 +0000458
459 void linkAppendingVarInit(const AppendingVarInfo &AVI);
460 void linkGlobalInits();
461 void linkFunctionBody(Function *Dst, Function *Src);
462 void linkAliasBodies();
463 void linkNamedMDNodes();
464 };
Bill Wendling601c0942012-02-28 04:01:21 +0000465}
466
Chris Lattner1afcace2011-07-09 17:41:24 +0000467/// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
Reid Spencer8bef0372007-02-04 04:29:21 +0000468/// in the symbol table. This is good for all clients except for us. Go
469/// through the trouble to force this back.
Chris Lattner1afcace2011-07-09 17:41:24 +0000470static void forceRenaming(GlobalValue *GV, StringRef Name) {
471 // If the global doesn't force its name or if it already has the right name,
472 // there is nothing for us to do.
473 if (GV->hasLocalLinkage() || GV->getName() == Name)
474 return;
475
476 Module *M = GV->getParent();
Chris Lattnerc0036282004-08-04 07:05:54 +0000477
478 // If there is a conflict, rename the conflict.
Chris Lattner1afcace2011-07-09 17:41:24 +0000479 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
Chris Lattner33f29492007-02-11 00:39:38 +0000480 GV->takeName(ConflictGV);
481 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Chris Lattner1afcace2011-07-09 17:41:24 +0000482 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
Chris Lattner33f29492007-02-11 00:39:38 +0000483 } else {
484 GV->setName(Name); // Force the name back
Reid Spenceref9b9a72007-02-05 20:47:22 +0000485 }
Reid Spenceref9b9a72007-02-05 20:47:22 +0000486}
Reid Spencer8bef0372007-02-04 04:29:21 +0000487
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000488/// copyGVAttributes - copy additional attributes (those not needed to construct
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000489/// a GlobalValue) from the SrcGV to the DestGV.
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000490static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
Duncan Sands28c3cff2008-05-26 19:58:59 +0000491 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
492 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
493 DestGV->copyAttributesFrom(SrcGV);
494 DestGV->setAlignment(Alignment);
Chris Lattner1afcace2011-07-09 17:41:24 +0000495
496 forceRenaming(DestGV, SrcGV->getName());
Chris Lattnerc0036282004-08-04 07:05:54 +0000497}
498
Rafael Espindola3ed88152012-01-05 23:02:01 +0000499static bool isLessConstraining(GlobalValue::VisibilityTypes a,
500 GlobalValue::VisibilityTypes b) {
501 if (a == GlobalValue::HiddenVisibility)
502 return false;
503 if (b == GlobalValue::HiddenVisibility)
504 return true;
505 if (a == GlobalValue::ProtectedVisibility)
506 return false;
507 if (b == GlobalValue::ProtectedVisibility)
508 return true;
509 return false;
510}
511
James Molloya84a83b2013-05-28 15:17:05 +0000512Value *ValueMaterializerTy::materializeValueFor(Value *V) {
513 Function *SF = dyn_cast<Function>(V);
514 if (!SF)
515 return NULL;
516
517 Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()),
518 SF->getLinkage(), SF->getName(), DstM);
519 copyGVAttributes(DF, SF);
520
521 LazilyLinkFunctions.push_back(SF);
522 return DF;
523}
524
525
Chris Lattner1afcace2011-07-09 17:41:24 +0000526/// getLinkageResult - This analyzes the two global values and determines what
Chris Lattneraee38ea2004-12-03 22:18:41 +0000527/// the result will look like in the destination module. In particular, it
Rafael Espindola3ed88152012-01-05 23:02:01 +0000528/// computes the resultant linkage type and visibility, computes whether the
529/// global in the source should be copied over to the destination (replacing
530/// the existing one), and computes whether this linkage is an error or not.
Chris Lattner1afcace2011-07-09 17:41:24 +0000531bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Rafael Espindola3ed88152012-01-05 23:02:01 +0000532 GlobalValue::LinkageTypes &LT,
533 GlobalValue::VisibilityTypes &Vis,
Chris Lattner1afcace2011-07-09 17:41:24 +0000534 bool &LinkFromSrc) {
535 assert(Dest && "Must have two globals being queried");
536 assert(!Src->hasLocalLinkage() &&
Chris Lattneraee38ea2004-12-03 22:18:41 +0000537 "If Src has internal linkage, Dest shouldn't be set!");
Chris Lattner1afcace2011-07-09 17:41:24 +0000538
Peter Collingbourne88953162011-10-30 17:46:34 +0000539 bool SrcIsDeclaration = Src->isDeclaration() && !Src->isMaterializable();
Chris Lattnerf84c59d2011-07-14 20:23:05 +0000540 bool DestIsDeclaration = Dest->isDeclaration();
Chris Lattner1afcace2011-07-09 17:41:24 +0000541
542 if (SrcIsDeclaration) {
Anton Korobeynikov2b48ef02008-03-10 22:33:22 +0000543 // If Src is external or if both Src & Dest are external.. Just link the
Chris Lattneraee38ea2004-12-03 22:18:41 +0000544 // external globals, we aren't adding anything.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000545 if (Src->hasDLLImportLinkage()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000546 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
Chris Lattner1afcace2011-07-09 17:41:24 +0000547 if (DestIsDeclaration) {
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000548 LinkFromSrc = true;
549 LT = Src->getLinkage();
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000550 }
Andrew Lenharth8753c442006-12-15 17:35:32 +0000551 } else if (Dest->hasExternalWeakLinkage()) {
Duncan Sands667d4b82009-03-07 15:45:40 +0000552 // If the Dest is weak, use the source linkage.
Andrew Lenharth8753c442006-12-15 17:35:32 +0000553 LinkFromSrc = true;
554 LT = Src->getLinkage();
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000555 } else {
556 LinkFromSrc = false;
557 LT = Dest->getLinkage();
558 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000559 } else if (DestIsDeclaration && !Dest->hasDLLImportLinkage()) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000560 // If Dest is external but Src is not:
561 LinkFromSrc = true;
562 LT = Src->getLinkage();
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000563 } else if (Src->isWeakForLinker()) {
Dale Johannesenaafce772008-05-14 20:12:51 +0000564 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
565 // or DLL* linkage.
Chris Lattner266c7bb2009-04-13 05:44:34 +0000566 if (Dest->hasExternalWeakLinkage() ||
567 Dest->hasAvailableExternallyLinkage() ||
568 (Dest->hasLinkOnceLinkage() &&
569 (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000570 LinkFromSrc = true;
571 LT = Src->getLinkage();
572 } else {
573 LinkFromSrc = false;
574 LT = Dest->getLinkage();
575 }
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000576 } else if (Dest->isWeakForLinker()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000577 // At this point we know that Src has External* or DLL* linkage.
578 if (Src->hasExternalWeakLinkage()) {
579 LinkFromSrc = false;
580 LT = Dest->getLinkage();
581 } else {
582 LinkFromSrc = true;
583 LT = GlobalValue::ExternalLinkage;
584 }
Chris Lattneraee38ea2004-12-03 22:18:41 +0000585 } else {
Chris Lattner1afcace2011-07-09 17:41:24 +0000586 assert((Dest->hasExternalLinkage() || Dest->hasDLLImportLinkage() ||
587 Dest->hasDLLExportLinkage() || Dest->hasExternalWeakLinkage()) &&
588 (Src->hasExternalLinkage() || Src->hasDLLImportLinkage() ||
589 Src->hasDLLExportLinkage() || Src->hasExternalWeakLinkage()) &&
Chris Lattneraee38ea2004-12-03 22:18:41 +0000590 "Unexpected linkage type!");
Chris Lattner1afcace2011-07-09 17:41:24 +0000591 return emitError("Linking globals named '" + Src->getName() +
Chris Lattneraee38ea2004-12-03 22:18:41 +0000592 "': symbol multiply defined!");
593 }
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +0000594
Rafael Espindola3ed88152012-01-05 23:02:01 +0000595 // Compute the visibility. We follow the rules in the System V Application
596 // Binary Interface.
597 Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
598 Dest->getVisibility() : Src->getVisibility();
Chris Lattneraee38ea2004-12-03 22:18:41 +0000599 return false;
600}
Chris Lattner5c377c52001-10-14 23:29:15 +0000601
Chris Lattner1afcace2011-07-09 17:41:24 +0000602/// computeTypeMapping - Loop over all of the linked values to compute type
603/// mappings. For example, if we link "extern Foo *x" and "Foo *x = NULL", then
604/// we have two struct types 'Foo' but one got renamed when the module was
605/// loaded into the same LLVMContext.
606void ModuleLinker::computeTypeMapping() {
607 // Incorporate globals.
608 for (Module::global_iterator I = SrcM->global_begin(),
609 E = SrcM->global_end(); I != E; ++I) {
610 GlobalValue *DGV = getLinkedToGlobal(I);
611 if (DGV == 0) continue;
612
613 if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
614 TypeMap.addTypeMapping(DGV->getType(), I->getType());
615 continue;
616 }
617
618 // Unify the element type of appending arrays.
619 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
620 ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
621 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
Devang Patelab67e702009-08-11 18:01:24 +0000622 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000623
624 // Incorporate functions.
625 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
626 if (GlobalValue *DGV = getLinkedToGlobal(I))
627 TypeMap.addTypeMapping(DGV->getType(), I->getType());
628 }
Bill Wendlingc68d1272012-02-27 22:34:19 +0000629
Bill Wendling601c0942012-02-28 04:01:21 +0000630 // Incorporate types by name, scanning all the types in the source module.
631 // At this point, the destination module may have a type "%foo = { i32 }" for
Bill Wendling348e5e72012-02-27 23:48:30 +0000632 // example. When the source module got loaded into the same LLVMContext, if
633 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
Bill Wendling573e9732012-08-03 00:30:35 +0000634 TypeFinder SrcStructTypes;
635 SrcStructTypes.run(*SrcM, true);
Bill Wendling348e5e72012-02-27 23:48:30 +0000636 SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
637 SrcStructTypes.end());
Bill Wendlinga20689f2012-03-23 23:17:38 +0000638
Bill Wendling348e5e72012-02-27 23:48:30 +0000639 for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
640 StructType *ST = SrcStructTypes[i];
641 if (!ST->hasName()) continue;
642
643 // Check to see if there is a dot in the name followed by a digit.
Bill Wendling601c0942012-02-28 04:01:21 +0000644 size_t DotPos = ST->getName().rfind('.');
645 if (DotPos == 0 || DotPos == StringRef::npos ||
Guy Benyei87d0b9e2013-02-12 21:21:59 +0000646 ST->getName().back() == '.' ||
647 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
Bill Wendling601c0942012-02-28 04:01:21 +0000648 continue;
Bill Wendling348e5e72012-02-27 23:48:30 +0000649
650 // Check to see if the destination module has a struct with the prefix name.
Bill Wendling601c0942012-02-28 04:01:21 +0000651 if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
Bill Wendlinga20689f2012-03-23 23:17:38 +0000652 // Don't use it if this actually came from the source module. They're in
653 // the same LLVMContext after all. Also don't use it unless the type is
654 // actually used in the destination module. This can happen in situations
655 // like this:
656 //
657 // Module A Module B
658 // -------- --------
659 // %Z = type { %A } %B = type { %C.1 }
660 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
661 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
662 // %C = type { i8* } %B.3 = type { %C.1 }
663 //
664 // When we link Module B with Module A, the '%B' in Module B is
665 // used. However, that would then use '%C.1'. But when we process '%C.1',
666 // we prefer to take the '%C' version. So we are then left with both
667 // '%C.1' and '%C' being used for the same types. This leads to some
668 // variables using one type and some using the other.
Rafael Espindolacfb320f2013-05-04 05:05:18 +0000669 if (!SrcStructTypesSet.count(DST) && TypeMap.DstStructTypesSet.count(DST))
Bill Wendling348e5e72012-02-27 23:48:30 +0000670 TypeMap.addTypeMapping(DST, ST);
671 }
672
Chris Lattner1afcace2011-07-09 17:41:24 +0000673 // Don't bother incorporating aliases, they aren't generally typed well.
Bill Wendling601c0942012-02-28 04:01:21 +0000674
Chris Lattner1afcace2011-07-09 17:41:24 +0000675 // Now that we have discovered all of the type equivalences, get a body for
676 // any 'opaque' types in the dest module that are now resolved.
677 TypeMap.linkDefinedTypeBodies();
Devang Patelab67e702009-08-11 18:01:24 +0000678}
679
Chris Lattner1afcace2011-07-09 17:41:24 +0000680/// linkAppendingVarProto - If there were any appending global variables, link
681/// them together now. Return true on error.
682bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
683 GlobalVariable *SrcGV) {
Bill Wendling601c0942012-02-28 04:01:21 +0000684
Chris Lattner1afcace2011-07-09 17:41:24 +0000685 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
686 return emitError("Linking globals named '" + SrcGV->getName() +
687 "': can only link appending global with another appending global!");
688
689 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
690 ArrayType *SrcTy =
691 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
692 Type *EltTy = DstTy->getElementType();
693
694 // Check to see that they two arrays agree on type.
695 if (EltTy != SrcTy->getElementType())
696 return emitError("Appending variables with different element types!");
697 if (DstGV->isConstant() != SrcGV->isConstant())
698 return emitError("Appending variables linked with different const'ness!");
699
700 if (DstGV->getAlignment() != SrcGV->getAlignment())
701 return emitError(
702 "Appending variables with different alignment need to be linked!");
703
704 if (DstGV->getVisibility() != SrcGV->getVisibility())
705 return emitError(
706 "Appending variables with different visibility need to be linked!");
Rafael Espindola91273342013-09-04 15:33:34 +0000707
708 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
709 return emitError(
710 "Appending variables with different unnamed_addr need to be linked!");
711
Chris Lattner1afcace2011-07-09 17:41:24 +0000712 if (DstGV->getSection() != SrcGV->getSection())
713 return emitError(
714 "Appending variables with different section name need to be linked!");
715
716 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
717 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
718
719 // Create the new global variable.
720 GlobalVariable *NG =
721 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
722 DstGV->getLinkage(), /*init*/0, /*name*/"", DstGV,
Hans Wennborgce718ff2012-06-23 11:37:03 +0000723 DstGV->getThreadLocalMode(),
Chris Lattner1afcace2011-07-09 17:41:24 +0000724 DstGV->getType()->getAddressSpace());
725
726 // Propagate alignment, visibility and section info.
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000727 copyGVAttributes(NG, DstGV);
Chris Lattner1afcace2011-07-09 17:41:24 +0000728
729 AppendingVarInfo AVI;
730 AVI.NewGV = NG;
731 AVI.DstInit = DstGV->getInitializer();
732 AVI.SrcInit = SrcGV->getInitializer();
733 AppendingVars.push_back(AVI);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000734
Chris Lattner1afcace2011-07-09 17:41:24 +0000735 // Replace any uses of the two global variables with uses of the new
736 // global.
737 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000738
Chris Lattner1afcace2011-07-09 17:41:24 +0000739 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
740 DstGV->eraseFromParent();
741
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000742 // Track the source variable so we don't try to link it.
743 DoNotLinkFromSource.insert(SrcGV);
744
Chris Lattner1afcace2011-07-09 17:41:24 +0000745 return false;
746}
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000747
Chris Lattner1afcace2011-07-09 17:41:24 +0000748/// linkGlobalProto - Loop through the global variables in the src module and
749/// merge them into the dest module.
750bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
751 GlobalValue *DGV = getLinkedToGlobal(SGV);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000752 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Rafael Espindola3acfb582013-09-04 14:05:09 +0000753 bool HasUnnamedAddr = SGV->hasUnnamedAddr();
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000754
Chris Lattner1afcace2011-07-09 17:41:24 +0000755 if (DGV) {
756 // Concatenation of appending linkage variables is magic and handled later.
757 if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
758 return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
759
760 // Determine whether linkage of these two globals follows the source
761 // module's definition or the destination module's definition.
Chris Lattnerb324bd72006-11-09 05:18:12 +0000762 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000763 GlobalValue::VisibilityTypes NV;
Chris Lattnerb324bd72006-11-09 05:18:12 +0000764 bool LinkFromSrc = false;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000765 if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
Chris Lattneraee38ea2004-12-03 22:18:41 +0000766 return true;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000767 NewVisibility = NV;
Rafael Espindola6947f102013-09-04 14:59:03 +0000768 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
Chris Lattner0fec08e2003-04-21 21:07:05 +0000769
Chris Lattner1afcace2011-07-09 17:41:24 +0000770 // If we're not linking from the source, then keep the definition that we
771 // have.
772 if (!LinkFromSrc) {
773 // Special case for const propagation.
774 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
775 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
776 DGVar->setConstant(true);
Rafael Espindola3acfb582013-09-04 14:05:09 +0000777
778 // Set calculated linkage, visibility and unnamed_addr.
Chris Lattner1afcace2011-07-09 17:41:24 +0000779 DGV->setLinkage(NewLinkage);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000780 DGV->setVisibility(*NewVisibility);
Rafael Espindola3acfb582013-09-04 14:05:09 +0000781 DGV->setUnnamedAddr(HasUnnamedAddr);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000782
Chris Lattner6157e382008-07-14 07:23:24 +0000783 // Make sure to remember this mapping.
Chris Lattner1afcace2011-07-09 17:41:24 +0000784 ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
785
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000786 // Track the source global so that we don't attempt to copy it over when
787 // processing global initializers.
788 DoNotLinkFromSource.insert(SGV);
789
Chris Lattner1afcace2011-07-09 17:41:24 +0000790 return false;
Chris Lattner6157e382008-07-14 07:23:24 +0000791 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000792 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000793
794 // No linking to be performed or linking from the source: simply create an
795 // identical version of the symbol over in the dest module... the
796 // initializer will be filled in later by LinkGlobalInits.
797 GlobalVariable *NewDGV =
798 new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
799 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
800 SGV->getName(), /*insertbefore*/0,
Hans Wennborgce718ff2012-06-23 11:37:03 +0000801 SGV->getThreadLocalMode(),
Chris Lattner1afcace2011-07-09 17:41:24 +0000802 SGV->getType()->getAddressSpace());
803 // Propagate alignment, visibility and section info.
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000804 copyGVAttributes(NewDGV, SGV);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000805 if (NewVisibility)
806 NewDGV->setVisibility(*NewVisibility);
Rafael Espindola3acfb582013-09-04 14:05:09 +0000807 NewDGV->setUnnamedAddr(HasUnnamedAddr);
Chris Lattner1afcace2011-07-09 17:41:24 +0000808
809 if (DGV) {
810 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
811 DGV->eraseFromParent();
812 }
813
814 // Make sure to remember this mapping.
815 ValueMap[SGV] = NewDGV;
Chris Lattner5c377c52001-10-14 23:29:15 +0000816 return false;
817}
818
Chris Lattner1afcace2011-07-09 17:41:24 +0000819/// linkFunctionProto - Link the function in the source module into the
820/// destination module if needed, setting up mapping information.
821bool ModuleLinker::linkFunctionProto(Function *SF) {
822 GlobalValue *DGV = getLinkedToGlobal(SF);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000823 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Rafael Espindola6947f102013-09-04 14:59:03 +0000824 bool HasUnnamedAddr = SF->hasUnnamedAddr();
Chris Lattner1afcace2011-07-09 17:41:24 +0000825
826 if (DGV) {
827 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
828 bool LinkFromSrc = false;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000829 GlobalValue::VisibilityTypes NV;
830 if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
Chris Lattner1afcace2011-07-09 17:41:24 +0000831 return true;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000832 NewVisibility = NV;
Rafael Espindola6947f102013-09-04 14:59:03 +0000833 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
Rafael Espindola3ed88152012-01-05 23:02:01 +0000834
Chris Lattner1afcace2011-07-09 17:41:24 +0000835 if (!LinkFromSrc) {
836 // Set calculated linkage
837 DGV->setLinkage(NewLinkage);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000838 DGV->setVisibility(*NewVisibility);
Rafael Espindola6947f102013-09-04 14:59:03 +0000839 DGV->setUnnamedAddr(HasUnnamedAddr);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000840
Chris Lattner1afcace2011-07-09 17:41:24 +0000841 // Make sure to remember this mapping.
842 ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
843
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000844 // Track the function from the source module so we don't attempt to remap
845 // it.
846 DoNotLinkFromSource.insert(SF);
847
Chris Lattner1afcace2011-07-09 17:41:24 +0000848 return false;
849 }
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000850 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000851
James Molloya84a83b2013-05-28 15:17:05 +0000852 // If the function is to be lazily linked, don't create it just yet.
853 // The ValueMaterializerTy will deal with creating it if it's used.
854 if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
855 SF->hasAvailableExternallyLinkage())) {
856 DoNotLinkFromSource.insert(SF);
857 return false;
858 }
859
Chris Lattner1afcace2011-07-09 17:41:24 +0000860 // If there is no linkage to be performed or we are linking from the source,
861 // bring SF over.
862 Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
863 SF->getLinkage(), SF->getName(), DstM);
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000864 copyGVAttributes(NewDF, SF);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000865 if (NewVisibility)
866 NewDF->setVisibility(*NewVisibility);
Rafael Espindola6947f102013-09-04 14:59:03 +0000867 NewDF->setUnnamedAddr(HasUnnamedAddr);
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000868
Chris Lattner1afcace2011-07-09 17:41:24 +0000869 if (DGV) {
870 // Any uses of DF need to change to NewDF, with cast.
871 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
872 DGV->eraseFromParent();
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000873 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000874
875 ValueMap[SF] = NewDF;
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000876 return false;
877}
878
Chris Lattner1afcace2011-07-09 17:41:24 +0000879/// LinkAliasProto - Set up prototypes for any aliases that come over from the
880/// source module.
881bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
882 GlobalValue *DGV = getLinkedToGlobal(SGA);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000883 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
884
Chris Lattner1afcace2011-07-09 17:41:24 +0000885 if (DGV) {
886 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000887 GlobalValue::VisibilityTypes NV;
Chris Lattner1afcace2011-07-09 17:41:24 +0000888 bool LinkFromSrc = false;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000889 if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
Chris Lattner1afcace2011-07-09 17:41:24 +0000890 return true;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000891 NewVisibility = NV;
892
Chris Lattner1afcace2011-07-09 17:41:24 +0000893 if (!LinkFromSrc) {
894 // Set calculated linkage.
895 DGV->setLinkage(NewLinkage);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000896 DGV->setVisibility(*NewVisibility);
897
Chris Lattner1afcace2011-07-09 17:41:24 +0000898 // Make sure to remember this mapping.
899 ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
900
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000901 // Track the alias from the source module so we don't attempt to remap it.
902 DoNotLinkFromSource.insert(SGA);
903
Chris Lattner1afcace2011-07-09 17:41:24 +0000904 return false;
905 }
906 }
907
908 // If there is no linkage to be performed or we're linking from the source,
909 // bring over SGA.
910 GlobalAlias *NewDA = new GlobalAlias(TypeMap.get(SGA->getType()),
911 SGA->getLinkage(), SGA->getName(),
912 /*aliasee*/0, DstM);
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000913 copyGVAttributes(NewDA, SGA);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000914 if (NewVisibility)
915 NewDA->setVisibility(*NewVisibility);
Chris Lattner5c377c52001-10-14 23:29:15 +0000916
Chris Lattner1afcace2011-07-09 17:41:24 +0000917 if (DGV) {
918 // Any uses of DGV need to change to NewDA, with cast.
919 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
920 DGV->eraseFromParent();
921 }
922
923 ValueMap[SGA] = NewDA;
924 return false;
925}
926
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000927static void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000928 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
929
930 for (unsigned i = 0; i != NumElements; ++i)
931 Dest.push_back(C->getAggregateElement(i));
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000932}
933
Chris Lattner1afcace2011-07-09 17:41:24 +0000934void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
935 // Merge the initializer.
936 SmallVector<Constant*, 16> Elements;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000937 getArrayElements(AVI.DstInit, Elements);
Chris Lattner1afcace2011-07-09 17:41:24 +0000938
James Molloya84a83b2013-05-28 15:17:05 +0000939 Constant *SrcInit = MapValue(AVI.SrcInit, ValueMap, RF_None, &TypeMap, &ValMaterializer);
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000940 getArrayElements(SrcInit, Elements);
941
Chris Lattner1afcace2011-07-09 17:41:24 +0000942 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
943 AVI.NewGV->setInitializer(ConstantArray::get(NewType, Elements));
944}
945
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000946/// linkGlobalInits - Update the initializers in the Dest module now that all
947/// globals that may be referenced are in Dest.
Chris Lattner1afcace2011-07-09 17:41:24 +0000948void ModuleLinker::linkGlobalInits() {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000949 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattner1afcace2011-07-09 17:41:24 +0000950 for (Module::const_global_iterator I = SrcM->global_begin(),
951 E = SrcM->global_end(); I != E; ++I) {
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000952
953 // Only process initialized GV's or ones not already in dest.
954 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
Chris Lattner1afcace2011-07-09 17:41:24 +0000955
956 // Grab destination global variable.
957 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
958 // Figure out what the initializer looks like in the dest module.
959 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
James Molloya84a83b2013-05-28 15:17:05 +0000960 RF_None, &TypeMap, &ValMaterializer));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000961 }
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000962}
Chris Lattner5c377c52001-10-14 23:29:15 +0000963
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000964/// linkFunctionBody - Copy the source function over into the dest function and
965/// fix up references to values. At this point we know that Dest is an external
966/// function, and that Src is not.
Chris Lattner1afcace2011-07-09 17:41:24 +0000967void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
968 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
Chris Lattner5c377c52001-10-14 23:29:15 +0000969
Chris Lattner0033baf2004-11-16 17:12:38 +0000970 // Go through and convert function arguments over, remembering the mapping.
Chris Lattner1afcace2011-07-09 17:41:24 +0000971 Function::arg_iterator DI = Dst->arg_begin();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000972 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
Chris Lattner69da5cf2002-10-13 20:57:00 +0000973 I != E; ++I, ++DI) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000974 DI->setName(I->getName()); // Copy the name over.
Chris Lattner5c377c52001-10-14 23:29:15 +0000975
Chris Lattner1afcace2011-07-09 17:41:24 +0000976 // Add a mapping to our mapping.
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000977 ValueMap[I] = DI;
Chris Lattner5c377c52001-10-14 23:29:15 +0000978 }
979
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000980 if (Mode == Linker::DestroySource) {
981 // Splice the body of the source function into the dest function.
982 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
983
984 // At this point, all of the instructions and values of the function are now
985 // copied over. The only problem is that they are still referencing values in
986 // the Source function as operands. Loop through all of the operands of the
987 // functions and patch them up to point to the local versions.
988 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
989 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
James Molloya84a83b2013-05-28 15:17:05 +0000990 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries,
991 &TypeMap, &ValMaterializer);
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000992
993 } else {
994 // Clone the body of the function into the dest function.
995 SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
James Molloya84a83b2013-05-28 15:17:05 +0000996 CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", NULL,
997 &TypeMap, &ValMaterializer);
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000998 }
999
Chris Lattner0033baf2004-11-16 17:12:38 +00001000 // There is no need to map the arguments anymore.
Chris Lattner11273152006-06-16 01:24:04 +00001001 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1002 I != E; ++I)
Reid Spenceref9b9a72007-02-05 20:47:22 +00001003 ValueMap.erase(I);
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +00001004
Chris Lattner5c377c52001-10-14 23:29:15 +00001005}
1006
Bill Wendlingcd7193f2012-03-22 20:28:27 +00001007/// linkAliasBodies - Insert all of the aliases in Src into the Dest module.
Chris Lattner1afcace2011-07-09 17:41:24 +00001008void ModuleLinker::linkAliasBodies() {
1009 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +00001010 I != E; ++I) {
1011 if (DoNotLinkFromSource.count(I))
1012 continue;
Chris Lattner1afcace2011-07-09 17:41:24 +00001013 if (Constant *Aliasee = I->getAliasee()) {
1014 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
James Molloya84a83b2013-05-28 15:17:05 +00001015 DA->setAliasee(MapValue(Aliasee, ValueMap, RF_None,
1016 &TypeMap, &ValMaterializer));
David Chisnall34722462010-01-09 16:27:31 +00001017 }
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +00001018 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001019}
Anton Korobeynikov9f2ee702008-03-05 23:21:39 +00001020
Bill Wendlingcd7193f2012-03-22 20:28:27 +00001021/// linkNamedMDNodes - Insert all of the named MDNodes in Src into the Dest
Chris Lattner1afcace2011-07-09 17:41:24 +00001022/// module.
1023void ModuleLinker::linkNamedMDNodes() {
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001024 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
Chris Lattner1afcace2011-07-09 17:41:24 +00001025 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1026 E = SrcM->named_metadata_end(); I != E; ++I) {
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001027 // Don't link module flags here. Do them separately.
1028 if (&*I == SrcModFlags) continue;
Chris Lattner1afcace2011-07-09 17:41:24 +00001029 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1030 // Add Src elements into Dest node.
1031 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1032 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
James Molloya84a83b2013-05-28 15:17:05 +00001033 RF_None, &TypeMap, &ValMaterializer));
Chris Lattner1afcace2011-07-09 17:41:24 +00001034 }
1035}
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001036
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001037/// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest
1038/// module.
1039bool ModuleLinker::linkModuleFlagsMetadata() {
Daniel Dunbar1e081652013-01-16 18:39:23 +00001040 // If the source module has no module flags, we are done.
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001041 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1042 if (!SrcModFlags) return false;
1043
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001044 // If the destination module doesn't have module flags yet, then just copy
1045 // over the source module's flags.
Daniel Dunbar1e081652013-01-16 18:39:23 +00001046 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001047 if (DstModFlags->getNumOperands() == 0) {
1048 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1049 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1050
1051 return false;
1052 }
1053
Daniel Dunbar1e081652013-01-16 18:39:23 +00001054 // First build a map of the existing module flags and requirements.
1055 DenseMap<MDString*, MDNode*> Flags;
1056 SmallSetVector<MDNode*, 16> Requirements;
1057 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1058 MDNode *Op = DstModFlags->getOperand(I);
1059 ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1060 MDString *ID = cast<MDString>(Op->getOperand(1));
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001061
Daniel Dunbar1e081652013-01-16 18:39:23 +00001062 if (Behavior->getZExtValue() == Module::Require) {
1063 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1064 } else {
1065 Flags[ID] = Op;
1066 }
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001067 }
1068
Daniel Dunbar1e081652013-01-16 18:39:23 +00001069 // Merge in the flags from the source module, and also collect its set of
1070 // requirements.
1071 bool HasErr = false;
1072 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1073 MDNode *SrcOp = SrcModFlags->getOperand(I);
1074 ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1075 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1076 MDNode *DstOp = Flags.lookup(ID);
1077 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001078
Daniel Dunbar1e081652013-01-16 18:39:23 +00001079 // If this is a requirement, add it and continue.
1080 if (SrcBehaviorValue == Module::Require) {
1081 // If the destination module does not already have this requirement, add
1082 // it.
1083 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1084 DstModFlags->addOperand(SrcOp);
1085 }
1086 continue;
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001087 }
1088
Daniel Dunbar1e081652013-01-16 18:39:23 +00001089 // If there is no existing flag with this ID, just add it.
1090 if (!DstOp) {
1091 Flags[ID] = SrcOp;
1092 DstModFlags->addOperand(SrcOp);
1093 continue;
1094 }
1095
1096 // Otherwise, perform a merge.
1097 ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1098 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1099
1100 // If either flag has override behavior, handle it first.
1101 if (DstBehaviorValue == Module::Override) {
1102 // Diagnose inconsistent flags which both have override behavior.
1103 if (SrcBehaviorValue == Module::Override &&
1104 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1105 HasErr |= emitError("linking module flags '" + ID->getString() +
1106 "': IDs have conflicting override values");
1107 }
1108 continue;
1109 } else if (SrcBehaviorValue == Module::Override) {
1110 // Update the destination flag to that of the source.
1111 DstOp->replaceOperandWith(0, SrcBehavior);
1112 DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1113 continue;
1114 }
1115
1116 // Diagnose inconsistent merge behavior types.
1117 if (SrcBehaviorValue != DstBehaviorValue) {
1118 HasErr |= emitError("linking module flags '" + ID->getString() +
1119 "': IDs have conflicting behaviors");
1120 continue;
1121 }
1122
1123 // Perform the merge for standard behavior types.
1124 switch (SrcBehaviorValue) {
1125 case Module::Require:
1126 case Module::Override: assert(0 && "not possible"); break;
1127 case Module::Error: {
1128 // Emit an error if the values differ.
1129 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1130 HasErr |= emitError("linking module flags '" + ID->getString() +
1131 "': IDs have conflicting values");
1132 }
1133 continue;
1134 }
1135 case Module::Warning: {
1136 // Emit a warning if the values differ.
1137 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1138 errs() << "WARNING: linking module flags '" << ID->getString()
1139 << "': IDs have conflicting values";
1140 }
1141 continue;
1142 }
Daniel Dunbar5db391c2013-01-16 21:38:56 +00001143 case Module::Append: {
1144 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1145 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1146 unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1147 Value **VP, **Values = VP = new Value*[NumOps];
1148 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1149 *VP = DstValue->getOperand(i);
1150 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1151 *VP = SrcValue->getOperand(i);
1152 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1153 ArrayRef<Value*>(Values,
1154 NumOps)));
1155 delete[] Values;
1156 break;
1157 }
1158 case Module::AppendUnique: {
1159 SmallSetVector<Value*, 16> Elts;
1160 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1161 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1162 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1163 Elts.insert(DstValue->getOperand(i));
1164 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1165 Elts.insert(SrcValue->getOperand(i));
1166 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1167 ArrayRef<Value*>(Elts.begin(),
1168 Elts.end())));
1169 break;
1170 }
Daniel Dunbar1e081652013-01-16 18:39:23 +00001171 }
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001172 }
1173
Daniel Dunbar1e081652013-01-16 18:39:23 +00001174 // Check all of the requirements.
1175 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1176 MDNode *Requirement = Requirements[I];
1177 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1178 Value *ReqValue = Requirement->getOperand(1);
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001179
Daniel Dunbar1e081652013-01-16 18:39:23 +00001180 MDNode *Op = Flags[Flag];
1181 if (!Op || Op->getOperand(2) != ReqValue) {
1182 HasErr |= emitError("linking module flags '" + Flag->getString() +
1183 "': does not have the required value");
1184 continue;
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001185 }
1186 }
1187
1188 return HasErr;
1189}
Chris Lattner1afcace2011-07-09 17:41:24 +00001190
1191bool ModuleLinker::run() {
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001192 assert(DstM && "Null destination module");
1193 assert(SrcM && "Null source module");
Chris Lattner1afcace2011-07-09 17:41:24 +00001194
1195 // Inherit the target data from the source module if the destination module
1196 // doesn't have one already.
1197 if (DstM->getDataLayout().empty() && !SrcM->getDataLayout().empty())
1198 DstM->setDataLayout(SrcM->getDataLayout());
1199
1200 // Copy the target triple from the source to dest if the dest's is empty.
1201 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1202 DstM->setTargetTriple(SrcM->getTargetTriple());
1203
1204 if (!SrcM->getDataLayout().empty() && !DstM->getDataLayout().empty() &&
1205 SrcM->getDataLayout() != DstM->getDataLayout())
1206 errs() << "WARNING: Linking two modules of different data layouts!\n";
1207 if (!SrcM->getTargetTriple().empty() &&
1208 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1209 errs() << "WARNING: Linking two modules of different target triples: ";
1210 if (!SrcM->getModuleIdentifier().empty())
1211 errs() << SrcM->getModuleIdentifier() << ": ";
1212 errs() << "'" << SrcM->getTargetTriple() << "' and '"
1213 << DstM->getTargetTriple() << "'\n";
1214 }
1215
1216 // Append the module inline asm string.
1217 if (!SrcM->getModuleInlineAsm().empty()) {
1218 if (DstM->getModuleInlineAsm().empty())
1219 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1220 else
1221 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1222 SrcM->getModuleInlineAsm());
1223 }
1224
Chris Lattner1afcace2011-07-09 17:41:24 +00001225 // Loop over all of the linked values to compute type mappings.
1226 computeTypeMapping();
1227
1228 // Insert all of the globals in src into the DstM module... without linking
1229 // initializers (which could refer to functions not yet mapped over).
1230 for (Module::global_iterator I = SrcM->global_begin(),
1231 E = SrcM->global_end(); I != E; ++I)
1232 if (linkGlobalProto(I))
1233 return true;
1234
1235 // Link the functions together between the two modules, without doing function
1236 // bodies... this just adds external function prototypes to the DstM
1237 // function... We do this so that when we begin processing function bodies,
1238 // all of the global values that may be referenced are available in our
1239 // ValueMap.
1240 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1241 if (linkFunctionProto(I))
1242 return true;
1243
1244 // If there were any aliases, link them now.
1245 for (Module::alias_iterator I = SrcM->alias_begin(),
1246 E = SrcM->alias_end(); I != E; ++I)
1247 if (linkAliasProto(I))
1248 return true;
1249
1250 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1251 linkAppendingVarInit(AppendingVars[i]);
1252
1253 // Update the initializers in the DstM module now that all globals that may
1254 // be referenced are in DstM.
1255 linkGlobalInits();
1256
1257 // Link in the function bodies that are defined in the source module into
1258 // DstM.
1259 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
Tanya Lattner2b28a742011-10-14 22:17:46 +00001260 // Skip if not linking from source.
1261 if (DoNotLinkFromSource.count(SF)) continue;
1262
Peter Collingbourne1e3037f2013-09-16 01:08:15 +00001263 Function *DF = cast<Function>(ValueMap[SF]);
1264 if (SF->hasPrefixData()) {
1265 // Link in the prefix data.
1266 DF->setPrefixData(MapValue(
1267 SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
1268 }
1269
Tanya Lattner2b28a742011-10-14 22:17:46 +00001270 // Skip if no body (function is external) or materialize.
1271 if (SF->isDeclaration()) {
1272 if (!SF->isMaterializable())
1273 continue;
1274 if (SF->Materialize(&ErrorMsg))
1275 return true;
1276 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001277
Peter Collingbourne1e3037f2013-09-16 01:08:15 +00001278 linkFunctionBody(DF, SF);
Bill Wendling208b6f62012-03-23 07:22:49 +00001279 SF->Dematerialize();
Chris Lattner1afcace2011-07-09 17:41:24 +00001280 }
1281
1282 // Resolve all uses of aliases with aliasees.
1283 linkAliasBodies();
1284
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001285 // Remap all of the named MDNodes in Src into the DstM module. We do this
Devang Patel211da8f2011-08-04 19:44:28 +00001286 // after linking GlobalValues so that MDNodes that reference GlobalValues
1287 // are properly remapped.
1288 linkNamedMDNodes();
1289
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001290 // Merge the module flags into the DstM module.
1291 if (linkModuleFlagsMetadata())
1292 return true;
1293
Tanya Lattner9af37a32011-11-02 00:24:56 +00001294 // Process vector of lazily linked in functions.
1295 bool LinkedInAnyFunctions;
1296 do {
1297 LinkedInAnyFunctions = false;
1298
Bill Wendlingd99a29e2013-03-27 17:54:41 +00001299 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
James Molloya84a83b2013-05-28 15:17:05 +00001300 E = LazilyLinkFunctions.end(); I != E; ++I) {
Bill Wendlingd99a29e2013-03-27 17:54:41 +00001301 Function *SF = *I;
James Molloya84a83b2013-05-28 15:17:05 +00001302 if (!SF)
1303 continue;
Bill Wendling208b6f62012-03-23 07:22:49 +00001304
James Molloya84a83b2013-05-28 15:17:05 +00001305 Function *DF = cast<Function>(ValueMap[SF]);
Peter Collingbourne1e3037f2013-09-16 01:08:15 +00001306 if (SF->hasPrefixData()) {
1307 // Link in the prefix data.
1308 DF->setPrefixData(MapValue(SF->getPrefixData(),
1309 ValueMap,
1310 RF_None,
1311 &TypeMap,
1312 &ValMaterializer));
1313 }
James Molloya84a83b2013-05-28 15:17:05 +00001314
1315 // Materialize if necessary.
1316 if (SF->isDeclaration()) {
1317 if (!SF->isMaterializable())
1318 continue;
1319 if (SF->Materialize(&ErrorMsg))
1320 return true;
Tanya Lattner9af37a32011-11-02 00:24:56 +00001321 }
James Molloya84a83b2013-05-28 15:17:05 +00001322
1323 // Erase from vector *before* the function body is linked - linkFunctionBody could
1324 // invalidate I.
1325 LazilyLinkFunctions.erase(I);
1326
1327 // Link in function body.
1328 linkFunctionBody(DF, SF);
1329 SF->Dematerialize();
1330
1331 // Set flag to indicate we may have more functions to lazily link in
1332 // since we linked in a function.
1333 LinkedInAnyFunctions = true;
1334 break;
Tanya Lattner9af37a32011-11-02 00:24:56 +00001335 }
1336 } while (LinkedInAnyFunctions);
1337
Chris Lattner1afcace2011-07-09 17:41:24 +00001338 // Now that all of the types from the source are used, resolve any structs
1339 // copied over to the dest that didn't exist there.
1340 TypeMap.linkDefinedTypeBodies();
1341
Anton Korobeynikov9f2ee702008-03-05 23:21:39 +00001342 return false;
1343}
Chris Lattner52f7e902001-10-13 07:03:50 +00001344
Rafael Espindolacfb320f2013-05-04 05:05:18 +00001345Linker::Linker(Module *M) : Composite(M) {
1346 TypeFinder StructTypes;
1347 StructTypes.run(*M, true);
1348 IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end());
1349}
Rafael Espindolac7c35a92013-05-04 03:48:37 +00001350
1351Linker::~Linker() {
1352}
1353
1354bool Linker::linkInModule(Module *Src, unsigned Mode, std::string *ErrorMsg) {
Rafael Espindolacfb320f2013-05-04 05:05:18 +00001355 ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src, Mode);
Rafael Espindola2e013022013-05-04 04:08:02 +00001356 if (TheLinker.run()) {
1357 if (ErrorMsg)
1358 *ErrorMsg = TheLinker.ErrorMsg;
1359 return true;
1360 }
1361 return false;
Rafael Espindolac7c35a92013-05-04 03:48:37 +00001362}
1363
Chris Lattner1afcace2011-07-09 17:41:24 +00001364//===----------------------------------------------------------------------===//
1365// LinkModules entrypoint.
1366//===----------------------------------------------------------------------===//
1367
Bill Wendlingcd7193f2012-03-22 20:28:27 +00001368/// LinkModules - This function links two modules together, with the resulting
Eli Benderskyd25c05e2013-03-08 22:29:44 +00001369/// Dest module modified to be the composite of the two input modules. If an
Bill Wendlingcd7193f2012-03-22 20:28:27 +00001370/// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1371/// the problem. Upon failure, the Dest module could be in a modified state,
1372/// and shouldn't be relied on to be consistent.
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +00001373bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode,
1374 std::string *ErrorMsg) {
Rafael Espindola2e013022013-05-04 04:08:02 +00001375 Linker L(Dest);
1376 return L.linkInModule(Src, Mode, ErrorMsg);
Chris Lattner52f7e902001-10-13 07:03:50 +00001377}
Bill Wendlingf24fde22012-05-09 08:55:40 +00001378
1379//===----------------------------------------------------------------------===//
1380// C API.
1381//===----------------------------------------------------------------------===//
1382
1383LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1384 LLVMLinkerMode Mode, char **OutMessages) {
1385 std::string Messages;
1386 LLVMBool Result = Linker::LinkModules(unwrap(Dest), unwrap(Src),
1387 Mode, OutMessages? &Messages : 0);
1388 if (OutMessages)
1389 *OutMessages = strdup(Messages.c_str());
1390 return Result;
1391}