blob: 45f2d4e03a19934fc5a58eafbbfe24764a46ad9c [file] [log] [blame]
Mikhail Glushenkov59a5afa2009-03-03 10:04:23 +00001//===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
Misha Brukman10468d82005-04-21 22:55:34 +00002//
Reid Spencer361e5132004-11-12 20:37:43 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Brukman10468d82005-04-21 22:55:34 +00007//
Reid Spencer361e5132004-11-12 20:37:43 +00008//===----------------------------------------------------------------------===//
9//
10// This file implements the LLVM module linker.
11//
Reid Spencer361e5132004-11-12 20:37:43 +000012//===----------------------------------------------------------------------===//
13
Chandler Carruth6cc07df2014-03-06 03:42:23 +000014#include "llvm/Linker/Linker.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm-c/Linker.h"
Rafael Espindola23f8d642012-01-05 23:02:01 +000016#include "llvm/ADT/Optional.h"
Bill Wendling66f02412012-02-11 11:38:06 +000017#include "llvm/ADT/SetVector.h"
Eli Bendersky0f7fd362013-03-19 15:26:24 +000018#include "llvm/ADT/SmallString.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000019#include "llvm/IR/Constants.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000020#include "llvm/IR/Module.h"
Chandler Carruthdcb603f2013-01-07 15:43:51 +000021#include "llvm/IR/TypeFinder.h"
Eli Benderskye17f3702014-02-06 18:01:56 +000022#include "llvm/Support/CommandLine.h"
Bill Wendlingb6af2f32012-03-22 20:28:27 +000023#include "llvm/Support/Debug.h"
Bill Wendlingb6af2f32012-03-22 20:28:27 +000024#include "llvm/Support/raw_ostream.h"
Tanya Lattnercbb91402011-10-11 00:24:54 +000025#include "llvm/Transforms/Utils/Cloning.h"
Will Dietz981af002013-10-12 00:55:57 +000026#include <cctype>
Reid Spencer361e5132004-11-12 20:37:43 +000027using namespace llvm;
28
Eli Benderskye17f3702014-02-06 18:01:56 +000029
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000030//===----------------------------------------------------------------------===//
31// TypeMap implementation.
32//===----------------------------------------------------------------------===//
Reid Spencer361e5132004-11-12 20:37:43 +000033
Chris Lattnereee6f992008-06-16 21:00:18 +000034namespace {
Rafael Espindolaaa9918a2013-05-04 05:05:18 +000035 typedef SmallPtrSet<StructType*, 32> TypeSet;
36
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000037class TypeMapTy : public ValueMapTypeRemapper {
38 /// MappedTypes - This is a mapping from a source type to a destination type
39 /// to use.
40 DenseMap<Type*, Type*> MappedTypes;
Mikhail Glushenkov766d4892009-03-03 07:22:23 +000041
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000042 /// SpeculativeTypes - When checking to see if two subgraphs are isomorphic,
43 /// we speculatively add types to MappedTypes, but keep track of them here in
44 /// case we need to roll back.
45 SmallVector<Type*, 16> SpeculativeTypes;
Rafael Espindolaed6dc372014-05-09 14:39:25 +000046
Chris Lattner5e3bd972011-12-20 00:03:52 +000047 /// SrcDefinitionsToResolve - This is a list of non-opaque structs in the
48 /// source module that are mapped to an opaque struct in the destination
49 /// module.
50 SmallVector<StructType*, 16> SrcDefinitionsToResolve;
Rafael Espindolaed6dc372014-05-09 14:39:25 +000051
Chris Lattner5e3bd972011-12-20 00:03:52 +000052 /// DstResolvedOpaqueTypes - This is the set of opaque types in the
53 /// destination modules who are getting a body from the source module.
54 SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
Bill Wendling8c2cc412012-03-22 20:30:41 +000055
Chris Lattner56cdea62008-06-16 23:06:51 +000056public:
Rafael Espindolaaa9918a2013-05-04 05:05:18 +000057 TypeMapTy(TypeSet &Set) : DstStructTypesSet(Set) {}
58
59 TypeSet &DstStructTypesSet;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000060 /// addTypeMapping - Indicate that the specified type in the destination
61 /// module is conceptually equivalent to the specified type in the source
62 /// module.
63 void addTypeMapping(Type *DstTy, Type *SrcTy);
64
65 /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
66 /// module from a type definition in the source module.
67 void linkDefinedTypeBodies();
Rafael Espindolaed6dc372014-05-09 14:39:25 +000068
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000069 /// get - Return the mapped type to use for the specified input type from the
70 /// source module.
71 Type *get(Type *SrcTy);
72
73 FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*)T));}
74
Bill Wendlingb6af2f32012-03-22 20:28:27 +000075 /// dump - Dump out the type map for debugging purposes.
76 void dump() const {
77 for (DenseMap<Type*, Type*>::const_iterator
78 I = MappedTypes.begin(), E = MappedTypes.end(); I != E; ++I) {
79 dbgs() << "TypeMap: ";
80 I->first->dump();
81 dbgs() << " => ";
82 I->second->dump();
83 dbgs() << '\n';
84 }
85 }
Bill Wendlingb6af2f32012-03-22 20:28:27 +000086
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000087private:
88 Type *getImpl(Type *T);
89 /// remapType - Implement the ValueMapTypeRemapper interface.
Craig Topper85482992014-03-05 07:52:44 +000090 Type *remapType(Type *SrcTy) override {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000091 return get(SrcTy);
Chris Lattnereee6f992008-06-16 21:00:18 +000092 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +000093
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000094 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
Chris Lattnereee6f992008-06-16 21:00:18 +000095};
96}
97
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000098void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
99 Type *&Entry = MappedTypes[SrcTy];
100 if (Entry) return;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000101
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000102 if (DstTy == SrcTy) {
103 Entry = DstTy;
104 return;
105 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000106
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000107 // Check to see if these types are recursively isomorphic and establish a
108 // mapping between them if so.
Bill Wendlingd48b7782012-02-28 04:01:21 +0000109 if (!areTypesIsomorphic(DstTy, SrcTy)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000110 // Oops, they aren't isomorphic. Just discard this request by rolling out
111 // any speculative mappings we've established.
112 for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i)
113 MappedTypes.erase(SpeculativeTypes[i]);
Bill Wendlingd48b7782012-02-28 04:01:21 +0000114 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000115 SpeculativeTypes.clear();
116}
Chris Lattnereee6f992008-06-16 21:00:18 +0000117
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000118/// areTypesIsomorphic - Recursively walk this pair of types, returning true
119/// if they are isomorphic, false if they are not.
120bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
121 // Two types with differing kinds are clearly not isomorphic.
122 if (DstTy->getTypeID() != SrcTy->getTypeID()) return false;
Misha Brukman10468d82005-04-21 22:55:34 +0000123
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000124 // If we have an entry in the MappedTypes table, then we have our answer.
125 Type *&Entry = MappedTypes[SrcTy];
126 if (Entry)
127 return Entry == DstTy;
Misha Brukman10468d82005-04-21 22:55:34 +0000128
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000129 // Two identical types are clearly isomorphic. Remember this
130 // non-speculatively.
131 if (DstTy == SrcTy) {
132 Entry = DstTy;
Chris Lattnerfe677e92008-06-16 20:03:01 +0000133 return true;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000134 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000135
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000136 // Okay, we have two types with identical kinds that we haven't seen before.
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000137
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000138 // If this is an opaque struct type, special case it.
139 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
140 // Mapping an opaque type to any struct, just keep the dest struct.
141 if (SSTy->isOpaque()) {
142 Entry = DstTy;
143 SpeculativeTypes.push_back(SrcTy);
Reid Spencer361e5132004-11-12 20:37:43 +0000144 return true;
Chris Lattner9be15892008-06-16 21:17:12 +0000145 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000146
Chris Lattner5e3bd972011-12-20 00:03:52 +0000147 // Mapping a non-opaque source type to an opaque dest. If this is the first
148 // type that we're mapping onto this destination type then we succeed. Keep
149 // the dest, but fill it in later. This doesn't need to be speculative. If
150 // this is the second (different) type that we're trying to map onto the
151 // same opaque type then we fail.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000152 if (cast<StructType>(DstTy)->isOpaque()) {
Chris Lattner5e3bd972011-12-20 00:03:52 +0000153 // We can only map one source type onto the opaque destination type.
154 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)))
155 return false;
156 SrcDefinitionsToResolve.push_back(SSTy);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000157 Entry = DstTy;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000158 return true;
159 }
160 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000161
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000162 // If the number of subtypes disagree between the two types, then we fail.
163 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
Reid Spencer361e5132004-11-12 20:37:43 +0000164 return false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000165
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000166 // Fail if any of the extra properties (e.g. array size) of the type disagree.
167 if (isa<IntegerType>(DstTy))
168 return false; // bitwidth disagrees.
169 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
170 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
171 return false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000172
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000173 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
174 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
175 return false;
176 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
177 StructType *SSTy = cast<StructType>(SrcTy);
Chris Lattner44f7ab42011-08-12 18:07:26 +0000178 if (DSTy->isLiteral() != SSTy->isLiteral() ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000179 DSTy->isPacked() != SSTy->isPacked())
180 return false;
181 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
182 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
183 return false;
184 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
Joey Gouly5fad3e92013-01-10 10:49:36 +0000185 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000186 return false;
Reid Spencer361e5132004-11-12 20:37:43 +0000187 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000188
189 // Otherwise, we speculate that these two types will line up and recursively
190 // check the subelements.
191 Entry = DstTy;
192 SpeculativeTypes.push_back(SrcTy);
193
Bill Wendlingd48b7782012-02-28 04:01:21 +0000194 for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i)
195 if (!areTypesIsomorphic(DstTy->getContainedType(i),
196 SrcTy->getContainedType(i)))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000197 return false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000198
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000199 // If everything seems to have lined up, then everything is great.
200 return true;
201}
202
203/// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
204/// module from a type definition in the source module.
205void TypeMapTy::linkDefinedTypeBodies() {
206 SmallVector<Type*, 16> Elements;
207 SmallString<16> TmpName;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000208
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000209 // Note that processing entries in this loop (calling 'get') can add new
Chris Lattner5e3bd972011-12-20 00:03:52 +0000210 // entries to the SrcDefinitionsToResolve vector.
211 while (!SrcDefinitionsToResolve.empty()) {
212 StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000213 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000214
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000215 // TypeMap is a many-to-one mapping, if there were multiple types that
216 // provide a body for DstSTy then previous iterations of this loop may have
217 // already handled it. Just ignore this case.
218 if (!DstSTy->isOpaque()) continue;
219 assert(!SrcSTy->isOpaque() && "Not resolving a definition?");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000220
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000221 // Map the body of the source type over to a new body for the dest type.
222 Elements.resize(SrcSTy->getNumElements());
223 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
224 Elements[i] = getImpl(SrcSTy->getElementType(i));
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000225
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000226 DstSTy->setBody(Elements, SrcSTy->isPacked());
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000227
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000228 // If DstSTy has no name or has a longer name than STy, then viciously steal
229 // STy's name.
230 if (!SrcSTy->hasName()) continue;
231 StringRef SrcName = SrcSTy->getName();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000232
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000233 if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
234 TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
235 SrcSTy->setName("");
236 DstSTy->setName(TmpName.str());
237 TmpName.clear();
238 }
239 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000240
Chris Lattner5e3bd972011-12-20 00:03:52 +0000241 DstResolvedOpaqueTypes.clear();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000242}
243
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000244/// get - Return the mapped type to use for the specified input type from the
245/// source module.
246Type *TypeMapTy::get(Type *Ty) {
247 Type *Result = getImpl(Ty);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000248
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000249 // If this caused a reference to any struct type, resolve it before returning.
Chris Lattner5e3bd972011-12-20 00:03:52 +0000250 if (!SrcDefinitionsToResolve.empty())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000251 linkDefinedTypeBodies();
252 return Result;
253}
254
255/// getImpl - This is the recursive version of get().
256Type *TypeMapTy::getImpl(Type *Ty) {
257 // If we already have an entry for this type, return it.
258 Type **Entry = &MappedTypes[Ty];
259 if (*Entry) return *Entry;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000260
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000261 // If this is not a named struct type, then just map all of the elements and
262 // then rebuild the type from inside out.
Chris Lattner44f7ab42011-08-12 18:07:26 +0000263 if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000264 // If there are no element types to map, then the type is itself. This is
265 // true for the anonymous {} struct, things like 'float', integers, etc.
266 if (Ty->getNumContainedTypes() == 0)
267 return *Entry = Ty;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000268
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000269 // Remap all of the elements, keeping track of whether any of them change.
270 bool AnyChange = false;
271 SmallVector<Type*, 4> ElementTypes;
272 ElementTypes.resize(Ty->getNumContainedTypes());
273 for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) {
274 ElementTypes[i] = getImpl(Ty->getContainedType(i));
275 AnyChange |= ElementTypes[i] != Ty->getContainedType(i);
276 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000277
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000278 // If we found our type while recursively processing stuff, just use it.
279 Entry = &MappedTypes[Ty];
280 if (*Entry) return *Entry;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000281
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000282 // If all of the element types mapped directly over, then the type is usable
283 // as-is.
284 if (!AnyChange)
285 return *Entry = Ty;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000286
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000287 // Otherwise, rebuild a modified type.
288 switch (Ty->getTypeID()) {
Craig Toppera2886c22012-02-07 05:05:23 +0000289 default: llvm_unreachable("unknown derived type to remap");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000290 case Type::ArrayTyID:
291 return *Entry = ArrayType::get(ElementTypes[0],
292 cast<ArrayType>(Ty)->getNumElements());
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000293 case Type::VectorTyID:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000294 return *Entry = VectorType::get(ElementTypes[0],
295 cast<VectorType>(Ty)->getNumElements());
296 case Type::PointerTyID:
297 return *Entry = PointerType::get(ElementTypes[0],
298 cast<PointerType>(Ty)->getAddressSpace());
299 case Type::FunctionTyID:
300 return *Entry = FunctionType::get(ElementTypes[0],
Frits van Bommel717d7ed2011-07-18 12:00:32 +0000301 makeArrayRef(ElementTypes).slice(1),
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000302 cast<FunctionType>(Ty)->isVarArg());
303 case Type::StructTyID:
304 // Note that this is only reached for anonymous structs.
305 return *Entry = StructType::get(Ty->getContext(), ElementTypes,
306 cast<StructType>(Ty)->isPacked());
307 }
308 }
309
310 // Otherwise, this is an unmapped named struct. If the struct can be directly
311 // mapped over, just use it as-is. This happens in a case when the linked-in
312 // module has something like:
313 // %T = type {%T*, i32}
314 // @GV = global %T* null
315 // where T does not exist at all in the destination module.
316 //
317 // The other case we watch for is when the type is not in the destination
318 // module, but that it has to be rebuilt because it refers to something that
319 // is already mapped. For example, if the destination module has:
320 // %A = type { i32 }
321 // and the source module has something like
322 // %A' = type { i32 }
323 // %B = type { %A'* }
324 // @GV = global %B* null
325 // then we want to create a new type: "%B = type { %A*}" and have it take the
326 // pristine "%B" name from the source module.
327 //
328 // To determine which case this is, we have to recursively walk the type graph
329 // speculating that we'll be able to reuse it unmodified. Only if this is
330 // safe would we map the entire thing over. Because this is an optimization,
331 // and is not required for the prettiness of the linked module, we just skip
332 // it and always rebuild a type here.
333 StructType *STy = cast<StructType>(Ty);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000334
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000335 // If the type is opaque, we can just use it directly.
Rafael Espindolaaa9918a2013-05-04 05:05:18 +0000336 if (STy->isOpaque()) {
337 // A named structure type from src module is used. Add it to the Set of
338 // identified structs in the destination module.
339 DstStructTypesSet.insert(STy);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000340 return *Entry = STy;
Rafael Espindolaaa9918a2013-05-04 05:05:18 +0000341 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000342
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000343 // Otherwise we create a new type and resolve its body later. This will be
344 // resolved by the top level of get().
Chris Lattner5e3bd972011-12-20 00:03:52 +0000345 SrcDefinitionsToResolve.push_back(STy);
346 StructType *DTy = StructType::create(STy->getContext());
Rafael Espindolaaa9918a2013-05-04 05:05:18 +0000347 // A new identified structure type was created. Add it to the set of
348 // identified structs in the destination module.
349 DstStructTypesSet.insert(DTy);
Chris Lattner5e3bd972011-12-20 00:03:52 +0000350 DstResolvedOpaqueTypes.insert(DTy);
351 return *Entry = DTy;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000352}
353
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000354//===----------------------------------------------------------------------===//
355// ModuleLinker implementation.
356//===----------------------------------------------------------------------===//
357
358namespace {
James Molloyf6f121e2013-05-28 15:17:05 +0000359 class ModuleLinker;
360
361 /// ValueMaterializerTy - Creates prototypes for functions that are lazily
362 /// linked on the fly. This speeds up linking for modules with many
363 /// lazily linked functions of which few get used.
364 class ValueMaterializerTy : public ValueMaterializer {
365 TypeMapTy &TypeMap;
366 Module *DstM;
367 std::vector<Function*> &LazilyLinkFunctions;
368 public:
369 ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
370 std::vector<Function*> &LazilyLinkFunctions) :
371 ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
372 LazilyLinkFunctions(LazilyLinkFunctions) {
373 }
374
Craig Topper85482992014-03-05 07:52:44 +0000375 Value *materializeValueFor(Value *V) override;
James Molloyf6f121e2013-05-28 15:17:05 +0000376 };
377
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000378 /// ModuleLinker - This is an implementation class for the LinkModules
379 /// function, which is the entrypoint for this file.
380 class ModuleLinker {
381 Module *DstM, *SrcM;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000382
383 TypeMapTy TypeMap;
James Molloyf6f121e2013-05-28 15:17:05 +0000384 ValueMaterializerTy ValMaterializer;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000385
386 /// ValueMap - Mapping of values from what they used to be in Src, to what
387 /// they are now in DstM. ValueToValueMapTy is a ValueMap, which involves
388 /// some overhead due to the use of Value handles which the Linker doesn't
389 /// actually need, but this allows us to reuse the ValueMapper code.
390 ValueToValueMapTy ValueMap;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000391
Rafael Espindola6b238632014-05-16 19:35:39 +0000392 std::vector<std::pair<GlobalValue *, GlobalAlias *>> ReplaceWithAlias;
393
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000394 struct AppendingVarInfo {
395 GlobalVariable *NewGV; // New aggregate global in dest module.
396 Constant *DstInit; // Old initializer from dest module.
397 Constant *SrcInit; // Old initializer from src module.
398 };
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000399
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000400 std::vector<AppendingVarInfo> AppendingVars;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000401
Tanya Lattnercbb91402011-10-11 00:24:54 +0000402 unsigned Mode; // Mode to treat source module.
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000403
Tanya Lattnercbb91402011-10-11 00:24:54 +0000404 // Set of items not to link in from source.
405 SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000406
Tanya Lattner0a48b872011-11-02 00:24:56 +0000407 // Vector of functions to lazily link in.
Bill Wendlingfa2287822013-03-27 17:54:41 +0000408 std::vector<Function*> LazilyLinkFunctions;
Eli Bendersky7da92ed2014-02-20 22:19:24 +0000409
410 bool SuppressWarnings;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000411
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000412 public:
413 std::string ErrorMsg;
Eli Bendersky7da92ed2014-02-20 22:19:24 +0000414
415 ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM, unsigned mode,
416 bool SuppressWarnings=false)
417 : DstM(dstM), SrcM(srcM), TypeMap(Set),
418 ValMaterializer(TypeMap, DstM, LazilyLinkFunctions), Mode(mode),
419 SuppressWarnings(SuppressWarnings) {}
420
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000421 bool run();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000422
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000423 private:
424 /// emitError - Helper method for setting a message and returning an error
425 /// code.
426 bool emitError(const Twine &Message) {
427 ErrorMsg = Message.str();
Chris Lattner99953022008-06-16 18:27:53 +0000428 return true;
Chris Lattner9be15892008-06-16 21:17:12 +0000429 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000430
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000431 /// getLinkageResult - This analyzes the two global values and determines
432 /// what the result will look like in the destination module.
433 bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Rafael Espindola23f8d642012-01-05 23:02:01 +0000434 GlobalValue::LinkageTypes &LT,
435 GlobalValue::VisibilityTypes &Vis,
436 bool &LinkFromSrc);
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000437
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000438 /// getLinkedToGlobal - Given a global in the source module, return the
439 /// global in the destination module that is being linked to, if any.
440 GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
441 // If the source has no name it can't link. If it has local linkage,
442 // there is no name match-up going on.
443 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
Craig Topper2617dcc2014-04-15 06:32:26 +0000444 return nullptr;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000445
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000446 // Otherwise see if we have a match in the destination module's symtab.
447 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
Craig Topper2617dcc2014-04-15 06:32:26 +0000448 if (!DGV) return nullptr;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000449
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000450 // If we found a global with the same name in the dest module, but it has
451 // internal linkage, we are really not doing any linkage here.
452 if (DGV->hasLocalLinkage())
Craig Topper2617dcc2014-04-15 06:32:26 +0000453 return nullptr;
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000454
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000455 // Otherwise, we do in fact link to the destination global.
456 return DGV;
457 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000458
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000459 void computeTypeMapping();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000460
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000461 bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
462 bool linkGlobalProto(GlobalVariable *SrcGV);
463 bool linkFunctionProto(Function *SrcF);
464 bool linkAliasProto(GlobalAlias *SrcA);
Bill Wendling66f02412012-02-11 11:38:06 +0000465 bool linkModuleFlagsMetadata();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000466
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000467 void linkAppendingVarInit(const AppendingVarInfo &AVI);
468 void linkGlobalInits();
469 void linkFunctionBody(Function *Dst, Function *Src);
470 void linkAliasBodies();
471 void linkNamedMDNodes();
472 };
Bill Wendlingd48b7782012-02-28 04:01:21 +0000473}
474
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000475/// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
Reid Spencer90246aa2007-02-04 04:29:21 +0000476/// in the symbol table. This is good for all clients except for us. Go
477/// through the trouble to force this back.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000478static void forceRenaming(GlobalValue *GV, StringRef Name) {
479 // If the global doesn't force its name or if it already has the right name,
480 // there is nothing for us to do.
481 if (GV->hasLocalLinkage() || GV->getName() == Name)
482 return;
483
484 Module *M = GV->getParent();
Reid Spencer361e5132004-11-12 20:37:43 +0000485
486 // If there is a conflict, rename the conflict.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000487 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
Chris Lattner2a8d2e02007-02-11 00:39:38 +0000488 GV->takeName(ConflictGV);
489 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000490 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
Chris Lattner2a8d2e02007-02-11 00:39:38 +0000491 } else {
492 GV->setName(Name); // Force the name back
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000493 }
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000494}
Reid Spencer90246aa2007-02-04 04:29:21 +0000495
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000496/// copyGVAttributes - copy additional attributes (those not needed to construct
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000497/// a GlobalValue) from the SrcGV to the DestGV.
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000498static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
Duncan Sandsdd7daee2008-05-26 19:58:59 +0000499 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
Rafael Espindola99e05cf2014-05-13 18:45:48 +0000500 auto *DestGO = dyn_cast<GlobalObject>(DestGV);
Rafael Espindolaa7d9c692014-05-06 14:51:36 +0000501 unsigned Alignment;
Rafael Espindola99e05cf2014-05-13 18:45:48 +0000502 if (DestGO)
503 Alignment = std::max(DestGO->getAlignment(), SrcGV->getAlignment());
Rafael Espindolaa7d9c692014-05-06 14:51:36 +0000504
Duncan Sandsdd7daee2008-05-26 19:58:59 +0000505 DestGV->copyAttributesFrom(SrcGV);
Rafael Espindolaa7d9c692014-05-06 14:51:36 +0000506
Rafael Espindola99e05cf2014-05-13 18:45:48 +0000507 if (DestGO)
508 DestGO->setAlignment(Alignment);
Rafael Espindolaa7d9c692014-05-06 14:51:36 +0000509
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000510 forceRenaming(DestGV, SrcGV->getName());
Reid Spencer361e5132004-11-12 20:37:43 +0000511}
512
Rafael Espindola23f8d642012-01-05 23:02:01 +0000513static bool isLessConstraining(GlobalValue::VisibilityTypes a,
514 GlobalValue::VisibilityTypes b) {
515 if (a == GlobalValue::HiddenVisibility)
516 return false;
517 if (b == GlobalValue::HiddenVisibility)
518 return true;
519 if (a == GlobalValue::ProtectedVisibility)
520 return false;
521 if (b == GlobalValue::ProtectedVisibility)
522 return true;
523 return false;
524}
525
James Molloyf6f121e2013-05-28 15:17:05 +0000526Value *ValueMaterializerTy::materializeValueFor(Value *V) {
527 Function *SF = dyn_cast<Function>(V);
528 if (!SF)
Craig Topper2617dcc2014-04-15 06:32:26 +0000529 return nullptr;
James Molloyf6f121e2013-05-28 15:17:05 +0000530
531 Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()),
532 SF->getLinkage(), SF->getName(), DstM);
533 copyGVAttributes(DF, SF);
534
535 LazilyLinkFunctions.push_back(SF);
536 return DF;
537}
538
539
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000540/// getLinkageResult - This analyzes the two global values and determines what
Chris Lattnerfc61de32004-12-03 22:18:41 +0000541/// the result will look like in the destination module. In particular, it
Rafael Espindola23f8d642012-01-05 23:02:01 +0000542/// computes the resultant linkage type and visibility, computes whether the
543/// global in the source should be copied over to the destination (replacing
544/// the existing one), and computes whether this linkage is an error or not.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000545bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Rafael Espindola23f8d642012-01-05 23:02:01 +0000546 GlobalValue::LinkageTypes &LT,
547 GlobalValue::VisibilityTypes &Vis,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000548 bool &LinkFromSrc) {
549 assert(Dest && "Must have two globals being queried");
550 assert(!Src->hasLocalLinkage() &&
Chris Lattnerfc61de32004-12-03 22:18:41 +0000551 "If Src has internal linkage, Dest shouldn't be set!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000552
Peter Collingbourne8bb15d82011-10-30 17:46:34 +0000553 bool SrcIsDeclaration = Src->isDeclaration() && !Src->isMaterializable();
Chris Lattner0c134b52011-07-14 20:23:05 +0000554 bool DestIsDeclaration = Dest->isDeclaration();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000555
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000556 if (SrcIsDeclaration) {
Anton Korobeynikov1f93c502008-03-10 22:33:22 +0000557 // If Src is external or if both Src & Dest are external.. Just link the
Chris Lattnerfc61de32004-12-03 22:18:41 +0000558 // external globals, we aren't adding anything.
Nico Rieck7157bb72014-01-14 15:22:47 +0000559 if (Src->hasDLLImportStorageClass()) {
560 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000561 if (DestIsDeclaration) {
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +0000562 LinkFromSrc = true;
563 LT = Src->getLinkage();
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000564 }
Andrew Lenharthe06036d2006-12-15 17:35:32 +0000565 } else if (Dest->hasExternalWeakLinkage()) {
Duncan Sands12da8ce2009-03-07 15:45:40 +0000566 // If the Dest is weak, use the source linkage.
Andrew Lenharthe06036d2006-12-15 17:35:32 +0000567 LinkFromSrc = true;
568 LT = Src->getLinkage();
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +0000569 } else {
570 LinkFromSrc = false;
571 LT = Dest->getLinkage();
572 }
Nico Rieck7157bb72014-01-14 15:22:47 +0000573 } else if (DestIsDeclaration && !Dest->hasDLLImportStorageClass()) {
Chris Lattnerfc61de32004-12-03 22:18:41 +0000574 // If Dest is external but Src is not:
575 LinkFromSrc = true;
576 LT = Src->getLinkage();
Duncan Sandsd725c992009-03-08 13:35:23 +0000577 } else if (Src->isWeakForLinker()) {
Dale Johannesence4396b2008-05-14 20:12:51 +0000578 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
579 // or DLL* linkage.
Chris Lattner184f1be2009-04-13 05:44:34 +0000580 if (Dest->hasExternalWeakLinkage() ||
581 Dest->hasAvailableExternallyLinkage() ||
582 (Dest->hasLinkOnceLinkage() &&
583 (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
Chris Lattnerfc61de32004-12-03 22:18:41 +0000584 LinkFromSrc = true;
585 LT = Src->getLinkage();
586 } else {
587 LinkFromSrc = false;
588 LT = Dest->getLinkage();
589 }
Duncan Sandsd725c992009-03-08 13:35:23 +0000590 } else if (Dest->isWeakForLinker()) {
Anton Korobeynikov12c94942006-12-01 00:25:12 +0000591 // At this point we know that Src has External* or DLL* linkage.
592 if (Src->hasExternalWeakLinkage()) {
593 LinkFromSrc = false;
594 LT = Dest->getLinkage();
595 } else {
596 LinkFromSrc = true;
597 LT = GlobalValue::ExternalLinkage;
598 }
Chris Lattnerfc61de32004-12-03 22:18:41 +0000599 } else {
Nico Rieck7157bb72014-01-14 15:22:47 +0000600 assert((Dest->hasExternalLinkage() || Dest->hasExternalWeakLinkage()) &&
601 (Src->hasExternalLinkage() || Src->hasExternalWeakLinkage()) &&
Chris Lattnerfc61de32004-12-03 22:18:41 +0000602 "Unexpected linkage type!");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000603 return emitError("Linking globals named '" + Src->getName() +
Chris Lattnerfc61de32004-12-03 22:18:41 +0000604 "': symbol multiply defined!");
605 }
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000606
Rafael Espindola23f8d642012-01-05 23:02:01 +0000607 // Compute the visibility. We follow the rules in the System V Application
608 // Binary Interface.
Duncan P. N. Exon Smithb2becfd2014-05-07 22:55:46 +0000609 assert(!GlobalValue::isLocalLinkage(LT) &&
610 "Symbols with local linkage should not be merged");
Rafael Espindola23f8d642012-01-05 23:02:01 +0000611 Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
612 Dest->getVisibility() : Src->getVisibility();
Chris Lattnerfc61de32004-12-03 22:18:41 +0000613 return false;
614}
Reid Spencer361e5132004-11-12 20:37:43 +0000615
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000616/// computeTypeMapping - Loop over all of the linked values to compute type
617/// mappings. For example, if we link "extern Foo *x" and "Foo *x = NULL", then
618/// we have two struct types 'Foo' but one got renamed when the module was
619/// loaded into the same LLVMContext.
620void ModuleLinker::computeTypeMapping() {
621 // Incorporate globals.
622 for (Module::global_iterator I = SrcM->global_begin(),
623 E = SrcM->global_end(); I != E; ++I) {
624 GlobalValue *DGV = getLinkedToGlobal(I);
Craig Topper2617dcc2014-04-15 06:32:26 +0000625 if (!DGV) continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000626
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000627 if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
628 TypeMap.addTypeMapping(DGV->getType(), I->getType());
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000629 continue;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000630 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000631
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000632 // Unify the element type of appending arrays.
633 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
634 ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
635 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
Devang Patel5c310be2009-08-11 18:01:24 +0000636 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000637
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000638 // Incorporate functions.
639 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
640 if (GlobalValue *DGV = getLinkedToGlobal(I))
641 TypeMap.addTypeMapping(DGV->getType(), I->getType());
642 }
Bill Wendling7b464612012-02-27 22:34:19 +0000643
Bill Wendlingd48b7782012-02-28 04:01:21 +0000644 // Incorporate types by name, scanning all the types in the source module.
645 // At this point, the destination module may have a type "%foo = { i32 }" for
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000646 // example. When the source module got loaded into the same LLVMContext, if
647 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
Bill Wendling8555a372012-08-03 00:30:35 +0000648 TypeFinder SrcStructTypes;
649 SrcStructTypes.run(*SrcM, true);
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000650 SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
651 SrcStructTypes.end());
Bill Wendling87374802012-03-23 23:17:38 +0000652
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000653 for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
654 StructType *ST = SrcStructTypes[i];
655 if (!ST->hasName()) continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000656
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000657 // Check to see if there is a dot in the name followed by a digit.
Bill Wendlingd48b7782012-02-28 04:01:21 +0000658 size_t DotPos = ST->getName().rfind('.');
659 if (DotPos == 0 || DotPos == StringRef::npos ||
Guy Benyei83c74e92013-02-12 21:21:59 +0000660 ST->getName().back() == '.' ||
661 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
Bill Wendlingd48b7782012-02-28 04:01:21 +0000662 continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000663
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000664 // Check to see if the destination module has a struct with the prefix name.
Bill Wendlingd48b7782012-02-28 04:01:21 +0000665 if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
Bill Wendling87374802012-03-23 23:17:38 +0000666 // Don't use it if this actually came from the source module. They're in
667 // the same LLVMContext after all. Also don't use it unless the type is
668 // actually used in the destination module. This can happen in situations
669 // like this:
670 //
671 // Module A Module B
672 // -------- --------
673 // %Z = type { %A } %B = type { %C.1 }
674 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
675 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
676 // %C = type { i8* } %B.3 = type { %C.1 }
677 //
678 // When we link Module B with Module A, the '%B' in Module B is
679 // used. However, that would then use '%C.1'. But when we process '%C.1',
680 // we prefer to take the '%C' version. So we are then left with both
681 // '%C.1' and '%C' being used for the same types. This leads to some
682 // variables using one type and some using the other.
Rafael Espindolaaa9918a2013-05-04 05:05:18 +0000683 if (!SrcStructTypesSet.count(DST) && TypeMap.DstStructTypesSet.count(DST))
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000684 TypeMap.addTypeMapping(DST, ST);
685 }
686
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000687 // Don't bother incorporating aliases, they aren't generally typed well.
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000688
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000689 // Now that we have discovered all of the type equivalences, get a body for
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000690 // any 'opaque' types in the dest module that are now resolved.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000691 TypeMap.linkDefinedTypeBodies();
Devang Patel5c310be2009-08-11 18:01:24 +0000692}
693
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000694/// linkAppendingVarProto - If there were any appending global variables, link
695/// them together now. Return true on error.
696bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
697 GlobalVariable *SrcGV) {
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000698
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000699 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
700 return emitError("Linking globals named '" + SrcGV->getName() +
701 "': can only link appending global with another appending global!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000702
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000703 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
704 ArrayType *SrcTy =
705 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
706 Type *EltTy = DstTy->getElementType();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000707
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000708 // Check to see that they two arrays agree on type.
709 if (EltTy != SrcTy->getElementType())
710 return emitError("Appending variables with different element types!");
711 if (DstGV->isConstant() != SrcGV->isConstant())
712 return emitError("Appending variables linked with different const'ness!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000713
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000714 if (DstGV->getAlignment() != SrcGV->getAlignment())
715 return emitError(
716 "Appending variables with different alignment need to be linked!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000717
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000718 if (DstGV->getVisibility() != SrcGV->getVisibility())
719 return emitError(
720 "Appending variables with different visibility need to be linked!");
Rafael Espindolafac3a012013-09-04 15:33:34 +0000721
722 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
723 return emitError(
724 "Appending variables with different unnamed_addr need to be linked!");
725
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000726 if (DstGV->getSection() != SrcGV->getSection())
727 return emitError(
728 "Appending variables with different section name need to be linked!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000729
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000730 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
731 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000732
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000733 // Create the new global variable.
734 GlobalVariable *NG =
735 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
Craig Topper2617dcc2014-04-15 06:32:26 +0000736 DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000737 DstGV->getThreadLocalMode(),
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000738 DstGV->getType()->getAddressSpace());
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000739
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000740 // Propagate alignment, visibility and section info.
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000741 copyGVAttributes(NG, DstGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000742
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000743 AppendingVarInfo AVI;
744 AVI.NewGV = NG;
745 AVI.DstInit = DstGV->getInitializer();
746 AVI.SrcInit = SrcGV->getInitializer();
747 AppendingVars.push_back(AVI);
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000748
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000749 // Replace any uses of the two global variables with uses of the new
750 // global.
751 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
Anton Korobeynikove79f4c72008-03-10 22:34:28 +0000752
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000753 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
754 DstGV->eraseFromParent();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000755
Tanya Lattnercbb91402011-10-11 00:24:54 +0000756 // Track the source variable so we don't try to link it.
757 DoNotLinkFromSource.insert(SrcGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000758
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000759 return false;
760}
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000761
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000762/// linkGlobalProto - Loop through the global variables in the src module and
763/// merge them into the dest module.
764bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
765 GlobalValue *DGV = getLinkedToGlobal(SGV);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000766 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Rafael Espindolad4885da2013-09-04 14:05:09 +0000767 bool HasUnnamedAddr = SGV->hasUnnamedAddr();
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000768
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000769 if (DGV) {
770 // Concatenation of appending linkage variables is magic and handled later.
771 if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
772 return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000773
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000774 // Determine whether linkage of these two globals follows the source
775 // module's definition or the destination module's definition.
Chris Lattner1b9633d2006-11-09 05:18:12 +0000776 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
Rafael Espindola23f8d642012-01-05 23:02:01 +0000777 GlobalValue::VisibilityTypes NV;
Chris Lattner1b9633d2006-11-09 05:18:12 +0000778 bool LinkFromSrc = false;
Rafael Espindola23f8d642012-01-05 23:02:01 +0000779 if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
Chris Lattnerfc61de32004-12-03 22:18:41 +0000780 return true;
Rafael Espindola23f8d642012-01-05 23:02:01 +0000781 NewVisibility = NV;
Rafael Espindolafd9a9412013-09-04 14:59:03 +0000782 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
Reid Spencer361e5132004-11-12 20:37:43 +0000783
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000784 // If we're not linking from the source, then keep the definition that we
785 // have.
786 if (!LinkFromSrc) {
787 // Special case for const propagation.
788 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
789 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
790 DGVar->setConstant(true);
Rafael Espindolad4885da2013-09-04 14:05:09 +0000791
792 // Set calculated linkage, visibility and unnamed_addr.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000793 DGV->setLinkage(NewLinkage);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000794 DGV->setVisibility(*NewVisibility);
Rafael Espindolad4885da2013-09-04 14:05:09 +0000795 DGV->setUnnamedAddr(HasUnnamedAddr);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000796
Chris Lattner0ead7a52008-07-14 07:23:24 +0000797 // Make sure to remember this mapping.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000798 ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000799
800 // Track the source global so that we don't attempt to copy it over when
Tanya Lattnercbb91402011-10-11 00:24:54 +0000801 // processing global initializers.
802 DoNotLinkFromSource.insert(SGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000803
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000804 return false;
Chris Lattner0ead7a52008-07-14 07:23:24 +0000805 }
Reid Spencer361e5132004-11-12 20:37:43 +0000806 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000807
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000808 // No linking to be performed or linking from the source: simply create an
809 // identical version of the symbol over in the dest module... the
810 // initializer will be filled in later by LinkGlobalInits.
811 GlobalVariable *NewDGV =
812 new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
Craig Topper2617dcc2014-04-15 06:32:26 +0000813 SGV->isConstant(), SGV->getLinkage(), /*init*/nullptr,
814 SGV->getName(), /*insertbefore*/nullptr,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000815 SGV->getThreadLocalMode(),
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000816 SGV->getType()->getAddressSpace());
817 // Propagate alignment, visibility and section info.
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000818 copyGVAttributes(NewDGV, SGV);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000819 if (NewVisibility)
820 NewDGV->setVisibility(*NewVisibility);
Rafael Espindolad4885da2013-09-04 14:05:09 +0000821 NewDGV->setUnnamedAddr(HasUnnamedAddr);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000822
823 if (DGV) {
824 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
825 DGV->eraseFromParent();
826 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000827
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000828 // Make sure to remember this mapping.
829 ValueMap[SGV] = NewDGV;
Reid Spencer361e5132004-11-12 20:37:43 +0000830 return false;
831}
832
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000833/// linkFunctionProto - Link the function in the source module into the
834/// destination module if needed, setting up mapping information.
835bool ModuleLinker::linkFunctionProto(Function *SF) {
836 GlobalValue *DGV = getLinkedToGlobal(SF);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000837 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Rafael Espindolafd9a9412013-09-04 14:59:03 +0000838 bool HasUnnamedAddr = SF->hasUnnamedAddr();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000839
840 if (DGV) {
841 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
842 bool LinkFromSrc = false;
Rafael Espindola23f8d642012-01-05 23:02:01 +0000843 GlobalValue::VisibilityTypes NV;
844 if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000845 return true;
Rafael Espindola23f8d642012-01-05 23:02:01 +0000846 NewVisibility = NV;
Rafael Espindolafd9a9412013-09-04 14:59:03 +0000847 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
Rafael Espindola23f8d642012-01-05 23:02:01 +0000848
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000849 if (!LinkFromSrc) {
850 // Set calculated linkage
851 DGV->setLinkage(NewLinkage);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000852 DGV->setVisibility(*NewVisibility);
Rafael Espindolafd9a9412013-09-04 14:59:03 +0000853 DGV->setUnnamedAddr(HasUnnamedAddr);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000854
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000855 // Make sure to remember this mapping.
856 ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000857
858 // Track the function from the source module so we don't attempt to remap
Tanya Lattnercbb91402011-10-11 00:24:54 +0000859 // it.
860 DoNotLinkFromSource.insert(SF);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000861
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000862 return false;
863 }
Anton Korobeynikovdac5fa92008-03-05 22:22:46 +0000864 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000865
James Molloyf6f121e2013-05-28 15:17:05 +0000866 // If the function is to be lazily linked, don't create it just yet.
867 // The ValueMaterializerTy will deal with creating it if it's used.
868 if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
869 SF->hasAvailableExternallyLinkage())) {
870 DoNotLinkFromSource.insert(SF);
871 return false;
872 }
873
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000874 // If there is no linkage to be performed or we are linking from the source,
875 // bring SF over.
876 Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
877 SF->getLinkage(), SF->getName(), DstM);
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000878 copyGVAttributes(NewDF, SF);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000879 if (NewVisibility)
880 NewDF->setVisibility(*NewVisibility);
Rafael Espindolafd9a9412013-09-04 14:59:03 +0000881 NewDF->setUnnamedAddr(HasUnnamedAddr);
Anton Korobeynikovdac5fa92008-03-05 22:22:46 +0000882
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000883 if (DGV) {
884 // Any uses of DF need to change to NewDF, with cast.
885 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
886 DGV->eraseFromParent();
Lauro Ramos Venanciob00c9c02007-06-28 19:02:54 +0000887 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000888
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000889 ValueMap[SF] = NewDF;
Lauro Ramos Venanciob00c9c02007-06-28 19:02:54 +0000890 return false;
891}
892
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000893/// LinkAliasProto - Set up prototypes for any aliases that come over from the
894/// source module.
895bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
896 GlobalValue *DGV = getLinkedToGlobal(SGA);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000897 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
898
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000899 if (DGV) {
900 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
Rafael Espindola23f8d642012-01-05 23:02:01 +0000901 GlobalValue::VisibilityTypes NV;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000902 bool LinkFromSrc = false;
Rafael Espindola23f8d642012-01-05 23:02:01 +0000903 if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000904 return true;
Rafael Espindola23f8d642012-01-05 23:02:01 +0000905 NewVisibility = NV;
906
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000907 if (!LinkFromSrc) {
908 // Set calculated linkage.
909 DGV->setLinkage(NewLinkage);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000910 DGV->setVisibility(*NewVisibility);
911
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000912 // Make sure to remember this mapping.
913 ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000914
Tanya Lattnercbb91402011-10-11 00:24:54 +0000915 // Track the alias from the source module so we don't attempt to remap it.
916 DoNotLinkFromSource.insert(SGA);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000917
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000918 return false;
919 }
920 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000921
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000922 // If there is no linkage to be performed or we're linking from the source,
923 // bring over SGA.
Rafael Espindola4fe00942014-05-16 13:34:04 +0000924 auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType()));
Rafael Espindolaf1bedd3742014-05-17 21:29:57 +0000925 auto *NewDA =
926 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
927 SGA->getLinkage(), SGA->getName(), DstM);
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000928 copyGVAttributes(NewDA, SGA);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000929 if (NewVisibility)
930 NewDA->setVisibility(*NewVisibility);
Reid Spencer361e5132004-11-12 20:37:43 +0000931
Rafael Espindola6b238632014-05-16 19:35:39 +0000932 if (DGV)
933 ReplaceWithAlias.push_back(std::make_pair(DGV, NewDA));
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000934
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000935 ValueMap[SGA] = NewDA;
936 return false;
937}
938
Chris Lattner00245f42012-01-24 13:41:11 +0000939static void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest) {
Chris Lattner67058832012-01-25 06:48:06 +0000940 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
941
942 for (unsigned i = 0; i != NumElements; ++i)
943 Dest.push_back(C->getAggregateElement(i));
Chris Lattner00245f42012-01-24 13:41:11 +0000944}
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000945
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000946void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
947 // Merge the initializer.
948 SmallVector<Constant*, 16> Elements;
Chris Lattner00245f42012-01-24 13:41:11 +0000949 getArrayElements(AVI.DstInit, Elements);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000950
James Molloyf6f121e2013-05-28 15:17:05 +0000951 Constant *SrcInit = MapValue(AVI.SrcInit, ValueMap, RF_None, &TypeMap, &ValMaterializer);
Chris Lattner00245f42012-01-24 13:41:11 +0000952 getArrayElements(SrcInit, Elements);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000953
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000954 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
955 AVI.NewGV->setInitializer(ConstantArray::get(NewType, Elements));
956}
957
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000958/// linkGlobalInits - Update the initializers in the Dest module now that all
959/// globals that may be referenced are in Dest.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000960void ModuleLinker::linkGlobalInits() {
Reid Spencer361e5132004-11-12 20:37:43 +0000961 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000962 for (Module::const_global_iterator I = SrcM->global_begin(),
963 E = SrcM->global_end(); I != E; ++I) {
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000964
Tanya Lattnercbb91402011-10-11 00:24:54 +0000965 // Only process initialized GV's or ones not already in dest.
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000966 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
967
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000968 // Grab destination global variable.
969 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
970 // Figure out what the initializer looks like in the dest module.
971 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
James Molloyf6f121e2013-05-28 15:17:05 +0000972 RF_None, &TypeMap, &ValMaterializer));
Reid Spencer361e5132004-11-12 20:37:43 +0000973 }
Reid Spencer361e5132004-11-12 20:37:43 +0000974}
975
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000976/// linkFunctionBody - Copy the source function over into the dest function and
977/// fix up references to values. At this point we know that Dest is an external
978/// function, and that Src is not.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000979void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
980 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
Reid Spencer361e5132004-11-12 20:37:43 +0000981
Chris Lattner7391dde2004-11-16 17:12:38 +0000982 // Go through and convert function arguments over, remembering the mapping.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000983 Function::arg_iterator DI = Dst->arg_begin();
Chris Lattner531f9e92005-03-15 04:54:21 +0000984 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
Reid Spencer361e5132004-11-12 20:37:43 +0000985 I != E; ++I, ++DI) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000986 DI->setName(I->getName()); // Copy the name over.
Reid Spencer361e5132004-11-12 20:37:43 +0000987
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000988 // Add a mapping to our mapping.
Anton Korobeynikov66a62712008-03-10 22:36:08 +0000989 ValueMap[I] = DI;
Reid Spencer361e5132004-11-12 20:37:43 +0000990 }
991
Tanya Lattnercbb91402011-10-11 00:24:54 +0000992 if (Mode == Linker::DestroySource) {
993 // Splice the body of the source function into the dest function.
994 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000995
Tanya Lattnercbb91402011-10-11 00:24:54 +0000996 // At this point, all of the instructions and values of the function are now
997 // copied over. The only problem is that they are still referencing values in
998 // the Source function as operands. Loop through all of the operands of the
999 // functions and patch them up to point to the local versions.
1000 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
1001 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
James Molloyf6f121e2013-05-28 15:17:05 +00001002 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries,
1003 &TypeMap, &ValMaterializer);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001004
Tanya Lattnercbb91402011-10-11 00:24:54 +00001005 } else {
1006 // Clone the body of the function into the dest function.
1007 SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
Craig Topper2617dcc2014-04-15 06:32:26 +00001008 CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", nullptr,
James Molloyf6f121e2013-05-28 15:17:05 +00001009 &TypeMap, &ValMaterializer);
Tanya Lattnercbb91402011-10-11 00:24:54 +00001010 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001011
Chris Lattner7391dde2004-11-16 17:12:38 +00001012 // There is no need to map the arguments anymore.
Chris Lattner44ab8ae2006-06-16 01:24:04 +00001013 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1014 I != E; ++I)
Reid Spencer3aaaa0b2007-02-05 20:47:22 +00001015 ValueMap.erase(I);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001016
Reid Spencer361e5132004-11-12 20:37:43 +00001017}
1018
Rafael Espindola6b238632014-05-16 19:35:39 +00001019static GlobalObject &getGlobalObjectInExpr(Constant &C) {
1020 auto *GO = dyn_cast<GlobalObject>(&C);
1021 if (GO)
1022 return *GO;
1023 auto *GA = dyn_cast<GlobalAlias>(&C);
1024 if (GA)
1025 return *GA->getAliasee();
1026 auto &CE = cast<ConstantExpr>(C);
1027 assert(CE.getOpcode() == Instruction::BitCast ||
1028 CE.getOpcode() == Instruction::AddrSpaceCast);
1029 return getGlobalObjectInExpr(*CE.getOperand(0));
1030}
1031
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001032/// linkAliasBodies - Insert all of the aliases in Src into the Dest module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001033void ModuleLinker::linkAliasBodies() {
1034 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
Tanya Lattnercbb91402011-10-11 00:24:54 +00001035 I != E; ++I) {
1036 if (DoNotLinkFromSource.count(I))
1037 continue;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001038 if (Constant *Aliasee = I->getAliasee()) {
1039 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
Rafael Espindola6b238632014-05-16 19:35:39 +00001040 Constant *Val =
1041 MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer);
1042 DA->setAliasee(&getGlobalObjectInExpr(*Val));
David Chisnall2c4a34a2010-01-09 16:27:31 +00001043 }
Tanya Lattnercbb91402011-10-11 00:24:54 +00001044 }
Rafael Espindola6b238632014-05-16 19:35:39 +00001045
1046 // Any uses of DGV need to change to NewDA, with cast.
1047 for (auto &Pair : ReplaceWithAlias) {
1048 GlobalValue *DGV = Pair.first;
1049 GlobalAlias *NewDA = Pair.second;
1050
1051 for (auto *User : DGV->users()) {
1052 if (auto *GA = dyn_cast<GlobalAlias>(User)) {
1053 if (GA == NewDA)
1054 report_fatal_error("Linking these modules creates an alias cycle.");
1055 }
1056 }
1057
1058 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
1059 DGV->eraseFromParent();
1060 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001061}
Anton Korobeynikov26098882008-03-05 23:21:39 +00001062
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001063/// linkNamedMDNodes - Insert all of the named MDNodes in Src into the Dest
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001064/// module.
1065void ModuleLinker::linkNamedMDNodes() {
Bill Wendling66f02412012-02-11 11:38:06 +00001066 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001067 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1068 E = SrcM->named_metadata_end(); I != E; ++I) {
Bill Wendling66f02412012-02-11 11:38:06 +00001069 // Don't link module flags here. Do them separately.
1070 if (&*I == SrcModFlags) continue;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001071 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1072 // Add Src elements into Dest node.
1073 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1074 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
James Molloyf6f121e2013-05-28 15:17:05 +00001075 RF_None, &TypeMap, &ValMaterializer));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001076 }
1077}
Bill Wendling66f02412012-02-11 11:38:06 +00001078
Bill Wendling66f02412012-02-11 11:38:06 +00001079/// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest
1080/// module.
1081bool ModuleLinker::linkModuleFlagsMetadata() {
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001082 // If the source module has no module flags, we are done.
Bill Wendling66f02412012-02-11 11:38:06 +00001083 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1084 if (!SrcModFlags) return false;
1085
Bill Wendling66f02412012-02-11 11:38:06 +00001086 // If the destination module doesn't have module flags yet, then just copy
1087 // over the source module's flags.
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001088 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
Bill Wendling66f02412012-02-11 11:38:06 +00001089 if (DstModFlags->getNumOperands() == 0) {
1090 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1091 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1092
1093 return false;
1094 }
1095
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001096 // First build a map of the existing module flags and requirements.
1097 DenseMap<MDString*, MDNode*> Flags;
1098 SmallSetVector<MDNode*, 16> Requirements;
1099 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1100 MDNode *Op = DstModFlags->getOperand(I);
1101 ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1102 MDString *ID = cast<MDString>(Op->getOperand(1));
Bill Wendling66f02412012-02-11 11:38:06 +00001103
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001104 if (Behavior->getZExtValue() == Module::Require) {
1105 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1106 } else {
1107 Flags[ID] = Op;
1108 }
Bill Wendling66f02412012-02-11 11:38:06 +00001109 }
1110
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001111 // Merge in the flags from the source module, and also collect its set of
1112 // requirements.
1113 bool HasErr = false;
1114 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1115 MDNode *SrcOp = SrcModFlags->getOperand(I);
1116 ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1117 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1118 MDNode *DstOp = Flags.lookup(ID);
1119 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
Bill Wendling66f02412012-02-11 11:38:06 +00001120
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001121 // If this is a requirement, add it and continue.
1122 if (SrcBehaviorValue == Module::Require) {
1123 // If the destination module does not already have this requirement, add
1124 // it.
1125 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1126 DstModFlags->addOperand(SrcOp);
1127 }
1128 continue;
Bill Wendling66f02412012-02-11 11:38:06 +00001129 }
1130
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001131 // If there is no existing flag with this ID, just add it.
1132 if (!DstOp) {
1133 Flags[ID] = SrcOp;
1134 DstModFlags->addOperand(SrcOp);
1135 continue;
1136 }
1137
1138 // Otherwise, perform a merge.
1139 ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1140 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1141
1142 // If either flag has override behavior, handle it first.
1143 if (DstBehaviorValue == Module::Override) {
1144 // Diagnose inconsistent flags which both have override behavior.
1145 if (SrcBehaviorValue == Module::Override &&
1146 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1147 HasErr |= emitError("linking module flags '" + ID->getString() +
1148 "': IDs have conflicting override values");
1149 }
1150 continue;
1151 } else if (SrcBehaviorValue == Module::Override) {
1152 // Update the destination flag to that of the source.
1153 DstOp->replaceOperandWith(0, SrcBehavior);
1154 DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1155 continue;
1156 }
1157
1158 // Diagnose inconsistent merge behavior types.
1159 if (SrcBehaviorValue != DstBehaviorValue) {
1160 HasErr |= emitError("linking module flags '" + ID->getString() +
1161 "': IDs have conflicting behaviors");
1162 continue;
1163 }
1164
1165 // Perform the merge for standard behavior types.
1166 switch (SrcBehaviorValue) {
1167 case Module::Require:
1168 case Module::Override: assert(0 && "not possible"); break;
1169 case Module::Error: {
1170 // Emit an error if the values differ.
1171 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1172 HasErr |= emitError("linking module flags '" + ID->getString() +
1173 "': IDs have conflicting values");
1174 }
1175 continue;
1176 }
1177 case Module::Warning: {
1178 // Emit a warning if the values differ.
1179 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
Eli Benderskye17f3702014-02-06 18:01:56 +00001180 if (!SuppressWarnings) {
1181 errs() << "WARNING: linking module flags '" << ID->getString()
1182 << "': IDs have conflicting values";
1183 }
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001184 }
1185 continue;
1186 }
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001187 case Module::Append: {
1188 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1189 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1190 unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1191 Value **VP, **Values = VP = new Value*[NumOps];
1192 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1193 *VP = DstValue->getOperand(i);
1194 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1195 *VP = SrcValue->getOperand(i);
1196 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1197 ArrayRef<Value*>(Values,
1198 NumOps)));
1199 delete[] Values;
1200 break;
1201 }
1202 case Module::AppendUnique: {
1203 SmallSetVector<Value*, 16> Elts;
1204 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1205 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1206 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1207 Elts.insert(DstValue->getOperand(i));
1208 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1209 Elts.insert(SrcValue->getOperand(i));
1210 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1211 ArrayRef<Value*>(Elts.begin(),
1212 Elts.end())));
1213 break;
1214 }
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001215 }
Bill Wendling66f02412012-02-11 11:38:06 +00001216 }
1217
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001218 // Check all of the requirements.
1219 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1220 MDNode *Requirement = Requirements[I];
1221 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1222 Value *ReqValue = Requirement->getOperand(1);
Bill Wendling66f02412012-02-11 11:38:06 +00001223
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001224 MDNode *Op = Flags[Flag];
1225 if (!Op || Op->getOperand(2) != ReqValue) {
1226 HasErr |= emitError("linking module flags '" + Flag->getString() +
1227 "': does not have the required value");
1228 continue;
Bill Wendling66f02412012-02-11 11:38:06 +00001229 }
1230 }
1231
1232 return HasErr;
1233}
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001234
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001235bool ModuleLinker::run() {
Bill Wendling66f02412012-02-11 11:38:06 +00001236 assert(DstM && "Null destination module");
1237 assert(SrcM && "Null source module");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001238
1239 // Inherit the target data from the source module if the destination module
1240 // doesn't have one already.
Rafael Espindolaf863ee22014-02-25 20:01:08 +00001241 if (!DstM->getDataLayout() && SrcM->getDataLayout())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001242 DstM->setDataLayout(SrcM->getDataLayout());
1243
1244 // Copy the target triple from the source to dest if the dest's is empty.
1245 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1246 DstM->setTargetTriple(SrcM->getTargetTriple());
1247
Rafael Espindolaf863ee22014-02-25 20:01:08 +00001248 if (SrcM->getDataLayout() && DstM->getDataLayout() &&
Rafael Espindolaae593f12014-02-26 17:02:08 +00001249 *SrcM->getDataLayout() != *DstM->getDataLayout()) {
Eli Benderskye17f3702014-02-06 18:01:56 +00001250 if (!SuppressWarnings) {
JF Bastien026fc5f2014-03-05 21:26:42 +00001251 errs() << "WARNING: Linking two modules of different data layouts: '"
1252 << SrcM->getModuleIdentifier() << "' is '"
1253 << SrcM->getDataLayoutStr() << "' whereas '"
1254 << DstM->getModuleIdentifier() << "' is '"
1255 << DstM->getDataLayoutStr() << "'\n";
Eli Benderskye17f3702014-02-06 18:01:56 +00001256 }
1257 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001258 if (!SrcM->getTargetTriple().empty() &&
1259 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
Eli Benderskye17f3702014-02-06 18:01:56 +00001260 if (!SuppressWarnings) {
JF Bastien026fc5f2014-03-05 21:26:42 +00001261 errs() << "WARNING: Linking two modules of different target triples: "
1262 << SrcM->getModuleIdentifier() << "' is '"
1263 << SrcM->getTargetTriple() << "' whereas '"
1264 << DstM->getModuleIdentifier() << "' is '"
Eli Benderskye17f3702014-02-06 18:01:56 +00001265 << DstM->getTargetTriple() << "'\n";
1266 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001267 }
1268
1269 // Append the module inline asm string.
1270 if (!SrcM->getModuleInlineAsm().empty()) {
1271 if (DstM->getModuleInlineAsm().empty())
1272 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1273 else
1274 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1275 SrcM->getModuleInlineAsm());
1276 }
1277
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001278 // Loop over all of the linked values to compute type mappings.
1279 computeTypeMapping();
1280
1281 // Insert all of the globals in src into the DstM module... without linking
1282 // initializers (which could refer to functions not yet mapped over).
1283 for (Module::global_iterator I = SrcM->global_begin(),
1284 E = SrcM->global_end(); I != E; ++I)
1285 if (linkGlobalProto(I))
1286 return true;
1287
1288 // Link the functions together between the two modules, without doing function
1289 // bodies... this just adds external function prototypes to the DstM
1290 // function... We do this so that when we begin processing function bodies,
1291 // all of the global values that may be referenced are available in our
1292 // ValueMap.
1293 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1294 if (linkFunctionProto(I))
1295 return true;
1296
1297 // If there were any aliases, link them now.
1298 for (Module::alias_iterator I = SrcM->alias_begin(),
1299 E = SrcM->alias_end(); I != E; ++I)
1300 if (linkAliasProto(I))
1301 return true;
1302
1303 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1304 linkAppendingVarInit(AppendingVars[i]);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001305
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001306 // Link in the function bodies that are defined in the source module into
1307 // DstM.
1308 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
Tanya Lattnerea166d42011-10-14 22:17:46 +00001309 // Skip if not linking from source.
1310 if (DoNotLinkFromSource.count(SF)) continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001311
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001312 Function *DF = cast<Function>(ValueMap[SF]);
1313 if (SF->hasPrefixData()) {
1314 // Link in the prefix data.
1315 DF->setPrefixData(MapValue(
1316 SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
1317 }
1318
Tanya Lattnerea166d42011-10-14 22:17:46 +00001319 // Skip if no body (function is external) or materialize.
1320 if (SF->isDeclaration()) {
1321 if (!SF->isMaterializable())
1322 continue;
1323 if (SF->Materialize(&ErrorMsg))
1324 return true;
1325 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001326
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001327 linkFunctionBody(DF, SF);
Bill Wendling00623782012-03-23 07:22:49 +00001328 SF->Dematerialize();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001329 }
1330
1331 // Resolve all uses of aliases with aliasees.
1332 linkAliasBodies();
1333
Bill Wendling66f02412012-02-11 11:38:06 +00001334 // Remap all of the named MDNodes in Src into the DstM module. We do this
Devang Patel6ddbb2e2011-08-04 19:44:28 +00001335 // after linking GlobalValues so that MDNodes that reference GlobalValues
1336 // are properly remapped.
1337 linkNamedMDNodes();
1338
Bill Wendling66f02412012-02-11 11:38:06 +00001339 // Merge the module flags into the DstM module.
1340 if (linkModuleFlagsMetadata())
1341 return true;
1342
Bill Wendling91686d62014-01-16 06:29:36 +00001343 // Update the initializers in the DstM module now that all globals that may
1344 // be referenced are in DstM.
1345 linkGlobalInits();
1346
Tanya Lattner0a48b872011-11-02 00:24:56 +00001347 // Process vector of lazily linked in functions.
1348 bool LinkedInAnyFunctions;
1349 do {
1350 LinkedInAnyFunctions = false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001351
Bill Wendlingfa2287822013-03-27 17:54:41 +00001352 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001353 E = LazilyLinkFunctions.end(); I != E; ++I) {
Bill Wendlingfa2287822013-03-27 17:54:41 +00001354 Function *SF = *I;
James Molloyf6f121e2013-05-28 15:17:05 +00001355 if (!SF)
1356 continue;
Bill Wendling00623782012-03-23 07:22:49 +00001357
James Molloyf6f121e2013-05-28 15:17:05 +00001358 Function *DF = cast<Function>(ValueMap[SF]);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001359 if (SF->hasPrefixData()) {
1360 // Link in the prefix data.
1361 DF->setPrefixData(MapValue(SF->getPrefixData(),
1362 ValueMap,
1363 RF_None,
1364 &TypeMap,
1365 &ValMaterializer));
1366 }
James Molloyf6f121e2013-05-28 15:17:05 +00001367
1368 // Materialize if necessary.
1369 if (SF->isDeclaration()) {
1370 if (!SF->isMaterializable())
1371 continue;
1372 if (SF->Materialize(&ErrorMsg))
1373 return true;
Tanya Lattner0a48b872011-11-02 00:24:56 +00001374 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001375
James Molloyf6f121e2013-05-28 15:17:05 +00001376 // Erase from vector *before* the function body is linked - linkFunctionBody could
1377 // invalidate I.
1378 LazilyLinkFunctions.erase(I);
1379
1380 // Link in function body.
1381 linkFunctionBody(DF, SF);
1382 SF->Dematerialize();
1383
1384 // Set flag to indicate we may have more functions to lazily link in
1385 // since we linked in a function.
1386 LinkedInAnyFunctions = true;
1387 break;
Tanya Lattner0a48b872011-11-02 00:24:56 +00001388 }
1389 } while (LinkedInAnyFunctions);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001390
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001391 // Now that all of the types from the source are used, resolve any structs
1392 // copied over to the dest that didn't exist there.
1393 TypeMap.linkDefinedTypeBodies();
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001394
Anton Korobeynikov26098882008-03-05 23:21:39 +00001395 return false;
1396}
Reid Spencer361e5132004-11-12 20:37:43 +00001397
Eli Bendersky7da92ed2014-02-20 22:19:24 +00001398Linker::Linker(Module *M, bool SuppressWarnings)
1399 : Composite(M), SuppressWarnings(SuppressWarnings) {
Rafael Espindolaaa9918a2013-05-04 05:05:18 +00001400 TypeFinder StructTypes;
1401 StructTypes.run(*M, true);
1402 IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end());
1403}
Rafael Espindola3df61b72013-05-04 03:48:37 +00001404
1405Linker::~Linker() {
1406}
1407
Bill Wendling91e6f6e2013-10-16 08:59:57 +00001408void Linker::deleteModule() {
1409 delete Composite;
Craig Topper2617dcc2014-04-15 06:32:26 +00001410 Composite = nullptr;
Bill Wendling91e6f6e2013-10-16 08:59:57 +00001411}
1412
Rafael Espindola3df61b72013-05-04 03:48:37 +00001413bool Linker::linkInModule(Module *Src, unsigned Mode, std::string *ErrorMsg) {
Eli Bendersky7da92ed2014-02-20 22:19:24 +00001414 ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src, Mode,
1415 SuppressWarnings);
Rafael Espindola287f18b2013-05-04 04:08:02 +00001416 if (TheLinker.run()) {
1417 if (ErrorMsg)
1418 *ErrorMsg = TheLinker.ErrorMsg;
1419 return true;
1420 }
1421 return false;
Rafael Espindola3df61b72013-05-04 03:48:37 +00001422}
1423
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001424//===----------------------------------------------------------------------===//
1425// LinkModules entrypoint.
1426//===----------------------------------------------------------------------===//
1427
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001428/// LinkModules - This function links two modules together, with the resulting
Eli Bendersky970cc632013-03-08 22:29:44 +00001429/// Dest module modified to be the composite of the two input modules. If an
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001430/// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1431/// the problem. Upon failure, the Dest module could be in a modified state,
1432/// and shouldn't be relied on to be consistent.
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001433bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode,
Tanya Lattnercbb91402011-10-11 00:24:54 +00001434 std::string *ErrorMsg) {
Rafael Espindola287f18b2013-05-04 04:08:02 +00001435 Linker L(Dest);
1436 return L.linkInModule(Src, Mode, ErrorMsg);
Reid Spencer361e5132004-11-12 20:37:43 +00001437}
Bill Wendlinga3aeb982012-05-09 08:55:40 +00001438
1439//===----------------------------------------------------------------------===//
1440// C API.
1441//===----------------------------------------------------------------------===//
1442
1443LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1444 LLVMLinkerMode Mode, char **OutMessages) {
1445 std::string Messages;
1446 LLVMBool Result = Linker::LinkModules(unwrap(Dest), unwrap(Src),
Craig Topper2617dcc2014-04-15 06:32:26 +00001447 Mode, OutMessages? &Messages : nullptr);
Bill Wendlinga3aeb982012-05-09 08:55:40 +00001448 if (OutMessages)
1449 *OutMessages = strdup(Messages.c_str());
1450 return Result;
1451}