blob: 1f089e4c8f486f5fd62fadffe3754c992a0cf057 [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"
Chris Lattner74382b72009-08-23 22:45:37 +000023#include "llvm/Support/raw_ostream.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000024#include "llvm/Support/Path.h"
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +000025#include "llvm/Transforms/Utils/Cloning.h"
Dan Gohman05ea54e2010-08-24 18:50:07 +000026#include "llvm/Transforms/Utils/ValueMapper.h"
Bill Wendlingcb8a7ed2012-02-28 03:47:09 +000027
28#include "llvm/Support/Debug.h"
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 {
Bill Wendlingcb8a7ed2012-02-28 03:47:09 +000036
Chris Lattner1afcace2011-07-09 17:41:24 +000037class TypeMapTy : public ValueMapTypeRemapper {
38 /// MappedTypes - This is a mapping from a source type to a destination type
39 /// to use.
40 DenseMap<Type*, Type*> MappedTypes;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +000041
Chris Lattner1afcace2011-07-09 17:41:24 +000042 /// SpeculativeTypes - When checking to see if two subgraphs are isomorphic,
43 /// we speculatively add types to MappedTypes, but keep track of them here in
44 /// case we need to roll back.
45 SmallVector<Type*, 16> SpeculativeTypes;
46
Chris Lattner68910502011-12-20 00:03:52 +000047 /// SrcDefinitionsToResolve - This is a list of non-opaque structs in the
48 /// source module that are mapped to an opaque struct in the destination
49 /// module.
50 SmallVector<StructType*, 16> SrcDefinitionsToResolve;
51
52 /// DstResolvedOpaqueTypes - This is the set of opaque types in the
53 /// destination modules who are getting a body from the source module.
54 SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
Bill Wendlingcb8a7ed2012-02-28 03:47:09 +000055
Chris Lattnerfc196f92008-06-16 23:06:51 +000056public:
Chris Lattner1afcace2011-07-09 17:41:24 +000057 /// addTypeMapping - Indicate that the specified type in the destination
58 /// module is conceptually equivalent to the specified type in the source
59 /// module.
60 void addTypeMapping(Type *DstTy, Type *SrcTy);
61
62 /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
63 /// module from a type definition in the source module.
64 void linkDefinedTypeBodies();
65
66 /// get - Return the mapped type to use for the specified input type from the
67 /// source module.
68 Type *get(Type *SrcTy);
69
70 FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*)T));}
71
72private:
73 Type *getImpl(Type *T);
74 /// remapType - Implement the ValueMapTypeRemapper interface.
75 Type *remapType(Type *SrcTy) {
76 return get(SrcTy);
Chris Lattner62a81a12008-06-16 21:00:18 +000077 }
Chris Lattner1afcace2011-07-09 17:41:24 +000078
79 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
Chris Lattner62a81a12008-06-16 21:00:18 +000080};
Bill Wendlingcb8a7ed2012-02-28 03:47:09 +000081
82} // end anonymous namespace
83
84/// endsInDotNumber - Check to see if there is a dot in the name followed by a
85/// digit.
86static bool endsInDotNumber(StructType *Ty) {
87 size_t DotPos = Ty->getName().rfind('.');
88 return DotPos != 0 && DotPos != StringRef::npos &&
89 Ty->getName().back() != '.' && isdigit(Ty->getName()[DotPos + 1]);
Chris Lattner62a81a12008-06-16 21:00:18 +000090}
91
Chris Lattner1afcace2011-07-09 17:41:24 +000092void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
93 Type *&Entry = MappedTypes[SrcTy];
94 if (Entry) return;
95
96 if (DstTy == SrcTy) {
97 Entry = DstTy;
98 return;
99 }
Bill Wendlingcb8a7ed2012-02-28 03:47:09 +0000100
Chris Lattner1afcace2011-07-09 17:41:24 +0000101 // Check to see if these types are recursively isomorphic and establish a
102 // mapping between them if so.
Bill Wendlingcb8a7ed2012-02-28 03:47:09 +0000103 if (!areTypesIsomorphic(DstTy, SrcTy))
Chris Lattner1afcace2011-07-09 17:41:24 +0000104 // Oops, they aren't isomorphic. Just discard this request by rolling out
105 // any speculative mappings we've established.
106 for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i)
107 MappedTypes.erase(SpeculativeTypes[i]);
Bill Wendlingcb8a7ed2012-02-28 03:47:09 +0000108
Chris Lattner1afcace2011-07-09 17:41:24 +0000109 SpeculativeTypes.clear();
110}
Chris Lattner62a81a12008-06-16 21:00:18 +0000111
Chris Lattner1afcace2011-07-09 17:41:24 +0000112/// areTypesIsomorphic - Recursively walk this pair of types, returning true
113/// if they are isomorphic, false if they are not.
114bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
115 // Two types with differing kinds are clearly not isomorphic.
116 if (DstTy->getTypeID() != SrcTy->getTypeID()) return false;
Misha Brukmanf976c852005-04-21 22:55:34 +0000117
Chris Lattner1afcace2011-07-09 17:41:24 +0000118 // If we have an entry in the MappedTypes table, then we have our answer.
119 Type *&Entry = MappedTypes[SrcTy];
120 if (Entry)
121 return Entry == DstTy;
Misha Brukmanf976c852005-04-21 22:55:34 +0000122
Chris Lattner1afcace2011-07-09 17:41:24 +0000123 // Two identical types are clearly isomorphic. Remember this
124 // non-speculatively.
125 if (DstTy == SrcTy) {
126 Entry = DstTy;
Chris Lattner56539652008-06-16 20:03:01 +0000127 return true;
Chris Lattner1afcace2011-07-09 17:41:24 +0000128 }
Bill Wendlingcb8a7ed2012-02-28 03:47:09 +0000129
Chris Lattner1afcace2011-07-09 17:41:24 +0000130 // Okay, we have two types with identical kinds that we haven't seen before.
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000131
Chris Lattner1afcace2011-07-09 17:41:24 +0000132 // If this is an opaque struct type, special case it.
133 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
134 // Mapping an opaque type to any struct, just keep the dest struct.
135 if (SSTy->isOpaque()) {
136 Entry = DstTy;
137 SpeculativeTypes.push_back(SrcTy);
Chris Lattner43f4ba82003-08-22 19:12:55 +0000138 return true;
Chris Lattnera4477f92008-06-16 21:17:12 +0000139 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000140
Chris Lattner68910502011-12-20 00:03:52 +0000141 // Mapping a non-opaque source type to an opaque dest. If this is the first
142 // type that we're mapping onto this destination type then we succeed. Keep
143 // the dest, but fill it in later. This doesn't need to be speculative. If
144 // this is the second (different) type that we're trying to map onto the
145 // same opaque type then we fail.
Chris Lattner1afcace2011-07-09 17:41:24 +0000146 if (cast<StructType>(DstTy)->isOpaque()) {
Chris Lattner68910502011-12-20 00:03:52 +0000147 // We can only map one source type onto the opaque destination type.
148 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)))
149 return false;
150 SrcDefinitionsToResolve.push_back(SSTy);
Chris Lattner1afcace2011-07-09 17:41:24 +0000151 Entry = DstTy;
Chris Lattner1afcace2011-07-09 17:41:24 +0000152 return true;
153 }
154 }
155
156 // If the number of subtypes disagree between the two types, then we fail.
157 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
Chris Lattnere76c57a2003-08-22 06:07:12 +0000158 return false;
Chris Lattner1afcace2011-07-09 17:41:24 +0000159
160 // Fail if any of the extra properties (e.g. array size) of the type disagree.
161 if (isa<IntegerType>(DstTy))
162 return false; // bitwidth disagrees.
163 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
164 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
165 return false;
Chris Lattner1a31f3b2011-12-20 23:14:57 +0000166
Chris Lattner1afcace2011-07-09 17:41:24 +0000167 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
168 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
169 return false;
170 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
171 StructType *SSTy = cast<StructType>(SrcTy);
Chris Lattner1bcbf852011-08-12 18:07:26 +0000172 if (DSTy->isLiteral() != SSTy->isLiteral() ||
Chris Lattner1afcace2011-07-09 17:41:24 +0000173 DSTy->isPacked() != SSTy->isPacked())
174 return false;
175 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
176 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
177 return false;
178 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
179 if (DVTy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
180 return false;
Chris Lattnere76c57a2003-08-22 06:07:12 +0000181 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000182
183 // Otherwise, we speculate that these two types will line up and recursively
184 // check the subelements.
185 Entry = DstTy;
186 SpeculativeTypes.push_back(SrcTy);
187
Bill Wendlingcb8a7ed2012-02-28 03:47:09 +0000188 for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i) {
189 Type *SrcSubTy = SrcTy->getContainedType(i);
190 Type *DstSubTy = DstTy->getContainedType(i);
191
192 if (StructType *DST = dyn_cast<StructType>(DstSubTy))
193 if (DST->hasName() && endsInDotNumber(DST))
194 std::swap(SrcSubTy, DstSubTy);
195
196 if (!areTypesIsomorphic(DstSubTy, SrcSubTy))
Chris Lattner1afcace2011-07-09 17:41:24 +0000197 return false;
Bill Wendlingcb8a7ed2012-02-28 03:47:09 +0000198 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000199
200 // If everything seems to have lined up, then everything is great.
201 return true;
202}
203
204/// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
205/// module from a type definition in the source module.
206void TypeMapTy::linkDefinedTypeBodies() {
207 SmallVector<Type*, 16> Elements;
208 SmallString<16> TmpName;
209
210 // Note that processing entries in this loop (calling 'get') can add new
Chris Lattner68910502011-12-20 00:03:52 +0000211 // entries to the SrcDefinitionsToResolve vector.
212 while (!SrcDefinitionsToResolve.empty()) {
213 StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val();
Chris Lattner1afcace2011-07-09 17:41:24 +0000214 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
215
216 // TypeMap is a many-to-one mapping, if there were multiple types that
217 // provide a body for DstSTy then previous iterations of this loop may have
218 // already handled it. Just ignore this case.
219 if (!DstSTy->isOpaque()) continue;
220 assert(!SrcSTy->isOpaque() && "Not resolving a definition?");
221
222 // Map the body of the source type over to a new body for the dest type.
223 Elements.resize(SrcSTy->getNumElements());
224 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
225 Elements[i] = getImpl(SrcSTy->getElementType(i));
226
227 DstSTy->setBody(Elements, SrcSTy->isPacked());
228
229 // If DstSTy has no name or has a longer name than STy, then viciously steal
230 // STy's name.
231 if (!SrcSTy->hasName()) continue;
232 StringRef SrcName = SrcSTy->getName();
233
234 if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
235 TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
236 SrcSTy->setName("");
237 DstSTy->setName(TmpName.str());
238 TmpName.clear();
239 }
240 }
Chris Lattner68910502011-12-20 00:03:52 +0000241
242 DstResolvedOpaqueTypes.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000243}
244
Chris Lattner1afcace2011-07-09 17:41:24 +0000245/// get - Return the mapped type to use for the specified input type from the
246/// source module.
247Type *TypeMapTy::get(Type *Ty) {
248 Type *Result = getImpl(Ty);
249
250 // If this caused a reference to any struct type, resolve it before returning.
Chris Lattner68910502011-12-20 00:03:52 +0000251 if (!SrcDefinitionsToResolve.empty())
Chris Lattner1afcace2011-07-09 17:41:24 +0000252 linkDefinedTypeBodies();
253 return Result;
254}
255
256/// getImpl - This is the recursive version of get().
257Type *TypeMapTy::getImpl(Type *Ty) {
258 // If we already have an entry for this type, return it.
259 Type **Entry = &MappedTypes[Ty];
260 if (*Entry) return *Entry;
Bill Wendlingcb8a7ed2012-02-28 03:47:09 +0000261
Chris Lattner1afcace2011-07-09 17:41:24 +0000262 // If this is not a named struct type, then just map all of the elements and
263 // then rebuild the type from inside out.
Chris Lattner1bcbf852011-08-12 18:07:26 +0000264 if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000265 // If there are no element types to map, then the type is itself. This is
266 // true for the anonymous {} struct, things like 'float', integers, etc.
267 if (Ty->getNumContainedTypes() == 0)
268 return *Entry = Ty;
269
270 // Remap all of the elements, keeping track of whether any of them change.
271 bool AnyChange = false;
272 SmallVector<Type*, 4> ElementTypes;
273 ElementTypes.resize(Ty->getNumContainedTypes());
274 for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) {
275 ElementTypes[i] = getImpl(Ty->getContainedType(i));
276 AnyChange |= ElementTypes[i] != Ty->getContainedType(i);
277 }
278
279 // If we found our type while recursively processing stuff, just use it.
280 Entry = &MappedTypes[Ty];
281 if (*Entry) return *Entry;
282
283 // If all of the element types mapped directly over, then the type is usable
284 // as-is.
285 if (!AnyChange)
286 return *Entry = Ty;
287
288 // Otherwise, rebuild a modified type.
289 switch (Ty->getTypeID()) {
Craig Topper85814382012-02-07 05:05:23 +0000290 default: llvm_unreachable("unknown derived type to remap");
Chris Lattner1afcace2011-07-09 17:41:24 +0000291 case Type::ArrayTyID:
292 return *Entry = ArrayType::get(ElementTypes[0],
293 cast<ArrayType>(Ty)->getNumElements());
294 case Type::VectorTyID:
295 return *Entry = VectorType::get(ElementTypes[0],
296 cast<VectorType>(Ty)->getNumElements());
297 case Type::PointerTyID:
298 return *Entry = PointerType::get(ElementTypes[0],
299 cast<PointerType>(Ty)->getAddressSpace());
300 case Type::FunctionTyID:
301 return *Entry = FunctionType::get(ElementTypes[0],
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000302 makeArrayRef(ElementTypes).slice(1),
Chris Lattner1afcace2011-07-09 17:41:24 +0000303 cast<FunctionType>(Ty)->isVarArg());
304 case Type::StructTyID:
305 // Note that this is only reached for anonymous structs.
306 return *Entry = StructType::get(Ty->getContext(), ElementTypes,
307 cast<StructType>(Ty)->isPacked());
308 }
309 }
310
311 // Otherwise, this is an unmapped named struct. If the struct can be directly
312 // mapped over, just use it as-is. This happens in a case when the linked-in
313 // module has something like:
314 // %T = type {%T*, i32}
315 // @GV = global %T* null
316 // where T does not exist at all in the destination module.
317 //
318 // The other case we watch for is when the type is not in the destination
319 // module, but that it has to be rebuilt because it refers to something that
320 // is already mapped. For example, if the destination module has:
321 // %A = type { i32 }
322 // and the source module has something like
323 // %A' = type { i32 }
324 // %B = type { %A'* }
325 // @GV = global %B* null
326 // then we want to create a new type: "%B = type { %A*}" and have it take the
327 // pristine "%B" name from the source module.
328 //
329 // To determine which case this is, we have to recursively walk the type graph
330 // speculating that we'll be able to reuse it unmodified. Only if this is
331 // safe would we map the entire thing over. Because this is an optimization,
332 // and is not required for the prettiness of the linked module, we just skip
333 // it and always rebuild a type here.
334 StructType *STy = cast<StructType>(Ty);
335
336 // If the type is opaque, we can just use it directly.
337 if (STy->isOpaque())
338 return *Entry = STy;
Bill Wendlingcb8a7ed2012-02-28 03:47:09 +0000339
Chris Lattner1afcace2011-07-09 17:41:24 +0000340 // Otherwise we create a new type and resolve its body later. This will be
341 // resolved by the top level of get().
Chris Lattner68910502011-12-20 00:03:52 +0000342 SrcDefinitionsToResolve.push_back(STy);
343 StructType *DTy = StructType::create(STy->getContext());
344 DstResolvedOpaqueTypes.insert(DTy);
345 return *Entry = DTy;
Chris Lattner1afcace2011-07-09 17:41:24 +0000346}
347
Chris Lattner1afcace2011-07-09 17:41:24 +0000348//===----------------------------------------------------------------------===//
349// ModuleLinker implementation.
350//===----------------------------------------------------------------------===//
351
352namespace {
353 /// ModuleLinker - This is an implementation class for the LinkModules
354 /// function, which is the entrypoint for this file.
355 class ModuleLinker {
356 Module *DstM, *SrcM;
357
358 TypeMapTy TypeMap;
359
360 /// ValueMap - Mapping of values from what they used to be in Src, to what
361 /// they are now in DstM. ValueToValueMapTy is a ValueMap, which involves
362 /// some overhead due to the use of Value handles which the Linker doesn't
363 /// actually need, but this allows us to reuse the ValueMapper code.
364 ValueToValueMapTy ValueMap;
365
366 struct AppendingVarInfo {
367 GlobalVariable *NewGV; // New aggregate global in dest module.
368 Constant *DstInit; // Old initializer from dest module.
369 Constant *SrcInit; // Old initializer from src module.
370 };
371
372 std::vector<AppendingVarInfo> AppendingVars;
373
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000374 unsigned Mode; // Mode to treat source module.
375
376 // Set of items not to link in from source.
377 SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
378
Tanya Lattner9af37a32011-11-02 00:24:56 +0000379 // Vector of functions to lazily link in.
380 std::vector<Function*> LazilyLinkFunctions;
381
Chris Lattner1afcace2011-07-09 17:41:24 +0000382 public:
383 std::string ErrorMsg;
384
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000385 ModuleLinker(Module *dstM, Module *srcM, unsigned mode)
386 : DstM(dstM), SrcM(srcM), Mode(mode) { }
Chris Lattner1afcace2011-07-09 17:41:24 +0000387
388 bool run();
389
390 private:
391 /// emitError - Helper method for setting a message and returning an error
392 /// code.
393 bool emitError(const Twine &Message) {
394 ErrorMsg = Message.str();
Chris Lattnerf6f4f7a2008-06-16 18:27:53 +0000395 return true;
Chris Lattnera4477f92008-06-16 21:17:12 +0000396 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000397
398 /// getLinkageResult - This analyzes the two global values and determines
399 /// what the result will look like in the destination module.
400 bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Rafael Espindola3ed88152012-01-05 23:02:01 +0000401 GlobalValue::LinkageTypes &LT,
402 GlobalValue::VisibilityTypes &Vis,
403 bool &LinkFromSrc);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000404
Chris Lattner1afcace2011-07-09 17:41:24 +0000405 /// getLinkedToGlobal - Given a global in the source module, return the
406 /// global in the destination module that is being linked to, if any.
407 GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
408 // If the source has no name it can't link. If it has local linkage,
409 // there is no name match-up going on.
410 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
411 return 0;
Bill Wendlingcb8a7ed2012-02-28 03:47:09 +0000412
Chris Lattner1afcace2011-07-09 17:41:24 +0000413 // Otherwise see if we have a match in the destination module's symtab.
414 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
415 if (DGV == 0) return 0;
Bill Wendlingcb8a7ed2012-02-28 03:47:09 +0000416
Chris Lattner1afcace2011-07-09 17:41:24 +0000417 // If we found a global with the same name in the dest module, but it has
418 // internal linkage, we are really not doing any linkage here.
419 if (DGV->hasLocalLinkage())
420 return 0;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000421
Chris Lattner1afcace2011-07-09 17:41:24 +0000422 // Otherwise, we do in fact link to the destination global.
423 return DGV;
424 }
425
426 void computeTypeMapping();
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000427 bool categorizeModuleFlagNodes(const NamedMDNode *ModFlags,
428 DenseMap<MDString*, MDNode*> &ErrorNode,
429 DenseMap<MDString*, MDNode*> &WarningNode,
430 DenseMap<MDString*, MDNode*> &OverrideNode,
431 DenseMap<MDString*,
432 SmallSetVector<MDNode*, 8> > &RequireNodes,
433 SmallSetVector<MDString*, 16> &SeenIDs);
Chris Lattner1afcace2011-07-09 17:41:24 +0000434
435 bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
436 bool linkGlobalProto(GlobalVariable *SrcGV);
437 bool linkFunctionProto(Function *SrcF);
438 bool linkAliasProto(GlobalAlias *SrcA);
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000439 bool linkModuleFlagsMetadata();
Chris Lattner1afcace2011-07-09 17:41:24 +0000440
441 void linkAppendingVarInit(const AppendingVarInfo &AVI);
442 void linkGlobalInits();
443 void linkFunctionBody(Function *Dst, Function *Src);
444 void linkAliasBodies();
445 void linkNamedMDNodes();
446 };
Bill Wendlingcb8a7ed2012-02-28 03:47:09 +0000447} // end anonymous namespace
Chris Lattner2c236f32001-11-03 05:18:24 +0000448
Chris Lattner1afcace2011-07-09 17:41:24 +0000449/// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
Reid Spencer8bef0372007-02-04 04:29:21 +0000450/// in the symbol table. This is good for all clients except for us. Go
451/// through the trouble to force this back.
Chris Lattner1afcace2011-07-09 17:41:24 +0000452static void forceRenaming(GlobalValue *GV, StringRef Name) {
453 // If the global doesn't force its name or if it already has the right name,
454 // there is nothing for us to do.
455 if (GV->hasLocalLinkage() || GV->getName() == Name)
456 return;
457
458 Module *M = GV->getParent();
Chris Lattnerc0036282004-08-04 07:05:54 +0000459
460 // If there is a conflict, rename the conflict.
Chris Lattner1afcace2011-07-09 17:41:24 +0000461 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
Chris Lattner33f29492007-02-11 00:39:38 +0000462 GV->takeName(ConflictGV);
463 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Chris Lattner1afcace2011-07-09 17:41:24 +0000464 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
Chris Lattner33f29492007-02-11 00:39:38 +0000465 } else {
466 GV->setName(Name); // Force the name back
Reid Spenceref9b9a72007-02-05 20:47:22 +0000467 }
Reid Spenceref9b9a72007-02-05 20:47:22 +0000468}
Reid Spencer8bef0372007-02-04 04:29:21 +0000469
Reid Spenceref9b9a72007-02-05 20:47:22 +0000470/// CopyGVAttributes - copy additional attributes (those not needed to construct
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000471/// a GlobalValue) from the SrcGV to the DestGV.
Reid Spenceref9b9a72007-02-05 20:47:22 +0000472static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
Duncan Sands28c3cff2008-05-26 19:58:59 +0000473 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
474 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
475 DestGV->copyAttributesFrom(SrcGV);
476 DestGV->setAlignment(Alignment);
Chris Lattner1afcace2011-07-09 17:41:24 +0000477
478 forceRenaming(DestGV, SrcGV->getName());
Chris Lattnerc0036282004-08-04 07:05:54 +0000479}
480
Rafael Espindola3ed88152012-01-05 23:02:01 +0000481static bool isLessConstraining(GlobalValue::VisibilityTypes a,
482 GlobalValue::VisibilityTypes b) {
483 if (a == GlobalValue::HiddenVisibility)
484 return false;
485 if (b == GlobalValue::HiddenVisibility)
486 return true;
487 if (a == GlobalValue::ProtectedVisibility)
488 return false;
489 if (b == GlobalValue::ProtectedVisibility)
490 return true;
491 return false;
492}
493
Chris Lattner1afcace2011-07-09 17:41:24 +0000494/// getLinkageResult - This analyzes the two global values and determines what
Chris Lattneraee38ea2004-12-03 22:18:41 +0000495/// the result will look like in the destination module. In particular, it
Rafael Espindola3ed88152012-01-05 23:02:01 +0000496/// computes the resultant linkage type and visibility, computes whether the
497/// global in the source should be copied over to the destination (replacing
498/// the existing one), and computes whether this linkage is an error or not.
Chris Lattner1afcace2011-07-09 17:41:24 +0000499bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Rafael Espindola3ed88152012-01-05 23:02:01 +0000500 GlobalValue::LinkageTypes &LT,
501 GlobalValue::VisibilityTypes &Vis,
Chris Lattner1afcace2011-07-09 17:41:24 +0000502 bool &LinkFromSrc) {
503 assert(Dest && "Must have two globals being queried");
504 assert(!Src->hasLocalLinkage() &&
Chris Lattneraee38ea2004-12-03 22:18:41 +0000505 "If Src has internal linkage, Dest shouldn't be set!");
Chris Lattner1afcace2011-07-09 17:41:24 +0000506
Peter Collingbourne88953162011-10-30 17:46:34 +0000507 bool SrcIsDeclaration = Src->isDeclaration() && !Src->isMaterializable();
Chris Lattnerf84c59d2011-07-14 20:23:05 +0000508 bool DestIsDeclaration = Dest->isDeclaration();
Chris Lattner1afcace2011-07-09 17:41:24 +0000509
510 if (SrcIsDeclaration) {
Anton Korobeynikov2b48ef02008-03-10 22:33:22 +0000511 // If Src is external or if both Src & Dest are external.. Just link the
Chris Lattneraee38ea2004-12-03 22:18:41 +0000512 // external globals, we aren't adding anything.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000513 if (Src->hasDLLImportLinkage()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000514 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
Chris Lattner1afcace2011-07-09 17:41:24 +0000515 if (DestIsDeclaration) {
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000516 LinkFromSrc = true;
517 LT = Src->getLinkage();
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000518 }
Andrew Lenharth8753c442006-12-15 17:35:32 +0000519 } else if (Dest->hasExternalWeakLinkage()) {
Duncan Sands667d4b82009-03-07 15:45:40 +0000520 // If the Dest is weak, use the source linkage.
Andrew Lenharth8753c442006-12-15 17:35:32 +0000521 LinkFromSrc = true;
522 LT = Src->getLinkage();
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000523 } else {
524 LinkFromSrc = false;
525 LT = Dest->getLinkage();
526 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000527 } else if (DestIsDeclaration && !Dest->hasDLLImportLinkage()) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000528 // If Dest is external but Src is not:
529 LinkFromSrc = true;
530 LT = Src->getLinkage();
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000531 } else if (Src->isWeakForLinker()) {
Dale Johannesenaafce772008-05-14 20:12:51 +0000532 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
533 // or DLL* linkage.
Chris Lattner266c7bb2009-04-13 05:44:34 +0000534 if (Dest->hasExternalWeakLinkage() ||
535 Dest->hasAvailableExternallyLinkage() ||
536 (Dest->hasLinkOnceLinkage() &&
537 (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000538 LinkFromSrc = true;
539 LT = Src->getLinkage();
540 } else {
541 LinkFromSrc = false;
542 LT = Dest->getLinkage();
543 }
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000544 } else if (Dest->isWeakForLinker()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000545 // At this point we know that Src has External* or DLL* linkage.
546 if (Src->hasExternalWeakLinkage()) {
547 LinkFromSrc = false;
548 LT = Dest->getLinkage();
549 } else {
550 LinkFromSrc = true;
551 LT = GlobalValue::ExternalLinkage;
552 }
Chris Lattneraee38ea2004-12-03 22:18:41 +0000553 } else {
Chris Lattner1afcace2011-07-09 17:41:24 +0000554 assert((Dest->hasExternalLinkage() || Dest->hasDLLImportLinkage() ||
555 Dest->hasDLLExportLinkage() || Dest->hasExternalWeakLinkage()) &&
556 (Src->hasExternalLinkage() || Src->hasDLLImportLinkage() ||
557 Src->hasDLLExportLinkage() || Src->hasExternalWeakLinkage()) &&
Chris Lattneraee38ea2004-12-03 22:18:41 +0000558 "Unexpected linkage type!");
Chris Lattner1afcace2011-07-09 17:41:24 +0000559 return emitError("Linking globals named '" + Src->getName() +
Chris Lattneraee38ea2004-12-03 22:18:41 +0000560 "': symbol multiply defined!");
561 }
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +0000562
Rafael Espindola3ed88152012-01-05 23:02:01 +0000563 // Compute the visibility. We follow the rules in the System V Application
564 // Binary Interface.
565 Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
566 Dest->getVisibility() : Src->getVisibility();
Chris Lattneraee38ea2004-12-03 22:18:41 +0000567 return false;
568}
Chris Lattner5c377c52001-10-14 23:29:15 +0000569
Chris Lattner1afcace2011-07-09 17:41:24 +0000570/// computeTypeMapping - Loop over all of the linked values to compute type
571/// mappings. For example, if we link "extern Foo *x" and "Foo *x = NULL", then
572/// we have two struct types 'Foo' but one got renamed when the module was
573/// loaded into the same LLVMContext.
574void ModuleLinker::computeTypeMapping() {
Bill Wendlingcb8a7ed2012-02-28 03:47:09 +0000575 return;
Chris Lattner1afcace2011-07-09 17:41:24 +0000576 // Incorporate globals.
577 for (Module::global_iterator I = SrcM->global_begin(),
578 E = SrcM->global_end(); I != E; ++I) {
579 GlobalValue *DGV = getLinkedToGlobal(I);
580 if (DGV == 0) continue;
581
582 if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
583 TypeMap.addTypeMapping(DGV->getType(), I->getType());
584 continue;
585 }
586
587 // Unify the element type of appending arrays.
588 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
589 ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
590 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
Devang Patelab67e702009-08-11 18:01:24 +0000591 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000592
593 // Incorporate functions.
594 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
595 if (GlobalValue *DGV = getLinkedToGlobal(I))
596 TypeMap.addTypeMapping(DGV->getType(), I->getType());
597 }
Bill Wendlingc68d1272012-02-27 22:34:19 +0000598
Bill Wendlingcb8a7ed2012-02-28 03:47:09 +0000599 // Incorporate types by name, scanning all the types in the source module. At
600 // this point, the destination module may have a type "%foo = { i32 }" for
Bill Wendling348e5e72012-02-27 23:48:30 +0000601 // example. When the source module got loaded into the same LLVMContext, if
602 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
Bill Wendlingcb8a7ed2012-02-28 03:47:09 +0000603 // Attempt to link these up to clean up the IR.
Bill Wendling348e5e72012-02-27 23:48:30 +0000604 std::vector<StructType*> SrcStructTypes;
605 SrcM->findUsedStructTypes(SrcStructTypes);
606
607 SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
608 SrcStructTypes.end());
609
610 for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
611 StructType *ST = SrcStructTypes[i];
612 if (!ST->hasName()) continue;
613
614 // Check to see if there is a dot in the name followed by a digit.
Bill Wendlingcb8a7ed2012-02-28 03:47:09 +0000615 if (endsInDotNumber(ST)) continue;
616
617 if (endsInDotNumber(ST))
618 DstM->dump();
Bill Wendling348e5e72012-02-27 23:48:30 +0000619
620 // Check to see if the destination module has a struct with the prefix name.
Bill Wendlingcb8a7ed2012-02-28 03:47:09 +0000621 size_t DotPos = ST->getName().rfind('.');
622 if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0,DotPos))) {
Bill Wendling348e5e72012-02-27 23:48:30 +0000623 // Don't use it if this actually came from the source module. They're in
624 // the same LLVMContext after all.
625 if (!SrcStructTypesSet.count(DST))
626 TypeMap.addTypeMapping(DST, ST);
Bill Wendlingcb8a7ed2012-02-28 03:47:09 +0000627 }
Bill Wendling348e5e72012-02-27 23:48:30 +0000628 }
629
Chris Lattner1afcace2011-07-09 17:41:24 +0000630 // Don't bother incorporating aliases, they aren't generally typed well.
Bill Wendlingcb8a7ed2012-02-28 03:47:09 +0000631
Chris Lattner1afcace2011-07-09 17:41:24 +0000632 // Now that we have discovered all of the type equivalences, get a body for
633 // any 'opaque' types in the dest module that are now resolved.
634 TypeMap.linkDefinedTypeBodies();
Devang Patelab67e702009-08-11 18:01:24 +0000635}
636
Chris Lattner1afcace2011-07-09 17:41:24 +0000637/// linkAppendingVarProto - If there were any appending global variables, link
638/// them together now. Return true on error.
639bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
640 GlobalVariable *SrcGV) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000641 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
642 return emitError("Linking globals named '" + SrcGV->getName() +
643 "': can only link appending global with another appending global!");
644
645 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
646 ArrayType *SrcTy =
647 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
648 Type *EltTy = DstTy->getElementType();
649
650 // Check to see that they two arrays agree on type.
651 if (EltTy != SrcTy->getElementType())
652 return emitError("Appending variables with different element types!");
653 if (DstGV->isConstant() != SrcGV->isConstant())
654 return emitError("Appending variables linked with different const'ness!");
655
656 if (DstGV->getAlignment() != SrcGV->getAlignment())
657 return emitError(
658 "Appending variables with different alignment need to be linked!");
659
660 if (DstGV->getVisibility() != SrcGV->getVisibility())
661 return emitError(
662 "Appending variables with different visibility need to be linked!");
663
664 if (DstGV->getSection() != SrcGV->getSection())
665 return emitError(
666 "Appending variables with different section name need to be linked!");
667
668 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
669 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
670
671 // Create the new global variable.
672 GlobalVariable *NG =
673 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
674 DstGV->getLinkage(), /*init*/0, /*name*/"", DstGV,
675 DstGV->isThreadLocal(),
676 DstGV->getType()->getAddressSpace());
677
678 // Propagate alignment, visibility and section info.
679 CopyGVAttributes(NG, DstGV);
680
681 AppendingVarInfo AVI;
682 AVI.NewGV = NG;
683 AVI.DstInit = DstGV->getInitializer();
684 AVI.SrcInit = SrcGV->getInitializer();
685 AppendingVars.push_back(AVI);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000686
Chris Lattner1afcace2011-07-09 17:41:24 +0000687 // Replace any uses of the two global variables with uses of the new
688 // global.
689 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000690
Chris Lattner1afcace2011-07-09 17:41:24 +0000691 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
692 DstGV->eraseFromParent();
693
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000694 // Track the source variable so we don't try to link it.
695 DoNotLinkFromSource.insert(SrcGV);
696
Chris Lattner1afcace2011-07-09 17:41:24 +0000697 return false;
698}
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000699
Chris Lattner1afcace2011-07-09 17:41:24 +0000700/// linkGlobalProto - Loop through the global variables in the src module and
701/// merge them into the dest module.
702bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
703 GlobalValue *DGV = getLinkedToGlobal(SGV);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000704 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000705
Chris Lattner1afcace2011-07-09 17:41:24 +0000706 if (DGV) {
707 // Concatenation of appending linkage variables is magic and handled later.
708 if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
709 return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
710
711 // Determine whether linkage of these two globals follows the source
712 // module's definition or the destination module's definition.
Chris Lattnerb324bd72006-11-09 05:18:12 +0000713 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000714 GlobalValue::VisibilityTypes NV;
Chris Lattnerb324bd72006-11-09 05:18:12 +0000715 bool LinkFromSrc = false;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000716 if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
Chris Lattneraee38ea2004-12-03 22:18:41 +0000717 return true;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000718 NewVisibility = NV;
Chris Lattner0fec08e2003-04-21 21:07:05 +0000719
Chris Lattner1afcace2011-07-09 17:41:24 +0000720 // If we're not linking from the source, then keep the definition that we
721 // have.
722 if (!LinkFromSrc) {
723 // Special case for const propagation.
724 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
725 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
726 DGVar->setConstant(true);
727
Rafael Espindola3ed88152012-01-05 23:02:01 +0000728 // Set calculated linkage and visibility.
Chris Lattner1afcace2011-07-09 17:41:24 +0000729 DGV->setLinkage(NewLinkage);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000730 DGV->setVisibility(*NewVisibility);
731
Chris Lattner6157e382008-07-14 07:23:24 +0000732 // Make sure to remember this mapping.
Chris Lattner1afcace2011-07-09 17:41:24 +0000733 ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
734
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000735 // Track the source global so that we don't attempt to copy it over when
736 // processing global initializers.
737 DoNotLinkFromSource.insert(SGV);
738
Chris Lattner1afcace2011-07-09 17:41:24 +0000739 return false;
Chris Lattner6157e382008-07-14 07:23:24 +0000740 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000741 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000742
743 // No linking to be performed or linking from the source: simply create an
744 // identical version of the symbol over in the dest module... the
745 // initializer will be filled in later by LinkGlobalInits.
746 GlobalVariable *NewDGV =
747 new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
748 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
749 SGV->getName(), /*insertbefore*/0,
750 SGV->isThreadLocal(),
751 SGV->getType()->getAddressSpace());
752 // Propagate alignment, visibility and section info.
753 CopyGVAttributes(NewDGV, SGV);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000754 if (NewVisibility)
755 NewDGV->setVisibility(*NewVisibility);
Chris Lattner1afcace2011-07-09 17:41:24 +0000756
757 if (DGV) {
758 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
759 DGV->eraseFromParent();
760 }
761
762 // Make sure to remember this mapping.
763 ValueMap[SGV] = NewDGV;
Chris Lattner5c377c52001-10-14 23:29:15 +0000764 return false;
765}
766
Chris Lattner1afcace2011-07-09 17:41:24 +0000767/// linkFunctionProto - Link the function in the source module into the
768/// destination module if needed, setting up mapping information.
769bool ModuleLinker::linkFunctionProto(Function *SF) {
770 GlobalValue *DGV = getLinkedToGlobal(SF);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000771 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Chris Lattner1afcace2011-07-09 17:41:24 +0000772
773 if (DGV) {
774 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
775 bool LinkFromSrc = false;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000776 GlobalValue::VisibilityTypes NV;
777 if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
Chris Lattner1afcace2011-07-09 17:41:24 +0000778 return true;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000779 NewVisibility = NV;
780
Chris Lattner1afcace2011-07-09 17:41:24 +0000781 if (!LinkFromSrc) {
782 // Set calculated linkage
783 DGV->setLinkage(NewLinkage);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000784 DGV->setVisibility(*NewVisibility);
785
Chris Lattner1afcace2011-07-09 17:41:24 +0000786 // Make sure to remember this mapping.
787 ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
788
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000789 // Track the function from the source module so we don't attempt to remap
790 // it.
791 DoNotLinkFromSource.insert(SF);
792
Chris Lattner1afcace2011-07-09 17:41:24 +0000793 return false;
794 }
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000795 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000796
797 // If there is no linkage to be performed or we are linking from the source,
798 // bring SF over.
799 Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
800 SF->getLinkage(), SF->getName(), DstM);
801 CopyGVAttributes(NewDF, SF);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000802 if (NewVisibility)
803 NewDF->setVisibility(*NewVisibility);
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000804
Chris Lattner1afcace2011-07-09 17:41:24 +0000805 if (DGV) {
806 // Any uses of DF need to change to NewDF, with cast.
807 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
808 DGV->eraseFromParent();
Tanya Lattner9af37a32011-11-02 00:24:56 +0000809 } else {
810 // Internal, LO_ODR, or LO linkage - stick in set to ignore and lazily link.
811 if (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
812 SF->hasAvailableExternallyLinkage()) {
813 DoNotLinkFromSource.insert(SF);
814 LazilyLinkFunctions.push_back(SF);
815 }
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000816 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000817
818 ValueMap[SF] = NewDF;
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000819 return false;
820}
821
Chris Lattner1afcace2011-07-09 17:41:24 +0000822/// LinkAliasProto - Set up prototypes for any aliases that come over from the
823/// source module.
824bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
825 GlobalValue *DGV = getLinkedToGlobal(SGA);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000826 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
827
Chris Lattner1afcace2011-07-09 17:41:24 +0000828 if (DGV) {
829 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000830 GlobalValue::VisibilityTypes NV;
Chris Lattner1afcace2011-07-09 17:41:24 +0000831 bool LinkFromSrc = false;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000832 if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
Chris Lattner1afcace2011-07-09 17:41:24 +0000833 return true;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000834 NewVisibility = NV;
835
Chris Lattner1afcace2011-07-09 17:41:24 +0000836 if (!LinkFromSrc) {
837 // Set calculated linkage.
838 DGV->setLinkage(NewLinkage);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000839 DGV->setVisibility(*NewVisibility);
840
Chris Lattner1afcace2011-07-09 17:41:24 +0000841 // Make sure to remember this mapping.
842 ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
843
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000844 // Track the alias from the source module so we don't attempt to remap it.
845 DoNotLinkFromSource.insert(SGA);
846
Chris Lattner1afcace2011-07-09 17:41:24 +0000847 return false;
848 }
849 }
850
851 // If there is no linkage to be performed or we're linking from the source,
852 // bring over SGA.
853 GlobalAlias *NewDA = new GlobalAlias(TypeMap.get(SGA->getType()),
854 SGA->getLinkage(), SGA->getName(),
855 /*aliasee*/0, DstM);
856 CopyGVAttributes(NewDA, SGA);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000857 if (NewVisibility)
858 NewDA->setVisibility(*NewVisibility);
Chris Lattner5c377c52001-10-14 23:29:15 +0000859
Chris Lattner1afcace2011-07-09 17:41:24 +0000860 if (DGV) {
861 // Any uses of DGV need to change to NewDA, with cast.
862 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
863 DGV->eraseFromParent();
864 }
865
866 ValueMap[SGA] = NewDA;
867 return false;
868}
869
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000870static void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000871 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
872
873 for (unsigned i = 0; i != NumElements; ++i)
874 Dest.push_back(C->getAggregateElement(i));
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000875}
876
Chris Lattner1afcace2011-07-09 17:41:24 +0000877void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
878 // Merge the initializer.
879 SmallVector<Constant*, 16> Elements;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000880 getArrayElements(AVI.DstInit, Elements);
Chris Lattner1afcace2011-07-09 17:41:24 +0000881
882 Constant *SrcInit = MapValue(AVI.SrcInit, ValueMap, RF_None, &TypeMap);
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000883 getArrayElements(SrcInit, Elements);
884
Chris Lattner1afcace2011-07-09 17:41:24 +0000885 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
886 AVI.NewGV->setInitializer(ConstantArray::get(NewType, Elements));
887}
888
889
890// linkGlobalInits - Update the initializers in the Dest module now that all
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000891// globals that may be referenced are in Dest.
Chris Lattner1afcace2011-07-09 17:41:24 +0000892void ModuleLinker::linkGlobalInits() {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000893 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattner1afcace2011-07-09 17:41:24 +0000894 for (Module::const_global_iterator I = SrcM->global_begin(),
895 E = SrcM->global_end(); I != E; ++I) {
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000896
897 // Only process initialized GV's or ones not already in dest.
898 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
Chris Lattner1afcace2011-07-09 17:41:24 +0000899
900 // Grab destination global variable.
901 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
902 // Figure out what the initializer looks like in the dest module.
903 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
904 RF_None, &TypeMap));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000905 }
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000906}
Chris Lattner5c377c52001-10-14 23:29:15 +0000907
Chris Lattner1afcace2011-07-09 17:41:24 +0000908// linkFunctionBody - Copy the source function over into the dest function and
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000909// fix up references to values. At this point we know that Dest is an external
910// function, and that Src is not.
Chris Lattner1afcace2011-07-09 17:41:24 +0000911void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
912 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
Chris Lattner5c377c52001-10-14 23:29:15 +0000913
Chris Lattner0033baf2004-11-16 17:12:38 +0000914 // Go through and convert function arguments over, remembering the mapping.
Chris Lattner1afcace2011-07-09 17:41:24 +0000915 Function::arg_iterator DI = Dst->arg_begin();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000916 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
Chris Lattner69da5cf2002-10-13 20:57:00 +0000917 I != E; ++I, ++DI) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000918 DI->setName(I->getName()); // Copy the name over.
Chris Lattner5c377c52001-10-14 23:29:15 +0000919
Chris Lattner1afcace2011-07-09 17:41:24 +0000920 // Add a mapping to our mapping.
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000921 ValueMap[I] = DI;
Chris Lattner5c377c52001-10-14 23:29:15 +0000922 }
923
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000924 if (Mode == Linker::DestroySource) {
925 // Splice the body of the source function into the dest function.
926 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
927
928 // At this point, all of the instructions and values of the function are now
929 // copied over. The only problem is that they are still referencing values in
930 // the Source function as operands. Loop through all of the operands of the
931 // functions and patch them up to point to the local versions.
932 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
933 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
934 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap);
935
936 } else {
937 // Clone the body of the function into the dest function.
938 SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
Mon P Wangd24397a2011-12-23 02:18:32 +0000939 CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", NULL, &TypeMap);
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000940 }
941
Chris Lattner0033baf2004-11-16 17:12:38 +0000942 // There is no need to map the arguments anymore.
Chris Lattner11273152006-06-16 01:24:04 +0000943 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
944 I != E; ++I)
Reid Spenceref9b9a72007-02-05 20:47:22 +0000945 ValueMap.erase(I);
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000946
Chris Lattner5c377c52001-10-14 23:29:15 +0000947}
948
949
Chris Lattner1afcace2011-07-09 17:41:24 +0000950void ModuleLinker::linkAliasBodies() {
951 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000952 I != E; ++I) {
953 if (DoNotLinkFromSource.count(I))
954 continue;
Chris Lattner1afcace2011-07-09 17:41:24 +0000955 if (Constant *Aliasee = I->getAliasee()) {
956 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
957 DA->setAliasee(MapValue(Aliasee, ValueMap, RF_None, &TypeMap));
David Chisnall34722462010-01-09 16:27:31 +0000958 }
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000959 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000960}
Anton Korobeynikov9f2ee702008-03-05 23:21:39 +0000961
Chris Lattner1afcace2011-07-09 17:41:24 +0000962/// linkNamedMDNodes - Insert all of the named mdnodes in Src into the Dest
963/// module.
964void ModuleLinker::linkNamedMDNodes() {
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000965 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
Chris Lattner1afcace2011-07-09 17:41:24 +0000966 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
967 E = SrcM->named_metadata_end(); I != E; ++I) {
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000968 // Don't link module flags here. Do them separately.
969 if (&*I == SrcModFlags) continue;
Chris Lattner1afcace2011-07-09 17:41:24 +0000970 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
971 // Add Src elements into Dest node.
972 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
973 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
974 RF_None, &TypeMap));
975 }
976}
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000977
978/// categorizeModuleFlagNodes -
979bool ModuleLinker::
980categorizeModuleFlagNodes(const NamedMDNode *ModFlags,
981 DenseMap<MDString*, MDNode*> &ErrorNode,
982 DenseMap<MDString*, MDNode*> &WarningNode,
983 DenseMap<MDString*, MDNode*> &OverrideNode,
984 DenseMap<MDString*,
985 SmallSetVector<MDNode*, 8> > &RequireNodes,
986 SmallSetVector<MDString*, 16> &SeenIDs) {
987 bool HasErr = false;
988
989 for (unsigned I = 0, E = ModFlags->getNumOperands(); I != E; ++I) {
990 MDNode *Op = ModFlags->getOperand(I);
991 assert(Op->getNumOperands() == 3 && "Invalid module flag metadata!");
992 assert(isa<ConstantInt>(Op->getOperand(0)) &&
993 "Module flag's first operand must be an integer!");
994 assert(isa<MDString>(Op->getOperand(1)) &&
995 "Module flag's second operand must be an MDString!");
996
997 ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
998 MDString *ID = cast<MDString>(Op->getOperand(1));
999 Value *Val = Op->getOperand(2);
1000 switch (Behavior->getZExtValue()) {
1001 default:
1002 assert(false && "Invalid behavior in module flag metadata!");
1003 break;
1004 case Module::Error: {
1005 MDNode *&ErrNode = ErrorNode[ID];
1006 if (!ErrNode) ErrNode = Op;
1007 if (ErrNode->getOperand(2) != Val)
Bill Wendling75b3d682012-02-14 09:13:54 +00001008 HasErr = emitError("linking module flags '" + ID->getString() +
1009 "': IDs have conflicting values");
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001010 break;
1011 }
1012 case Module::Warning: {
1013 MDNode *&WarnNode = WarningNode[ID];
1014 if (!WarnNode) WarnNode = Op;
1015 if (WarnNode->getOperand(2) != Val)
Bill Wendling75b3d682012-02-14 09:13:54 +00001016 errs() << "WARNING: linking module flags '" << ID->getString()
1017 << "': IDs have conflicting values";
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001018 break;
1019 }
1020 case Module::Require: RequireNodes[ID].insert(Op); break;
1021 case Module::Override: {
1022 MDNode *&OvrNode = OverrideNode[ID];
1023 if (!OvrNode) OvrNode = Op;
1024 if (OvrNode->getOperand(2) != Val)
Bill Wendling75b3d682012-02-14 09:13:54 +00001025 HasErr = emitError("linking module flags '" + ID->getString() +
1026 "': IDs have conflicting override values");
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001027 break;
1028 }
1029 }
1030
1031 SeenIDs.insert(ID);
1032 }
1033
1034 return HasErr;
1035}
1036
1037/// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest
1038/// module.
1039bool ModuleLinker::linkModuleFlagsMetadata() {
1040 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1041 if (!SrcModFlags) return false;
1042
1043 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
1044
1045 // If the destination module doesn't have module flags yet, then just copy
1046 // over the source module's flags.
1047 if (DstModFlags->getNumOperands() == 0) {
1048 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1049 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1050
1051 return false;
1052 }
1053
1054 bool HasErr = false;
1055
1056 // Otherwise, we have to merge them based on their behaviors. First,
1057 // categorize all of the nodes in the modules' module flags. If an error or
1058 // warning occurs, then emit the appropriate message(s).
1059 DenseMap<MDString*, MDNode*> ErrorNode;
1060 DenseMap<MDString*, MDNode*> WarningNode;
1061 DenseMap<MDString*, MDNode*> OverrideNode;
1062 DenseMap<MDString*, SmallSetVector<MDNode*, 8> > RequireNodes;
1063 SmallSetVector<MDString*, 16> SeenIDs;
1064
1065 HasErr |= categorizeModuleFlagNodes(SrcModFlags, ErrorNode, WarningNode,
1066 OverrideNode, RequireNodes, SeenIDs);
1067 HasErr |= categorizeModuleFlagNodes(DstModFlags, ErrorNode, WarningNode,
1068 OverrideNode, RequireNodes, SeenIDs);
1069
1070 // Check that there isn't both an error and warning node for a flag.
1071 for (SmallSetVector<MDString*, 16>::iterator
1072 I = SeenIDs.begin(), E = SeenIDs.end(); I != E; ++I) {
1073 MDString *ID = *I;
1074 if (ErrorNode[ID] && WarningNode[ID])
Bill Wendling75b3d682012-02-14 09:13:54 +00001075 HasErr = emitError("linking module flags '" + ID->getString() +
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001076 "': IDs have conflicting behaviors");
1077 }
1078
1079 // Early exit if we had an error.
1080 if (HasErr) return true;
1081
1082 // Get the destination's module flags ready for new operands.
1083 DstModFlags->dropAllReferences();
1084
1085 // Add all of the module flags to the destination module.
1086 DenseMap<MDString*, SmallVector<MDNode*, 4> > AddedNodes;
1087 for (SmallSetVector<MDString*, 16>::iterator
1088 I = SeenIDs.begin(), E = SeenIDs.end(); I != E; ++I) {
1089 MDString *ID = *I;
1090 if (OverrideNode[ID]) {
1091 DstModFlags->addOperand(OverrideNode[ID]);
1092 AddedNodes[ID].push_back(OverrideNode[ID]);
1093 } else if (ErrorNode[ID]) {
1094 DstModFlags->addOperand(ErrorNode[ID]);
1095 AddedNodes[ID].push_back(ErrorNode[ID]);
1096 } else if (WarningNode[ID]) {
1097 DstModFlags->addOperand(WarningNode[ID]);
1098 AddedNodes[ID].push_back(WarningNode[ID]);
1099 }
1100
1101 for (SmallSetVector<MDNode*, 8>::iterator
1102 II = RequireNodes[ID].begin(), IE = RequireNodes[ID].end();
1103 II != IE; ++II)
1104 DstModFlags->addOperand(*II);
1105 }
1106
1107 // Now check that all of the requirements have been satisfied.
1108 for (SmallSetVector<MDString*, 16>::iterator
1109 I = SeenIDs.begin(), E = SeenIDs.end(); I != E; ++I) {
1110 MDString *ID = *I;
1111 SmallSetVector<MDNode*, 8> &Set = RequireNodes[ID];
1112
1113 for (SmallSetVector<MDNode*, 8>::iterator
1114 II = Set.begin(), IE = Set.end(); II != IE; ++II) {
1115 MDNode *Node = *II;
1116 assert(isa<MDNode>(Node->getOperand(2)) &&
1117 "Module flag's third operand must be an MDNode!");
1118 MDNode *Val = cast<MDNode>(Node->getOperand(2));
1119
1120 MDString *ReqID = cast<MDString>(Val->getOperand(0));
1121 Value *ReqVal = Val->getOperand(1);
1122
1123 bool HasValue = false;
1124 for (SmallVectorImpl<MDNode*>::iterator
1125 RI = AddedNodes[ReqID].begin(), RE = AddedNodes[ReqID].end();
1126 RI != RE; ++RI) {
1127 MDNode *ReqNode = *RI;
1128 if (ReqNode->getOperand(2) == ReqVal) {
1129 HasValue = true;
1130 break;
1131 }
1132 }
1133
1134 if (!HasValue)
Bill Wendling75b3d682012-02-14 09:13:54 +00001135 HasErr = emitError("linking module flags '" + ReqID->getString() +
1136 "': does not have the required value");
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001137 }
1138 }
1139
1140 return HasErr;
1141}
Chris Lattner1afcace2011-07-09 17:41:24 +00001142
1143bool ModuleLinker::run() {
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001144 assert(DstM && "Null destination module");
1145 assert(SrcM && "Null source module");
Chris Lattner1afcace2011-07-09 17:41:24 +00001146
1147 // Inherit the target data from the source module if the destination module
1148 // doesn't have one already.
1149 if (DstM->getDataLayout().empty() && !SrcM->getDataLayout().empty())
1150 DstM->setDataLayout(SrcM->getDataLayout());
1151
1152 // Copy the target triple from the source to dest if the dest's is empty.
1153 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1154 DstM->setTargetTriple(SrcM->getTargetTriple());
1155
1156 if (!SrcM->getDataLayout().empty() && !DstM->getDataLayout().empty() &&
1157 SrcM->getDataLayout() != DstM->getDataLayout())
1158 errs() << "WARNING: Linking two modules of different data layouts!\n";
1159 if (!SrcM->getTargetTriple().empty() &&
1160 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1161 errs() << "WARNING: Linking two modules of different target triples: ";
1162 if (!SrcM->getModuleIdentifier().empty())
1163 errs() << SrcM->getModuleIdentifier() << ": ";
1164 errs() << "'" << SrcM->getTargetTriple() << "' and '"
1165 << DstM->getTargetTriple() << "'\n";
1166 }
1167
1168 // Append the module inline asm string.
1169 if (!SrcM->getModuleInlineAsm().empty()) {
1170 if (DstM->getModuleInlineAsm().empty())
1171 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1172 else
1173 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1174 SrcM->getModuleInlineAsm());
1175 }
1176
1177 // Update the destination module's dependent libraries list with the libraries
1178 // from the source module. There's no opportunity for duplicates here as the
1179 // Module ensures that duplicate insertions are discarded.
1180 for (Module::lib_iterator SI = SrcM->lib_begin(), SE = SrcM->lib_end();
1181 SI != SE; ++SI)
1182 DstM->addLibrary(*SI);
1183
1184 // If the source library's module id is in the dependent library list of the
1185 // destination library, remove it since that module is now linked in.
1186 StringRef ModuleId = SrcM->getModuleIdentifier();
1187 if (!ModuleId.empty())
1188 DstM->removeLibrary(sys::path::stem(ModuleId));
Chris Lattner1afcace2011-07-09 17:41:24 +00001189
1190 // Loop over all of the linked values to compute type mappings.
1191 computeTypeMapping();
1192
1193 // Insert all of the globals in src into the DstM module... without linking
1194 // initializers (which could refer to functions not yet mapped over).
1195 for (Module::global_iterator I = SrcM->global_begin(),
1196 E = SrcM->global_end(); I != E; ++I)
1197 if (linkGlobalProto(I))
1198 return true;
1199
1200 // Link the functions together between the two modules, without doing function
1201 // bodies... this just adds external function prototypes to the DstM
1202 // function... We do this so that when we begin processing function bodies,
1203 // all of the global values that may be referenced are available in our
1204 // ValueMap.
1205 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1206 if (linkFunctionProto(I))
1207 return true;
1208
1209 // If there were any aliases, link them now.
1210 for (Module::alias_iterator I = SrcM->alias_begin(),
1211 E = SrcM->alias_end(); I != E; ++I)
1212 if (linkAliasProto(I))
1213 return true;
1214
1215 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1216 linkAppendingVarInit(AppendingVars[i]);
1217
1218 // Update the initializers in the DstM module now that all globals that may
1219 // be referenced are in DstM.
1220 linkGlobalInits();
1221
1222 // Link in the function bodies that are defined in the source module into
1223 // DstM.
1224 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
Tanya Lattner2b28a742011-10-14 22:17:46 +00001225 // Skip if not linking from source.
1226 if (DoNotLinkFromSource.count(SF)) continue;
1227
1228 // Skip if no body (function is external) or materialize.
1229 if (SF->isDeclaration()) {
1230 if (!SF->isMaterializable())
1231 continue;
1232 if (SF->Materialize(&ErrorMsg))
1233 return true;
1234 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001235
1236 linkFunctionBody(cast<Function>(ValueMap[SF]), SF);
1237 }
1238
1239 // Resolve all uses of aliases with aliasees.
1240 linkAliasBodies();
1241
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001242 // Remap all of the named MDNodes in Src into the DstM module. We do this
Devang Patel211da8f2011-08-04 19:44:28 +00001243 // after linking GlobalValues so that MDNodes that reference GlobalValues
1244 // are properly remapped.
1245 linkNamedMDNodes();
1246
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001247 // Merge the module flags into the DstM module.
1248 if (linkModuleFlagsMetadata())
1249 return true;
1250
Tanya Lattner9af37a32011-11-02 00:24:56 +00001251 // Process vector of lazily linked in functions.
1252 bool LinkedInAnyFunctions;
1253 do {
1254 LinkedInAnyFunctions = false;
1255
1256 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1257 E = LazilyLinkFunctions.end(); I != E; ++I) {
1258 if (!*I)
1259 continue;
1260
1261 Function *SF = *I;
1262 Function *DF = cast<Function>(ValueMap[SF]);
1263
1264 if (!DF->use_empty()) {
1265
1266 // Materialize if necessary.
1267 if (SF->isDeclaration()) {
1268 if (!SF->isMaterializable())
1269 continue;
1270 if (SF->Materialize(&ErrorMsg))
1271 return true;
1272 }
1273
1274 // Link in function body.
1275 linkFunctionBody(DF, SF);
1276
1277 // "Remove" from vector by setting the element to 0.
1278 *I = 0;
1279
1280 // Set flag to indicate we may have more functions to lazily link in
1281 // since we linked in a function.
1282 LinkedInAnyFunctions = true;
1283 }
1284 }
1285 } while (LinkedInAnyFunctions);
1286
1287 // Remove any prototypes of functions that were not actually linked in.
1288 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1289 E = LazilyLinkFunctions.end(); I != E; ++I) {
1290 if (!*I)
1291 continue;
1292
1293 Function *SF = *I;
1294 Function *DF = cast<Function>(ValueMap[SF]);
1295 if (DF->use_empty())
1296 DF->eraseFromParent();
1297 }
1298
Chris Lattner1afcace2011-07-09 17:41:24 +00001299 // Now that all of the types from the source are used, resolve any structs
1300 // copied over to the dest that didn't exist there.
1301 TypeMap.linkDefinedTypeBodies();
1302
Anton Korobeynikov9f2ee702008-03-05 23:21:39 +00001303 return false;
1304}
Chris Lattner52f7e902001-10-13 07:03:50 +00001305
Chris Lattner1afcace2011-07-09 17:41:24 +00001306//===----------------------------------------------------------------------===//
1307// LinkModules entrypoint.
1308//===----------------------------------------------------------------------===//
1309
Chris Lattner52f7e902001-10-13 07:03:50 +00001310// LinkModules - This function links two modules together, with the resulting
1311// left module modified to be the composite of the two input modules. If an
1312// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
Chris Lattner5c377c52001-10-14 23:29:15 +00001313// the problem. Upon failure, the Dest module could be in a modified state, and
1314// shouldn't be relied on to be consistent.
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +00001315bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode,
1316 std::string *ErrorMsg) {
1317 ModuleLinker TheLinker(Dest, Src, Mode);
Chris Lattner1afcace2011-07-09 17:41:24 +00001318 if (TheLinker.run()) {
1319 if (ErrorMsg) *ErrorMsg = TheLinker.ErrorMsg;
Reid Spencer619f0242007-02-04 04:43:17 +00001320 return true;
Chris Lattner5a837de2004-08-04 07:44:58 +00001321 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001322
Chris Lattner52f7e902001-10-13 07:03:50 +00001323 return false;
1324}