blob: e2ec02243773e8256ce1d1b5e1d60edbd7fa51ea [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"
Chris Lattneradbc0b52003-11-20 18:23:14 +000015#include "llvm/Constants.h"
16#include "llvm/DerivedTypes.h"
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +000017#include "llvm/Instructions.h"
Chris Lattner5c377c52001-10-14 23:29:15 +000018#include "llvm/Module.h"
Bill Wendlingd34cb1e2012-02-11 11:38:06 +000019#include "llvm/ADT/DenseSet.h"
Rafael Espindola3ed88152012-01-05 23:02:01 +000020#include "llvm/ADT/Optional.h"
Bill Wendlingd34cb1e2012-02-11 11:38:06 +000021#include "llvm/ADT/SetVector.h"
22#include "llvm/ADT/SmallPtrSet.h"
Bill Wendlingcd7193f2012-03-22 20:28:27 +000023#include "llvm/Support/Debug.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000024#include "llvm/Support/Path.h"
Bill Wendlingcd7193f2012-03-22 20:28:27 +000025#include "llvm/Support/raw_ostream.h"
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +000026#include "llvm/Transforms/Utils/Cloning.h"
Dan Gohman05ea54e2010-08-24 18:50:07 +000027#include "llvm/Transforms/Utils/ValueMapper.h"
Duncan Sands0aaf2f62012-03-03 09:36:58 +000028#include <cctype>
Chris Lattnerf7703df2004-01-09 06:12:26 +000029using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000030
Chris Lattner1afcace2011-07-09 17:41:24 +000031//===----------------------------------------------------------------------===//
32// TypeMap implementation.
33//===----------------------------------------------------------------------===//
Chris Lattner5c377c52001-10-14 23:29:15 +000034
Chris Lattner62a81a12008-06-16 21:00:18 +000035namespace {
Chris Lattner1afcace2011-07-09 17:41:24 +000036class TypeMapTy : public ValueMapTypeRemapper {
37 /// MappedTypes - This is a mapping from a source type to a destination type
38 /// to use.
39 DenseMap<Type*, Type*> MappedTypes;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +000040
Chris Lattner1afcace2011-07-09 17:41:24 +000041 /// SpeculativeTypes - When checking to see if two subgraphs are isomorphic,
42 /// we speculatively add types to MappedTypes, but keep track of them here in
43 /// case we need to roll back.
44 SmallVector<Type*, 16> SpeculativeTypes;
45
Chris Lattner68910502011-12-20 00:03:52 +000046 /// SrcDefinitionsToResolve - This is a list of non-opaque structs in the
47 /// source module that are mapped to an opaque struct in the destination
48 /// module.
49 SmallVector<StructType*, 16> SrcDefinitionsToResolve;
50
51 /// DstResolvedOpaqueTypes - This is the set of opaque types in the
52 /// destination modules who are getting a body from the source module.
53 SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
Bill Wendling6d6c6d72012-03-22 20:30:41 +000054
Chris Lattnerfc196f92008-06-16 23:06:51 +000055public:
Chris Lattner1afcace2011-07-09 17:41:24 +000056 /// addTypeMapping - Indicate that the specified type in the destination
57 /// module is conceptually equivalent to the specified type in the source
58 /// module.
59 void addTypeMapping(Type *DstTy, Type *SrcTy);
60
61 /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
62 /// module from a type definition in the source module.
63 void linkDefinedTypeBodies();
64
65 /// get - Return the mapped type to use for the specified input type from the
66 /// source module.
67 Type *get(Type *SrcTy);
68
69 FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*)T));}
70
Bill Wendlingcd7193f2012-03-22 20:28:27 +000071 /// dump - Dump out the type map for debugging purposes.
72 void dump() const {
73 for (DenseMap<Type*, Type*>::const_iterator
74 I = MappedTypes.begin(), E = MappedTypes.end(); I != E; ++I) {
75 dbgs() << "TypeMap: ";
76 I->first->dump();
77 dbgs() << " => ";
78 I->second->dump();
79 dbgs() << '\n';
80 }
81 }
Bill Wendlingcd7193f2012-03-22 20:28:27 +000082
Chris Lattner1afcace2011-07-09 17:41:24 +000083private:
84 Type *getImpl(Type *T);
85 /// remapType - Implement the ValueMapTypeRemapper interface.
86 Type *remapType(Type *SrcTy) {
87 return get(SrcTy);
Chris Lattner62a81a12008-06-16 21:00:18 +000088 }
Chris Lattner1afcace2011-07-09 17:41:24 +000089
90 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
Chris Lattner62a81a12008-06-16 21:00:18 +000091};
92}
93
Chris Lattner1afcace2011-07-09 17:41:24 +000094void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
95 Type *&Entry = MappedTypes[SrcTy];
96 if (Entry) return;
97
98 if (DstTy == SrcTy) {
99 Entry = DstTy;
100 return;
101 }
Bill Wendling601c0942012-02-28 04:01:21 +0000102
Chris Lattner1afcace2011-07-09 17:41:24 +0000103 // Check to see if these types are recursively isomorphic and establish a
104 // mapping between them if so.
Bill Wendling601c0942012-02-28 04:01:21 +0000105 if (!areTypesIsomorphic(DstTy, SrcTy)) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000106 // Oops, they aren't isomorphic. Just discard this request by rolling out
107 // any speculative mappings we've established.
108 for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i)
109 MappedTypes.erase(SpeculativeTypes[i]);
Bill Wendling601c0942012-02-28 04:01:21 +0000110 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000111 SpeculativeTypes.clear();
112}
Chris Lattner62a81a12008-06-16 21:00:18 +0000113
Chris Lattner1afcace2011-07-09 17:41:24 +0000114/// areTypesIsomorphic - Recursively walk this pair of types, returning true
115/// if they are isomorphic, false if they are not.
116bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
117 // Two types with differing kinds are clearly not isomorphic.
118 if (DstTy->getTypeID() != SrcTy->getTypeID()) return false;
Misha Brukmanf976c852005-04-21 22:55:34 +0000119
Chris Lattner1afcace2011-07-09 17:41:24 +0000120 // If we have an entry in the MappedTypes table, then we have our answer.
121 Type *&Entry = MappedTypes[SrcTy];
122 if (Entry)
123 return Entry == DstTy;
Misha Brukmanf976c852005-04-21 22:55:34 +0000124
Chris Lattner1afcace2011-07-09 17:41:24 +0000125 // Two identical types are clearly isomorphic. Remember this
126 // non-speculatively.
127 if (DstTy == SrcTy) {
128 Entry = DstTy;
Chris Lattner56539652008-06-16 20:03:01 +0000129 return true;
Chris Lattner1afcace2011-07-09 17:41:24 +0000130 }
Bill Wendling601c0942012-02-28 04:01:21 +0000131
Chris Lattner1afcace2011-07-09 17:41:24 +0000132 // Okay, we have two types with identical kinds that we haven't seen before.
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000133
Chris Lattner1afcace2011-07-09 17:41:24 +0000134 // If this is an opaque struct type, special case it.
135 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
136 // Mapping an opaque type to any struct, just keep the dest struct.
137 if (SSTy->isOpaque()) {
138 Entry = DstTy;
139 SpeculativeTypes.push_back(SrcTy);
Chris Lattner43f4ba82003-08-22 19:12:55 +0000140 return true;
Chris Lattnera4477f92008-06-16 21:17:12 +0000141 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000142
Chris Lattner68910502011-12-20 00:03:52 +0000143 // Mapping a non-opaque source type to an opaque dest. If this is the first
144 // type that we're mapping onto this destination type then we succeed. Keep
145 // the dest, but fill it in later. This doesn't need to be speculative. If
146 // this is the second (different) type that we're trying to map onto the
147 // same opaque type then we fail.
Chris Lattner1afcace2011-07-09 17:41:24 +0000148 if (cast<StructType>(DstTy)->isOpaque()) {
Chris Lattner68910502011-12-20 00:03:52 +0000149 // We can only map one source type onto the opaque destination type.
150 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)))
151 return false;
152 SrcDefinitionsToResolve.push_back(SSTy);
Chris Lattner1afcace2011-07-09 17:41:24 +0000153 Entry = DstTy;
Chris Lattner1afcace2011-07-09 17:41:24 +0000154 return true;
155 }
156 }
157
158 // If the number of subtypes disagree between the two types, then we fail.
159 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
Chris Lattnere76c57a2003-08-22 06:07:12 +0000160 return false;
Chris Lattner1afcace2011-07-09 17:41:24 +0000161
162 // Fail if any of the extra properties (e.g. array size) of the type disagree.
163 if (isa<IntegerType>(DstTy))
164 return false; // bitwidth disagrees.
165 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
166 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
167 return false;
Chris Lattner1a31f3b2011-12-20 23:14:57 +0000168
Chris Lattner1afcace2011-07-09 17:41:24 +0000169 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
170 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
171 return false;
172 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
173 StructType *SSTy = cast<StructType>(SrcTy);
Chris Lattner1bcbf852011-08-12 18:07:26 +0000174 if (DSTy->isLiteral() != SSTy->isLiteral() ||
Chris Lattner1afcace2011-07-09 17:41:24 +0000175 DSTy->isPacked() != SSTy->isPacked())
176 return false;
177 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
178 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
179 return false;
180 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
181 if (DVTy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
182 return false;
Chris Lattnere76c57a2003-08-22 06:07:12 +0000183 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000184
185 // Otherwise, we speculate that these two types will line up and recursively
186 // check the subelements.
187 Entry = DstTy;
188 SpeculativeTypes.push_back(SrcTy);
189
Bill Wendling601c0942012-02-28 04:01:21 +0000190 for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i)
191 if (!areTypesIsomorphic(DstTy->getContainedType(i),
192 SrcTy->getContainedType(i)))
Chris Lattner1afcace2011-07-09 17:41:24 +0000193 return false;
194
195 // If everything seems to have lined up, then everything is great.
196 return true;
197}
198
199/// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
200/// module from a type definition in the source module.
201void TypeMapTy::linkDefinedTypeBodies() {
202 SmallVector<Type*, 16> Elements;
203 SmallString<16> TmpName;
204
205 // Note that processing entries in this loop (calling 'get') can add new
Chris Lattner68910502011-12-20 00:03:52 +0000206 // entries to the SrcDefinitionsToResolve vector.
207 while (!SrcDefinitionsToResolve.empty()) {
208 StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val();
Chris Lattner1afcace2011-07-09 17:41:24 +0000209 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
210
211 // TypeMap is a many-to-one mapping, if there were multiple types that
212 // provide a body for DstSTy then previous iterations of this loop may have
213 // already handled it. Just ignore this case.
214 if (!DstSTy->isOpaque()) continue;
215 assert(!SrcSTy->isOpaque() && "Not resolving a definition?");
216
217 // Map the body of the source type over to a new body for the dest type.
218 Elements.resize(SrcSTy->getNumElements());
219 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
220 Elements[i] = getImpl(SrcSTy->getElementType(i));
221
222 DstSTy->setBody(Elements, SrcSTy->isPacked());
223
224 // If DstSTy has no name or has a longer name than STy, then viciously steal
225 // STy's name.
226 if (!SrcSTy->hasName()) continue;
227 StringRef SrcName = SrcSTy->getName();
228
229 if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
230 TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
231 SrcSTy->setName("");
232 DstSTy->setName(TmpName.str());
233 TmpName.clear();
234 }
235 }
Chris Lattner68910502011-12-20 00:03:52 +0000236
237 DstResolvedOpaqueTypes.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000238}
239
Bill Wendling601c0942012-02-28 04:01:21 +0000240
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.
333 if (STy->isOpaque())
334 return *Entry = STy;
Bill Wendling601c0942012-02-28 04:01:21 +0000335
Chris Lattner1afcace2011-07-09 17:41:24 +0000336 // Otherwise we create a new type and resolve its body later. This will be
337 // resolved by the top level of get().
Chris Lattner68910502011-12-20 00:03:52 +0000338 SrcDefinitionsToResolve.push_back(STy);
339 StructType *DTy = StructType::create(STy->getContext());
340 DstResolvedOpaqueTypes.insert(DTy);
341 return *Entry = DTy;
Chris Lattner1afcace2011-07-09 17:41:24 +0000342}
343
Bill Wendling601c0942012-02-28 04:01:21 +0000344
345
Chris Lattner1afcace2011-07-09 17:41:24 +0000346//===----------------------------------------------------------------------===//
347// ModuleLinker implementation.
348//===----------------------------------------------------------------------===//
349
350namespace {
351 /// ModuleLinker - This is an implementation class for the LinkModules
352 /// function, which is the entrypoint for this file.
353 class ModuleLinker {
354 Module *DstM, *SrcM;
355
356 TypeMapTy TypeMap;
357
358 /// ValueMap - Mapping of values from what they used to be in Src, to what
359 /// they are now in DstM. ValueToValueMapTy is a ValueMap, which involves
360 /// some overhead due to the use of Value handles which the Linker doesn't
361 /// actually need, but this allows us to reuse the ValueMapper code.
362 ValueToValueMapTy ValueMap;
363
364 struct AppendingVarInfo {
365 GlobalVariable *NewGV; // New aggregate global in dest module.
366 Constant *DstInit; // Old initializer from dest module.
367 Constant *SrcInit; // Old initializer from src module.
368 };
369
370 std::vector<AppendingVarInfo> AppendingVars;
371
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000372 unsigned Mode; // Mode to treat source module.
373
374 // Set of items not to link in from source.
375 SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
376
Tanya Lattner9af37a32011-11-02 00:24:56 +0000377 // Vector of functions to lazily link in.
378 std::vector<Function*> LazilyLinkFunctions;
379
Chris Lattner1afcace2011-07-09 17:41:24 +0000380 public:
381 std::string ErrorMsg;
382
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000383 ModuleLinker(Module *dstM, Module *srcM, unsigned mode)
384 : DstM(dstM), SrcM(srcM), Mode(mode) { }
Chris Lattner1afcace2011-07-09 17:41:24 +0000385
386 bool run();
387
388 private:
389 /// emitError - Helper method for setting a message and returning an error
390 /// code.
391 bool emitError(const Twine &Message) {
392 ErrorMsg = Message.str();
Chris Lattnerf6f4f7a2008-06-16 18:27:53 +0000393 return true;
Chris Lattnera4477f92008-06-16 21:17:12 +0000394 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000395
396 /// getLinkageResult - This analyzes the two global values and determines
397 /// what the result will look like in the destination module.
398 bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Rafael Espindola3ed88152012-01-05 23:02:01 +0000399 GlobalValue::LinkageTypes &LT,
400 GlobalValue::VisibilityTypes &Vis,
401 bool &LinkFromSrc);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000402
Chris Lattner1afcace2011-07-09 17:41:24 +0000403 /// getLinkedToGlobal - Given a global in the source module, return the
404 /// global in the destination module that is being linked to, if any.
405 GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
406 // If the source has no name it can't link. If it has local linkage,
407 // there is no name match-up going on.
408 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
409 return 0;
Bill Wendling601c0942012-02-28 04:01:21 +0000410
Chris Lattner1afcace2011-07-09 17:41:24 +0000411 // Otherwise see if we have a match in the destination module's symtab.
412 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
413 if (DGV == 0) return 0;
Bill Wendling601c0942012-02-28 04:01:21 +0000414
Chris Lattner1afcace2011-07-09 17:41:24 +0000415 // If we found a global with the same name in the dest module, but it has
416 // internal linkage, we are really not doing any linkage here.
417 if (DGV->hasLocalLinkage())
418 return 0;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000419
Chris Lattner1afcace2011-07-09 17:41:24 +0000420 // Otherwise, we do in fact link to the destination global.
421 return DGV;
422 }
423
424 void computeTypeMapping();
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000425 bool categorizeModuleFlagNodes(const NamedMDNode *ModFlags,
426 DenseMap<MDString*, MDNode*> &ErrorNode,
427 DenseMap<MDString*, MDNode*> &WarningNode,
428 DenseMap<MDString*, MDNode*> &OverrideNode,
429 DenseMap<MDString*,
430 SmallSetVector<MDNode*, 8> > &RequireNodes,
431 SmallSetVector<MDString*, 16> &SeenIDs);
Chris Lattner1afcace2011-07-09 17:41:24 +0000432
433 bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
434 bool linkGlobalProto(GlobalVariable *SrcGV);
435 bool linkFunctionProto(Function *SrcF);
436 bool linkAliasProto(GlobalAlias *SrcA);
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000437 bool linkModuleFlagsMetadata();
Chris Lattner1afcace2011-07-09 17:41:24 +0000438
439 void linkAppendingVarInit(const AppendingVarInfo &AVI);
440 void linkGlobalInits();
441 void linkFunctionBody(Function *Dst, Function *Src);
442 void linkAliasBodies();
443 void linkNamedMDNodes();
444 };
Bill Wendling601c0942012-02-28 04:01:21 +0000445}
446
Chris Lattner1afcace2011-07-09 17:41:24 +0000447/// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
Reid Spencer8bef0372007-02-04 04:29:21 +0000448/// in the symbol table. This is good for all clients except for us. Go
449/// through the trouble to force this back.
Chris Lattner1afcace2011-07-09 17:41:24 +0000450static void forceRenaming(GlobalValue *GV, StringRef Name) {
451 // If the global doesn't force its name or if it already has the right name,
452 // there is nothing for us to do.
453 if (GV->hasLocalLinkage() || GV->getName() == Name)
454 return;
455
456 Module *M = GV->getParent();
Chris Lattnerc0036282004-08-04 07:05:54 +0000457
458 // If there is a conflict, rename the conflict.
Chris Lattner1afcace2011-07-09 17:41:24 +0000459 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
Chris Lattner33f29492007-02-11 00:39:38 +0000460 GV->takeName(ConflictGV);
461 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Chris Lattner1afcace2011-07-09 17:41:24 +0000462 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
Chris Lattner33f29492007-02-11 00:39:38 +0000463 } else {
464 GV->setName(Name); // Force the name back
Reid Spenceref9b9a72007-02-05 20:47:22 +0000465 }
Reid Spenceref9b9a72007-02-05 20:47:22 +0000466}
Reid Spencer8bef0372007-02-04 04:29:21 +0000467
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000468/// copyGVAttributes - copy additional attributes (those not needed to construct
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000469/// a GlobalValue) from the SrcGV to the DestGV.
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000470static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
Duncan Sands28c3cff2008-05-26 19:58:59 +0000471 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
472 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
473 DestGV->copyAttributesFrom(SrcGV);
474 DestGV->setAlignment(Alignment);
Chris Lattner1afcace2011-07-09 17:41:24 +0000475
476 forceRenaming(DestGV, SrcGV->getName());
Chris Lattnerc0036282004-08-04 07:05:54 +0000477}
478
Rafael Espindola3ed88152012-01-05 23:02:01 +0000479static bool isLessConstraining(GlobalValue::VisibilityTypes a,
480 GlobalValue::VisibilityTypes b) {
481 if (a == GlobalValue::HiddenVisibility)
482 return false;
483 if (b == GlobalValue::HiddenVisibility)
484 return true;
485 if (a == GlobalValue::ProtectedVisibility)
486 return false;
487 if (b == GlobalValue::ProtectedVisibility)
488 return true;
489 return false;
490}
491
Chris Lattner1afcace2011-07-09 17:41:24 +0000492/// getLinkageResult - This analyzes the two global values and determines what
Chris Lattneraee38ea2004-12-03 22:18:41 +0000493/// the result will look like in the destination module. In particular, it
Rafael Espindola3ed88152012-01-05 23:02:01 +0000494/// computes the resultant linkage type and visibility, computes whether the
495/// global in the source should be copied over to the destination (replacing
496/// the existing one), and computes whether this linkage is an error or not.
Chris Lattner1afcace2011-07-09 17:41:24 +0000497bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Rafael Espindola3ed88152012-01-05 23:02:01 +0000498 GlobalValue::LinkageTypes &LT,
499 GlobalValue::VisibilityTypes &Vis,
Chris Lattner1afcace2011-07-09 17:41:24 +0000500 bool &LinkFromSrc) {
501 assert(Dest && "Must have two globals being queried");
502 assert(!Src->hasLocalLinkage() &&
Chris Lattneraee38ea2004-12-03 22:18:41 +0000503 "If Src has internal linkage, Dest shouldn't be set!");
Chris Lattner1afcace2011-07-09 17:41:24 +0000504
Peter Collingbourne88953162011-10-30 17:46:34 +0000505 bool SrcIsDeclaration = Src->isDeclaration() && !Src->isMaterializable();
Chris Lattnerf84c59d2011-07-14 20:23:05 +0000506 bool DestIsDeclaration = Dest->isDeclaration();
Chris Lattner1afcace2011-07-09 17:41:24 +0000507
508 if (SrcIsDeclaration) {
Anton Korobeynikov2b48ef02008-03-10 22:33:22 +0000509 // If Src is external or if both Src & Dest are external.. Just link the
Chris Lattneraee38ea2004-12-03 22:18:41 +0000510 // external globals, we aren't adding anything.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000511 if (Src->hasDLLImportLinkage()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000512 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
Chris Lattner1afcace2011-07-09 17:41:24 +0000513 if (DestIsDeclaration) {
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000514 LinkFromSrc = true;
515 LT = Src->getLinkage();
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000516 }
Andrew Lenharth8753c442006-12-15 17:35:32 +0000517 } else if (Dest->hasExternalWeakLinkage()) {
Duncan Sands667d4b82009-03-07 15:45:40 +0000518 // If the Dest is weak, use the source linkage.
Andrew Lenharth8753c442006-12-15 17:35:32 +0000519 LinkFromSrc = true;
520 LT = Src->getLinkage();
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000521 } else {
522 LinkFromSrc = false;
523 LT = Dest->getLinkage();
524 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000525 } else if (DestIsDeclaration && !Dest->hasDLLImportLinkage()) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000526 // If Dest is external but Src is not:
527 LinkFromSrc = true;
528 LT = Src->getLinkage();
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000529 } else if (Src->isWeakForLinker()) {
Dale Johannesenaafce772008-05-14 20:12:51 +0000530 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
531 // or DLL* linkage.
Chris Lattner266c7bb2009-04-13 05:44:34 +0000532 if (Dest->hasExternalWeakLinkage() ||
533 Dest->hasAvailableExternallyLinkage() ||
534 (Dest->hasLinkOnceLinkage() &&
535 (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000536 LinkFromSrc = true;
537 LT = Src->getLinkage();
538 } else {
539 LinkFromSrc = false;
540 LT = Dest->getLinkage();
541 }
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000542 } else if (Dest->isWeakForLinker()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000543 // At this point we know that Src has External* or DLL* linkage.
544 if (Src->hasExternalWeakLinkage()) {
545 LinkFromSrc = false;
546 LT = Dest->getLinkage();
547 } else {
548 LinkFromSrc = true;
549 LT = GlobalValue::ExternalLinkage;
550 }
Chris Lattneraee38ea2004-12-03 22:18:41 +0000551 } else {
Chris Lattner1afcace2011-07-09 17:41:24 +0000552 assert((Dest->hasExternalLinkage() || Dest->hasDLLImportLinkage() ||
553 Dest->hasDLLExportLinkage() || Dest->hasExternalWeakLinkage()) &&
554 (Src->hasExternalLinkage() || Src->hasDLLImportLinkage() ||
555 Src->hasDLLExportLinkage() || Src->hasExternalWeakLinkage()) &&
Chris Lattneraee38ea2004-12-03 22:18:41 +0000556 "Unexpected linkage type!");
Chris Lattner1afcace2011-07-09 17:41:24 +0000557 return emitError("Linking globals named '" + Src->getName() +
Chris Lattneraee38ea2004-12-03 22:18:41 +0000558 "': symbol multiply defined!");
559 }
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +0000560
Rafael Espindola3ed88152012-01-05 23:02:01 +0000561 // Compute the visibility. We follow the rules in the System V Application
562 // Binary Interface.
563 Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
564 Dest->getVisibility() : Src->getVisibility();
Chris Lattneraee38ea2004-12-03 22:18:41 +0000565 return false;
566}
Chris Lattner5c377c52001-10-14 23:29:15 +0000567
Chris Lattner1afcace2011-07-09 17:41:24 +0000568/// computeTypeMapping - Loop over all of the linked values to compute type
569/// mappings. For example, if we link "extern Foo *x" and "Foo *x = NULL", then
570/// we have two struct types 'Foo' but one got renamed when the module was
571/// loaded into the same LLVMContext.
572void ModuleLinker::computeTypeMapping() {
573 // Incorporate globals.
574 for (Module::global_iterator I = SrcM->global_begin(),
575 E = SrcM->global_end(); I != E; ++I) {
576 GlobalValue *DGV = getLinkedToGlobal(I);
577 if (DGV == 0) continue;
578
579 if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
580 TypeMap.addTypeMapping(DGV->getType(), I->getType());
581 continue;
582 }
583
584 // Unify the element type of appending arrays.
585 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
586 ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
587 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
Devang Patelab67e702009-08-11 18:01:24 +0000588 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000589
590 // Incorporate functions.
591 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
592 if (GlobalValue *DGV = getLinkedToGlobal(I))
593 TypeMap.addTypeMapping(DGV->getType(), I->getType());
594 }
Bill Wendlingc68d1272012-02-27 22:34:19 +0000595
Bill Wendling601c0942012-02-28 04:01:21 +0000596 // Incorporate types by name, scanning all the types in the source module.
597 // At this point, the destination module may have a type "%foo = { i32 }" for
Bill Wendling348e5e72012-02-27 23:48:30 +0000598 // example. When the source module got loaded into the same LLVMContext, if
599 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
Bill Wendling601c0942012-02-28 04:01:21 +0000600 // Though it isn't required for correctness, attempt to link these up to clean
601 // up the IR.
Bill Wendling348e5e72012-02-27 23:48:30 +0000602 std::vector<StructType*> SrcStructTypes;
603 SrcM->findUsedStructTypes(SrcStructTypes);
604
605 SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
606 SrcStructTypes.end());
607
608 for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
609 StructType *ST = SrcStructTypes[i];
610 if (!ST->hasName()) continue;
611
612 // Check to see if there is a dot in the name followed by a digit.
Bill Wendling601c0942012-02-28 04:01:21 +0000613 size_t DotPos = ST->getName().rfind('.');
614 if (DotPos == 0 || DotPos == StringRef::npos ||
615 ST->getName().back() == '.' || !isdigit(ST->getName()[DotPos+1]))
616 continue;
Bill Wendling348e5e72012-02-27 23:48:30 +0000617
618 // Check to see if the destination module has a struct with the prefix name.
Bill Wendling601c0942012-02-28 04:01:21 +0000619 if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
Bill Wendling348e5e72012-02-27 23:48:30 +0000620 // Don't use it if this actually came from the source module. They're in
621 // the same LLVMContext after all.
622 if (!SrcStructTypesSet.count(DST))
623 TypeMap.addTypeMapping(DST, ST);
624 }
625
Chris Lattner1afcace2011-07-09 17:41:24 +0000626 // Don't bother incorporating aliases, they aren't generally typed well.
Bill Wendling601c0942012-02-28 04:01:21 +0000627
Chris Lattner1afcace2011-07-09 17:41:24 +0000628 // Now that we have discovered all of the type equivalences, get a body for
629 // any 'opaque' types in the dest module that are now resolved.
630 TypeMap.linkDefinedTypeBodies();
Devang Patelab67e702009-08-11 18:01:24 +0000631}
632
Chris Lattner1afcace2011-07-09 17:41:24 +0000633/// linkAppendingVarProto - If there were any appending global variables, link
634/// them together now. Return true on error.
635bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
636 GlobalVariable *SrcGV) {
Bill Wendling601c0942012-02-28 04:01:21 +0000637
Chris Lattner1afcace2011-07-09 17:41:24 +0000638 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
639 return emitError("Linking globals named '" + SrcGV->getName() +
640 "': can only link appending global with another appending global!");
641
642 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
643 ArrayType *SrcTy =
644 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
645 Type *EltTy = DstTy->getElementType();
646
647 // Check to see that they two arrays agree on type.
648 if (EltTy != SrcTy->getElementType())
649 return emitError("Appending variables with different element types!");
650 if (DstGV->isConstant() != SrcGV->isConstant())
651 return emitError("Appending variables linked with different const'ness!");
652
653 if (DstGV->getAlignment() != SrcGV->getAlignment())
654 return emitError(
655 "Appending variables with different alignment need to be linked!");
656
657 if (DstGV->getVisibility() != SrcGV->getVisibility())
658 return emitError(
659 "Appending variables with different visibility need to be linked!");
660
661 if (DstGV->getSection() != SrcGV->getSection())
662 return emitError(
663 "Appending variables with different section name need to be linked!");
664
665 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
666 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
667
668 // Create the new global variable.
669 GlobalVariable *NG =
670 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
671 DstGV->getLinkage(), /*init*/0, /*name*/"", DstGV,
672 DstGV->isThreadLocal(),
673 DstGV->getType()->getAddressSpace());
674
675 // Propagate alignment, visibility and section info.
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000676 copyGVAttributes(NG, DstGV);
Chris Lattner1afcace2011-07-09 17:41:24 +0000677
678 AppendingVarInfo AVI;
679 AVI.NewGV = NG;
680 AVI.DstInit = DstGV->getInitializer();
681 AVI.SrcInit = SrcGV->getInitializer();
682 AppendingVars.push_back(AVI);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000683
Chris Lattner1afcace2011-07-09 17:41:24 +0000684 // Replace any uses of the two global variables with uses of the new
685 // global.
686 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000687
Chris Lattner1afcace2011-07-09 17:41:24 +0000688 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
689 DstGV->eraseFromParent();
690
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000691 // Track the source variable so we don't try to link it.
692 DoNotLinkFromSource.insert(SrcGV);
693
Chris Lattner1afcace2011-07-09 17:41:24 +0000694 return false;
695}
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000696
Chris Lattner1afcace2011-07-09 17:41:24 +0000697/// linkGlobalProto - Loop through the global variables in the src module and
698/// merge them into the dest module.
699bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
700 GlobalValue *DGV = getLinkedToGlobal(SGV);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000701 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000702
Chris Lattner1afcace2011-07-09 17:41:24 +0000703 if (DGV) {
704 // Concatenation of appending linkage variables is magic and handled later.
705 if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
706 return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
707
708 // Determine whether linkage of these two globals follows the source
709 // module's definition or the destination module's definition.
Chris Lattnerb324bd72006-11-09 05:18:12 +0000710 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000711 GlobalValue::VisibilityTypes NV;
Chris Lattnerb324bd72006-11-09 05:18:12 +0000712 bool LinkFromSrc = false;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000713 if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
Chris Lattneraee38ea2004-12-03 22:18:41 +0000714 return true;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000715 NewVisibility = NV;
Chris Lattner0fec08e2003-04-21 21:07:05 +0000716
Chris Lattner1afcace2011-07-09 17:41:24 +0000717 // If we're not linking from the source, then keep the definition that we
718 // have.
719 if (!LinkFromSrc) {
720 // Special case for const propagation.
721 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
722 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
723 DGVar->setConstant(true);
724
Rafael Espindola3ed88152012-01-05 23:02:01 +0000725 // Set calculated linkage and visibility.
Chris Lattner1afcace2011-07-09 17:41:24 +0000726 DGV->setLinkage(NewLinkage);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000727 DGV->setVisibility(*NewVisibility);
728
Chris Lattner6157e382008-07-14 07:23:24 +0000729 // Make sure to remember this mapping.
Chris Lattner1afcace2011-07-09 17:41:24 +0000730 ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
731
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000732 // Track the source global so that we don't attempt to copy it over when
733 // processing global initializers.
734 DoNotLinkFromSource.insert(SGV);
735
Chris Lattner1afcace2011-07-09 17:41:24 +0000736 return false;
Chris Lattner6157e382008-07-14 07:23:24 +0000737 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000738 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000739
740 // No linking to be performed or linking from the source: simply create an
741 // identical version of the symbol over in the dest module... the
742 // initializer will be filled in later by LinkGlobalInits.
743 GlobalVariable *NewDGV =
744 new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
745 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
746 SGV->getName(), /*insertbefore*/0,
747 SGV->isThreadLocal(),
748 SGV->getType()->getAddressSpace());
749 // Propagate alignment, visibility and section info.
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000750 copyGVAttributes(NewDGV, SGV);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000751 if (NewVisibility)
752 NewDGV->setVisibility(*NewVisibility);
Chris Lattner1afcace2011-07-09 17:41:24 +0000753
754 if (DGV) {
755 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
756 DGV->eraseFromParent();
757 }
758
759 // Make sure to remember this mapping.
760 ValueMap[SGV] = NewDGV;
Chris Lattner5c377c52001-10-14 23:29:15 +0000761 return false;
762}
763
Chris Lattner1afcace2011-07-09 17:41:24 +0000764/// linkFunctionProto - Link the function in the source module into the
765/// destination module if needed, setting up mapping information.
766bool ModuleLinker::linkFunctionProto(Function *SF) {
767 GlobalValue *DGV = getLinkedToGlobal(SF);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000768 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Chris Lattner1afcace2011-07-09 17:41:24 +0000769
770 if (DGV) {
771 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
772 bool LinkFromSrc = false;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000773 GlobalValue::VisibilityTypes NV;
774 if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
Chris Lattner1afcace2011-07-09 17:41:24 +0000775 return true;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000776 NewVisibility = NV;
777
Chris Lattner1afcace2011-07-09 17:41:24 +0000778 if (!LinkFromSrc) {
779 // Set calculated linkage
780 DGV->setLinkage(NewLinkage);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000781 DGV->setVisibility(*NewVisibility);
782
Chris Lattner1afcace2011-07-09 17:41:24 +0000783 // Make sure to remember this mapping.
784 ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
785
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000786 // Track the function from the source module so we don't attempt to remap
787 // it.
788 DoNotLinkFromSource.insert(SF);
789
Chris Lattner1afcace2011-07-09 17:41:24 +0000790 return false;
791 }
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000792 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000793
794 // If there is no linkage to be performed or we are linking from the source,
795 // bring SF over.
796 Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
797 SF->getLinkage(), SF->getName(), DstM);
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000798 copyGVAttributes(NewDF, SF);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000799 if (NewVisibility)
800 NewDF->setVisibility(*NewVisibility);
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000801
Chris Lattner1afcace2011-07-09 17:41:24 +0000802 if (DGV) {
803 // Any uses of DF need to change to NewDF, with cast.
804 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
805 DGV->eraseFromParent();
Tanya Lattner9af37a32011-11-02 00:24:56 +0000806 } else {
807 // Internal, LO_ODR, or LO linkage - stick in set to ignore and lazily link.
808 if (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
809 SF->hasAvailableExternallyLinkage()) {
810 DoNotLinkFromSource.insert(SF);
811 LazilyLinkFunctions.push_back(SF);
812 }
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000813 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000814
815 ValueMap[SF] = NewDF;
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000816 return false;
817}
818
Chris Lattner1afcace2011-07-09 17:41:24 +0000819/// LinkAliasProto - Set up prototypes for any aliases that come over from the
820/// source module.
821bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
822 GlobalValue *DGV = getLinkedToGlobal(SGA);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000823 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
824
Chris Lattner1afcace2011-07-09 17:41:24 +0000825 if (DGV) {
826 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000827 GlobalValue::VisibilityTypes NV;
Chris Lattner1afcace2011-07-09 17:41:24 +0000828 bool LinkFromSrc = false;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000829 if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
Chris Lattner1afcace2011-07-09 17:41:24 +0000830 return true;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000831 NewVisibility = NV;
832
Chris Lattner1afcace2011-07-09 17:41:24 +0000833 if (!LinkFromSrc) {
834 // Set calculated linkage.
835 DGV->setLinkage(NewLinkage);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000836 DGV->setVisibility(*NewVisibility);
837
Chris Lattner1afcace2011-07-09 17:41:24 +0000838 // Make sure to remember this mapping.
839 ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
840
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000841 // Track the alias from the source module so we don't attempt to remap it.
842 DoNotLinkFromSource.insert(SGA);
843
Chris Lattner1afcace2011-07-09 17:41:24 +0000844 return false;
845 }
846 }
847
848 // If there is no linkage to be performed or we're linking from the source,
849 // bring over SGA.
850 GlobalAlias *NewDA = new GlobalAlias(TypeMap.get(SGA->getType()),
851 SGA->getLinkage(), SGA->getName(),
852 /*aliasee*/0, DstM);
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000853 copyGVAttributes(NewDA, SGA);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000854 if (NewVisibility)
855 NewDA->setVisibility(*NewVisibility);
Chris Lattner5c377c52001-10-14 23:29:15 +0000856
Chris Lattner1afcace2011-07-09 17:41:24 +0000857 if (DGV) {
858 // Any uses of DGV need to change to NewDA, with cast.
859 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
860 DGV->eraseFromParent();
861 }
862
863 ValueMap[SGA] = NewDA;
864 return false;
865}
866
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000867static void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000868 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
869
870 for (unsigned i = 0; i != NumElements; ++i)
871 Dest.push_back(C->getAggregateElement(i));
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000872}
873
Chris Lattner1afcace2011-07-09 17:41:24 +0000874void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
875 // Merge the initializer.
876 SmallVector<Constant*, 16> Elements;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000877 getArrayElements(AVI.DstInit, Elements);
Chris Lattner1afcace2011-07-09 17:41:24 +0000878
879 Constant *SrcInit = MapValue(AVI.SrcInit, ValueMap, RF_None, &TypeMap);
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000880 getArrayElements(SrcInit, Elements);
881
Chris Lattner1afcace2011-07-09 17:41:24 +0000882 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
883 AVI.NewGV->setInitializer(ConstantArray::get(NewType, Elements));
884}
885
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000886/// linkGlobalInits - Update the initializers in the Dest module now that all
887/// globals that may be referenced are in Dest.
Chris Lattner1afcace2011-07-09 17:41:24 +0000888void ModuleLinker::linkGlobalInits() {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000889 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattner1afcace2011-07-09 17:41:24 +0000890 for (Module::const_global_iterator I = SrcM->global_begin(),
891 E = SrcM->global_end(); I != E; ++I) {
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000892
893 // Only process initialized GV's or ones not already in dest.
894 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
Chris Lattner1afcace2011-07-09 17:41:24 +0000895
896 // Grab destination global variable.
897 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
898 // Figure out what the initializer looks like in the dest module.
899 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
900 RF_None, &TypeMap));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000901 }
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000902}
Chris Lattner5c377c52001-10-14 23:29:15 +0000903
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000904/// linkFunctionBody - Copy the source function over into the dest function and
905/// fix up references to values. At this point we know that Dest is an external
906/// function, and that Src is not.
Chris Lattner1afcace2011-07-09 17:41:24 +0000907void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
908 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
Chris Lattner5c377c52001-10-14 23:29:15 +0000909
Chris Lattner0033baf2004-11-16 17:12:38 +0000910 // Go through and convert function arguments over, remembering the mapping.
Chris Lattner1afcace2011-07-09 17:41:24 +0000911 Function::arg_iterator DI = Dst->arg_begin();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000912 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
Chris Lattner69da5cf2002-10-13 20:57:00 +0000913 I != E; ++I, ++DI) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000914 DI->setName(I->getName()); // Copy the name over.
Chris Lattner5c377c52001-10-14 23:29:15 +0000915
Chris Lattner1afcace2011-07-09 17:41:24 +0000916 // Add a mapping to our mapping.
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000917 ValueMap[I] = DI;
Chris Lattner5c377c52001-10-14 23:29:15 +0000918 }
919
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000920 if (Mode == Linker::DestroySource) {
921 // Splice the body of the source function into the dest function.
922 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
923
924 // At this point, all of the instructions and values of the function are now
925 // copied over. The only problem is that they are still referencing values in
926 // the Source function as operands. Loop through all of the operands of the
927 // functions and patch them up to point to the local versions.
928 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
929 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
930 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap);
931
932 } else {
933 // Clone the body of the function into the dest function.
934 SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
Mon P Wangd24397a2011-12-23 02:18:32 +0000935 CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", NULL, &TypeMap);
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000936 }
937
Chris Lattner0033baf2004-11-16 17:12:38 +0000938 // There is no need to map the arguments anymore.
Chris Lattner11273152006-06-16 01:24:04 +0000939 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
940 I != E; ++I)
Reid Spenceref9b9a72007-02-05 20:47:22 +0000941 ValueMap.erase(I);
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000942
Chris Lattner5c377c52001-10-14 23:29:15 +0000943}
944
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000945/// linkAliasBodies - Insert all of the aliases in Src into the Dest module.
Chris Lattner1afcace2011-07-09 17:41:24 +0000946void ModuleLinker::linkAliasBodies() {
947 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000948 I != E; ++I) {
949 if (DoNotLinkFromSource.count(I))
950 continue;
Chris Lattner1afcace2011-07-09 17:41:24 +0000951 if (Constant *Aliasee = I->getAliasee()) {
952 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
953 DA->setAliasee(MapValue(Aliasee, ValueMap, RF_None, &TypeMap));
David Chisnall34722462010-01-09 16:27:31 +0000954 }
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000955 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000956}
Anton Korobeynikov9f2ee702008-03-05 23:21:39 +0000957
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000958/// linkNamedMDNodes - Insert all of the named MDNodes in Src into the Dest
Chris Lattner1afcace2011-07-09 17:41:24 +0000959/// module.
960void ModuleLinker::linkNamedMDNodes() {
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000961 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
Chris Lattner1afcace2011-07-09 17:41:24 +0000962 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
963 E = SrcM->named_metadata_end(); I != E; ++I) {
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000964 // Don't link module flags here. Do them separately.
965 if (&*I == SrcModFlags) continue;
Chris Lattner1afcace2011-07-09 17:41:24 +0000966 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
967 // Add Src elements into Dest node.
968 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
969 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
970 RF_None, &TypeMap));
971 }
972}
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000973
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000974/// categorizeModuleFlagNodes - Categorize the module flags according to their
975/// type: Error, Warning, Override, and Require.
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000976bool ModuleLinker::
977categorizeModuleFlagNodes(const NamedMDNode *ModFlags,
978 DenseMap<MDString*, MDNode*> &ErrorNode,
979 DenseMap<MDString*, MDNode*> &WarningNode,
980 DenseMap<MDString*, MDNode*> &OverrideNode,
981 DenseMap<MDString*,
982 SmallSetVector<MDNode*, 8> > &RequireNodes,
983 SmallSetVector<MDString*, 16> &SeenIDs) {
984 bool HasErr = false;
985
986 for (unsigned I = 0, E = ModFlags->getNumOperands(); I != E; ++I) {
987 MDNode *Op = ModFlags->getOperand(I);
988 assert(Op->getNumOperands() == 3 && "Invalid module flag metadata!");
989 assert(isa<ConstantInt>(Op->getOperand(0)) &&
990 "Module flag's first operand must be an integer!");
991 assert(isa<MDString>(Op->getOperand(1)) &&
992 "Module flag's second operand must be an MDString!");
993
994 ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
995 MDString *ID = cast<MDString>(Op->getOperand(1));
996 Value *Val = Op->getOperand(2);
997 switch (Behavior->getZExtValue()) {
998 default:
999 assert(false && "Invalid behavior in module flag metadata!");
1000 break;
1001 case Module::Error: {
1002 MDNode *&ErrNode = ErrorNode[ID];
1003 if (!ErrNode) ErrNode = Op;
1004 if (ErrNode->getOperand(2) != Val)
Bill Wendling75b3d682012-02-14 09:13:54 +00001005 HasErr = emitError("linking module flags '" + ID->getString() +
1006 "': IDs have conflicting values");
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001007 break;
1008 }
1009 case Module::Warning: {
1010 MDNode *&WarnNode = WarningNode[ID];
1011 if (!WarnNode) WarnNode = Op;
1012 if (WarnNode->getOperand(2) != Val)
Bill Wendling75b3d682012-02-14 09:13:54 +00001013 errs() << "WARNING: linking module flags '" << ID->getString()
1014 << "': IDs have conflicting values";
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001015 break;
1016 }
1017 case Module::Require: RequireNodes[ID].insert(Op); break;
1018 case Module::Override: {
1019 MDNode *&OvrNode = OverrideNode[ID];
1020 if (!OvrNode) OvrNode = Op;
1021 if (OvrNode->getOperand(2) != Val)
Bill Wendling75b3d682012-02-14 09:13:54 +00001022 HasErr = emitError("linking module flags '" + ID->getString() +
1023 "': IDs have conflicting override values");
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001024 break;
1025 }
1026 }
1027
1028 SeenIDs.insert(ID);
1029 }
1030
1031 return HasErr;
1032}
1033
1034/// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest
1035/// module.
1036bool ModuleLinker::linkModuleFlagsMetadata() {
1037 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1038 if (!SrcModFlags) return false;
1039
1040 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
1041
1042 // If the destination module doesn't have module flags yet, then just copy
1043 // over the source module's flags.
1044 if (DstModFlags->getNumOperands() == 0) {
1045 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1046 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1047
1048 return false;
1049 }
1050
1051 bool HasErr = false;
1052
1053 // Otherwise, we have to merge them based on their behaviors. First,
1054 // categorize all of the nodes in the modules' module flags. If an error or
1055 // warning occurs, then emit the appropriate message(s).
1056 DenseMap<MDString*, MDNode*> ErrorNode;
1057 DenseMap<MDString*, MDNode*> WarningNode;
1058 DenseMap<MDString*, MDNode*> OverrideNode;
1059 DenseMap<MDString*, SmallSetVector<MDNode*, 8> > RequireNodes;
1060 SmallSetVector<MDString*, 16> SeenIDs;
1061
1062 HasErr |= categorizeModuleFlagNodes(SrcModFlags, ErrorNode, WarningNode,
1063 OverrideNode, RequireNodes, SeenIDs);
1064 HasErr |= categorizeModuleFlagNodes(DstModFlags, ErrorNode, WarningNode,
1065 OverrideNode, RequireNodes, SeenIDs);
1066
1067 // Check that there isn't both an error and warning node for a flag.
1068 for (SmallSetVector<MDString*, 16>::iterator
1069 I = SeenIDs.begin(), E = SeenIDs.end(); I != E; ++I) {
1070 MDString *ID = *I;
1071 if (ErrorNode[ID] && WarningNode[ID])
Bill Wendling75b3d682012-02-14 09:13:54 +00001072 HasErr = emitError("linking module flags '" + ID->getString() +
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001073 "': IDs have conflicting behaviors");
1074 }
1075
1076 // Early exit if we had an error.
1077 if (HasErr) return true;
1078
1079 // Get the destination's module flags ready for new operands.
1080 DstModFlags->dropAllReferences();
1081
1082 // Add all of the module flags to the destination module.
1083 DenseMap<MDString*, SmallVector<MDNode*, 4> > AddedNodes;
1084 for (SmallSetVector<MDString*, 16>::iterator
1085 I = SeenIDs.begin(), E = SeenIDs.end(); I != E; ++I) {
1086 MDString *ID = *I;
1087 if (OverrideNode[ID]) {
1088 DstModFlags->addOperand(OverrideNode[ID]);
1089 AddedNodes[ID].push_back(OverrideNode[ID]);
1090 } else if (ErrorNode[ID]) {
1091 DstModFlags->addOperand(ErrorNode[ID]);
1092 AddedNodes[ID].push_back(ErrorNode[ID]);
1093 } else if (WarningNode[ID]) {
1094 DstModFlags->addOperand(WarningNode[ID]);
1095 AddedNodes[ID].push_back(WarningNode[ID]);
1096 }
1097
1098 for (SmallSetVector<MDNode*, 8>::iterator
1099 II = RequireNodes[ID].begin(), IE = RequireNodes[ID].end();
1100 II != IE; ++II)
1101 DstModFlags->addOperand(*II);
1102 }
1103
1104 // Now check that all of the requirements have been satisfied.
1105 for (SmallSetVector<MDString*, 16>::iterator
1106 I = SeenIDs.begin(), E = SeenIDs.end(); I != E; ++I) {
1107 MDString *ID = *I;
1108 SmallSetVector<MDNode*, 8> &Set = RequireNodes[ID];
1109
1110 for (SmallSetVector<MDNode*, 8>::iterator
1111 II = Set.begin(), IE = Set.end(); II != IE; ++II) {
1112 MDNode *Node = *II;
1113 assert(isa<MDNode>(Node->getOperand(2)) &&
1114 "Module flag's third operand must be an MDNode!");
1115 MDNode *Val = cast<MDNode>(Node->getOperand(2));
1116
1117 MDString *ReqID = cast<MDString>(Val->getOperand(0));
1118 Value *ReqVal = Val->getOperand(1);
1119
1120 bool HasValue = false;
1121 for (SmallVectorImpl<MDNode*>::iterator
1122 RI = AddedNodes[ReqID].begin(), RE = AddedNodes[ReqID].end();
1123 RI != RE; ++RI) {
1124 MDNode *ReqNode = *RI;
1125 if (ReqNode->getOperand(2) == ReqVal) {
1126 HasValue = true;
1127 break;
1128 }
1129 }
1130
1131 if (!HasValue)
Bill Wendling75b3d682012-02-14 09:13:54 +00001132 HasErr = emitError("linking module flags '" + ReqID->getString() +
1133 "': does not have the required value");
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001134 }
1135 }
1136
1137 return HasErr;
1138}
Chris Lattner1afcace2011-07-09 17:41:24 +00001139
1140bool ModuleLinker::run() {
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001141 assert(DstM && "Null destination module");
1142 assert(SrcM && "Null source module");
Chris Lattner1afcace2011-07-09 17:41:24 +00001143
1144 // Inherit the target data from the source module if the destination module
1145 // doesn't have one already.
1146 if (DstM->getDataLayout().empty() && !SrcM->getDataLayout().empty())
1147 DstM->setDataLayout(SrcM->getDataLayout());
1148
1149 // Copy the target triple from the source to dest if the dest's is empty.
1150 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1151 DstM->setTargetTriple(SrcM->getTargetTriple());
1152
1153 if (!SrcM->getDataLayout().empty() && !DstM->getDataLayout().empty() &&
1154 SrcM->getDataLayout() != DstM->getDataLayout())
1155 errs() << "WARNING: Linking two modules of different data layouts!\n";
1156 if (!SrcM->getTargetTriple().empty() &&
1157 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1158 errs() << "WARNING: Linking two modules of different target triples: ";
1159 if (!SrcM->getModuleIdentifier().empty())
1160 errs() << SrcM->getModuleIdentifier() << ": ";
1161 errs() << "'" << SrcM->getTargetTriple() << "' and '"
1162 << DstM->getTargetTriple() << "'\n";
1163 }
1164
1165 // Append the module inline asm string.
1166 if (!SrcM->getModuleInlineAsm().empty()) {
1167 if (DstM->getModuleInlineAsm().empty())
1168 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1169 else
1170 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1171 SrcM->getModuleInlineAsm());
1172 }
1173
1174 // Update the destination module's dependent libraries list with the libraries
1175 // from the source module. There's no opportunity for duplicates here as the
1176 // Module ensures that duplicate insertions are discarded.
1177 for (Module::lib_iterator SI = SrcM->lib_begin(), SE = SrcM->lib_end();
1178 SI != SE; ++SI)
1179 DstM->addLibrary(*SI);
1180
1181 // If the source library's module id is in the dependent library list of the
1182 // destination library, remove it since that module is now linked in.
1183 StringRef ModuleId = SrcM->getModuleIdentifier();
1184 if (!ModuleId.empty())
1185 DstM->removeLibrary(sys::path::stem(ModuleId));
Chris Lattner1afcace2011-07-09 17:41:24 +00001186
1187 // Loop over all of the linked values to compute type mappings.
1188 computeTypeMapping();
1189
1190 // Insert all of the globals in src into the DstM module... without linking
1191 // initializers (which could refer to functions not yet mapped over).
1192 for (Module::global_iterator I = SrcM->global_begin(),
1193 E = SrcM->global_end(); I != E; ++I)
1194 if (linkGlobalProto(I))
1195 return true;
1196
1197 // Link the functions together between the two modules, without doing function
1198 // bodies... this just adds external function prototypes to the DstM
1199 // function... We do this so that when we begin processing function bodies,
1200 // all of the global values that may be referenced are available in our
1201 // ValueMap.
1202 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1203 if (linkFunctionProto(I))
1204 return true;
1205
1206 // If there were any aliases, link them now.
1207 for (Module::alias_iterator I = SrcM->alias_begin(),
1208 E = SrcM->alias_end(); I != E; ++I)
1209 if (linkAliasProto(I))
1210 return true;
1211
1212 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1213 linkAppendingVarInit(AppendingVars[i]);
1214
1215 // Update the initializers in the DstM module now that all globals that may
1216 // be referenced are in DstM.
1217 linkGlobalInits();
1218
1219 // Link in the function bodies that are defined in the source module into
1220 // DstM.
1221 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
Tanya Lattner2b28a742011-10-14 22:17:46 +00001222 // Skip if not linking from source.
1223 if (DoNotLinkFromSource.count(SF)) continue;
1224
1225 // Skip if no body (function is external) or materialize.
1226 if (SF->isDeclaration()) {
1227 if (!SF->isMaterializable())
1228 continue;
1229 if (SF->Materialize(&ErrorMsg))
1230 return true;
1231 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001232
1233 linkFunctionBody(cast<Function>(ValueMap[SF]), SF);
1234 }
1235
1236 // Resolve all uses of aliases with aliasees.
1237 linkAliasBodies();
1238
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001239 // Remap all of the named MDNodes in Src into the DstM module. We do this
Devang Patel211da8f2011-08-04 19:44:28 +00001240 // after linking GlobalValues so that MDNodes that reference GlobalValues
1241 // are properly remapped.
1242 linkNamedMDNodes();
1243
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001244 // Merge the module flags into the DstM module.
1245 if (linkModuleFlagsMetadata())
1246 return true;
1247
Tanya Lattner9af37a32011-11-02 00:24:56 +00001248 // Process vector of lazily linked in functions.
1249 bool LinkedInAnyFunctions;
1250 do {
1251 LinkedInAnyFunctions = false;
1252
1253 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1254 E = LazilyLinkFunctions.end(); I != E; ++I) {
1255 if (!*I)
1256 continue;
1257
1258 Function *SF = *I;
1259 Function *DF = cast<Function>(ValueMap[SF]);
1260
1261 if (!DF->use_empty()) {
1262
1263 // Materialize if necessary.
1264 if (SF->isDeclaration()) {
1265 if (!SF->isMaterializable())
1266 continue;
1267 if (SF->Materialize(&ErrorMsg))
1268 return true;
1269 }
1270
1271 // Link in function body.
1272 linkFunctionBody(DF, SF);
1273
1274 // "Remove" from vector by setting the element to 0.
1275 *I = 0;
1276
1277 // Set flag to indicate we may have more functions to lazily link in
1278 // since we linked in a function.
1279 LinkedInAnyFunctions = true;
1280 }
1281 }
1282 } while (LinkedInAnyFunctions);
1283
1284 // Remove any prototypes of functions that were not actually linked in.
1285 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1286 E = LazilyLinkFunctions.end(); I != E; ++I) {
1287 if (!*I)
1288 continue;
1289
1290 Function *SF = *I;
1291 Function *DF = cast<Function>(ValueMap[SF]);
1292 if (DF->use_empty())
1293 DF->eraseFromParent();
1294 }
1295
Chris Lattner1afcace2011-07-09 17:41:24 +00001296 // Now that all of the types from the source are used, resolve any structs
1297 // copied over to the dest that didn't exist there.
1298 TypeMap.linkDefinedTypeBodies();
1299
Anton Korobeynikov9f2ee702008-03-05 23:21:39 +00001300 return false;
1301}
Chris Lattner52f7e902001-10-13 07:03:50 +00001302
Chris Lattner1afcace2011-07-09 17:41:24 +00001303//===----------------------------------------------------------------------===//
1304// LinkModules entrypoint.
1305//===----------------------------------------------------------------------===//
1306
Bill Wendlingcd7193f2012-03-22 20:28:27 +00001307/// LinkModules - This function links two modules together, with the resulting
1308/// left module modified to be the composite of the two input modules. If an
1309/// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1310/// the problem. Upon failure, the Dest module could be in a modified state,
1311/// and shouldn't be relied on to be consistent.
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +00001312bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode,
1313 std::string *ErrorMsg) {
1314 ModuleLinker TheLinker(Dest, Src, Mode);
Chris Lattner1afcace2011-07-09 17:41:24 +00001315 if (TheLinker.run()) {
1316 if (ErrorMsg) *ErrorMsg = TheLinker.ErrorMsg;
Reid Spencer619f0242007-02-04 04:43:17 +00001317 return true;
Chris Lattner5a837de2004-08-04 07:44:58 +00001318 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001319
Chris Lattner52f7e902001-10-13 07:03:50 +00001320 return false;
1321}