blob: d2e13c91c4339db2acdd1b68c2ca90a4cb1dbcba [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 {
356 /// ModuleLinker - This is an implementation class for the LinkModules
357 /// function, which is the entrypoint for this file.
358 class ModuleLinker {
359 Module *DstM, *SrcM;
360
361 TypeMapTy TypeMap;
362
363 /// ValueMap - Mapping of values from what they used to be in Src, to what
364 /// they are now in DstM. ValueToValueMapTy is a ValueMap, which involves
365 /// some overhead due to the use of Value handles which the Linker doesn't
366 /// actually need, but this allows us to reuse the ValueMapper code.
367 ValueToValueMapTy ValueMap;
368
369 struct AppendingVarInfo {
370 GlobalVariable *NewGV; // New aggregate global in dest module.
371 Constant *DstInit; // Old initializer from dest module.
372 Constant *SrcInit; // Old initializer from src module.
373 };
374
375 std::vector<AppendingVarInfo> AppendingVars;
376
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000377 unsigned Mode; // Mode to treat source module.
378
379 // Set of items not to link in from source.
380 SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
381
Tanya Lattner9af37a32011-11-02 00:24:56 +0000382 // Vector of functions to lazily link in.
Bill Wendlingd99a29e2013-03-27 17:54:41 +0000383 std::vector<Function*> LazilyLinkFunctions;
Tanya Lattner9af37a32011-11-02 00:24:56 +0000384
Chris Lattner1afcace2011-07-09 17:41:24 +0000385 public:
386 std::string ErrorMsg;
387
Rafael Espindolacfb320f2013-05-04 05:05:18 +0000388 ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM, unsigned mode)
389 : DstM(dstM), SrcM(srcM), TypeMap(Set), Mode(mode) { }
Chris Lattner1afcace2011-07-09 17:41:24 +0000390
391 bool run();
392
393 private:
394 /// emitError - Helper method for setting a message and returning an error
395 /// code.
396 bool emitError(const Twine &Message) {
397 ErrorMsg = Message.str();
Chris Lattnerf6f4f7a2008-06-16 18:27:53 +0000398 return true;
Chris Lattnera4477f92008-06-16 21:17:12 +0000399 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000400
401 /// getLinkageResult - This analyzes the two global values and determines
402 /// what the result will look like in the destination module.
403 bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Rafael Espindola3ed88152012-01-05 23:02:01 +0000404 GlobalValue::LinkageTypes &LT,
405 GlobalValue::VisibilityTypes &Vis,
406 bool &LinkFromSrc);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000407
Chris Lattner1afcace2011-07-09 17:41:24 +0000408 /// getLinkedToGlobal - Given a global in the source module, return the
409 /// global in the destination module that is being linked to, if any.
410 GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
411 // If the source has no name it can't link. If it has local linkage,
412 // there is no name match-up going on.
413 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
414 return 0;
Bill Wendling601c0942012-02-28 04:01:21 +0000415
Chris Lattner1afcace2011-07-09 17:41:24 +0000416 // Otherwise see if we have a match in the destination module's symtab.
417 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
418 if (DGV == 0) return 0;
Bill Wendling601c0942012-02-28 04:01:21 +0000419
Chris Lattner1afcace2011-07-09 17:41:24 +0000420 // If we found a global with the same name in the dest module, but it has
421 // internal linkage, we are really not doing any linkage here.
422 if (DGV->hasLocalLinkage())
423 return 0;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000424
Chris Lattner1afcace2011-07-09 17:41:24 +0000425 // Otherwise, we do in fact link to the destination global.
426 return DGV;
427 }
428
429 void computeTypeMapping();
430
431 bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
432 bool linkGlobalProto(GlobalVariable *SrcGV);
433 bool linkFunctionProto(Function *SrcF);
434 bool linkAliasProto(GlobalAlias *SrcA);
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000435 bool linkModuleFlagsMetadata();
Chris Lattner1afcace2011-07-09 17:41:24 +0000436
437 void linkAppendingVarInit(const AppendingVarInfo &AVI);
438 void linkGlobalInits();
439 void linkFunctionBody(Function *Dst, Function *Src);
440 void linkAliasBodies();
441 void linkNamedMDNodes();
442 };
Bill Wendling601c0942012-02-28 04:01:21 +0000443}
444
Chris Lattner1afcace2011-07-09 17:41:24 +0000445/// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
Reid Spencer8bef0372007-02-04 04:29:21 +0000446/// in the symbol table. This is good for all clients except for us. Go
447/// through the trouble to force this back.
Chris Lattner1afcace2011-07-09 17:41:24 +0000448static void forceRenaming(GlobalValue *GV, StringRef Name) {
449 // If the global doesn't force its name or if it already has the right name,
450 // there is nothing for us to do.
451 if (GV->hasLocalLinkage() || GV->getName() == Name)
452 return;
453
454 Module *M = GV->getParent();
Chris Lattnerc0036282004-08-04 07:05:54 +0000455
456 // If there is a conflict, rename the conflict.
Chris Lattner1afcace2011-07-09 17:41:24 +0000457 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
Chris Lattner33f29492007-02-11 00:39:38 +0000458 GV->takeName(ConflictGV);
459 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Chris Lattner1afcace2011-07-09 17:41:24 +0000460 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
Chris Lattner33f29492007-02-11 00:39:38 +0000461 } else {
462 GV->setName(Name); // Force the name back
Reid Spenceref9b9a72007-02-05 20:47:22 +0000463 }
Reid Spenceref9b9a72007-02-05 20:47:22 +0000464}
Reid Spencer8bef0372007-02-04 04:29:21 +0000465
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000466/// copyGVAttributes - copy additional attributes (those not needed to construct
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000467/// a GlobalValue) from the SrcGV to the DestGV.
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000468static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
Duncan Sands28c3cff2008-05-26 19:58:59 +0000469 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
470 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
471 DestGV->copyAttributesFrom(SrcGV);
472 DestGV->setAlignment(Alignment);
Chris Lattner1afcace2011-07-09 17:41:24 +0000473
474 forceRenaming(DestGV, SrcGV->getName());
Chris Lattnerc0036282004-08-04 07:05:54 +0000475}
476
Rafael Espindola3ed88152012-01-05 23:02:01 +0000477static bool isLessConstraining(GlobalValue::VisibilityTypes a,
478 GlobalValue::VisibilityTypes b) {
479 if (a == GlobalValue::HiddenVisibility)
480 return false;
481 if (b == GlobalValue::HiddenVisibility)
482 return true;
483 if (a == GlobalValue::ProtectedVisibility)
484 return false;
485 if (b == GlobalValue::ProtectedVisibility)
486 return true;
487 return false;
488}
489
Chris Lattner1afcace2011-07-09 17:41:24 +0000490/// getLinkageResult - This analyzes the two global values and determines what
Chris Lattneraee38ea2004-12-03 22:18:41 +0000491/// the result will look like in the destination module. In particular, it
Rafael Espindola3ed88152012-01-05 23:02:01 +0000492/// computes the resultant linkage type and visibility, computes whether the
493/// global in the source should be copied over to the destination (replacing
494/// the existing one), and computes whether this linkage is an error or not.
Chris Lattner1afcace2011-07-09 17:41:24 +0000495bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Rafael Espindola3ed88152012-01-05 23:02:01 +0000496 GlobalValue::LinkageTypes &LT,
497 GlobalValue::VisibilityTypes &Vis,
Chris Lattner1afcace2011-07-09 17:41:24 +0000498 bool &LinkFromSrc) {
499 assert(Dest && "Must have two globals being queried");
500 assert(!Src->hasLocalLinkage() &&
Chris Lattneraee38ea2004-12-03 22:18:41 +0000501 "If Src has internal linkage, Dest shouldn't be set!");
Chris Lattner1afcace2011-07-09 17:41:24 +0000502
Peter Collingbourne88953162011-10-30 17:46:34 +0000503 bool SrcIsDeclaration = Src->isDeclaration() && !Src->isMaterializable();
Chris Lattnerf84c59d2011-07-14 20:23:05 +0000504 bool DestIsDeclaration = Dest->isDeclaration();
Chris Lattner1afcace2011-07-09 17:41:24 +0000505
506 if (SrcIsDeclaration) {
Anton Korobeynikov2b48ef02008-03-10 22:33:22 +0000507 // If Src is external or if both Src & Dest are external.. Just link the
Chris Lattneraee38ea2004-12-03 22:18:41 +0000508 // external globals, we aren't adding anything.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000509 if (Src->hasDLLImportLinkage()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000510 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
Chris Lattner1afcace2011-07-09 17:41:24 +0000511 if (DestIsDeclaration) {
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000512 LinkFromSrc = true;
513 LT = Src->getLinkage();
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000514 }
Andrew Lenharth8753c442006-12-15 17:35:32 +0000515 } else if (Dest->hasExternalWeakLinkage()) {
Duncan Sands667d4b82009-03-07 15:45:40 +0000516 // If the Dest is weak, use the source linkage.
Andrew Lenharth8753c442006-12-15 17:35:32 +0000517 LinkFromSrc = true;
518 LT = Src->getLinkage();
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000519 } else {
520 LinkFromSrc = false;
521 LT = Dest->getLinkage();
522 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000523 } else if (DestIsDeclaration && !Dest->hasDLLImportLinkage()) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000524 // If Dest is external but Src is not:
525 LinkFromSrc = true;
526 LT = Src->getLinkage();
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000527 } else if (Src->isWeakForLinker()) {
Dale Johannesenaafce772008-05-14 20:12:51 +0000528 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
529 // or DLL* linkage.
Chris Lattner266c7bb2009-04-13 05:44:34 +0000530 if (Dest->hasExternalWeakLinkage() ||
531 Dest->hasAvailableExternallyLinkage() ||
532 (Dest->hasLinkOnceLinkage() &&
533 (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000534 LinkFromSrc = true;
535 LT = Src->getLinkage();
536 } else {
537 LinkFromSrc = false;
538 LT = Dest->getLinkage();
539 }
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000540 } else if (Dest->isWeakForLinker()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000541 // At this point we know that Src has External* or DLL* linkage.
542 if (Src->hasExternalWeakLinkage()) {
543 LinkFromSrc = false;
544 LT = Dest->getLinkage();
545 } else {
546 LinkFromSrc = true;
547 LT = GlobalValue::ExternalLinkage;
548 }
Chris Lattneraee38ea2004-12-03 22:18:41 +0000549 } else {
Chris Lattner1afcace2011-07-09 17:41:24 +0000550 assert((Dest->hasExternalLinkage() || Dest->hasDLLImportLinkage() ||
551 Dest->hasDLLExportLinkage() || Dest->hasExternalWeakLinkage()) &&
552 (Src->hasExternalLinkage() || Src->hasDLLImportLinkage() ||
553 Src->hasDLLExportLinkage() || Src->hasExternalWeakLinkage()) &&
Chris Lattneraee38ea2004-12-03 22:18:41 +0000554 "Unexpected linkage type!");
Chris Lattner1afcace2011-07-09 17:41:24 +0000555 return emitError("Linking globals named '" + Src->getName() +
Chris Lattneraee38ea2004-12-03 22:18:41 +0000556 "': symbol multiply defined!");
557 }
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +0000558
Rafael Espindola3ed88152012-01-05 23:02:01 +0000559 // Compute the visibility. We follow the rules in the System V Application
560 // Binary Interface.
561 Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
562 Dest->getVisibility() : Src->getVisibility();
Chris Lattneraee38ea2004-12-03 22:18:41 +0000563 return false;
564}
Chris Lattner5c377c52001-10-14 23:29:15 +0000565
Chris Lattner1afcace2011-07-09 17:41:24 +0000566/// computeTypeMapping - Loop over all of the linked values to compute type
567/// mappings. For example, if we link "extern Foo *x" and "Foo *x = NULL", then
568/// we have two struct types 'Foo' but one got renamed when the module was
569/// loaded into the same LLVMContext.
570void ModuleLinker::computeTypeMapping() {
571 // Incorporate globals.
572 for (Module::global_iterator I = SrcM->global_begin(),
573 E = SrcM->global_end(); I != E; ++I) {
574 GlobalValue *DGV = getLinkedToGlobal(I);
575 if (DGV == 0) continue;
576
577 if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
578 TypeMap.addTypeMapping(DGV->getType(), I->getType());
579 continue;
580 }
581
582 // Unify the element type of appending arrays.
583 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
584 ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
585 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
Devang Patelab67e702009-08-11 18:01:24 +0000586 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000587
588 // Incorporate functions.
589 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
590 if (GlobalValue *DGV = getLinkedToGlobal(I))
591 TypeMap.addTypeMapping(DGV->getType(), I->getType());
592 }
Bill Wendlingc68d1272012-02-27 22:34:19 +0000593
Bill Wendling601c0942012-02-28 04:01:21 +0000594 // Incorporate types by name, scanning all the types in the source module.
595 // At this point, the destination module may have a type "%foo = { i32 }" for
Bill Wendling348e5e72012-02-27 23:48:30 +0000596 // example. When the source module got loaded into the same LLVMContext, if
597 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
Bill Wendling573e9732012-08-03 00:30:35 +0000598 TypeFinder SrcStructTypes;
599 SrcStructTypes.run(*SrcM, true);
Bill Wendling348e5e72012-02-27 23:48:30 +0000600 SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
601 SrcStructTypes.end());
Bill Wendlinga20689f2012-03-23 23:17:38 +0000602
Bill Wendling348e5e72012-02-27 23:48:30 +0000603 for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
604 StructType *ST = SrcStructTypes[i];
605 if (!ST->hasName()) continue;
606
607 // Check to see if there is a dot in the name followed by a digit.
Bill Wendling601c0942012-02-28 04:01:21 +0000608 size_t DotPos = ST->getName().rfind('.');
609 if (DotPos == 0 || DotPos == StringRef::npos ||
Guy Benyei87d0b9e2013-02-12 21:21:59 +0000610 ST->getName().back() == '.' ||
611 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
Bill Wendling601c0942012-02-28 04:01:21 +0000612 continue;
Bill Wendling348e5e72012-02-27 23:48:30 +0000613
614 // Check to see if the destination module has a struct with the prefix name.
Bill Wendling601c0942012-02-28 04:01:21 +0000615 if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
Bill Wendlinga20689f2012-03-23 23:17:38 +0000616 // Don't use it if this actually came from the source module. They're in
617 // the same LLVMContext after all. Also don't use it unless the type is
618 // actually used in the destination module. This can happen in situations
619 // like this:
620 //
621 // Module A Module B
622 // -------- --------
623 // %Z = type { %A } %B = type { %C.1 }
624 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
625 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
626 // %C = type { i8* } %B.3 = type { %C.1 }
627 //
628 // When we link Module B with Module A, the '%B' in Module B is
629 // used. However, that would then use '%C.1'. But when we process '%C.1',
630 // we prefer to take the '%C' version. So we are then left with both
631 // '%C.1' and '%C' being used for the same types. This leads to some
632 // variables using one type and some using the other.
Rafael Espindolacfb320f2013-05-04 05:05:18 +0000633 if (!SrcStructTypesSet.count(DST) && TypeMap.DstStructTypesSet.count(DST))
Bill Wendling348e5e72012-02-27 23:48:30 +0000634 TypeMap.addTypeMapping(DST, ST);
635 }
636
Chris Lattner1afcace2011-07-09 17:41:24 +0000637 // Don't bother incorporating aliases, they aren't generally typed well.
Bill Wendling601c0942012-02-28 04:01:21 +0000638
Chris Lattner1afcace2011-07-09 17:41:24 +0000639 // Now that we have discovered all of the type equivalences, get a body for
640 // any 'opaque' types in the dest module that are now resolved.
641 TypeMap.linkDefinedTypeBodies();
Devang Patelab67e702009-08-11 18:01:24 +0000642}
643
Chris Lattner1afcace2011-07-09 17:41:24 +0000644/// linkAppendingVarProto - If there were any appending global variables, link
645/// them together now. Return true on error.
646bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
647 GlobalVariable *SrcGV) {
Bill Wendling601c0942012-02-28 04:01:21 +0000648
Chris Lattner1afcace2011-07-09 17:41:24 +0000649 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
650 return emitError("Linking globals named '" + SrcGV->getName() +
651 "': can only link appending global with another appending global!");
652
653 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
654 ArrayType *SrcTy =
655 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
656 Type *EltTy = DstTy->getElementType();
657
658 // Check to see that they two arrays agree on type.
659 if (EltTy != SrcTy->getElementType())
660 return emitError("Appending variables with different element types!");
661 if (DstGV->isConstant() != SrcGV->isConstant())
662 return emitError("Appending variables linked with different const'ness!");
663
664 if (DstGV->getAlignment() != SrcGV->getAlignment())
665 return emitError(
666 "Appending variables with different alignment need to be linked!");
667
668 if (DstGV->getVisibility() != SrcGV->getVisibility())
669 return emitError(
670 "Appending variables with different visibility need to be linked!");
671
672 if (DstGV->getSection() != SrcGV->getSection())
673 return emitError(
674 "Appending variables with different section name need to be linked!");
675
676 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
677 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
678
679 // Create the new global variable.
680 GlobalVariable *NG =
681 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
682 DstGV->getLinkage(), /*init*/0, /*name*/"", DstGV,
Hans Wennborgce718ff2012-06-23 11:37:03 +0000683 DstGV->getThreadLocalMode(),
Chris Lattner1afcace2011-07-09 17:41:24 +0000684 DstGV->getType()->getAddressSpace());
685
686 // Propagate alignment, visibility and section info.
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000687 copyGVAttributes(NG, DstGV);
Chris Lattner1afcace2011-07-09 17:41:24 +0000688
689 AppendingVarInfo AVI;
690 AVI.NewGV = NG;
691 AVI.DstInit = DstGV->getInitializer();
692 AVI.SrcInit = SrcGV->getInitializer();
693 AppendingVars.push_back(AVI);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000694
Chris Lattner1afcace2011-07-09 17:41:24 +0000695 // Replace any uses of the two global variables with uses of the new
696 // global.
697 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000698
Chris Lattner1afcace2011-07-09 17:41:24 +0000699 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
700 DstGV->eraseFromParent();
701
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000702 // Track the source variable so we don't try to link it.
703 DoNotLinkFromSource.insert(SrcGV);
704
Chris Lattner1afcace2011-07-09 17:41:24 +0000705 return false;
706}
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000707
Chris Lattner1afcace2011-07-09 17:41:24 +0000708/// linkGlobalProto - Loop through the global variables in the src module and
709/// merge them into the dest module.
710bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
711 GlobalValue *DGV = getLinkedToGlobal(SGV);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000712 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000713
Chris Lattner1afcace2011-07-09 17:41:24 +0000714 if (DGV) {
715 // Concatenation of appending linkage variables is magic and handled later.
716 if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
717 return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
718
719 // Determine whether linkage of these two globals follows the source
720 // module's definition or the destination module's definition.
Chris Lattnerb324bd72006-11-09 05:18:12 +0000721 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000722 GlobalValue::VisibilityTypes NV;
Chris Lattnerb324bd72006-11-09 05:18:12 +0000723 bool LinkFromSrc = false;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000724 if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
Chris Lattneraee38ea2004-12-03 22:18:41 +0000725 return true;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000726 NewVisibility = NV;
Chris Lattner0fec08e2003-04-21 21:07:05 +0000727
Chris Lattner1afcace2011-07-09 17:41:24 +0000728 // If we're not linking from the source, then keep the definition that we
729 // have.
730 if (!LinkFromSrc) {
731 // Special case for const propagation.
732 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
733 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
734 DGVar->setConstant(true);
735
Rafael Espindola3ed88152012-01-05 23:02:01 +0000736 // Set calculated linkage and visibility.
Chris Lattner1afcace2011-07-09 17:41:24 +0000737 DGV->setLinkage(NewLinkage);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000738 DGV->setVisibility(*NewVisibility);
739
Chris Lattner6157e382008-07-14 07:23:24 +0000740 // Make sure to remember this mapping.
Chris Lattner1afcace2011-07-09 17:41:24 +0000741 ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
742
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000743 // Track the source global so that we don't attempt to copy it over when
744 // processing global initializers.
745 DoNotLinkFromSource.insert(SGV);
746
Chris Lattner1afcace2011-07-09 17:41:24 +0000747 return false;
Chris Lattner6157e382008-07-14 07:23:24 +0000748 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000749 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000750
751 // No linking to be performed or linking from the source: simply create an
752 // identical version of the symbol over in the dest module... the
753 // initializer will be filled in later by LinkGlobalInits.
754 GlobalVariable *NewDGV =
755 new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
756 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
757 SGV->getName(), /*insertbefore*/0,
Hans Wennborgce718ff2012-06-23 11:37:03 +0000758 SGV->getThreadLocalMode(),
Chris Lattner1afcace2011-07-09 17:41:24 +0000759 SGV->getType()->getAddressSpace());
760 // Propagate alignment, visibility and section info.
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000761 copyGVAttributes(NewDGV, SGV);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000762 if (NewVisibility)
763 NewDGV->setVisibility(*NewVisibility);
Chris Lattner1afcace2011-07-09 17:41:24 +0000764
765 if (DGV) {
766 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
767 DGV->eraseFromParent();
768 }
769
770 // Make sure to remember this mapping.
771 ValueMap[SGV] = NewDGV;
Chris Lattner5c377c52001-10-14 23:29:15 +0000772 return false;
773}
774
Chris Lattner1afcace2011-07-09 17:41:24 +0000775/// linkFunctionProto - Link the function in the source module into the
776/// destination module if needed, setting up mapping information.
777bool ModuleLinker::linkFunctionProto(Function *SF) {
778 GlobalValue *DGV = getLinkedToGlobal(SF);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000779 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Chris Lattner1afcace2011-07-09 17:41:24 +0000780
781 if (DGV) {
782 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
783 bool LinkFromSrc = false;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000784 GlobalValue::VisibilityTypes NV;
785 if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
Chris Lattner1afcace2011-07-09 17:41:24 +0000786 return true;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000787 NewVisibility = NV;
788
Chris Lattner1afcace2011-07-09 17:41:24 +0000789 if (!LinkFromSrc) {
790 // Set calculated linkage
791 DGV->setLinkage(NewLinkage);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000792 DGV->setVisibility(*NewVisibility);
793
Chris Lattner1afcace2011-07-09 17:41:24 +0000794 // Make sure to remember this mapping.
795 ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
796
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000797 // Track the function from the source module so we don't attempt to remap
798 // it.
799 DoNotLinkFromSource.insert(SF);
800
Chris Lattner1afcace2011-07-09 17:41:24 +0000801 return false;
802 }
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000803 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000804
805 // If there is no linkage to be performed or we are linking from the source,
806 // bring SF over.
807 Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
808 SF->getLinkage(), SF->getName(), DstM);
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000809 copyGVAttributes(NewDF, SF);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000810 if (NewVisibility)
811 NewDF->setVisibility(*NewVisibility);
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000812
Chris Lattner1afcace2011-07-09 17:41:24 +0000813 if (DGV) {
814 // Any uses of DF need to change to NewDF, with cast.
815 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
816 DGV->eraseFromParent();
Bill Wendlingd99a29e2013-03-27 17:54:41 +0000817 } else {
818 // Internal, LO_ODR, or LO linkage - stick in set to ignore and lazily link.
819 if (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
820 SF->hasAvailableExternallyLinkage()) {
821 DoNotLinkFromSource.insert(SF);
822 LazilyLinkFunctions.push_back(SF);
823 }
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000824 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000825
826 ValueMap[SF] = NewDF;
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000827 return false;
828}
829
Chris Lattner1afcace2011-07-09 17:41:24 +0000830/// LinkAliasProto - Set up prototypes for any aliases that come over from the
831/// source module.
832bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
833 GlobalValue *DGV = getLinkedToGlobal(SGA);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000834 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
835
Chris Lattner1afcace2011-07-09 17:41:24 +0000836 if (DGV) {
837 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000838 GlobalValue::VisibilityTypes NV;
Chris Lattner1afcace2011-07-09 17:41:24 +0000839 bool LinkFromSrc = false;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000840 if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
Chris Lattner1afcace2011-07-09 17:41:24 +0000841 return true;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000842 NewVisibility = NV;
843
Chris Lattner1afcace2011-07-09 17:41:24 +0000844 if (!LinkFromSrc) {
845 // Set calculated linkage.
846 DGV->setLinkage(NewLinkage);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000847 DGV->setVisibility(*NewVisibility);
848
Chris Lattner1afcace2011-07-09 17:41:24 +0000849 // Make sure to remember this mapping.
850 ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
851
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000852 // Track the alias from the source module so we don't attempt to remap it.
853 DoNotLinkFromSource.insert(SGA);
854
Chris Lattner1afcace2011-07-09 17:41:24 +0000855 return false;
856 }
857 }
858
859 // If there is no linkage to be performed or we're linking from the source,
860 // bring over SGA.
861 GlobalAlias *NewDA = new GlobalAlias(TypeMap.get(SGA->getType()),
862 SGA->getLinkage(), SGA->getName(),
863 /*aliasee*/0, DstM);
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000864 copyGVAttributes(NewDA, SGA);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000865 if (NewVisibility)
866 NewDA->setVisibility(*NewVisibility);
Chris Lattner5c377c52001-10-14 23:29:15 +0000867
Chris Lattner1afcace2011-07-09 17:41:24 +0000868 if (DGV) {
869 // Any uses of DGV need to change to NewDA, with cast.
870 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
871 DGV->eraseFromParent();
872 }
873
874 ValueMap[SGA] = NewDA;
875 return false;
876}
877
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000878static void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000879 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
880
881 for (unsigned i = 0; i != NumElements; ++i)
882 Dest.push_back(C->getAggregateElement(i));
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000883}
884
Chris Lattner1afcace2011-07-09 17:41:24 +0000885void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
886 // Merge the initializer.
887 SmallVector<Constant*, 16> Elements;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000888 getArrayElements(AVI.DstInit, Elements);
Chris Lattner1afcace2011-07-09 17:41:24 +0000889
890 Constant *SrcInit = MapValue(AVI.SrcInit, ValueMap, RF_None, &TypeMap);
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000891 getArrayElements(SrcInit, Elements);
892
Chris Lattner1afcace2011-07-09 17:41:24 +0000893 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
894 AVI.NewGV->setInitializer(ConstantArray::get(NewType, Elements));
895}
896
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000897/// linkGlobalInits - Update the initializers in the Dest module now that all
898/// globals that may be referenced are in Dest.
Chris Lattner1afcace2011-07-09 17:41:24 +0000899void ModuleLinker::linkGlobalInits() {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000900 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattner1afcace2011-07-09 17:41:24 +0000901 for (Module::const_global_iterator I = SrcM->global_begin(),
902 E = SrcM->global_end(); I != E; ++I) {
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000903
904 // Only process initialized GV's or ones not already in dest.
905 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
Chris Lattner1afcace2011-07-09 17:41:24 +0000906
907 // Grab destination global variable.
908 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
909 // Figure out what the initializer looks like in the dest module.
910 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
911 RF_None, &TypeMap));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000912 }
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000913}
Chris Lattner5c377c52001-10-14 23:29:15 +0000914
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000915/// linkFunctionBody - Copy the source function over into the dest function and
916/// fix up references to values. At this point we know that Dest is an external
917/// function, and that Src is not.
Chris Lattner1afcace2011-07-09 17:41:24 +0000918void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
919 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
Chris Lattner5c377c52001-10-14 23:29:15 +0000920
Chris Lattner0033baf2004-11-16 17:12:38 +0000921 // Go through and convert function arguments over, remembering the mapping.
Chris Lattner1afcace2011-07-09 17:41:24 +0000922 Function::arg_iterator DI = Dst->arg_begin();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000923 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
Chris Lattner69da5cf2002-10-13 20:57:00 +0000924 I != E; ++I, ++DI) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000925 DI->setName(I->getName()); // Copy the name over.
Chris Lattner5c377c52001-10-14 23:29:15 +0000926
Chris Lattner1afcace2011-07-09 17:41:24 +0000927 // Add a mapping to our mapping.
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000928 ValueMap[I] = DI;
Chris Lattner5c377c52001-10-14 23:29:15 +0000929 }
930
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000931 if (Mode == Linker::DestroySource) {
932 // Splice the body of the source function into the dest function.
933 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
934
935 // At this point, all of the instructions and values of the function are now
936 // copied over. The only problem is that they are still referencing values in
937 // the Source function as operands. Loop through all of the operands of the
938 // functions and patch them up to point to the local versions.
939 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
940 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
941 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap);
942
943 } else {
944 // Clone the body of the function into the dest function.
945 SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
Mon P Wangd24397a2011-12-23 02:18:32 +0000946 CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", NULL, &TypeMap);
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000947 }
948
Chris Lattner0033baf2004-11-16 17:12:38 +0000949 // There is no need to map the arguments anymore.
Chris Lattner11273152006-06-16 01:24:04 +0000950 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
951 I != E; ++I)
Reid Spenceref9b9a72007-02-05 20:47:22 +0000952 ValueMap.erase(I);
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000953
Chris Lattner5c377c52001-10-14 23:29:15 +0000954}
955
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000956/// linkAliasBodies - Insert all of the aliases in Src into the Dest module.
Chris Lattner1afcace2011-07-09 17:41:24 +0000957void ModuleLinker::linkAliasBodies() {
958 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000959 I != E; ++I) {
960 if (DoNotLinkFromSource.count(I))
961 continue;
Chris Lattner1afcace2011-07-09 17:41:24 +0000962 if (Constant *Aliasee = I->getAliasee()) {
963 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
964 DA->setAliasee(MapValue(Aliasee, ValueMap, RF_None, &TypeMap));
David Chisnall34722462010-01-09 16:27:31 +0000965 }
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000966 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000967}
Anton Korobeynikov9f2ee702008-03-05 23:21:39 +0000968
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000969/// linkNamedMDNodes - Insert all of the named MDNodes in Src into the Dest
Chris Lattner1afcace2011-07-09 17:41:24 +0000970/// module.
971void ModuleLinker::linkNamedMDNodes() {
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000972 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
Chris Lattner1afcace2011-07-09 17:41:24 +0000973 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
974 E = SrcM->named_metadata_end(); I != E; ++I) {
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000975 // Don't link module flags here. Do them separately.
976 if (&*I == SrcModFlags) continue;
Chris Lattner1afcace2011-07-09 17:41:24 +0000977 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
978 // Add Src elements into Dest node.
979 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
980 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
981 RF_None, &TypeMap));
982 }
983}
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000984
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000985/// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest
986/// module.
987bool ModuleLinker::linkModuleFlagsMetadata() {
Daniel Dunbar1e081652013-01-16 18:39:23 +0000988 // If the source module has no module flags, we are done.
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000989 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
990 if (!SrcModFlags) return false;
991
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000992 // If the destination module doesn't have module flags yet, then just copy
993 // over the source module's flags.
Daniel Dunbar1e081652013-01-16 18:39:23 +0000994 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000995 if (DstModFlags->getNumOperands() == 0) {
996 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
997 DstModFlags->addOperand(SrcModFlags->getOperand(I));
998
999 return false;
1000 }
1001
Daniel Dunbar1e081652013-01-16 18:39:23 +00001002 // First build a map of the existing module flags and requirements.
1003 DenseMap<MDString*, MDNode*> Flags;
1004 SmallSetVector<MDNode*, 16> Requirements;
1005 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1006 MDNode *Op = DstModFlags->getOperand(I);
1007 ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1008 MDString *ID = cast<MDString>(Op->getOperand(1));
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001009
Daniel Dunbar1e081652013-01-16 18:39:23 +00001010 if (Behavior->getZExtValue() == Module::Require) {
1011 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1012 } else {
1013 Flags[ID] = Op;
1014 }
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001015 }
1016
Daniel Dunbar1e081652013-01-16 18:39:23 +00001017 // Merge in the flags from the source module, and also collect its set of
1018 // requirements.
1019 bool HasErr = false;
1020 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1021 MDNode *SrcOp = SrcModFlags->getOperand(I);
1022 ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1023 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1024 MDNode *DstOp = Flags.lookup(ID);
1025 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001026
Daniel Dunbar1e081652013-01-16 18:39:23 +00001027 // If this is a requirement, add it and continue.
1028 if (SrcBehaviorValue == Module::Require) {
1029 // If the destination module does not already have this requirement, add
1030 // it.
1031 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1032 DstModFlags->addOperand(SrcOp);
1033 }
1034 continue;
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001035 }
1036
Daniel Dunbar1e081652013-01-16 18:39:23 +00001037 // If there is no existing flag with this ID, just add it.
1038 if (!DstOp) {
1039 Flags[ID] = SrcOp;
1040 DstModFlags->addOperand(SrcOp);
1041 continue;
1042 }
1043
1044 // Otherwise, perform a merge.
1045 ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1046 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1047
1048 // If either flag has override behavior, handle it first.
1049 if (DstBehaviorValue == Module::Override) {
1050 // Diagnose inconsistent flags which both have override behavior.
1051 if (SrcBehaviorValue == Module::Override &&
1052 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1053 HasErr |= emitError("linking module flags '" + ID->getString() +
1054 "': IDs have conflicting override values");
1055 }
1056 continue;
1057 } else if (SrcBehaviorValue == Module::Override) {
1058 // Update the destination flag to that of the source.
1059 DstOp->replaceOperandWith(0, SrcBehavior);
1060 DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1061 continue;
1062 }
1063
1064 // Diagnose inconsistent merge behavior types.
1065 if (SrcBehaviorValue != DstBehaviorValue) {
1066 HasErr |= emitError("linking module flags '" + ID->getString() +
1067 "': IDs have conflicting behaviors");
1068 continue;
1069 }
1070
1071 // Perform the merge for standard behavior types.
1072 switch (SrcBehaviorValue) {
1073 case Module::Require:
1074 case Module::Override: assert(0 && "not possible"); break;
1075 case Module::Error: {
1076 // Emit an error if the values differ.
1077 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1078 HasErr |= emitError("linking module flags '" + ID->getString() +
1079 "': IDs have conflicting values");
1080 }
1081 continue;
1082 }
1083 case Module::Warning: {
1084 // Emit a warning if the values differ.
1085 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1086 errs() << "WARNING: linking module flags '" << ID->getString()
1087 << "': IDs have conflicting values";
1088 }
1089 continue;
1090 }
Daniel Dunbar5db391c2013-01-16 21:38:56 +00001091 case Module::Append: {
1092 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1093 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1094 unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1095 Value **VP, **Values = VP = new Value*[NumOps];
1096 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1097 *VP = DstValue->getOperand(i);
1098 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1099 *VP = SrcValue->getOperand(i);
1100 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1101 ArrayRef<Value*>(Values,
1102 NumOps)));
1103 delete[] Values;
1104 break;
1105 }
1106 case Module::AppendUnique: {
1107 SmallSetVector<Value*, 16> Elts;
1108 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1109 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1110 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1111 Elts.insert(DstValue->getOperand(i));
1112 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1113 Elts.insert(SrcValue->getOperand(i));
1114 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1115 ArrayRef<Value*>(Elts.begin(),
1116 Elts.end())));
1117 break;
1118 }
Daniel Dunbar1e081652013-01-16 18:39:23 +00001119 }
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001120 }
1121
Daniel Dunbar1e081652013-01-16 18:39:23 +00001122 // Check all of the requirements.
1123 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1124 MDNode *Requirement = Requirements[I];
1125 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1126 Value *ReqValue = Requirement->getOperand(1);
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001127
Daniel Dunbar1e081652013-01-16 18:39:23 +00001128 MDNode *Op = Flags[Flag];
1129 if (!Op || Op->getOperand(2) != ReqValue) {
1130 HasErr |= emitError("linking module flags '" + Flag->getString() +
1131 "': does not have the required value");
1132 continue;
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001133 }
1134 }
1135
1136 return HasErr;
1137}
Chris Lattner1afcace2011-07-09 17:41:24 +00001138
1139bool ModuleLinker::run() {
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001140 assert(DstM && "Null destination module");
1141 assert(SrcM && "Null source module");
Chris Lattner1afcace2011-07-09 17:41:24 +00001142
1143 // Inherit the target data from the source module if the destination module
1144 // doesn't have one already.
1145 if (DstM->getDataLayout().empty() && !SrcM->getDataLayout().empty())
1146 DstM->setDataLayout(SrcM->getDataLayout());
1147
1148 // Copy the target triple from the source to dest if the dest's is empty.
1149 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1150 DstM->setTargetTriple(SrcM->getTargetTriple());
1151
1152 if (!SrcM->getDataLayout().empty() && !DstM->getDataLayout().empty() &&
1153 SrcM->getDataLayout() != DstM->getDataLayout())
1154 errs() << "WARNING: Linking two modules of different data layouts!\n";
1155 if (!SrcM->getTargetTriple().empty() &&
1156 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1157 errs() << "WARNING: Linking two modules of different target triples: ";
1158 if (!SrcM->getModuleIdentifier().empty())
1159 errs() << SrcM->getModuleIdentifier() << ": ";
1160 errs() << "'" << SrcM->getTargetTriple() << "' and '"
1161 << DstM->getTargetTriple() << "'\n";
1162 }
1163
1164 // Append the module inline asm string.
1165 if (!SrcM->getModuleInlineAsm().empty()) {
1166 if (DstM->getModuleInlineAsm().empty())
1167 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1168 else
1169 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1170 SrcM->getModuleInlineAsm());
1171 }
1172
Chris Lattner1afcace2011-07-09 17:41:24 +00001173 // Loop over all of the linked values to compute type mappings.
1174 computeTypeMapping();
1175
1176 // Insert all of the globals in src into the DstM module... without linking
1177 // initializers (which could refer to functions not yet mapped over).
1178 for (Module::global_iterator I = SrcM->global_begin(),
1179 E = SrcM->global_end(); I != E; ++I)
1180 if (linkGlobalProto(I))
1181 return true;
1182
1183 // Link the functions together between the two modules, without doing function
1184 // bodies... this just adds external function prototypes to the DstM
1185 // function... We do this so that when we begin processing function bodies,
1186 // all of the global values that may be referenced are available in our
1187 // ValueMap.
1188 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1189 if (linkFunctionProto(I))
1190 return true;
1191
1192 // If there were any aliases, link them now.
1193 for (Module::alias_iterator I = SrcM->alias_begin(),
1194 E = SrcM->alias_end(); I != E; ++I)
1195 if (linkAliasProto(I))
1196 return true;
1197
1198 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1199 linkAppendingVarInit(AppendingVars[i]);
1200
1201 // Update the initializers in the DstM module now that all globals that may
1202 // be referenced are in DstM.
1203 linkGlobalInits();
1204
1205 // Link in the function bodies that are defined in the source module into
1206 // DstM.
1207 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
Tanya Lattner2b28a742011-10-14 22:17:46 +00001208 // Skip if not linking from source.
1209 if (DoNotLinkFromSource.count(SF)) continue;
1210
1211 // Skip if no body (function is external) or materialize.
1212 if (SF->isDeclaration()) {
1213 if (!SF->isMaterializable())
1214 continue;
1215 if (SF->Materialize(&ErrorMsg))
1216 return true;
1217 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001218
1219 linkFunctionBody(cast<Function>(ValueMap[SF]), SF);
Bill Wendling208b6f62012-03-23 07:22:49 +00001220 SF->Dematerialize();
Chris Lattner1afcace2011-07-09 17:41:24 +00001221 }
1222
1223 // Resolve all uses of aliases with aliasees.
1224 linkAliasBodies();
1225
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001226 // Remap all of the named MDNodes in Src into the DstM module. We do this
Devang Patel211da8f2011-08-04 19:44:28 +00001227 // after linking GlobalValues so that MDNodes that reference GlobalValues
1228 // are properly remapped.
1229 linkNamedMDNodes();
1230
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001231 // Merge the module flags into the DstM module.
1232 if (linkModuleFlagsMetadata())
1233 return true;
1234
Tanya Lattner9af37a32011-11-02 00:24:56 +00001235 // Process vector of lazily linked in functions.
1236 bool LinkedInAnyFunctions;
1237 do {
1238 LinkedInAnyFunctions = false;
1239
Bill Wendlingd99a29e2013-03-27 17:54:41 +00001240 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1241 E = LazilyLinkFunctions.end(); I != E; ++I) {
1242 if (!*I)
Tanya Lattner9af37a32011-11-02 00:24:56 +00001243 continue;
1244
Bill Wendlingd99a29e2013-03-27 17:54:41 +00001245 Function *SF = *I;
1246 Function *DF = cast<Function>(ValueMap[SF]);
1247
1248 if (!DF->use_empty()) {
1249
Tanya Lattner9af37a32011-11-02 00:24:56 +00001250 // Materialize if necessary.
1251 if (SF->isDeclaration()) {
1252 if (!SF->isMaterializable())
1253 continue;
1254 if (SF->Materialize(&ErrorMsg))
1255 return true;
1256 }
1257
1258 // Link in function body.
1259 linkFunctionBody(DF, SF);
Bill Wendling208b6f62012-03-23 07:22:49 +00001260 SF->Dematerialize();
1261
Tanya Lattner9af37a32011-11-02 00:24:56 +00001262 // "Remove" from vector by setting the element to 0.
Bill Wendlingd99a29e2013-03-27 17:54:41 +00001263 *I = 0;
Tanya Lattner9af37a32011-11-02 00:24:56 +00001264
1265 // Set flag to indicate we may have more functions to lazily link in
1266 // since we linked in a function.
1267 LinkedInAnyFunctions = true;
1268 }
1269 }
1270 } while (LinkedInAnyFunctions);
1271
Bill Wendlingd99a29e2013-03-27 17:54:41 +00001272 // Remove any prototypes of functions that were not actually linked in.
1273 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1274 E = LazilyLinkFunctions.end(); I != E; ++I) {
1275 if (!*I)
1276 continue;
1277
1278 Function *SF = *I;
1279 Function *DF = cast<Function>(ValueMap[SF]);
1280 if (DF->use_empty())
1281 DF->eraseFromParent();
1282 }
1283
Chris Lattner1afcace2011-07-09 17:41:24 +00001284 // Now that all of the types from the source are used, resolve any structs
1285 // copied over to the dest that didn't exist there.
1286 TypeMap.linkDefinedTypeBodies();
1287
Anton Korobeynikov9f2ee702008-03-05 23:21:39 +00001288 return false;
1289}
Chris Lattner52f7e902001-10-13 07:03:50 +00001290
Rafael Espindolacfb320f2013-05-04 05:05:18 +00001291Linker::Linker(Module *M) : Composite(M) {
1292 TypeFinder StructTypes;
1293 StructTypes.run(*M, true);
1294 IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end());
1295}
Rafael Espindolac7c35a92013-05-04 03:48:37 +00001296
1297Linker::~Linker() {
1298}
1299
1300bool Linker::linkInModule(Module *Src, unsigned Mode, std::string *ErrorMsg) {
Rafael Espindolacfb320f2013-05-04 05:05:18 +00001301 ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src, Mode);
Rafael Espindola2e013022013-05-04 04:08:02 +00001302 if (TheLinker.run()) {
1303 if (ErrorMsg)
1304 *ErrorMsg = TheLinker.ErrorMsg;
1305 return true;
1306 }
1307 return false;
Rafael Espindolac7c35a92013-05-04 03:48:37 +00001308}
1309
Chris Lattner1afcace2011-07-09 17:41:24 +00001310//===----------------------------------------------------------------------===//
1311// LinkModules entrypoint.
1312//===----------------------------------------------------------------------===//
1313
Bill Wendlingcd7193f2012-03-22 20:28:27 +00001314/// LinkModules - This function links two modules together, with the resulting
Eli Benderskyd25c05e2013-03-08 22:29:44 +00001315/// Dest module modified to be the composite of the two input modules. If an
Bill Wendlingcd7193f2012-03-22 20:28:27 +00001316/// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1317/// the problem. Upon failure, the Dest module could be in a modified state,
1318/// and shouldn't be relied on to be consistent.
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +00001319bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode,
1320 std::string *ErrorMsg) {
Rafael Espindola2e013022013-05-04 04:08:02 +00001321 Linker L(Dest);
1322 return L.linkInModule(Src, Mode, ErrorMsg);
Chris Lattner52f7e902001-10-13 07:03:50 +00001323}
Bill Wendlingf24fde22012-05-09 08:55:40 +00001324
1325//===----------------------------------------------------------------------===//
1326// C API.
1327//===----------------------------------------------------------------------===//
1328
1329LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1330 LLVMLinkerMode Mode, char **OutMessages) {
1331 std::string Messages;
1332 LLVMBool Result = Linker::LinkModules(unwrap(Dest), unwrap(Src),
1333 Mode, OutMessages? &Messages : 0);
1334 if (OutMessages)
1335 *OutMessages = strdup(Messages.c_str());
1336 return Result;
1337}