159a5afa9SMikhail Glushenkov //===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
2361e513dSReid Spencer //
3361e513dSReid Spencer //                     The LLVM Compiler Infrastructure
4361e513dSReid Spencer //
5f3ebc3f3SChris Lattner // This file is distributed under the University of Illinois Open Source
6f3ebc3f3SChris Lattner // License. See LICENSE.TXT for details.
7361e513dSReid Spencer //
8361e513dSReid Spencer //===----------------------------------------------------------------------===//
9361e513dSReid Spencer //
10361e513dSReid Spencer // This file implements the LLVM module linker.
11361e513dSReid Spencer //
12361e513dSReid Spencer //===----------------------------------------------------------------------===//
13361e513dSReid Spencer 
146cc07df4SChandler Carruth #include "llvm/Linker/Linker.h"
15ed0881b2SChandler Carruth #include "llvm-c/Linker.h"
1623f8d64bSRafael Espindola #include "llvm/ADT/Optional.h"
1766f02413SBill Wendling #include "llvm/ADT/SetVector.h"
180f7fd36fSEli Bendersky #include "llvm/ADT/SmallString.h"
199fb823bbSChandler Carruth #include "llvm/IR/Constants.h"
20d12b4a33SRafael Espindola #include "llvm/IR/DiagnosticInfo.h"
21d12b4a33SRafael Espindola #include "llvm/IR/DiagnosticPrinter.h"
22d12b4a33SRafael Espindola #include "llvm/IR/LLVMContext.h"
239fb823bbSChandler Carruth #include "llvm/IR/Module.h"
24dcb603feSChandler Carruth #include "llvm/IR/TypeFinder.h"
25e17f3708SEli Bendersky #include "llvm/Support/CommandLine.h"
26b6af2f36SBill Wendling #include "llvm/Support/Debug.h"
27b6af2f36SBill Wendling #include "llvm/Support/raw_ostream.h"
28cbb91408STanya Lattner #include "llvm/Transforms/Utils/Cloning.h"
29981af002SWill Dietz #include <cctype>
3082d6ff6bSDavid Majnemer #include <tuple>
31361e513dSReid Spencer using namespace llvm;
32361e513dSReid Spencer 
33e17f3708SEli Bendersky 
34b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
35b1ed91f3SChris Lattner // TypeMap implementation.
36b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
37b1ed91f3SChris Lattner 
38b1ed91f3SChris Lattner namespace {
39aa9918aaSRafael Espindola typedef SmallPtrSet<StructType *, 32> TypeSet;
40aa9918aaSRafael Espindola 
41b1ed91f3SChris Lattner class TypeMapTy : public ValueMapTypeRemapper {
4218c89411SRafael Espindola   /// This is a mapping from a source type to a destination type to use.
43b1ed91f3SChris Lattner   DenseMap<Type*, Type*> MappedTypes;
44b1ed91f3SChris Lattner 
4518c89411SRafael Espindola   /// When checking to see if two subgraphs are isomorphic, we speculatively
4618c89411SRafael Espindola   /// add types to MappedTypes, but keep track of them here in case we need to
4718c89411SRafael Espindola   /// roll back.
48b1ed91f3SChris Lattner   SmallVector<Type*, 16> SpeculativeTypes;
49b1ed91f3SChris Lattner 
5018c89411SRafael Espindola   /// This is a list of non-opaque structs in the source module that are mapped
5118c89411SRafael Espindola   /// to an opaque struct in the destination module.
525e3bd972SChris Lattner   SmallVector<StructType*, 16> SrcDefinitionsToResolve;
535e3bd972SChris Lattner 
5418c89411SRafael Espindola   /// This is the set of opaque types in the destination modules who are
5518c89411SRafael Espindola   /// getting a body from the source module.
565e3bd972SChris Lattner   SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
57d48b7783SBill Wendling 
588c2cc416SBill Wendling public:
59aa9918aaSRafael Espindola   TypeMapTy(TypeSet &Set) : DstStructTypesSet(Set) {}
60aa9918aaSRafael Espindola 
61aa9918aaSRafael Espindola   TypeSet &DstStructTypesSet;
6218c89411SRafael Espindola   /// Indicate that the specified type in the destination module is conceptually
6318c89411SRafael Espindola   /// equivalent to the specified type in the source module.
64b1ed91f3SChris Lattner   void addTypeMapping(Type *DstTy, Type *SrcTy);
65b1ed91f3SChris Lattner 
66d2a13a2eSRafael Espindola   /// Produce a body for an opaque type in the dest module from a type
67d2a13a2eSRafael Espindola   /// definition in the source module.
68b1ed91f3SChris Lattner   void linkDefinedTypeBodies();
69b1ed91f3SChris Lattner 
7018c89411SRafael Espindola   /// Return the mapped type to use for the specified input type from the
71b1ed91f3SChris Lattner   /// source module.
72b1ed91f3SChris Lattner   Type *get(Type *SrcTy);
73b1ed91f3SChris Lattner 
74290e2cc5SRafael Espindola   FunctionType *get(FunctionType *T) {
75290e2cc5SRafael Espindola     return cast<FunctionType>(get((Type *)T));
76290e2cc5SRafael Espindola   }
77b1ed91f3SChris Lattner 
7818c89411SRafael Espindola   /// Dump out the type map for debugging purposes.
79b6af2f36SBill Wendling   void dump() const {
808f14471eSRafael Espindola     for (auto &Pair : MappedTypes) {
81b6af2f36SBill Wendling       dbgs() << "TypeMap: ";
828f14471eSRafael Espindola       Pair.first->print(dbgs());
83b6af2f36SBill Wendling       dbgs() << " => ";
848f14471eSRafael Espindola       Pair.second->print(dbgs());
85b6af2f36SBill Wendling       dbgs() << '\n';
86b6af2f36SBill Wendling     }
87b6af2f36SBill Wendling   }
88b6af2f36SBill Wendling 
89b1ed91f3SChris Lattner private:
90290e2cc5SRafael Espindola   Type *remapType(Type *SrcTy) override { return get(SrcTy); }
91b1ed91f3SChris Lattner 
92b1ed91f3SChris Lattner   bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
93b1ed91f3SChris Lattner };
94b1ed91f3SChris Lattner }
95b1ed91f3SChris Lattner 
96b1ed91f3SChris Lattner void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
97b1ed91f3SChris Lattner   // Check to see if these types are recursively isomorphic and establish a
98b1ed91f3SChris Lattner   // mapping between them if so.
99*c586eaa1SDuncan P. N. Exon Smith   if (!areTypesIsomorphic(DstTy, SrcTy)) {
100b1ed91f3SChris Lattner     // Oops, they aren't isomorphic.  Just discard this request by rolling out
101b1ed91f3SChris Lattner     // any speculative mappings we've established.
102*c586eaa1SDuncan P. N. Exon Smith     for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i)
103*c586eaa1SDuncan P. N. Exon Smith       MappedTypes.erase(SpeculativeTypes[i]);
104d48b7783SBill Wendling   }
105b1ed91f3SChris Lattner   SpeculativeTypes.clear();
106b1ed91f3SChris Lattner }
107b1ed91f3SChris Lattner 
10818c89411SRafael Espindola /// Recursively walk this pair of types, returning true if they are isomorphic,
10918c89411SRafael Espindola /// false if they are not.
110b1ed91f3SChris Lattner bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
111b1ed91f3SChris Lattner   // Two types with differing kinds are clearly not isomorphic.
112290e2cc5SRafael Espindola   if (DstTy->getTypeID() != SrcTy->getTypeID())
113290e2cc5SRafael Espindola     return false;
114b1ed91f3SChris Lattner 
115b1ed91f3SChris Lattner   // If we have an entry in the MappedTypes table, then we have our answer.
116b1ed91f3SChris Lattner   Type *&Entry = MappedTypes[SrcTy];
117b1ed91f3SChris Lattner   if (Entry)
118b1ed91f3SChris Lattner     return Entry == DstTy;
119b1ed91f3SChris Lattner 
120b1ed91f3SChris Lattner   // Two identical types are clearly isomorphic.  Remember this
121b1ed91f3SChris Lattner   // non-speculatively.
122b1ed91f3SChris Lattner   if (DstTy == SrcTy) {
123b1ed91f3SChris Lattner     Entry = DstTy;
124361e513dSReid Spencer     return true;
125361e513dSReid Spencer   }
126361e513dSReid Spencer 
127b1ed91f3SChris Lattner   // Okay, we have two types with identical kinds that we haven't seen before.
128361e513dSReid Spencer 
129b1ed91f3SChris Lattner   // If this is an opaque struct type, special case it.
130b1ed91f3SChris Lattner   if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
131b1ed91f3SChris Lattner     // Mapping an opaque type to any struct, just keep the dest struct.
132b1ed91f3SChris Lattner     if (SSTy->isOpaque()) {
133b1ed91f3SChris Lattner       Entry = DstTy;
134b1ed91f3SChris Lattner       SpeculativeTypes.push_back(SrcTy);
135b1ed91f3SChris Lattner       return true;
136361e513dSReid Spencer     }
137b1ed91f3SChris Lattner 
1385e3bd972SChris Lattner     // Mapping a non-opaque source type to an opaque dest.  If this is the first
1395e3bd972SChris Lattner     // type that we're mapping onto this destination type then we succeed.  Keep
140*c586eaa1SDuncan P. N. Exon Smith     // the dest, but fill it in later.  This doesn't need to be speculative.  If
141*c586eaa1SDuncan P. N. Exon Smith     // this is the second (different) type that we're trying to map onto the
142*c586eaa1SDuncan P. N. Exon Smith     // same opaque type then we fail.
143b1ed91f3SChris Lattner     if (cast<StructType>(DstTy)->isOpaque()) {
1445e3bd972SChris Lattner       // We can only map one source type onto the opaque destination type.
14570573dcdSDavid Blaikie       if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
1465e3bd972SChris Lattner         return false;
1475e3bd972SChris Lattner       SrcDefinitionsToResolve.push_back(SSTy);
148b1ed91f3SChris Lattner       Entry = DstTy;
149b1ed91f3SChris Lattner       return true;
150b1ed91f3SChris Lattner     }
151b1ed91f3SChris Lattner   }
152b1ed91f3SChris Lattner 
153b1ed91f3SChris Lattner   // If the number of subtypes disagree between the two types, then we fail.
154b1ed91f3SChris Lattner   if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
155b1ed91f3SChris Lattner     return false;
156b1ed91f3SChris Lattner 
157b1ed91f3SChris Lattner   // Fail if any of the extra properties (e.g. array size) of the type disagree.
158b1ed91f3SChris Lattner   if (isa<IntegerType>(DstTy))
159b1ed91f3SChris Lattner     return false;  // bitwidth disagrees.
160b1ed91f3SChris Lattner   if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
161b1ed91f3SChris Lattner     if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
162b1ed91f3SChris Lattner       return false;
163eaf9b762SChris Lattner 
164b1ed91f3SChris Lattner   } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
165b1ed91f3SChris Lattner     if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
166b1ed91f3SChris Lattner       return false;
167b1ed91f3SChris Lattner   } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
168b1ed91f3SChris Lattner     StructType *SSTy = cast<StructType>(SrcTy);
16944f7ab45SChris Lattner     if (DSTy->isLiteral() != SSTy->isLiteral() ||
170b1ed91f3SChris Lattner         DSTy->isPacked() != SSTy->isPacked())
171b1ed91f3SChris Lattner       return false;
172b1ed91f3SChris Lattner   } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
173b1ed91f3SChris Lattner     if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
174b1ed91f3SChris Lattner       return false;
175b1ed91f3SChris Lattner   } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
1765fad3e9aSJoey Gouly     if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
177361e513dSReid Spencer       return false;
178361e513dSReid Spencer   }
179361e513dSReid Spencer 
180b1ed91f3SChris Lattner   // Otherwise, we speculate that these two types will line up and recursively
181b1ed91f3SChris Lattner   // check the subelements.
182b1ed91f3SChris Lattner   Entry = DstTy;
183b1ed91f3SChris Lattner   SpeculativeTypes.push_back(SrcTy);
184eee6f995SChris Lattner 
185290e2cc5SRafael Espindola   for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
186290e2cc5SRafael Espindola     if (!areTypesIsomorphic(DstTy->getContainedType(I),
187290e2cc5SRafael Espindola                             SrcTy->getContainedType(I)))
188b1ed91f3SChris Lattner       return false;
189eee6f995SChris Lattner 
190b1ed91f3SChris Lattner   // If everything seems to have lined up, then everything is great.
191eee6f995SChris Lattner   return true;
192eee6f995SChris Lattner }
193eee6f995SChris Lattner 
194b1ed91f3SChris Lattner void TypeMapTy::linkDefinedTypeBodies() {
195b1ed91f3SChris Lattner   SmallVector<Type*, 16> Elements;
196c81c3f55SRafael Espindola   for (StructType *SrcSTy : SrcDefinitionsToResolve) {
197b1ed91f3SChris Lattner     StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
198c81c3f55SRafael Espindola     assert(DstSTy->isOpaque());
199b1ed91f3SChris Lattner 
200b1ed91f3SChris Lattner     // Map the body of the source type over to a new body for the dest type.
201b1ed91f3SChris Lattner     Elements.resize(SrcSTy->getNumElements());
202290e2cc5SRafael Espindola     for (unsigned I = 0, E = Elements.size(); I != E; ++I)
203c81c3f55SRafael Espindola       Elements[I] = get(SrcSTy->getElementType(I));
204b1ed91f3SChris Lattner 
205b1ed91f3SChris Lattner     DstSTy->setBody(Elements, SrcSTy->isPacked());
206b1ed91f3SChris Lattner   }
207c81c3f55SRafael Espindola   SrcDefinitionsToResolve.clear();
2085e3bd972SChris Lattner   DstResolvedOpaqueTypes.clear();
209eee6f995SChris Lattner }
210eee6f995SChris Lattner 
211b1ed91f3SChris Lattner Type *TypeMapTy::get(Type *Ty) {
212b1ed91f3SChris Lattner   // If we already have an entry for this type, return it.
213b1ed91f3SChris Lattner   Type **Entry = &MappedTypes[Ty];
214290e2cc5SRafael Espindola   if (*Entry)
215290e2cc5SRafael Espindola     return *Entry;
216b1ed91f3SChris Lattner 
217b1ed91f3SChris Lattner   // If this is not a named struct type, then just map all of the elements and
218b1ed91f3SChris Lattner   // then rebuild the type from inside out.
21944f7ab45SChris Lattner   if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
220b1ed91f3SChris Lattner     // If there are no element types to map, then the type is itself.  This is
221b1ed91f3SChris Lattner     // true for the anonymous {} struct, things like 'float', integers, etc.
222b1ed91f3SChris Lattner     if (Ty->getNumContainedTypes() == 0)
223b1ed91f3SChris Lattner       return *Entry = Ty;
224b1ed91f3SChris Lattner 
225b1ed91f3SChris Lattner     // Remap all of the elements, keeping track of whether any of them change.
226b1ed91f3SChris Lattner     bool AnyChange = false;
227b1ed91f3SChris Lattner     SmallVector<Type*, 4> ElementTypes;
228b1ed91f3SChris Lattner     ElementTypes.resize(Ty->getNumContainedTypes());
229290e2cc5SRafael Espindola     for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
230c81c3f55SRafael Espindola       ElementTypes[I] = get(Ty->getContainedType(I));
231290e2cc5SRafael Espindola       AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
232eee6f995SChris Lattner     }
233b1ed91f3SChris Lattner 
234b1ed91f3SChris Lattner     // If we found our type while recursively processing stuff, just use it.
235b1ed91f3SChris Lattner     Entry = &MappedTypes[Ty];
236290e2cc5SRafael Espindola     if (*Entry)
237290e2cc5SRafael Espindola       return *Entry;
238b1ed91f3SChris Lattner 
239b1ed91f3SChris Lattner     // If all of the element types mapped directly over, then the type is usable
240b1ed91f3SChris Lattner     // as-is.
241b1ed91f3SChris Lattner     if (!AnyChange)
242b1ed91f3SChris Lattner       return *Entry = Ty;
243b1ed91f3SChris Lattner 
244b1ed91f3SChris Lattner     // Otherwise, rebuild a modified type.
245b1ed91f3SChris Lattner     switch (Ty->getTypeID()) {
246290e2cc5SRafael Espindola     default:
247290e2cc5SRafael Espindola       llvm_unreachable("unknown derived type to remap");
248b1ed91f3SChris Lattner     case Type::ArrayTyID:
249b1ed91f3SChris Lattner       return *Entry = ArrayType::get(ElementTypes[0],
250b1ed91f3SChris Lattner                                      cast<ArrayType>(Ty)->getNumElements());
251b1ed91f3SChris Lattner     case Type::VectorTyID:
252b1ed91f3SChris Lattner       return *Entry = VectorType::get(ElementTypes[0],
253b1ed91f3SChris Lattner                                       cast<VectorType>(Ty)->getNumElements());
254b1ed91f3SChris Lattner     case Type::PointerTyID:
255290e2cc5SRafael Espindola       return *Entry = PointerType::get(
256290e2cc5SRafael Espindola                  ElementTypes[0], cast<PointerType>(Ty)->getAddressSpace());
257b1ed91f3SChris Lattner     case Type::FunctionTyID:
258b1ed91f3SChris Lattner       return *Entry = FunctionType::get(ElementTypes[0],
259717d7eddSFrits van Bommel                                         makeArrayRef(ElementTypes).slice(1),
260b1ed91f3SChris Lattner                                         cast<FunctionType>(Ty)->isVarArg());
261b1ed91f3SChris Lattner     case Type::StructTyID:
262b1ed91f3SChris Lattner       // Note that this is only reached for anonymous structs.
263b1ed91f3SChris Lattner       return *Entry = StructType::get(Ty->getContext(), ElementTypes,
264b1ed91f3SChris Lattner                                       cast<StructType>(Ty)->isPacked());
265b1ed91f3SChris Lattner     }
266b1ed91f3SChris Lattner   }
267b1ed91f3SChris Lattner 
268b1ed91f3SChris Lattner   // Otherwise, this is an unmapped named struct.  If the struct can be directly
269b1ed91f3SChris Lattner   // mapped over, just use it as-is.  This happens in a case when the linked-in
270b1ed91f3SChris Lattner   // module has something like:
271b1ed91f3SChris Lattner   //   %T = type {%T*, i32}
272b1ed91f3SChris Lattner   //   @GV = global %T* null
273b1ed91f3SChris Lattner   // where T does not exist at all in the destination module.
274b1ed91f3SChris Lattner   //
275b1ed91f3SChris Lattner   // The other case we watch for is when the type is not in the destination
276b1ed91f3SChris Lattner   // module, but that it has to be rebuilt because it refers to something that
277b1ed91f3SChris Lattner   // is already mapped.  For example, if the destination module has:
278b1ed91f3SChris Lattner   //  %A = type { i32 }
279b1ed91f3SChris Lattner   // and the source module has something like
280b1ed91f3SChris Lattner   //  %A' = type { i32 }
281b1ed91f3SChris Lattner   //  %B = type { %A'* }
282b1ed91f3SChris Lattner   //  @GV = global %B* null
283b1ed91f3SChris Lattner   // then we want to create a new type: "%B = type { %A*}" and have it take the
284b1ed91f3SChris Lattner   // pristine "%B" name from the source module.
285b1ed91f3SChris Lattner   //
286b1ed91f3SChris Lattner   // To determine which case this is, we have to recursively walk the type graph
287b1ed91f3SChris Lattner   // speculating that we'll be able to reuse it unmodified.  Only if this is
288b1ed91f3SChris Lattner   // safe would we map the entire thing over.  Because this is an optimization,
289b1ed91f3SChris Lattner   // and is not required for the prettiness of the linked module, we just skip
290b1ed91f3SChris Lattner   // it and always rebuild a type here.
291b1ed91f3SChris Lattner   StructType *STy = cast<StructType>(Ty);
292b1ed91f3SChris Lattner 
293b1ed91f3SChris Lattner   // If the type is opaque, we can just use it directly.
294aa9918aaSRafael Espindola   if (STy->isOpaque()) {
295aa9918aaSRafael Espindola     // A named structure type from src module is used. Add it to the Set of
296aa9918aaSRafael Espindola     // identified structs in the destination module.
297aa9918aaSRafael Espindola     DstStructTypesSet.insert(STy);
298b1ed91f3SChris Lattner     return *Entry = STy;
299aa9918aaSRafael Espindola   }
300b1ed91f3SChris Lattner 
301c81c3f55SRafael Espindola   // Otherwise we create a new type.
3025e3bd972SChris Lattner   StructType *DTy = StructType::create(STy->getContext());
303aa9918aaSRafael Espindola   // A new identified structure type was created. Add it to the set of
304aa9918aaSRafael Espindola   // identified structs in the destination module.
305aa9918aaSRafael Espindola   DstStructTypesSet.insert(DTy);
306c81c3f55SRafael Espindola   *Entry = DTy;
307c81c3f55SRafael Espindola 
308c81c3f55SRafael Espindola   SmallVector<Type*, 4> ElementTypes;
309c81c3f55SRafael Espindola   ElementTypes.resize(STy->getNumElements());
310c81c3f55SRafael Espindola   for (unsigned I = 0, E = ElementTypes.size(); I != E; ++I)
311c81c3f55SRafael Espindola     ElementTypes[I] = get(STy->getElementType(I));
312c81c3f55SRafael Espindola   DTy->setBody(ElementTypes, STy->isPacked());
313c81c3f55SRafael Espindola 
314c81c3f55SRafael Espindola   // Steal STy's name.
315c81c3f55SRafael Espindola   if (STy->hasName()) {
316c81c3f55SRafael Espindola     SmallString<16> TmpName = STy->getName();
317c81c3f55SRafael Espindola     STy->setName("");
318c81c3f55SRafael Espindola     DTy->setName(TmpName);
319c81c3f55SRafael Espindola   }
320c81c3f55SRafael Espindola 
321c81c3f55SRafael Espindola   return DTy;
322b1ed91f3SChris Lattner }
323b1ed91f3SChris Lattner 
324b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
325b1ed91f3SChris Lattner // ModuleLinker implementation.
326b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
327b1ed91f3SChris Lattner 
328b1ed91f3SChris Lattner namespace {
329f6f121e2SJames Molloy class ModuleLinker;
330f6f121e2SJames Molloy 
33118c89411SRafael Espindola /// Creates prototypes for functions that are lazily linked on the fly. This
33218c89411SRafael Espindola /// speeds up linking for modules with many/ lazily linked functions of which
33318c89411SRafael Espindola /// few get used.
334f6f121e2SJames Molloy class ValueMaterializerTy : public ValueMaterializer {
335f6f121e2SJames Molloy   TypeMapTy &TypeMap;
336f6f121e2SJames Molloy   Module *DstM;
337f6f121e2SJames Molloy   std::vector<Function *> &LazilyLinkFunctions;
338c84f608bSRafael Espindola 
339f6f121e2SJames Molloy public:
340f6f121e2SJames Molloy   ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
341c84f608bSRafael Espindola                       std::vector<Function *> &LazilyLinkFunctions)
342c84f608bSRafael Espindola       : ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
343c84f608bSRafael Espindola         LazilyLinkFunctions(LazilyLinkFunctions) {}
344f6f121e2SJames Molloy 
3458548299aSCraig Topper   Value *materializeValueFor(Value *V) override;
346f6f121e2SJames Molloy };
347f6f121e2SJames Molloy 
348d12b4a33SRafael Espindola class LinkDiagnosticInfo : public DiagnosticInfo {
349d12b4a33SRafael Espindola   const Twine &Msg;
350d12b4a33SRafael Espindola 
351d12b4a33SRafael Espindola public:
352d12b4a33SRafael Espindola   LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg);
353d12b4a33SRafael Espindola   void print(DiagnosticPrinter &DP) const override;
354d12b4a33SRafael Espindola };
355d12b4a33SRafael Espindola LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
356d12b4a33SRafael Espindola                                        const Twine &Msg)
357d12b4a33SRafael Espindola     : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
358d12b4a33SRafael Espindola void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
359d12b4a33SRafael Espindola 
36018c89411SRafael Espindola /// This is an implementation class for the LinkModules function, which is the
36118c89411SRafael Espindola /// entrypoint for this file.
362b1ed91f3SChris Lattner class ModuleLinker {
363b1ed91f3SChris Lattner   Module *DstM, *SrcM;
364b1ed91f3SChris Lattner 
365b1ed91f3SChris Lattner   TypeMapTy TypeMap;
366f6f121e2SJames Molloy   ValueMaterializerTy ValMaterializer;
367b1ed91f3SChris Lattner 
36818c89411SRafael Espindola   /// Mapping of values from what they used to be in Src, to what they are now
36918c89411SRafael Espindola   /// in DstM.  ValueToValueMapTy is a ValueMap, which involves some overhead
37018c89411SRafael Espindola   /// due to the use of Value handles which the Linker doesn't actually need,
37118c89411SRafael Espindola   /// but this allows us to reuse the ValueMapper code.
372b1ed91f3SChris Lattner   ValueToValueMapTy ValueMap;
373b1ed91f3SChris Lattner 
374b1ed91f3SChris Lattner   struct AppendingVarInfo {
375b1ed91f3SChris Lattner     GlobalVariable *NewGV;   // New aggregate global in dest module.
3763e8bc6a8SRafael Espindola     const Constant *DstInit; // Old initializer from dest module.
3773e8bc6a8SRafael Espindola     const Constant *SrcInit; // Old initializer from src module.
378b1ed91f3SChris Lattner   };
379b1ed91f3SChris Lattner 
380b1ed91f3SChris Lattner   std::vector<AppendingVarInfo> AppendingVars;
381b1ed91f3SChris Lattner 
382cbb91408STanya Lattner   // Set of items not to link in from source.
383cbb91408STanya Lattner   SmallPtrSet<const Value *, 16> DoNotLinkFromSource;
384cbb91408STanya Lattner 
3850a48b877STanya Lattner   // Vector of functions to lazily link in.
386fa228782SBill Wendling   std::vector<Function *> LazilyLinkFunctions;
3870a48b877STanya Lattner 
3884160f5d3SRafael Espindola   Linker::DiagnosticHandlerFunction DiagnosticHandler;
3894160f5d3SRafael Espindola 
390b1ed91f3SChris Lattner public:
3919f8eff31SRafael Espindola   ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM,
3924160f5d3SRafael Espindola                Linker::DiagnosticHandlerFunction DiagnosticHandler)
393f6f121e2SJames Molloy       : DstM(dstM), SrcM(srcM), TypeMap(Set),
3949f8eff31SRafael Espindola         ValMaterializer(TypeMap, DstM, LazilyLinkFunctions),
3954160f5d3SRafael Espindola         DiagnosticHandler(DiagnosticHandler) {}
396b1ed91f3SChris Lattner 
397b1ed91f3SChris Lattner   bool run();
398b1ed91f3SChris Lattner 
399b1ed91f3SChris Lattner private:
400d12b4a33SRafael Espindola   bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
401d12b4a33SRafael Espindola                             const GlobalValue &Src);
402dbb0bd1aSRafael Espindola 
403d12b4a33SRafael Espindola   /// Helper method for setting a message and returning an error code.
404b1ed91f3SChris Lattner   bool emitError(const Twine &Message) {
4054160f5d3SRafael Espindola     DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
406b1ed91f3SChris Lattner     return true;
407b1ed91f3SChris Lattner   }
408b1ed91f3SChris Lattner 
409d12b4a33SRafael Espindola   void emitWarning(const Twine &Message) {
4104160f5d3SRafael Espindola     DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
411d12b4a33SRafael Espindola   }
412d12b4a33SRafael Espindola 
413dad0a645SDavid Majnemer   bool getComdatLeader(Module *M, StringRef ComdatName,
414dad0a645SDavid Majnemer                        const GlobalVariable *&GVar);
415dad0a645SDavid Majnemer   bool computeResultingSelectionKind(StringRef ComdatName,
416dad0a645SDavid Majnemer                                      Comdat::SelectionKind Src,
417dad0a645SDavid Majnemer                                      Comdat::SelectionKind Dst,
418dad0a645SDavid Majnemer                                      Comdat::SelectionKind &Result,
419dad0a645SDavid Majnemer                                      bool &LinkFromSrc);
420dad0a645SDavid Majnemer   std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
421dad0a645SDavid Majnemer       ComdatsChosen;
422dad0a645SDavid Majnemer   bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
423dad0a645SDavid Majnemer                        bool &LinkFromSrc);
424dad0a645SDavid Majnemer 
42518c89411SRafael Espindola   /// Given a global in the source module, return the global in the
42618c89411SRafael Espindola   /// destination module that is being linked to, if any.
4273e8bc6a8SRafael Espindola   GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
428b1ed91f3SChris Lattner     // If the source has no name it can't link.  If it has local linkage,
429b1ed91f3SChris Lattner     // there is no name match-up going on.
430b1ed91f3SChris Lattner     if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
4312617dcceSCraig Topper       return nullptr;
432b1ed91f3SChris Lattner 
433b1ed91f3SChris Lattner     // Otherwise see if we have a match in the destination module's symtab.
434b1ed91f3SChris Lattner     GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
435c84f608bSRafael Espindola     if (!DGV)
436c84f608bSRafael Espindola       return nullptr;
437b1ed91f3SChris Lattner 
438b1ed91f3SChris Lattner     // If we found a global with the same name in the dest module, but it has
439b1ed91f3SChris Lattner     // internal linkage, we are really not doing any linkage here.
440b1ed91f3SChris Lattner     if (DGV->hasLocalLinkage())
4412617dcceSCraig Topper       return nullptr;
442b1ed91f3SChris Lattner 
443b1ed91f3SChris Lattner     // Otherwise, we do in fact link to the destination global.
444b1ed91f3SChris Lattner     return DGV;
445b1ed91f3SChris Lattner   }
446b1ed91f3SChris Lattner 
447b1ed91f3SChris Lattner   void computeTypeMapping();
448b1ed91f3SChris Lattner 
44909d84addSDuncan P. N. Exon Smith   void upgradeMismatchedGlobalArray(StringRef Name);
45009d84addSDuncan P. N. Exon Smith   void upgradeMismatchedGlobals();
45109d84addSDuncan P. N. Exon Smith 
4523e8bc6a8SRafael Espindola   bool linkAppendingVarProto(GlobalVariable *DstGV,
4533e8bc6a8SRafael Espindola                              const GlobalVariable *SrcGV);
454778fcc77SRafael Espindola 
455778fcc77SRafael Espindola   bool linkGlobalValueProto(GlobalValue *GV);
456778fcc77SRafael Espindola   GlobalValue *linkGlobalVariableProto(const GlobalVariable *SGVar,
457778fcc77SRafael Espindola                                        GlobalValue *DGV, bool LinkFromSrc);
458778fcc77SRafael Espindola   GlobalValue *linkFunctionProto(const Function *SF, GlobalValue *DGV,
459778fcc77SRafael Espindola                                  bool LinkFromSrc);
460778fcc77SRafael Espindola   GlobalValue *linkGlobalAliasProto(const GlobalAlias *SGA, GlobalValue *DGV,
461778fcc77SRafael Espindola                                     bool LinkFromSrc);
462778fcc77SRafael Espindola 
46366f02413SBill Wendling   bool linkModuleFlagsMetadata();
464b1ed91f3SChris Lattner 
465b1ed91f3SChris Lattner   void linkAppendingVarInit(const AppendingVarInfo &AVI);
466b1ed91f3SChris Lattner   void linkGlobalInits();
467b1ed91f3SChris Lattner   void linkFunctionBody(Function *Dst, Function *Src);
468b1ed91f3SChris Lattner   void linkAliasBodies();
469b1ed91f3SChris Lattner   void linkNamedMDNodes();
470eee6f995SChris Lattner };
471d48b7783SBill Wendling }
472d48b7783SBill Wendling 
47318c89411SRafael Espindola /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
47418c89411SRafael Espindola /// table. This is good for all clients except for us. Go through the trouble
47518c89411SRafael Espindola /// to force this back.
476b1ed91f3SChris Lattner static void forceRenaming(GlobalValue *GV, StringRef Name) {
477b1ed91f3SChris Lattner   // If the global doesn't force its name or if it already has the right name,
478b1ed91f3SChris Lattner   // there is nothing for us to do.
479b1ed91f3SChris Lattner   if (GV->hasLocalLinkage() || GV->getName() == Name)
480b1ed91f3SChris Lattner     return;
481b1ed91f3SChris Lattner 
482b1ed91f3SChris Lattner   Module *M = GV->getParent();
483361e513dSReid Spencer 
484361e513dSReid Spencer   // If there is a conflict, rename the conflict.
485b1ed91f3SChris Lattner   if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
4862a8d2e0eSChris Lattner     GV->takeName(ConflictGV);
487361e513dSReid Spencer     ConflictGV->setName(Name);    // This will cause ConflictGV to get renamed
488b1ed91f3SChris Lattner     assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
4892a8d2e0eSChris Lattner   } else {
4902a8d2e0eSChris Lattner     GV->setName(Name);              // Force the name back
4913aaaa0b2SReid Spencer   }
4923aaaa0b2SReid Spencer }
4933aaaa0b2SReid Spencer 
49418c89411SRafael Espindola /// copy additional attributes (those not needed to construct a GlobalValue)
49518c89411SRafael Espindola /// from the SrcGV to the DestGV.
496b6af2f36SBill Wendling static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
497dd7daee8SDuncan Sands   // Use the maximum alignment, rather than just copying the alignment of SrcGV.
49899e05cf1SRafael Espindola   auto *DestGO = dyn_cast<GlobalObject>(DestGV);
499a7d9c69cSRafael Espindola   unsigned Alignment;
50099e05cf1SRafael Espindola   if (DestGO)
50199e05cf1SRafael Espindola     Alignment = std::max(DestGO->getAlignment(), SrcGV->getAlignment());
502a7d9c69cSRafael Espindola 
503dd7daee8SDuncan Sands   DestGV->copyAttributesFrom(SrcGV);
504a7d9c69cSRafael Espindola 
50599e05cf1SRafael Espindola   if (DestGO)
50699e05cf1SRafael Espindola     DestGO->setAlignment(Alignment);
507b1ed91f3SChris Lattner 
508b1ed91f3SChris Lattner   forceRenaming(DestGV, SrcGV->getName());
509361e513dSReid Spencer }
510361e513dSReid Spencer 
51123f8d64bSRafael Espindola static bool isLessConstraining(GlobalValue::VisibilityTypes a,
51223f8d64bSRafael Espindola                                GlobalValue::VisibilityTypes b) {
51323f8d64bSRafael Espindola   if (a == GlobalValue::HiddenVisibility)
51423f8d64bSRafael Espindola     return false;
51523f8d64bSRafael Espindola   if (b == GlobalValue::HiddenVisibility)
51623f8d64bSRafael Espindola     return true;
51723f8d64bSRafael Espindola   if (a == GlobalValue::ProtectedVisibility)
51823f8d64bSRafael Espindola     return false;
51923f8d64bSRafael Espindola   if (b == GlobalValue::ProtectedVisibility)
52023f8d64bSRafael Espindola     return true;
52123f8d64bSRafael Espindola   return false;
52223f8d64bSRafael Espindola }
52323f8d64bSRafael Espindola 
524f6f121e2SJames Molloy Value *ValueMaterializerTy::materializeValueFor(Value *V) {
525f6f121e2SJames Molloy   Function *SF = dyn_cast<Function>(V);
526f6f121e2SJames Molloy   if (!SF)
5272617dcceSCraig Topper     return nullptr;
528f6f121e2SJames Molloy 
529f6f121e2SJames Molloy   Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()),
530f6f121e2SJames Molloy                                   SF->getLinkage(), SF->getName(), DstM);
531f6f121e2SJames Molloy   copyGVAttributes(DF, SF);
532f6f121e2SJames Molloy 
5333931c28bSRafael Espindola   if (Comdat *SC = SF->getComdat()) {
5343931c28bSRafael Espindola     Comdat *DC = DstM->getOrInsertComdat(SC->getName());
5353931c28bSRafael Espindola     DF->setComdat(DC);
5363931c28bSRafael Espindola   }
5373931c28bSRafael Espindola 
538f6f121e2SJames Molloy   LazilyLinkFunctions.push_back(SF);
539f6f121e2SJames Molloy   return DF;
540f6f121e2SJames Molloy }
541f6f121e2SJames Molloy 
542dad0a645SDavid Majnemer bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName,
543dad0a645SDavid Majnemer                                    const GlobalVariable *&GVar) {
544dad0a645SDavid Majnemer   const GlobalValue *GVal = M->getNamedValue(ComdatName);
545dad0a645SDavid Majnemer   if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
546dad0a645SDavid Majnemer     GVal = GA->getBaseObject();
547dad0a645SDavid Majnemer     if (!GVal)
548dad0a645SDavid Majnemer       // We cannot resolve the size of the aliasee yet.
549dad0a645SDavid Majnemer       return emitError("Linking COMDATs named '" + ComdatName +
550dad0a645SDavid Majnemer                        "': COMDAT key involves incomputable alias size.");
551dad0a645SDavid Majnemer   }
552dad0a645SDavid Majnemer 
553dad0a645SDavid Majnemer   GVar = dyn_cast_or_null<GlobalVariable>(GVal);
554dad0a645SDavid Majnemer   if (!GVar)
555dad0a645SDavid Majnemer     return emitError(
556dad0a645SDavid Majnemer         "Linking COMDATs named '" + ComdatName +
557dad0a645SDavid Majnemer         "': GlobalVariable required for data dependent selection!");
558dad0a645SDavid Majnemer 
559dad0a645SDavid Majnemer   return false;
560dad0a645SDavid Majnemer }
561dad0a645SDavid Majnemer 
562dad0a645SDavid Majnemer bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
563dad0a645SDavid Majnemer                                                  Comdat::SelectionKind Src,
564dad0a645SDavid Majnemer                                                  Comdat::SelectionKind Dst,
565dad0a645SDavid Majnemer                                                  Comdat::SelectionKind &Result,
566dad0a645SDavid Majnemer                                                  bool &LinkFromSrc) {
567dad0a645SDavid Majnemer   // The ability to mix Comdat::SelectionKind::Any with
568dad0a645SDavid Majnemer   // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
569dad0a645SDavid Majnemer   bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
570dad0a645SDavid Majnemer                          Dst == Comdat::SelectionKind::Largest;
571dad0a645SDavid Majnemer   bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
572dad0a645SDavid Majnemer                          Src == Comdat::SelectionKind::Largest;
573dad0a645SDavid Majnemer   if (DstAnyOrLargest && SrcAnyOrLargest) {
574dad0a645SDavid Majnemer     if (Dst == Comdat::SelectionKind::Largest ||
575dad0a645SDavid Majnemer         Src == Comdat::SelectionKind::Largest)
576dad0a645SDavid Majnemer       Result = Comdat::SelectionKind::Largest;
577dad0a645SDavid Majnemer     else
578dad0a645SDavid Majnemer       Result = Comdat::SelectionKind::Any;
579dad0a645SDavid Majnemer   } else if (Src == Dst) {
580dad0a645SDavid Majnemer     Result = Dst;
581dad0a645SDavid Majnemer   } else {
582dad0a645SDavid Majnemer     return emitError("Linking COMDATs named '" + ComdatName +
583dad0a645SDavid Majnemer                      "': invalid selection kinds!");
584dad0a645SDavid Majnemer   }
585dad0a645SDavid Majnemer 
586dad0a645SDavid Majnemer   switch (Result) {
587dad0a645SDavid Majnemer   case Comdat::SelectionKind::Any:
588dad0a645SDavid Majnemer     // Go with Dst.
589dad0a645SDavid Majnemer     LinkFromSrc = false;
590dad0a645SDavid Majnemer     break;
591dad0a645SDavid Majnemer   case Comdat::SelectionKind::NoDuplicates:
592dad0a645SDavid Majnemer     return emitError("Linking COMDATs named '" + ComdatName +
593dad0a645SDavid Majnemer                      "': noduplicates has been violated!");
594dad0a645SDavid Majnemer   case Comdat::SelectionKind::ExactMatch:
595dad0a645SDavid Majnemer   case Comdat::SelectionKind::Largest:
596dad0a645SDavid Majnemer   case Comdat::SelectionKind::SameSize: {
597dad0a645SDavid Majnemer     const GlobalVariable *DstGV;
598dad0a645SDavid Majnemer     const GlobalVariable *SrcGV;
599dad0a645SDavid Majnemer     if (getComdatLeader(DstM, ComdatName, DstGV) ||
600dad0a645SDavid Majnemer         getComdatLeader(SrcM, ComdatName, SrcGV))
601dad0a645SDavid Majnemer       return true;
602dad0a645SDavid Majnemer 
603dad0a645SDavid Majnemer     const DataLayout *DstDL = DstM->getDataLayout();
604dad0a645SDavid Majnemer     const DataLayout *SrcDL = SrcM->getDataLayout();
605dad0a645SDavid Majnemer     if (!DstDL || !SrcDL) {
606dad0a645SDavid Majnemer       return emitError(
607dad0a645SDavid Majnemer           "Linking COMDATs named '" + ComdatName +
608dad0a645SDavid Majnemer           "': can't do size dependent selection without DataLayout!");
609dad0a645SDavid Majnemer     }
610dad0a645SDavid Majnemer     uint64_t DstSize =
611dad0a645SDavid Majnemer         DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType());
612dad0a645SDavid Majnemer     uint64_t SrcSize =
613dad0a645SDavid Majnemer         SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType());
614dad0a645SDavid Majnemer     if (Result == Comdat::SelectionKind::ExactMatch) {
615dad0a645SDavid Majnemer       if (SrcGV->getInitializer() != DstGV->getInitializer())
616dad0a645SDavid Majnemer         return emitError("Linking COMDATs named '" + ComdatName +
617dad0a645SDavid Majnemer                          "': ExactMatch violated!");
618dad0a645SDavid Majnemer       LinkFromSrc = false;
619dad0a645SDavid Majnemer     } else if (Result == Comdat::SelectionKind::Largest) {
620dad0a645SDavid Majnemer       LinkFromSrc = SrcSize > DstSize;
621dad0a645SDavid Majnemer     } else if (Result == Comdat::SelectionKind::SameSize) {
622dad0a645SDavid Majnemer       if (SrcSize != DstSize)
623dad0a645SDavid Majnemer         return emitError("Linking COMDATs named '" + ComdatName +
624dad0a645SDavid Majnemer                          "': SameSize violated!");
625dad0a645SDavid Majnemer       LinkFromSrc = false;
626dad0a645SDavid Majnemer     } else {
627dad0a645SDavid Majnemer       llvm_unreachable("unknown selection kind");
628dad0a645SDavid Majnemer     }
629dad0a645SDavid Majnemer     break;
630dad0a645SDavid Majnemer   }
631dad0a645SDavid Majnemer   }
632dad0a645SDavid Majnemer 
633dad0a645SDavid Majnemer   return false;
634dad0a645SDavid Majnemer }
635dad0a645SDavid Majnemer 
636dad0a645SDavid Majnemer bool ModuleLinker::getComdatResult(const Comdat *SrcC,
637dad0a645SDavid Majnemer                                    Comdat::SelectionKind &Result,
638dad0a645SDavid Majnemer                                    bool &LinkFromSrc) {
639b16196a3SRafael Espindola   Comdat::SelectionKind SSK = SrcC->getSelectionKind();
640dad0a645SDavid Majnemer   StringRef ComdatName = SrcC->getName();
641dad0a645SDavid Majnemer   Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable();
642dad0a645SDavid Majnemer   Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
6432ef3f299SRafael Espindola 
644b16196a3SRafael Espindola   if (DstCI == ComdatSymTab.end()) {
645b16196a3SRafael Espindola     // Use the comdat if it is only available in one of the modules.
646b16196a3SRafael Espindola     LinkFromSrc = true;
647b16196a3SRafael Espindola     Result = SSK;
6482ef3f299SRafael Espindola     return false;
649b16196a3SRafael Espindola   }
6502ef3f299SRafael Espindola 
651dad0a645SDavid Majnemer   const Comdat *DstC = &DstCI->second;
652dad0a645SDavid Majnemer   Comdat::SelectionKind DSK = DstC->getSelectionKind();
6532ef3f299SRafael Espindola   return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
6542ef3f299SRafael Espindola                                        LinkFromSrc);
655dad0a645SDavid Majnemer }
656f6f121e2SJames Molloy 
657d12b4a33SRafael Espindola bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
658d12b4a33SRafael Espindola                                         const GlobalValue &Dest,
659dbb0bd1aSRafael Espindola                                         const GlobalValue &Src) {
660778fcc77SRafael Espindola   // We always have to add Src if it has appending linkage.
661778fcc77SRafael Espindola   if (Src.hasAppendingLinkage()) {
662778fcc77SRafael Espindola     LinkFromSrc = true;
663778fcc77SRafael Espindola     return false;
664778fcc77SRafael Espindola   }
665778fcc77SRafael Espindola 
666d4bcefc7SRafael Espindola   bool SrcIsDeclaration = Src.isDeclarationForLinker();
667d4bcefc7SRafael Espindola   bool DestIsDeclaration = Dest.isDeclarationForLinker();
668dbb0bd1aSRafael Espindola 
669dbb0bd1aSRafael Espindola   if (SrcIsDeclaration) {
670dbb0bd1aSRafael Espindola     // If Src is external or if both Src & Dest are external..  Just link the
671dbb0bd1aSRafael Espindola     // external globals, we aren't adding anything.
672d12b4a33SRafael Espindola     if (Src.hasDLLImportStorageClass()) {
673dbb0bd1aSRafael Espindola       // If one of GVs is marked as DLLImport, result should be dllimport'ed.
674d12b4a33SRafael Espindola       LinkFromSrc = DestIsDeclaration;
675d12b4a33SRafael Espindola       return false;
676d12b4a33SRafael Espindola     }
677dbb0bd1aSRafael Espindola     // If the Dest is weak, use the source linkage.
678d12b4a33SRafael Espindola     LinkFromSrc = Dest.hasExternalWeakLinkage();
679d12b4a33SRafael Espindola     return false;
680dbb0bd1aSRafael Espindola   }
681dbb0bd1aSRafael Espindola 
682d12b4a33SRafael Espindola   if (DestIsDeclaration) {
683dbb0bd1aSRafael Espindola     // If Dest is external but Src is not:
684d12b4a33SRafael Espindola     LinkFromSrc = true;
685d12b4a33SRafael Espindola     return false;
686d12b4a33SRafael Espindola   }
687dbb0bd1aSRafael Espindola 
6880910605aSRafael Espindola   if (Src.hasCommonLinkage()) {
689d12b4a33SRafael Espindola     if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
690d12b4a33SRafael Espindola       LinkFromSrc = true;
6910910605aSRafael Espindola       return false;
692d12b4a33SRafael Espindola     }
693d12b4a33SRafael Espindola 
694d12b4a33SRafael Espindola     if (!Dest.hasCommonLinkage()) {
695d12b4a33SRafael Espindola       LinkFromSrc = false;
696d12b4a33SRafael Espindola       return false;
697d12b4a33SRafael Espindola     }
6980910605aSRafael Espindola 
6990ae225b6SRafael Espindola     // FIXME: Make datalayout mandatory and just use getDataLayout().
7000ae225b6SRafael Espindola     DataLayout DL(Dest.getParent());
7010ae225b6SRafael Espindola 
7020910605aSRafael Espindola     uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
7030910605aSRafael Espindola     uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
704d12b4a33SRafael Espindola     LinkFromSrc = SrcSize > DestSize;
705d12b4a33SRafael Espindola     return false;
7060910605aSRafael Espindola   }
7070910605aSRafael Espindola 
708dbb0bd1aSRafael Espindola   if (Src.isWeakForLinker()) {
709dbb0bd1aSRafael Espindola     assert(!Dest.hasExternalWeakLinkage());
710dbb0bd1aSRafael Espindola     assert(!Dest.hasAvailableExternallyLinkage());
7110910605aSRafael Espindola 
712d12b4a33SRafael Espindola     if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
713d12b4a33SRafael Espindola       LinkFromSrc = true;
714d12b4a33SRafael Espindola       return false;
715d12b4a33SRafael Espindola     }
716dbb0bd1aSRafael Espindola 
717d12b4a33SRafael Espindola     LinkFromSrc = false;
7180910605aSRafael Espindola     return false;
719dbb0bd1aSRafael Espindola   }
720dbb0bd1aSRafael Espindola 
721dbb0bd1aSRafael Espindola   if (Dest.isWeakForLinker()) {
722dbb0bd1aSRafael Espindola     assert(Src.hasExternalLinkage());
723d12b4a33SRafael Espindola     LinkFromSrc = true;
724d12b4a33SRafael Espindola     return false;
725dbb0bd1aSRafael Espindola   }
726dbb0bd1aSRafael Espindola 
727dbb0bd1aSRafael Espindola   assert(!Src.hasExternalWeakLinkage());
728dbb0bd1aSRafael Espindola   assert(!Dest.hasExternalWeakLinkage());
729dbb0bd1aSRafael Espindola   assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
730dbb0bd1aSRafael Espindola          "Unexpected linkage type!");
731dbb0bd1aSRafael Espindola   return emitError("Linking globals named '" + Src.getName() +
732dbb0bd1aSRafael Espindola                    "': symbol multiply defined!");
733dbb0bd1aSRafael Espindola }
734dbb0bd1aSRafael Espindola 
73518c89411SRafael Espindola /// Loop over all of the linked values to compute type mappings.  For example,
73618c89411SRafael Espindola /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
73718c89411SRafael Espindola /// types 'Foo' but one got renamed when the module was loaded into the same
73818c89411SRafael Espindola /// LLVMContext.
739b1ed91f3SChris Lattner void ModuleLinker::computeTypeMapping() {
740c8a476eeSRafael Espindola   for (GlobalValue &SGV : SrcM->globals()) {
741c8a476eeSRafael Espindola     GlobalValue *DGV = getLinkedToGlobal(&SGV);
742c8a476eeSRafael Espindola     if (!DGV)
743c8a476eeSRafael Espindola       continue;
744b1ed91f3SChris Lattner 
745c8a476eeSRafael Espindola     if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
746c8a476eeSRafael Espindola       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
747b1ed91f3SChris Lattner       continue;
7485c310be0SDevang Patel     }
7495c310be0SDevang Patel 
750b1ed91f3SChris Lattner     // Unify the element type of appending arrays.
751b1ed91f3SChris Lattner     ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
752c8a476eeSRafael Espindola     ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
753b1ed91f3SChris Lattner     TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
754b1ed91f3SChris Lattner   }
75534fc5a0eSChris Lattner 
756c8a476eeSRafael Espindola   for (GlobalValue &SGV : *SrcM) {
757c8a476eeSRafael Espindola     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
758c8a476eeSRafael Espindola       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
759b1ed91f3SChris Lattner   }
760e79f4c77SAnton Korobeynikov 
761e96d7eb8SRafael Espindola   for (GlobalValue &SGV : SrcM->aliases()) {
762e96d7eb8SRafael Espindola     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
763e96d7eb8SRafael Espindola       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
764e96d7eb8SRafael Espindola   }
765e96d7eb8SRafael Espindola 
766d48b7783SBill Wendling   // Incorporate types by name, scanning all the types in the source module.
767d48b7783SBill Wendling   // At this point, the destination module may have a type "%foo = { i32 }" for
7682b3f61afSBill Wendling   // example.  When the source module got loaded into the same LLVMContext, if
7692b3f61afSBill Wendling   // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
7708555a37cSBill Wendling   TypeFinder SrcStructTypes;
7718555a37cSBill Wendling   SrcStructTypes.run(*SrcM, true);
7722b3f61afSBill Wendling   SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
7732b3f61afSBill Wendling                                                  SrcStructTypes.end());
7742b3f61afSBill Wendling 
7752b3f61afSBill Wendling   for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
7762b3f61afSBill Wendling     StructType *ST = SrcStructTypes[i];
7772b3f61afSBill Wendling     if (!ST->hasName()) continue;
7782b3f61afSBill Wendling 
7792b3f61afSBill Wendling     // Check to see if there is a dot in the name followed by a digit.
780d48b7783SBill Wendling     size_t DotPos = ST->getName().rfind('.');
781d48b7783SBill Wendling     if (DotPos == 0 || DotPos == StringRef::npos ||
78283c74e9fSGuy Benyei         ST->getName().back() == '.' ||
78383c74e9fSGuy Benyei         !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
784d48b7783SBill Wendling       continue;
7852b3f61afSBill Wendling 
7862b3f61afSBill Wendling     // Check to see if the destination module has a struct with the prefix name.
787d48b7783SBill Wendling     if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
7882b3f61afSBill Wendling       // Don't use it if this actually came from the source module. They're in
7898737480dSBill Wendling       // the same LLVMContext after all. Also don't use it unless the type is
7908737480dSBill Wendling       // actually used in the destination module. This can happen in situations
7918737480dSBill Wendling       // like this:
7928737480dSBill Wendling       //
7938737480dSBill Wendling       //      Module A                         Module B
7948737480dSBill Wendling       //      --------                         --------
7958737480dSBill Wendling       //   %Z = type { %A }                %B = type { %C.1 }
7968737480dSBill Wendling       //   %A = type { %B.1, [7 x i8] }    %C.1 = type { i8* }
7978737480dSBill Wendling       //   %B.1 = type { %C }              %A.2 = type { %B.3, [5 x i8] }
7988737480dSBill Wendling       //   %C = type { i8* }               %B.3 = type { %C.1 }
7998737480dSBill Wendling       //
8008737480dSBill Wendling       // When we link Module B with Module A, the '%B' in Module B is
8018737480dSBill Wendling       // used. However, that would then use '%C.1'. But when we process '%C.1',
8028737480dSBill Wendling       // we prefer to take the '%C' version. So we are then left with both
8038737480dSBill Wendling       // '%C.1' and '%C' being used for the same types. This leads to some
8048737480dSBill Wendling       // variables using one type and some using the other.
805aa9918aaSRafael Espindola       if (!SrcStructTypesSet.count(DST) && TypeMap.DstStructTypesSet.count(DST))
8062b3f61afSBill Wendling         TypeMap.addTypeMapping(DST, ST);
8072b3f61afSBill Wendling   }
8082b3f61afSBill Wendling 
809b1ed91f3SChris Lattner   // Now that we have discovered all of the type equivalences, get a body for
810b1ed91f3SChris Lattner   // any 'opaque' types in the dest module that are now resolved.
811b1ed91f3SChris Lattner   TypeMap.linkDefinedTypeBodies();
812b1ed91f3SChris Lattner }
813c08e7a00SChris Lattner 
81409d84addSDuncan P. N. Exon Smith static void upgradeGlobalArray(GlobalVariable *GV) {
81509d84addSDuncan P. N. Exon Smith   ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
81609d84addSDuncan P. N. Exon Smith   StructType *OldTy = cast<StructType>(ATy->getElementType());
81709d84addSDuncan P. N. Exon Smith   assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
81809d84addSDuncan P. N. Exon Smith 
81909d84addSDuncan P. N. Exon Smith   // Get the upgraded 3 element type.
82009d84addSDuncan P. N. Exon Smith   PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
82109d84addSDuncan P. N. Exon Smith   Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
82209d84addSDuncan P. N. Exon Smith                   VoidPtrTy};
82309d84addSDuncan P. N. Exon Smith   StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
82409d84addSDuncan P. N. Exon Smith 
82509d84addSDuncan P. N. Exon Smith   // Build new constants with a null third field filled in.
82609d84addSDuncan P. N. Exon Smith   Constant *OldInitC = GV->getInitializer();
82709d84addSDuncan P. N. Exon Smith   ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
82809d84addSDuncan P. N. Exon Smith   if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
82909d84addSDuncan P. N. Exon Smith     // Invalid initializer; give up.
83009d84addSDuncan P. N. Exon Smith     return;
83109d84addSDuncan P. N. Exon Smith   std::vector<Constant *> Initializers;
83209d84addSDuncan P. N. Exon Smith   if (OldInit && OldInit->getNumOperands()) {
83309d84addSDuncan P. N. Exon Smith     Value *Null = Constant::getNullValue(VoidPtrTy);
83409d84addSDuncan P. N. Exon Smith     for (Use &U : OldInit->operands()) {
83509d84addSDuncan P. N. Exon Smith       ConstantStruct *Init = cast<ConstantStruct>(U.get());
83609d84addSDuncan P. N. Exon Smith       Initializers.push_back(ConstantStruct::get(
83709d84addSDuncan P. N. Exon Smith           NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
83809d84addSDuncan P. N. Exon Smith     }
83909d84addSDuncan P. N. Exon Smith   }
84009d84addSDuncan P. N. Exon Smith   assert(Initializers.size() == ATy->getNumElements() &&
84109d84addSDuncan P. N. Exon Smith          "Failed to copy all array elements");
84209d84addSDuncan P. N. Exon Smith 
84309d84addSDuncan P. N. Exon Smith   // Replace the old GV with a new one.
84409d84addSDuncan P. N. Exon Smith   ATy = ArrayType::get(NewTy, Initializers.size());
84509d84addSDuncan P. N. Exon Smith   Constant *NewInit = ConstantArray::get(ATy, Initializers);
84609d84addSDuncan P. N. Exon Smith   GlobalVariable *NewGV = new GlobalVariable(
84709d84addSDuncan P. N. Exon Smith       *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
84809d84addSDuncan P. N. Exon Smith       GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
84909d84addSDuncan P. N. Exon Smith       GV->isExternallyInitialized());
85009d84addSDuncan P. N. Exon Smith   NewGV->copyAttributesFrom(GV);
85109d84addSDuncan P. N. Exon Smith   NewGV->takeName(GV);
85209d84addSDuncan P. N. Exon Smith   assert(GV->use_empty() && "program cannot use initializer list");
85309d84addSDuncan P. N. Exon Smith   GV->eraseFromParent();
85409d84addSDuncan P. N. Exon Smith }
85509d84addSDuncan P. N. Exon Smith 
85609d84addSDuncan P. N. Exon Smith void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
85709d84addSDuncan P. N. Exon Smith   // Look for the global arrays.
85809d84addSDuncan P. N. Exon Smith   auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name));
85909d84addSDuncan P. N. Exon Smith   if (!DstGV)
86009d84addSDuncan P. N. Exon Smith     return;
86109d84addSDuncan P. N. Exon Smith   auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name));
86209d84addSDuncan P. N. Exon Smith   if (!SrcGV)
86309d84addSDuncan P. N. Exon Smith     return;
86409d84addSDuncan P. N. Exon Smith 
86509d84addSDuncan P. N. Exon Smith   // Check if the types already match.
86609d84addSDuncan P. N. Exon Smith   auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
86709d84addSDuncan P. N. Exon Smith   auto *SrcTy =
86809d84addSDuncan P. N. Exon Smith       cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
86909d84addSDuncan P. N. Exon Smith   if (DstTy == SrcTy)
87009d84addSDuncan P. N. Exon Smith     return;
87109d84addSDuncan P. N. Exon Smith 
87209d84addSDuncan P. N. Exon Smith   // Grab the element types.  We can only upgrade an array of a two-field
87309d84addSDuncan P. N. Exon Smith   // struct.  Only bother if the other one has three-fields.
87409d84addSDuncan P. N. Exon Smith   auto *DstEltTy = cast<StructType>(DstTy->getElementType());
87509d84addSDuncan P. N. Exon Smith   auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
87609d84addSDuncan P. N. Exon Smith   if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
87709d84addSDuncan P. N. Exon Smith     upgradeGlobalArray(DstGV);
87809d84addSDuncan P. N. Exon Smith     return;
87909d84addSDuncan P. N. Exon Smith   }
88009d84addSDuncan P. N. Exon Smith   if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
88109d84addSDuncan P. N. Exon Smith     upgradeGlobalArray(SrcGV);
88209d84addSDuncan P. N. Exon Smith 
88309d84addSDuncan P. N. Exon Smith   // We can't upgrade any other differences.
88409d84addSDuncan P. N. Exon Smith }
88509d84addSDuncan P. N. Exon Smith 
88609d84addSDuncan P. N. Exon Smith void ModuleLinker::upgradeMismatchedGlobals() {
88709d84addSDuncan P. N. Exon Smith   upgradeMismatchedGlobalArray("llvm.global_ctors");
88809d84addSDuncan P. N. Exon Smith   upgradeMismatchedGlobalArray("llvm.global_dtors");
88909d84addSDuncan P. N. Exon Smith }
89009d84addSDuncan P. N. Exon Smith 
89118c89411SRafael Espindola /// If there were any appending global variables, link them together now.
89218c89411SRafael Espindola /// Return true on error.
893b1ed91f3SChris Lattner bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
8943e8bc6a8SRafael Espindola                                          const GlobalVariable *SrcGV) {
895d48b7783SBill Wendling 
896b1ed91f3SChris Lattner   if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
897b1ed91f3SChris Lattner     return emitError("Linking globals named '" + SrcGV->getName() +
898b1ed91f3SChris Lattner            "': can only link appending global with another appending global!");
899361e513dSReid Spencer 
900b1ed91f3SChris Lattner   ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
901b1ed91f3SChris Lattner   ArrayType *SrcTy =
902b1ed91f3SChris Lattner     cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
903b1ed91f3SChris Lattner   Type *EltTy = DstTy->getElementType();
904b1ed91f3SChris Lattner 
905b1ed91f3SChris Lattner   // Check to see that they two arrays agree on type.
906b1ed91f3SChris Lattner   if (EltTy != SrcTy->getElementType())
907b1ed91f3SChris Lattner     return emitError("Appending variables with different element types!");
908b1ed91f3SChris Lattner   if (DstGV->isConstant() != SrcGV->isConstant())
909b1ed91f3SChris Lattner     return emitError("Appending variables linked with different const'ness!");
910b1ed91f3SChris Lattner 
911b1ed91f3SChris Lattner   if (DstGV->getAlignment() != SrcGV->getAlignment())
912b1ed91f3SChris Lattner     return emitError(
913b1ed91f3SChris Lattner              "Appending variables with different alignment need to be linked!");
914b1ed91f3SChris Lattner 
915b1ed91f3SChris Lattner   if (DstGV->getVisibility() != SrcGV->getVisibility())
916b1ed91f3SChris Lattner     return emitError(
917b1ed91f3SChris Lattner             "Appending variables with different visibility need to be linked!");
918b1ed91f3SChris Lattner 
919fac3a018SRafael Espindola   if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
920fac3a018SRafael Espindola     return emitError(
921fac3a018SRafael Espindola         "Appending variables with different unnamed_addr need to be linked!");
922fac3a018SRafael Espindola 
92364c1e180SRafael Espindola   if (StringRef(DstGV->getSection()) != SrcGV->getSection())
924b1ed91f3SChris Lattner     return emitError(
925b1ed91f3SChris Lattner           "Appending variables with different section name need to be linked!");
926b1ed91f3SChris Lattner 
927b1ed91f3SChris Lattner   uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
928b1ed91f3SChris Lattner   ArrayType *NewType = ArrayType::get(EltTy, NewSize);
929b1ed91f3SChris Lattner 
930b1ed91f3SChris Lattner   // Create the new global variable.
931b1ed91f3SChris Lattner   GlobalVariable *NG =
932b1ed91f3SChris Lattner     new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
9332617dcceSCraig Topper                        DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
934cbe34b4cSHans Wennborg                        DstGV->getThreadLocalMode(),
935b1ed91f3SChris Lattner                        DstGV->getType()->getAddressSpace());
936b1ed91f3SChris Lattner 
937b1ed91f3SChris Lattner   // Propagate alignment, visibility and section info.
938b6af2f36SBill Wendling   copyGVAttributes(NG, DstGV);
939b1ed91f3SChris Lattner 
940b1ed91f3SChris Lattner   AppendingVarInfo AVI;
941b1ed91f3SChris Lattner   AVI.NewGV = NG;
942b1ed91f3SChris Lattner   AVI.DstInit = DstGV->getInitializer();
943b1ed91f3SChris Lattner   AVI.SrcInit = SrcGV->getInitializer();
944b1ed91f3SChris Lattner   AppendingVars.push_back(AVI);
945b1ed91f3SChris Lattner 
946b1ed91f3SChris Lattner   // Replace any uses of the two global variables with uses of the new
947b1ed91f3SChris Lattner   // global.
948b1ed91f3SChris Lattner   ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
949b1ed91f3SChris Lattner 
950b1ed91f3SChris Lattner   DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
951b1ed91f3SChris Lattner   DstGV->eraseFromParent();
952b1ed91f3SChris Lattner 
953cbb91408STanya Lattner   // Track the source variable so we don't try to link it.
954cbb91408STanya Lattner   DoNotLinkFromSource.insert(SrcGV);
955cbb91408STanya Lattner 
956b1ed91f3SChris Lattner   return false;
957b1ed91f3SChris Lattner }
958b1ed91f3SChris Lattner 
959778fcc77SRafael Espindola bool ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) {
960b1ed91f3SChris Lattner   GlobalValue *DGV = getLinkedToGlobal(SGV);
961b1ed91f3SChris Lattner 
962778fcc77SRafael Espindola   // Handle the ultra special appending linkage case first.
963778fcc77SRafael Espindola   if (DGV && DGV->hasAppendingLinkage())
964778fcc77SRafael Espindola     return linkAppendingVarProto(cast<GlobalVariable>(DGV),
965778fcc77SRafael Espindola                                  cast<GlobalVariable>(SGV));
966778fcc77SRafael Espindola 
967778fcc77SRafael Espindola   bool LinkFromSrc = true;
968778fcc77SRafael Espindola   Comdat *C = nullptr;
969778fcc77SRafael Espindola   GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
970778fcc77SRafael Espindola   bool HasUnnamedAddr = SGV->hasUnnamedAddr();
971778fcc77SRafael Espindola 
972dad0a645SDavid Majnemer   if (const Comdat *SC = SGV->getComdat()) {
973dad0a645SDavid Majnemer     Comdat::SelectionKind SK;
974dad0a645SDavid Majnemer     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
975778fcc77SRafael Espindola     C = DstM->getOrInsertComdat(SC->getName());
976778fcc77SRafael Espindola     C->setSelectionKind(SK);
977778fcc77SRafael Espindola   } else if (DGV) {
978778fcc77SRafael Espindola     if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
979fc61de39SChris Lattner       return true;
980dad0a645SDavid Majnemer   }
98134fc5a0eSChris Lattner 
982dad0a645SDavid Majnemer   if (!LinkFromSrc) {
983cbb91408STanya Lattner     // Track the source global so that we don't attempt to copy it over when
984cbb91408STanya Lattner     // processing global initializers.
985cbb91408STanya Lattner     DoNotLinkFromSource.insert(SGV);
986cbb91408STanya Lattner 
987778fcc77SRafael Espindola     if (DGV)
988778fcc77SRafael Espindola       // Make sure to remember this mapping.
989778fcc77SRafael Espindola       ValueMap[SGV] =
990778fcc77SRafael Espindola           ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->getType()));
991778fcc77SRafael Espindola   }
992778fcc77SRafael Espindola 
993778fcc77SRafael Espindola   if (DGV) {
994778fcc77SRafael Espindola     Visibility = isLessConstraining(Visibility, DGV->getVisibility())
995778fcc77SRafael Espindola                      ? DGV->getVisibility()
996778fcc77SRafael Espindola                      : Visibility;
997778fcc77SRafael Espindola     HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
998778fcc77SRafael Espindola   }
999778fcc77SRafael Espindola 
1000778fcc77SRafael Espindola   if (!LinkFromSrc && !DGV)
1001dad0a645SDavid Majnemer     return false;
1002778fcc77SRafael Espindola 
1003778fcc77SRafael Espindola   GlobalValue *NewGV;
1004778fcc77SRafael Espindola   if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
1005778fcc77SRafael Espindola     NewGV = linkGlobalVariableProto(SGVar, DGV, LinkFromSrc);
1006778fcc77SRafael Espindola     if (!NewGV)
1007778fcc77SRafael Espindola       return true;
1008778fcc77SRafael Espindola   } else if (auto *SF = dyn_cast<Function>(SGV)) {
1009778fcc77SRafael Espindola     NewGV = linkFunctionProto(SF, DGV, LinkFromSrc);
1010778fcc77SRafael Espindola   } else {
1011778fcc77SRafael Espindola     NewGV = linkGlobalAliasProto(cast<GlobalAlias>(SGV), DGV, LinkFromSrc);
1012778fcc77SRafael Espindola   }
1013778fcc77SRafael Espindola 
1014778fcc77SRafael Espindola   if (NewGV) {
1015778fcc77SRafael Espindola     if (NewGV != DGV)
1016778fcc77SRafael Espindola       copyGVAttributes(NewGV, SGV);
1017778fcc77SRafael Espindola 
1018778fcc77SRafael Espindola     NewGV->setUnnamedAddr(HasUnnamedAddr);
1019778fcc77SRafael Espindola     NewGV->setVisibility(Visibility);
1020778fcc77SRafael Espindola 
1021778fcc77SRafael Espindola     if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
1022778fcc77SRafael Espindola       if (C)
1023778fcc77SRafael Espindola         NewGO->setComdat(C);
1024778fcc77SRafael Espindola     }
1025778fcc77SRafael Espindola 
1026778fcc77SRafael Espindola     // Make sure to remember this mapping.
1027778fcc77SRafael Espindola     if (NewGV != DGV) {
1028778fcc77SRafael Espindola       if (DGV) {
1029778fcc77SRafael Espindola         DGV->replaceAllUsesWith(
1030778fcc77SRafael Espindola             ConstantExpr::getBitCast(NewGV, DGV->getType()));
1031778fcc77SRafael Espindola         DGV->eraseFromParent();
1032778fcc77SRafael Espindola       }
1033778fcc77SRafael Espindola       ValueMap[SGV] = NewGV;
1034dad0a645SDavid Majnemer     }
10354e27567aSRafael Espindola   }
10364e27567aSRafael Espindola 
1037fd38af2dSChandler Carruth   return false;
10384e27567aSRafael Espindola }
10394e27567aSRafael Espindola 
1040778fcc77SRafael Espindola /// Loop through the global variables in the src module and merge them into the
1041778fcc77SRafael Espindola /// dest module.
1042778fcc77SRafael Espindola GlobalValue *ModuleLinker::linkGlobalVariableProto(const GlobalVariable *SGVar,
1043778fcc77SRafael Espindola                                                    GlobalValue *DGV,
1044778fcc77SRafael Espindola                                                    bool LinkFromSrc) {
1045778fcc77SRafael Espindola   unsigned Alignment = 0;
1046778fcc77SRafael Espindola   bool ClearConstant = false;
1047778fcc77SRafael Espindola 
1048778fcc77SRafael Espindola   if (DGV) {
1049778fcc77SRafael Espindola     if (DGV->hasCommonLinkage() && SGVar->hasCommonLinkage())
1050778fcc77SRafael Espindola       Alignment = std::max(SGVar->getAlignment(), DGV->getAlignment());
1051778fcc77SRafael Espindola 
1052778fcc77SRafael Espindola     auto *DGVar = dyn_cast<GlobalVariable>(DGV);
1053778fcc77SRafael Espindola     if (!SGVar->isConstant() || (DGVar && !DGVar->isConstant()))
1054778fcc77SRafael Espindola       ClearConstant = true;
1055778fcc77SRafael Espindola   }
1056778fcc77SRafael Espindola 
1057778fcc77SRafael Espindola   if (!LinkFromSrc) {
1058778fcc77SRafael Espindola     if (auto *NewGVar = dyn_cast<GlobalVariable>(DGV)) {
1059778fcc77SRafael Espindola       if (Alignment)
1060778fcc77SRafael Espindola         NewGVar->setAlignment(Alignment);
1061778fcc77SRafael Espindola       if (NewGVar->isDeclaration() && ClearConstant)
1062778fcc77SRafael Espindola         NewGVar->setConstant(false);
1063778fcc77SRafael Espindola     }
1064778fcc77SRafael Espindola     return DGV;
1065778fcc77SRafael Espindola   }
1066778fcc77SRafael Espindola 
1067b1ed91f3SChris Lattner   // No linking to be performed or linking from the source: simply create an
1068b1ed91f3SChris Lattner   // identical version of the symbol over in the dest module... the
1069b1ed91f3SChris Lattner   // initializer will be filled in later by LinkGlobalInits.
1070778fcc77SRafael Espindola   GlobalVariable *NewDGV = new GlobalVariable(
1071778fcc77SRafael Espindola       *DstM, TypeMap.get(SGVar->getType()->getElementType()),
1072778fcc77SRafael Espindola       SGVar->isConstant(), SGVar->getLinkage(), /*init*/ nullptr,
1073778fcc77SRafael Espindola       SGVar->getName(), /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
1074778fcc77SRafael Espindola       SGVar->getType()->getAddressSpace());
1075778fcc77SRafael Espindola 
1076778fcc77SRafael Espindola   if (Alignment)
1077fe3842cdSRafael Espindola     NewDGV->setAlignment(Alignment);
1078b1ed91f3SChris Lattner 
1079778fcc77SRafael Espindola   return NewDGV;
1080361e513dSReid Spencer }
1081361e513dSReid Spencer 
108218c89411SRafael Espindola /// Link the function in the source module into the destination module if
108318c89411SRafael Espindola /// needed, setting up mapping information.
1084778fcc77SRafael Espindola GlobalValue *ModuleLinker::linkFunctionProto(const Function *SF,
1085778fcc77SRafael Espindola                                              GlobalValue *DGV,
1086778fcc77SRafael Espindola                                              bool LinkFromSrc) {
1087778fcc77SRafael Espindola   if (!LinkFromSrc)
1088778fcc77SRafael Espindola     return DGV;
1089b1ed91f3SChris Lattner 
1090f6f121e2SJames Molloy   // If the function is to be lazily linked, don't create it just yet.
1091f6f121e2SJames Molloy   // The ValueMaterializerTy will deal with creating it if it's used.
1092f6f121e2SJames Molloy   if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
1093f6f121e2SJames Molloy                SF->hasAvailableExternallyLinkage())) {
1094f6f121e2SJames Molloy     DoNotLinkFromSource.insert(SF);
1095778fcc77SRafael Espindola     return nullptr;
1096dad0a645SDavid Majnemer   }
1097dad0a645SDavid Majnemer 
1098b1ed91f3SChris Lattner   // If there is no linkage to be performed or we are linking from the source,
1099b1ed91f3SChris Lattner   // bring SF over.
1100778fcc77SRafael Espindola   return Function::Create(TypeMap.get(SF->getFunctionType()), SF->getLinkage(),
1101778fcc77SRafael Espindola                           SF->getName(), DstM);
1102361e513dSReid Spencer }
1103361e513dSReid Spencer 
110418c89411SRafael Espindola /// Set up prototypes for any aliases that come over from the source module.
1105778fcc77SRafael Espindola GlobalValue *ModuleLinker::linkGlobalAliasProto(const GlobalAlias *SGA,
1106778fcc77SRafael Espindola                                                 GlobalValue *DGV,
1107778fcc77SRafael Espindola                                                 bool LinkFromSrc) {
1108778fcc77SRafael Espindola   if (!LinkFromSrc)
1109778fcc77SRafael Espindola     return DGV;
1110dad0a645SDavid Majnemer 
1111b1ed91f3SChris Lattner   // If there is no linkage to be performed or we're linking from the source,
1112b1ed91f3SChris Lattner   // bring over SGA.
11134fe0094fSRafael Espindola   auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType()));
1114778fcc77SRafael Espindola   return GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
111583705658SRafael Espindola                              SGA->getLinkage(), SGA->getName(), DstM);
1116b1ed91f3SChris Lattner }
1117b1ed91f3SChris Lattner 
11183e8bc6a8SRafael Espindola static void getArrayElements(const Constant *C,
11193e8bc6a8SRafael Espindola                              SmallVectorImpl<Constant *> &Dest) {
11206705883aSChris Lattner   unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
112100245f42SChris Lattner 
11226705883aSChris Lattner   for (unsigned i = 0; i != NumElements; ++i)
11236705883aSChris Lattner     Dest.push_back(C->getAggregateElement(i));
112400245f42SChris Lattner }
112500245f42SChris Lattner 
1126b1ed91f3SChris Lattner void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
1127b1ed91f3SChris Lattner   // Merge the initializer.
1128d31dc048SRafael Espindola   SmallVector<Constant *, 16> DstElements;
1129d31dc048SRafael Espindola   getArrayElements(AVI.DstInit, DstElements);
1130b1ed91f3SChris Lattner 
1131d31dc048SRafael Espindola   SmallVector<Constant *, 16> SrcElements;
1132d31dc048SRafael Espindola   getArrayElements(AVI.SrcInit, SrcElements);
113300245f42SChris Lattner 
1134b1ed91f3SChris Lattner   ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
1135d31dc048SRafael Espindola 
1136d31dc048SRafael Espindola   StringRef Name = AVI.NewGV->getName();
1137d31dc048SRafael Espindola   bool IsNewStructor =
1138d31dc048SRafael Espindola       (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
1139d31dc048SRafael Espindola       cast<StructType>(NewType->getElementType())->getNumElements() == 3;
1140d31dc048SRafael Espindola 
1141d31dc048SRafael Espindola   for (auto *V : SrcElements) {
1142d31dc048SRafael Espindola     if (IsNewStructor) {
1143d31dc048SRafael Espindola       Constant *Key = V->getAggregateElement(2);
1144d31dc048SRafael Espindola       if (DoNotLinkFromSource.count(Key))
1145d31dc048SRafael Espindola         continue;
1146d31dc048SRafael Espindola     }
1147d31dc048SRafael Espindola     DstElements.push_back(
1148d31dc048SRafael Espindola         MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer));
1149d31dc048SRafael Espindola   }
1150d31dc048SRafael Espindola   if (IsNewStructor) {
1151d31dc048SRafael Espindola     NewType = ArrayType::get(NewType->getElementType(), DstElements.size());
1152d31dc048SRafael Espindola     AVI.NewGV->mutateType(PointerType::get(NewType, 0));
1153d31dc048SRafael Espindola   }
1154d31dc048SRafael Espindola 
1155d31dc048SRafael Espindola   AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements));
1156b1ed91f3SChris Lattner }
1157b1ed91f3SChris Lattner 
115818c89411SRafael Espindola /// Update the initializers in the Dest module now that all globals that may be
115918c89411SRafael Espindola /// referenced are in Dest.
1160b1ed91f3SChris Lattner void ModuleLinker::linkGlobalInits() {
1161b1ed91f3SChris Lattner   // Loop over all of the globals in the src module, mapping them over as we go
1162b1ed91f3SChris Lattner   for (Module::const_global_iterator I = SrcM->global_begin(),
1163b1ed91f3SChris Lattner        E = SrcM->global_end(); I != E; ++I) {
1164cbb91408STanya Lattner 
1165cbb91408STanya Lattner     // Only process initialized GV's or ones not already in dest.
1166cbb91408STanya Lattner     if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
1167b1ed91f3SChris Lattner 
1168b1ed91f3SChris Lattner     // Grab destination global variable.
1169b1ed91f3SChris Lattner     GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
1170b1ed91f3SChris Lattner     // Figure out what the initializer looks like in the dest module.
1171b1ed91f3SChris Lattner     DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
1172f6f121e2SJames Molloy                                  RF_None, &TypeMap, &ValMaterializer));
1173b1ed91f3SChris Lattner   }
1174b1ed91f3SChris Lattner }
1175b1ed91f3SChris Lattner 
117618c89411SRafael Espindola /// Copy the source function over into the dest function and fix up references
117718c89411SRafael Espindola /// to values. At this point we know that Dest is an external function, and
117818c89411SRafael Espindola /// that Src is not.
1179b1ed91f3SChris Lattner void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
1180b1ed91f3SChris Lattner   assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
1181361e513dSReid Spencer 
11827391dde1SChris Lattner   // Go through and convert function arguments over, remembering the mapping.
1183b1ed91f3SChris Lattner   Function::arg_iterator DI = Dst->arg_begin();
1184531f9e92SChris Lattner   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1185361e513dSReid Spencer        I != E; ++I, ++DI) {
1186b1ed91f3SChris Lattner     DI->setName(I->getName());  // Copy the name over.
1187361e513dSReid Spencer 
1188b1ed91f3SChris Lattner     // Add a mapping to our mapping.
118966a6271cSAnton Korobeynikov     ValueMap[I] = DI;
1190361e513dSReid Spencer   }
1191361e513dSReid Spencer 
11922f0557d0SChris Lattner   // Splice the body of the source function into the dest function.
1193b1ed91f3SChris Lattner   Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
1194361e513dSReid Spencer 
1195361e513dSReid Spencer   // At this point, all of the instructions and values of the function are now
1196361e513dSReid Spencer   // copied over.  The only problem is that they are still referencing values in
1197361e513dSReid Spencer   // the Source function as operands.  Loop through all of the operands of the
119843f8d164SChris Lattner   // functions and patch them up to point to the local versions.
1199b1ed91f3SChris Lattner   for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
120043f8d164SChris Lattner     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
12019f8eff31SRafael Espindola       RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap,
12029f8eff31SRafael Espindola                        &ValMaterializer);
1203cbb91408STanya Lattner 
12047391dde1SChris Lattner   // There is no need to map the arguments anymore.
120544ab8aefSChris Lattner   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
120644ab8aefSChris Lattner        I != E; ++I)
12073aaaa0b2SReid Spencer     ValueMap.erase(I);
1208cbb91408STanya Lattner 
1209361e513dSReid Spencer }
1210361e513dSReid Spencer 
121118c89411SRafael Espindola /// Insert all of the aliases in Src into the Dest module.
1212b1ed91f3SChris Lattner void ModuleLinker::linkAliasBodies() {
1213b1ed91f3SChris Lattner   for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
1214cbb91408STanya Lattner        I != E; ++I) {
1215cbb91408STanya Lattner     if (DoNotLinkFromSource.count(I))
1216cbb91408STanya Lattner       continue;
1217b1ed91f3SChris Lattner     if (Constant *Aliasee = I->getAliasee()) {
1218b1ed91f3SChris Lattner       GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
12196b238633SRafael Espindola       Constant *Val =
12206b238633SRafael Espindola           MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer);
122164c1e180SRafael Espindola       DA->setAliasee(Val);
12222c4a34aeSDavid Chisnall     }
1223b1ed91f3SChris Lattner   }
1224cbb91408STanya Lattner }
1225b1ed91f3SChris Lattner 
122618c89411SRafael Espindola /// Insert all of the named MDNodes in Src into the Dest module.
1227b1ed91f3SChris Lattner void ModuleLinker::linkNamedMDNodes() {
122866f02413SBill Wendling   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1229b1ed91f3SChris Lattner   for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1230b1ed91f3SChris Lattner        E = SrcM->named_metadata_end(); I != E; ++I) {
123166f02413SBill Wendling     // Don't link module flags here. Do them separately.
123266f02413SBill Wendling     if (&*I == SrcModFlags) continue;
1233b1ed91f3SChris Lattner     NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1234b1ed91f3SChris Lattner     // Add Src elements into Dest node.
1235b1ed91f3SChris Lattner     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1236b1ed91f3SChris Lattner       DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
1237f6f121e2SJames Molloy                                    RF_None, &TypeMap, &ValMaterializer));
1238b1ed91f3SChris Lattner   }
1239b1ed91f3SChris Lattner }
1240b1ed91f3SChris Lattner 
124118c89411SRafael Espindola /// Merge the linker flags in Src into the Dest module.
124266f02413SBill Wendling bool ModuleLinker::linkModuleFlagsMetadata() {
12430ec72bbcSDaniel Dunbar   // If the source module has no module flags, we are done.
124466f02413SBill Wendling   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
124566f02413SBill Wendling   if (!SrcModFlags) return false;
124666f02413SBill Wendling 
124766f02413SBill Wendling   // If the destination module doesn't have module flags yet, then just copy
124866f02413SBill Wendling   // over the source module's flags.
12490ec72bbcSDaniel Dunbar   NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
125066f02413SBill Wendling   if (DstModFlags->getNumOperands() == 0) {
125166f02413SBill Wendling     for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
125266f02413SBill Wendling       DstModFlags->addOperand(SrcModFlags->getOperand(I));
125366f02413SBill Wendling 
125466f02413SBill Wendling     return false;
125566f02413SBill Wendling   }
125666f02413SBill Wendling 
12570ec72bbcSDaniel Dunbar   // First build a map of the existing module flags and requirements.
12580ec72bbcSDaniel Dunbar   DenseMap<MDString*, MDNode*> Flags;
12590ec72bbcSDaniel Dunbar   SmallSetVector<MDNode*, 16> Requirements;
12600ec72bbcSDaniel Dunbar   for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1261de36e804SDuncan P. N. Exon Smith     MDNode *Op = DstModFlags->getOperand(I);
12620ec72bbcSDaniel Dunbar     ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
12630ec72bbcSDaniel Dunbar     MDString *ID = cast<MDString>(Op->getOperand(1));
12640ec72bbcSDaniel Dunbar 
12650ec72bbcSDaniel Dunbar     if (Behavior->getZExtValue() == Module::Require) {
12660ec72bbcSDaniel Dunbar       Requirements.insert(cast<MDNode>(Op->getOperand(2)));
12670ec72bbcSDaniel Dunbar     } else {
12680ec72bbcSDaniel Dunbar       Flags[ID] = Op;
12690ec72bbcSDaniel Dunbar     }
12700ec72bbcSDaniel Dunbar   }
12710ec72bbcSDaniel Dunbar 
12720ec72bbcSDaniel Dunbar   // Merge in the flags from the source module, and also collect its set of
12730ec72bbcSDaniel Dunbar   // requirements.
127466f02413SBill Wendling   bool HasErr = false;
12750ec72bbcSDaniel Dunbar   for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1276de36e804SDuncan P. N. Exon Smith     MDNode *SrcOp = SrcModFlags->getOperand(I);
12770ec72bbcSDaniel Dunbar     ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
12780ec72bbcSDaniel Dunbar     MDString *ID = cast<MDString>(SrcOp->getOperand(1));
12790ec72bbcSDaniel Dunbar     MDNode *DstOp = Flags.lookup(ID);
12800ec72bbcSDaniel Dunbar     unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
128166f02413SBill Wendling 
12820ec72bbcSDaniel Dunbar     // If this is a requirement, add it and continue.
12830ec72bbcSDaniel Dunbar     if (SrcBehaviorValue == Module::Require) {
12840ec72bbcSDaniel Dunbar       // If the destination module does not already have this requirement, add
12850ec72bbcSDaniel Dunbar       // it.
12860ec72bbcSDaniel Dunbar       if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
12870ec72bbcSDaniel Dunbar         DstModFlags->addOperand(SrcOp);
12880ec72bbcSDaniel Dunbar       }
12890ec72bbcSDaniel Dunbar       continue;
12900ec72bbcSDaniel Dunbar     }
129166f02413SBill Wendling 
12920ec72bbcSDaniel Dunbar     // If there is no existing flag with this ID, just add it.
12930ec72bbcSDaniel Dunbar     if (!DstOp) {
12940ec72bbcSDaniel Dunbar       Flags[ID] = SrcOp;
12950ec72bbcSDaniel Dunbar       DstModFlags->addOperand(SrcOp);
12960ec72bbcSDaniel Dunbar       continue;
12970ec72bbcSDaniel Dunbar     }
129866f02413SBill Wendling 
12990ec72bbcSDaniel Dunbar     // Otherwise, perform a merge.
13000ec72bbcSDaniel Dunbar     ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
13010ec72bbcSDaniel Dunbar     unsigned DstBehaviorValue = DstBehavior->getZExtValue();
13020ec72bbcSDaniel Dunbar 
13030ec72bbcSDaniel Dunbar     // If either flag has override behavior, handle it first.
13040ec72bbcSDaniel Dunbar     if (DstBehaviorValue == Module::Override) {
13050ec72bbcSDaniel Dunbar       // Diagnose inconsistent flags which both have override behavior.
13060ec72bbcSDaniel Dunbar       if (SrcBehaviorValue == Module::Override &&
13070ec72bbcSDaniel Dunbar           SrcOp->getOperand(2) != DstOp->getOperand(2)) {
13080ec72bbcSDaniel Dunbar         HasErr |= emitError("linking module flags '" + ID->getString() +
13090ec72bbcSDaniel Dunbar                             "': IDs have conflicting override values");
13100ec72bbcSDaniel Dunbar       }
13110ec72bbcSDaniel Dunbar       continue;
13120ec72bbcSDaniel Dunbar     } else if (SrcBehaviorValue == Module::Override) {
13130ec72bbcSDaniel Dunbar       // Update the destination flag to that of the source.
13140ec72bbcSDaniel Dunbar       DstOp->replaceOperandWith(0, SrcBehavior);
13150ec72bbcSDaniel Dunbar       DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
13160ec72bbcSDaniel Dunbar       continue;
13170ec72bbcSDaniel Dunbar     }
13180ec72bbcSDaniel Dunbar 
13190ec72bbcSDaniel Dunbar     // Diagnose inconsistent merge behavior types.
13200ec72bbcSDaniel Dunbar     if (SrcBehaviorValue != DstBehaviorValue) {
13210ec72bbcSDaniel Dunbar       HasErr |= emitError("linking module flags '" + ID->getString() +
132266f02413SBill Wendling                           "': IDs have conflicting behaviors");
13230ec72bbcSDaniel Dunbar       continue;
132466f02413SBill Wendling     }
132566f02413SBill Wendling 
13260ec72bbcSDaniel Dunbar     // Perform the merge for standard behavior types.
13270ec72bbcSDaniel Dunbar     switch (SrcBehaviorValue) {
13280ec72bbcSDaniel Dunbar     case Module::Require:
13292a30d788SCraig Topper     case Module::Override: llvm_unreachable("not possible");
13300ec72bbcSDaniel Dunbar     case Module::Error: {
13310ec72bbcSDaniel Dunbar       // Emit an error if the values differ.
13320ec72bbcSDaniel Dunbar       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
13330ec72bbcSDaniel Dunbar         HasErr |= emitError("linking module flags '" + ID->getString() +
13340ec72bbcSDaniel Dunbar                             "': IDs have conflicting values");
133566f02413SBill Wendling       }
13360ec72bbcSDaniel Dunbar       continue;
133766f02413SBill Wendling     }
13380ec72bbcSDaniel Dunbar     case Module::Warning: {
13390ec72bbcSDaniel Dunbar       // Emit a warning if the values differ.
13400ec72bbcSDaniel Dunbar       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1341d12b4a33SRafael Espindola         emitWarning("linking module flags '" + ID->getString() +
1342d12b4a33SRafael Espindola                     "': IDs have conflicting values");
1343e17f3708SEli Bendersky       }
13440ec72bbcSDaniel Dunbar       continue;
13450ec72bbcSDaniel Dunbar     }
1346d77d9fb0SDaniel Dunbar     case Module::Append: {
1347d77d9fb0SDaniel Dunbar       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1348d77d9fb0SDaniel Dunbar       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1349d77d9fb0SDaniel Dunbar       unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1350d77d9fb0SDaniel Dunbar       Value **VP, **Values = VP = new Value*[NumOps];
1351d77d9fb0SDaniel Dunbar       for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1352d77d9fb0SDaniel Dunbar         *VP = DstValue->getOperand(i);
1353d77d9fb0SDaniel Dunbar       for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1354d77d9fb0SDaniel Dunbar         *VP = SrcValue->getOperand(i);
1355d77d9fb0SDaniel Dunbar       DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1356d77d9fb0SDaniel Dunbar                                                ArrayRef<Value*>(Values,
1357d77d9fb0SDaniel Dunbar                                                                 NumOps)));
1358d77d9fb0SDaniel Dunbar       delete[] Values;
1359d77d9fb0SDaniel Dunbar       break;
1360d77d9fb0SDaniel Dunbar     }
1361d77d9fb0SDaniel Dunbar     case Module::AppendUnique: {
1362d77d9fb0SDaniel Dunbar       SmallSetVector<Value*, 16> Elts;
1363d77d9fb0SDaniel Dunbar       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1364d77d9fb0SDaniel Dunbar       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1365d77d9fb0SDaniel Dunbar       for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1366d77d9fb0SDaniel Dunbar         Elts.insert(DstValue->getOperand(i));
1367d77d9fb0SDaniel Dunbar       for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1368d77d9fb0SDaniel Dunbar         Elts.insert(SrcValue->getOperand(i));
1369d77d9fb0SDaniel Dunbar       DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1370d77d9fb0SDaniel Dunbar                                                ArrayRef<Value*>(Elts.begin(),
1371d77d9fb0SDaniel Dunbar                                                                 Elts.end())));
1372d77d9fb0SDaniel Dunbar       break;
1373d77d9fb0SDaniel Dunbar     }
137466f02413SBill Wendling     }
137566f02413SBill Wendling   }
137666f02413SBill Wendling 
13770ec72bbcSDaniel Dunbar   // Check all of the requirements.
13780ec72bbcSDaniel Dunbar   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
13790ec72bbcSDaniel Dunbar     MDNode *Requirement = Requirements[I];
13800ec72bbcSDaniel Dunbar     MDString *Flag = cast<MDString>(Requirement->getOperand(0));
13810ec72bbcSDaniel Dunbar     Value *ReqValue = Requirement->getOperand(1);
13820ec72bbcSDaniel Dunbar 
13830ec72bbcSDaniel Dunbar     MDNode *Op = Flags[Flag];
13840ec72bbcSDaniel Dunbar     if (!Op || Op->getOperand(2) != ReqValue) {
13850ec72bbcSDaniel Dunbar       HasErr |= emitError("linking module flags '" + Flag->getString() +
13869273b539SBill Wendling                           "': does not have the required value");
13870ec72bbcSDaniel Dunbar       continue;
138866f02413SBill Wendling     }
138966f02413SBill Wendling   }
139066f02413SBill Wendling 
139166f02413SBill Wendling   return HasErr;
139266f02413SBill Wendling }
139366f02413SBill Wendling 
1394b1ed91f3SChris Lattner bool ModuleLinker::run() {
139566f02413SBill Wendling   assert(DstM && "Null destination module");
139666f02413SBill Wendling   assert(SrcM && "Null source module");
1397b1ed91f3SChris Lattner 
1398b1ed91f3SChris Lattner   // Inherit the target data from the source module if the destination module
1399b1ed91f3SChris Lattner   // doesn't have one already.
1400f863ee29SRafael Espindola   if (!DstM->getDataLayout() && SrcM->getDataLayout())
1401b1ed91f3SChris Lattner     DstM->setDataLayout(SrcM->getDataLayout());
1402b1ed91f3SChris Lattner 
1403b1ed91f3SChris Lattner   // Copy the target triple from the source to dest if the dest's is empty.
1404b1ed91f3SChris Lattner   if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1405b1ed91f3SChris Lattner     DstM->setTargetTriple(SrcM->getTargetTriple());
1406b1ed91f3SChris Lattner 
1407f863ee29SRafael Espindola   if (SrcM->getDataLayout() && DstM->getDataLayout() &&
1408ae593f15SRafael Espindola       *SrcM->getDataLayout() != *DstM->getDataLayout()) {
1409d12b4a33SRafael Espindola     emitWarning("Linking two modules of different data layouts: '" +
1410d12b4a33SRafael Espindola                 SrcM->getModuleIdentifier() + "' is '" +
1411d12b4a33SRafael Espindola                 SrcM->getDataLayoutStr() + "' whereas '" +
1412d12b4a33SRafael Espindola                 DstM->getModuleIdentifier() + "' is '" +
1413d12b4a33SRafael Espindola                 DstM->getDataLayoutStr() + "'\n");
1414e17f3708SEli Bendersky   }
1415b1ed91f3SChris Lattner   if (!SrcM->getTargetTriple().empty() &&
1416b1ed91f3SChris Lattner       DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1417d12b4a33SRafael Espindola     emitWarning("Linking two modules of different target triples: " +
1418d12b4a33SRafael Espindola                 SrcM->getModuleIdentifier() + "' is '" +
1419d12b4a33SRafael Espindola                 SrcM->getTargetTriple() + "' whereas '" +
1420d12b4a33SRafael Espindola                 DstM->getModuleIdentifier() + "' is '" +
1421d12b4a33SRafael Espindola                 DstM->getTargetTriple() + "'\n");
1422e17f3708SEli Bendersky   }
1423b1ed91f3SChris Lattner 
1424b1ed91f3SChris Lattner   // Append the module inline asm string.
1425b1ed91f3SChris Lattner   if (!SrcM->getModuleInlineAsm().empty()) {
1426b1ed91f3SChris Lattner     if (DstM->getModuleInlineAsm().empty())
1427b1ed91f3SChris Lattner       DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1428b1ed91f3SChris Lattner     else
1429b1ed91f3SChris Lattner       DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1430b1ed91f3SChris Lattner                                SrcM->getModuleInlineAsm());
1431b1ed91f3SChris Lattner   }
1432b1ed91f3SChris Lattner 
1433b1ed91f3SChris Lattner   // Loop over all of the linked values to compute type mappings.
1434b1ed91f3SChris Lattner   computeTypeMapping();
1435b1ed91f3SChris Lattner 
1436dad0a645SDavid Majnemer   ComdatsChosen.clear();
14375106ce78SDavid Blaikie   for (const auto &SMEC : SrcM->getComdatSymbolTable()) {
1438dad0a645SDavid Majnemer     const Comdat &C = SMEC.getValue();
1439dad0a645SDavid Majnemer     if (ComdatsChosen.count(&C))
1440dad0a645SDavid Majnemer       continue;
1441dad0a645SDavid Majnemer     Comdat::SelectionKind SK;
1442dad0a645SDavid Majnemer     bool LinkFromSrc;
1443dad0a645SDavid Majnemer     if (getComdatResult(&C, SK, LinkFromSrc))
1444dad0a645SDavid Majnemer       return true;
1445dad0a645SDavid Majnemer     ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1446dad0a645SDavid Majnemer   }
1447dad0a645SDavid Majnemer 
144809d84addSDuncan P. N. Exon Smith   // Upgrade mismatched global arrays.
144909d84addSDuncan P. N. Exon Smith   upgradeMismatchedGlobals();
145009d84addSDuncan P. N. Exon Smith 
1451b1ed91f3SChris Lattner   // Insert all of the globals in src into the DstM module... without linking
1452b1ed91f3SChris Lattner   // initializers (which could refer to functions not yet mapped over).
1453b1ed91f3SChris Lattner   for (Module::global_iterator I = SrcM->global_begin(),
1454b1ed91f3SChris Lattner        E = SrcM->global_end(); I != E; ++I)
1455778fcc77SRafael Espindola     if (linkGlobalValueProto(I))
1456b1ed91f3SChris Lattner       return true;
1457b1ed91f3SChris Lattner 
1458b1ed91f3SChris Lattner   // Link the functions together between the two modules, without doing function
1459b1ed91f3SChris Lattner   // bodies... this just adds external function prototypes to the DstM
1460b1ed91f3SChris Lattner   // function...  We do this so that when we begin processing function bodies,
1461b1ed91f3SChris Lattner   // all of the global values that may be referenced are available in our
1462b1ed91f3SChris Lattner   // ValueMap.
1463b1ed91f3SChris Lattner   for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1464778fcc77SRafael Espindola     if (linkGlobalValueProto(I))
1465b1ed91f3SChris Lattner       return true;
1466b1ed91f3SChris Lattner 
1467b1ed91f3SChris Lattner   // If there were any aliases, link them now.
1468b1ed91f3SChris Lattner   for (Module::alias_iterator I = SrcM->alias_begin(),
1469b1ed91f3SChris Lattner        E = SrcM->alias_end(); I != E; ++I)
1470778fcc77SRafael Espindola     if (linkGlobalValueProto(I))
1471b1ed91f3SChris Lattner       return true;
1472b1ed91f3SChris Lattner 
1473b1ed91f3SChris Lattner   for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1474b1ed91f3SChris Lattner     linkAppendingVarInit(AppendingVars[i]);
1475b1ed91f3SChris Lattner 
1476b1ed91f3SChris Lattner   // Link in the function bodies that are defined in the source module into
1477b1ed91f3SChris Lattner   // DstM.
1478b1ed91f3SChris Lattner   for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
1479ea166d44STanya Lattner     // Skip if not linking from source.
1480ea166d44STanya Lattner     if (DoNotLinkFromSource.count(SF)) continue;
1481ea166d44STanya Lattner 
14823fa50f9bSPeter Collingbourne     Function *DF = cast<Function>(ValueMap[SF]);
14833fa50f9bSPeter Collingbourne     if (SF->hasPrefixData()) {
14843fa50f9bSPeter Collingbourne       // Link in the prefix data.
14853fa50f9bSPeter Collingbourne       DF->setPrefixData(MapValue(
14863fa50f9bSPeter Collingbourne           SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
14873fa50f9bSPeter Collingbourne     }
14883fa50f9bSPeter Collingbourne 
1489d4bcefc7SRafael Espindola     // Materialize if needed.
1490d12b4a33SRafael Espindola     if (std::error_code EC = SF->materialize())
1491d12b4a33SRafael Espindola       return emitError(EC.message());
1492b1ed91f3SChris Lattner 
1493d4bcefc7SRafael Espindola     // Skip if no body (function is external).
1494d4bcefc7SRafael Espindola     if (SF->isDeclaration())
1495d4bcefc7SRafael Espindola       continue;
1496d4bcefc7SRafael Espindola 
14973fa50f9bSPeter Collingbourne     linkFunctionBody(DF, SF);
149800623787SBill Wendling     SF->Dematerialize();
1499b1ed91f3SChris Lattner   }
1500b1ed91f3SChris Lattner 
1501b1ed91f3SChris Lattner   // Resolve all uses of aliases with aliasees.
1502b1ed91f3SChris Lattner   linkAliasBodies();
1503b1ed91f3SChris Lattner 
150466f02413SBill Wendling   // Remap all of the named MDNodes in Src into the DstM module. We do this
15056ddbb2e2SDevang Patel   // after linking GlobalValues so that MDNodes that reference GlobalValues
15066ddbb2e2SDevang Patel   // are properly remapped.
15076ddbb2e2SDevang Patel   linkNamedMDNodes();
15086ddbb2e2SDevang Patel 
150966f02413SBill Wendling   // Merge the module flags into the DstM module.
151066f02413SBill Wendling   if (linkModuleFlagsMetadata())
151166f02413SBill Wendling     return true;
151266f02413SBill Wendling 
151391686d6dSBill Wendling   // Update the initializers in the DstM module now that all globals that may
151491686d6dSBill Wendling   // be referenced are in DstM.
151591686d6dSBill Wendling   linkGlobalInits();
151691686d6dSBill Wendling 
15170a48b877STanya Lattner   // Process vector of lazily linked in functions.
15180a48b877STanya Lattner   bool LinkedInAnyFunctions;
15190a48b877STanya Lattner   do {
15200a48b877STanya Lattner     LinkedInAnyFunctions = false;
15210a48b877STanya Lattner 
1522fa228782SBill Wendling     for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
15230a48b877STanya Lattner         E = LazilyLinkFunctions.end(); I != E; ++I) {
1524f6f121e2SJames Molloy       Function *SF = *I;
1525f6f121e2SJames Molloy       if (!SF)
15260a48b877STanya Lattner         continue;
15270a48b877STanya Lattner 
1528fa228782SBill Wendling       Function *DF = cast<Function>(ValueMap[SF]);
15293fa50f9bSPeter Collingbourne       if (SF->hasPrefixData()) {
15303fa50f9bSPeter Collingbourne         // Link in the prefix data.
15313fa50f9bSPeter Collingbourne         DF->setPrefixData(MapValue(SF->getPrefixData(),
15323fa50f9bSPeter Collingbourne                                    ValueMap,
15333fa50f9bSPeter Collingbourne                                    RF_None,
15343fa50f9bSPeter Collingbourne                                    &TypeMap,
15353fa50f9bSPeter Collingbourne                                    &ValMaterializer));
15363fa50f9bSPeter Collingbourne       }
15370a48b877STanya Lattner 
1538d4bcefc7SRafael Espindola       // Materialize if needed.
1539d12b4a33SRafael Espindola       if (std::error_code EC = SF->materialize())
1540d12b4a33SRafael Espindola         return emitError(EC.message());
15410a48b877STanya Lattner 
1542d4bcefc7SRafael Espindola       // Skip if no body (function is external).
1543d4bcefc7SRafael Espindola       if (SF->isDeclaration())
1544d4bcefc7SRafael Espindola         continue;
1545d4bcefc7SRafael Espindola 
1546f6f121e2SJames Molloy       // Erase from vector *before* the function body is linked - linkFunctionBody could
1547f6f121e2SJames Molloy       // invalidate I.
1548f6f121e2SJames Molloy       LazilyLinkFunctions.erase(I);
1549f6f121e2SJames Molloy 
15500a48b877STanya Lattner       // Link in function body.
15510a48b877STanya Lattner       linkFunctionBody(DF, SF);
155200623787SBill Wendling       SF->Dematerialize();
15530a48b877STanya Lattner 
15540a48b877STanya Lattner       // Set flag to indicate we may have more functions to lazily link in
15550a48b877STanya Lattner       // since we linked in a function.
15560a48b877STanya Lattner       LinkedInAnyFunctions = true;
1557f6f121e2SJames Molloy       break;
15580a48b877STanya Lattner     }
15590a48b877STanya Lattner   } while (LinkedInAnyFunctions);
15600a48b877STanya Lattner 
15612609888fSAnton Korobeynikov   return false;
15622609888fSAnton Korobeynikov }
1563361e513dSReid Spencer 
15645cb9c82aSRafael Espindola void Linker::init(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
15655cb9c82aSRafael Espindola   this->Composite = M;
15665cb9c82aSRafael Espindola   this->DiagnosticHandler = DiagnosticHandler;
15674160f5d3SRafael Espindola 
1568aa9918aaSRafael Espindola   TypeFinder StructTypes;
1569aa9918aaSRafael Espindola   StructTypes.run(*M, true);
1570aa9918aaSRafael Espindola   IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end());
1571aa9918aaSRafael Espindola }
15723df61b7bSRafael Espindola 
15735cb9c82aSRafael Espindola Linker::Linker(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
15745cb9c82aSRafael Espindola   init(M, DiagnosticHandler);
15755cb9c82aSRafael Espindola }
15765cb9c82aSRafael Espindola 
15775cb9c82aSRafael Espindola Linker::Linker(Module *M) {
15785cb9c82aSRafael Espindola   init(M, [this](const DiagnosticInfo &DI) {
15795cb9c82aSRafael Espindola     Composite->getContext().diagnose(DI);
15805cb9c82aSRafael Espindola   });
15815cb9c82aSRafael Espindola }
15825cb9c82aSRafael Espindola 
15833df61b7bSRafael Espindola Linker::~Linker() {
15843df61b7bSRafael Espindola }
15853df61b7bSRafael Espindola 
158691e6f6e1SBill Wendling void Linker::deleteModule() {
158791e6f6e1SBill Wendling   delete Composite;
15882617dcceSCraig Topper   Composite = nullptr;
158991e6f6e1SBill Wendling }
159091e6f6e1SBill Wendling 
15919f8eff31SRafael Espindola bool Linker::linkInModule(Module *Src) {
15929f8eff31SRafael Espindola   ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src,
15939f8eff31SRafael Espindola                          DiagnosticHandler);
1594d12b4a33SRafael Espindola   return TheLinker.run();
15953df61b7bSRafael Espindola }
15963df61b7bSRafael Espindola 
1597b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
1598b1ed91f3SChris Lattner // LinkModules entrypoint.
1599b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
1600b1ed91f3SChris Lattner 
160118c89411SRafael Espindola /// This function links two modules together, with the resulting Dest module
160218c89411SRafael Espindola /// modified to be the composite of the two input modules. If an error occurs,
160318c89411SRafael Espindola /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
160418c89411SRafael Espindola /// Upon failure, the Dest module could be in a modified state, and shouldn't be
160518c89411SRafael Espindola /// relied on to be consistent.
16069f8eff31SRafael Espindola bool Linker::LinkModules(Module *Dest, Module *Src,
16074160f5d3SRafael Espindola                          DiagnosticHandlerFunction DiagnosticHandler) {
16084160f5d3SRafael Espindola   Linker L(Dest, DiagnosticHandler);
16099f8eff31SRafael Espindola   return L.linkInModule(Src);
16104160f5d3SRafael Espindola }
16114160f5d3SRafael Espindola 
16129f8eff31SRafael Espindola bool Linker::LinkModules(Module *Dest, Module *Src) {
1613287f18b4SRafael Espindola   Linker L(Dest);
16149f8eff31SRafael Espindola   return L.linkInModule(Src);
1615361e513dSReid Spencer }
1616a3aeb980SBill Wendling 
1617a3aeb980SBill Wendling //===----------------------------------------------------------------------===//
1618a3aeb980SBill Wendling // C API.
1619a3aeb980SBill Wendling //===----------------------------------------------------------------------===//
1620a3aeb980SBill Wendling 
1621a3aeb980SBill Wendling LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1622a3aeb980SBill Wendling                          LLVMLinkerMode Mode, char **OutMessages) {
162398ab63ceSRafael Espindola   Module *D = unwrap(Dest);
162498ab63ceSRafael Espindola   std::string Message;
16254160f5d3SRafael Espindola   raw_string_ostream Stream(Message);
16264160f5d3SRafael Espindola   DiagnosticPrinterRawOStream DP(Stream);
16274160f5d3SRafael Espindola 
16284160f5d3SRafael Espindola   LLVMBool Result = Linker::LinkModules(
16299f8eff31SRafael Espindola       D, unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
163098ab63ceSRafael Espindola 
163198ab63ceSRafael Espindola   if (OutMessages && Result)
163298ab63ceSRafael Espindola     *OutMessages = strdup(Message.c_str());
1633a3aeb980SBill Wendling   return Result;
1634a3aeb980SBill Wendling }
1635