blob: eb73a49402adf8df5b6cacb22121e2087d69e625 [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
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000392 struct AppendingVarInfo {
393 GlobalVariable *NewGV; // New aggregate global in dest module.
394 Constant *DstInit; // Old initializer from dest module.
395 Constant *SrcInit; // Old initializer from src module.
396 };
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000397
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000398 std::vector<AppendingVarInfo> AppendingVars;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000399
Tanya Lattnercbb91402011-10-11 00:24:54 +0000400 unsigned Mode; // Mode to treat source module.
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000401
Tanya Lattnercbb91402011-10-11 00:24:54 +0000402 // Set of items not to link in from source.
403 SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000404
Tanya Lattner0a48b872011-11-02 00:24:56 +0000405 // Vector of functions to lazily link in.
Bill Wendlingfa2287822013-03-27 17:54:41 +0000406 std::vector<Function*> LazilyLinkFunctions;
Eli Bendersky7da92ed2014-02-20 22:19:24 +0000407
408 bool SuppressWarnings;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000409
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000410 public:
411 std::string ErrorMsg;
Eli Bendersky7da92ed2014-02-20 22:19:24 +0000412
413 ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM, unsigned mode,
414 bool SuppressWarnings=false)
415 : DstM(dstM), SrcM(srcM), TypeMap(Set),
416 ValMaterializer(TypeMap, DstM, LazilyLinkFunctions), Mode(mode),
417 SuppressWarnings(SuppressWarnings) {}
418
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000419 bool run();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000420
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000421 private:
422 /// emitError - Helper method for setting a message and returning an error
423 /// code.
424 bool emitError(const Twine &Message) {
425 ErrorMsg = Message.str();
Chris Lattner99953022008-06-16 18:27:53 +0000426 return true;
Chris Lattner9be15892008-06-16 21:17:12 +0000427 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000428
David Majnemerdad0a642014-06-27 18:19:56 +0000429 bool getComdatLeader(Module *M, StringRef ComdatName,
430 const GlobalVariable *&GVar);
431 bool computeResultingSelectionKind(StringRef ComdatName,
432 Comdat::SelectionKind Src,
433 Comdat::SelectionKind Dst,
434 Comdat::SelectionKind &Result,
435 bool &LinkFromSrc);
436 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
437 ComdatsChosen;
438 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
439 bool &LinkFromSrc);
440
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000441 /// getLinkageResult - This analyzes the two global values and determines
442 /// what the result will look like in the destination module.
443 bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Rafael Espindola23f8d642012-01-05 23:02:01 +0000444 GlobalValue::LinkageTypes &LT,
445 GlobalValue::VisibilityTypes &Vis,
446 bool &LinkFromSrc);
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000447
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000448 /// getLinkedToGlobal - Given a global in the source module, return the
449 /// global in the destination module that is being linked to, if any.
450 GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
451 // If the source has no name it can't link. If it has local linkage,
452 // there is no name match-up going on.
453 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
Craig Topper2617dcc2014-04-15 06:32:26 +0000454 return nullptr;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000455
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000456 // Otherwise see if we have a match in the destination module's symtab.
457 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
Craig Topper2617dcc2014-04-15 06:32:26 +0000458 if (!DGV) return nullptr;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000459
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000460 // If we found a global with the same name in the dest module, but it has
461 // internal linkage, we are really not doing any linkage here.
462 if (DGV->hasLocalLinkage())
Craig Topper2617dcc2014-04-15 06:32:26 +0000463 return nullptr;
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000464
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000465 // Otherwise, we do in fact link to the destination global.
466 return DGV;
467 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000468
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000469 void computeTypeMapping();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000470
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000471 bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
472 bool linkGlobalProto(GlobalVariable *SrcGV);
473 bool linkFunctionProto(Function *SrcF);
474 bool linkAliasProto(GlobalAlias *SrcA);
Bill Wendling66f02412012-02-11 11:38:06 +0000475 bool linkModuleFlagsMetadata();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000476
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000477 void linkAppendingVarInit(const AppendingVarInfo &AVI);
478 void linkGlobalInits();
479 void linkFunctionBody(Function *Dst, Function *Src);
480 void linkAliasBodies();
481 void linkNamedMDNodes();
482 };
Bill Wendlingd48b7782012-02-28 04:01:21 +0000483}
484
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000485/// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
Reid Spencer90246aa2007-02-04 04:29:21 +0000486/// in the symbol table. This is good for all clients except for us. Go
487/// through the trouble to force this back.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000488static void forceRenaming(GlobalValue *GV, StringRef Name) {
489 // If the global doesn't force its name or if it already has the right name,
490 // there is nothing for us to do.
491 if (GV->hasLocalLinkage() || GV->getName() == Name)
492 return;
493
494 Module *M = GV->getParent();
Reid Spencer361e5132004-11-12 20:37:43 +0000495
496 // If there is a conflict, rename the conflict.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000497 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
Chris Lattner2a8d2e02007-02-11 00:39:38 +0000498 GV->takeName(ConflictGV);
499 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000500 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
Chris Lattner2a8d2e02007-02-11 00:39:38 +0000501 } else {
502 GV->setName(Name); // Force the name back
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000503 }
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000504}
Reid Spencer90246aa2007-02-04 04:29:21 +0000505
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000506/// copyGVAttributes - copy additional attributes (those not needed to construct
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000507/// a GlobalValue) from the SrcGV to the DestGV.
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000508static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
Duncan Sandsdd7daee2008-05-26 19:58:59 +0000509 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
Rafael Espindola99e05cf2014-05-13 18:45:48 +0000510 auto *DestGO = dyn_cast<GlobalObject>(DestGV);
Rafael Espindolaa7d9c692014-05-06 14:51:36 +0000511 unsigned Alignment;
Rafael Espindola99e05cf2014-05-13 18:45:48 +0000512 if (DestGO)
513 Alignment = std::max(DestGO->getAlignment(), SrcGV->getAlignment());
Rafael Espindolaa7d9c692014-05-06 14:51:36 +0000514
Duncan Sandsdd7daee2008-05-26 19:58:59 +0000515 DestGV->copyAttributesFrom(SrcGV);
Rafael Espindolaa7d9c692014-05-06 14:51:36 +0000516
Rafael Espindola99e05cf2014-05-13 18:45:48 +0000517 if (DestGO)
518 DestGO->setAlignment(Alignment);
Rafael Espindolaa7d9c692014-05-06 14:51:36 +0000519
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000520 forceRenaming(DestGV, SrcGV->getName());
Reid Spencer361e5132004-11-12 20:37:43 +0000521}
522
Rafael Espindola23f8d642012-01-05 23:02:01 +0000523static bool isLessConstraining(GlobalValue::VisibilityTypes a,
524 GlobalValue::VisibilityTypes b) {
525 if (a == GlobalValue::HiddenVisibility)
526 return false;
527 if (b == GlobalValue::HiddenVisibility)
528 return true;
529 if (a == GlobalValue::ProtectedVisibility)
530 return false;
531 if (b == GlobalValue::ProtectedVisibility)
532 return true;
533 return false;
534}
535
James Molloyf6f121e2013-05-28 15:17:05 +0000536Value *ValueMaterializerTy::materializeValueFor(Value *V) {
537 Function *SF = dyn_cast<Function>(V);
538 if (!SF)
Craig Topper2617dcc2014-04-15 06:32:26 +0000539 return nullptr;
James Molloyf6f121e2013-05-28 15:17:05 +0000540
541 Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()),
542 SF->getLinkage(), SF->getName(), DstM);
543 copyGVAttributes(DF, SF);
544
545 LazilyLinkFunctions.push_back(SF);
546 return DF;
547}
548
David Majnemerdad0a642014-06-27 18:19:56 +0000549bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName,
550 const GlobalVariable *&GVar) {
551 const GlobalValue *GVal = M->getNamedValue(ComdatName);
552 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
553 GVal = GA->getBaseObject();
554 if (!GVal)
555 // We cannot resolve the size of the aliasee yet.
556 return emitError("Linking COMDATs named '" + ComdatName +
557 "': COMDAT key involves incomputable alias size.");
558 }
559
560 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
561 if (!GVar)
562 return emitError(
563 "Linking COMDATs named '" + ComdatName +
564 "': GlobalVariable required for data dependent selection!");
565
566 return false;
567}
568
569bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
570 Comdat::SelectionKind Src,
571 Comdat::SelectionKind Dst,
572 Comdat::SelectionKind &Result,
573 bool &LinkFromSrc) {
574 // The ability to mix Comdat::SelectionKind::Any with
575 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
576 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
577 Dst == Comdat::SelectionKind::Largest;
578 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
579 Src == Comdat::SelectionKind::Largest;
580 if (DstAnyOrLargest && SrcAnyOrLargest) {
581 if (Dst == Comdat::SelectionKind::Largest ||
582 Src == Comdat::SelectionKind::Largest)
583 Result = Comdat::SelectionKind::Largest;
584 else
585 Result = Comdat::SelectionKind::Any;
586 } else if (Src == Dst) {
587 Result = Dst;
588 } else {
589 return emitError("Linking COMDATs named '" + ComdatName +
590 "': invalid selection kinds!");
591 }
592
593 switch (Result) {
594 case Comdat::SelectionKind::Any:
595 // Go with Dst.
596 LinkFromSrc = false;
597 break;
598 case Comdat::SelectionKind::NoDuplicates:
599 return emitError("Linking COMDATs named '" + ComdatName +
600 "': noduplicates has been violated!");
601 case Comdat::SelectionKind::ExactMatch:
602 case Comdat::SelectionKind::Largest:
603 case Comdat::SelectionKind::SameSize: {
604 const GlobalVariable *DstGV;
605 const GlobalVariable *SrcGV;
606 if (getComdatLeader(DstM, ComdatName, DstGV) ||
607 getComdatLeader(SrcM, ComdatName, SrcGV))
608 return true;
609
610 const DataLayout *DstDL = DstM->getDataLayout();
611 const DataLayout *SrcDL = SrcM->getDataLayout();
612 if (!DstDL || !SrcDL) {
613 return emitError(
614 "Linking COMDATs named '" + ComdatName +
615 "': can't do size dependent selection without DataLayout!");
616 }
617 uint64_t DstSize =
618 DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType());
619 uint64_t SrcSize =
620 SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType());
621 if (Result == Comdat::SelectionKind::ExactMatch) {
622 if (SrcGV->getInitializer() != DstGV->getInitializer())
623 return emitError("Linking COMDATs named '" + ComdatName +
624 "': ExactMatch violated!");
625 LinkFromSrc = false;
626 } else if (Result == Comdat::SelectionKind::Largest) {
627 LinkFromSrc = SrcSize > DstSize;
628 } else if (Result == Comdat::SelectionKind::SameSize) {
629 if (SrcSize != DstSize)
630 return emitError("Linking COMDATs named '" + ComdatName +
631 "': SameSize violated!");
632 LinkFromSrc = false;
633 } else {
634 llvm_unreachable("unknown selection kind");
635 }
636 break;
637 }
638 }
639
640 return false;
641}
642
643bool ModuleLinker::getComdatResult(const Comdat *SrcC,
644 Comdat::SelectionKind &Result,
645 bool &LinkFromSrc) {
646 StringRef ComdatName = SrcC->getName();
647 Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable();
648 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
649 if (DstCI != ComdatSymTab.end()) {
650 const Comdat *DstC = &DstCI->second;
651 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
652 Comdat::SelectionKind DSK = DstC->getSelectionKind();
653 if (computeResultingSelectionKind(ComdatName, SSK, DSK, Result, LinkFromSrc))
654 return true;
655 }
656 return false;
657}
James Molloyf6f121e2013-05-28 15:17:05 +0000658
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000659/// getLinkageResult - This analyzes the two global values and determines what
Chris Lattnerfc61de32004-12-03 22:18:41 +0000660/// the result will look like in the destination module. In particular, it
Rafael Espindola23f8d642012-01-05 23:02:01 +0000661/// computes the resultant linkage type and visibility, computes whether the
662/// global in the source should be copied over to the destination (replacing
663/// the existing one), and computes whether this linkage is an error or not.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000664bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Rafael Espindola23f8d642012-01-05 23:02:01 +0000665 GlobalValue::LinkageTypes &LT,
666 GlobalValue::VisibilityTypes &Vis,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000667 bool &LinkFromSrc) {
668 assert(Dest && "Must have two globals being queried");
669 assert(!Src->hasLocalLinkage() &&
Chris Lattnerfc61de32004-12-03 22:18:41 +0000670 "If Src has internal linkage, Dest shouldn't be set!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000671
Peter Collingbourne8bb15d82011-10-30 17:46:34 +0000672 bool SrcIsDeclaration = Src->isDeclaration() && !Src->isMaterializable();
Chris Lattner0c134b52011-07-14 20:23:05 +0000673 bool DestIsDeclaration = Dest->isDeclaration();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000674
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000675 if (SrcIsDeclaration) {
Anton Korobeynikov1f93c502008-03-10 22:33:22 +0000676 // If Src is external or if both Src & Dest are external.. Just link the
Chris Lattnerfc61de32004-12-03 22:18:41 +0000677 // external globals, we aren't adding anything.
Nico Rieck7157bb72014-01-14 15:22:47 +0000678 if (Src->hasDLLImportStorageClass()) {
679 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000680 if (DestIsDeclaration) {
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +0000681 LinkFromSrc = true;
682 LT = Src->getLinkage();
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000683 }
Andrew Lenharthe06036d2006-12-15 17:35:32 +0000684 } else if (Dest->hasExternalWeakLinkage()) {
Duncan Sands12da8ce2009-03-07 15:45:40 +0000685 // If the Dest is weak, use the source linkage.
Andrew Lenharthe06036d2006-12-15 17:35:32 +0000686 LinkFromSrc = true;
687 LT = Src->getLinkage();
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +0000688 } else {
689 LinkFromSrc = false;
690 LT = Dest->getLinkage();
691 }
Nico Rieck7157bb72014-01-14 15:22:47 +0000692 } else if (DestIsDeclaration && !Dest->hasDLLImportStorageClass()) {
Chris Lattnerfc61de32004-12-03 22:18:41 +0000693 // If Dest is external but Src is not:
694 LinkFromSrc = true;
695 LT = Src->getLinkage();
Duncan Sandsd725c992009-03-08 13:35:23 +0000696 } else if (Src->isWeakForLinker()) {
Dale Johannesence4396b2008-05-14 20:12:51 +0000697 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
698 // or DLL* linkage.
Chris Lattner184f1be2009-04-13 05:44:34 +0000699 if (Dest->hasExternalWeakLinkage() ||
700 Dest->hasAvailableExternallyLinkage() ||
701 (Dest->hasLinkOnceLinkage() &&
702 (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
Chris Lattnerfc61de32004-12-03 22:18:41 +0000703 LinkFromSrc = true;
704 LT = Src->getLinkage();
705 } else {
706 LinkFromSrc = false;
707 LT = Dest->getLinkage();
708 }
Duncan Sandsd725c992009-03-08 13:35:23 +0000709 } else if (Dest->isWeakForLinker()) {
Anton Korobeynikov12c94942006-12-01 00:25:12 +0000710 // At this point we know that Src has External* or DLL* linkage.
711 if (Src->hasExternalWeakLinkage()) {
712 LinkFromSrc = false;
713 LT = Dest->getLinkage();
714 } else {
715 LinkFromSrc = true;
716 LT = GlobalValue::ExternalLinkage;
717 }
Chris Lattnerfc61de32004-12-03 22:18:41 +0000718 } else {
Nico Rieck7157bb72014-01-14 15:22:47 +0000719 assert((Dest->hasExternalLinkage() || Dest->hasExternalWeakLinkage()) &&
720 (Src->hasExternalLinkage() || Src->hasExternalWeakLinkage()) &&
Chris Lattnerfc61de32004-12-03 22:18:41 +0000721 "Unexpected linkage type!");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000722 return emitError("Linking globals named '" + Src->getName() +
Chris Lattnerfc61de32004-12-03 22:18:41 +0000723 "': symbol multiply defined!");
724 }
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000725
Rafael Espindola23f8d642012-01-05 23:02:01 +0000726 // Compute the visibility. We follow the rules in the System V Application
727 // Binary Interface.
Duncan P. N. Exon Smithb2becfd2014-05-07 22:55:46 +0000728 assert(!GlobalValue::isLocalLinkage(LT) &&
729 "Symbols with local linkage should not be merged");
Rafael Espindola23f8d642012-01-05 23:02:01 +0000730 Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
731 Dest->getVisibility() : Src->getVisibility();
Chris Lattnerfc61de32004-12-03 22:18:41 +0000732 return false;
733}
Reid Spencer361e5132004-11-12 20:37:43 +0000734
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000735/// computeTypeMapping - Loop over all of the linked values to compute type
736/// mappings. For example, if we link "extern Foo *x" and "Foo *x = NULL", then
737/// we have two struct types 'Foo' but one got renamed when the module was
738/// loaded into the same LLVMContext.
739void ModuleLinker::computeTypeMapping() {
740 // Incorporate globals.
741 for (Module::global_iterator I = SrcM->global_begin(),
742 E = SrcM->global_end(); I != E; ++I) {
743 GlobalValue *DGV = getLinkedToGlobal(I);
Craig Topper2617dcc2014-04-15 06:32:26 +0000744 if (!DGV) continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000745
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000746 if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
747 TypeMap.addTypeMapping(DGV->getType(), I->getType());
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000748 continue;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000749 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000750
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000751 // Unify the element type of appending arrays.
752 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
753 ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
754 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
Devang Patel5c310be2009-08-11 18:01:24 +0000755 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000756
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000757 // Incorporate functions.
758 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
759 if (GlobalValue *DGV = getLinkedToGlobal(I))
760 TypeMap.addTypeMapping(DGV->getType(), I->getType());
761 }
Bill Wendling7b464612012-02-27 22:34:19 +0000762
Bill Wendlingd48b7782012-02-28 04:01:21 +0000763 // Incorporate types by name, scanning all the types in the source module.
764 // At this point, the destination module may have a type "%foo = { i32 }" for
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000765 // example. When the source module got loaded into the same LLVMContext, if
766 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
Bill Wendling8555a372012-08-03 00:30:35 +0000767 TypeFinder SrcStructTypes;
768 SrcStructTypes.run(*SrcM, true);
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000769 SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
770 SrcStructTypes.end());
Bill Wendling87374802012-03-23 23:17:38 +0000771
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000772 for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
773 StructType *ST = SrcStructTypes[i];
774 if (!ST->hasName()) continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000775
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000776 // Check to see if there is a dot in the name followed by a digit.
Bill Wendlingd48b7782012-02-28 04:01:21 +0000777 size_t DotPos = ST->getName().rfind('.');
778 if (DotPos == 0 || DotPos == StringRef::npos ||
Guy Benyei83c74e92013-02-12 21:21:59 +0000779 ST->getName().back() == '.' ||
780 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
Bill Wendlingd48b7782012-02-28 04:01:21 +0000781 continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000782
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000783 // Check to see if the destination module has a struct with the prefix name.
Bill Wendlingd48b7782012-02-28 04:01:21 +0000784 if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
Bill Wendling87374802012-03-23 23:17:38 +0000785 // Don't use it if this actually came from the source module. They're in
786 // the same LLVMContext after all. Also don't use it unless the type is
787 // actually used in the destination module. This can happen in situations
788 // like this:
789 //
790 // Module A Module B
791 // -------- --------
792 // %Z = type { %A } %B = type { %C.1 }
793 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
794 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
795 // %C = type { i8* } %B.3 = type { %C.1 }
796 //
797 // When we link Module B with Module A, the '%B' in Module B is
798 // used. However, that would then use '%C.1'. But when we process '%C.1',
799 // we prefer to take the '%C' version. So we are then left with both
800 // '%C.1' and '%C' being used for the same types. This leads to some
801 // variables using one type and some using the other.
Rafael Espindolaaa9918a2013-05-04 05:05:18 +0000802 if (!SrcStructTypesSet.count(DST) && TypeMap.DstStructTypesSet.count(DST))
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000803 TypeMap.addTypeMapping(DST, ST);
804 }
805
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000806 // Don't bother incorporating aliases, they aren't generally typed well.
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000807
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000808 // Now that we have discovered all of the type equivalences, get a body for
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000809 // any 'opaque' types in the dest module that are now resolved.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000810 TypeMap.linkDefinedTypeBodies();
Devang Patel5c310be2009-08-11 18:01:24 +0000811}
812
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000813/// linkAppendingVarProto - If there were any appending global variables, link
814/// them together now. Return true on error.
815bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
816 GlobalVariable *SrcGV) {
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000817
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000818 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
819 return emitError("Linking globals named '" + SrcGV->getName() +
820 "': can only link appending global with another appending global!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000821
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000822 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
823 ArrayType *SrcTy =
824 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
825 Type *EltTy = DstTy->getElementType();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000826
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000827 // Check to see that they two arrays agree on type.
828 if (EltTy != SrcTy->getElementType())
829 return emitError("Appending variables with different element types!");
830 if (DstGV->isConstant() != SrcGV->isConstant())
831 return emitError("Appending variables linked with different const'ness!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000832
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000833 if (DstGV->getAlignment() != SrcGV->getAlignment())
834 return emitError(
835 "Appending variables with different alignment need to be linked!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000836
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000837 if (DstGV->getVisibility() != SrcGV->getVisibility())
838 return emitError(
839 "Appending variables with different visibility need to be linked!");
Rafael Espindolafac3a012013-09-04 15:33:34 +0000840
841 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
842 return emitError(
843 "Appending variables with different unnamed_addr need to be linked!");
844
Rafael Espindola64c1e182014-06-03 02:41:57 +0000845 if (StringRef(DstGV->getSection()) != SrcGV->getSection())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000846 return emitError(
847 "Appending variables with different section name need to be linked!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000848
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000849 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
850 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000851
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000852 // Create the new global variable.
853 GlobalVariable *NG =
854 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
Craig Topper2617dcc2014-04-15 06:32:26 +0000855 DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000856 DstGV->getThreadLocalMode(),
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000857 DstGV->getType()->getAddressSpace());
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000858
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000859 // Propagate alignment, visibility and section info.
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000860 copyGVAttributes(NG, DstGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000861
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000862 AppendingVarInfo AVI;
863 AVI.NewGV = NG;
864 AVI.DstInit = DstGV->getInitializer();
865 AVI.SrcInit = SrcGV->getInitializer();
866 AppendingVars.push_back(AVI);
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000867
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000868 // Replace any uses of the two global variables with uses of the new
869 // global.
870 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
Anton Korobeynikove79f4c72008-03-10 22:34:28 +0000871
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000872 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
873 DstGV->eraseFromParent();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000874
Tanya Lattnercbb91402011-10-11 00:24:54 +0000875 // Track the source variable so we don't try to link it.
876 DoNotLinkFromSource.insert(SrcGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000877
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000878 return false;
879}
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000880
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000881/// linkGlobalProto - Loop through the global variables in the src module and
882/// merge them into the dest module.
883bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
884 GlobalValue *DGV = getLinkedToGlobal(SGV);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000885 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Rafael Espindolad4885da2013-09-04 14:05:09 +0000886 bool HasUnnamedAddr = SGV->hasUnnamedAddr();
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000887
David Majnemerdad0a642014-06-27 18:19:56 +0000888 bool LinkFromSrc = false;
889 Comdat *DC = nullptr;
890 if (const Comdat *SC = SGV->getComdat()) {
891 Comdat::SelectionKind SK;
892 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
893 DC = DstM->getOrInsertComdat(SC->getName());
894 DC->setSelectionKind(SK);
895 }
896
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000897 if (DGV) {
David Majnemerdad0a642014-06-27 18:19:56 +0000898 if (!DC) {
899 // Concatenation of appending linkage variables is magic and handled later.
900 if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
901 return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000902
David Majnemerdad0a642014-06-27 18:19:56 +0000903 // Determine whether linkage of these two globals follows the source
904 // module's definition or the destination module's definition.
905 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
906 GlobalValue::VisibilityTypes NV;
907 if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
908 return true;
909 NewVisibility = NV;
910 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
Reid Spencer361e5132004-11-12 20:37:43 +0000911
David Majnemerdad0a642014-06-27 18:19:56 +0000912 // If we're not linking from the source, then keep the definition that we
913 // have.
914 if (!LinkFromSrc) {
915 // Special case for const propagation.
916 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
917 if (DGVar->isDeclaration() && SGV->isConstant() &&
918 !DGVar->isConstant())
919 DGVar->setConstant(true);
920
921 // Set calculated linkage, visibility and unnamed_addr.
922 DGV->setLinkage(NewLinkage);
923 DGV->setVisibility(*NewVisibility);
924 DGV->setUnnamedAddr(HasUnnamedAddr);
925 }
926 }
927
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000928 if (!LinkFromSrc) {
Chris Lattner0ead7a52008-07-14 07:23:24 +0000929 // Make sure to remember this mapping.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000930 ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000931
932 // Track the source global so that we don't attempt to copy it over when
Tanya Lattnercbb91402011-10-11 00:24:54 +0000933 // processing global initializers.
934 DoNotLinkFromSource.insert(SGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000935
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000936 return false;
Chris Lattner0ead7a52008-07-14 07:23:24 +0000937 }
Reid Spencer361e5132004-11-12 20:37:43 +0000938 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000939
David Majnemerdad0a642014-06-27 18:19:56 +0000940 // If the Comdat this variable was inside of wasn't selected, skip it.
941 if (DC && !DGV && !LinkFromSrc) {
942 DoNotLinkFromSource.insert(SGV);
943 return false;
944 }
945
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000946 // No linking to be performed or linking from the source: simply create an
947 // identical version of the symbol over in the dest module... the
948 // initializer will be filled in later by LinkGlobalInits.
949 GlobalVariable *NewDGV =
950 new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
Craig Topper2617dcc2014-04-15 06:32:26 +0000951 SGV->isConstant(), SGV->getLinkage(), /*init*/nullptr,
952 SGV->getName(), /*insertbefore*/nullptr,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000953 SGV->getThreadLocalMode(),
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000954 SGV->getType()->getAddressSpace());
955 // Propagate alignment, visibility and section info.
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000956 copyGVAttributes(NewDGV, SGV);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000957 if (NewVisibility)
958 NewDGV->setVisibility(*NewVisibility);
Rafael Espindolad4885da2013-09-04 14:05:09 +0000959 NewDGV->setUnnamedAddr(HasUnnamedAddr);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000960
David Majnemerdad0a642014-06-27 18:19:56 +0000961 if (DC)
962 NewDGV->setComdat(DC);
963
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000964 if (DGV) {
965 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
966 DGV->eraseFromParent();
967 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000968
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000969 // Make sure to remember this mapping.
970 ValueMap[SGV] = NewDGV;
Reid Spencer361e5132004-11-12 20:37:43 +0000971 return false;
972}
973
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000974/// linkFunctionProto - Link the function in the source module into the
975/// destination module if needed, setting up mapping information.
976bool ModuleLinker::linkFunctionProto(Function *SF) {
977 GlobalValue *DGV = getLinkedToGlobal(SF);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000978 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Rafael Espindolafd9a9412013-09-04 14:59:03 +0000979 bool HasUnnamedAddr = SF->hasUnnamedAddr();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000980
David Majnemerdad0a642014-06-27 18:19:56 +0000981 bool LinkFromSrc = false;
982 Comdat *DC = nullptr;
983 if (const Comdat *SC = SF->getComdat()) {
984 Comdat::SelectionKind SK;
985 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
986 DC = DstM->getOrInsertComdat(SC->getName());
987 DC->setSelectionKind(SK);
988 }
989
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000990 if (DGV) {
David Majnemerdad0a642014-06-27 18:19:56 +0000991 if (!DC) {
992 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
993 GlobalValue::VisibilityTypes NV;
994 if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
995 return true;
996 NewVisibility = NV;
997 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
998
999 if (!LinkFromSrc) {
1000 // Set calculated linkage
1001 DGV->setLinkage(NewLinkage);
1002 DGV->setVisibility(*NewVisibility);
1003 DGV->setUnnamedAddr(HasUnnamedAddr);
1004 }
1005 }
Rafael Espindola23f8d642012-01-05 23:02:01 +00001006
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001007 if (!LinkFromSrc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001008 // Make sure to remember this mapping.
1009 ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001010
1011 // Track the function from the source module so we don't attempt to remap
Tanya Lattnercbb91402011-10-11 00:24:54 +00001012 // it.
1013 DoNotLinkFromSource.insert(SF);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001014
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001015 return false;
1016 }
Anton Korobeynikovdac5fa92008-03-05 22:22:46 +00001017 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001018
James Molloyf6f121e2013-05-28 15:17:05 +00001019 // If the function is to be lazily linked, don't create it just yet.
1020 // The ValueMaterializerTy will deal with creating it if it's used.
1021 if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
1022 SF->hasAvailableExternallyLinkage())) {
1023 DoNotLinkFromSource.insert(SF);
1024 return false;
1025 }
1026
David Majnemerdad0a642014-06-27 18:19:56 +00001027 // If the Comdat this function was inside of wasn't selected, skip it.
1028 if (DC && !DGV && !LinkFromSrc) {
1029 DoNotLinkFromSource.insert(SF);
1030 return false;
1031 }
1032
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001033 // If there is no linkage to be performed or we are linking from the source,
1034 // bring SF over.
1035 Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
1036 SF->getLinkage(), SF->getName(), DstM);
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001037 copyGVAttributes(NewDF, SF);
Rafael Espindola23f8d642012-01-05 23:02:01 +00001038 if (NewVisibility)
1039 NewDF->setVisibility(*NewVisibility);
Rafael Espindolafd9a9412013-09-04 14:59:03 +00001040 NewDF->setUnnamedAddr(HasUnnamedAddr);
Anton Korobeynikovdac5fa92008-03-05 22:22:46 +00001041
David Majnemerdad0a642014-06-27 18:19:56 +00001042 if (DC)
1043 NewDF->setComdat(DC);
1044
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001045 if (DGV) {
1046 // Any uses of DF need to change to NewDF, with cast.
1047 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
1048 DGV->eraseFromParent();
Lauro Ramos Venanciob00c9c02007-06-28 19:02:54 +00001049 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001050
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001051 ValueMap[SF] = NewDF;
Lauro Ramos Venanciob00c9c02007-06-28 19:02:54 +00001052 return false;
1053}
1054
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001055/// LinkAliasProto - Set up prototypes for any aliases that come over from the
1056/// source module.
1057bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
1058 GlobalValue *DGV = getLinkedToGlobal(SGA);
Rafael Espindola23f8d642012-01-05 23:02:01 +00001059 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +00001060 bool HasUnnamedAddr = SGA->hasUnnamedAddr();
Rafael Espindola23f8d642012-01-05 23:02:01 +00001061
David Majnemerdad0a642014-06-27 18:19:56 +00001062 bool LinkFromSrc = false;
1063 Comdat *DC = nullptr;
1064 if (const Comdat *SC = SGA->getComdat()) {
1065 Comdat::SelectionKind SK;
1066 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1067 DC = DstM->getOrInsertComdat(SC->getName());
1068 DC->setSelectionKind(SK);
1069 }
1070
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001071 if (DGV) {
David Majnemerdad0a642014-06-27 18:19:56 +00001072 if (!DC) {
1073 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
1074 GlobalValue::VisibilityTypes NV;
1075 if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
1076 return true;
1077 NewVisibility = NV;
1078 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1079
1080 if (!LinkFromSrc) {
1081 // Set calculated linkage.
1082 DGV->setLinkage(NewLinkage);
1083 DGV->setVisibility(*NewVisibility);
1084 DGV->setUnnamedAddr(HasUnnamedAddr);
1085 }
1086 }
Rafael Espindola23f8d642012-01-05 23:02:01 +00001087
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001088 if (!LinkFromSrc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001089 // Make sure to remember this mapping.
1090 ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001091
Tanya Lattnercbb91402011-10-11 00:24:54 +00001092 // Track the alias from the source module so we don't attempt to remap it.
1093 DoNotLinkFromSource.insert(SGA);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001094
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001095 return false;
1096 }
1097 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001098
David Majnemerdad0a642014-06-27 18:19:56 +00001099 // If the Comdat this alias was inside of wasn't selected, skip it.
1100 if (DC && !DGV && !LinkFromSrc) {
1101 DoNotLinkFromSource.insert(SGA);
1102 return false;
1103 }
1104
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001105 // If there is no linkage to be performed or we're linking from the source,
1106 // bring over SGA.
Rafael Espindola4fe00942014-05-16 13:34:04 +00001107 auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType()));
Rafael Espindolaf1bedd3742014-05-17 21:29:57 +00001108 auto *NewDA =
1109 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
1110 SGA->getLinkage(), SGA->getName(), DstM);
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001111 copyGVAttributes(NewDA, SGA);
Rafael Espindola23f8d642012-01-05 23:02:01 +00001112 if (NewVisibility)
1113 NewDA->setVisibility(*NewVisibility);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +00001114 NewDA->setUnnamedAddr(HasUnnamedAddr);
Reid Spencer361e5132004-11-12 20:37:43 +00001115
Rafael Espindola64c1e182014-06-03 02:41:57 +00001116 if (DGV) {
1117 // Any uses of DGV need to change to NewDA, with cast.
1118 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
1119 DGV->eraseFromParent();
1120 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001121
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001122 ValueMap[SGA] = NewDA;
1123 return false;
1124}
1125
Chris Lattner00245f42012-01-24 13:41:11 +00001126static void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest) {
Chris Lattner67058832012-01-25 06:48:06 +00001127 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
1128
1129 for (unsigned i = 0; i != NumElements; ++i)
1130 Dest.push_back(C->getAggregateElement(i));
Chris Lattner00245f42012-01-24 13:41:11 +00001131}
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001132
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001133void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
1134 // Merge the initializer.
1135 SmallVector<Constant*, 16> Elements;
Chris Lattner00245f42012-01-24 13:41:11 +00001136 getArrayElements(AVI.DstInit, Elements);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001137
James Molloyf6f121e2013-05-28 15:17:05 +00001138 Constant *SrcInit = MapValue(AVI.SrcInit, ValueMap, RF_None, &TypeMap, &ValMaterializer);
Chris Lattner00245f42012-01-24 13:41:11 +00001139 getArrayElements(SrcInit, Elements);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001140
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001141 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
1142 AVI.NewGV->setInitializer(ConstantArray::get(NewType, Elements));
1143}
1144
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001145/// linkGlobalInits - Update the initializers in the Dest module now that all
1146/// globals that may be referenced are in Dest.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001147void ModuleLinker::linkGlobalInits() {
Reid Spencer361e5132004-11-12 20:37:43 +00001148 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001149 for (Module::const_global_iterator I = SrcM->global_begin(),
1150 E = SrcM->global_end(); I != E; ++I) {
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001151
Tanya Lattnercbb91402011-10-11 00:24:54 +00001152 // Only process initialized GV's or ones not already in dest.
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001153 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
1154
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001155 // Grab destination global variable.
1156 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
1157 // Figure out what the initializer looks like in the dest module.
1158 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
James Molloyf6f121e2013-05-28 15:17:05 +00001159 RF_None, &TypeMap, &ValMaterializer));
Reid Spencer361e5132004-11-12 20:37:43 +00001160 }
Reid Spencer361e5132004-11-12 20:37:43 +00001161}
1162
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001163/// linkFunctionBody - Copy the source function over into the dest function and
1164/// fix up references to values. At this point we know that Dest is an external
1165/// function, and that Src is not.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001166void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
1167 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
Reid Spencer361e5132004-11-12 20:37:43 +00001168
Chris Lattner7391dde2004-11-16 17:12:38 +00001169 // Go through and convert function arguments over, remembering the mapping.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001170 Function::arg_iterator DI = Dst->arg_begin();
Chris Lattner531f9e92005-03-15 04:54:21 +00001171 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
Reid Spencer361e5132004-11-12 20:37:43 +00001172 I != E; ++I, ++DI) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001173 DI->setName(I->getName()); // Copy the name over.
Reid Spencer361e5132004-11-12 20:37:43 +00001174
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001175 // Add a mapping to our mapping.
Anton Korobeynikov66a62712008-03-10 22:36:08 +00001176 ValueMap[I] = DI;
Reid Spencer361e5132004-11-12 20:37:43 +00001177 }
1178
Tanya Lattnercbb91402011-10-11 00:24:54 +00001179 if (Mode == Linker::DestroySource) {
1180 // Splice the body of the source function into the dest function.
1181 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001182
Tanya Lattnercbb91402011-10-11 00:24:54 +00001183 // At this point, all of the instructions and values of the function are now
1184 // copied over. The only problem is that they are still referencing values in
1185 // the Source function as operands. Loop through all of the operands of the
1186 // functions and patch them up to point to the local versions.
1187 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
1188 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
James Molloyf6f121e2013-05-28 15:17:05 +00001189 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries,
1190 &TypeMap, &ValMaterializer);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001191
Tanya Lattnercbb91402011-10-11 00:24:54 +00001192 } else {
1193 // Clone the body of the function into the dest function.
1194 SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
Craig Topper2617dcc2014-04-15 06:32:26 +00001195 CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", nullptr,
James Molloyf6f121e2013-05-28 15:17:05 +00001196 &TypeMap, &ValMaterializer);
Tanya Lattnercbb91402011-10-11 00:24:54 +00001197 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001198
Chris Lattner7391dde2004-11-16 17:12:38 +00001199 // There is no need to map the arguments anymore.
Chris Lattner44ab8ae2006-06-16 01:24:04 +00001200 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1201 I != E; ++I)
Reid Spencer3aaaa0b2007-02-05 20:47:22 +00001202 ValueMap.erase(I);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001203
Reid Spencer361e5132004-11-12 20:37:43 +00001204}
1205
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001206/// linkAliasBodies - Insert all of the aliases in Src into the Dest module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001207void ModuleLinker::linkAliasBodies() {
1208 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
Tanya Lattnercbb91402011-10-11 00:24:54 +00001209 I != E; ++I) {
1210 if (DoNotLinkFromSource.count(I))
1211 continue;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001212 if (Constant *Aliasee = I->getAliasee()) {
1213 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
Rafael Espindola6b238632014-05-16 19:35:39 +00001214 Constant *Val =
1215 MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer);
Rafael Espindola64c1e182014-06-03 02:41:57 +00001216 DA->setAliasee(Val);
David Chisnall2c4a34a2010-01-09 16:27:31 +00001217 }
Tanya Lattnercbb91402011-10-11 00:24:54 +00001218 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001219}
Anton Korobeynikov26098882008-03-05 23:21:39 +00001220
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001221/// linkNamedMDNodes - Insert all of the named MDNodes in Src into the Dest
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001222/// module.
1223void ModuleLinker::linkNamedMDNodes() {
Bill Wendling66f02412012-02-11 11:38:06 +00001224 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001225 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1226 E = SrcM->named_metadata_end(); I != E; ++I) {
Bill Wendling66f02412012-02-11 11:38:06 +00001227 // Don't link module flags here. Do them separately.
1228 if (&*I == SrcModFlags) continue;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001229 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1230 // Add Src elements into Dest node.
1231 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1232 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
James Molloyf6f121e2013-05-28 15:17:05 +00001233 RF_None, &TypeMap, &ValMaterializer));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001234 }
1235}
Bill Wendling66f02412012-02-11 11:38:06 +00001236
Bill Wendling66f02412012-02-11 11:38:06 +00001237/// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest
1238/// module.
1239bool ModuleLinker::linkModuleFlagsMetadata() {
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001240 // If the source module has no module flags, we are done.
Bill Wendling66f02412012-02-11 11:38:06 +00001241 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1242 if (!SrcModFlags) return false;
1243
Bill Wendling66f02412012-02-11 11:38:06 +00001244 // If the destination module doesn't have module flags yet, then just copy
1245 // over the source module's flags.
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001246 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
Bill Wendling66f02412012-02-11 11:38:06 +00001247 if (DstModFlags->getNumOperands() == 0) {
1248 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1249 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1250
1251 return false;
1252 }
1253
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001254 // First build a map of the existing module flags and requirements.
1255 DenseMap<MDString*, MDNode*> Flags;
1256 SmallSetVector<MDNode*, 16> Requirements;
1257 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1258 MDNode *Op = DstModFlags->getOperand(I);
1259 ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1260 MDString *ID = cast<MDString>(Op->getOperand(1));
Bill Wendling66f02412012-02-11 11:38:06 +00001261
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001262 if (Behavior->getZExtValue() == Module::Require) {
1263 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1264 } else {
1265 Flags[ID] = Op;
1266 }
Bill Wendling66f02412012-02-11 11:38:06 +00001267 }
1268
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001269 // Merge in the flags from the source module, and also collect its set of
1270 // requirements.
1271 bool HasErr = false;
1272 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1273 MDNode *SrcOp = SrcModFlags->getOperand(I);
1274 ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1275 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1276 MDNode *DstOp = Flags.lookup(ID);
1277 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
Bill Wendling66f02412012-02-11 11:38:06 +00001278
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001279 // If this is a requirement, add it and continue.
1280 if (SrcBehaviorValue == Module::Require) {
1281 // If the destination module does not already have this requirement, add
1282 // it.
1283 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1284 DstModFlags->addOperand(SrcOp);
1285 }
1286 continue;
Bill Wendling66f02412012-02-11 11:38:06 +00001287 }
1288
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001289 // If there is no existing flag with this ID, just add it.
1290 if (!DstOp) {
1291 Flags[ID] = SrcOp;
1292 DstModFlags->addOperand(SrcOp);
1293 continue;
1294 }
1295
1296 // Otherwise, perform a merge.
1297 ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1298 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1299
1300 // If either flag has override behavior, handle it first.
1301 if (DstBehaviorValue == Module::Override) {
1302 // Diagnose inconsistent flags which both have override behavior.
1303 if (SrcBehaviorValue == Module::Override &&
1304 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1305 HasErr |= emitError("linking module flags '" + ID->getString() +
1306 "': IDs have conflicting override values");
1307 }
1308 continue;
1309 } else if (SrcBehaviorValue == Module::Override) {
1310 // Update the destination flag to that of the source.
1311 DstOp->replaceOperandWith(0, SrcBehavior);
1312 DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1313 continue;
1314 }
1315
1316 // Diagnose inconsistent merge behavior types.
1317 if (SrcBehaviorValue != DstBehaviorValue) {
1318 HasErr |= emitError("linking module flags '" + ID->getString() +
1319 "': IDs have conflicting behaviors");
1320 continue;
1321 }
1322
1323 // Perform the merge for standard behavior types.
1324 switch (SrcBehaviorValue) {
1325 case Module::Require:
Craig Topper2a30d782014-06-18 05:05:13 +00001326 case Module::Override: llvm_unreachable("not possible");
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001327 case Module::Error: {
1328 // Emit an error if the values differ.
1329 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1330 HasErr |= emitError("linking module flags '" + ID->getString() +
1331 "': IDs have conflicting values");
1332 }
1333 continue;
1334 }
1335 case Module::Warning: {
1336 // Emit a warning if the values differ.
1337 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
Eli Benderskye17f3702014-02-06 18:01:56 +00001338 if (!SuppressWarnings) {
1339 errs() << "WARNING: linking module flags '" << ID->getString()
1340 << "': IDs have conflicting values";
1341 }
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001342 }
1343 continue;
1344 }
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001345 case Module::Append: {
1346 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1347 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1348 unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1349 Value **VP, **Values = VP = new Value*[NumOps];
1350 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1351 *VP = DstValue->getOperand(i);
1352 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1353 *VP = SrcValue->getOperand(i);
1354 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1355 ArrayRef<Value*>(Values,
1356 NumOps)));
1357 delete[] Values;
1358 break;
1359 }
1360 case Module::AppendUnique: {
1361 SmallSetVector<Value*, 16> Elts;
1362 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1363 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1364 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1365 Elts.insert(DstValue->getOperand(i));
1366 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1367 Elts.insert(SrcValue->getOperand(i));
1368 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1369 ArrayRef<Value*>(Elts.begin(),
1370 Elts.end())));
1371 break;
1372 }
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001373 }
Bill Wendling66f02412012-02-11 11:38:06 +00001374 }
1375
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001376 // Check all of the requirements.
1377 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1378 MDNode *Requirement = Requirements[I];
1379 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1380 Value *ReqValue = Requirement->getOperand(1);
Bill Wendling66f02412012-02-11 11:38:06 +00001381
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001382 MDNode *Op = Flags[Flag];
1383 if (!Op || Op->getOperand(2) != ReqValue) {
1384 HasErr |= emitError("linking module flags '" + Flag->getString() +
1385 "': does not have the required value");
1386 continue;
Bill Wendling66f02412012-02-11 11:38:06 +00001387 }
1388 }
1389
1390 return HasErr;
1391}
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001392
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001393bool ModuleLinker::run() {
Bill Wendling66f02412012-02-11 11:38:06 +00001394 assert(DstM && "Null destination module");
1395 assert(SrcM && "Null source module");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001396
1397 // Inherit the target data from the source module if the destination module
1398 // doesn't have one already.
Rafael Espindolaf863ee22014-02-25 20:01:08 +00001399 if (!DstM->getDataLayout() && SrcM->getDataLayout())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001400 DstM->setDataLayout(SrcM->getDataLayout());
1401
1402 // Copy the target triple from the source to dest if the dest's is empty.
1403 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1404 DstM->setTargetTriple(SrcM->getTargetTriple());
1405
Rafael Espindolaf863ee22014-02-25 20:01:08 +00001406 if (SrcM->getDataLayout() && DstM->getDataLayout() &&
Rafael Espindolaae593f12014-02-26 17:02:08 +00001407 *SrcM->getDataLayout() != *DstM->getDataLayout()) {
Eli Benderskye17f3702014-02-06 18:01:56 +00001408 if (!SuppressWarnings) {
JF Bastien026fc5f2014-03-05 21:26:42 +00001409 errs() << "WARNING: Linking two modules of different data layouts: '"
1410 << SrcM->getModuleIdentifier() << "' is '"
1411 << SrcM->getDataLayoutStr() << "' whereas '"
1412 << DstM->getModuleIdentifier() << "' is '"
1413 << DstM->getDataLayoutStr() << "'\n";
Eli Benderskye17f3702014-02-06 18:01:56 +00001414 }
1415 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001416 if (!SrcM->getTargetTriple().empty() &&
1417 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
Eli Benderskye17f3702014-02-06 18:01:56 +00001418 if (!SuppressWarnings) {
JF Bastien026fc5f2014-03-05 21:26:42 +00001419 errs() << "WARNING: Linking two modules of different target triples: "
1420 << SrcM->getModuleIdentifier() << "' is '"
1421 << SrcM->getTargetTriple() << "' whereas '"
1422 << DstM->getModuleIdentifier() << "' is '"
Eli Benderskye17f3702014-02-06 18:01:56 +00001423 << DstM->getTargetTriple() << "'\n";
1424 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001425 }
1426
1427 // Append the module inline asm string.
1428 if (!SrcM->getModuleInlineAsm().empty()) {
1429 if (DstM->getModuleInlineAsm().empty())
1430 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1431 else
1432 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1433 SrcM->getModuleInlineAsm());
1434 }
1435
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001436 // Loop over all of the linked values to compute type mappings.
1437 computeTypeMapping();
1438
David Majnemerdad0a642014-06-27 18:19:56 +00001439 ComdatsChosen.clear();
1440 for (const StringMapEntry<llvm::Comdat> &SMEC : SrcM->getComdatSymbolTable()) {
1441 const Comdat &C = SMEC.getValue();
1442 if (ComdatsChosen.count(&C))
1443 continue;
1444 Comdat::SelectionKind SK;
1445 bool LinkFromSrc;
1446 if (getComdatResult(&C, SK, LinkFromSrc))
1447 return true;
1448 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1449 }
1450
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001451 // Insert all of the globals in src into the DstM module... without linking
1452 // initializers (which could refer to functions not yet mapped over).
1453 for (Module::global_iterator I = SrcM->global_begin(),
1454 E = SrcM->global_end(); I != E; ++I)
1455 if (linkGlobalProto(I))
1456 return true;
1457
1458 // Link the functions together between the two modules, without doing function
1459 // bodies... this just adds external function prototypes to the DstM
1460 // function... We do this so that when we begin processing function bodies,
1461 // all of the global values that may be referenced are available in our
1462 // ValueMap.
1463 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1464 if (linkFunctionProto(I))
1465 return true;
1466
1467 // If there were any aliases, link them now.
1468 for (Module::alias_iterator I = SrcM->alias_begin(),
1469 E = SrcM->alias_end(); I != E; ++I)
1470 if (linkAliasProto(I))
1471 return true;
1472
1473 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1474 linkAppendingVarInit(AppendingVars[i]);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001475
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001476 // Link in the function bodies that are defined in the source module into
1477 // DstM.
1478 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
Tanya Lattnerea166d42011-10-14 22:17:46 +00001479 // Skip if not linking from source.
1480 if (DoNotLinkFromSource.count(SF)) continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001481
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001482 Function *DF = cast<Function>(ValueMap[SF]);
1483 if (SF->hasPrefixData()) {
1484 // Link in the prefix data.
1485 DF->setPrefixData(MapValue(
1486 SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
1487 }
1488
Tanya Lattnerea166d42011-10-14 22:17:46 +00001489 // Skip if no body (function is external) or materialize.
1490 if (SF->isDeclaration()) {
1491 if (!SF->isMaterializable())
1492 continue;
1493 if (SF->Materialize(&ErrorMsg))
1494 return true;
1495 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001496
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001497 linkFunctionBody(DF, SF);
Bill Wendling00623782012-03-23 07:22:49 +00001498 SF->Dematerialize();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001499 }
1500
1501 // Resolve all uses of aliases with aliasees.
1502 linkAliasBodies();
1503
Bill Wendling66f02412012-02-11 11:38:06 +00001504 // Remap all of the named MDNodes in Src into the DstM module. We do this
Devang Patel6ddbb2e2011-08-04 19:44:28 +00001505 // after linking GlobalValues so that MDNodes that reference GlobalValues
1506 // are properly remapped.
1507 linkNamedMDNodes();
1508
Bill Wendling66f02412012-02-11 11:38:06 +00001509 // Merge the module flags into the DstM module.
1510 if (linkModuleFlagsMetadata())
1511 return true;
1512
Bill Wendling91686d62014-01-16 06:29:36 +00001513 // Update the initializers in the DstM module now that all globals that may
1514 // be referenced are in DstM.
1515 linkGlobalInits();
1516
Tanya Lattner0a48b872011-11-02 00:24:56 +00001517 // Process vector of lazily linked in functions.
1518 bool LinkedInAnyFunctions;
1519 do {
1520 LinkedInAnyFunctions = false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001521
Bill Wendlingfa2287822013-03-27 17:54:41 +00001522 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001523 E = LazilyLinkFunctions.end(); I != E; ++I) {
Bill Wendlingfa2287822013-03-27 17:54:41 +00001524 Function *SF = *I;
James Molloyf6f121e2013-05-28 15:17:05 +00001525 if (!SF)
1526 continue;
Bill Wendling00623782012-03-23 07:22:49 +00001527
James Molloyf6f121e2013-05-28 15:17:05 +00001528 Function *DF = cast<Function>(ValueMap[SF]);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001529 if (SF->hasPrefixData()) {
1530 // Link in the prefix data.
1531 DF->setPrefixData(MapValue(SF->getPrefixData(),
1532 ValueMap,
1533 RF_None,
1534 &TypeMap,
1535 &ValMaterializer));
1536 }
James Molloyf6f121e2013-05-28 15:17:05 +00001537
1538 // Materialize if necessary.
1539 if (SF->isDeclaration()) {
1540 if (!SF->isMaterializable())
1541 continue;
1542 if (SF->Materialize(&ErrorMsg))
1543 return true;
Tanya Lattner0a48b872011-11-02 00:24:56 +00001544 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001545
James Molloyf6f121e2013-05-28 15:17:05 +00001546 // Erase from vector *before* the function body is linked - linkFunctionBody could
1547 // invalidate I.
1548 LazilyLinkFunctions.erase(I);
1549
1550 // Link in function body.
1551 linkFunctionBody(DF, SF);
1552 SF->Dematerialize();
1553
1554 // Set flag to indicate we may have more functions to lazily link in
1555 // since we linked in a function.
1556 LinkedInAnyFunctions = true;
1557 break;
Tanya Lattner0a48b872011-11-02 00:24:56 +00001558 }
1559 } while (LinkedInAnyFunctions);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001560
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001561 // Now that all of the types from the source are used, resolve any structs
1562 // copied over to the dest that didn't exist there.
1563 TypeMap.linkDefinedTypeBodies();
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001564
Anton Korobeynikov26098882008-03-05 23:21:39 +00001565 return false;
1566}
Reid Spencer361e5132004-11-12 20:37:43 +00001567
Eli Bendersky7da92ed2014-02-20 22:19:24 +00001568Linker::Linker(Module *M, bool SuppressWarnings)
1569 : Composite(M), SuppressWarnings(SuppressWarnings) {
Rafael Espindolaaa9918a2013-05-04 05:05:18 +00001570 TypeFinder StructTypes;
1571 StructTypes.run(*M, true);
1572 IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end());
1573}
Rafael Espindola3df61b72013-05-04 03:48:37 +00001574
1575Linker::~Linker() {
1576}
1577
Bill Wendling91e6f6e2013-10-16 08:59:57 +00001578void Linker::deleteModule() {
1579 delete Composite;
Craig Topper2617dcc2014-04-15 06:32:26 +00001580 Composite = nullptr;
Bill Wendling91e6f6e2013-10-16 08:59:57 +00001581}
1582
Rafael Espindola3df61b72013-05-04 03:48:37 +00001583bool Linker::linkInModule(Module *Src, unsigned Mode, std::string *ErrorMsg) {
Eli Bendersky7da92ed2014-02-20 22:19:24 +00001584 ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src, Mode,
1585 SuppressWarnings);
Rafael Espindola287f18b2013-05-04 04:08:02 +00001586 if (TheLinker.run()) {
1587 if (ErrorMsg)
1588 *ErrorMsg = TheLinker.ErrorMsg;
1589 return true;
1590 }
1591 return false;
Rafael Espindola3df61b72013-05-04 03:48:37 +00001592}
1593
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001594//===----------------------------------------------------------------------===//
1595// LinkModules entrypoint.
1596//===----------------------------------------------------------------------===//
1597
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001598/// LinkModules - This function links two modules together, with the resulting
Eli Bendersky970cc632013-03-08 22:29:44 +00001599/// Dest module modified to be the composite of the two input modules. If an
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001600/// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1601/// the problem. Upon failure, the Dest module could be in a modified state,
1602/// and shouldn't be relied on to be consistent.
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001603bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode,
Tanya Lattnercbb91402011-10-11 00:24:54 +00001604 std::string *ErrorMsg) {
Rafael Espindola287f18b2013-05-04 04:08:02 +00001605 Linker L(Dest);
1606 return L.linkInModule(Src, Mode, ErrorMsg);
Reid Spencer361e5132004-11-12 20:37:43 +00001607}
Bill Wendlinga3aeb982012-05-09 08:55:40 +00001608
1609//===----------------------------------------------------------------------===//
1610// C API.
1611//===----------------------------------------------------------------------===//
1612
1613LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1614 LLVMLinkerMode Mode, char **OutMessages) {
1615 std::string Messages;
1616 LLVMBool Result = Linker::LinkModules(unwrap(Dest), unwrap(Src),
Craig Topper2617dcc2014-04-15 06:32:26 +00001617 Mode, OutMessages? &Messages : nullptr);
Bill Wendlinga3aeb982012-05-09 08:55:40 +00001618 if (OutMessages)
1619 *OutMessages = strdup(Messages.c_str());
1620 return Result;
1621}