blob: c53b2067a29799c3e322f7f64639ac04b2baa5cf [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"
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +000019#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner74382b72009-08-23 22:45:37 +000020#include "llvm/Support/raw_ostream.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000021#include "llvm/Support/Path.h"
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +000022#include "llvm/Transforms/Utils/Cloning.h"
Dan Gohman05ea54e2010-08-24 18:50:07 +000023#include "llvm/Transforms/Utils/ValueMapper.h"
Chris Lattnerf7703df2004-01-09 06:12:26 +000024using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000025
Chris Lattner1afcace2011-07-09 17:41:24 +000026//===----------------------------------------------------------------------===//
27// TypeMap implementation.
28//===----------------------------------------------------------------------===//
Chris Lattner5c377c52001-10-14 23:29:15 +000029
Chris Lattner62a81a12008-06-16 21:00:18 +000030namespace {
Chris Lattner1afcace2011-07-09 17:41:24 +000031class TypeMapTy : public ValueMapTypeRemapper {
32 /// MappedTypes - This is a mapping from a source type to a destination type
33 /// to use.
34 DenseMap<Type*, Type*> MappedTypes;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +000035
Chris Lattner1afcace2011-07-09 17:41:24 +000036 /// SpeculativeTypes - When checking to see if two subgraphs are isomorphic,
37 /// we speculatively add types to MappedTypes, but keep track of them here in
38 /// case we need to roll back.
39 SmallVector<Type*, 16> SpeculativeTypes;
40
41 /// DefinitionsToResolve - This is a list of non-opaque structs in the source
42 /// module that are mapped to an opaque struct in the destination module.
43 SmallVector<StructType*, 16> DefinitionsToResolve;
Chris Lattnerfc196f92008-06-16 23:06:51 +000044public:
Chris Lattner1afcace2011-07-09 17:41:24 +000045
46 /// addTypeMapping - Indicate that the specified type in the destination
47 /// module is conceptually equivalent to the specified type in the source
48 /// module.
49 void addTypeMapping(Type *DstTy, Type *SrcTy);
50
51 /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
52 /// module from a type definition in the source module.
53 void linkDefinedTypeBodies();
54
55 /// get - Return the mapped type to use for the specified input type from the
56 /// source module.
57 Type *get(Type *SrcTy);
58
59 FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*)T));}
60
61private:
62 Type *getImpl(Type *T);
63 /// remapType - Implement the ValueMapTypeRemapper interface.
64 Type *remapType(Type *SrcTy) {
65 return get(SrcTy);
Chris Lattner62a81a12008-06-16 21:00:18 +000066 }
Chris Lattner1afcace2011-07-09 17:41:24 +000067
68 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
Chris Lattner62a81a12008-06-16 21:00:18 +000069};
70}
71
Chris Lattner1afcace2011-07-09 17:41:24 +000072void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
73 Type *&Entry = MappedTypes[SrcTy];
74 if (Entry) return;
75
76 if (DstTy == SrcTy) {
77 Entry = DstTy;
78 return;
79 }
80
81 // Check to see if these types are recursively isomorphic and establish a
82 // mapping between them if so.
83 if (!areTypesIsomorphic(DstTy, SrcTy)) {
84 // Oops, they aren't isomorphic. Just discard this request by rolling out
85 // any speculative mappings we've established.
86 for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i)
87 MappedTypes.erase(SpeculativeTypes[i]);
88 }
89 SpeculativeTypes.clear();
90}
Chris Lattner62a81a12008-06-16 21:00:18 +000091
Chris Lattner1afcace2011-07-09 17:41:24 +000092/// areTypesIsomorphic - Recursively walk this pair of types, returning true
93/// if they are isomorphic, false if they are not.
94bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
95 // Two types with differing kinds are clearly not isomorphic.
96 if (DstTy->getTypeID() != SrcTy->getTypeID()) return false;
Misha Brukmanf976c852005-04-21 22:55:34 +000097
Chris Lattner1afcace2011-07-09 17:41:24 +000098 // If we have an entry in the MappedTypes table, then we have our answer.
99 Type *&Entry = MappedTypes[SrcTy];
100 if (Entry)
101 return Entry == DstTy;
Misha Brukmanf976c852005-04-21 22:55:34 +0000102
Chris Lattner1afcace2011-07-09 17:41:24 +0000103 // Two identical types are clearly isomorphic. Remember this
104 // non-speculatively.
105 if (DstTy == SrcTy) {
106 Entry = DstTy;
Chris Lattner56539652008-06-16 20:03:01 +0000107 return true;
Chris Lattner1afcace2011-07-09 17:41:24 +0000108 }
109
110 // Okay, we have two types with identical kinds that we haven't seen before.
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000111
Chris Lattner1afcace2011-07-09 17:41:24 +0000112 // If this is an opaque struct type, special case it.
113 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
114 // Mapping an opaque type to any struct, just keep the dest struct.
115 if (SSTy->isOpaque()) {
116 Entry = DstTy;
117 SpeculativeTypes.push_back(SrcTy);
Chris Lattner43f4ba82003-08-22 19:12:55 +0000118 return true;
Chris Lattnera4477f92008-06-16 21:17:12 +0000119 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000120
121 // Mapping a non-opaque source type to an opaque dest. Keep the dest, but
122 // fill it in later. This doesn't need to be speculative.
123 if (cast<StructType>(DstTy)->isOpaque()) {
124 Entry = DstTy;
125 DefinitionsToResolve.push_back(SSTy);
126 return true;
127 }
128 }
129
130 // If the number of subtypes disagree between the two types, then we fail.
131 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
Chris Lattnere76c57a2003-08-22 06:07:12 +0000132 return false;
Chris Lattner1afcace2011-07-09 17:41:24 +0000133
134 // Fail if any of the extra properties (e.g. array size) of the type disagree.
135 if (isa<IntegerType>(DstTy))
136 return false; // bitwidth disagrees.
137 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
138 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
139 return false;
140 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
141 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
142 return false;
143 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
144 StructType *SSTy = cast<StructType>(SrcTy);
Chris Lattner1bcbf852011-08-12 18:07:26 +0000145 if (DSTy->isLiteral() != SSTy->isLiteral() ||
Chris Lattner1afcace2011-07-09 17:41:24 +0000146 DSTy->isPacked() != SSTy->isPacked())
147 return false;
148 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
149 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
150 return false;
151 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
152 if (DVTy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
153 return false;
Chris Lattnere76c57a2003-08-22 06:07:12 +0000154 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000155
156 // Otherwise, we speculate that these two types will line up and recursively
157 // check the subelements.
158 Entry = DstTy;
159 SpeculativeTypes.push_back(SrcTy);
160
161 for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i)
162 if (!areTypesIsomorphic(DstTy->getContainedType(i),
163 SrcTy->getContainedType(i)))
164 return false;
165
166 // If everything seems to have lined up, then everything is great.
167 return true;
168}
169
170/// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
171/// module from a type definition in the source module.
172void TypeMapTy::linkDefinedTypeBodies() {
173 SmallVector<Type*, 16> Elements;
174 SmallString<16> TmpName;
175
176 // Note that processing entries in this loop (calling 'get') can add new
177 // entries to the DefinitionsToResolve vector.
178 while (!DefinitionsToResolve.empty()) {
179 StructType *SrcSTy = DefinitionsToResolve.pop_back_val();
180 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
181
182 // TypeMap is a many-to-one mapping, if there were multiple types that
183 // provide a body for DstSTy then previous iterations of this loop may have
184 // already handled it. Just ignore this case.
185 if (!DstSTy->isOpaque()) continue;
186 assert(!SrcSTy->isOpaque() && "Not resolving a definition?");
187
188 // Map the body of the source type over to a new body for the dest type.
189 Elements.resize(SrcSTy->getNumElements());
190 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
191 Elements[i] = getImpl(SrcSTy->getElementType(i));
192
193 DstSTy->setBody(Elements, SrcSTy->isPacked());
194
195 // If DstSTy has no name or has a longer name than STy, then viciously steal
196 // STy's name.
197 if (!SrcSTy->hasName()) continue;
198 StringRef SrcName = SrcSTy->getName();
199
200 if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
201 TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
202 SrcSTy->setName("");
203 DstSTy->setName(TmpName.str());
204 TmpName.clear();
205 }
206 }
207}
208
209
210/// get - Return the mapped type to use for the specified input type from the
211/// source module.
212Type *TypeMapTy::get(Type *Ty) {
213 Type *Result = getImpl(Ty);
214
215 // If this caused a reference to any struct type, resolve it before returning.
216 if (!DefinitionsToResolve.empty())
217 linkDefinedTypeBodies();
218 return Result;
219}
220
221/// getImpl - This is the recursive version of get().
222Type *TypeMapTy::getImpl(Type *Ty) {
223 // If we already have an entry for this type, return it.
224 Type **Entry = &MappedTypes[Ty];
225 if (*Entry) return *Entry;
226
227 // If this is not a named struct type, then just map all of the elements and
228 // then rebuild the type from inside out.
Chris Lattner1bcbf852011-08-12 18:07:26 +0000229 if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000230 // If there are no element types to map, then the type is itself. This is
231 // true for the anonymous {} struct, things like 'float', integers, etc.
232 if (Ty->getNumContainedTypes() == 0)
233 return *Entry = Ty;
234
235 // Remap all of the elements, keeping track of whether any of them change.
236 bool AnyChange = false;
237 SmallVector<Type*, 4> ElementTypes;
238 ElementTypes.resize(Ty->getNumContainedTypes());
239 for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) {
240 ElementTypes[i] = getImpl(Ty->getContainedType(i));
241 AnyChange |= ElementTypes[i] != Ty->getContainedType(i);
242 }
243
244 // If we found our type while recursively processing stuff, just use it.
245 Entry = &MappedTypes[Ty];
246 if (*Entry) return *Entry;
247
248 // If all of the element types mapped directly over, then the type is usable
249 // as-is.
250 if (!AnyChange)
251 return *Entry = Ty;
252
253 // Otherwise, rebuild a modified type.
254 switch (Ty->getTypeID()) {
255 default: assert(0 && "unknown derived type to remap");
256 case Type::ArrayTyID:
257 return *Entry = ArrayType::get(ElementTypes[0],
258 cast<ArrayType>(Ty)->getNumElements());
259 case Type::VectorTyID:
260 return *Entry = VectorType::get(ElementTypes[0],
261 cast<VectorType>(Ty)->getNumElements());
262 case Type::PointerTyID:
263 return *Entry = PointerType::get(ElementTypes[0],
264 cast<PointerType>(Ty)->getAddressSpace());
265 case Type::FunctionTyID:
266 return *Entry = FunctionType::get(ElementTypes[0],
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000267 makeArrayRef(ElementTypes).slice(1),
Chris Lattner1afcace2011-07-09 17:41:24 +0000268 cast<FunctionType>(Ty)->isVarArg());
269 case Type::StructTyID:
270 // Note that this is only reached for anonymous structs.
271 return *Entry = StructType::get(Ty->getContext(), ElementTypes,
272 cast<StructType>(Ty)->isPacked());
273 }
274 }
275
276 // Otherwise, this is an unmapped named struct. If the struct can be directly
277 // mapped over, just use it as-is. This happens in a case when the linked-in
278 // module has something like:
279 // %T = type {%T*, i32}
280 // @GV = global %T* null
281 // where T does not exist at all in the destination module.
282 //
283 // The other case we watch for is when the type is not in the destination
284 // module, but that it has to be rebuilt because it refers to something that
285 // is already mapped. For example, if the destination module has:
286 // %A = type { i32 }
287 // and the source module has something like
288 // %A' = type { i32 }
289 // %B = type { %A'* }
290 // @GV = global %B* null
291 // then we want to create a new type: "%B = type { %A*}" and have it take the
292 // pristine "%B" name from the source module.
293 //
294 // To determine which case this is, we have to recursively walk the type graph
295 // speculating that we'll be able to reuse it unmodified. Only if this is
296 // safe would we map the entire thing over. Because this is an optimization,
297 // and is not required for the prettiness of the linked module, we just skip
298 // it and always rebuild a type here.
299 StructType *STy = cast<StructType>(Ty);
300
301 // If the type is opaque, we can just use it directly.
302 if (STy->isOpaque())
303 return *Entry = STy;
304
305 // Otherwise we create a new type and resolve its body later. This will be
306 // resolved by the top level of get().
307 DefinitionsToResolve.push_back(STy);
Chris Lattner1bcbf852011-08-12 18:07:26 +0000308 return *Entry = StructType::create(STy->getContext());
Chris Lattner1afcace2011-07-09 17:41:24 +0000309}
310
311
312
313//===----------------------------------------------------------------------===//
314// ModuleLinker implementation.
315//===----------------------------------------------------------------------===//
316
317namespace {
318 /// ModuleLinker - This is an implementation class for the LinkModules
319 /// function, which is the entrypoint for this file.
320 class ModuleLinker {
321 Module *DstM, *SrcM;
322
323 TypeMapTy TypeMap;
324
325 /// ValueMap - Mapping of values from what they used to be in Src, to what
326 /// they are now in DstM. ValueToValueMapTy is a ValueMap, which involves
327 /// some overhead due to the use of Value handles which the Linker doesn't
328 /// actually need, but this allows us to reuse the ValueMapper code.
329 ValueToValueMapTy ValueMap;
330
331 struct AppendingVarInfo {
332 GlobalVariable *NewGV; // New aggregate global in dest module.
333 Constant *DstInit; // Old initializer from dest module.
334 Constant *SrcInit; // Old initializer from src module.
335 };
336
337 std::vector<AppendingVarInfo> AppendingVars;
338
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000339 unsigned Mode; // Mode to treat source module.
340
341 // Set of items not to link in from source.
342 SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
343
Tanya Lattner9af37a32011-11-02 00:24:56 +0000344 // Vector of functions to lazily link in.
345 std::vector<Function*> LazilyLinkFunctions;
346
Chris Lattner1afcace2011-07-09 17:41:24 +0000347 public:
348 std::string ErrorMsg;
349
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000350 ModuleLinker(Module *dstM, Module *srcM, unsigned mode)
351 : DstM(dstM), SrcM(srcM), Mode(mode) { }
Chris Lattner1afcace2011-07-09 17:41:24 +0000352
353 bool run();
354
355 private:
356 /// emitError - Helper method for setting a message and returning an error
357 /// code.
358 bool emitError(const Twine &Message) {
359 ErrorMsg = Message.str();
Chris Lattnerf6f4f7a2008-06-16 18:27:53 +0000360 return true;
Chris Lattnera4477f92008-06-16 21:17:12 +0000361 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000362
363 /// getLinkageResult - This analyzes the two global values and determines
364 /// what the result will look like in the destination module.
365 bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
366 GlobalValue::LinkageTypes &LT, bool &LinkFromSrc);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000367
Chris Lattner1afcace2011-07-09 17:41:24 +0000368 /// getLinkedToGlobal - Given a global in the source module, return the
369 /// global in the destination module that is being linked to, if any.
370 GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
371 // If the source has no name it can't link. If it has local linkage,
372 // there is no name match-up going on.
373 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
374 return 0;
375
376 // Otherwise see if we have a match in the destination module's symtab.
377 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
378 if (DGV == 0) return 0;
379
380 // If we found a global with the same name in the dest module, but it has
381 // internal linkage, we are really not doing any linkage here.
382 if (DGV->hasLocalLinkage())
383 return 0;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000384
Chris Lattner1afcace2011-07-09 17:41:24 +0000385 // Otherwise, we do in fact link to the destination global.
386 return DGV;
387 }
388
389 void computeTypeMapping();
390
391 bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
392 bool linkGlobalProto(GlobalVariable *SrcGV);
393 bool linkFunctionProto(Function *SrcF);
394 bool linkAliasProto(GlobalAlias *SrcA);
395
396 void linkAppendingVarInit(const AppendingVarInfo &AVI);
397 void linkGlobalInits();
398 void linkFunctionBody(Function *Dst, Function *Src);
399 void linkAliasBodies();
400 void linkNamedMDNodes();
401 };
Chris Lattnere3092c92003-08-23 21:25:54 +0000402}
403
Chris Lattnere76c57a2003-08-22 06:07:12 +0000404
Chris Lattner2c236f32001-11-03 05:18:24 +0000405
Chris Lattner1afcace2011-07-09 17:41:24 +0000406/// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
Reid Spencer8bef0372007-02-04 04:29:21 +0000407/// in the symbol table. This is good for all clients except for us. Go
408/// through the trouble to force this back.
Chris Lattner1afcace2011-07-09 17:41:24 +0000409static void forceRenaming(GlobalValue *GV, StringRef Name) {
410 // If the global doesn't force its name or if it already has the right name,
411 // there is nothing for us to do.
412 if (GV->hasLocalLinkage() || GV->getName() == Name)
413 return;
414
415 Module *M = GV->getParent();
Chris Lattnerc0036282004-08-04 07:05:54 +0000416
417 // If there is a conflict, rename the conflict.
Chris Lattner1afcace2011-07-09 17:41:24 +0000418 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
Chris Lattner33f29492007-02-11 00:39:38 +0000419 GV->takeName(ConflictGV);
420 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Chris Lattner1afcace2011-07-09 17:41:24 +0000421 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
Chris Lattner33f29492007-02-11 00:39:38 +0000422 } else {
423 GV->setName(Name); // Force the name back
Reid Spenceref9b9a72007-02-05 20:47:22 +0000424 }
Reid Spenceref9b9a72007-02-05 20:47:22 +0000425}
Reid Spencer8bef0372007-02-04 04:29:21 +0000426
Reid Spenceref9b9a72007-02-05 20:47:22 +0000427/// CopyGVAttributes - copy additional attributes (those not needed to construct
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000428/// a GlobalValue) from the SrcGV to the DestGV.
Reid Spenceref9b9a72007-02-05 20:47:22 +0000429static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
Duncan Sands28c3cff2008-05-26 19:58:59 +0000430 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
431 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
432 DestGV->copyAttributesFrom(SrcGV);
433 DestGV->setAlignment(Alignment);
Chris Lattner1afcace2011-07-09 17:41:24 +0000434
435 forceRenaming(DestGV, SrcGV->getName());
Chris Lattnerc0036282004-08-04 07:05:54 +0000436}
437
Chris Lattner1afcace2011-07-09 17:41:24 +0000438/// getLinkageResult - This analyzes the two global values and determines what
Chris Lattneraee38ea2004-12-03 22:18:41 +0000439/// the result will look like in the destination module. In particular, it
440/// computes the resultant linkage type, computes whether the global in the
441/// source should be copied over to the destination (replacing the existing
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +0000442/// one), and computes whether this linkage is an error or not. It also performs
443/// visibility checks: we cannot link together two symbols with different
444/// visibilities.
Chris Lattner1afcace2011-07-09 17:41:24 +0000445bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
446 GlobalValue::LinkageTypes &LT,
447 bool &LinkFromSrc) {
448 assert(Dest && "Must have two globals being queried");
449 assert(!Src->hasLocalLinkage() &&
Chris Lattneraee38ea2004-12-03 22:18:41 +0000450 "If Src has internal linkage, Dest shouldn't be set!");
Chris Lattner1afcace2011-07-09 17:41:24 +0000451
Peter Collingbourne88953162011-10-30 17:46:34 +0000452 bool SrcIsDeclaration = Src->isDeclaration() && !Src->isMaterializable();
Chris Lattnerf84c59d2011-07-14 20:23:05 +0000453 bool DestIsDeclaration = Dest->isDeclaration();
Chris Lattner1afcace2011-07-09 17:41:24 +0000454
455 if (SrcIsDeclaration) {
Anton Korobeynikov2b48ef02008-03-10 22:33:22 +0000456 // If Src is external or if both Src & Dest are external.. Just link the
Chris Lattneraee38ea2004-12-03 22:18:41 +0000457 // external globals, we aren't adding anything.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000458 if (Src->hasDLLImportLinkage()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000459 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
Chris Lattner1afcace2011-07-09 17:41:24 +0000460 if (DestIsDeclaration) {
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000461 LinkFromSrc = true;
462 LT = Src->getLinkage();
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000463 }
Andrew Lenharth8753c442006-12-15 17:35:32 +0000464 } else if (Dest->hasExternalWeakLinkage()) {
Duncan Sands667d4b82009-03-07 15:45:40 +0000465 // If the Dest is weak, use the source linkage.
Andrew Lenharth8753c442006-12-15 17:35:32 +0000466 LinkFromSrc = true;
467 LT = Src->getLinkage();
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000468 } else {
469 LinkFromSrc = false;
470 LT = Dest->getLinkage();
471 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000472 } else if (DestIsDeclaration && !Dest->hasDLLImportLinkage()) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000473 // If Dest is external but Src is not:
474 LinkFromSrc = true;
475 LT = Src->getLinkage();
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000476 } else if (Src->isWeakForLinker()) {
Dale Johannesenaafce772008-05-14 20:12:51 +0000477 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
478 // or DLL* linkage.
Chris Lattner266c7bb2009-04-13 05:44:34 +0000479 if (Dest->hasExternalWeakLinkage() ||
480 Dest->hasAvailableExternallyLinkage() ||
481 (Dest->hasLinkOnceLinkage() &&
482 (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000483 LinkFromSrc = true;
484 LT = Src->getLinkage();
485 } else {
486 LinkFromSrc = false;
487 LT = Dest->getLinkage();
488 }
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000489 } else if (Dest->isWeakForLinker()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000490 // At this point we know that Src has External* or DLL* linkage.
491 if (Src->hasExternalWeakLinkage()) {
492 LinkFromSrc = false;
493 LT = Dest->getLinkage();
494 } else {
495 LinkFromSrc = true;
496 LT = GlobalValue::ExternalLinkage;
497 }
Chris Lattneraee38ea2004-12-03 22:18:41 +0000498 } else {
Chris Lattner1afcace2011-07-09 17:41:24 +0000499 assert((Dest->hasExternalLinkage() || Dest->hasDLLImportLinkage() ||
500 Dest->hasDLLExportLinkage() || Dest->hasExternalWeakLinkage()) &&
501 (Src->hasExternalLinkage() || Src->hasDLLImportLinkage() ||
502 Src->hasDLLExportLinkage() || Src->hasExternalWeakLinkage()) &&
Chris Lattneraee38ea2004-12-03 22:18:41 +0000503 "Unexpected linkage type!");
Chris Lattner1afcace2011-07-09 17:41:24 +0000504 return emitError("Linking globals named '" + Src->getName() +
Chris Lattneraee38ea2004-12-03 22:18:41 +0000505 "': symbol multiply defined!");
506 }
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +0000507
508 // Check visibility
Chris Lattner1afcace2011-07-09 17:41:24 +0000509 if (Src->getVisibility() != Dest->getVisibility() &&
510 !SrcIsDeclaration && !DestIsDeclaration &&
Rafael Espindola4e938852011-02-01 05:33:52 +0000511 !Src->hasAvailableExternallyLinkage() &&
512 !Dest->hasAvailableExternallyLinkage())
Chris Lattner1afcace2011-07-09 17:41:24 +0000513 return emitError("Linking globals named '" + Src->getName() +
Chris Lattner97f8b092007-08-19 22:22:54 +0000514 "': symbols have different visibilities!");
Chris Lattneraee38ea2004-12-03 22:18:41 +0000515 return false;
516}
Chris Lattner5c377c52001-10-14 23:29:15 +0000517
Chris Lattner1afcace2011-07-09 17:41:24 +0000518/// computeTypeMapping - Loop over all of the linked values to compute type
519/// mappings. For example, if we link "extern Foo *x" and "Foo *x = NULL", then
520/// we have two struct types 'Foo' but one got renamed when the module was
521/// loaded into the same LLVMContext.
522void ModuleLinker::computeTypeMapping() {
523 // Incorporate globals.
524 for (Module::global_iterator I = SrcM->global_begin(),
525 E = SrcM->global_end(); I != E; ++I) {
526 GlobalValue *DGV = getLinkedToGlobal(I);
527 if (DGV == 0) continue;
528
529 if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
530 TypeMap.addTypeMapping(DGV->getType(), I->getType());
531 continue;
532 }
533
534 // Unify the element type of appending arrays.
535 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
536 ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
537 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
Devang Patelab67e702009-08-11 18:01:24 +0000538 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000539
540 // Incorporate functions.
541 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
542 if (GlobalValue *DGV = getLinkedToGlobal(I))
543 TypeMap.addTypeMapping(DGV->getType(), I->getType());
544 }
545
Chris Lattner9646acf2011-12-16 08:36:07 +0000546 // Incorporate types by name, scanning all the types in the source module.
547 // At this point, the destination module may have a type "%foo = { i32 }" for
548 // example. When the source module got loaded into the same LLVMContext, if
549 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
550 // Though it isn't required for correctness, attempt to link these up to clean
551 // up the IR.
552 std::vector<StructType*> SrcStructTypes;
553 SrcM->findUsedStructTypes(SrcStructTypes);
554
555 for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
556 StructType *ST = SrcStructTypes[i];
557 if (!ST->hasName()) continue;
558
559 // Check to see if there is a dot in the name followed by a digit.
560 size_t DotPos = ST->getName().rfind('.');
561 if (DotPos == 0 || DotPos == StringRef::npos ||
562 ST->getName().back() == '.' || !isdigit(ST->getName()[DotPos+1]))
563 continue;
564
565 // Check to see if the destination module has a struct with the prefix name.
566 if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
567 TypeMap.addTypeMapping(DST, ST);
568 }
569
570
Chris Lattner1afcace2011-07-09 17:41:24 +0000571 // Don't bother incorporating aliases, they aren't generally typed well.
572
573 // Now that we have discovered all of the type equivalences, get a body for
574 // any 'opaque' types in the dest module that are now resolved.
575 TypeMap.linkDefinedTypeBodies();
Devang Patelab67e702009-08-11 18:01:24 +0000576}
577
Chris Lattner1afcace2011-07-09 17:41:24 +0000578/// linkAppendingVarProto - If there were any appending global variables, link
579/// them together now. Return true on error.
580bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
581 GlobalVariable *SrcGV) {
582
583 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
584 return emitError("Linking globals named '" + SrcGV->getName() +
585 "': can only link appending global with another appending global!");
586
587 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
588 ArrayType *SrcTy =
589 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
590 Type *EltTy = DstTy->getElementType();
591
592 // Check to see that they two arrays agree on type.
593 if (EltTy != SrcTy->getElementType())
594 return emitError("Appending variables with different element types!");
595 if (DstGV->isConstant() != SrcGV->isConstant())
596 return emitError("Appending variables linked with different const'ness!");
597
598 if (DstGV->getAlignment() != SrcGV->getAlignment())
599 return emitError(
600 "Appending variables with different alignment need to be linked!");
601
602 if (DstGV->getVisibility() != SrcGV->getVisibility())
603 return emitError(
604 "Appending variables with different visibility need to be linked!");
605
606 if (DstGV->getSection() != SrcGV->getSection())
607 return emitError(
608 "Appending variables with different section name need to be linked!");
609
610 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
611 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
612
613 // Create the new global variable.
614 GlobalVariable *NG =
615 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
616 DstGV->getLinkage(), /*init*/0, /*name*/"", DstGV,
617 DstGV->isThreadLocal(),
618 DstGV->getType()->getAddressSpace());
619
620 // Propagate alignment, visibility and section info.
621 CopyGVAttributes(NG, DstGV);
622
623 AppendingVarInfo AVI;
624 AVI.NewGV = NG;
625 AVI.DstInit = DstGV->getInitializer();
626 AVI.SrcInit = SrcGV->getInitializer();
627 AppendingVars.push_back(AVI);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000628
Chris Lattner1afcace2011-07-09 17:41:24 +0000629 // Replace any uses of the two global variables with uses of the new
630 // global.
631 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000632
Chris Lattner1afcace2011-07-09 17:41:24 +0000633 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
634 DstGV->eraseFromParent();
635
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000636 // Track the source variable so we don't try to link it.
637 DoNotLinkFromSource.insert(SrcGV);
638
Chris Lattner1afcace2011-07-09 17:41:24 +0000639 return false;
640}
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000641
Chris Lattner1afcace2011-07-09 17:41:24 +0000642/// linkGlobalProto - Loop through the global variables in the src module and
643/// merge them into the dest module.
644bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
645 GlobalValue *DGV = getLinkedToGlobal(SGV);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000646
Chris Lattner1afcace2011-07-09 17:41:24 +0000647 if (DGV) {
648 // Concatenation of appending linkage variables is magic and handled later.
649 if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
650 return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
651
652 // Determine whether linkage of these two globals follows the source
653 // module's definition or the destination module's definition.
Chris Lattnerb324bd72006-11-09 05:18:12 +0000654 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
655 bool LinkFromSrc = false;
Chris Lattner1afcace2011-07-09 17:41:24 +0000656 if (getLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc))
Chris Lattneraee38ea2004-12-03 22:18:41 +0000657 return true;
Chris Lattner0fec08e2003-04-21 21:07:05 +0000658
Chris Lattner1afcace2011-07-09 17:41:24 +0000659 // If we're not linking from the source, then keep the definition that we
660 // have.
661 if (!LinkFromSrc) {
662 // Special case for const propagation.
663 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
664 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
665 DGVar->setConstant(true);
666
667 // Set calculated linkage.
668 DGV->setLinkage(NewLinkage);
669
Chris Lattner6157e382008-07-14 07:23:24 +0000670 // Make sure to remember this mapping.
Chris Lattner1afcace2011-07-09 17:41:24 +0000671 ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
672
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000673 // Track the source global so that we don't attempt to copy it over when
674 // processing global initializers.
675 DoNotLinkFromSource.insert(SGV);
676
Chris Lattner1afcace2011-07-09 17:41:24 +0000677 return false;
Chris Lattner6157e382008-07-14 07:23:24 +0000678 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000679 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000680
681 // No linking to be performed or linking from the source: simply create an
682 // identical version of the symbol over in the dest module... the
683 // initializer will be filled in later by LinkGlobalInits.
684 GlobalVariable *NewDGV =
685 new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
686 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
687 SGV->getName(), /*insertbefore*/0,
688 SGV->isThreadLocal(),
689 SGV->getType()->getAddressSpace());
690 // Propagate alignment, visibility and section info.
691 CopyGVAttributes(NewDGV, SGV);
692
693 if (DGV) {
694 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
695 DGV->eraseFromParent();
696 }
697
698 // Make sure to remember this mapping.
699 ValueMap[SGV] = NewDGV;
Chris Lattner5c377c52001-10-14 23:29:15 +0000700 return false;
701}
702
Chris Lattner1afcace2011-07-09 17:41:24 +0000703/// linkFunctionProto - Link the function in the source module into the
704/// destination module if needed, setting up mapping information.
705bool ModuleLinker::linkFunctionProto(Function *SF) {
706 GlobalValue *DGV = getLinkedToGlobal(SF);
707
708 if (DGV) {
709 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
710 bool LinkFromSrc = false;
711 if (getLinkageResult(DGV, SF, NewLinkage, LinkFromSrc))
712 return true;
713
714 if (!LinkFromSrc) {
715 // Set calculated linkage
716 DGV->setLinkage(NewLinkage);
717
718 // Make sure to remember this mapping.
719 ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
720
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000721 // Track the function from the source module so we don't attempt to remap
722 // it.
723 DoNotLinkFromSource.insert(SF);
724
Chris Lattner1afcace2011-07-09 17:41:24 +0000725 return false;
726 }
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000727 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000728
729 // If there is no linkage to be performed or we are linking from the source,
730 // bring SF over.
731 Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
732 SF->getLinkage(), SF->getName(), DstM);
733 CopyGVAttributes(NewDF, SF);
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000734
Chris Lattner1afcace2011-07-09 17:41:24 +0000735 if (DGV) {
736 // Any uses of DF need to change to NewDF, with cast.
737 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
738 DGV->eraseFromParent();
Tanya Lattner9af37a32011-11-02 00:24:56 +0000739 } else {
740 // Internal, LO_ODR, or LO linkage - stick in set to ignore and lazily link.
741 if (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
742 SF->hasAvailableExternallyLinkage()) {
743 DoNotLinkFromSource.insert(SF);
744 LazilyLinkFunctions.push_back(SF);
745 }
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000746 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000747
748 ValueMap[SF] = NewDF;
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000749 return false;
750}
751
Chris Lattner1afcace2011-07-09 17:41:24 +0000752/// LinkAliasProto - Set up prototypes for any aliases that come over from the
753/// source module.
754bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
755 GlobalValue *DGV = getLinkedToGlobal(SGA);
756
757 if (DGV) {
758 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
759 bool LinkFromSrc = false;
760 if (getLinkageResult(DGV, SGA, NewLinkage, LinkFromSrc))
761 return true;
762
763 if (!LinkFromSrc) {
764 // Set calculated linkage.
765 DGV->setLinkage(NewLinkage);
766
767 // Make sure to remember this mapping.
768 ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
769
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000770 // Track the alias from the source module so we don't attempt to remap it.
771 DoNotLinkFromSource.insert(SGA);
772
Chris Lattner1afcace2011-07-09 17:41:24 +0000773 return false;
774 }
775 }
776
777 // If there is no linkage to be performed or we're linking from the source,
778 // bring over SGA.
779 GlobalAlias *NewDA = new GlobalAlias(TypeMap.get(SGA->getType()),
780 SGA->getLinkage(), SGA->getName(),
781 /*aliasee*/0, DstM);
782 CopyGVAttributes(NewDA, SGA);
Chris Lattner5c377c52001-10-14 23:29:15 +0000783
Chris Lattner1afcace2011-07-09 17:41:24 +0000784 if (DGV) {
785 // Any uses of DGV need to change to NewDA, with cast.
786 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
787 DGV->eraseFromParent();
788 }
789
790 ValueMap[SGA] = NewDA;
791 return false;
792}
793
794void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
795 // Merge the initializer.
796 SmallVector<Constant*, 16> Elements;
797 if (ConstantArray *I = dyn_cast<ConstantArray>(AVI.DstInit)) {
798 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
799 Elements.push_back(I->getOperand(i));
800 } else {
801 assert(isa<ConstantAggregateZero>(AVI.DstInit));
802 ArrayType *DstAT = cast<ArrayType>(AVI.DstInit->getType());
803 Type *EltTy = DstAT->getElementType();
804 Elements.append(DstAT->getNumElements(), Constant::getNullValue(EltTy));
805 }
806
807 Constant *SrcInit = MapValue(AVI.SrcInit, ValueMap, RF_None, &TypeMap);
808 if (const ConstantArray *I = dyn_cast<ConstantArray>(SrcInit)) {
809 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
810 Elements.push_back(I->getOperand(i));
811 } else {
812 assert(isa<ConstantAggregateZero>(SrcInit));
813 ArrayType *SrcAT = cast<ArrayType>(SrcInit->getType());
814 Type *EltTy = SrcAT->getElementType();
815 Elements.append(SrcAT->getNumElements(), Constant::getNullValue(EltTy));
816 }
817 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
818 AVI.NewGV->setInitializer(ConstantArray::get(NewType, Elements));
819}
820
821
822// linkGlobalInits - Update the initializers in the Dest module now that all
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000823// globals that may be referenced are in Dest.
Chris Lattner1afcace2011-07-09 17:41:24 +0000824void ModuleLinker::linkGlobalInits() {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000825 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattner1afcace2011-07-09 17:41:24 +0000826 for (Module::const_global_iterator I = SrcM->global_begin(),
827 E = SrcM->global_end(); I != E; ++I) {
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000828
829 // Only process initialized GV's or ones not already in dest.
830 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
Chris Lattner1afcace2011-07-09 17:41:24 +0000831
832 // Grab destination global variable.
833 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
834 // Figure out what the initializer looks like in the dest module.
835 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
836 RF_None, &TypeMap));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000837 }
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000838}
Chris Lattner5c377c52001-10-14 23:29:15 +0000839
Chris Lattner1afcace2011-07-09 17:41:24 +0000840// linkFunctionBody - Copy the source function over into the dest function and
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000841// fix up references to values. At this point we know that Dest is an external
842// function, and that Src is not.
Chris Lattner1afcace2011-07-09 17:41:24 +0000843void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
844 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
Chris Lattner5c377c52001-10-14 23:29:15 +0000845
Chris Lattner0033baf2004-11-16 17:12:38 +0000846 // Go through and convert function arguments over, remembering the mapping.
Chris Lattner1afcace2011-07-09 17:41:24 +0000847 Function::arg_iterator DI = Dst->arg_begin();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000848 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
Chris Lattner69da5cf2002-10-13 20:57:00 +0000849 I != E; ++I, ++DI) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000850 DI->setName(I->getName()); // Copy the name over.
Chris Lattner5c377c52001-10-14 23:29:15 +0000851
Chris Lattner1afcace2011-07-09 17:41:24 +0000852 // Add a mapping to our mapping.
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000853 ValueMap[I] = DI;
Chris Lattner5c377c52001-10-14 23:29:15 +0000854 }
855
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000856 if (Mode == Linker::DestroySource) {
857 // Splice the body of the source function into the dest function.
858 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
859
860 // At this point, all of the instructions and values of the function are now
861 // copied over. The only problem is that they are still referencing values in
862 // the Source function as operands. Loop through all of the operands of the
863 // functions and patch them up to point to the local versions.
864 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
865 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
866 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap);
867
868 } else {
869 // Clone the body of the function into the dest function.
870 SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
871 CloneFunctionInto(Dst, Src, ValueMap, false, Returns);
872 }
873
Chris Lattner0033baf2004-11-16 17:12:38 +0000874 // There is no need to map the arguments anymore.
Chris Lattner11273152006-06-16 01:24:04 +0000875 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
876 I != E; ++I)
Reid Spenceref9b9a72007-02-05 20:47:22 +0000877 ValueMap.erase(I);
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000878
Chris Lattner5c377c52001-10-14 23:29:15 +0000879}
880
881
Chris Lattner1afcace2011-07-09 17:41:24 +0000882void ModuleLinker::linkAliasBodies() {
883 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000884 I != E; ++I) {
885 if (DoNotLinkFromSource.count(I))
886 continue;
Chris Lattner1afcace2011-07-09 17:41:24 +0000887 if (Constant *Aliasee = I->getAliasee()) {
888 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
889 DA->setAliasee(MapValue(Aliasee, ValueMap, RF_None, &TypeMap));
David Chisnall34722462010-01-09 16:27:31 +0000890 }
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000891 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000892}
Anton Korobeynikov9f2ee702008-03-05 23:21:39 +0000893
Chris Lattner1afcace2011-07-09 17:41:24 +0000894/// linkNamedMDNodes - Insert all of the named mdnodes in Src into the Dest
895/// module.
896void ModuleLinker::linkNamedMDNodes() {
897 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
898 E = SrcM->named_metadata_end(); I != E; ++I) {
899 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
900 // Add Src elements into Dest node.
901 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
902 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
903 RF_None, &TypeMap));
904 }
905}
906
907bool ModuleLinker::run() {
908 assert(DstM && "Null Destination module");
909 assert(SrcM && "Null Source Module");
910
911 // Inherit the target data from the source module if the destination module
912 // doesn't have one already.
913 if (DstM->getDataLayout().empty() && !SrcM->getDataLayout().empty())
914 DstM->setDataLayout(SrcM->getDataLayout());
915
916 // Copy the target triple from the source to dest if the dest's is empty.
917 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
918 DstM->setTargetTriple(SrcM->getTargetTriple());
919
920 if (!SrcM->getDataLayout().empty() && !DstM->getDataLayout().empty() &&
921 SrcM->getDataLayout() != DstM->getDataLayout())
922 errs() << "WARNING: Linking two modules of different data layouts!\n";
923 if (!SrcM->getTargetTriple().empty() &&
924 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
925 errs() << "WARNING: Linking two modules of different target triples: ";
926 if (!SrcM->getModuleIdentifier().empty())
927 errs() << SrcM->getModuleIdentifier() << ": ";
928 errs() << "'" << SrcM->getTargetTriple() << "' and '"
929 << DstM->getTargetTriple() << "'\n";
930 }
931
932 // Append the module inline asm string.
933 if (!SrcM->getModuleInlineAsm().empty()) {
934 if (DstM->getModuleInlineAsm().empty())
935 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
936 else
937 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
938 SrcM->getModuleInlineAsm());
939 }
940
941 // Update the destination module's dependent libraries list with the libraries
942 // from the source module. There's no opportunity for duplicates here as the
943 // Module ensures that duplicate insertions are discarded.
944 for (Module::lib_iterator SI = SrcM->lib_begin(), SE = SrcM->lib_end();
945 SI != SE; ++SI)
946 DstM->addLibrary(*SI);
947
948 // If the source library's module id is in the dependent library list of the
949 // destination library, remove it since that module is now linked in.
950 StringRef ModuleId = SrcM->getModuleIdentifier();
951 if (!ModuleId.empty())
952 DstM->removeLibrary(sys::path::stem(ModuleId));
Chris Lattner1afcace2011-07-09 17:41:24 +0000953
954 // Loop over all of the linked values to compute type mappings.
955 computeTypeMapping();
956
957 // Insert all of the globals in src into the DstM module... without linking
958 // initializers (which could refer to functions not yet mapped over).
959 for (Module::global_iterator I = SrcM->global_begin(),
960 E = SrcM->global_end(); I != E; ++I)
961 if (linkGlobalProto(I))
962 return true;
963
964 // Link the functions together between the two modules, without doing function
965 // bodies... this just adds external function prototypes to the DstM
966 // function... We do this so that when we begin processing function bodies,
967 // all of the global values that may be referenced are available in our
968 // ValueMap.
969 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
970 if (linkFunctionProto(I))
971 return true;
972
973 // If there were any aliases, link them now.
974 for (Module::alias_iterator I = SrcM->alias_begin(),
975 E = SrcM->alias_end(); I != E; ++I)
976 if (linkAliasProto(I))
977 return true;
978
979 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
980 linkAppendingVarInit(AppendingVars[i]);
981
982 // Update the initializers in the DstM module now that all globals that may
983 // be referenced are in DstM.
984 linkGlobalInits();
985
986 // Link in the function bodies that are defined in the source module into
987 // DstM.
988 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
Tanya Lattner2b28a742011-10-14 22:17:46 +0000989
990 // Skip if not linking from source.
991 if (DoNotLinkFromSource.count(SF)) continue;
992
993 // Skip if no body (function is external) or materialize.
994 if (SF->isDeclaration()) {
995 if (!SF->isMaterializable())
996 continue;
997 if (SF->Materialize(&ErrorMsg))
998 return true;
999 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001000
1001 linkFunctionBody(cast<Function>(ValueMap[SF]), SF);
1002 }
1003
1004 // Resolve all uses of aliases with aliasees.
1005 linkAliasBodies();
1006
Devang Patel211da8f2011-08-04 19:44:28 +00001007 // Remap all of the named mdnoes in Src into the DstM module. We do this
1008 // after linking GlobalValues so that MDNodes that reference GlobalValues
1009 // are properly remapped.
1010 linkNamedMDNodes();
1011
Tanya Lattner9af37a32011-11-02 00:24:56 +00001012 // Process vector of lazily linked in functions.
1013 bool LinkedInAnyFunctions;
1014 do {
1015 LinkedInAnyFunctions = false;
1016
1017 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1018 E = LazilyLinkFunctions.end(); I != E; ++I) {
1019 if (!*I)
1020 continue;
1021
1022 Function *SF = *I;
1023 Function *DF = cast<Function>(ValueMap[SF]);
1024
1025 if (!DF->use_empty()) {
1026
1027 // Materialize if necessary.
1028 if (SF->isDeclaration()) {
1029 if (!SF->isMaterializable())
1030 continue;
1031 if (SF->Materialize(&ErrorMsg))
1032 return true;
1033 }
1034
1035 // Link in function body.
1036 linkFunctionBody(DF, SF);
1037
1038 // "Remove" from vector by setting the element to 0.
1039 *I = 0;
1040
1041 // Set flag to indicate we may have more functions to lazily link in
1042 // since we linked in a function.
1043 LinkedInAnyFunctions = true;
1044 }
1045 }
1046 } while (LinkedInAnyFunctions);
1047
1048 // Remove any prototypes of functions that were not actually linked in.
1049 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1050 E = LazilyLinkFunctions.end(); I != E; ++I) {
1051 if (!*I)
1052 continue;
1053
1054 Function *SF = *I;
1055 Function *DF = cast<Function>(ValueMap[SF]);
1056 if (DF->use_empty())
1057 DF->eraseFromParent();
1058 }
1059
Chris Lattner1afcace2011-07-09 17:41:24 +00001060 // Now that all of the types from the source are used, resolve any structs
1061 // copied over to the dest that didn't exist there.
1062 TypeMap.linkDefinedTypeBodies();
1063
Anton Korobeynikov9f2ee702008-03-05 23:21:39 +00001064 return false;
1065}
Chris Lattner52f7e902001-10-13 07:03:50 +00001066
Chris Lattner1afcace2011-07-09 17:41:24 +00001067//===----------------------------------------------------------------------===//
1068// LinkModules entrypoint.
1069//===----------------------------------------------------------------------===//
1070
Chris Lattner52f7e902001-10-13 07:03:50 +00001071// LinkModules - This function links two modules together, with the resulting
1072// left module modified to be the composite of the two input modules. If an
1073// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
Chris Lattner5c377c52001-10-14 23:29:15 +00001074// the problem. Upon failure, the Dest module could be in a modified state, and
1075// shouldn't be relied on to be consistent.
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +00001076bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode,
1077 std::string *ErrorMsg) {
1078 ModuleLinker TheLinker(Dest, Src, Mode);
Chris Lattner1afcace2011-07-09 17:41:24 +00001079 if (TheLinker.run()) {
1080 if (ErrorMsg) *ErrorMsg = TheLinker.ErrorMsg;
Reid Spencer619f0242007-02-04 04:43:17 +00001081 return true;
Chris Lattner5a837de2004-08-04 07:44:58 +00001082 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001083
Chris Lattner52f7e902001-10-13 07:03:50 +00001084 return false;
1085}