blob: bc512b46bc2b3ad566c871c783623d2e9f597efa [file] [log] [blame]
Mikhail Glushenkovc834bbf2009-03-03 10:04:23 +00001//===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
Misha Brukmanf976c852005-04-21 22:55:34 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanf976c852005-04-21 22:55:34 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner52f7e902001-10-13 07:03:50 +00009//
10// This file implements the LLVM module linker.
11//
Chris Lattner52f7e902001-10-13 07:03:50 +000012//===----------------------------------------------------------------------===//
13
Reid Spencer7cc371a2004-11-14 23:27:04 +000014#include "llvm/Linker.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000015#include "llvm-c/Linker.h"
Bill Wendlingd34cb1e2012-02-11 11:38:06 +000016#include "llvm/ADT/DenseSet.h"
Rafael Espindola3ed88152012-01-05 23:02:01 +000017#include "llvm/ADT/Optional.h"
Bill Wendlingd34cb1e2012-02-11 11:38:06 +000018#include "llvm/ADT/SetVector.h"
19#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000020#include "llvm/IR/Constants.h"
21#include "llvm/IR/DerivedTypes.h"
22#include "llvm/IR/Instructions.h"
23#include "llvm/IR/Module.h"
Bill Wendlingcd7193f2012-03-22 20:28:27 +000024#include "llvm/Support/Debug.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000025#include "llvm/Support/Path.h"
Bill Wendlingcd7193f2012-03-22 20:28:27 +000026#include "llvm/Support/raw_ostream.h"
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +000027#include "llvm/Transforms/Utils/Cloning.h"
Dan Gohman05ea54e2010-08-24 18:50:07 +000028#include "llvm/Transforms/Utils/ValueMapper.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000029#include "llvm/TypeFinder.h"
Duncan Sands0aaf2f62012-03-03 09:36:58 +000030#include <cctype>
Chris Lattnerf7703df2004-01-09 06:12:26 +000031using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000032
Chris Lattner1afcace2011-07-09 17:41:24 +000033//===----------------------------------------------------------------------===//
34// TypeMap implementation.
35//===----------------------------------------------------------------------===//
Chris Lattner5c377c52001-10-14 23:29:15 +000036
Chris Lattner62a81a12008-06-16 21:00:18 +000037namespace {
Chris Lattner1afcace2011-07-09 17:41:24 +000038class TypeMapTy : public ValueMapTypeRemapper {
39 /// MappedTypes - This is a mapping from a source type to a destination type
40 /// to use.
41 DenseMap<Type*, Type*> MappedTypes;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +000042
Chris Lattner1afcace2011-07-09 17:41:24 +000043 /// SpeculativeTypes - When checking to see if two subgraphs are isomorphic,
44 /// we speculatively add types to MappedTypes, but keep track of them here in
45 /// case we need to roll back.
46 SmallVector<Type*, 16> SpeculativeTypes;
47
Chris Lattner68910502011-12-20 00:03:52 +000048 /// SrcDefinitionsToResolve - This is a list of non-opaque structs in the
49 /// source module that are mapped to an opaque struct in the destination
50 /// module.
51 SmallVector<StructType*, 16> SrcDefinitionsToResolve;
52
53 /// DstResolvedOpaqueTypes - This is the set of opaque types in the
54 /// destination modules who are getting a body from the source module.
55 SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
Bill Wendling6d6c6d72012-03-22 20:30:41 +000056
Chris Lattnerfc196f92008-06-16 23:06:51 +000057public:
Chris Lattner1afcace2011-07-09 17:41:24 +000058 /// addTypeMapping - Indicate that the specified type in the destination
59 /// module is conceptually equivalent to the specified type in the source
60 /// module.
61 void addTypeMapping(Type *DstTy, Type *SrcTy);
62
63 /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
64 /// module from a type definition in the source module.
65 void linkDefinedTypeBodies();
66
67 /// get - Return the mapped type to use for the specified input type from the
68 /// source module.
69 Type *get(Type *SrcTy);
70
71 FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*)T));}
72
Bill Wendlingcd7193f2012-03-22 20:28:27 +000073 /// dump - Dump out the type map for debugging purposes.
74 void dump() const {
75 for (DenseMap<Type*, Type*>::const_iterator
76 I = MappedTypes.begin(), E = MappedTypes.end(); I != E; ++I) {
77 dbgs() << "TypeMap: ";
78 I->first->dump();
79 dbgs() << " => ";
80 I->second->dump();
81 dbgs() << '\n';
82 }
83 }
Bill Wendlingcd7193f2012-03-22 20:28:27 +000084
Chris Lattner1afcace2011-07-09 17:41:24 +000085private:
86 Type *getImpl(Type *T);
87 /// remapType - Implement the ValueMapTypeRemapper interface.
88 Type *remapType(Type *SrcTy) {
89 return get(SrcTy);
Chris Lattner62a81a12008-06-16 21:00:18 +000090 }
Chris Lattner1afcace2011-07-09 17:41:24 +000091
92 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
Chris Lattner62a81a12008-06-16 21:00:18 +000093};
94}
95
Chris Lattner1afcace2011-07-09 17:41:24 +000096void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
97 Type *&Entry = MappedTypes[SrcTy];
98 if (Entry) return;
99
100 if (DstTy == SrcTy) {
101 Entry = DstTy;
102 return;
103 }
Bill Wendling601c0942012-02-28 04:01:21 +0000104
Chris Lattner1afcace2011-07-09 17:41:24 +0000105 // Check to see if these types are recursively isomorphic and establish a
106 // mapping between them if so.
Bill Wendling601c0942012-02-28 04:01:21 +0000107 if (!areTypesIsomorphic(DstTy, SrcTy)) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000108 // Oops, they aren't isomorphic. Just discard this request by rolling out
109 // any speculative mappings we've established.
110 for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i)
111 MappedTypes.erase(SpeculativeTypes[i]);
Bill Wendling601c0942012-02-28 04:01:21 +0000112 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000113 SpeculativeTypes.clear();
114}
Chris Lattner62a81a12008-06-16 21:00:18 +0000115
Chris Lattner1afcace2011-07-09 17:41:24 +0000116/// areTypesIsomorphic - Recursively walk this pair of types, returning true
117/// if they are isomorphic, false if they are not.
118bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
119 // Two types with differing kinds are clearly not isomorphic.
120 if (DstTy->getTypeID() != SrcTy->getTypeID()) return false;
Misha Brukmanf976c852005-04-21 22:55:34 +0000121
Chris Lattner1afcace2011-07-09 17:41:24 +0000122 // If we have an entry in the MappedTypes table, then we have our answer.
123 Type *&Entry = MappedTypes[SrcTy];
124 if (Entry)
125 return Entry == DstTy;
Misha Brukmanf976c852005-04-21 22:55:34 +0000126
Chris Lattner1afcace2011-07-09 17:41:24 +0000127 // Two identical types are clearly isomorphic. Remember this
128 // non-speculatively.
129 if (DstTy == SrcTy) {
130 Entry = DstTy;
Chris Lattner56539652008-06-16 20:03:01 +0000131 return true;
Chris Lattner1afcace2011-07-09 17:41:24 +0000132 }
Bill Wendling601c0942012-02-28 04:01:21 +0000133
Chris Lattner1afcace2011-07-09 17:41:24 +0000134 // Okay, we have two types with identical kinds that we haven't seen before.
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000135
Chris Lattner1afcace2011-07-09 17:41:24 +0000136 // If this is an opaque struct type, special case it.
137 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
138 // Mapping an opaque type to any struct, just keep the dest struct.
139 if (SSTy->isOpaque()) {
140 Entry = DstTy;
141 SpeculativeTypes.push_back(SrcTy);
Chris Lattner43f4ba82003-08-22 19:12:55 +0000142 return true;
Chris Lattnera4477f92008-06-16 21:17:12 +0000143 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000144
Chris Lattner68910502011-12-20 00:03:52 +0000145 // Mapping a non-opaque source type to an opaque dest. If this is the first
146 // type that we're mapping onto this destination type then we succeed. Keep
147 // the dest, but fill it in later. This doesn't need to be speculative. If
148 // this is the second (different) type that we're trying to map onto the
149 // same opaque type then we fail.
Chris Lattner1afcace2011-07-09 17:41:24 +0000150 if (cast<StructType>(DstTy)->isOpaque()) {
Chris Lattner68910502011-12-20 00:03:52 +0000151 // We can only map one source type onto the opaque destination type.
152 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)))
153 return false;
154 SrcDefinitionsToResolve.push_back(SSTy);
Chris Lattner1afcace2011-07-09 17:41:24 +0000155 Entry = DstTy;
Chris Lattner1afcace2011-07-09 17:41:24 +0000156 return true;
157 }
158 }
159
160 // If the number of subtypes disagree between the two types, then we fail.
161 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
Chris Lattnere76c57a2003-08-22 06:07:12 +0000162 return false;
Chris Lattner1afcace2011-07-09 17:41:24 +0000163
164 // Fail if any of the extra properties (e.g. array size) of the type disagree.
165 if (isa<IntegerType>(DstTy))
166 return false; // bitwidth disagrees.
167 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
168 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
169 return false;
Chris Lattner1a31f3b2011-12-20 23:14:57 +0000170
Chris Lattner1afcace2011-07-09 17:41:24 +0000171 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
172 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
173 return false;
174 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
175 StructType *SSTy = cast<StructType>(SrcTy);
Chris Lattner1bcbf852011-08-12 18:07:26 +0000176 if (DSTy->isLiteral() != SSTy->isLiteral() ||
Chris Lattner1afcace2011-07-09 17:41:24 +0000177 DSTy->isPacked() != SSTy->isPacked())
178 return false;
179 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
180 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
181 return false;
182 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
183 if (DVTy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
184 return false;
Chris Lattnere76c57a2003-08-22 06:07:12 +0000185 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000186
187 // Otherwise, we speculate that these two types will line up and recursively
188 // check the subelements.
189 Entry = DstTy;
190 SpeculativeTypes.push_back(SrcTy);
191
Bill Wendling601c0942012-02-28 04:01:21 +0000192 for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i)
193 if (!areTypesIsomorphic(DstTy->getContainedType(i),
194 SrcTy->getContainedType(i)))
Chris Lattner1afcace2011-07-09 17:41:24 +0000195 return false;
196
197 // If everything seems to have lined up, then everything is great.
198 return true;
199}
200
201/// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
202/// module from a type definition in the source module.
203void TypeMapTy::linkDefinedTypeBodies() {
204 SmallVector<Type*, 16> Elements;
205 SmallString<16> TmpName;
206
207 // Note that processing entries in this loop (calling 'get') can add new
Chris Lattner68910502011-12-20 00:03:52 +0000208 // entries to the SrcDefinitionsToResolve vector.
209 while (!SrcDefinitionsToResolve.empty()) {
210 StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val();
Chris Lattner1afcace2011-07-09 17:41:24 +0000211 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
212
213 // TypeMap is a many-to-one mapping, if there were multiple types that
214 // provide a body for DstSTy then previous iterations of this loop may have
215 // already handled it. Just ignore this case.
216 if (!DstSTy->isOpaque()) continue;
217 assert(!SrcSTy->isOpaque() && "Not resolving a definition?");
218
219 // Map the body of the source type over to a new body for the dest type.
220 Elements.resize(SrcSTy->getNumElements());
221 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
222 Elements[i] = getImpl(SrcSTy->getElementType(i));
223
224 DstSTy->setBody(Elements, SrcSTy->isPacked());
225
226 // If DstSTy has no name or has a longer name than STy, then viciously steal
227 // STy's name.
228 if (!SrcSTy->hasName()) continue;
229 StringRef SrcName = SrcSTy->getName();
230
231 if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
232 TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
233 SrcSTy->setName("");
234 DstSTy->setName(TmpName.str());
235 TmpName.clear();
236 }
237 }
Chris Lattner68910502011-12-20 00:03:52 +0000238
239 DstResolvedOpaqueTypes.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000240}
241
Chris Lattner1afcace2011-07-09 17:41:24 +0000242/// get - Return the mapped type to use for the specified input type from the
243/// source module.
244Type *TypeMapTy::get(Type *Ty) {
245 Type *Result = getImpl(Ty);
246
247 // If this caused a reference to any struct type, resolve it before returning.
Chris Lattner68910502011-12-20 00:03:52 +0000248 if (!SrcDefinitionsToResolve.empty())
Chris Lattner1afcace2011-07-09 17:41:24 +0000249 linkDefinedTypeBodies();
250 return Result;
251}
252
253/// getImpl - This is the recursive version of get().
254Type *TypeMapTy::getImpl(Type *Ty) {
255 // If we already have an entry for this type, return it.
256 Type **Entry = &MappedTypes[Ty];
257 if (*Entry) return *Entry;
Bill Wendling601c0942012-02-28 04:01:21 +0000258
Chris Lattner1afcace2011-07-09 17:41:24 +0000259 // If this is not a named struct type, then just map all of the elements and
260 // then rebuild the type from inside out.
Chris Lattner1bcbf852011-08-12 18:07:26 +0000261 if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000262 // If there are no element types to map, then the type is itself. This is
263 // true for the anonymous {} struct, things like 'float', integers, etc.
264 if (Ty->getNumContainedTypes() == 0)
265 return *Entry = Ty;
266
267 // Remap all of the elements, keeping track of whether any of them change.
268 bool AnyChange = false;
269 SmallVector<Type*, 4> ElementTypes;
270 ElementTypes.resize(Ty->getNumContainedTypes());
271 for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) {
272 ElementTypes[i] = getImpl(Ty->getContainedType(i));
273 AnyChange |= ElementTypes[i] != Ty->getContainedType(i);
274 }
275
276 // If we found our type while recursively processing stuff, just use it.
277 Entry = &MappedTypes[Ty];
278 if (*Entry) return *Entry;
279
280 // If all of the element types mapped directly over, then the type is usable
281 // as-is.
282 if (!AnyChange)
283 return *Entry = Ty;
284
285 // Otherwise, rebuild a modified type.
286 switch (Ty->getTypeID()) {
Craig Topper85814382012-02-07 05:05:23 +0000287 default: llvm_unreachable("unknown derived type to remap");
Chris Lattner1afcace2011-07-09 17:41:24 +0000288 case Type::ArrayTyID:
289 return *Entry = ArrayType::get(ElementTypes[0],
290 cast<ArrayType>(Ty)->getNumElements());
291 case Type::VectorTyID:
292 return *Entry = VectorType::get(ElementTypes[0],
293 cast<VectorType>(Ty)->getNumElements());
294 case Type::PointerTyID:
295 return *Entry = PointerType::get(ElementTypes[0],
296 cast<PointerType>(Ty)->getAddressSpace());
297 case Type::FunctionTyID:
298 return *Entry = FunctionType::get(ElementTypes[0],
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000299 makeArrayRef(ElementTypes).slice(1),
Chris Lattner1afcace2011-07-09 17:41:24 +0000300 cast<FunctionType>(Ty)->isVarArg());
301 case Type::StructTyID:
302 // Note that this is only reached for anonymous structs.
303 return *Entry = StructType::get(Ty->getContext(), ElementTypes,
304 cast<StructType>(Ty)->isPacked());
305 }
306 }
307
308 // Otherwise, this is an unmapped named struct. If the struct can be directly
309 // mapped over, just use it as-is. This happens in a case when the linked-in
310 // module has something like:
311 // %T = type {%T*, i32}
312 // @GV = global %T* null
313 // where T does not exist at all in the destination module.
314 //
315 // The other case we watch for is when the type is not in the destination
316 // module, but that it has to be rebuilt because it refers to something that
317 // is already mapped. For example, if the destination module has:
318 // %A = type { i32 }
319 // and the source module has something like
320 // %A' = type { i32 }
321 // %B = type { %A'* }
322 // @GV = global %B* null
323 // then we want to create a new type: "%B = type { %A*}" and have it take the
324 // pristine "%B" name from the source module.
325 //
326 // To determine which case this is, we have to recursively walk the type graph
327 // speculating that we'll be able to reuse it unmodified. Only if this is
328 // safe would we map the entire thing over. Because this is an optimization,
329 // and is not required for the prettiness of the linked module, we just skip
330 // it and always rebuild a type here.
331 StructType *STy = cast<StructType>(Ty);
332
333 // If the type is opaque, we can just use it directly.
334 if (STy->isOpaque())
335 return *Entry = STy;
Bill Wendling601c0942012-02-28 04:01:21 +0000336
Chris Lattner1afcace2011-07-09 17:41:24 +0000337 // Otherwise we create a new type and resolve its body later. This will be
338 // resolved by the top level of get().
Chris Lattner68910502011-12-20 00:03:52 +0000339 SrcDefinitionsToResolve.push_back(STy);
340 StructType *DTy = StructType::create(STy->getContext());
341 DstResolvedOpaqueTypes.insert(DTy);
342 return *Entry = DTy;
Chris Lattner1afcace2011-07-09 17:41:24 +0000343}
344
Chris Lattner1afcace2011-07-09 17:41:24 +0000345//===----------------------------------------------------------------------===//
346// ModuleLinker implementation.
347//===----------------------------------------------------------------------===//
348
349namespace {
350 /// ModuleLinker - This is an implementation class for the LinkModules
351 /// function, which is the entrypoint for this file.
352 class ModuleLinker {
353 Module *DstM, *SrcM;
354
355 TypeMapTy TypeMap;
356
357 /// ValueMap - Mapping of values from what they used to be in Src, to what
358 /// they are now in DstM. ValueToValueMapTy is a ValueMap, which involves
359 /// some overhead due to the use of Value handles which the Linker doesn't
360 /// actually need, but this allows us to reuse the ValueMapper code.
361 ValueToValueMapTy ValueMap;
362
363 struct AppendingVarInfo {
364 GlobalVariable *NewGV; // New aggregate global in dest module.
365 Constant *DstInit; // Old initializer from dest module.
366 Constant *SrcInit; // Old initializer from src module.
367 };
368
369 std::vector<AppendingVarInfo> AppendingVars;
370
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000371 unsigned Mode; // Mode to treat source module.
372
373 // Set of items not to link in from source.
374 SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
375
Tanya Lattner9af37a32011-11-02 00:24:56 +0000376 // Vector of functions to lazily link in.
377 std::vector<Function*> LazilyLinkFunctions;
378
Chris Lattner1afcace2011-07-09 17:41:24 +0000379 public:
380 std::string ErrorMsg;
381
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000382 ModuleLinker(Module *dstM, Module *srcM, unsigned mode)
383 : DstM(dstM), SrcM(srcM), Mode(mode) { }
Chris Lattner1afcace2011-07-09 17:41:24 +0000384
385 bool run();
386
387 private:
388 /// emitError - Helper method for setting a message and returning an error
389 /// code.
390 bool emitError(const Twine &Message) {
391 ErrorMsg = Message.str();
Chris Lattnerf6f4f7a2008-06-16 18:27:53 +0000392 return true;
Chris Lattnera4477f92008-06-16 21:17:12 +0000393 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000394
395 /// getLinkageResult - This analyzes the two global values and determines
396 /// what the result will look like in the destination module.
397 bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Rafael Espindola3ed88152012-01-05 23:02:01 +0000398 GlobalValue::LinkageTypes &LT,
399 GlobalValue::VisibilityTypes &Vis,
400 bool &LinkFromSrc);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000401
Chris Lattner1afcace2011-07-09 17:41:24 +0000402 /// getLinkedToGlobal - Given a global in the source module, return the
403 /// global in the destination module that is being linked to, if any.
404 GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
405 // If the source has no name it can't link. If it has local linkage,
406 // there is no name match-up going on.
407 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
408 return 0;
Bill Wendling601c0942012-02-28 04:01:21 +0000409
Chris Lattner1afcace2011-07-09 17:41:24 +0000410 // Otherwise see if we have a match in the destination module's symtab.
411 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
412 if (DGV == 0) return 0;
Bill Wendling601c0942012-02-28 04:01:21 +0000413
Chris Lattner1afcace2011-07-09 17:41:24 +0000414 // If we found a global with the same name in the dest module, but it has
415 // internal linkage, we are really not doing any linkage here.
416 if (DGV->hasLocalLinkage())
417 return 0;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000418
Chris Lattner1afcace2011-07-09 17:41:24 +0000419 // Otherwise, we do in fact link to the destination global.
420 return DGV;
421 }
422
423 void computeTypeMapping();
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000424 bool categorizeModuleFlagNodes(const NamedMDNode *ModFlags,
425 DenseMap<MDString*, MDNode*> &ErrorNode,
426 DenseMap<MDString*, MDNode*> &WarningNode,
427 DenseMap<MDString*, MDNode*> &OverrideNode,
428 DenseMap<MDString*,
429 SmallSetVector<MDNode*, 8> > &RequireNodes,
430 SmallSetVector<MDString*, 16> &SeenIDs);
Chris Lattner1afcace2011-07-09 17:41:24 +0000431
432 bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
433 bool linkGlobalProto(GlobalVariable *SrcGV);
434 bool linkFunctionProto(Function *SrcF);
435 bool linkAliasProto(GlobalAlias *SrcA);
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000436 bool linkModuleFlagsMetadata();
Chris Lattner1afcace2011-07-09 17:41:24 +0000437
438 void linkAppendingVarInit(const AppendingVarInfo &AVI);
439 void linkGlobalInits();
440 void linkFunctionBody(Function *Dst, Function *Src);
441 void linkAliasBodies();
442 void linkNamedMDNodes();
443 };
Bill Wendling601c0942012-02-28 04:01:21 +0000444}
445
Chris Lattner1afcace2011-07-09 17:41:24 +0000446/// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
Reid Spencer8bef0372007-02-04 04:29:21 +0000447/// in the symbol table. This is good for all clients except for us. Go
448/// through the trouble to force this back.
Chris Lattner1afcace2011-07-09 17:41:24 +0000449static void forceRenaming(GlobalValue *GV, StringRef Name) {
450 // If the global doesn't force its name or if it already has the right name,
451 // there is nothing for us to do.
452 if (GV->hasLocalLinkage() || GV->getName() == Name)
453 return;
454
455 Module *M = GV->getParent();
Chris Lattnerc0036282004-08-04 07:05:54 +0000456
457 // If there is a conflict, rename the conflict.
Chris Lattner1afcace2011-07-09 17:41:24 +0000458 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
Chris Lattner33f29492007-02-11 00:39:38 +0000459 GV->takeName(ConflictGV);
460 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Chris Lattner1afcace2011-07-09 17:41:24 +0000461 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
Chris Lattner33f29492007-02-11 00:39:38 +0000462 } else {
463 GV->setName(Name); // Force the name back
Reid Spenceref9b9a72007-02-05 20:47:22 +0000464 }
Reid Spenceref9b9a72007-02-05 20:47:22 +0000465}
Reid Spencer8bef0372007-02-04 04:29:21 +0000466
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000467/// copyGVAttributes - copy additional attributes (those not needed to construct
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000468/// a GlobalValue) from the SrcGV to the DestGV.
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000469static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
Duncan Sands28c3cff2008-05-26 19:58:59 +0000470 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
471 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
472 DestGV->copyAttributesFrom(SrcGV);
473 DestGV->setAlignment(Alignment);
Chris Lattner1afcace2011-07-09 17:41:24 +0000474
475 forceRenaming(DestGV, SrcGV->getName());
Chris Lattnerc0036282004-08-04 07:05:54 +0000476}
477
Rafael Espindola3ed88152012-01-05 23:02:01 +0000478static bool isLessConstraining(GlobalValue::VisibilityTypes a,
479 GlobalValue::VisibilityTypes b) {
480 if (a == GlobalValue::HiddenVisibility)
481 return false;
482 if (b == GlobalValue::HiddenVisibility)
483 return true;
484 if (a == GlobalValue::ProtectedVisibility)
485 return false;
486 if (b == GlobalValue::ProtectedVisibility)
487 return true;
488 return false;
489}
490
Chris Lattner1afcace2011-07-09 17:41:24 +0000491/// getLinkageResult - This analyzes the two global values and determines what
Chris Lattneraee38ea2004-12-03 22:18:41 +0000492/// the result will look like in the destination module. In particular, it
Rafael Espindola3ed88152012-01-05 23:02:01 +0000493/// computes the resultant linkage type and visibility, computes whether the
494/// global in the source should be copied over to the destination (replacing
495/// the existing one), and computes whether this linkage is an error or not.
Chris Lattner1afcace2011-07-09 17:41:24 +0000496bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Rafael Espindola3ed88152012-01-05 23:02:01 +0000497 GlobalValue::LinkageTypes &LT,
498 GlobalValue::VisibilityTypes &Vis,
Chris Lattner1afcace2011-07-09 17:41:24 +0000499 bool &LinkFromSrc) {
500 assert(Dest && "Must have two globals being queried");
501 assert(!Src->hasLocalLinkage() &&
Chris Lattneraee38ea2004-12-03 22:18:41 +0000502 "If Src has internal linkage, Dest shouldn't be set!");
Chris Lattner1afcace2011-07-09 17:41:24 +0000503
Peter Collingbourne88953162011-10-30 17:46:34 +0000504 bool SrcIsDeclaration = Src->isDeclaration() && !Src->isMaterializable();
Chris Lattnerf84c59d2011-07-14 20:23:05 +0000505 bool DestIsDeclaration = Dest->isDeclaration();
Chris Lattner1afcace2011-07-09 17:41:24 +0000506
507 if (SrcIsDeclaration) {
Anton Korobeynikov2b48ef02008-03-10 22:33:22 +0000508 // If Src is external or if both Src & Dest are external.. Just link the
Chris Lattneraee38ea2004-12-03 22:18:41 +0000509 // external globals, we aren't adding anything.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000510 if (Src->hasDLLImportLinkage()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000511 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
Chris Lattner1afcace2011-07-09 17:41:24 +0000512 if (DestIsDeclaration) {
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000513 LinkFromSrc = true;
514 LT = Src->getLinkage();
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000515 }
Andrew Lenharth8753c442006-12-15 17:35:32 +0000516 } else if (Dest->hasExternalWeakLinkage()) {
Duncan Sands667d4b82009-03-07 15:45:40 +0000517 // If the Dest is weak, use the source linkage.
Andrew Lenharth8753c442006-12-15 17:35:32 +0000518 LinkFromSrc = true;
519 LT = Src->getLinkage();
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000520 } else {
521 LinkFromSrc = false;
522 LT = Dest->getLinkage();
523 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000524 } else if (DestIsDeclaration && !Dest->hasDLLImportLinkage()) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000525 // If Dest is external but Src is not:
526 LinkFromSrc = true;
527 LT = Src->getLinkage();
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000528 } else if (Src->isWeakForLinker()) {
Dale Johannesenaafce772008-05-14 20:12:51 +0000529 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
530 // or DLL* linkage.
Chris Lattner266c7bb2009-04-13 05:44:34 +0000531 if (Dest->hasExternalWeakLinkage() ||
532 Dest->hasAvailableExternallyLinkage() ||
533 (Dest->hasLinkOnceLinkage() &&
534 (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000535 LinkFromSrc = true;
536 LT = Src->getLinkage();
537 } else {
538 LinkFromSrc = false;
539 LT = Dest->getLinkage();
540 }
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000541 } else if (Dest->isWeakForLinker()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000542 // At this point we know that Src has External* or DLL* linkage.
543 if (Src->hasExternalWeakLinkage()) {
544 LinkFromSrc = false;
545 LT = Dest->getLinkage();
546 } else {
547 LinkFromSrc = true;
548 LT = GlobalValue::ExternalLinkage;
549 }
Chris Lattneraee38ea2004-12-03 22:18:41 +0000550 } else {
Chris Lattner1afcace2011-07-09 17:41:24 +0000551 assert((Dest->hasExternalLinkage() || Dest->hasDLLImportLinkage() ||
552 Dest->hasDLLExportLinkage() || Dest->hasExternalWeakLinkage()) &&
553 (Src->hasExternalLinkage() || Src->hasDLLImportLinkage() ||
554 Src->hasDLLExportLinkage() || Src->hasExternalWeakLinkage()) &&
Chris Lattneraee38ea2004-12-03 22:18:41 +0000555 "Unexpected linkage type!");
Chris Lattner1afcace2011-07-09 17:41:24 +0000556 return emitError("Linking globals named '" + Src->getName() +
Chris Lattneraee38ea2004-12-03 22:18:41 +0000557 "': symbol multiply defined!");
558 }
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +0000559
Rafael Espindola3ed88152012-01-05 23:02:01 +0000560 // Compute the visibility. We follow the rules in the System V Application
561 // Binary Interface.
562 Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
563 Dest->getVisibility() : Src->getVisibility();
Chris Lattneraee38ea2004-12-03 22:18:41 +0000564 return false;
565}
Chris Lattner5c377c52001-10-14 23:29:15 +0000566
Chris Lattner1afcace2011-07-09 17:41:24 +0000567/// computeTypeMapping - Loop over all of the linked values to compute type
568/// mappings. For example, if we link "extern Foo *x" and "Foo *x = NULL", then
569/// we have two struct types 'Foo' but one got renamed when the module was
570/// loaded into the same LLVMContext.
571void ModuleLinker::computeTypeMapping() {
572 // Incorporate globals.
573 for (Module::global_iterator I = SrcM->global_begin(),
574 E = SrcM->global_end(); I != E; ++I) {
575 GlobalValue *DGV = getLinkedToGlobal(I);
576 if (DGV == 0) continue;
577
578 if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
579 TypeMap.addTypeMapping(DGV->getType(), I->getType());
580 continue;
581 }
582
583 // Unify the element type of appending arrays.
584 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
585 ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
586 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
Devang Patelab67e702009-08-11 18:01:24 +0000587 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000588
589 // Incorporate functions.
590 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
591 if (GlobalValue *DGV = getLinkedToGlobal(I))
592 TypeMap.addTypeMapping(DGV->getType(), I->getType());
593 }
Bill Wendlingc68d1272012-02-27 22:34:19 +0000594
Bill Wendling601c0942012-02-28 04:01:21 +0000595 // Incorporate types by name, scanning all the types in the source module.
596 // At this point, the destination module may have a type "%foo = { i32 }" for
Bill Wendling348e5e72012-02-27 23:48:30 +0000597 // example. When the source module got loaded into the same LLVMContext, if
598 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
Bill Wendling573e9732012-08-03 00:30:35 +0000599 TypeFinder SrcStructTypes;
600 SrcStructTypes.run(*SrcM, true);
Bill Wendling348e5e72012-02-27 23:48:30 +0000601 SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
602 SrcStructTypes.end());
Bill Wendlinga20689f2012-03-23 23:17:38 +0000603
Bill Wendling573e9732012-08-03 00:30:35 +0000604 TypeFinder DstStructTypes;
605 DstStructTypes.run(*DstM, true);
Bill Wendlinga20689f2012-03-23 23:17:38 +0000606 SmallPtrSet<StructType*, 32> DstStructTypesSet(DstStructTypes.begin(),
607 DstStructTypes.end());
608
Bill Wendling348e5e72012-02-27 23:48:30 +0000609 for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
610 StructType *ST = SrcStructTypes[i];
611 if (!ST->hasName()) continue;
612
613 // Check to see if there is a dot in the name followed by a digit.
Bill Wendling601c0942012-02-28 04:01:21 +0000614 size_t DotPos = ST->getName().rfind('.');
615 if (DotPos == 0 || DotPos == StringRef::npos ||
616 ST->getName().back() == '.' || !isdigit(ST->getName()[DotPos+1]))
617 continue;
Bill Wendling348e5e72012-02-27 23:48:30 +0000618
619 // Check to see if the destination module has a struct with the prefix name.
Bill Wendling601c0942012-02-28 04:01:21 +0000620 if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
Bill Wendlinga20689f2012-03-23 23:17:38 +0000621 // Don't use it if this actually came from the source module. They're in
622 // the same LLVMContext after all. Also don't use it unless the type is
623 // actually used in the destination module. This can happen in situations
624 // like this:
625 //
626 // Module A Module B
627 // -------- --------
628 // %Z = type { %A } %B = type { %C.1 }
629 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
630 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
631 // %C = type { i8* } %B.3 = type { %C.1 }
632 //
633 // When we link Module B with Module A, the '%B' in Module B is
634 // used. However, that would then use '%C.1'. But when we process '%C.1',
635 // we prefer to take the '%C' version. So we are then left with both
636 // '%C.1' and '%C' being used for the same types. This leads to some
637 // variables using one type and some using the other.
638 if (!SrcStructTypesSet.count(DST) && DstStructTypesSet.count(DST))
Bill Wendling348e5e72012-02-27 23:48:30 +0000639 TypeMap.addTypeMapping(DST, ST);
640 }
641
Chris Lattner1afcace2011-07-09 17:41:24 +0000642 // Don't bother incorporating aliases, they aren't generally typed well.
Bill Wendling601c0942012-02-28 04:01:21 +0000643
Chris Lattner1afcace2011-07-09 17:41:24 +0000644 // Now that we have discovered all of the type equivalences, get a body for
645 // any 'opaque' types in the dest module that are now resolved.
646 TypeMap.linkDefinedTypeBodies();
Devang Patelab67e702009-08-11 18:01:24 +0000647}
648
Chris Lattner1afcace2011-07-09 17:41:24 +0000649/// linkAppendingVarProto - If there were any appending global variables, link
650/// them together now. Return true on error.
651bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
652 GlobalVariable *SrcGV) {
Bill Wendling601c0942012-02-28 04:01:21 +0000653
Chris Lattner1afcace2011-07-09 17:41:24 +0000654 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
655 return emitError("Linking globals named '" + SrcGV->getName() +
656 "': can only link appending global with another appending global!");
657
658 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
659 ArrayType *SrcTy =
660 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
661 Type *EltTy = DstTy->getElementType();
662
663 // Check to see that they two arrays agree on type.
664 if (EltTy != SrcTy->getElementType())
665 return emitError("Appending variables with different element types!");
666 if (DstGV->isConstant() != SrcGV->isConstant())
667 return emitError("Appending variables linked with different const'ness!");
668
669 if (DstGV->getAlignment() != SrcGV->getAlignment())
670 return emitError(
671 "Appending variables with different alignment need to be linked!");
672
673 if (DstGV->getVisibility() != SrcGV->getVisibility())
674 return emitError(
675 "Appending variables with different visibility need to be linked!");
676
677 if (DstGV->getSection() != SrcGV->getSection())
678 return emitError(
679 "Appending variables with different section name need to be linked!");
680
681 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
682 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
683
684 // Create the new global variable.
685 GlobalVariable *NG =
686 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
687 DstGV->getLinkage(), /*init*/0, /*name*/"", DstGV,
Hans Wennborgce718ff2012-06-23 11:37:03 +0000688 DstGV->getThreadLocalMode(),
Chris Lattner1afcace2011-07-09 17:41:24 +0000689 DstGV->getType()->getAddressSpace());
690
691 // Propagate alignment, visibility and section info.
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000692 copyGVAttributes(NG, DstGV);
Chris Lattner1afcace2011-07-09 17:41:24 +0000693
694 AppendingVarInfo AVI;
695 AVI.NewGV = NG;
696 AVI.DstInit = DstGV->getInitializer();
697 AVI.SrcInit = SrcGV->getInitializer();
698 AppendingVars.push_back(AVI);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000699
Chris Lattner1afcace2011-07-09 17:41:24 +0000700 // Replace any uses of the two global variables with uses of the new
701 // global.
702 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000703
Chris Lattner1afcace2011-07-09 17:41:24 +0000704 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
705 DstGV->eraseFromParent();
706
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000707 // Track the source variable so we don't try to link it.
708 DoNotLinkFromSource.insert(SrcGV);
709
Chris Lattner1afcace2011-07-09 17:41:24 +0000710 return false;
711}
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000712
Chris Lattner1afcace2011-07-09 17:41:24 +0000713/// linkGlobalProto - Loop through the global variables in the src module and
714/// merge them into the dest module.
715bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
716 GlobalValue *DGV = getLinkedToGlobal(SGV);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000717 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000718
Chris Lattner1afcace2011-07-09 17:41:24 +0000719 if (DGV) {
720 // Concatenation of appending linkage variables is magic and handled later.
721 if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
722 return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
723
724 // Determine whether linkage of these two globals follows the source
725 // module's definition or the destination module's definition.
Chris Lattnerb324bd72006-11-09 05:18:12 +0000726 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000727 GlobalValue::VisibilityTypes NV;
Chris Lattnerb324bd72006-11-09 05:18:12 +0000728 bool LinkFromSrc = false;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000729 if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
Chris Lattneraee38ea2004-12-03 22:18:41 +0000730 return true;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000731 NewVisibility = NV;
Chris Lattner0fec08e2003-04-21 21:07:05 +0000732
Chris Lattner1afcace2011-07-09 17:41:24 +0000733 // If we're not linking from the source, then keep the definition that we
734 // have.
735 if (!LinkFromSrc) {
736 // Special case for const propagation.
737 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
738 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
739 DGVar->setConstant(true);
740
Rafael Espindola3ed88152012-01-05 23:02:01 +0000741 // Set calculated linkage and visibility.
Chris Lattner1afcace2011-07-09 17:41:24 +0000742 DGV->setLinkage(NewLinkage);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000743 DGV->setVisibility(*NewVisibility);
744
Chris Lattner6157e382008-07-14 07:23:24 +0000745 // Make sure to remember this mapping.
Chris Lattner1afcace2011-07-09 17:41:24 +0000746 ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
747
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000748 // Track the source global so that we don't attempt to copy it over when
749 // processing global initializers.
750 DoNotLinkFromSource.insert(SGV);
751
Chris Lattner1afcace2011-07-09 17:41:24 +0000752 return false;
Chris Lattner6157e382008-07-14 07:23:24 +0000753 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000754 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000755
756 // No linking to be performed or linking from the source: simply create an
757 // identical version of the symbol over in the dest module... the
758 // initializer will be filled in later by LinkGlobalInits.
759 GlobalVariable *NewDGV =
760 new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
761 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
762 SGV->getName(), /*insertbefore*/0,
Hans Wennborgce718ff2012-06-23 11:37:03 +0000763 SGV->getThreadLocalMode(),
Chris Lattner1afcace2011-07-09 17:41:24 +0000764 SGV->getType()->getAddressSpace());
765 // Propagate alignment, visibility and section info.
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000766 copyGVAttributes(NewDGV, SGV);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000767 if (NewVisibility)
768 NewDGV->setVisibility(*NewVisibility);
Chris Lattner1afcace2011-07-09 17:41:24 +0000769
770 if (DGV) {
771 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
772 DGV->eraseFromParent();
773 }
774
775 // Make sure to remember this mapping.
776 ValueMap[SGV] = NewDGV;
Chris Lattner5c377c52001-10-14 23:29:15 +0000777 return false;
778}
779
Chris Lattner1afcace2011-07-09 17:41:24 +0000780/// linkFunctionProto - Link the function in the source module into the
781/// destination module if needed, setting up mapping information.
782bool ModuleLinker::linkFunctionProto(Function *SF) {
783 GlobalValue *DGV = getLinkedToGlobal(SF);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000784 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Chris Lattner1afcace2011-07-09 17:41:24 +0000785
786 if (DGV) {
787 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
788 bool LinkFromSrc = false;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000789 GlobalValue::VisibilityTypes NV;
790 if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
Chris Lattner1afcace2011-07-09 17:41:24 +0000791 return true;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000792 NewVisibility = NV;
793
Chris Lattner1afcace2011-07-09 17:41:24 +0000794 if (!LinkFromSrc) {
795 // Set calculated linkage
796 DGV->setLinkage(NewLinkage);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000797 DGV->setVisibility(*NewVisibility);
798
Chris Lattner1afcace2011-07-09 17:41:24 +0000799 // Make sure to remember this mapping.
800 ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
801
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000802 // Track the function from the source module so we don't attempt to remap
803 // it.
804 DoNotLinkFromSource.insert(SF);
805
Chris Lattner1afcace2011-07-09 17:41:24 +0000806 return false;
807 }
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000808 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000809
810 // If there is no linkage to be performed or we are linking from the source,
811 // bring SF over.
812 Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
813 SF->getLinkage(), SF->getName(), DstM);
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000814 copyGVAttributes(NewDF, SF);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000815 if (NewVisibility)
816 NewDF->setVisibility(*NewVisibility);
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000817
Chris Lattner1afcace2011-07-09 17:41:24 +0000818 if (DGV) {
819 // Any uses of DF need to change to NewDF, with cast.
820 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
821 DGV->eraseFromParent();
Tanya Lattner9af37a32011-11-02 00:24:56 +0000822 } else {
823 // Internal, LO_ODR, or LO linkage - stick in set to ignore and lazily link.
824 if (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
825 SF->hasAvailableExternallyLinkage()) {
826 DoNotLinkFromSource.insert(SF);
827 LazilyLinkFunctions.push_back(SF);
828 }
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000829 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000830
831 ValueMap[SF] = NewDF;
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000832 return false;
833}
834
Chris Lattner1afcace2011-07-09 17:41:24 +0000835/// LinkAliasProto - Set up prototypes for any aliases that come over from the
836/// source module.
837bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
838 GlobalValue *DGV = getLinkedToGlobal(SGA);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000839 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
840
Chris Lattner1afcace2011-07-09 17:41:24 +0000841 if (DGV) {
842 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000843 GlobalValue::VisibilityTypes NV;
Chris Lattner1afcace2011-07-09 17:41:24 +0000844 bool LinkFromSrc = false;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000845 if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
Chris Lattner1afcace2011-07-09 17:41:24 +0000846 return true;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000847 NewVisibility = NV;
848
Chris Lattner1afcace2011-07-09 17:41:24 +0000849 if (!LinkFromSrc) {
850 // Set calculated linkage.
851 DGV->setLinkage(NewLinkage);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000852 DGV->setVisibility(*NewVisibility);
853
Chris Lattner1afcace2011-07-09 17:41:24 +0000854 // Make sure to remember this mapping.
855 ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
856
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000857 // Track the alias from the source module so we don't attempt to remap it.
858 DoNotLinkFromSource.insert(SGA);
859
Chris Lattner1afcace2011-07-09 17:41:24 +0000860 return false;
861 }
862 }
863
864 // If there is no linkage to be performed or we're linking from the source,
865 // bring over SGA.
866 GlobalAlias *NewDA = new GlobalAlias(TypeMap.get(SGA->getType()),
867 SGA->getLinkage(), SGA->getName(),
868 /*aliasee*/0, DstM);
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000869 copyGVAttributes(NewDA, SGA);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000870 if (NewVisibility)
871 NewDA->setVisibility(*NewVisibility);
Chris Lattner5c377c52001-10-14 23:29:15 +0000872
Chris Lattner1afcace2011-07-09 17:41:24 +0000873 if (DGV) {
874 // Any uses of DGV need to change to NewDA, with cast.
875 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
876 DGV->eraseFromParent();
877 }
878
879 ValueMap[SGA] = NewDA;
880 return false;
881}
882
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000883static void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000884 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
885
886 for (unsigned i = 0; i != NumElements; ++i)
887 Dest.push_back(C->getAggregateElement(i));
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000888}
889
Chris Lattner1afcace2011-07-09 17:41:24 +0000890void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
891 // Merge the initializer.
892 SmallVector<Constant*, 16> Elements;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000893 getArrayElements(AVI.DstInit, Elements);
Chris Lattner1afcace2011-07-09 17:41:24 +0000894
895 Constant *SrcInit = MapValue(AVI.SrcInit, ValueMap, RF_None, &TypeMap);
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000896 getArrayElements(SrcInit, Elements);
897
Chris Lattner1afcace2011-07-09 17:41:24 +0000898 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
899 AVI.NewGV->setInitializer(ConstantArray::get(NewType, Elements));
900}
901
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000902/// linkGlobalInits - Update the initializers in the Dest module now that all
903/// globals that may be referenced are in Dest.
Chris Lattner1afcace2011-07-09 17:41:24 +0000904void ModuleLinker::linkGlobalInits() {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000905 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattner1afcace2011-07-09 17:41:24 +0000906 for (Module::const_global_iterator I = SrcM->global_begin(),
907 E = SrcM->global_end(); I != E; ++I) {
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000908
909 // Only process initialized GV's or ones not already in dest.
910 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
Chris Lattner1afcace2011-07-09 17:41:24 +0000911
912 // Grab destination global variable.
913 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
914 // Figure out what the initializer looks like in the dest module.
915 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
916 RF_None, &TypeMap));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000917 }
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000918}
Chris Lattner5c377c52001-10-14 23:29:15 +0000919
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000920/// linkFunctionBody - Copy the source function over into the dest function and
921/// fix up references to values. At this point we know that Dest is an external
922/// function, and that Src is not.
Chris Lattner1afcace2011-07-09 17:41:24 +0000923void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
924 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
Chris Lattner5c377c52001-10-14 23:29:15 +0000925
Chris Lattner0033baf2004-11-16 17:12:38 +0000926 // Go through and convert function arguments over, remembering the mapping.
Chris Lattner1afcace2011-07-09 17:41:24 +0000927 Function::arg_iterator DI = Dst->arg_begin();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000928 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
Chris Lattner69da5cf2002-10-13 20:57:00 +0000929 I != E; ++I, ++DI) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000930 DI->setName(I->getName()); // Copy the name over.
Chris Lattner5c377c52001-10-14 23:29:15 +0000931
Chris Lattner1afcace2011-07-09 17:41:24 +0000932 // Add a mapping to our mapping.
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000933 ValueMap[I] = DI;
Chris Lattner5c377c52001-10-14 23:29:15 +0000934 }
935
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000936 if (Mode == Linker::DestroySource) {
937 // Splice the body of the source function into the dest function.
938 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
939
940 // At this point, all of the instructions and values of the function are now
941 // copied over. The only problem is that they are still referencing values in
942 // the Source function as operands. Loop through all of the operands of the
943 // functions and patch them up to point to the local versions.
944 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
945 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
946 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap);
947
948 } else {
949 // Clone the body of the function into the dest function.
950 SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
Mon P Wangd24397a2011-12-23 02:18:32 +0000951 CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", NULL, &TypeMap);
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000952 }
953
Chris Lattner0033baf2004-11-16 17:12:38 +0000954 // There is no need to map the arguments anymore.
Chris Lattner11273152006-06-16 01:24:04 +0000955 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
956 I != E; ++I)
Reid Spenceref9b9a72007-02-05 20:47:22 +0000957 ValueMap.erase(I);
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000958
Chris Lattner5c377c52001-10-14 23:29:15 +0000959}
960
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000961/// linkAliasBodies - Insert all of the aliases in Src into the Dest module.
Chris Lattner1afcace2011-07-09 17:41:24 +0000962void ModuleLinker::linkAliasBodies() {
963 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000964 I != E; ++I) {
965 if (DoNotLinkFromSource.count(I))
966 continue;
Chris Lattner1afcace2011-07-09 17:41:24 +0000967 if (Constant *Aliasee = I->getAliasee()) {
968 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
969 DA->setAliasee(MapValue(Aliasee, ValueMap, RF_None, &TypeMap));
David Chisnall34722462010-01-09 16:27:31 +0000970 }
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000971 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000972}
Anton Korobeynikov9f2ee702008-03-05 23:21:39 +0000973
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000974/// linkNamedMDNodes - Insert all of the named MDNodes in Src into the Dest
Chris Lattner1afcace2011-07-09 17:41:24 +0000975/// module.
976void ModuleLinker::linkNamedMDNodes() {
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000977 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
Chris Lattner1afcace2011-07-09 17:41:24 +0000978 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
979 E = SrcM->named_metadata_end(); I != E; ++I) {
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000980 // Don't link module flags here. Do them separately.
981 if (&*I == SrcModFlags) continue;
Chris Lattner1afcace2011-07-09 17:41:24 +0000982 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
983 // Add Src elements into Dest node.
984 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
985 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
986 RF_None, &TypeMap));
987 }
988}
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000989
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000990/// categorizeModuleFlagNodes - Categorize the module flags according to their
991/// type: Error, Warning, Override, and Require.
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000992bool ModuleLinker::
993categorizeModuleFlagNodes(const NamedMDNode *ModFlags,
994 DenseMap<MDString*, MDNode*> &ErrorNode,
995 DenseMap<MDString*, MDNode*> &WarningNode,
996 DenseMap<MDString*, MDNode*> &OverrideNode,
997 DenseMap<MDString*,
998 SmallSetVector<MDNode*, 8> > &RequireNodes,
999 SmallSetVector<MDString*, 16> &SeenIDs) {
1000 bool HasErr = false;
1001
1002 for (unsigned I = 0, E = ModFlags->getNumOperands(); I != E; ++I) {
1003 MDNode *Op = ModFlags->getOperand(I);
1004 assert(Op->getNumOperands() == 3 && "Invalid module flag metadata!");
1005 assert(isa<ConstantInt>(Op->getOperand(0)) &&
1006 "Module flag's first operand must be an integer!");
1007 assert(isa<MDString>(Op->getOperand(1)) &&
1008 "Module flag's second operand must be an MDString!");
1009
1010 ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1011 MDString *ID = cast<MDString>(Op->getOperand(1));
1012 Value *Val = Op->getOperand(2);
1013 switch (Behavior->getZExtValue()) {
1014 default:
1015 assert(false && "Invalid behavior in module flag metadata!");
1016 break;
1017 case Module::Error: {
1018 MDNode *&ErrNode = ErrorNode[ID];
1019 if (!ErrNode) ErrNode = Op;
1020 if (ErrNode->getOperand(2) != Val)
Bill Wendling75b3d682012-02-14 09:13:54 +00001021 HasErr = emitError("linking module flags '" + ID->getString() +
1022 "': IDs have conflicting values");
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001023 break;
1024 }
1025 case Module::Warning: {
1026 MDNode *&WarnNode = WarningNode[ID];
1027 if (!WarnNode) WarnNode = Op;
1028 if (WarnNode->getOperand(2) != Val)
Bill Wendling75b3d682012-02-14 09:13:54 +00001029 errs() << "WARNING: linking module flags '" << ID->getString()
1030 << "': IDs have conflicting values";
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001031 break;
1032 }
1033 case Module::Require: RequireNodes[ID].insert(Op); break;
1034 case Module::Override: {
1035 MDNode *&OvrNode = OverrideNode[ID];
1036 if (!OvrNode) OvrNode = Op;
1037 if (OvrNode->getOperand(2) != Val)
Bill Wendling75b3d682012-02-14 09:13:54 +00001038 HasErr = emitError("linking module flags '" + ID->getString() +
1039 "': IDs have conflicting override values");
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001040 break;
1041 }
1042 }
1043
1044 SeenIDs.insert(ID);
1045 }
1046
1047 return HasErr;
1048}
1049
1050/// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest
1051/// module.
1052bool ModuleLinker::linkModuleFlagsMetadata() {
1053 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1054 if (!SrcModFlags) return false;
1055
1056 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
1057
1058 // If the destination module doesn't have module flags yet, then just copy
1059 // over the source module's flags.
1060 if (DstModFlags->getNumOperands() == 0) {
1061 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1062 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1063
1064 return false;
1065 }
1066
1067 bool HasErr = false;
1068
1069 // Otherwise, we have to merge them based on their behaviors. First,
1070 // categorize all of the nodes in the modules' module flags. If an error or
1071 // warning occurs, then emit the appropriate message(s).
1072 DenseMap<MDString*, MDNode*> ErrorNode;
1073 DenseMap<MDString*, MDNode*> WarningNode;
1074 DenseMap<MDString*, MDNode*> OverrideNode;
1075 DenseMap<MDString*, SmallSetVector<MDNode*, 8> > RequireNodes;
1076 SmallSetVector<MDString*, 16> SeenIDs;
1077
1078 HasErr |= categorizeModuleFlagNodes(SrcModFlags, ErrorNode, WarningNode,
1079 OverrideNode, RequireNodes, SeenIDs);
1080 HasErr |= categorizeModuleFlagNodes(DstModFlags, ErrorNode, WarningNode,
1081 OverrideNode, RequireNodes, SeenIDs);
1082
1083 // Check that there isn't both an error and warning node for a flag.
1084 for (SmallSetVector<MDString*, 16>::iterator
1085 I = SeenIDs.begin(), E = SeenIDs.end(); I != E; ++I) {
1086 MDString *ID = *I;
1087 if (ErrorNode[ID] && WarningNode[ID])
Bill Wendling75b3d682012-02-14 09:13:54 +00001088 HasErr = emitError("linking module flags '" + ID->getString() +
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001089 "': IDs have conflicting behaviors");
1090 }
1091
1092 // Early exit if we had an error.
1093 if (HasErr) return true;
1094
1095 // Get the destination's module flags ready for new operands.
1096 DstModFlags->dropAllReferences();
1097
1098 // Add all of the module flags to the destination module.
1099 DenseMap<MDString*, SmallVector<MDNode*, 4> > AddedNodes;
1100 for (SmallSetVector<MDString*, 16>::iterator
1101 I = SeenIDs.begin(), E = SeenIDs.end(); I != E; ++I) {
1102 MDString *ID = *I;
1103 if (OverrideNode[ID]) {
1104 DstModFlags->addOperand(OverrideNode[ID]);
1105 AddedNodes[ID].push_back(OverrideNode[ID]);
1106 } else if (ErrorNode[ID]) {
1107 DstModFlags->addOperand(ErrorNode[ID]);
1108 AddedNodes[ID].push_back(ErrorNode[ID]);
1109 } else if (WarningNode[ID]) {
1110 DstModFlags->addOperand(WarningNode[ID]);
1111 AddedNodes[ID].push_back(WarningNode[ID]);
1112 }
1113
1114 for (SmallSetVector<MDNode*, 8>::iterator
1115 II = RequireNodes[ID].begin(), IE = RequireNodes[ID].end();
1116 II != IE; ++II)
1117 DstModFlags->addOperand(*II);
1118 }
1119
1120 // Now check that all of the requirements have been satisfied.
1121 for (SmallSetVector<MDString*, 16>::iterator
1122 I = SeenIDs.begin(), E = SeenIDs.end(); I != E; ++I) {
1123 MDString *ID = *I;
1124 SmallSetVector<MDNode*, 8> &Set = RequireNodes[ID];
1125
1126 for (SmallSetVector<MDNode*, 8>::iterator
1127 II = Set.begin(), IE = Set.end(); II != IE; ++II) {
1128 MDNode *Node = *II;
1129 assert(isa<MDNode>(Node->getOperand(2)) &&
1130 "Module flag's third operand must be an MDNode!");
1131 MDNode *Val = cast<MDNode>(Node->getOperand(2));
1132
1133 MDString *ReqID = cast<MDString>(Val->getOperand(0));
1134 Value *ReqVal = Val->getOperand(1);
1135
1136 bool HasValue = false;
1137 for (SmallVectorImpl<MDNode*>::iterator
1138 RI = AddedNodes[ReqID].begin(), RE = AddedNodes[ReqID].end();
1139 RI != RE; ++RI) {
1140 MDNode *ReqNode = *RI;
1141 if (ReqNode->getOperand(2) == ReqVal) {
1142 HasValue = true;
1143 break;
1144 }
1145 }
1146
1147 if (!HasValue)
Bill Wendling75b3d682012-02-14 09:13:54 +00001148 HasErr = emitError("linking module flags '" + ReqID->getString() +
1149 "': does not have the required value");
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001150 }
1151 }
1152
1153 return HasErr;
1154}
Chris Lattner1afcace2011-07-09 17:41:24 +00001155
1156bool ModuleLinker::run() {
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001157 assert(DstM && "Null destination module");
1158 assert(SrcM && "Null source module");
Chris Lattner1afcace2011-07-09 17:41:24 +00001159
1160 // Inherit the target data from the source module if the destination module
1161 // doesn't have one already.
1162 if (DstM->getDataLayout().empty() && !SrcM->getDataLayout().empty())
1163 DstM->setDataLayout(SrcM->getDataLayout());
1164
1165 // Copy the target triple from the source to dest if the dest's is empty.
1166 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1167 DstM->setTargetTriple(SrcM->getTargetTriple());
1168
1169 if (!SrcM->getDataLayout().empty() && !DstM->getDataLayout().empty() &&
1170 SrcM->getDataLayout() != DstM->getDataLayout())
1171 errs() << "WARNING: Linking two modules of different data layouts!\n";
1172 if (!SrcM->getTargetTriple().empty() &&
1173 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1174 errs() << "WARNING: Linking two modules of different target triples: ";
1175 if (!SrcM->getModuleIdentifier().empty())
1176 errs() << SrcM->getModuleIdentifier() << ": ";
1177 errs() << "'" << SrcM->getTargetTriple() << "' and '"
1178 << DstM->getTargetTriple() << "'\n";
1179 }
1180
1181 // Append the module inline asm string.
1182 if (!SrcM->getModuleInlineAsm().empty()) {
1183 if (DstM->getModuleInlineAsm().empty())
1184 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1185 else
1186 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1187 SrcM->getModuleInlineAsm());
1188 }
1189
Chris Lattner1afcace2011-07-09 17:41:24 +00001190 // 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);
Bill Wendling208b6f62012-03-23 07:22:49 +00001237 SF->Dematerialize();
Chris Lattner1afcace2011-07-09 17:41:24 +00001238 }
1239
1240 // Resolve all uses of aliases with aliasees.
1241 linkAliasBodies();
1242
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001243 // Remap all of the named MDNodes in Src into the DstM module. We do this
Devang Patel211da8f2011-08-04 19:44:28 +00001244 // after linking GlobalValues so that MDNodes that reference GlobalValues
1245 // are properly remapped.
1246 linkNamedMDNodes();
1247
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001248 // Merge the module flags into the DstM module.
1249 if (linkModuleFlagsMetadata())
1250 return true;
1251
Tanya Lattner9af37a32011-11-02 00:24:56 +00001252 // Process vector of lazily linked in functions.
1253 bool LinkedInAnyFunctions;
1254 do {
1255 LinkedInAnyFunctions = false;
1256
1257 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1258 E = LazilyLinkFunctions.end(); I != E; ++I) {
1259 if (!*I)
1260 continue;
1261
1262 Function *SF = *I;
1263 Function *DF = cast<Function>(ValueMap[SF]);
1264
1265 if (!DF->use_empty()) {
1266
1267 // Materialize if necessary.
1268 if (SF->isDeclaration()) {
1269 if (!SF->isMaterializable())
1270 continue;
1271 if (SF->Materialize(&ErrorMsg))
1272 return true;
1273 }
1274
1275 // Link in function body.
1276 linkFunctionBody(DF, SF);
Bill Wendling208b6f62012-03-23 07:22:49 +00001277 SF->Dematerialize();
1278
Tanya Lattner9af37a32011-11-02 00:24:56 +00001279 // "Remove" from vector by setting the element to 0.
1280 *I = 0;
1281
1282 // Set flag to indicate we may have more functions to lazily link in
1283 // since we linked in a function.
1284 LinkedInAnyFunctions = true;
1285 }
1286 }
1287 } while (LinkedInAnyFunctions);
1288
1289 // Remove any prototypes of functions that were not actually linked in.
1290 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1291 E = LazilyLinkFunctions.end(); I != E; ++I) {
1292 if (!*I)
1293 continue;
1294
1295 Function *SF = *I;
1296 Function *DF = cast<Function>(ValueMap[SF]);
1297 if (DF->use_empty())
1298 DF->eraseFromParent();
1299 }
1300
Chris Lattner1afcace2011-07-09 17:41:24 +00001301 // Now that all of the types from the source are used, resolve any structs
1302 // copied over to the dest that didn't exist there.
1303 TypeMap.linkDefinedTypeBodies();
1304
Anton Korobeynikov9f2ee702008-03-05 23:21:39 +00001305 return false;
1306}
Chris Lattner52f7e902001-10-13 07:03:50 +00001307
Chris Lattner1afcace2011-07-09 17:41:24 +00001308//===----------------------------------------------------------------------===//
1309// LinkModules entrypoint.
1310//===----------------------------------------------------------------------===//
1311
Bill Wendlingcd7193f2012-03-22 20:28:27 +00001312/// LinkModules - This function links two modules together, with the resulting
1313/// left module modified to be the composite of the two input modules. If an
1314/// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1315/// the problem. Upon failure, the Dest module could be in a modified state,
1316/// and shouldn't be relied on to be consistent.
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +00001317bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode,
1318 std::string *ErrorMsg) {
1319 ModuleLinker TheLinker(Dest, Src, Mode);
Chris Lattner1afcace2011-07-09 17:41:24 +00001320 if (TheLinker.run()) {
1321 if (ErrorMsg) *ErrorMsg = TheLinker.ErrorMsg;
Reid Spencer619f0242007-02-04 04:43:17 +00001322 return true;
Chris Lattner5a837de2004-08-04 07:44:58 +00001323 }
Bill Wendlinga20689f2012-03-23 23:17:38 +00001324
Chris Lattner52f7e902001-10-13 07:03:50 +00001325 return false;
1326}
Bill Wendlingf24fde22012-05-09 08:55:40 +00001327
1328//===----------------------------------------------------------------------===//
1329// C API.
1330//===----------------------------------------------------------------------===//
1331
1332LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1333 LLVMLinkerMode Mode, char **OutMessages) {
1334 std::string Messages;
1335 LLVMBool Result = Linker::LinkModules(unwrap(Dest), unwrap(Src),
1336 Mode, OutMessages? &Messages : 0);
1337 if (OutMessages)
1338 *OutMessages = strdup(Messages.c_str());
1339 return Result;
1340}