blob: 74cbdadd61eba980e69aa22c382beb5b8e9d5e94 [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"
Eli Bendersky58890d52013-03-19 15:26:24 +000020#include "llvm/ADT/SmallString.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000021#include "llvm/IR/Constants.h"
22#include "llvm/IR/DerivedTypes.h"
23#include "llvm/IR/Instructions.h"
24#include "llvm/IR/Module.h"
Chandler Carruth4068e1a2013-01-07 15:43:51 +000025#include "llvm/IR/TypeFinder.h"
Bill Wendlingcd7193f2012-03-22 20:28:27 +000026#include "llvm/Support/Debug.h"
Bill Wendlingcd7193f2012-03-22 20:28:27 +000027#include "llvm/Support/raw_ostream.h"
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +000028#include "llvm/Transforms/Utils/Cloning.h"
Dan Gohman05ea54e2010-08-24 18:50:07 +000029#include "llvm/Transforms/Utils/ValueMapper.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)) {
Joey Gouly2b8f6ae2013-01-10 10:49:36 +0000183 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
Chris Lattner1afcace2011-07-09 17:41:24 +0000184 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();
424
425 bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
426 bool linkGlobalProto(GlobalVariable *SrcGV);
427 bool linkFunctionProto(Function *SrcF);
428 bool linkAliasProto(GlobalAlias *SrcA);
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000429 bool linkModuleFlagsMetadata();
Chris Lattner1afcace2011-07-09 17:41:24 +0000430
431 void linkAppendingVarInit(const AppendingVarInfo &AVI);
432 void linkGlobalInits();
433 void linkFunctionBody(Function *Dst, Function *Src);
434 void linkAliasBodies();
435 void linkNamedMDNodes();
436 };
Bill Wendling601c0942012-02-28 04:01:21 +0000437}
438
Chris Lattner1afcace2011-07-09 17:41:24 +0000439/// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
Reid Spencer8bef0372007-02-04 04:29:21 +0000440/// in the symbol table. This is good for all clients except for us. Go
441/// through the trouble to force this back.
Chris Lattner1afcace2011-07-09 17:41:24 +0000442static void forceRenaming(GlobalValue *GV, StringRef Name) {
443 // If the global doesn't force its name or if it already has the right name,
444 // there is nothing for us to do.
445 if (GV->hasLocalLinkage() || GV->getName() == Name)
446 return;
447
448 Module *M = GV->getParent();
Chris Lattnerc0036282004-08-04 07:05:54 +0000449
450 // If there is a conflict, rename the conflict.
Chris Lattner1afcace2011-07-09 17:41:24 +0000451 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
Chris Lattner33f29492007-02-11 00:39:38 +0000452 GV->takeName(ConflictGV);
453 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Chris Lattner1afcace2011-07-09 17:41:24 +0000454 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
Chris Lattner33f29492007-02-11 00:39:38 +0000455 } else {
456 GV->setName(Name); // Force the name back
Reid Spenceref9b9a72007-02-05 20:47:22 +0000457 }
Reid Spenceref9b9a72007-02-05 20:47:22 +0000458}
Reid Spencer8bef0372007-02-04 04:29:21 +0000459
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000460/// copyGVAttributes - copy additional attributes (those not needed to construct
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000461/// a GlobalValue) from the SrcGV to the DestGV.
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000462static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
Duncan Sands28c3cff2008-05-26 19:58:59 +0000463 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
464 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
465 DestGV->copyAttributesFrom(SrcGV);
466 DestGV->setAlignment(Alignment);
Chris Lattner1afcace2011-07-09 17:41:24 +0000467
468 forceRenaming(DestGV, SrcGV->getName());
Chris Lattnerc0036282004-08-04 07:05:54 +0000469}
470
Rafael Espindola3ed88152012-01-05 23:02:01 +0000471static bool isLessConstraining(GlobalValue::VisibilityTypes a,
472 GlobalValue::VisibilityTypes b) {
473 if (a == GlobalValue::HiddenVisibility)
474 return false;
475 if (b == GlobalValue::HiddenVisibility)
476 return true;
477 if (a == GlobalValue::ProtectedVisibility)
478 return false;
479 if (b == GlobalValue::ProtectedVisibility)
480 return true;
481 return false;
482}
483
Chris Lattner1afcace2011-07-09 17:41:24 +0000484/// getLinkageResult - This analyzes the two global values and determines what
Chris Lattneraee38ea2004-12-03 22:18:41 +0000485/// the result will look like in the destination module. In particular, it
Rafael Espindola3ed88152012-01-05 23:02:01 +0000486/// computes the resultant linkage type and visibility, computes whether the
487/// global in the source should be copied over to the destination (replacing
488/// the existing one), and computes whether this linkage is an error or not.
Chris Lattner1afcace2011-07-09 17:41:24 +0000489bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Rafael Espindola3ed88152012-01-05 23:02:01 +0000490 GlobalValue::LinkageTypes &LT,
491 GlobalValue::VisibilityTypes &Vis,
Chris Lattner1afcace2011-07-09 17:41:24 +0000492 bool &LinkFromSrc) {
493 assert(Dest && "Must have two globals being queried");
494 assert(!Src->hasLocalLinkage() &&
Chris Lattneraee38ea2004-12-03 22:18:41 +0000495 "If Src has internal linkage, Dest shouldn't be set!");
Chris Lattner1afcace2011-07-09 17:41:24 +0000496
Peter Collingbourne88953162011-10-30 17:46:34 +0000497 bool SrcIsDeclaration = Src->isDeclaration() && !Src->isMaterializable();
Chris Lattnerf84c59d2011-07-14 20:23:05 +0000498 bool DestIsDeclaration = Dest->isDeclaration();
Chris Lattner1afcace2011-07-09 17:41:24 +0000499
500 if (SrcIsDeclaration) {
Anton Korobeynikov2b48ef02008-03-10 22:33:22 +0000501 // If Src is external or if both Src & Dest are external.. Just link the
Chris Lattneraee38ea2004-12-03 22:18:41 +0000502 // external globals, we aren't adding anything.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000503 if (Src->hasDLLImportLinkage()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000504 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
Chris Lattner1afcace2011-07-09 17:41:24 +0000505 if (DestIsDeclaration) {
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000506 LinkFromSrc = true;
507 LT = Src->getLinkage();
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000508 }
Andrew Lenharth8753c442006-12-15 17:35:32 +0000509 } else if (Dest->hasExternalWeakLinkage()) {
Duncan Sands667d4b82009-03-07 15:45:40 +0000510 // If the Dest is weak, use the source linkage.
Andrew Lenharth8753c442006-12-15 17:35:32 +0000511 LinkFromSrc = true;
512 LT = Src->getLinkage();
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000513 } else {
514 LinkFromSrc = false;
515 LT = Dest->getLinkage();
516 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000517 } else if (DestIsDeclaration && !Dest->hasDLLImportLinkage()) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000518 // If Dest is external but Src is not:
519 LinkFromSrc = true;
520 LT = Src->getLinkage();
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000521 } else if (Src->isWeakForLinker()) {
Dale Johannesenaafce772008-05-14 20:12:51 +0000522 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
523 // or DLL* linkage.
Chris Lattner266c7bb2009-04-13 05:44:34 +0000524 if (Dest->hasExternalWeakLinkage() ||
525 Dest->hasAvailableExternallyLinkage() ||
526 (Dest->hasLinkOnceLinkage() &&
527 (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000528 LinkFromSrc = true;
529 LT = Src->getLinkage();
530 } else {
531 LinkFromSrc = false;
532 LT = Dest->getLinkage();
533 }
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000534 } else if (Dest->isWeakForLinker()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000535 // At this point we know that Src has External* or DLL* linkage.
536 if (Src->hasExternalWeakLinkage()) {
537 LinkFromSrc = false;
538 LT = Dest->getLinkage();
539 } else {
540 LinkFromSrc = true;
541 LT = GlobalValue::ExternalLinkage;
542 }
Chris Lattneraee38ea2004-12-03 22:18:41 +0000543 } else {
Chris Lattner1afcace2011-07-09 17:41:24 +0000544 assert((Dest->hasExternalLinkage() || Dest->hasDLLImportLinkage() ||
545 Dest->hasDLLExportLinkage() || Dest->hasExternalWeakLinkage()) &&
546 (Src->hasExternalLinkage() || Src->hasDLLImportLinkage() ||
547 Src->hasDLLExportLinkage() || Src->hasExternalWeakLinkage()) &&
Chris Lattneraee38ea2004-12-03 22:18:41 +0000548 "Unexpected linkage type!");
Chris Lattner1afcace2011-07-09 17:41:24 +0000549 return emitError("Linking globals named '" + Src->getName() +
Chris Lattneraee38ea2004-12-03 22:18:41 +0000550 "': symbol multiply defined!");
551 }
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +0000552
Rafael Espindola3ed88152012-01-05 23:02:01 +0000553 // Compute the visibility. We follow the rules in the System V Application
554 // Binary Interface.
555 Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
556 Dest->getVisibility() : Src->getVisibility();
Chris Lattneraee38ea2004-12-03 22:18:41 +0000557 return false;
558}
Chris Lattner5c377c52001-10-14 23:29:15 +0000559
Chris Lattner1afcace2011-07-09 17:41:24 +0000560/// computeTypeMapping - Loop over all of the linked values to compute type
561/// mappings. For example, if we link "extern Foo *x" and "Foo *x = NULL", then
562/// we have two struct types 'Foo' but one got renamed when the module was
563/// loaded into the same LLVMContext.
564void ModuleLinker::computeTypeMapping() {
565 // Incorporate globals.
566 for (Module::global_iterator I = SrcM->global_begin(),
567 E = SrcM->global_end(); I != E; ++I) {
568 GlobalValue *DGV = getLinkedToGlobal(I);
569 if (DGV == 0) continue;
570
571 if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
572 TypeMap.addTypeMapping(DGV->getType(), I->getType());
573 continue;
574 }
575
576 // Unify the element type of appending arrays.
577 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
578 ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
579 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
Devang Patelab67e702009-08-11 18:01:24 +0000580 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000581
582 // Incorporate functions.
583 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
584 if (GlobalValue *DGV = getLinkedToGlobal(I))
585 TypeMap.addTypeMapping(DGV->getType(), I->getType());
586 }
Bill Wendlingc68d1272012-02-27 22:34:19 +0000587
Bill Wendling601c0942012-02-28 04:01:21 +0000588 // Incorporate types by name, scanning all the types in the source module.
589 // At this point, the destination module may have a type "%foo = { i32 }" for
Bill Wendling348e5e72012-02-27 23:48:30 +0000590 // example. When the source module got loaded into the same LLVMContext, if
591 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
Bill Wendling573e9732012-08-03 00:30:35 +0000592 TypeFinder SrcStructTypes;
593 SrcStructTypes.run(*SrcM, true);
Bill Wendling348e5e72012-02-27 23:48:30 +0000594 SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
595 SrcStructTypes.end());
Bill Wendlinga20689f2012-03-23 23:17:38 +0000596
Bill Wendling573e9732012-08-03 00:30:35 +0000597 TypeFinder DstStructTypes;
598 DstStructTypes.run(*DstM, true);
Bill Wendlinga20689f2012-03-23 23:17:38 +0000599 SmallPtrSet<StructType*, 32> DstStructTypesSet(DstStructTypes.begin(),
600 DstStructTypes.end());
601
Bill Wendling348e5e72012-02-27 23:48:30 +0000602 for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
603 StructType *ST = SrcStructTypes[i];
604 if (!ST->hasName()) continue;
605
606 // Check to see if there is a dot in the name followed by a digit.
Bill Wendling601c0942012-02-28 04:01:21 +0000607 size_t DotPos = ST->getName().rfind('.');
608 if (DotPos == 0 || DotPos == StringRef::npos ||
Guy Benyei87d0b9e2013-02-12 21:21:59 +0000609 ST->getName().back() == '.' ||
610 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
Bill Wendling601c0942012-02-28 04:01:21 +0000611 continue;
Bill Wendling348e5e72012-02-27 23:48:30 +0000612
613 // Check to see if the destination module has a struct with the prefix name.
Bill Wendling601c0942012-02-28 04:01:21 +0000614 if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
Bill Wendlinga20689f2012-03-23 23:17:38 +0000615 // Don't use it if this actually came from the source module. They're in
616 // the same LLVMContext after all. Also don't use it unless the type is
617 // actually used in the destination module. This can happen in situations
618 // like this:
619 //
620 // Module A Module B
621 // -------- --------
622 // %Z = type { %A } %B = type { %C.1 }
623 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
624 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
625 // %C = type { i8* } %B.3 = type { %C.1 }
626 //
627 // When we link Module B with Module A, the '%B' in Module B is
628 // used. However, that would then use '%C.1'. But when we process '%C.1',
629 // we prefer to take the '%C' version. So we are then left with both
630 // '%C.1' and '%C' being used for the same types. This leads to some
631 // variables using one type and some using the other.
632 if (!SrcStructTypesSet.count(DST) && DstStructTypesSet.count(DST))
Bill Wendling348e5e72012-02-27 23:48:30 +0000633 TypeMap.addTypeMapping(DST, ST);
634 }
635
Chris Lattner1afcace2011-07-09 17:41:24 +0000636 // Don't bother incorporating aliases, they aren't generally typed well.
Bill Wendling601c0942012-02-28 04:01:21 +0000637
Chris Lattner1afcace2011-07-09 17:41:24 +0000638 // Now that we have discovered all of the type equivalences, get a body for
639 // any 'opaque' types in the dest module that are now resolved.
640 TypeMap.linkDefinedTypeBodies();
Devang Patelab67e702009-08-11 18:01:24 +0000641}
642
Chris Lattner1afcace2011-07-09 17:41:24 +0000643/// linkAppendingVarProto - If there were any appending global variables, link
644/// them together now. Return true on error.
645bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
646 GlobalVariable *SrcGV) {
Bill Wendling601c0942012-02-28 04:01:21 +0000647
Chris Lattner1afcace2011-07-09 17:41:24 +0000648 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
649 return emitError("Linking globals named '" + SrcGV->getName() +
650 "': can only link appending global with another appending global!");
651
652 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
653 ArrayType *SrcTy =
654 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
655 Type *EltTy = DstTy->getElementType();
656
657 // Check to see that they two arrays agree on type.
658 if (EltTy != SrcTy->getElementType())
659 return emitError("Appending variables with different element types!");
660 if (DstGV->isConstant() != SrcGV->isConstant())
661 return emitError("Appending variables linked with different const'ness!");
662
663 if (DstGV->getAlignment() != SrcGV->getAlignment())
664 return emitError(
665 "Appending variables with different alignment need to be linked!");
666
667 if (DstGV->getVisibility() != SrcGV->getVisibility())
668 return emitError(
669 "Appending variables with different visibility need to be linked!");
670
671 if (DstGV->getSection() != SrcGV->getSection())
672 return emitError(
673 "Appending variables with different section name need to be linked!");
674
675 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
676 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
677
678 // Create the new global variable.
679 GlobalVariable *NG =
680 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
681 DstGV->getLinkage(), /*init*/0, /*name*/"", DstGV,
Hans Wennborgce718ff2012-06-23 11:37:03 +0000682 DstGV->getThreadLocalMode(),
Chris Lattner1afcace2011-07-09 17:41:24 +0000683 DstGV->getType()->getAddressSpace());
684
685 // Propagate alignment, visibility and section info.
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000686 copyGVAttributes(NG, DstGV);
Chris Lattner1afcace2011-07-09 17:41:24 +0000687
688 AppendingVarInfo AVI;
689 AVI.NewGV = NG;
690 AVI.DstInit = DstGV->getInitializer();
691 AVI.SrcInit = SrcGV->getInitializer();
692 AppendingVars.push_back(AVI);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000693
Chris Lattner1afcace2011-07-09 17:41:24 +0000694 // Replace any uses of the two global variables with uses of the new
695 // global.
696 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000697
Chris Lattner1afcace2011-07-09 17:41:24 +0000698 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
699 DstGV->eraseFromParent();
700
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000701 // Track the source variable so we don't try to link it.
702 DoNotLinkFromSource.insert(SrcGV);
703
Chris Lattner1afcace2011-07-09 17:41:24 +0000704 return false;
705}
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000706
Chris Lattner1afcace2011-07-09 17:41:24 +0000707/// linkGlobalProto - Loop through the global variables in the src module and
708/// merge them into the dest module.
709bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
710 GlobalValue *DGV = getLinkedToGlobal(SGV);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000711 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000712
Chris Lattner1afcace2011-07-09 17:41:24 +0000713 if (DGV) {
714 // Concatenation of appending linkage variables is magic and handled later.
715 if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
716 return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
717
718 // Determine whether linkage of these two globals follows the source
719 // module's definition or the destination module's definition.
Chris Lattnerb324bd72006-11-09 05:18:12 +0000720 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000721 GlobalValue::VisibilityTypes NV;
Chris Lattnerb324bd72006-11-09 05:18:12 +0000722 bool LinkFromSrc = false;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000723 if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
Chris Lattneraee38ea2004-12-03 22:18:41 +0000724 return true;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000725 NewVisibility = NV;
Chris Lattner0fec08e2003-04-21 21:07:05 +0000726
Chris Lattner1afcace2011-07-09 17:41:24 +0000727 // If we're not linking from the source, then keep the definition that we
728 // have.
729 if (!LinkFromSrc) {
730 // Special case for const propagation.
731 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
732 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
733 DGVar->setConstant(true);
734
Rafael Espindola3ed88152012-01-05 23:02:01 +0000735 // Set calculated linkage and visibility.
Chris Lattner1afcace2011-07-09 17:41:24 +0000736 DGV->setLinkage(NewLinkage);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000737 DGV->setVisibility(*NewVisibility);
738
Chris Lattner6157e382008-07-14 07:23:24 +0000739 // Make sure to remember this mapping.
Chris Lattner1afcace2011-07-09 17:41:24 +0000740 ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
741
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000742 // Track the source global so that we don't attempt to copy it over when
743 // processing global initializers.
744 DoNotLinkFromSource.insert(SGV);
745
Chris Lattner1afcace2011-07-09 17:41:24 +0000746 return false;
Chris Lattner6157e382008-07-14 07:23:24 +0000747 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000748 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000749
750 // No linking to be performed or linking from the source: simply create an
751 // identical version of the symbol over in the dest module... the
752 // initializer will be filled in later by LinkGlobalInits.
753 GlobalVariable *NewDGV =
754 new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
755 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
756 SGV->getName(), /*insertbefore*/0,
Hans Wennborgce718ff2012-06-23 11:37:03 +0000757 SGV->getThreadLocalMode(),
Chris Lattner1afcace2011-07-09 17:41:24 +0000758 SGV->getType()->getAddressSpace());
759 // Propagate alignment, visibility and section info.
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000760 copyGVAttributes(NewDGV, SGV);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000761 if (NewVisibility)
762 NewDGV->setVisibility(*NewVisibility);
Chris Lattner1afcace2011-07-09 17:41:24 +0000763
764 if (DGV) {
765 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
766 DGV->eraseFromParent();
767 }
768
769 // Make sure to remember this mapping.
770 ValueMap[SGV] = NewDGV;
Chris Lattner5c377c52001-10-14 23:29:15 +0000771 return false;
772}
773
Chris Lattner1afcace2011-07-09 17:41:24 +0000774/// linkFunctionProto - Link the function in the source module into the
775/// destination module if needed, setting up mapping information.
776bool ModuleLinker::linkFunctionProto(Function *SF) {
777 GlobalValue *DGV = getLinkedToGlobal(SF);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000778 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Chris Lattner1afcace2011-07-09 17:41:24 +0000779
780 if (DGV) {
781 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
782 bool LinkFromSrc = false;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000783 GlobalValue::VisibilityTypes NV;
784 if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
Chris Lattner1afcace2011-07-09 17:41:24 +0000785 return true;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000786 NewVisibility = NV;
787
Chris Lattner1afcace2011-07-09 17:41:24 +0000788 if (!LinkFromSrc) {
789 // Set calculated linkage
790 DGV->setLinkage(NewLinkage);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000791 DGV->setVisibility(*NewVisibility);
792
Chris Lattner1afcace2011-07-09 17:41:24 +0000793 // Make sure to remember this mapping.
794 ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
795
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000796 // Track the function from the source module so we don't attempt to remap
797 // it.
798 DoNotLinkFromSource.insert(SF);
799
Chris Lattner1afcace2011-07-09 17:41:24 +0000800 return false;
801 }
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000802 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000803
804 // If there is no linkage to be performed or we are linking from the source,
805 // bring SF over.
806 Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
807 SF->getLinkage(), SF->getName(), DstM);
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000808 copyGVAttributes(NewDF, SF);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000809 if (NewVisibility)
810 NewDF->setVisibility(*NewVisibility);
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000811
Chris Lattner1afcace2011-07-09 17:41:24 +0000812 if (DGV) {
813 // Any uses of DF need to change to NewDF, with cast.
814 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
815 DGV->eraseFromParent();
Tanya Lattner9af37a32011-11-02 00:24:56 +0000816 } else {
817 // Internal, LO_ODR, or LO linkage - stick in set to ignore and lazily link.
818 if (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
819 SF->hasAvailableExternallyLinkage()) {
820 DoNotLinkFromSource.insert(SF);
821 LazilyLinkFunctions.push_back(SF);
822 }
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000823 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000824
825 ValueMap[SF] = NewDF;
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000826 return false;
827}
828
Chris Lattner1afcace2011-07-09 17:41:24 +0000829/// LinkAliasProto - Set up prototypes for any aliases that come over from the
830/// source module.
831bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
832 GlobalValue *DGV = getLinkedToGlobal(SGA);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000833 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
834
Chris Lattner1afcace2011-07-09 17:41:24 +0000835 if (DGV) {
836 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000837 GlobalValue::VisibilityTypes NV;
Chris Lattner1afcace2011-07-09 17:41:24 +0000838 bool LinkFromSrc = false;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000839 if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
Chris Lattner1afcace2011-07-09 17:41:24 +0000840 return true;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000841 NewVisibility = NV;
842
Chris Lattner1afcace2011-07-09 17:41:24 +0000843 if (!LinkFromSrc) {
844 // Set calculated linkage.
845 DGV->setLinkage(NewLinkage);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000846 DGV->setVisibility(*NewVisibility);
847
Chris Lattner1afcace2011-07-09 17:41:24 +0000848 // Make sure to remember this mapping.
849 ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
850
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000851 // Track the alias from the source module so we don't attempt to remap it.
852 DoNotLinkFromSource.insert(SGA);
853
Chris Lattner1afcace2011-07-09 17:41:24 +0000854 return false;
855 }
856 }
857
858 // If there is no linkage to be performed or we're linking from the source,
859 // bring over SGA.
860 GlobalAlias *NewDA = new GlobalAlias(TypeMap.get(SGA->getType()),
861 SGA->getLinkage(), SGA->getName(),
862 /*aliasee*/0, DstM);
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000863 copyGVAttributes(NewDA, SGA);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000864 if (NewVisibility)
865 NewDA->setVisibility(*NewVisibility);
Chris Lattner5c377c52001-10-14 23:29:15 +0000866
Chris Lattner1afcace2011-07-09 17:41:24 +0000867 if (DGV) {
868 // Any uses of DGV need to change to NewDA, with cast.
869 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
870 DGV->eraseFromParent();
871 }
872
873 ValueMap[SGA] = NewDA;
874 return false;
875}
876
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000877static void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000878 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
879
880 for (unsigned i = 0; i != NumElements; ++i)
881 Dest.push_back(C->getAggregateElement(i));
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000882}
883
Chris Lattner1afcace2011-07-09 17:41:24 +0000884void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
885 // Merge the initializer.
886 SmallVector<Constant*, 16> Elements;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000887 getArrayElements(AVI.DstInit, Elements);
Chris Lattner1afcace2011-07-09 17:41:24 +0000888
889 Constant *SrcInit = MapValue(AVI.SrcInit, ValueMap, RF_None, &TypeMap);
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000890 getArrayElements(SrcInit, Elements);
891
Chris Lattner1afcace2011-07-09 17:41:24 +0000892 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
893 AVI.NewGV->setInitializer(ConstantArray::get(NewType, Elements));
894}
895
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000896/// linkGlobalInits - Update the initializers in the Dest module now that all
897/// globals that may be referenced are in Dest.
Chris Lattner1afcace2011-07-09 17:41:24 +0000898void ModuleLinker::linkGlobalInits() {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000899 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattner1afcace2011-07-09 17:41:24 +0000900 for (Module::const_global_iterator I = SrcM->global_begin(),
901 E = SrcM->global_end(); I != E; ++I) {
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000902
903 // Only process initialized GV's or ones not already in dest.
904 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
Chris Lattner1afcace2011-07-09 17:41:24 +0000905
906 // Grab destination global variable.
907 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
908 // Figure out what the initializer looks like in the dest module.
909 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
910 RF_None, &TypeMap));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000911 }
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000912}
Chris Lattner5c377c52001-10-14 23:29:15 +0000913
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000914/// linkFunctionBody - Copy the source function over into the dest function and
915/// fix up references to values. At this point we know that Dest is an external
916/// function, and that Src is not.
Chris Lattner1afcace2011-07-09 17:41:24 +0000917void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
918 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
Chris Lattner5c377c52001-10-14 23:29:15 +0000919
Chris Lattner0033baf2004-11-16 17:12:38 +0000920 // Go through and convert function arguments over, remembering the mapping.
Chris Lattner1afcace2011-07-09 17:41:24 +0000921 Function::arg_iterator DI = Dst->arg_begin();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000922 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
Chris Lattner69da5cf2002-10-13 20:57:00 +0000923 I != E; ++I, ++DI) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000924 DI->setName(I->getName()); // Copy the name over.
Chris Lattner5c377c52001-10-14 23:29:15 +0000925
Chris Lattner1afcace2011-07-09 17:41:24 +0000926 // Add a mapping to our mapping.
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000927 ValueMap[I] = DI;
Chris Lattner5c377c52001-10-14 23:29:15 +0000928 }
929
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000930 if (Mode == Linker::DestroySource) {
931 // Splice the body of the source function into the dest function.
932 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
933
934 // At this point, all of the instructions and values of the function are now
935 // copied over. The only problem is that they are still referencing values in
936 // the Source function as operands. Loop through all of the operands of the
937 // functions and patch them up to point to the local versions.
938 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
939 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
940 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap);
941
942 } else {
943 // Clone the body of the function into the dest function.
944 SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
Mon P Wangd24397a2011-12-23 02:18:32 +0000945 CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", NULL, &TypeMap);
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000946 }
947
Chris Lattner0033baf2004-11-16 17:12:38 +0000948 // There is no need to map the arguments anymore.
Chris Lattner11273152006-06-16 01:24:04 +0000949 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
950 I != E; ++I)
Reid Spenceref9b9a72007-02-05 20:47:22 +0000951 ValueMap.erase(I);
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000952
Chris Lattner5c377c52001-10-14 23:29:15 +0000953}
954
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000955/// linkAliasBodies - Insert all of the aliases in Src into the Dest module.
Chris Lattner1afcace2011-07-09 17:41:24 +0000956void ModuleLinker::linkAliasBodies() {
957 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000958 I != E; ++I) {
959 if (DoNotLinkFromSource.count(I))
960 continue;
Chris Lattner1afcace2011-07-09 17:41:24 +0000961 if (Constant *Aliasee = I->getAliasee()) {
962 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
963 DA->setAliasee(MapValue(Aliasee, ValueMap, RF_None, &TypeMap));
David Chisnall34722462010-01-09 16:27:31 +0000964 }
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000965 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000966}
Anton Korobeynikov9f2ee702008-03-05 23:21:39 +0000967
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000968/// linkNamedMDNodes - Insert all of the named MDNodes in Src into the Dest
Chris Lattner1afcace2011-07-09 17:41:24 +0000969/// module.
970void ModuleLinker::linkNamedMDNodes() {
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000971 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
Chris Lattner1afcace2011-07-09 17:41:24 +0000972 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
973 E = SrcM->named_metadata_end(); I != E; ++I) {
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000974 // Don't link module flags here. Do them separately.
975 if (&*I == SrcModFlags) continue;
Chris Lattner1afcace2011-07-09 17:41:24 +0000976 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
977 // Add Src elements into Dest node.
978 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
979 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
980 RF_None, &TypeMap));
981 }
982}
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000983
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000984/// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest
985/// module.
986bool ModuleLinker::linkModuleFlagsMetadata() {
Daniel Dunbar1e081652013-01-16 18:39:23 +0000987 // If the source module has no module flags, we are done.
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000988 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
989 if (!SrcModFlags) return false;
990
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000991 // If the destination module doesn't have module flags yet, then just copy
992 // over the source module's flags.
Daniel Dunbar1e081652013-01-16 18:39:23 +0000993 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000994 if (DstModFlags->getNumOperands() == 0) {
995 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
996 DstModFlags->addOperand(SrcModFlags->getOperand(I));
997
998 return false;
999 }
1000
Daniel Dunbar1e081652013-01-16 18:39:23 +00001001 // First build a map of the existing module flags and requirements.
1002 DenseMap<MDString*, MDNode*> Flags;
1003 SmallSetVector<MDNode*, 16> Requirements;
1004 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1005 MDNode *Op = DstModFlags->getOperand(I);
1006 ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1007 MDString *ID = cast<MDString>(Op->getOperand(1));
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001008
Daniel Dunbar1e081652013-01-16 18:39:23 +00001009 if (Behavior->getZExtValue() == Module::Require) {
1010 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1011 } else {
1012 Flags[ID] = Op;
1013 }
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001014 }
1015
Daniel Dunbar1e081652013-01-16 18:39:23 +00001016 // Merge in the flags from the source module, and also collect its set of
1017 // requirements.
1018 bool HasErr = false;
1019 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1020 MDNode *SrcOp = SrcModFlags->getOperand(I);
1021 ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1022 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1023 MDNode *DstOp = Flags.lookup(ID);
1024 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001025
Daniel Dunbar1e081652013-01-16 18:39:23 +00001026 // If this is a requirement, add it and continue.
1027 if (SrcBehaviorValue == Module::Require) {
1028 // If the destination module does not already have this requirement, add
1029 // it.
1030 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1031 DstModFlags->addOperand(SrcOp);
1032 }
1033 continue;
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001034 }
1035
Daniel Dunbar1e081652013-01-16 18:39:23 +00001036 // If there is no existing flag with this ID, just add it.
1037 if (!DstOp) {
1038 Flags[ID] = SrcOp;
1039 DstModFlags->addOperand(SrcOp);
1040 continue;
1041 }
1042
1043 // Otherwise, perform a merge.
1044 ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1045 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1046
1047 // If either flag has override behavior, handle it first.
1048 if (DstBehaviorValue == Module::Override) {
1049 // Diagnose inconsistent flags which both have override behavior.
1050 if (SrcBehaviorValue == Module::Override &&
1051 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1052 HasErr |= emitError("linking module flags '" + ID->getString() +
1053 "': IDs have conflicting override values");
1054 }
1055 continue;
1056 } else if (SrcBehaviorValue == Module::Override) {
1057 // Update the destination flag to that of the source.
1058 DstOp->replaceOperandWith(0, SrcBehavior);
1059 DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1060 continue;
1061 }
1062
1063 // Diagnose inconsistent merge behavior types.
1064 if (SrcBehaviorValue != DstBehaviorValue) {
1065 HasErr |= emitError("linking module flags '" + ID->getString() +
1066 "': IDs have conflicting behaviors");
1067 continue;
1068 }
1069
1070 // Perform the merge for standard behavior types.
1071 switch (SrcBehaviorValue) {
1072 case Module::Require:
1073 case Module::Override: assert(0 && "not possible"); break;
1074 case Module::Error: {
1075 // Emit an error if the values differ.
1076 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1077 HasErr |= emitError("linking module flags '" + ID->getString() +
1078 "': IDs have conflicting values");
1079 }
1080 continue;
1081 }
1082 case Module::Warning: {
1083 // Emit a warning if the values differ.
1084 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1085 errs() << "WARNING: linking module flags '" << ID->getString()
1086 << "': IDs have conflicting values";
1087 }
1088 continue;
1089 }
Daniel Dunbar5db391c2013-01-16 21:38:56 +00001090 case Module::Append: {
1091 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1092 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1093 unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1094 Value **VP, **Values = VP = new Value*[NumOps];
1095 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1096 *VP = DstValue->getOperand(i);
1097 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1098 *VP = SrcValue->getOperand(i);
1099 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1100 ArrayRef<Value*>(Values,
1101 NumOps)));
1102 delete[] Values;
1103 break;
1104 }
1105 case Module::AppendUnique: {
1106 SmallSetVector<Value*, 16> Elts;
1107 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1108 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1109 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1110 Elts.insert(DstValue->getOperand(i));
1111 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1112 Elts.insert(SrcValue->getOperand(i));
1113 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1114 ArrayRef<Value*>(Elts.begin(),
1115 Elts.end())));
1116 break;
1117 }
Daniel Dunbar1e081652013-01-16 18:39:23 +00001118 }
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001119 }
1120
Daniel Dunbar1e081652013-01-16 18:39:23 +00001121 // Check all of the requirements.
1122 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1123 MDNode *Requirement = Requirements[I];
1124 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1125 Value *ReqValue = Requirement->getOperand(1);
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001126
Daniel Dunbar1e081652013-01-16 18:39:23 +00001127 MDNode *Op = Flags[Flag];
1128 if (!Op || Op->getOperand(2) != ReqValue) {
1129 HasErr |= emitError("linking module flags '" + Flag->getString() +
1130 "': does not have the required value");
1131 continue;
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001132 }
1133 }
1134
1135 return HasErr;
1136}
Chris Lattner1afcace2011-07-09 17:41:24 +00001137
1138bool ModuleLinker::run() {
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001139 assert(DstM && "Null destination module");
1140 assert(SrcM && "Null source module");
Chris Lattner1afcace2011-07-09 17:41:24 +00001141
1142 // Inherit the target data from the source module if the destination module
1143 // doesn't have one already.
1144 if (DstM->getDataLayout().empty() && !SrcM->getDataLayout().empty())
1145 DstM->setDataLayout(SrcM->getDataLayout());
1146
1147 // Copy the target triple from the source to dest if the dest's is empty.
1148 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1149 DstM->setTargetTriple(SrcM->getTargetTriple());
1150
1151 if (!SrcM->getDataLayout().empty() && !DstM->getDataLayout().empty() &&
1152 SrcM->getDataLayout() != DstM->getDataLayout())
1153 errs() << "WARNING: Linking two modules of different data layouts!\n";
1154 if (!SrcM->getTargetTriple().empty() &&
1155 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1156 errs() << "WARNING: Linking two modules of different target triples: ";
1157 if (!SrcM->getModuleIdentifier().empty())
1158 errs() << SrcM->getModuleIdentifier() << ": ";
1159 errs() << "'" << SrcM->getTargetTriple() << "' and '"
1160 << DstM->getTargetTriple() << "'\n";
1161 }
1162
1163 // Append the module inline asm string.
1164 if (!SrcM->getModuleInlineAsm().empty()) {
1165 if (DstM->getModuleInlineAsm().empty())
1166 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1167 else
1168 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1169 SrcM->getModuleInlineAsm());
1170 }
1171
Chris Lattner1afcace2011-07-09 17:41:24 +00001172 // Loop over all of the linked values to compute type mappings.
1173 computeTypeMapping();
1174
1175 // Insert all of the globals in src into the DstM module... without linking
1176 // initializers (which could refer to functions not yet mapped over).
1177 for (Module::global_iterator I = SrcM->global_begin(),
1178 E = SrcM->global_end(); I != E; ++I)
1179 if (linkGlobalProto(I))
1180 return true;
1181
1182 // Link the functions together between the two modules, without doing function
1183 // bodies... this just adds external function prototypes to the DstM
1184 // function... We do this so that when we begin processing function bodies,
1185 // all of the global values that may be referenced are available in our
1186 // ValueMap.
1187 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1188 if (linkFunctionProto(I))
1189 return true;
1190
1191 // If there were any aliases, link them now.
1192 for (Module::alias_iterator I = SrcM->alias_begin(),
1193 E = SrcM->alias_end(); I != E; ++I)
1194 if (linkAliasProto(I))
1195 return true;
1196
1197 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1198 linkAppendingVarInit(AppendingVars[i]);
1199
1200 // Update the initializers in the DstM module now that all globals that may
1201 // be referenced are in DstM.
1202 linkGlobalInits();
1203
1204 // Link in the function bodies that are defined in the source module into
1205 // DstM.
1206 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
Tanya Lattner2b28a742011-10-14 22:17:46 +00001207 // Skip if not linking from source.
1208 if (DoNotLinkFromSource.count(SF)) continue;
1209
1210 // Skip if no body (function is external) or materialize.
1211 if (SF->isDeclaration()) {
1212 if (!SF->isMaterializable())
1213 continue;
1214 if (SF->Materialize(&ErrorMsg))
1215 return true;
1216 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001217
1218 linkFunctionBody(cast<Function>(ValueMap[SF]), SF);
Bill Wendling208b6f62012-03-23 07:22:49 +00001219 SF->Dematerialize();
Chris Lattner1afcace2011-07-09 17:41:24 +00001220 }
1221
1222 // Resolve all uses of aliases with aliasees.
1223 linkAliasBodies();
1224
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001225 // Remap all of the named MDNodes in Src into the DstM module. We do this
Devang Patel211da8f2011-08-04 19:44:28 +00001226 // after linking GlobalValues so that MDNodes that reference GlobalValues
1227 // are properly remapped.
1228 linkNamedMDNodes();
1229
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001230 // Merge the module flags into the DstM module.
1231 if (linkModuleFlagsMetadata())
1232 return true;
1233
Tanya Lattner9af37a32011-11-02 00:24:56 +00001234 // Process vector of lazily linked in functions.
1235 bool LinkedInAnyFunctions;
1236 do {
1237 LinkedInAnyFunctions = false;
1238
1239 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1240 E = LazilyLinkFunctions.end(); I != E; ++I) {
1241 if (!*I)
1242 continue;
1243
1244 Function *SF = *I;
1245 Function *DF = cast<Function>(ValueMap[SF]);
1246
1247 if (!DF->use_empty()) {
1248
1249 // Materialize if necessary.
1250 if (SF->isDeclaration()) {
1251 if (!SF->isMaterializable())
1252 continue;
1253 if (SF->Materialize(&ErrorMsg))
1254 return true;
1255 }
1256
1257 // Link in function body.
1258 linkFunctionBody(DF, SF);
Bill Wendling208b6f62012-03-23 07:22:49 +00001259 SF->Dematerialize();
1260
Tanya Lattner9af37a32011-11-02 00:24:56 +00001261 // "Remove" from vector by setting the element to 0.
1262 *I = 0;
1263
1264 // Set flag to indicate we may have more functions to lazily link in
1265 // since we linked in a function.
1266 LinkedInAnyFunctions = true;
1267 }
1268 }
1269 } while (LinkedInAnyFunctions);
1270
1271 // Remove any prototypes of functions that were not actually linked in.
1272 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1273 E = LazilyLinkFunctions.end(); I != E; ++I) {
1274 if (!*I)
1275 continue;
1276
1277 Function *SF = *I;
1278 Function *DF = cast<Function>(ValueMap[SF]);
1279 if (DF->use_empty())
1280 DF->eraseFromParent();
1281 }
1282
Chris Lattner1afcace2011-07-09 17:41:24 +00001283 // Now that all of the types from the source are used, resolve any structs
1284 // copied over to the dest that didn't exist there.
1285 TypeMap.linkDefinedTypeBodies();
1286
Anton Korobeynikov9f2ee702008-03-05 23:21:39 +00001287 return false;
1288}
Chris Lattner52f7e902001-10-13 07:03:50 +00001289
Chris Lattner1afcace2011-07-09 17:41:24 +00001290//===----------------------------------------------------------------------===//
1291// LinkModules entrypoint.
1292//===----------------------------------------------------------------------===//
1293
Bill Wendlingcd7193f2012-03-22 20:28:27 +00001294/// LinkModules - This function links two modules together, with the resulting
Eli Benderskyd25c05e2013-03-08 22:29:44 +00001295/// Dest module modified to be the composite of the two input modules. If an
Bill Wendlingcd7193f2012-03-22 20:28:27 +00001296/// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1297/// the problem. Upon failure, the Dest module could be in a modified state,
1298/// and shouldn't be relied on to be consistent.
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +00001299bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode,
1300 std::string *ErrorMsg) {
1301 ModuleLinker TheLinker(Dest, Src, Mode);
Chris Lattner1afcace2011-07-09 17:41:24 +00001302 if (TheLinker.run()) {
1303 if (ErrorMsg) *ErrorMsg = TheLinker.ErrorMsg;
Reid Spencer619f0242007-02-04 04:43:17 +00001304 return true;
Chris Lattner5a837de2004-08-04 07:44:58 +00001305 }
Bill Wendlinga20689f2012-03-23 23:17:38 +00001306
Chris Lattner52f7e902001-10-13 07:03:50 +00001307 return false;
1308}
Bill Wendlingf24fde22012-05-09 08:55:40 +00001309
1310//===----------------------------------------------------------------------===//
1311// C API.
1312//===----------------------------------------------------------------------===//
1313
1314LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1315 LLVMLinkerMode Mode, char **OutMessages) {
1316 std::string Messages;
1317 LLVMBool Result = Linker::LinkModules(unwrap(Dest), unwrap(Src),
1318 Mode, OutMessages? &Messages : 0);
1319 if (OutMessages)
1320 *OutMessages = strdup(Messages.c_str());
1321 return Result;
1322}