blob: ecfb9431974efb1f3decc5b0d2683f246e16a6f1 [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"
Rafael Espindolad12b4a32014-10-25 04:06:10 +000020#include "llvm/IR/DiagnosticInfo.h"
21#include "llvm/IR/DiagnosticPrinter.h"
22#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Module.h"
Chandler Carruthdcb603f2013-01-07 15:43:51 +000024#include "llvm/IR/TypeFinder.h"
Eli Benderskye17f3702014-02-06 18:01:56 +000025#include "llvm/Support/CommandLine.h"
Bill Wendlingb6af2f32012-03-22 20:28:27 +000026#include "llvm/Support/Debug.h"
Bill Wendlingb6af2f32012-03-22 20:28:27 +000027#include "llvm/Support/raw_ostream.h"
Tanya Lattnercbb91402011-10-11 00:24:54 +000028#include "llvm/Transforms/Utils/Cloning.h"
Will Dietz981af002013-10-12 00:55:57 +000029#include <cctype>
David Majnemer82d6ff62014-06-27 18:38:12 +000030#include <tuple>
Reid Spencer361e5132004-11-12 20:37:43 +000031using namespace llvm;
32
Eli Benderskye17f3702014-02-06 18:01:56 +000033
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000034//===----------------------------------------------------------------------===//
35// TypeMap implementation.
36//===----------------------------------------------------------------------===//
Reid Spencer361e5132004-11-12 20:37:43 +000037
Chris Lattnereee6f992008-06-16 21:00:18 +000038namespace {
Rafael Espindola18c89412014-10-27 02:35:46 +000039typedef SmallPtrSet<StructType *, 32> TypeSet;
Rafael Espindolaaa9918a2013-05-04 05:05:18 +000040
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000041class TypeMapTy : public ValueMapTypeRemapper {
Rafael Espindola18c89412014-10-27 02:35:46 +000042 /// This is a mapping from a source type to a destination type to use.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000043 DenseMap<Type*, Type*> MappedTypes;
Mikhail Glushenkov766d4892009-03-03 07:22:23 +000044
Rafael Espindola18c89412014-10-27 02:35:46 +000045 /// When checking to see if two subgraphs are isomorphic, we speculatively
46 /// add types to MappedTypes, but keep track of them here in case we need to
47 /// roll back.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000048 SmallVector<Type*, 16> SpeculativeTypes;
Rafael Espindolaed6dc372014-05-09 14:39:25 +000049
Rafael Espindolaa96f2352014-11-28 16:41:24 +000050 SmallVector<StructType*, 16> SpeculativeDstOpaqueTypes;
51
Rafael Espindola18c89412014-10-27 02:35:46 +000052 /// This is a list of non-opaque structs in the source module that are mapped
53 /// to an opaque struct in the destination module.
Chris Lattner5e3bd972011-12-20 00:03:52 +000054 SmallVector<StructType*, 16> SrcDefinitionsToResolve;
Rafael Espindolaed6dc372014-05-09 14:39:25 +000055
Rafael Espindola18c89412014-10-27 02:35:46 +000056 /// This is the set of opaque types in the destination modules who are
57 /// getting a body from the source module.
Chris Lattner5e3bd972011-12-20 00:03:52 +000058 SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
Bill Wendling8c2cc412012-03-22 20:30:41 +000059
Chris Lattner56cdea62008-06-16 23:06:51 +000060public:
Rafael Espindolaa4e85e32014-12-01 16:32:20 +000061 TypeMapTy(TypeSet &Set) : DstStructTypesSet(Set) {}
Rafael Espindolaaa9918a2013-05-04 05:05:18 +000062
Rafael Espindolaa4e85e32014-12-01 16:32:20 +000063 TypeSet &DstStructTypesSet;
Rafael Espindola18c89412014-10-27 02:35:46 +000064 /// Indicate that the specified type in the destination module is conceptually
65 /// equivalent to the specified type in the source module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000066 void addTypeMapping(Type *DstTy, Type *SrcTy);
67
Rafael Espindolad2a13a22014-11-25 04:28:31 +000068 /// Produce a body for an opaque type in the dest module from a type
69 /// definition in the source module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000070 void linkDefinedTypeBodies();
Rafael Espindolaed6dc372014-05-09 14:39:25 +000071
Rafael Espindola18c89412014-10-27 02:35:46 +000072 /// Return the mapped type to use for the specified input type from the
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000073 /// source module.
74 Type *get(Type *SrcTy);
75
Rafael Espindola290e2cc2014-11-25 14:35:53 +000076 FunctionType *get(FunctionType *T) {
77 return cast<FunctionType>(get((Type *)T));
78 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000079
Rafael Espindola18c89412014-10-27 02:35:46 +000080 /// Dump out the type map for debugging purposes.
Bill Wendlingb6af2f32012-03-22 20:28:27 +000081 void dump() const {
Rafael Espindola8f144712014-11-25 06:16:27 +000082 for (auto &Pair : MappedTypes) {
Bill Wendlingb6af2f32012-03-22 20:28:27 +000083 dbgs() << "TypeMap: ";
Rafael Espindola8f144712014-11-25 06:16:27 +000084 Pair.first->print(dbgs());
Bill Wendlingb6af2f32012-03-22 20:28:27 +000085 dbgs() << " => ";
Rafael Espindola8f144712014-11-25 06:16:27 +000086 Pair.second->print(dbgs());
Bill Wendlingb6af2f32012-03-22 20:28:27 +000087 dbgs() << '\n';
88 }
89 }
Bill Wendlingb6af2f32012-03-22 20:28:27 +000090
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000091private:
Rafael Espindola290e2cc2014-11-25 14:35:53 +000092 Type *remapType(Type *SrcTy) override { return get(SrcTy); }
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) {
Rafael Espindola3d097412014-11-28 16:26:14 +000099 assert(SpeculativeTypes.empty());
Rafael Espindolaa96f2352014-11-28 16:41:24 +0000100 assert(SpeculativeDstOpaqueTypes.empty());
Rafael Espindola3d097412014-11-28 16:26:14 +0000101
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000102 // Check to see if these types are recursively isomorphic and establish a
103 // mapping between them if so.
Duncan P. N. Exon Smithc586eaa2014-11-27 17:01:10 +0000104 if (!areTypesIsomorphic(DstTy, SrcTy)) {
105 // Oops, they aren't isomorphic. Just discard this request by rolling out
106 // any speculative mappings we've established.
Rafael Espindola3d097412014-11-28 16:26:14 +0000107 for (Type *Ty : SpeculativeTypes)
108 MappedTypes.erase(Ty);
Rafael Espindolaa96f2352014-11-28 16:41:24 +0000109
110 SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
111 SpeculativeDstOpaqueTypes.size());
112 for (StructType *Ty : SpeculativeDstOpaqueTypes)
113 DstResolvedOpaqueTypes.erase(Ty);
Rafael Espindola04a74af2014-12-01 04:15:59 +0000114 } else {
115 for (Type *Ty : SpeculativeTypes)
116 if (auto *STy = dyn_cast<StructType>(Ty))
117 if (STy->hasName())
118 STy->setName("");
Bill Wendlingd48b7782012-02-28 04:01:21 +0000119 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000120 SpeculativeTypes.clear();
Rafael Espindolaa96f2352014-11-28 16:41:24 +0000121 SpeculativeDstOpaqueTypes.clear();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000122}
Chris Lattnereee6f992008-06-16 21:00:18 +0000123
Rafael Espindola18c89412014-10-27 02:35:46 +0000124/// Recursively walk this pair of types, returning true if they are isomorphic,
125/// false if they are not.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000126bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
127 // Two types with differing kinds are clearly not isomorphic.
Rafael Espindola290e2cc2014-11-25 14:35:53 +0000128 if (DstTy->getTypeID() != SrcTy->getTypeID())
129 return false;
Misha Brukman10468d82005-04-21 22:55:34 +0000130
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000131 // If we have an entry in the MappedTypes table, then we have our answer.
132 Type *&Entry = MappedTypes[SrcTy];
133 if (Entry)
134 return Entry == DstTy;
Misha Brukman10468d82005-04-21 22:55:34 +0000135
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000136 // Two identical types are clearly isomorphic. Remember this
137 // non-speculatively.
138 if (DstTy == SrcTy) {
139 Entry = DstTy;
Chris Lattnerfe677e92008-06-16 20:03:01 +0000140 return true;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000141 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000142
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000143 // Okay, we have two types with identical kinds that we haven't seen before.
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000144
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000145 // If this is an opaque struct type, special case it.
146 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
147 // Mapping an opaque type to any struct, just keep the dest struct.
148 if (SSTy->isOpaque()) {
149 Entry = DstTy;
150 SpeculativeTypes.push_back(SrcTy);
Reid Spencer361e5132004-11-12 20:37:43 +0000151 return true;
Chris Lattner9be15892008-06-16 21:17:12 +0000152 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000153
Chris Lattner5e3bd972011-12-20 00:03:52 +0000154 // Mapping a non-opaque source type to an opaque dest. If this is the first
155 // type that we're mapping onto this destination type then we succeed. Keep
Rafael Espindolaa96f2352014-11-28 16:41:24 +0000156 // the dest, but fill it in later. If this is the second (different) type
157 // that we're trying to map onto the same opaque type then we fail.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000158 if (cast<StructType>(DstTy)->isOpaque()) {
Chris Lattner5e3bd972011-12-20 00:03:52 +0000159 // We can only map one source type onto the opaque destination type.
David Blaikie70573dc2014-11-19 07:49:26 +0000160 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
Chris Lattner5e3bd972011-12-20 00:03:52 +0000161 return false;
162 SrcDefinitionsToResolve.push_back(SSTy);
Rafael Espindolaa96f2352014-11-28 16:41:24 +0000163 SpeculativeTypes.push_back(SrcTy);
164 SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000165 Entry = DstTy;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000166 return true;
167 }
168 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000169
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000170 // If the number of subtypes disagree between the two types, then we fail.
171 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
Reid Spencer361e5132004-11-12 20:37:43 +0000172 return false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000173
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000174 // Fail if any of the extra properties (e.g. array size) of the type disagree.
175 if (isa<IntegerType>(DstTy))
176 return false; // bitwidth disagrees.
177 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
178 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
179 return false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000180
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000181 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
182 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
183 return false;
184 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
185 StructType *SSTy = cast<StructType>(SrcTy);
Chris Lattner44f7ab42011-08-12 18:07:26 +0000186 if (DSTy->isLiteral() != SSTy->isLiteral() ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000187 DSTy->isPacked() != SSTy->isPacked())
188 return false;
189 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
190 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
191 return false;
192 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
Joey Gouly5fad3e92013-01-10 10:49:36 +0000193 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000194 return false;
Reid Spencer361e5132004-11-12 20:37:43 +0000195 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000196
197 // Otherwise, we speculate that these two types will line up and recursively
198 // check the subelements.
199 Entry = DstTy;
200 SpeculativeTypes.push_back(SrcTy);
201
Rafael Espindola290e2cc2014-11-25 14:35:53 +0000202 for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
203 if (!areTypesIsomorphic(DstTy->getContainedType(I),
204 SrcTy->getContainedType(I)))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000205 return false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000206
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000207 // If everything seems to have lined up, then everything is great.
208 return true;
209}
210
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000211void TypeMapTy::linkDefinedTypeBodies() {
212 SmallVector<Type*, 16> Elements;
Rafael Espindolac81c3f52014-11-25 15:33:40 +0000213 for (StructType *SrcSTy : SrcDefinitionsToResolve) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000214 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
Rafael Espindolac81c3f52014-11-25 15:33:40 +0000215 assert(DstSTy->isOpaque());
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000216
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000217 // Map the body of the source type over to a new body for the dest type.
218 Elements.resize(SrcSTy->getNumElements());
Rafael Espindola290e2cc2014-11-25 14:35:53 +0000219 for (unsigned I = 0, E = Elements.size(); I != E; ++I)
Rafael Espindolac81c3f52014-11-25 15:33:40 +0000220 Elements[I] = get(SrcSTy->getElementType(I));
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000221
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000222 DstSTy->setBody(Elements, SrcSTy->isPacked());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000223 }
Rafael Espindolac81c3f52014-11-25 15:33:40 +0000224 SrcDefinitionsToResolve.clear();
Chris Lattner5e3bd972011-12-20 00:03:52 +0000225 DstResolvedOpaqueTypes.clear();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000226}
227
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000228Type *TypeMapTy::get(Type *Ty) {
Rafael Espindolaa4e85e32014-12-01 16:32:20 +0000229#ifndef NDEBUG
230 for (auto &Pair : MappedTypes) {
231 assert(!(Pair.first != Ty && Pair.second == Ty) &&
232 "mapping to a source type");
233 }
234#endif
235
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000236 // If we already have an entry for this type, return it.
237 Type **Entry = &MappedTypes[Ty];
Rafael Espindola290e2cc2014-11-25 14:35:53 +0000238 if (*Entry)
239 return *Entry;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000240
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000241 // If this is not a named struct type, then just map all of the elements and
242 // then rebuild the type from inside out.
Chris Lattner44f7ab42011-08-12 18:07:26 +0000243 if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000244 // If there are no element types to map, then the type is itself. This is
245 // true for the anonymous {} struct, things like 'float', integers, etc.
246 if (Ty->getNumContainedTypes() == 0)
247 return *Entry = Ty;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000248
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000249 // Remap all of the elements, keeping track of whether any of them change.
250 bool AnyChange = false;
251 SmallVector<Type*, 4> ElementTypes;
252 ElementTypes.resize(Ty->getNumContainedTypes());
Rafael Espindola290e2cc2014-11-25 14:35:53 +0000253 for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
Rafael Espindolac81c3f52014-11-25 15:33:40 +0000254 ElementTypes[I] = get(Ty->getContainedType(I));
Rafael Espindola290e2cc2014-11-25 14:35:53 +0000255 AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000256 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000257
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000258 // If we found our type while recursively processing stuff, just use it.
259 Entry = &MappedTypes[Ty];
Rafael Espindola290e2cc2014-11-25 14:35:53 +0000260 if (*Entry)
261 return *Entry;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000262
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000263 // If all of the element types mapped directly over, then the type is usable
264 // as-is.
265 if (!AnyChange)
266 return *Entry = Ty;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000267
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000268 // Otherwise, rebuild a modified type.
269 switch (Ty->getTypeID()) {
Rafael Espindola290e2cc2014-11-25 14:35:53 +0000270 default:
271 llvm_unreachable("unknown derived type to remap");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000272 case Type::ArrayTyID:
273 return *Entry = ArrayType::get(ElementTypes[0],
274 cast<ArrayType>(Ty)->getNumElements());
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000275 case Type::VectorTyID:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000276 return *Entry = VectorType::get(ElementTypes[0],
277 cast<VectorType>(Ty)->getNumElements());
278 case Type::PointerTyID:
Rafael Espindola290e2cc2014-11-25 14:35:53 +0000279 return *Entry = PointerType::get(
280 ElementTypes[0], cast<PointerType>(Ty)->getAddressSpace());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000281 case Type::FunctionTyID:
282 return *Entry = FunctionType::get(ElementTypes[0],
Frits van Bommel717d7ed2011-07-18 12:00:32 +0000283 makeArrayRef(ElementTypes).slice(1),
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000284 cast<FunctionType>(Ty)->isVarArg());
285 case Type::StructTyID:
286 // Note that this is only reached for anonymous structs.
287 return *Entry = StructType::get(Ty->getContext(), ElementTypes,
288 cast<StructType>(Ty)->isPacked());
289 }
290 }
291
292 // Otherwise, this is an unmapped named struct. If the struct can be directly
293 // mapped over, just use it as-is. This happens in a case when the linked-in
294 // module has something like:
295 // %T = type {%T*, i32}
296 // @GV = global %T* null
297 // where T does not exist at all in the destination module.
298 //
299 // The other case we watch for is when the type is not in the destination
300 // module, but that it has to be rebuilt because it refers to something that
301 // is already mapped. For example, if the destination module has:
302 // %A = type { i32 }
303 // and the source module has something like
304 // %A' = type { i32 }
305 // %B = type { %A'* }
306 // @GV = global %B* null
307 // then we want to create a new type: "%B = type { %A*}" and have it take the
308 // pristine "%B" name from the source module.
309 //
310 // To determine which case this is, we have to recursively walk the type graph
311 // speculating that we'll be able to reuse it unmodified. Only if this is
312 // safe would we map the entire thing over. Because this is an optimization,
313 // and is not required for the prettiness of the linked module, we just skip
314 // it and always rebuild a type here.
315 StructType *STy = cast<StructType>(Ty);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000316
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000317 // If the type is opaque, we can just use it directly.
Rafael Espindolaaa9918a2013-05-04 05:05:18 +0000318 if (STy->isOpaque()) {
319 // A named structure type from src module is used. Add it to the Set of
320 // identified structs in the destination module.
Rafael Espindolaa4e85e32014-12-01 16:32:20 +0000321 DstStructTypesSet.insert(STy);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000322 return *Entry = STy;
Rafael Espindolaaa9918a2013-05-04 05:05:18 +0000323 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000324
Rafael Espindolac81c3f52014-11-25 15:33:40 +0000325 // Otherwise we create a new type.
Chris Lattner5e3bd972011-12-20 00:03:52 +0000326 StructType *DTy = StructType::create(STy->getContext());
Rafael Espindolaaa9918a2013-05-04 05:05:18 +0000327 // A new identified structure type was created. Add it to the set of
328 // identified structs in the destination module.
Rafael Espindolaa4e85e32014-12-01 16:32:20 +0000329 DstStructTypesSet.insert(DTy);
Rafael Espindolac81c3f52014-11-25 15:33:40 +0000330 *Entry = DTy;
331
332 SmallVector<Type*, 4> ElementTypes;
333 ElementTypes.resize(STy->getNumElements());
334 for (unsigned I = 0, E = ElementTypes.size(); I != E; ++I)
335 ElementTypes[I] = get(STy->getElementType(I));
336 DTy->setBody(ElementTypes, STy->isPacked());
337
338 // Steal STy's name.
339 if (STy->hasName()) {
340 SmallString<16> TmpName = STy->getName();
341 STy->setName("");
342 DTy->setName(TmpName);
343 }
344
345 return DTy;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000346}
347
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000348//===----------------------------------------------------------------------===//
349// ModuleLinker implementation.
350//===----------------------------------------------------------------------===//
351
352namespace {
Rafael Espindolac84f6082014-11-25 06:11:24 +0000353class ModuleLinker;
James Molloyf6f121e2013-05-28 15:17:05 +0000354
Rafael Espindolac84f6082014-11-25 06:11:24 +0000355/// Creates prototypes for functions that are lazily linked on the fly. This
356/// speeds up linking for modules with many/ lazily linked functions of which
357/// few get used.
358class ValueMaterializerTy : public ValueMaterializer {
359 TypeMapTy &TypeMap;
360 Module *DstM;
361 std::vector<Function *> &LazilyLinkFunctions;
James Molloyf6f121e2013-05-28 15:17:05 +0000362
Rafael Espindolac84f6082014-11-25 06:11:24 +0000363public:
364 ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
365 std::vector<Function *> &LazilyLinkFunctions)
366 : ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
367 LazilyLinkFunctions(LazilyLinkFunctions) {}
368
369 Value *materializeValueFor(Value *V) override;
370};
371
372class LinkDiagnosticInfo : public DiagnosticInfo {
373 const Twine &Msg;
374
375public:
376 LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg);
377 void print(DiagnosticPrinter &DP) const override;
378};
379LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
380 const Twine &Msg)
381 : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
382void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
383
384/// This is an implementation class for the LinkModules function, which is the
385/// entrypoint for this file.
386class ModuleLinker {
387 Module *DstM, *SrcM;
388
389 TypeMapTy TypeMap;
390 ValueMaterializerTy ValMaterializer;
391
392 /// Mapping of values from what they used to be in Src, to what they are now
393 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
394 /// due to the use of Value handles which the Linker doesn't actually need,
395 /// but this allows us to reuse the ValueMapper code.
396 ValueToValueMapTy ValueMap;
397
398 struct AppendingVarInfo {
399 GlobalVariable *NewGV; // New aggregate global in dest module.
400 const Constant *DstInit; // Old initializer from dest module.
401 const Constant *SrcInit; // Old initializer from src module.
James Molloyf6f121e2013-05-28 15:17:05 +0000402 };
403
Rafael Espindolac84f6082014-11-25 06:11:24 +0000404 std::vector<AppendingVarInfo> AppendingVars;
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000405
Rafael Espindolac84f6082014-11-25 06:11:24 +0000406 // Set of items not to link in from source.
407 SmallPtrSet<const Value *, 16> DoNotLinkFromSource;
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000408
Rafael Espindolac84f6082014-11-25 06:11:24 +0000409 // Vector of functions to lazily link in.
410 std::vector<Function *> LazilyLinkFunctions;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000411
Rafael Espindolac84f6082014-11-25 06:11:24 +0000412 Linker::DiagnosticHandlerFunction DiagnosticHandler;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000413
Rafael Espindolac84f6082014-11-25 06:11:24 +0000414public:
Rafael Espindolaa4e85e32014-12-01 16:32:20 +0000415 ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM,
Rafael Espindolac84f6082014-11-25 06:11:24 +0000416 Linker::DiagnosticHandlerFunction DiagnosticHandler)
Rafael Espindolaa4e85e32014-12-01 16:32:20 +0000417 : DstM(dstM), SrcM(srcM), TypeMap(Set),
Rafael Espindolac84f6082014-11-25 06:11:24 +0000418 ValMaterializer(TypeMap, DstM, LazilyLinkFunctions),
419 DiagnosticHandler(DiagnosticHandler) {}
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000420
Rafael Espindolac84f6082014-11-25 06:11:24 +0000421 bool run();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000422
Rafael Espindolac84f6082014-11-25 06:11:24 +0000423private:
424 bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
425 const GlobalValue &Src);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000426
Rafael Espindolac84f6082014-11-25 06:11:24 +0000427 /// Helper method for setting a message and returning an error code.
428 bool emitError(const Twine &Message) {
429 DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
430 return true;
431 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000432
Rafael Espindolac84f6082014-11-25 06:11:24 +0000433 void emitWarning(const Twine &Message) {
434 DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
435 }
Eli Bendersky7da92ed2014-02-20 22:19:24 +0000436
Rafael Espindolac84f6082014-11-25 06:11:24 +0000437 bool getComdatLeader(Module *M, StringRef ComdatName,
438 const GlobalVariable *&GVar);
439 bool computeResultingSelectionKind(StringRef ComdatName,
440 Comdat::SelectionKind Src,
441 Comdat::SelectionKind Dst,
442 Comdat::SelectionKind &Result,
443 bool &LinkFromSrc);
444 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
445 ComdatsChosen;
446 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
447 bool &LinkFromSrc);
Rafael Espindola4160f5d2014-10-27 23:02:10 +0000448
Rafael Espindolac84f6082014-11-25 06:11:24 +0000449 /// Given a global in the source module, return the global in the
450 /// destination module that is being linked to, if any.
451 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
452 // If the source has no name it can't link. If it has local linkage,
453 // there is no name match-up going on.
454 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
455 return nullptr;
Eli Bendersky7da92ed2014-02-20 22:19:24 +0000456
Rafael Espindolac84f6082014-11-25 06:11:24 +0000457 // Otherwise see if we have a match in the destination module's symtab.
458 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
459 if (!DGV)
460 return nullptr;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000461
Rafael Espindolac84f6082014-11-25 06:11:24 +0000462 // If we found a global with the same name in the dest module, but it has
463 // internal linkage, we are really not doing any linkage here.
464 if (DGV->hasLocalLinkage())
465 return nullptr;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000466
Rafael Espindolac84f6082014-11-25 06:11:24 +0000467 // Otherwise, we do in fact link to the destination global.
468 return DGV;
469 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000470
Rafael Espindolac84f6082014-11-25 06:11:24 +0000471 void computeTypeMapping();
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000472
Rafael Espindolac84f6082014-11-25 06:11:24 +0000473 void upgradeMismatchedGlobalArray(StringRef Name);
474 void upgradeMismatchedGlobals();
David Majnemerdad0a642014-06-27 18:19:56 +0000475
Rafael Espindolac84f6082014-11-25 06:11:24 +0000476 bool linkAppendingVarProto(GlobalVariable *DstGV,
477 const GlobalVariable *SrcGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000478
Rafael Espindolac84f6082014-11-25 06:11:24 +0000479 bool linkGlobalValueProto(GlobalValue *GV);
480 GlobalValue *linkGlobalVariableProto(const GlobalVariable *SGVar,
481 GlobalValue *DGV, bool LinkFromSrc);
482 GlobalValue *linkFunctionProto(const Function *SF, GlobalValue *DGV,
483 bool LinkFromSrc);
484 GlobalValue *linkGlobalAliasProto(const GlobalAlias *SGA, GlobalValue *DGV,
485 bool LinkFromSrc);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000486
Rafael Espindolac84f6082014-11-25 06:11:24 +0000487 bool linkModuleFlagsMetadata();
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000488
Rafael Espindolac84f6082014-11-25 06:11:24 +0000489 void linkAppendingVarInit(const AppendingVarInfo &AVI);
490 void linkGlobalInits();
491 void linkFunctionBody(Function *Dst, Function *Src);
492 void linkAliasBodies();
493 void linkNamedMDNodes();
494};
Bill Wendlingd48b7782012-02-28 04:01:21 +0000495}
496
Rafael Espindola18c89412014-10-27 02:35:46 +0000497/// The LLVM SymbolTable class autorenames globals that conflict in the symbol
498/// table. This is good for all clients except for us. Go through the trouble
499/// to force this back.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000500static void forceRenaming(GlobalValue *GV, StringRef Name) {
501 // If the global doesn't force its name or if it already has the right name,
502 // there is nothing for us to do.
503 if (GV->hasLocalLinkage() || GV->getName() == Name)
504 return;
505
506 Module *M = GV->getParent();
Reid Spencer361e5132004-11-12 20:37:43 +0000507
508 // If there is a conflict, rename the conflict.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000509 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
Chris Lattner2a8d2e02007-02-11 00:39:38 +0000510 GV->takeName(ConflictGV);
511 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000512 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
Chris Lattner2a8d2e02007-02-11 00:39:38 +0000513 } else {
514 GV->setName(Name); // Force the name back
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000515 }
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000516}
Reid Spencer90246aa2007-02-04 04:29:21 +0000517
Rafael Espindola18c89412014-10-27 02:35:46 +0000518/// copy additional attributes (those not needed to construct a GlobalValue)
519/// from the SrcGV to the DestGV.
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000520static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
Duncan Sandsdd7daee2008-05-26 19:58:59 +0000521 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
Rafael Espindola99e05cf2014-05-13 18:45:48 +0000522 auto *DestGO = dyn_cast<GlobalObject>(DestGV);
Rafael Espindolaa7d9c692014-05-06 14:51:36 +0000523 unsigned Alignment;
Rafael Espindola99e05cf2014-05-13 18:45:48 +0000524 if (DestGO)
525 Alignment = std::max(DestGO->getAlignment(), SrcGV->getAlignment());
Rafael Espindolaa7d9c692014-05-06 14:51:36 +0000526
Duncan Sandsdd7daee2008-05-26 19:58:59 +0000527 DestGV->copyAttributesFrom(SrcGV);
Rafael Espindolaa7d9c692014-05-06 14:51:36 +0000528
Rafael Espindola99e05cf2014-05-13 18:45:48 +0000529 if (DestGO)
530 DestGO->setAlignment(Alignment);
Rafael Espindolaa7d9c692014-05-06 14:51:36 +0000531
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000532 forceRenaming(DestGV, SrcGV->getName());
Reid Spencer361e5132004-11-12 20:37:43 +0000533}
534
Rafael Espindola23f8d642012-01-05 23:02:01 +0000535static bool isLessConstraining(GlobalValue::VisibilityTypes a,
536 GlobalValue::VisibilityTypes b) {
537 if (a == GlobalValue::HiddenVisibility)
538 return false;
539 if (b == GlobalValue::HiddenVisibility)
540 return true;
541 if (a == GlobalValue::ProtectedVisibility)
542 return false;
543 if (b == GlobalValue::ProtectedVisibility)
544 return true;
545 return false;
546}
547
James Molloyf6f121e2013-05-28 15:17:05 +0000548Value *ValueMaterializerTy::materializeValueFor(Value *V) {
549 Function *SF = dyn_cast<Function>(V);
550 if (!SF)
Craig Topper2617dcc2014-04-15 06:32:26 +0000551 return nullptr;
James Molloyf6f121e2013-05-28 15:17:05 +0000552
553 Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()),
554 SF->getLinkage(), SF->getName(), DstM);
555 copyGVAttributes(DF, SF);
556
Rafael Espindola3931c282014-08-15 20:17:08 +0000557 if (Comdat *SC = SF->getComdat()) {
558 Comdat *DC = DstM->getOrInsertComdat(SC->getName());
559 DF->setComdat(DC);
560 }
561
James Molloyf6f121e2013-05-28 15:17:05 +0000562 LazilyLinkFunctions.push_back(SF);
563 return DF;
564}
565
David Majnemerdad0a642014-06-27 18:19:56 +0000566bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName,
567 const GlobalVariable *&GVar) {
568 const GlobalValue *GVal = M->getNamedValue(ComdatName);
569 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
570 GVal = GA->getBaseObject();
571 if (!GVal)
572 // We cannot resolve the size of the aliasee yet.
573 return emitError("Linking COMDATs named '" + ComdatName +
574 "': COMDAT key involves incomputable alias size.");
575 }
576
577 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
578 if (!GVar)
579 return emitError(
580 "Linking COMDATs named '" + ComdatName +
581 "': GlobalVariable required for data dependent selection!");
582
583 return false;
584}
585
586bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
587 Comdat::SelectionKind Src,
588 Comdat::SelectionKind Dst,
589 Comdat::SelectionKind &Result,
590 bool &LinkFromSrc) {
591 // The ability to mix Comdat::SelectionKind::Any with
592 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
593 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
594 Dst == Comdat::SelectionKind::Largest;
595 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
596 Src == Comdat::SelectionKind::Largest;
597 if (DstAnyOrLargest && SrcAnyOrLargest) {
598 if (Dst == Comdat::SelectionKind::Largest ||
599 Src == Comdat::SelectionKind::Largest)
600 Result = Comdat::SelectionKind::Largest;
601 else
602 Result = Comdat::SelectionKind::Any;
603 } else if (Src == Dst) {
604 Result = Dst;
605 } else {
606 return emitError("Linking COMDATs named '" + ComdatName +
607 "': invalid selection kinds!");
608 }
609
610 switch (Result) {
611 case Comdat::SelectionKind::Any:
612 // Go with Dst.
613 LinkFromSrc = false;
614 break;
615 case Comdat::SelectionKind::NoDuplicates:
616 return emitError("Linking COMDATs named '" + ComdatName +
617 "': noduplicates has been violated!");
618 case Comdat::SelectionKind::ExactMatch:
619 case Comdat::SelectionKind::Largest:
620 case Comdat::SelectionKind::SameSize: {
621 const GlobalVariable *DstGV;
622 const GlobalVariable *SrcGV;
623 if (getComdatLeader(DstM, ComdatName, DstGV) ||
624 getComdatLeader(SrcM, ComdatName, SrcGV))
625 return true;
626
627 const DataLayout *DstDL = DstM->getDataLayout();
628 const DataLayout *SrcDL = SrcM->getDataLayout();
629 if (!DstDL || !SrcDL) {
630 return emitError(
631 "Linking COMDATs named '" + ComdatName +
632 "': can't do size dependent selection without DataLayout!");
633 }
634 uint64_t DstSize =
635 DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType());
636 uint64_t SrcSize =
637 SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType());
638 if (Result == Comdat::SelectionKind::ExactMatch) {
639 if (SrcGV->getInitializer() != DstGV->getInitializer())
640 return emitError("Linking COMDATs named '" + ComdatName +
641 "': ExactMatch violated!");
642 LinkFromSrc = false;
643 } else if (Result == Comdat::SelectionKind::Largest) {
644 LinkFromSrc = SrcSize > DstSize;
645 } else if (Result == Comdat::SelectionKind::SameSize) {
646 if (SrcSize != DstSize)
647 return emitError("Linking COMDATs named '" + ComdatName +
648 "': SameSize violated!");
649 LinkFromSrc = false;
650 } else {
651 llvm_unreachable("unknown selection kind");
652 }
653 break;
654 }
655 }
656
657 return false;
658}
659
660bool ModuleLinker::getComdatResult(const Comdat *SrcC,
661 Comdat::SelectionKind &Result,
662 bool &LinkFromSrc) {
Rafael Espindolab16196a2014-08-11 17:07:34 +0000663 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
David Majnemerdad0a642014-06-27 18:19:56 +0000664 StringRef ComdatName = SrcC->getName();
665 Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable();
666 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000667
Rafael Espindolab16196a2014-08-11 17:07:34 +0000668 if (DstCI == ComdatSymTab.end()) {
669 // Use the comdat if it is only available in one of the modules.
670 LinkFromSrc = true;
671 Result = SSK;
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000672 return false;
Rafael Espindolab16196a2014-08-11 17:07:34 +0000673 }
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000674
675 const Comdat *DstC = &DstCI->second;
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000676 Comdat::SelectionKind DSK = DstC->getSelectionKind();
677 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
678 LinkFromSrc);
David Majnemerdad0a642014-06-27 18:19:56 +0000679}
James Molloyf6f121e2013-05-28 15:17:05 +0000680
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000681bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
682 const GlobalValue &Dest,
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000683 const GlobalValue &Src) {
Rafael Espindola778fcc72014-11-02 13:28:57 +0000684 // We always have to add Src if it has appending linkage.
685 if (Src.hasAppendingLinkage()) {
686 LinkFromSrc = true;
687 return false;
688 }
689
Rafael Espindolad4bcefc2014-10-24 18:13:04 +0000690 bool SrcIsDeclaration = Src.isDeclarationForLinker();
691 bool DestIsDeclaration = Dest.isDeclarationForLinker();
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000692
693 if (SrcIsDeclaration) {
694 // If Src is external or if both Src & Dest are external.. Just link the
695 // external globals, we aren't adding anything.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000696 if (Src.hasDLLImportStorageClass()) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000697 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000698 LinkFromSrc = DestIsDeclaration;
699 return false;
700 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000701 // If the Dest is weak, use the source linkage.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000702 LinkFromSrc = Dest.hasExternalWeakLinkage();
703 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000704 }
705
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000706 if (DestIsDeclaration) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000707 // If Dest is external but Src is not:
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000708 LinkFromSrc = true;
709 return false;
710 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000711
Rafael Espindola09106052014-09-09 15:59:12 +0000712 if (Src.hasCommonLinkage()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000713 if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
714 LinkFromSrc = true;
Rafael Espindola09106052014-09-09 15:59:12 +0000715 return false;
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000716 }
717
718 if (!Dest.hasCommonLinkage()) {
719 LinkFromSrc = false;
720 return false;
721 }
Rafael Espindola09106052014-09-09 15:59:12 +0000722
Rafael Espindola0ae225b2014-10-31 04:46:38 +0000723 // FIXME: Make datalayout mandatory and just use getDataLayout().
724 DataLayout DL(Dest.getParent());
725
Rafael Espindola09106052014-09-09 15:59:12 +0000726 uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
727 uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000728 LinkFromSrc = SrcSize > DestSize;
729 return false;
Rafael Espindola09106052014-09-09 15:59:12 +0000730 }
731
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000732 if (Src.isWeakForLinker()) {
733 assert(!Dest.hasExternalWeakLinkage());
734 assert(!Dest.hasAvailableExternallyLinkage());
Rafael Espindola09106052014-09-09 15:59:12 +0000735
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000736 if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
737 LinkFromSrc = true;
738 return false;
739 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000740
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000741 LinkFromSrc = false;
Rafael Espindola09106052014-09-09 15:59:12 +0000742 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000743 }
744
745 if (Dest.isWeakForLinker()) {
746 assert(Src.hasExternalLinkage());
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000747 LinkFromSrc = true;
748 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000749 }
750
751 assert(!Src.hasExternalWeakLinkage());
752 assert(!Dest.hasExternalWeakLinkage());
753 assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
754 "Unexpected linkage type!");
755 return emitError("Linking globals named '" + Src.getName() +
756 "': symbol multiply defined!");
757}
758
Rafael Espindola18c89412014-10-27 02:35:46 +0000759/// Loop over all of the linked values to compute type mappings. For example,
760/// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
761/// types 'Foo' but one got renamed when the module was loaded into the same
762/// LLVMContext.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000763void ModuleLinker::computeTypeMapping() {
Rafael Espindolac8a476e2014-11-25 04:26:19 +0000764 for (GlobalValue &SGV : SrcM->globals()) {
765 GlobalValue *DGV = getLinkedToGlobal(&SGV);
766 if (!DGV)
767 continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000768
Rafael Espindolac8a476e2014-11-25 04:26:19 +0000769 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
770 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000771 continue;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000772 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000773
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000774 // Unify the element type of appending arrays.
775 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
Rafael Espindolac8a476e2014-11-25 04:26:19 +0000776 ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000777 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
Devang Patel5c310be2009-08-11 18:01:24 +0000778 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000779
Rafael Espindolac8a476e2014-11-25 04:26:19 +0000780 for (GlobalValue &SGV : *SrcM) {
781 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
782 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000783 }
Bill Wendling7b464612012-02-27 22:34:19 +0000784
Rafael Espindolae96d7eb2014-11-25 04:43:59 +0000785 for (GlobalValue &SGV : SrcM->aliases()) {
786 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
787 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
788 }
789
Bill Wendlingd48b7782012-02-28 04:01:21 +0000790 // Incorporate types by name, scanning all the types in the source module.
791 // At this point, the destination module may have a type "%foo = { i32 }" for
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000792 // example. When the source module got loaded into the same LLVMContext, if
793 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
Rafael Espindola2fa1e432014-12-03 07:18:23 +0000794 std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
795 for (StructType *ST : Types) {
Rafael Espindola4d4c9382014-12-01 19:08:07 +0000796 if (!ST->hasName())
797 continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000798
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000799 // Check to see if there is a dot in the name followed by a digit.
Bill Wendlingd48b7782012-02-28 04:01:21 +0000800 size_t DotPos = ST->getName().rfind('.');
801 if (DotPos == 0 || DotPos == StringRef::npos ||
Guy Benyei83c74e92013-02-12 21:21:59 +0000802 ST->getName().back() == '.' ||
Rafael Espindola973b3612014-12-01 19:17:46 +0000803 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
Bill Wendlingd48b7782012-02-28 04:01:21 +0000804 continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000805
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000806 // Check to see if the destination module has a struct with the prefix name.
Rafael Espindola973b3612014-12-01 19:17:46 +0000807 StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos));
808 if (!DST)
809 continue;
810
811 // Don't use it if this actually came from the source module. They're in
812 // the same LLVMContext after all. Also don't use it unless the type is
813 // actually used in the destination module. This can happen in situations
814 // like this:
815 //
816 // Module A Module B
817 // -------- --------
818 // %Z = type { %A } %B = type { %C.1 }
819 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
820 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
821 // %C = type { i8* } %B.3 = type { %C.1 }
822 //
823 // When we link Module B with Module A, the '%B' in Module B is
824 // used. However, that would then use '%C.1'. But when we process '%C.1',
825 // we prefer to take the '%C' version. So we are then left with both
826 // '%C.1' and '%C' being used for the same types. This leads to some
827 // variables using one type and some using the other.
828 if (TypeMap.DstStructTypesSet.count(DST))
829 TypeMap.addTypeMapping(DST, ST);
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000830 }
831
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000832 // Now that we have discovered all of the type equivalences, get a body for
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000833 // any 'opaque' types in the dest module that are now resolved.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000834 TypeMap.linkDefinedTypeBodies();
Devang Patel5c310be2009-08-11 18:01:24 +0000835}
836
Duncan P. N. Exon Smith09d84ad2014-08-12 16:46:37 +0000837static void upgradeGlobalArray(GlobalVariable *GV) {
838 ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
839 StructType *OldTy = cast<StructType>(ATy->getElementType());
840 assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
841
842 // Get the upgraded 3 element type.
843 PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
844 Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
845 VoidPtrTy};
846 StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
847
848 // Build new constants with a null third field filled in.
849 Constant *OldInitC = GV->getInitializer();
850 ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
851 if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
852 // Invalid initializer; give up.
853 return;
854 std::vector<Constant *> Initializers;
855 if (OldInit && OldInit->getNumOperands()) {
856 Value *Null = Constant::getNullValue(VoidPtrTy);
857 for (Use &U : OldInit->operands()) {
858 ConstantStruct *Init = cast<ConstantStruct>(U.get());
859 Initializers.push_back(ConstantStruct::get(
860 NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
861 }
862 }
863 assert(Initializers.size() == ATy->getNumElements() &&
864 "Failed to copy all array elements");
865
866 // Replace the old GV with a new one.
867 ATy = ArrayType::get(NewTy, Initializers.size());
868 Constant *NewInit = ConstantArray::get(ATy, Initializers);
869 GlobalVariable *NewGV = new GlobalVariable(
870 *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
871 GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
872 GV->isExternallyInitialized());
873 NewGV->copyAttributesFrom(GV);
874 NewGV->takeName(GV);
875 assert(GV->use_empty() && "program cannot use initializer list");
876 GV->eraseFromParent();
877}
878
879void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
880 // Look for the global arrays.
881 auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name));
882 if (!DstGV)
883 return;
884 auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name));
885 if (!SrcGV)
886 return;
887
888 // Check if the types already match.
889 auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
890 auto *SrcTy =
891 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
892 if (DstTy == SrcTy)
893 return;
894
895 // Grab the element types. We can only upgrade an array of a two-field
896 // struct. Only bother if the other one has three-fields.
897 auto *DstEltTy = cast<StructType>(DstTy->getElementType());
898 auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
899 if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
900 upgradeGlobalArray(DstGV);
901 return;
902 }
903 if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
904 upgradeGlobalArray(SrcGV);
905
906 // We can't upgrade any other differences.
907}
908
909void ModuleLinker::upgradeMismatchedGlobals() {
910 upgradeMismatchedGlobalArray("llvm.global_ctors");
911 upgradeMismatchedGlobalArray("llvm.global_dtors");
912}
913
Rafael Espindola18c89412014-10-27 02:35:46 +0000914/// If there were any appending global variables, link them together now.
915/// Return true on error.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000916bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
Rafael Espindola3e8bc6a2014-10-31 16:08:17 +0000917 const GlobalVariable *SrcGV) {
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000918
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000919 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
920 return emitError("Linking globals named '" + SrcGV->getName() +
921 "': can only link appending global with another appending global!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000922
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000923 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
924 ArrayType *SrcTy =
925 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
926 Type *EltTy = DstTy->getElementType();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000927
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000928 // Check to see that they two arrays agree on type.
929 if (EltTy != SrcTy->getElementType())
930 return emitError("Appending variables with different element types!");
931 if (DstGV->isConstant() != SrcGV->isConstant())
932 return emitError("Appending variables linked with different const'ness!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000933
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000934 if (DstGV->getAlignment() != SrcGV->getAlignment())
935 return emitError(
936 "Appending variables with different alignment need to be linked!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000937
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000938 if (DstGV->getVisibility() != SrcGV->getVisibility())
939 return emitError(
940 "Appending variables with different visibility need to be linked!");
Rafael Espindolafac3a012013-09-04 15:33:34 +0000941
942 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
943 return emitError(
944 "Appending variables with different unnamed_addr need to be linked!");
945
Rafael Espindola64c1e182014-06-03 02:41:57 +0000946 if (StringRef(DstGV->getSection()) != SrcGV->getSection())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000947 return emitError(
948 "Appending variables with different section name need to be linked!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000949
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000950 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
951 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000952
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000953 // Create the new global variable.
954 GlobalVariable *NG =
955 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
Craig Topper2617dcc2014-04-15 06:32:26 +0000956 DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000957 DstGV->getThreadLocalMode(),
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000958 DstGV->getType()->getAddressSpace());
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000959
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000960 // Propagate alignment, visibility and section info.
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000961 copyGVAttributes(NG, DstGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000962
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000963 AppendingVarInfo AVI;
964 AVI.NewGV = NG;
965 AVI.DstInit = DstGV->getInitializer();
966 AVI.SrcInit = SrcGV->getInitializer();
967 AppendingVars.push_back(AVI);
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000968
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000969 // Replace any uses of the two global variables with uses of the new
970 // global.
971 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
Anton Korobeynikove79f4c72008-03-10 22:34:28 +0000972
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000973 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
974 DstGV->eraseFromParent();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000975
Tanya Lattnercbb91402011-10-11 00:24:54 +0000976 // Track the source variable so we don't try to link it.
977 DoNotLinkFromSource.insert(SrcGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000978
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000979 return false;
980}
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000981
Rafael Espindola778fcc72014-11-02 13:28:57 +0000982bool ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000983 GlobalValue *DGV = getLinkedToGlobal(SGV);
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000984
Rafael Espindola778fcc72014-11-02 13:28:57 +0000985 // Handle the ultra special appending linkage case first.
986 if (DGV && DGV->hasAppendingLinkage())
987 return linkAppendingVarProto(cast<GlobalVariable>(DGV),
988 cast<GlobalVariable>(SGV));
989
990 bool LinkFromSrc = true;
991 Comdat *C = nullptr;
992 GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
993 bool HasUnnamedAddr = SGV->hasUnnamedAddr();
994
David Majnemerdad0a642014-06-27 18:19:56 +0000995 if (const Comdat *SC = SGV->getComdat()) {
996 Comdat::SelectionKind SK;
997 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
Rafael Espindola778fcc72014-11-02 13:28:57 +0000998 C = DstM->getOrInsertComdat(SC->getName());
999 C->setSelectionKind(SK);
1000 } else if (DGV) {
1001 if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
1002 return true;
1003 }
1004
1005 if (!LinkFromSrc) {
1006 // Track the source global so that we don't attempt to copy it over when
1007 // processing global initializers.
1008 DoNotLinkFromSource.insert(SGV);
1009
1010 if (DGV)
1011 // Make sure to remember this mapping.
1012 ValueMap[SGV] =
1013 ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->getType()));
David Majnemerdad0a642014-06-27 18:19:56 +00001014 }
1015
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001016 if (DGV) {
Rafael Espindola778fcc72014-11-02 13:28:57 +00001017 Visibility = isLessConstraining(Visibility, DGV->getVisibility())
1018 ? DGV->getVisibility()
1019 : Visibility;
1020 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1021 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001022
Rafael Espindola778fcc72014-11-02 13:28:57 +00001023 if (!LinkFromSrc && !DGV)
1024 return false;
Reid Spencer361e5132004-11-12 20:37:43 +00001025
Rafael Espindola778fcc72014-11-02 13:28:57 +00001026 GlobalValue *NewGV;
1027 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
1028 NewGV = linkGlobalVariableProto(SGVar, DGV, LinkFromSrc);
1029 if (!NewGV)
1030 return true;
1031 } else if (auto *SF = dyn_cast<Function>(SGV)) {
1032 NewGV = linkFunctionProto(SF, DGV, LinkFromSrc);
1033 } else {
1034 NewGV = linkGlobalAliasProto(cast<GlobalAlias>(SGV), DGV, LinkFromSrc);
1035 }
Rafael Espindolafe3842c2014-09-09 17:48:18 +00001036
Rafael Espindola778fcc72014-11-02 13:28:57 +00001037 if (NewGV) {
1038 if (NewGV != DGV)
1039 copyGVAttributes(NewGV, SGV);
David Majnemerdad0a642014-06-27 18:19:56 +00001040
Rafael Espindola778fcc72014-11-02 13:28:57 +00001041 NewGV->setUnnamedAddr(HasUnnamedAddr);
1042 NewGV->setVisibility(Visibility);
1043
1044 if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
1045 if (C)
1046 NewGO->setComdat(C);
Chandler Carruthfd38af22014-11-02 09:10:31 +00001047 }
1048
Rafael Espindola778fcc72014-11-02 13:28:57 +00001049 // Make sure to remember this mapping.
1050 if (NewGV != DGV) {
1051 if (DGV) {
1052 DGV->replaceAllUsesWith(
1053 ConstantExpr::getBitCast(NewGV, DGV->getType()));
1054 DGV->eraseFromParent();
1055 }
1056 ValueMap[SGV] = NewGV;
Chris Lattner0ead7a52008-07-14 07:23:24 +00001057 }
Reid Spencer361e5132004-11-12 20:37:43 +00001058 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001059
Rafael Espindola778fcc72014-11-02 13:28:57 +00001060 return false;
1061}
1062
1063/// Loop through the global variables in the src module and merge them into the
1064/// dest module.
1065GlobalValue *ModuleLinker::linkGlobalVariableProto(const GlobalVariable *SGVar,
1066 GlobalValue *DGV,
1067 bool LinkFromSrc) {
1068 unsigned Alignment = 0;
1069 bool ClearConstant = false;
1070
1071 if (DGV) {
1072 if (DGV->hasCommonLinkage() && SGVar->hasCommonLinkage())
1073 Alignment = std::max(SGVar->getAlignment(), DGV->getAlignment());
1074
1075 auto *DGVar = dyn_cast<GlobalVariable>(DGV);
1076 if (!SGVar->isConstant() || (DGVar && !DGVar->isConstant()))
1077 ClearConstant = true;
1078 }
1079
1080 if (!LinkFromSrc) {
1081 if (auto *NewGVar = dyn_cast<GlobalVariable>(DGV)) {
1082 if (Alignment)
1083 NewGVar->setAlignment(Alignment);
1084 if (NewGVar->isDeclaration() && ClearConstant)
1085 NewGVar->setConstant(false);
1086 }
1087 return DGV;
David Majnemerdad0a642014-06-27 18:19:56 +00001088 }
1089
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001090 // No linking to be performed or linking from the source: simply create an
1091 // identical version of the symbol over in the dest module... the
1092 // initializer will be filled in later by LinkGlobalInits.
Rafael Espindola778fcc72014-11-02 13:28:57 +00001093 GlobalVariable *NewDGV = new GlobalVariable(
1094 *DstM, TypeMap.get(SGVar->getType()->getElementType()),
1095 SGVar->isConstant(), SGVar->getLinkage(), /*init*/ nullptr,
1096 SGVar->getName(), /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
1097 SGVar->getType()->getAddressSpace());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001098
Rafael Espindola778fcc72014-11-02 13:28:57 +00001099 if (Alignment)
1100 NewDGV->setAlignment(Alignment);
David Majnemerdad0a642014-06-27 18:19:56 +00001101
Rafael Espindola778fcc72014-11-02 13:28:57 +00001102 return NewDGV;
Reid Spencer361e5132004-11-12 20:37:43 +00001103}
1104
Rafael Espindola18c89412014-10-27 02:35:46 +00001105/// Link the function in the source module into the destination module if
1106/// needed, setting up mapping information.
Rafael Espindola778fcc72014-11-02 13:28:57 +00001107GlobalValue *ModuleLinker::linkFunctionProto(const Function *SF,
1108 GlobalValue *DGV,
1109 bool LinkFromSrc) {
1110 if (!LinkFromSrc)
1111 return DGV;
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001112
James Molloyf6f121e2013-05-28 15:17:05 +00001113 // If the function is to be lazily linked, don't create it just yet.
1114 // The ValueMaterializerTy will deal with creating it if it's used.
1115 if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
1116 SF->hasAvailableExternallyLinkage())) {
1117 DoNotLinkFromSource.insert(SF);
Rafael Espindola778fcc72014-11-02 13:28:57 +00001118 return nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00001119 }
1120
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001121 // If there is no linkage to be performed or we are linking from the source,
1122 // bring SF over.
Rafael Espindola778fcc72014-11-02 13:28:57 +00001123 return Function::Create(TypeMap.get(SF->getFunctionType()), SF->getLinkage(),
1124 SF->getName(), DstM);
Lauro Ramos Venanciob00c9c02007-06-28 19:02:54 +00001125}
1126
Rafael Espindola18c89412014-10-27 02:35:46 +00001127/// Set up prototypes for any aliases that come over from the source module.
Rafael Espindola778fcc72014-11-02 13:28:57 +00001128GlobalValue *ModuleLinker::linkGlobalAliasProto(const GlobalAlias *SGA,
1129 GlobalValue *DGV,
1130 bool LinkFromSrc) {
1131 if (!LinkFromSrc)
1132 return DGV;
David Majnemerdad0a642014-06-27 18:19:56 +00001133
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001134 // If there is no linkage to be performed or we're linking from the source,
1135 // bring over SGA.
Rafael Espindola4fe00942014-05-16 13:34:04 +00001136 auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType()));
Rafael Espindola778fcc72014-11-02 13:28:57 +00001137 return GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
1138 SGA->getLinkage(), SGA->getName(), DstM);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001139}
1140
Rafael Espindola3e8bc6a2014-10-31 16:08:17 +00001141static void getArrayElements(const Constant *C,
1142 SmallVectorImpl<Constant *> &Dest) {
Chris Lattner67058832012-01-25 06:48:06 +00001143 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
1144
1145 for (unsigned i = 0; i != NumElements; ++i)
1146 Dest.push_back(C->getAggregateElement(i));
Chris Lattner00245f42012-01-24 13:41:11 +00001147}
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001148
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001149void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
1150 // Merge the initializer.
Rafael Espindolad31dc042014-09-05 21:27:52 +00001151 SmallVector<Constant *, 16> DstElements;
1152 getArrayElements(AVI.DstInit, DstElements);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001153
Rafael Espindolad31dc042014-09-05 21:27:52 +00001154 SmallVector<Constant *, 16> SrcElements;
1155 getArrayElements(AVI.SrcInit, SrcElements);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001156
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001157 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
Rafael Espindolad31dc042014-09-05 21:27:52 +00001158
1159 StringRef Name = AVI.NewGV->getName();
1160 bool IsNewStructor =
1161 (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
1162 cast<StructType>(NewType->getElementType())->getNumElements() == 3;
1163
1164 for (auto *V : SrcElements) {
1165 if (IsNewStructor) {
1166 Constant *Key = V->getAggregateElement(2);
1167 if (DoNotLinkFromSource.count(Key))
1168 continue;
1169 }
1170 DstElements.push_back(
1171 MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer));
1172 }
1173 if (IsNewStructor) {
1174 NewType = ArrayType::get(NewType->getElementType(), DstElements.size());
1175 AVI.NewGV->mutateType(PointerType::get(NewType, 0));
1176 }
1177
1178 AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001179}
1180
Rafael Espindola18c89412014-10-27 02:35:46 +00001181/// Update the initializers in the Dest module now that all globals that may be
1182/// referenced are in Dest.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001183void ModuleLinker::linkGlobalInits() {
Reid Spencer361e5132004-11-12 20:37:43 +00001184 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001185 for (Module::const_global_iterator I = SrcM->global_begin(),
1186 E = SrcM->global_end(); I != E; ++I) {
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001187
Tanya Lattnercbb91402011-10-11 00:24:54 +00001188 // Only process initialized GV's or ones not already in dest.
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001189 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
1190
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001191 // Grab destination global variable.
1192 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
1193 // Figure out what the initializer looks like in the dest module.
1194 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
James Molloyf6f121e2013-05-28 15:17:05 +00001195 RF_None, &TypeMap, &ValMaterializer));
Reid Spencer361e5132004-11-12 20:37:43 +00001196 }
Reid Spencer361e5132004-11-12 20:37:43 +00001197}
1198
Rafael Espindola18c89412014-10-27 02:35:46 +00001199/// Copy the source function over into the dest function and fix up references
1200/// to values. At this point we know that Dest is an external function, and
1201/// that Src is not.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001202void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
1203 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
Reid Spencer361e5132004-11-12 20:37:43 +00001204
Chris Lattner7391dde2004-11-16 17:12:38 +00001205 // Go through and convert function arguments over, remembering the mapping.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001206 Function::arg_iterator DI = Dst->arg_begin();
Chris Lattner531f9e92005-03-15 04:54:21 +00001207 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
Reid Spencer361e5132004-11-12 20:37:43 +00001208 I != E; ++I, ++DI) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001209 DI->setName(I->getName()); // Copy the name over.
Reid Spencer361e5132004-11-12 20:37:43 +00001210
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001211 // Add a mapping to our mapping.
Anton Korobeynikov66a62712008-03-10 22:36:08 +00001212 ValueMap[I] = DI;
Reid Spencer361e5132004-11-12 20:37:43 +00001213 }
1214
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001215 // Splice the body of the source function into the dest function.
1216 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001217
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001218 // At this point, all of the instructions and values of the function are now
1219 // copied over. The only problem is that they are still referencing values in
1220 // the Source function as operands. Loop through all of the operands of the
1221 // functions and patch them up to point to the local versions.
1222 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
1223 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1224 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap,
1225 &ValMaterializer);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001226
Chris Lattner7391dde2004-11-16 17:12:38 +00001227 // There is no need to map the arguments anymore.
Chris Lattner44ab8ae2006-06-16 01:24:04 +00001228 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1229 I != E; ++I)
Reid Spencer3aaaa0b2007-02-05 20:47:22 +00001230 ValueMap.erase(I);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001231
Reid Spencer361e5132004-11-12 20:37:43 +00001232}
1233
Rafael Espindola18c89412014-10-27 02:35:46 +00001234/// Insert all of the aliases in Src into the Dest module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001235void ModuleLinker::linkAliasBodies() {
1236 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
Tanya Lattnercbb91402011-10-11 00:24:54 +00001237 I != E; ++I) {
1238 if (DoNotLinkFromSource.count(I))
1239 continue;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001240 if (Constant *Aliasee = I->getAliasee()) {
1241 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
Rafael Espindola6b238632014-05-16 19:35:39 +00001242 Constant *Val =
1243 MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer);
Rafael Espindola64c1e182014-06-03 02:41:57 +00001244 DA->setAliasee(Val);
David Chisnall2c4a34a2010-01-09 16:27:31 +00001245 }
Tanya Lattnercbb91402011-10-11 00:24:54 +00001246 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001247}
Anton Korobeynikov26098882008-03-05 23:21:39 +00001248
Rafael Espindola18c89412014-10-27 02:35:46 +00001249/// Insert all of the named MDNodes in Src into the Dest module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001250void ModuleLinker::linkNamedMDNodes() {
Bill Wendling66f02412012-02-11 11:38:06 +00001251 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001252 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1253 E = SrcM->named_metadata_end(); I != E; ++I) {
Bill Wendling66f02412012-02-11 11:38:06 +00001254 // Don't link module flags here. Do them separately.
1255 if (&*I == SrcModFlags) continue;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001256 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1257 // Add Src elements into Dest node.
1258 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1259 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
James Molloyf6f121e2013-05-28 15:17:05 +00001260 RF_None, &TypeMap, &ValMaterializer));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001261 }
1262}
Bill Wendling66f02412012-02-11 11:38:06 +00001263
Rafael Espindola18c89412014-10-27 02:35:46 +00001264/// Merge the linker flags in Src into the Dest module.
Bill Wendling66f02412012-02-11 11:38:06 +00001265bool ModuleLinker::linkModuleFlagsMetadata() {
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001266 // If the source module has no module flags, we are done.
Bill Wendling66f02412012-02-11 11:38:06 +00001267 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1268 if (!SrcModFlags) return false;
1269
Bill Wendling66f02412012-02-11 11:38:06 +00001270 // If the destination module doesn't have module flags yet, then just copy
1271 // over the source module's flags.
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001272 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
Bill Wendling66f02412012-02-11 11:38:06 +00001273 if (DstModFlags->getNumOperands() == 0) {
1274 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1275 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1276
1277 return false;
1278 }
1279
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001280 // First build a map of the existing module flags and requirements.
1281 DenseMap<MDString*, MDNode*> Flags;
1282 SmallSetVector<MDNode*, 16> Requirements;
1283 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001284 MDNode *Op = DstModFlags->getOperand(I);
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001285 ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1286 MDString *ID = cast<MDString>(Op->getOperand(1));
Bill Wendling66f02412012-02-11 11:38:06 +00001287
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001288 if (Behavior->getZExtValue() == Module::Require) {
1289 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1290 } else {
1291 Flags[ID] = Op;
1292 }
Bill Wendling66f02412012-02-11 11:38:06 +00001293 }
1294
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001295 // Merge in the flags from the source module, and also collect its set of
1296 // requirements.
1297 bool HasErr = false;
1298 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001299 MDNode *SrcOp = SrcModFlags->getOperand(I);
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001300 ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1301 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1302 MDNode *DstOp = Flags.lookup(ID);
1303 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
Bill Wendling66f02412012-02-11 11:38:06 +00001304
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001305 // If this is a requirement, add it and continue.
1306 if (SrcBehaviorValue == Module::Require) {
1307 // If the destination module does not already have this requirement, add
1308 // it.
1309 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1310 DstModFlags->addOperand(SrcOp);
1311 }
1312 continue;
Bill Wendling66f02412012-02-11 11:38:06 +00001313 }
1314
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001315 // If there is no existing flag with this ID, just add it.
1316 if (!DstOp) {
1317 Flags[ID] = SrcOp;
1318 DstModFlags->addOperand(SrcOp);
1319 continue;
1320 }
1321
1322 // Otherwise, perform a merge.
1323 ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1324 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1325
1326 // If either flag has override behavior, handle it first.
1327 if (DstBehaviorValue == Module::Override) {
1328 // Diagnose inconsistent flags which both have override behavior.
1329 if (SrcBehaviorValue == Module::Override &&
1330 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1331 HasErr |= emitError("linking module flags '" + ID->getString() +
1332 "': IDs have conflicting override values");
1333 }
1334 continue;
1335 } else if (SrcBehaviorValue == Module::Override) {
1336 // Update the destination flag to that of the source.
1337 DstOp->replaceOperandWith(0, SrcBehavior);
1338 DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1339 continue;
1340 }
1341
1342 // Diagnose inconsistent merge behavior types.
1343 if (SrcBehaviorValue != DstBehaviorValue) {
1344 HasErr |= emitError("linking module flags '" + ID->getString() +
1345 "': IDs have conflicting behaviors");
1346 continue;
1347 }
1348
1349 // Perform the merge for standard behavior types.
1350 switch (SrcBehaviorValue) {
1351 case Module::Require:
Craig Topper2a30d782014-06-18 05:05:13 +00001352 case Module::Override: llvm_unreachable("not possible");
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001353 case Module::Error: {
1354 // Emit an error if the values differ.
1355 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1356 HasErr |= emitError("linking module flags '" + ID->getString() +
1357 "': IDs have conflicting values");
1358 }
1359 continue;
1360 }
1361 case Module::Warning: {
1362 // Emit a warning if the values differ.
1363 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001364 emitWarning("linking module flags '" + ID->getString() +
1365 "': IDs have conflicting values");
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001366 }
1367 continue;
1368 }
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001369 case Module::Append: {
1370 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1371 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1372 unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1373 Value **VP, **Values = VP = new Value*[NumOps];
1374 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1375 *VP = DstValue->getOperand(i);
1376 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1377 *VP = SrcValue->getOperand(i);
1378 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1379 ArrayRef<Value*>(Values,
1380 NumOps)));
1381 delete[] Values;
1382 break;
1383 }
1384 case Module::AppendUnique: {
1385 SmallSetVector<Value*, 16> Elts;
1386 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1387 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1388 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1389 Elts.insert(DstValue->getOperand(i));
1390 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1391 Elts.insert(SrcValue->getOperand(i));
1392 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1393 ArrayRef<Value*>(Elts.begin(),
1394 Elts.end())));
1395 break;
1396 }
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001397 }
Bill Wendling66f02412012-02-11 11:38:06 +00001398 }
1399
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001400 // Check all of the requirements.
1401 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1402 MDNode *Requirement = Requirements[I];
1403 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1404 Value *ReqValue = Requirement->getOperand(1);
Bill Wendling66f02412012-02-11 11:38:06 +00001405
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001406 MDNode *Op = Flags[Flag];
1407 if (!Op || Op->getOperand(2) != ReqValue) {
1408 HasErr |= emitError("linking module flags '" + Flag->getString() +
1409 "': does not have the required value");
1410 continue;
Bill Wendling66f02412012-02-11 11:38:06 +00001411 }
1412 }
1413
1414 return HasErr;
1415}
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001416
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001417bool ModuleLinker::run() {
Bill Wendling66f02412012-02-11 11:38:06 +00001418 assert(DstM && "Null destination module");
1419 assert(SrcM && "Null source module");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001420
1421 // Inherit the target data from the source module if the destination module
1422 // doesn't have one already.
Rafael Espindolaf863ee22014-02-25 20:01:08 +00001423 if (!DstM->getDataLayout() && SrcM->getDataLayout())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001424 DstM->setDataLayout(SrcM->getDataLayout());
1425
1426 // Copy the target triple from the source to dest if the dest's is empty.
1427 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1428 DstM->setTargetTriple(SrcM->getTargetTriple());
1429
Rafael Espindolaf863ee22014-02-25 20:01:08 +00001430 if (SrcM->getDataLayout() && DstM->getDataLayout() &&
Rafael Espindolaae593f12014-02-26 17:02:08 +00001431 *SrcM->getDataLayout() != *DstM->getDataLayout()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001432 emitWarning("Linking two modules of different data layouts: '" +
1433 SrcM->getModuleIdentifier() + "' is '" +
1434 SrcM->getDataLayoutStr() + "' whereas '" +
1435 DstM->getModuleIdentifier() + "' is '" +
1436 DstM->getDataLayoutStr() + "'\n");
Eli Benderskye17f3702014-02-06 18:01:56 +00001437 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001438 if (!SrcM->getTargetTriple().empty() &&
1439 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001440 emitWarning("Linking two modules of different target triples: " +
1441 SrcM->getModuleIdentifier() + "' is '" +
1442 SrcM->getTargetTriple() + "' whereas '" +
1443 DstM->getModuleIdentifier() + "' is '" +
1444 DstM->getTargetTriple() + "'\n");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001445 }
1446
1447 // Append the module inline asm string.
1448 if (!SrcM->getModuleInlineAsm().empty()) {
1449 if (DstM->getModuleInlineAsm().empty())
1450 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1451 else
1452 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1453 SrcM->getModuleInlineAsm());
1454 }
1455
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001456 // Loop over all of the linked values to compute type mappings.
1457 computeTypeMapping();
1458
David Majnemerdad0a642014-06-27 18:19:56 +00001459 ComdatsChosen.clear();
David Blaikie5106ce72014-11-19 05:49:42 +00001460 for (const auto &SMEC : SrcM->getComdatSymbolTable()) {
David Majnemerdad0a642014-06-27 18:19:56 +00001461 const Comdat &C = SMEC.getValue();
1462 if (ComdatsChosen.count(&C))
1463 continue;
1464 Comdat::SelectionKind SK;
1465 bool LinkFromSrc;
1466 if (getComdatResult(&C, SK, LinkFromSrc))
1467 return true;
1468 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1469 }
1470
Duncan P. N. Exon Smith09d84ad2014-08-12 16:46:37 +00001471 // Upgrade mismatched global arrays.
1472 upgradeMismatchedGlobals();
1473
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001474 // Insert all of the globals in src into the DstM module... without linking
1475 // initializers (which could refer to functions not yet mapped over).
1476 for (Module::global_iterator I = SrcM->global_begin(),
1477 E = SrcM->global_end(); I != E; ++I)
Rafael Espindola778fcc72014-11-02 13:28:57 +00001478 if (linkGlobalValueProto(I))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001479 return true;
1480
1481 // Link the functions together between the two modules, without doing function
1482 // bodies... this just adds external function prototypes to the DstM
1483 // function... We do this so that when we begin processing function bodies,
1484 // all of the global values that may be referenced are available in our
1485 // ValueMap.
1486 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
Rafael Espindola778fcc72014-11-02 13:28:57 +00001487 if (linkGlobalValueProto(I))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001488 return true;
1489
1490 // If there were any aliases, link them now.
1491 for (Module::alias_iterator I = SrcM->alias_begin(),
1492 E = SrcM->alias_end(); I != E; ++I)
Rafael Espindola778fcc72014-11-02 13:28:57 +00001493 if (linkGlobalValueProto(I))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001494 return true;
1495
1496 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1497 linkAppendingVarInit(AppendingVars[i]);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001498
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001499 // Link in the function bodies that are defined in the source module into
1500 // DstM.
1501 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
Tanya Lattnerea166d42011-10-14 22:17:46 +00001502 // Skip if not linking from source.
1503 if (DoNotLinkFromSource.count(SF)) continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001504
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001505 Function *DF = cast<Function>(ValueMap[SF]);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001506
1507 // Link in the prefix data.
1508 if (SF->hasPrefixData())
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001509 DF->setPrefixData(MapValue(
1510 SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001511
1512 // Link in the prologue data.
1513 if (SF->hasPrologueData())
1514 DF->setPrologueData(MapValue(
1515 SF->getPrologueData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001516
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00001517 // Materialize if needed.
Rafael Espindola246c4fb2014-11-01 16:46:18 +00001518 if (std::error_code EC = SF->materialize())
1519 return emitError(EC.message());
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001520
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00001521 // Skip if no body (function is external).
1522 if (SF->isDeclaration())
1523 continue;
1524
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001525 linkFunctionBody(DF, SF);
Bill Wendling00623782012-03-23 07:22:49 +00001526 SF->Dematerialize();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001527 }
1528
1529 // Resolve all uses of aliases with aliasees.
1530 linkAliasBodies();
1531
Bill Wendling66f02412012-02-11 11:38:06 +00001532 // Remap all of the named MDNodes in Src into the DstM module. We do this
Devang Patel6ddbb2e2011-08-04 19:44:28 +00001533 // after linking GlobalValues so that MDNodes that reference GlobalValues
1534 // are properly remapped.
1535 linkNamedMDNodes();
1536
Bill Wendling66f02412012-02-11 11:38:06 +00001537 // Merge the module flags into the DstM module.
1538 if (linkModuleFlagsMetadata())
1539 return true;
1540
Bill Wendling91686d62014-01-16 06:29:36 +00001541 // Update the initializers in the DstM module now that all globals that may
1542 // be referenced are in DstM.
1543 linkGlobalInits();
1544
Tanya Lattner0a48b872011-11-02 00:24:56 +00001545 // Process vector of lazily linked in functions.
1546 bool LinkedInAnyFunctions;
1547 do {
1548 LinkedInAnyFunctions = false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001549
Bill Wendlingfa2287822013-03-27 17:54:41 +00001550 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001551 E = LazilyLinkFunctions.end(); I != E; ++I) {
Bill Wendlingfa2287822013-03-27 17:54:41 +00001552 Function *SF = *I;
James Molloyf6f121e2013-05-28 15:17:05 +00001553 if (!SF)
1554 continue;
Bill Wendling00623782012-03-23 07:22:49 +00001555
James Molloyf6f121e2013-05-28 15:17:05 +00001556 Function *DF = cast<Function>(ValueMap[SF]);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001557 if (SF->hasPrefixData()) {
1558 // Link in the prefix data.
1559 DF->setPrefixData(MapValue(SF->getPrefixData(),
1560 ValueMap,
1561 RF_None,
1562 &TypeMap,
1563 &ValMaterializer));
1564 }
James Molloyf6f121e2013-05-28 15:17:05 +00001565
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00001566 // Materialize if needed.
Rafael Espindola246c4fb2014-11-01 16:46:18 +00001567 if (std::error_code EC = SF->materialize())
1568 return emitError(EC.message());
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001569
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00001570 // Skip if no body (function is external).
1571 if (SF->isDeclaration())
1572 continue;
1573
James Molloyf6f121e2013-05-28 15:17:05 +00001574 // Erase from vector *before* the function body is linked - linkFunctionBody could
1575 // invalidate I.
1576 LazilyLinkFunctions.erase(I);
1577
1578 // Link in function body.
1579 linkFunctionBody(DF, SF);
1580 SF->Dematerialize();
1581
1582 // Set flag to indicate we may have more functions to lazily link in
1583 // since we linked in a function.
1584 LinkedInAnyFunctions = true;
1585 break;
Tanya Lattner0a48b872011-11-02 00:24:56 +00001586 }
1587 } while (LinkedInAnyFunctions);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001588
Anton Korobeynikov26098882008-03-05 23:21:39 +00001589 return false;
1590}
Reid Spencer361e5132004-11-12 20:37:43 +00001591
Rafael Espindola5cb9c822014-11-17 20:51:01 +00001592void Linker::init(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
1593 this->Composite = M;
1594 this->DiagnosticHandler = DiagnosticHandler;
Rafael Espindolaa4e85e32014-12-01 16:32:20 +00001595
1596 TypeFinder StructTypes;
1597 StructTypes.run(*M, true);
1598 IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end());
Rafael Espindolaaa9918a2013-05-04 05:05:18 +00001599}
Rafael Espindola3df61b72013-05-04 03:48:37 +00001600
Rafael Espindola5cb9c822014-11-17 20:51:01 +00001601Linker::Linker(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
1602 init(M, DiagnosticHandler);
1603}
1604
1605Linker::Linker(Module *M) {
1606 init(M, [this](const DiagnosticInfo &DI) {
1607 Composite->getContext().diagnose(DI);
1608 });
1609}
1610
Rafael Espindola3df61b72013-05-04 03:48:37 +00001611Linker::~Linker() {
1612}
1613
Bill Wendling91e6f6e2013-10-16 08:59:57 +00001614void Linker::deleteModule() {
1615 delete Composite;
Craig Topper2617dcc2014-04-15 06:32:26 +00001616 Composite = nullptr;
Bill Wendling91e6f6e2013-10-16 08:59:57 +00001617}
1618
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001619bool Linker::linkInModule(Module *Src) {
Rafael Espindolaa4e85e32014-12-01 16:32:20 +00001620 ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src,
1621 DiagnosticHandler);
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001622 return TheLinker.run();
Rafael Espindola3df61b72013-05-04 03:48:37 +00001623}
1624
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001625//===----------------------------------------------------------------------===//
1626// LinkModules entrypoint.
1627//===----------------------------------------------------------------------===//
1628
Rafael Espindola18c89412014-10-27 02:35:46 +00001629/// This function links two modules together, with the resulting Dest module
1630/// modified to be the composite of the two input modules. If an error occurs,
1631/// true is returned and ErrorMsg (if not null) is set to indicate the problem.
1632/// Upon failure, the Dest module could be in a modified state, and shouldn't be
1633/// relied on to be consistent.
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001634bool Linker::LinkModules(Module *Dest, Module *Src,
Rafael Espindola4160f5d2014-10-27 23:02:10 +00001635 DiagnosticHandlerFunction DiagnosticHandler) {
1636 Linker L(Dest, DiagnosticHandler);
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001637 return L.linkInModule(Src);
Rafael Espindola4160f5d2014-10-27 23:02:10 +00001638}
1639
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001640bool Linker::LinkModules(Module *Dest, Module *Src) {
Rafael Espindola287f18b2013-05-04 04:08:02 +00001641 Linker L(Dest);
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001642 return L.linkInModule(Src);
Reid Spencer361e5132004-11-12 20:37:43 +00001643}
Bill Wendlinga3aeb982012-05-09 08:55:40 +00001644
1645//===----------------------------------------------------------------------===//
1646// C API.
1647//===----------------------------------------------------------------------===//
1648
1649LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1650 LLVMLinkerMode Mode, char **OutMessages) {
Rafael Espindola98ab63c2014-10-25 04:31:08 +00001651 Module *D = unwrap(Dest);
Rafael Espindola98ab63c2014-10-25 04:31:08 +00001652 std::string Message;
Rafael Espindola4160f5d2014-10-27 23:02:10 +00001653 raw_string_ostream Stream(Message);
1654 DiagnosticPrinterRawOStream DP(Stream);
1655
1656 LLVMBool Result = Linker::LinkModules(
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001657 D, unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
Rafael Espindola98ab63c2014-10-25 04:31:08 +00001658
1659 if (OutMessages && Result)
1660 *OutMessages = strdup(Message.c_str());
Bill Wendlinga3aeb982012-05-09 08:55:40 +00001661 return Result;
1662}