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"
1631ad468dSRafael Espindola #include "llvm/ADT/Hashing.h"
1723f8d64bSRafael Espindola #include "llvm/ADT/Optional.h"
1866f02413SBill Wendling #include "llvm/ADT/SetVector.h"
190f7fd36fSEli Bendersky #include "llvm/ADT/SmallString.h"
2031ad468dSRafael Espindola #include "llvm/ADT/Statistic.h"
219fb823bbSChandler Carruth #include "llvm/IR/Constants.h"
22fda0cee7SDuncan P. N. Exon Smith #include "llvm/IR/DebugInfo.h"
23d12b4a33SRafael Espindola #include "llvm/IR/DiagnosticInfo.h"
24d12b4a33SRafael Espindola #include "llvm/IR/DiagnosticPrinter.h"
25d12b4a33SRafael Espindola #include "llvm/IR/LLVMContext.h"
269fb823bbSChandler Carruth #include "llvm/IR/Module.h"
27dcb603feSChandler Carruth #include "llvm/IR/TypeFinder.h"
28e17f3708SEli Bendersky #include "llvm/Support/CommandLine.h"
29b6af2f36SBill Wendling #include "llvm/Support/Debug.h"
30b6af2f36SBill Wendling #include "llvm/Support/raw_ostream.h"
31cbb91408STanya Lattner #include "llvm/Transforms/Utils/Cloning.h"
32981af002SWill Dietz #include <cctype>
3382d6ff6bSDavid Majnemer #include <tuple>
34361e513dSReid Spencer using namespace llvm;
35361e513dSReid Spencer 
36e17f3708SEli Bendersky 
37b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
38b1ed91f3SChris Lattner // TypeMap implementation.
39b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
40b1ed91f3SChris Lattner 
41b1ed91f3SChris Lattner namespace {
42b1ed91f3SChris Lattner class TypeMapTy : public ValueMapTypeRemapper {
4318c89411SRafael Espindola   /// This is a mapping from a source type to a destination type to use.
44b1ed91f3SChris Lattner   DenseMap<Type*, Type*> MappedTypes;
45b1ed91f3SChris Lattner 
4618c89411SRafael Espindola   /// When checking to see if two subgraphs are isomorphic, we speculatively
4718c89411SRafael Espindola   /// add types to MappedTypes, but keep track of them here in case we need to
4818c89411SRafael Espindola   /// roll back.
49b1ed91f3SChris Lattner   SmallVector<Type*, 16> SpeculativeTypes;
50b1ed91f3SChris Lattner 
51a96f235cSRafael Espindola   SmallVector<StructType*, 16> SpeculativeDstOpaqueTypes;
52a96f235cSRafael Espindola 
5318c89411SRafael Espindola   /// This is a list of non-opaque structs in the source module that are mapped
5418c89411SRafael Espindola   /// to an opaque struct in the destination module.
555e3bd972SChris Lattner   SmallVector<StructType*, 16> SrcDefinitionsToResolve;
565e3bd972SChris Lattner 
5718c89411SRafael Espindola   /// This is the set of opaque types in the destination modules who are
5818c89411SRafael Espindola   /// getting a body from the source module.
595e3bd972SChris Lattner   SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
60d48b7783SBill Wendling 
618c2cc416SBill Wendling public:
6231ad468dSRafael Espindola   TypeMapTy(Linker::IdentifiedStructTypeSet &DstStructTypesSet)
6331ad468dSRafael Espindola       : DstStructTypesSet(DstStructTypesSet) {}
64aa9918aaSRafael Espindola 
6531ad468dSRafael Espindola   Linker::IdentifiedStructTypeSet &DstStructTypesSet;
6618c89411SRafael Espindola   /// Indicate that the specified type in the destination module is conceptually
6718c89411SRafael Espindola   /// equivalent to the specified type in the source module.
68b1ed91f3SChris Lattner   void addTypeMapping(Type *DstTy, Type *SrcTy);
69b1ed91f3SChris Lattner 
70d2a13a2eSRafael Espindola   /// Produce a body for an opaque type in the dest module from a type
71d2a13a2eSRafael Espindola   /// definition in the source module.
72b1ed91f3SChris Lattner   void linkDefinedTypeBodies();
73b1ed91f3SChris Lattner 
7418c89411SRafael Espindola   /// Return the mapped type to use for the specified input type from the
75b1ed91f3SChris Lattner   /// source module.
76b1ed91f3SChris Lattner   Type *get(Type *SrcTy);
7731ad468dSRafael Espindola   Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
7831ad468dSRafael Espindola 
7931ad468dSRafael Espindola   void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes);
80b1ed91f3SChris Lattner 
81290e2cc5SRafael Espindola   FunctionType *get(FunctionType *T) {
82290e2cc5SRafael Espindola     return cast<FunctionType>(get((Type *)T));
83290e2cc5SRafael Espindola   }
84b1ed91f3SChris Lattner 
8518c89411SRafael Espindola   /// Dump out the type map for debugging purposes.
86b6af2f36SBill Wendling   void dump() const {
878f14471eSRafael Espindola     for (auto &Pair : MappedTypes) {
88b6af2f36SBill Wendling       dbgs() << "TypeMap: ";
898f14471eSRafael Espindola       Pair.first->print(dbgs());
90b6af2f36SBill Wendling       dbgs() << " => ";
918f14471eSRafael Espindola       Pair.second->print(dbgs());
92b6af2f36SBill Wendling       dbgs() << '\n';
93b6af2f36SBill Wendling     }
94b6af2f36SBill Wendling   }
95b6af2f36SBill Wendling 
96b1ed91f3SChris Lattner private:
97290e2cc5SRafael Espindola   Type *remapType(Type *SrcTy) override { return get(SrcTy); }
98b1ed91f3SChris Lattner 
99b1ed91f3SChris Lattner   bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
100b1ed91f3SChris Lattner };
101b1ed91f3SChris Lattner }
102b1ed91f3SChris Lattner 
103b1ed91f3SChris Lattner void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
1043d097410SRafael Espindola   assert(SpeculativeTypes.empty());
105a96f235cSRafael Espindola   assert(SpeculativeDstOpaqueTypes.empty());
1063d097410SRafael Espindola 
107b1ed91f3SChris Lattner   // Check to see if these types are recursively isomorphic and establish a
108b1ed91f3SChris Lattner   // mapping between them if so.
109c586eaa1SDuncan P. N. Exon Smith   if (!areTypesIsomorphic(DstTy, SrcTy)) {
110b1ed91f3SChris Lattner     // Oops, they aren't isomorphic.  Just discard this request by rolling out
111b1ed91f3SChris Lattner     // any speculative mappings we've established.
1123d097410SRafael Espindola     for (Type *Ty : SpeculativeTypes)
1133d097410SRafael Espindola       MappedTypes.erase(Ty);
114a96f235cSRafael Espindola 
115a96f235cSRafael Espindola     SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
116a96f235cSRafael Espindola                                    SpeculativeDstOpaqueTypes.size());
117a96f235cSRafael Espindola     for (StructType *Ty : SpeculativeDstOpaqueTypes)
118a96f235cSRafael Espindola       DstResolvedOpaqueTypes.erase(Ty);
11904a74af7SRafael Espindola   } else {
12004a74af7SRafael Espindola     for (Type *Ty : SpeculativeTypes)
12104a74af7SRafael Espindola       if (auto *STy = dyn_cast<StructType>(Ty))
12204a74af7SRafael Espindola         if (STy->hasName())
12304a74af7SRafael Espindola           STy->setName("");
124d48b7783SBill Wendling   }
125b1ed91f3SChris Lattner   SpeculativeTypes.clear();
126a96f235cSRafael Espindola   SpeculativeDstOpaqueTypes.clear();
127b1ed91f3SChris Lattner }
128b1ed91f3SChris Lattner 
12918c89411SRafael Espindola /// Recursively walk this pair of types, returning true if they are isomorphic,
13018c89411SRafael Espindola /// false if they are not.
131b1ed91f3SChris Lattner bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
132b1ed91f3SChris Lattner   // Two types with differing kinds are clearly not isomorphic.
133290e2cc5SRafael Espindola   if (DstTy->getTypeID() != SrcTy->getTypeID())
134290e2cc5SRafael Espindola     return false;
135b1ed91f3SChris Lattner 
136b1ed91f3SChris Lattner   // If we have an entry in the MappedTypes table, then we have our answer.
137b1ed91f3SChris Lattner   Type *&Entry = MappedTypes[SrcTy];
138b1ed91f3SChris Lattner   if (Entry)
139b1ed91f3SChris Lattner     return Entry == DstTy;
140b1ed91f3SChris Lattner 
141b1ed91f3SChris Lattner   // Two identical types are clearly isomorphic.  Remember this
142b1ed91f3SChris Lattner   // non-speculatively.
143b1ed91f3SChris Lattner   if (DstTy == SrcTy) {
144b1ed91f3SChris Lattner     Entry = DstTy;
145361e513dSReid Spencer     return true;
146361e513dSReid Spencer   }
147361e513dSReid Spencer 
148b1ed91f3SChris Lattner   // Okay, we have two types with identical kinds that we haven't seen before.
149361e513dSReid Spencer 
150b1ed91f3SChris Lattner   // If this is an opaque struct type, special case it.
151b1ed91f3SChris Lattner   if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
152b1ed91f3SChris Lattner     // Mapping an opaque type to any struct, just keep the dest struct.
153b1ed91f3SChris Lattner     if (SSTy->isOpaque()) {
154b1ed91f3SChris Lattner       Entry = DstTy;
155b1ed91f3SChris Lattner       SpeculativeTypes.push_back(SrcTy);
156b1ed91f3SChris Lattner       return true;
157361e513dSReid Spencer     }
158b1ed91f3SChris Lattner 
1595e3bd972SChris Lattner     // Mapping a non-opaque source type to an opaque dest.  If this is the first
1605e3bd972SChris Lattner     // type that we're mapping onto this destination type then we succeed.  Keep
161a96f235cSRafael Espindola     // the dest, but fill it in later. If this is the second (different) type
162a96f235cSRafael Espindola     // that we're trying to map onto the same opaque type then we fail.
163b1ed91f3SChris Lattner     if (cast<StructType>(DstTy)->isOpaque()) {
1645e3bd972SChris Lattner       // We can only map one source type onto the opaque destination type.
16570573dcdSDavid Blaikie       if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
1665e3bd972SChris Lattner         return false;
1675e3bd972SChris Lattner       SrcDefinitionsToResolve.push_back(SSTy);
168a96f235cSRafael Espindola       SpeculativeTypes.push_back(SrcTy);
169a96f235cSRafael Espindola       SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
170b1ed91f3SChris Lattner       Entry = DstTy;
171b1ed91f3SChris Lattner       return true;
172b1ed91f3SChris Lattner     }
173b1ed91f3SChris Lattner   }
174b1ed91f3SChris Lattner 
175b1ed91f3SChris Lattner   // If the number of subtypes disagree between the two types, then we fail.
176b1ed91f3SChris Lattner   if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
177b1ed91f3SChris Lattner     return false;
178b1ed91f3SChris Lattner 
179b1ed91f3SChris Lattner   // Fail if any of the extra properties (e.g. array size) of the type disagree.
180b1ed91f3SChris Lattner   if (isa<IntegerType>(DstTy))
181b1ed91f3SChris Lattner     return false;  // bitwidth disagrees.
182b1ed91f3SChris Lattner   if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
183b1ed91f3SChris Lattner     if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
184b1ed91f3SChris Lattner       return false;
185eaf9b762SChris Lattner 
186b1ed91f3SChris Lattner   } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
187b1ed91f3SChris Lattner     if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
188b1ed91f3SChris Lattner       return false;
189b1ed91f3SChris Lattner   } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
190b1ed91f3SChris Lattner     StructType *SSTy = cast<StructType>(SrcTy);
19144f7ab45SChris Lattner     if (DSTy->isLiteral() != SSTy->isLiteral() ||
192b1ed91f3SChris Lattner         DSTy->isPacked() != SSTy->isPacked())
193b1ed91f3SChris Lattner       return false;
194b1ed91f3SChris Lattner   } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
195b1ed91f3SChris Lattner     if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
196b1ed91f3SChris Lattner       return false;
197b1ed91f3SChris Lattner   } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
1985fad3e9aSJoey Gouly     if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
199361e513dSReid Spencer       return false;
200361e513dSReid Spencer   }
201361e513dSReid Spencer 
202b1ed91f3SChris Lattner   // Otherwise, we speculate that these two types will line up and recursively
203b1ed91f3SChris Lattner   // check the subelements.
204b1ed91f3SChris Lattner   Entry = DstTy;
205b1ed91f3SChris Lattner   SpeculativeTypes.push_back(SrcTy);
206eee6f995SChris Lattner 
207290e2cc5SRafael Espindola   for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
208290e2cc5SRafael Espindola     if (!areTypesIsomorphic(DstTy->getContainedType(I),
209290e2cc5SRafael Espindola                             SrcTy->getContainedType(I)))
210b1ed91f3SChris Lattner       return false;
211eee6f995SChris Lattner 
212b1ed91f3SChris Lattner   // If everything seems to have lined up, then everything is great.
213eee6f995SChris Lattner   return true;
214eee6f995SChris Lattner }
215eee6f995SChris Lattner 
216b1ed91f3SChris Lattner void TypeMapTy::linkDefinedTypeBodies() {
217b1ed91f3SChris Lattner   SmallVector<Type*, 16> Elements;
218c81c3f55SRafael Espindola   for (StructType *SrcSTy : SrcDefinitionsToResolve) {
219b1ed91f3SChris Lattner     StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
220c81c3f55SRafael Espindola     assert(DstSTy->isOpaque());
221b1ed91f3SChris Lattner 
222b1ed91f3SChris Lattner     // Map the body of the source type over to a new body for the dest type.
223b1ed91f3SChris Lattner     Elements.resize(SrcSTy->getNumElements());
224290e2cc5SRafael Espindola     for (unsigned I = 0, E = Elements.size(); I != E; ++I)
225c81c3f55SRafael Espindola       Elements[I] = get(SrcSTy->getElementType(I));
226b1ed91f3SChris Lattner 
227b1ed91f3SChris Lattner     DstSTy->setBody(Elements, SrcSTy->isPacked());
228b1ed91f3SChris Lattner   }
229c81c3f55SRafael Espindola   SrcDefinitionsToResolve.clear();
2305e3bd972SChris Lattner   DstResolvedOpaqueTypes.clear();
231eee6f995SChris Lattner }
232eee6f995SChris Lattner 
23331ad468dSRafael Espindola void TypeMapTy::finishType(StructType *DTy, StructType *STy,
23431ad468dSRafael Espindola                            ArrayRef<Type *> ETypes) {
23531ad468dSRafael Espindola   DTy->setBody(ETypes, STy->isPacked());
236a4e85e3dSRafael Espindola 
23731ad468dSRafael Espindola   // Steal STy's name.
23831ad468dSRafael Espindola   if (STy->hasName()) {
23931ad468dSRafael Espindola     SmallString<16> TmpName = STy->getName();
24031ad468dSRafael Espindola     STy->setName("");
24131ad468dSRafael Espindola     DTy->setName(TmpName);
24231ad468dSRafael Espindola   }
24331ad468dSRafael Espindola 
24431ad468dSRafael Espindola   DstStructTypesSet.addNonOpaque(DTy);
24531ad468dSRafael Espindola }
24631ad468dSRafael Espindola 
24731ad468dSRafael Espindola Type *TypeMapTy::get(Type *Ty) {
24831ad468dSRafael Espindola   SmallPtrSet<StructType *, 8> Visited;
24931ad468dSRafael Espindola   return get(Ty, Visited);
25031ad468dSRafael Espindola }
25131ad468dSRafael Espindola 
25231ad468dSRafael Espindola Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
253b1ed91f3SChris Lattner   // If we already have an entry for this type, return it.
254b1ed91f3SChris Lattner   Type **Entry = &MappedTypes[Ty];
255290e2cc5SRafael Espindola   if (*Entry)
256290e2cc5SRafael Espindola     return *Entry;
257b1ed91f3SChris Lattner 
25831ad468dSRafael Espindola   // These are types that LLVM itself will unique.
25931ad468dSRafael Espindola   bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
26031ad468dSRafael Espindola 
26131ad468dSRafael Espindola #ifndef NDEBUG
26231ad468dSRafael Espindola   if (!IsUniqued) {
26331ad468dSRafael Espindola     for (auto &Pair : MappedTypes) {
26431ad468dSRafael Espindola       assert(!(Pair.first != Ty && Pair.second == Ty) &&
26531ad468dSRafael Espindola              "mapping to a source type");
26631ad468dSRafael Espindola     }
26731ad468dSRafael Espindola   }
26831ad468dSRafael Espindola #endif
26931ad468dSRafael Espindola 
27031ad468dSRafael Espindola   if (!IsUniqued && !Visited.insert(cast<StructType>(Ty)).second) {
27131ad468dSRafael Espindola     StructType *DTy = StructType::create(Ty->getContext());
27231ad468dSRafael Espindola     return *Entry = DTy;
27331ad468dSRafael Espindola   }
27431ad468dSRafael Espindola 
27531ad468dSRafael Espindola   // If this is not a recursive type, then just map all of the elements and
276b1ed91f3SChris Lattner   // then rebuild the type from inside out.
27731ad468dSRafael Espindola   SmallVector<Type *, 4> ElementTypes;
27831ad468dSRafael Espindola 
279b1ed91f3SChris Lattner   // If there are no element types to map, then the type is itself.  This is
280b1ed91f3SChris Lattner   // true for the anonymous {} struct, things like 'float', integers, etc.
28131ad468dSRafael Espindola   if (Ty->getNumContainedTypes() == 0 && IsUniqued)
282b1ed91f3SChris Lattner     return *Entry = Ty;
283b1ed91f3SChris Lattner 
284b1ed91f3SChris Lattner   // Remap all of the elements, keeping track of whether any of them change.
285b1ed91f3SChris Lattner   bool AnyChange = false;
286b1ed91f3SChris Lattner   ElementTypes.resize(Ty->getNumContainedTypes());
287290e2cc5SRafael Espindola   for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
28831ad468dSRafael Espindola     ElementTypes[I] = get(Ty->getContainedType(I), Visited);
289290e2cc5SRafael Espindola     AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
290eee6f995SChris Lattner   }
291b1ed91f3SChris Lattner 
292b1ed91f3SChris Lattner   // If we found our type while recursively processing stuff, just use it.
293b1ed91f3SChris Lattner   Entry = &MappedTypes[Ty];
29431ad468dSRafael Espindola   if (*Entry) {
29531ad468dSRafael Espindola     if (auto *DTy = dyn_cast<StructType>(*Entry)) {
29631ad468dSRafael Espindola       if (DTy->isOpaque()) {
29731ad468dSRafael Espindola         auto *STy = cast<StructType>(Ty);
29831ad468dSRafael Espindola         finishType(DTy, STy, ElementTypes);
29931ad468dSRafael Espindola       }
30031ad468dSRafael Espindola     }
301290e2cc5SRafael Espindola     return *Entry;
30231ad468dSRafael Espindola   }
303b1ed91f3SChris Lattner 
30431ad468dSRafael Espindola   // If all of the element types mapped directly over and the type is not
30531ad468dSRafael Espindola   // a nomed struct, then the type is usable as-is.
30631ad468dSRafael Espindola   if (!AnyChange && IsUniqued)
307b1ed91f3SChris Lattner     return *Entry = Ty;
308b1ed91f3SChris Lattner 
309b1ed91f3SChris Lattner   // Otherwise, rebuild a modified type.
310b1ed91f3SChris Lattner   switch (Ty->getTypeID()) {
311290e2cc5SRafael Espindola   default:
312290e2cc5SRafael Espindola     llvm_unreachable("unknown derived type to remap");
313b1ed91f3SChris Lattner   case Type::ArrayTyID:
314b1ed91f3SChris Lattner     return *Entry = ArrayType::get(ElementTypes[0],
315b1ed91f3SChris Lattner                                    cast<ArrayType>(Ty)->getNumElements());
316b1ed91f3SChris Lattner   case Type::VectorTyID:
317b1ed91f3SChris Lattner     return *Entry = VectorType::get(ElementTypes[0],
318b1ed91f3SChris Lattner                                     cast<VectorType>(Ty)->getNumElements());
319b1ed91f3SChris Lattner   case Type::PointerTyID:
32031ad468dSRafael Espindola     return *Entry = PointerType::get(ElementTypes[0],
32131ad468dSRafael Espindola                                      cast<PointerType>(Ty)->getAddressSpace());
322b1ed91f3SChris Lattner   case Type::FunctionTyID:
323b1ed91f3SChris Lattner     return *Entry = FunctionType::get(ElementTypes[0],
324717d7eddSFrits van Bommel                                       makeArrayRef(ElementTypes).slice(1),
325b1ed91f3SChris Lattner                                       cast<FunctionType>(Ty)->isVarArg());
32631ad468dSRafael Espindola   case Type::StructTyID: {
32731ad468dSRafael Espindola     auto *STy = cast<StructType>(Ty);
32831ad468dSRafael Espindola     bool IsPacked = STy->isPacked();
32931ad468dSRafael Espindola     if (IsUniqued)
33031ad468dSRafael Espindola       return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
331b1ed91f3SChris Lattner 
332b1ed91f3SChris Lattner     // If the type is opaque, we can just use it directly.
333aa9918aaSRafael Espindola     if (STy->isOpaque()) {
33431ad468dSRafael Espindola       DstStructTypesSet.addOpaque(STy);
33531ad468dSRafael Espindola       return *Entry = Ty;
336aa9918aaSRafael Espindola     }
337b1ed91f3SChris Lattner 
33831ad468dSRafael Espindola     if (StructType *OldT =
33931ad468dSRafael Espindola             DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
340c81c3f55SRafael Espindola       STy->setName("");
34131ad468dSRafael Espindola       return *Entry = OldT;
342c81c3f55SRafael Espindola     }
343c81c3f55SRafael Espindola 
34431ad468dSRafael Espindola     if (!AnyChange) {
34531ad468dSRafael Espindola       DstStructTypesSet.addNonOpaque(STy);
34631ad468dSRafael Espindola       return *Entry = Ty;
34731ad468dSRafael Espindola     }
34831ad468dSRafael Espindola 
34931ad468dSRafael Espindola     StructType *DTy = StructType::create(Ty->getContext());
35031ad468dSRafael Espindola     finishType(DTy, STy, ElementTypes);
35131ad468dSRafael Espindola     return *Entry = DTy;
35231ad468dSRafael Espindola   }
35331ad468dSRafael Espindola   }
354b1ed91f3SChris Lattner }
355b1ed91f3SChris Lattner 
356b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
357b1ed91f3SChris Lattner // ModuleLinker implementation.
358b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
359b1ed91f3SChris Lattner 
360b1ed91f3SChris Lattner namespace {
361f6f121e2SJames Molloy class ModuleLinker;
362f6f121e2SJames Molloy 
36318c89411SRafael Espindola /// Creates prototypes for functions that are lazily linked on the fly. This
36418c89411SRafael Espindola /// speeds up linking for modules with many/ lazily linked functions of which
36518c89411SRafael Espindola /// few get used.
366f6f121e2SJames Molloy class ValueMaterializerTy : public ValueMaterializer {
367f6f121e2SJames Molloy   TypeMapTy &TypeMap;
368f6f121e2SJames Molloy   Module *DstM;
369ef23711eSRafael Espindola   std::vector<GlobalValue *> &LazilyLinkGlobalValues;
370c84f608bSRafael Espindola 
371f6f121e2SJames Molloy public:
372f6f121e2SJames Molloy   ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
373ef23711eSRafael Espindola                       std::vector<GlobalValue *> &LazilyLinkGlobalValues)
374c84f608bSRafael Espindola       : ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
375ef23711eSRafael Espindola         LazilyLinkGlobalValues(LazilyLinkGlobalValues) {}
376f6f121e2SJames Molloy 
3778548299aSCraig Topper   Value *materializeValueFor(Value *V) override;
378f6f121e2SJames Molloy };
379f6f121e2SJames Molloy 
380d12b4a33SRafael Espindola class LinkDiagnosticInfo : public DiagnosticInfo {
381d12b4a33SRafael Espindola   const Twine &Msg;
382d12b4a33SRafael Espindola 
383d12b4a33SRafael Espindola public:
384d12b4a33SRafael Espindola   LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg);
385d12b4a33SRafael Espindola   void print(DiagnosticPrinter &DP) const override;
386d12b4a33SRafael Espindola };
387d12b4a33SRafael Espindola LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
388d12b4a33SRafael Espindola                                        const Twine &Msg)
389d12b4a33SRafael Espindola     : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
390d12b4a33SRafael Espindola void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
391d12b4a33SRafael Espindola 
39218c89411SRafael Espindola /// This is an implementation class for the LinkModules function, which is the
39318c89411SRafael Espindola /// entrypoint for this file.
394b1ed91f3SChris Lattner class ModuleLinker {
395b1ed91f3SChris Lattner   Module *DstM, *SrcM;
396b1ed91f3SChris Lattner 
397b1ed91f3SChris Lattner   TypeMapTy TypeMap;
398f6f121e2SJames Molloy   ValueMaterializerTy ValMaterializer;
399b1ed91f3SChris Lattner 
40018c89411SRafael Espindola   /// Mapping of values from what they used to be in Src, to what they are now
40118c89411SRafael Espindola   /// in DstM.  ValueToValueMapTy is a ValueMap, which involves some overhead
40218c89411SRafael Espindola   /// due to the use of Value handles which the Linker doesn't actually need,
40318c89411SRafael Espindola   /// but this allows us to reuse the ValueMapper code.
404b1ed91f3SChris Lattner   ValueToValueMapTy ValueMap;
405b1ed91f3SChris Lattner 
406b1ed91f3SChris Lattner   struct AppendingVarInfo {
407b1ed91f3SChris Lattner     GlobalVariable *NewGV;   // New aggregate global in dest module.
4083e8bc6a8SRafael Espindola     const Constant *DstInit; // Old initializer from dest module.
4093e8bc6a8SRafael Espindola     const Constant *SrcInit; // Old initializer from src module.
410b1ed91f3SChris Lattner   };
411b1ed91f3SChris Lattner 
412b1ed91f3SChris Lattner   std::vector<AppendingVarInfo> AppendingVars;
413b1ed91f3SChris Lattner 
414cbb91408STanya Lattner   // Set of items not to link in from source.
415cbb91408STanya Lattner   SmallPtrSet<const Value *, 16> DoNotLinkFromSource;
416cbb91408STanya Lattner 
417ef23711eSRafael Espindola   // Vector of GlobalValues to lazily link in.
418ef23711eSRafael Espindola   std::vector<GlobalValue *> LazilyLinkGlobalValues;
4190a48b877STanya Lattner 
420fda0cee7SDuncan P. N. Exon Smith   /// Functions that have replaced other functions.
421fda0cee7SDuncan P. N. Exon Smith   SmallPtrSet<const Function *, 16> OverridingFunctions;
422fda0cee7SDuncan P. N. Exon Smith 
423d0b23befSRafael Espindola   DiagnosticHandlerFunction DiagnosticHandler;
4244160f5d3SRafael Espindola 
425b1ed91f3SChris Lattner public:
42631ad468dSRafael Espindola   ModuleLinker(Module *dstM, Linker::IdentifiedStructTypeSet &Set, Module *srcM,
427d0b23befSRafael Espindola                DiagnosticHandlerFunction DiagnosticHandler)
428a4e85e3dSRafael Espindola       : DstM(dstM), SrcM(srcM), TypeMap(Set),
429ef23711eSRafael Espindola         ValMaterializer(TypeMap, DstM, LazilyLinkGlobalValues),
4304160f5d3SRafael Espindola         DiagnosticHandler(DiagnosticHandler) {}
431b1ed91f3SChris Lattner 
432b1ed91f3SChris Lattner   bool run();
433b1ed91f3SChris Lattner 
434b1ed91f3SChris Lattner private:
435d12b4a33SRafael Espindola   bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
436d12b4a33SRafael Espindola                             const GlobalValue &Src);
437dbb0bd1aSRafael Espindola 
438d12b4a33SRafael Espindola   /// Helper method for setting a message and returning an error code.
439b1ed91f3SChris Lattner   bool emitError(const Twine &Message) {
4404160f5d3SRafael Espindola     DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
441b1ed91f3SChris Lattner     return true;
442b1ed91f3SChris Lattner   }
443b1ed91f3SChris Lattner 
444d12b4a33SRafael Espindola   void emitWarning(const Twine &Message) {
4454160f5d3SRafael Espindola     DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
446d12b4a33SRafael Espindola   }
447d12b4a33SRafael Espindola 
448dad0a645SDavid Majnemer   bool getComdatLeader(Module *M, StringRef ComdatName,
449dad0a645SDavid Majnemer                        const GlobalVariable *&GVar);
450dad0a645SDavid Majnemer   bool computeResultingSelectionKind(StringRef ComdatName,
451dad0a645SDavid Majnemer                                      Comdat::SelectionKind Src,
452dad0a645SDavid Majnemer                                      Comdat::SelectionKind Dst,
453dad0a645SDavid Majnemer                                      Comdat::SelectionKind &Result,
454dad0a645SDavid Majnemer                                      bool &LinkFromSrc);
455dad0a645SDavid Majnemer   std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
456dad0a645SDavid Majnemer       ComdatsChosen;
457dad0a645SDavid Majnemer   bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
458dad0a645SDavid Majnemer                        bool &LinkFromSrc);
459dad0a645SDavid Majnemer 
46018c89411SRafael Espindola   /// Given a global in the source module, return the global in the
46118c89411SRafael Espindola   /// destination module that is being linked to, if any.
4623e8bc6a8SRafael Espindola   GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
463b1ed91f3SChris Lattner     // If the source has no name it can't link.  If it has local linkage,
464b1ed91f3SChris Lattner     // there is no name match-up going on.
465b1ed91f3SChris Lattner     if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
4662617dcceSCraig Topper       return nullptr;
467b1ed91f3SChris Lattner 
468b1ed91f3SChris Lattner     // Otherwise see if we have a match in the destination module's symtab.
469b1ed91f3SChris Lattner     GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
470c84f608bSRafael Espindola     if (!DGV)
471c84f608bSRafael Espindola       return nullptr;
472b1ed91f3SChris Lattner 
473b1ed91f3SChris Lattner     // If we found a global with the same name in the dest module, but it has
474b1ed91f3SChris Lattner     // internal linkage, we are really not doing any linkage here.
475b1ed91f3SChris Lattner     if (DGV->hasLocalLinkage())
4762617dcceSCraig Topper       return nullptr;
477b1ed91f3SChris Lattner 
478b1ed91f3SChris Lattner     // Otherwise, we do in fact link to the destination global.
479b1ed91f3SChris Lattner     return DGV;
480b1ed91f3SChris Lattner   }
481b1ed91f3SChris Lattner 
482b1ed91f3SChris Lattner   void computeTypeMapping();
483b1ed91f3SChris Lattner 
48409d84addSDuncan P. N. Exon Smith   void upgradeMismatchedGlobalArray(StringRef Name);
48509d84addSDuncan P. N. Exon Smith   void upgradeMismatchedGlobals();
48609d84addSDuncan P. N. Exon Smith 
4873e8bc6a8SRafael Espindola   bool linkAppendingVarProto(GlobalVariable *DstGV,
4883e8bc6a8SRafael Espindola                              const GlobalVariable *SrcGV);
489778fcc77SRafael Espindola 
490778fcc77SRafael Espindola   bool linkGlobalValueProto(GlobalValue *GV);
49166f02413SBill Wendling   bool linkModuleFlagsMetadata();
492b1ed91f3SChris Lattner 
493b1ed91f3SChris Lattner   void linkAppendingVarInit(const AppendingVarInfo &AVI);
494ef23711eSRafael Espindola 
495ef23711eSRafael Espindola   void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src);
496ef23711eSRafael Espindola   bool linkFunctionBody(Function &Dst, Function &Src);
497ef23711eSRafael Espindola   void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src);
498ef23711eSRafael Espindola   bool linkGlobalValueBody(GlobalValue &Src);
499ef23711eSRafael Espindola 
500b1ed91f3SChris Lattner   void linkNamedMDNodes();
501fda0cee7SDuncan P. N. Exon Smith   void stripReplacedSubprograms();
502eee6f995SChris Lattner };
503d48b7783SBill Wendling }
504d48b7783SBill Wendling 
50518c89411SRafael Espindola /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
50618c89411SRafael Espindola /// table. This is good for all clients except for us. Go through the trouble
50718c89411SRafael Espindola /// to force this back.
508b1ed91f3SChris Lattner static void forceRenaming(GlobalValue *GV, StringRef Name) {
509b1ed91f3SChris Lattner   // If the global doesn't force its name or if it already has the right name,
510b1ed91f3SChris Lattner   // there is nothing for us to do.
511b1ed91f3SChris Lattner   if (GV->hasLocalLinkage() || GV->getName() == Name)
512b1ed91f3SChris Lattner     return;
513b1ed91f3SChris Lattner 
514b1ed91f3SChris Lattner   Module *M = GV->getParent();
515361e513dSReid Spencer 
516361e513dSReid Spencer   // If there is a conflict, rename the conflict.
517b1ed91f3SChris Lattner   if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
5182a8d2e0eSChris Lattner     GV->takeName(ConflictGV);
519361e513dSReid Spencer     ConflictGV->setName(Name);    // This will cause ConflictGV to get renamed
520b1ed91f3SChris Lattner     assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
5212a8d2e0eSChris Lattner   } else {
5222a8d2e0eSChris Lattner     GV->setName(Name);              // Force the name back
5233aaaa0b2SReid Spencer   }
5243aaaa0b2SReid Spencer }
5253aaaa0b2SReid Spencer 
52618c89411SRafael Espindola /// copy additional attributes (those not needed to construct a GlobalValue)
52718c89411SRafael Espindola /// from the SrcGV to the DestGV.
528b6af2f36SBill Wendling static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
529dd7daee8SDuncan Sands   DestGV->copyAttributesFrom(SrcGV);
530b1ed91f3SChris Lattner   forceRenaming(DestGV, SrcGV->getName());
531361e513dSReid Spencer }
532361e513dSReid Spencer 
53323f8d64bSRafael Espindola static bool isLessConstraining(GlobalValue::VisibilityTypes a,
53423f8d64bSRafael Espindola                                GlobalValue::VisibilityTypes b) {
53523f8d64bSRafael Espindola   if (a == GlobalValue::HiddenVisibility)
53623f8d64bSRafael Espindola     return false;
53723f8d64bSRafael Espindola   if (b == GlobalValue::HiddenVisibility)
53823f8d64bSRafael Espindola     return true;
53923f8d64bSRafael Espindola   if (a == GlobalValue::ProtectedVisibility)
54023f8d64bSRafael Espindola     return false;
54123f8d64bSRafael Espindola   if (b == GlobalValue::ProtectedVisibility)
54223f8d64bSRafael Espindola     return true;
54323f8d64bSRafael Espindola   return false;
54423f8d64bSRafael Espindola }
54523f8d64bSRafael Espindola 
546ef23711eSRafael Espindola /// Loop through the global variables in the src module and merge them into the
547ef23711eSRafael Espindola /// dest module.
548ef23711eSRafael Espindola static GlobalVariable *copyGlobalVariableProto(TypeMapTy &TypeMap, Module &DstM,
549ef23711eSRafael Espindola                                                const GlobalVariable *SGVar) {
550ef23711eSRafael Espindola   // No linking to be performed or linking from the source: simply create an
551ef23711eSRafael Espindola   // identical version of the symbol over in the dest module... the
552ef23711eSRafael Espindola   // initializer will be filled in later by LinkGlobalInits.
553ef23711eSRafael Espindola   GlobalVariable *NewDGV = new GlobalVariable(
554ef23711eSRafael Espindola       DstM, TypeMap.get(SGVar->getType()->getElementType()),
555ef23711eSRafael Espindola       SGVar->isConstant(), SGVar->getLinkage(), /*init*/ nullptr,
556ef23711eSRafael Espindola       SGVar->getName(), /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
557ef23711eSRafael Espindola       SGVar->getType()->getAddressSpace());
558f6f121e2SJames Molloy 
559ef23711eSRafael Espindola   return NewDGV;
5603931c28bSRafael Espindola }
5613931c28bSRafael Espindola 
562ef23711eSRafael Espindola /// Link the function in the source module into the destination module if
563ef23711eSRafael Espindola /// needed, setting up mapping information.
564ef23711eSRafael Espindola static Function *copyFunctionProto(TypeMapTy &TypeMap, Module &DstM,
565ef23711eSRafael Espindola                                    const Function *SF) {
566ef23711eSRafael Espindola   // If there is no linkage to be performed or we are linking from the source,
567ef23711eSRafael Espindola   // bring SF over.
568ef23711eSRafael Espindola   return Function::Create(TypeMap.get(SF->getFunctionType()), SF->getLinkage(),
569ef23711eSRafael Espindola                           SF->getName(), &DstM);
570ef23711eSRafael Espindola }
571ef23711eSRafael Espindola 
572ef23711eSRafael Espindola /// Set up prototypes for any aliases that come over from the source module.
573ef23711eSRafael Espindola static GlobalAlias *copyGlobalAliasProto(TypeMapTy &TypeMap, Module &DstM,
574ef23711eSRafael Espindola                                          const GlobalAlias *SGA) {
575ef23711eSRafael Espindola   // If there is no linkage to be performed or we're linking from the source,
576ef23711eSRafael Espindola   // bring over SGA.
577ef23711eSRafael Espindola   auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType()));
578ef23711eSRafael Espindola   return GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
579ef23711eSRafael Espindola                              SGA->getLinkage(), SGA->getName(), &DstM);
580ef23711eSRafael Espindola }
581ef23711eSRafael Espindola 
582ef23711eSRafael Espindola static GlobalValue *copyGlobalValueProto(TypeMapTy &TypeMap, Module &DstM,
583ef23711eSRafael Espindola                                          const GlobalValue *SGV) {
584ef23711eSRafael Espindola   GlobalValue *NewGV;
585ef23711eSRafael Espindola   if (auto *SGVar = dyn_cast<GlobalVariable>(SGV))
586ef23711eSRafael Espindola     NewGV = copyGlobalVariableProto(TypeMap, DstM, SGVar);
587ef23711eSRafael Espindola   else if (auto *SF = dyn_cast<Function>(SGV))
588ef23711eSRafael Espindola     NewGV = copyFunctionProto(TypeMap, DstM, SF);
589ef23711eSRafael Espindola   else
590ef23711eSRafael Espindola     NewGV = copyGlobalAliasProto(TypeMap, DstM, cast<GlobalAlias>(SGV));
591ef23711eSRafael Espindola   copyGVAttributes(NewGV, SGV);
592ef23711eSRafael Espindola   return NewGV;
593ef23711eSRafael Espindola }
594ef23711eSRafael Espindola 
595ef23711eSRafael Espindola Value *ValueMaterializerTy::materializeValueFor(Value *V) {
596ef23711eSRafael Espindola   auto *SGV = dyn_cast<GlobalValue>(V);
597ef23711eSRafael Espindola   if (!SGV)
598ef23711eSRafael Espindola     return nullptr;
599ef23711eSRafael Espindola 
600ef23711eSRafael Espindola   GlobalValue *DGV = copyGlobalValueProto(TypeMap, *DstM, SGV);
601ef23711eSRafael Espindola 
602ef23711eSRafael Espindola   if (Comdat *SC = SGV->getComdat()) {
603ef23711eSRafael Espindola     if (auto *DGO = dyn_cast<GlobalObject>(DGV)) {
604ef23711eSRafael Espindola       Comdat *DC = DstM->getOrInsertComdat(SC->getName());
605ef23711eSRafael Espindola       DGO->setComdat(DC);
606ef23711eSRafael Espindola     }
607ef23711eSRafael Espindola   }
608ef23711eSRafael Espindola 
609ef23711eSRafael Espindola   LazilyLinkGlobalValues.push_back(SGV);
610ef23711eSRafael Espindola   return DGV;
611f6f121e2SJames Molloy }
612f6f121e2SJames Molloy 
613dad0a645SDavid Majnemer bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName,
614dad0a645SDavid Majnemer                                    const GlobalVariable *&GVar) {
615dad0a645SDavid Majnemer   const GlobalValue *GVal = M->getNamedValue(ComdatName);
616dad0a645SDavid Majnemer   if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
617dad0a645SDavid Majnemer     GVal = GA->getBaseObject();
618dad0a645SDavid Majnemer     if (!GVal)
619dad0a645SDavid Majnemer       // We cannot resolve the size of the aliasee yet.
620dad0a645SDavid Majnemer       return emitError("Linking COMDATs named '" + ComdatName +
621dad0a645SDavid Majnemer                        "': COMDAT key involves incomputable alias size.");
622dad0a645SDavid Majnemer   }
623dad0a645SDavid Majnemer 
624dad0a645SDavid Majnemer   GVar = dyn_cast_or_null<GlobalVariable>(GVal);
625dad0a645SDavid Majnemer   if (!GVar)
626dad0a645SDavid Majnemer     return emitError(
627dad0a645SDavid Majnemer         "Linking COMDATs named '" + ComdatName +
628dad0a645SDavid Majnemer         "': GlobalVariable required for data dependent selection!");
629dad0a645SDavid Majnemer 
630dad0a645SDavid Majnemer   return false;
631dad0a645SDavid Majnemer }
632dad0a645SDavid Majnemer 
633dad0a645SDavid Majnemer bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
634dad0a645SDavid Majnemer                                                  Comdat::SelectionKind Src,
635dad0a645SDavid Majnemer                                                  Comdat::SelectionKind Dst,
636dad0a645SDavid Majnemer                                                  Comdat::SelectionKind &Result,
637dad0a645SDavid Majnemer                                                  bool &LinkFromSrc) {
638dad0a645SDavid Majnemer   // The ability to mix Comdat::SelectionKind::Any with
639dad0a645SDavid Majnemer   // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
640dad0a645SDavid Majnemer   bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
641dad0a645SDavid Majnemer                          Dst == Comdat::SelectionKind::Largest;
642dad0a645SDavid Majnemer   bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
643dad0a645SDavid Majnemer                          Src == Comdat::SelectionKind::Largest;
644dad0a645SDavid Majnemer   if (DstAnyOrLargest && SrcAnyOrLargest) {
645dad0a645SDavid Majnemer     if (Dst == Comdat::SelectionKind::Largest ||
646dad0a645SDavid Majnemer         Src == Comdat::SelectionKind::Largest)
647dad0a645SDavid Majnemer       Result = Comdat::SelectionKind::Largest;
648dad0a645SDavid Majnemer     else
649dad0a645SDavid Majnemer       Result = Comdat::SelectionKind::Any;
650dad0a645SDavid Majnemer   } else if (Src == Dst) {
651dad0a645SDavid Majnemer     Result = Dst;
652dad0a645SDavid Majnemer   } else {
653dad0a645SDavid Majnemer     return emitError("Linking COMDATs named '" + ComdatName +
654dad0a645SDavid Majnemer                      "': invalid selection kinds!");
655dad0a645SDavid Majnemer   }
656dad0a645SDavid Majnemer 
657dad0a645SDavid Majnemer   switch (Result) {
658dad0a645SDavid Majnemer   case Comdat::SelectionKind::Any:
659dad0a645SDavid Majnemer     // Go with Dst.
660dad0a645SDavid Majnemer     LinkFromSrc = false;
661dad0a645SDavid Majnemer     break;
662dad0a645SDavid Majnemer   case Comdat::SelectionKind::NoDuplicates:
663dad0a645SDavid Majnemer     return emitError("Linking COMDATs named '" + ComdatName +
664dad0a645SDavid Majnemer                      "': noduplicates has been violated!");
665dad0a645SDavid Majnemer   case Comdat::SelectionKind::ExactMatch:
666dad0a645SDavid Majnemer   case Comdat::SelectionKind::Largest:
667dad0a645SDavid Majnemer   case Comdat::SelectionKind::SameSize: {
668dad0a645SDavid Majnemer     const GlobalVariable *DstGV;
669dad0a645SDavid Majnemer     const GlobalVariable *SrcGV;
670dad0a645SDavid Majnemer     if (getComdatLeader(DstM, ComdatName, DstGV) ||
671dad0a645SDavid Majnemer         getComdatLeader(SrcM, ComdatName, SrcGV))
672dad0a645SDavid Majnemer       return true;
673dad0a645SDavid Majnemer 
674dad0a645SDavid Majnemer     const DataLayout *DstDL = DstM->getDataLayout();
675dad0a645SDavid Majnemer     const DataLayout *SrcDL = SrcM->getDataLayout();
676dad0a645SDavid Majnemer     if (!DstDL || !SrcDL) {
677dad0a645SDavid Majnemer       return emitError(
678dad0a645SDavid Majnemer           "Linking COMDATs named '" + ComdatName +
679dad0a645SDavid Majnemer           "': can't do size dependent selection without DataLayout!");
680dad0a645SDavid Majnemer     }
681dad0a645SDavid Majnemer     uint64_t DstSize =
682dad0a645SDavid Majnemer         DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType());
683dad0a645SDavid Majnemer     uint64_t SrcSize =
684dad0a645SDavid Majnemer         SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType());
685dad0a645SDavid Majnemer     if (Result == Comdat::SelectionKind::ExactMatch) {
686dad0a645SDavid Majnemer       if (SrcGV->getInitializer() != DstGV->getInitializer())
687dad0a645SDavid Majnemer         return emitError("Linking COMDATs named '" + ComdatName +
688dad0a645SDavid Majnemer                          "': ExactMatch violated!");
689dad0a645SDavid Majnemer       LinkFromSrc = false;
690dad0a645SDavid Majnemer     } else if (Result == Comdat::SelectionKind::Largest) {
691dad0a645SDavid Majnemer       LinkFromSrc = SrcSize > DstSize;
692dad0a645SDavid Majnemer     } else if (Result == Comdat::SelectionKind::SameSize) {
693dad0a645SDavid Majnemer       if (SrcSize != DstSize)
694dad0a645SDavid Majnemer         return emitError("Linking COMDATs named '" + ComdatName +
695dad0a645SDavid Majnemer                          "': SameSize violated!");
696dad0a645SDavid Majnemer       LinkFromSrc = false;
697dad0a645SDavid Majnemer     } else {
698dad0a645SDavid Majnemer       llvm_unreachable("unknown selection kind");
699dad0a645SDavid Majnemer     }
700dad0a645SDavid Majnemer     break;
701dad0a645SDavid Majnemer   }
702dad0a645SDavid Majnemer   }
703dad0a645SDavid Majnemer 
704dad0a645SDavid Majnemer   return false;
705dad0a645SDavid Majnemer }
706dad0a645SDavid Majnemer 
707dad0a645SDavid Majnemer bool ModuleLinker::getComdatResult(const Comdat *SrcC,
708dad0a645SDavid Majnemer                                    Comdat::SelectionKind &Result,
709dad0a645SDavid Majnemer                                    bool &LinkFromSrc) {
710b16196a3SRafael Espindola   Comdat::SelectionKind SSK = SrcC->getSelectionKind();
711dad0a645SDavid Majnemer   StringRef ComdatName = SrcC->getName();
712dad0a645SDavid Majnemer   Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable();
713dad0a645SDavid Majnemer   Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
7142ef3f299SRafael Espindola 
715b16196a3SRafael Espindola   if (DstCI == ComdatSymTab.end()) {
716b16196a3SRafael Espindola     // Use the comdat if it is only available in one of the modules.
717b16196a3SRafael Espindola     LinkFromSrc = true;
718b16196a3SRafael Espindola     Result = SSK;
7192ef3f299SRafael Espindola     return false;
720b16196a3SRafael Espindola   }
7212ef3f299SRafael Espindola 
722dad0a645SDavid Majnemer   const Comdat *DstC = &DstCI->second;
723dad0a645SDavid Majnemer   Comdat::SelectionKind DSK = DstC->getSelectionKind();
7242ef3f299SRafael Espindola   return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
7252ef3f299SRafael Espindola                                        LinkFromSrc);
726dad0a645SDavid Majnemer }
727f6f121e2SJames Molloy 
728d12b4a33SRafael Espindola bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
729d12b4a33SRafael Espindola                                         const GlobalValue &Dest,
730dbb0bd1aSRafael Espindola                                         const GlobalValue &Src) {
731778fcc77SRafael Espindola   // We always have to add Src if it has appending linkage.
732778fcc77SRafael Espindola   if (Src.hasAppendingLinkage()) {
733778fcc77SRafael Espindola     LinkFromSrc = true;
734778fcc77SRafael Espindola     return false;
735778fcc77SRafael Espindola   }
736778fcc77SRafael Espindola 
737d4bcefc7SRafael Espindola   bool SrcIsDeclaration = Src.isDeclarationForLinker();
738d4bcefc7SRafael Espindola   bool DestIsDeclaration = Dest.isDeclarationForLinker();
739dbb0bd1aSRafael Espindola 
740dbb0bd1aSRafael Espindola   if (SrcIsDeclaration) {
741dbb0bd1aSRafael Espindola     // If Src is external or if both Src & Dest are external..  Just link the
742dbb0bd1aSRafael Espindola     // external globals, we aren't adding anything.
743d12b4a33SRafael Espindola     if (Src.hasDLLImportStorageClass()) {
744dbb0bd1aSRafael Espindola       // If one of GVs is marked as DLLImport, result should be dllimport'ed.
745d12b4a33SRafael Espindola       LinkFromSrc = DestIsDeclaration;
746d12b4a33SRafael Espindola       return false;
747d12b4a33SRafael Espindola     }
748dbb0bd1aSRafael Espindola     // If the Dest is weak, use the source linkage.
749d12b4a33SRafael Espindola     LinkFromSrc = Dest.hasExternalWeakLinkage();
750d12b4a33SRafael Espindola     return false;
751dbb0bd1aSRafael Espindola   }
752dbb0bd1aSRafael Espindola 
753d12b4a33SRafael Espindola   if (DestIsDeclaration) {
754dbb0bd1aSRafael Espindola     // If Dest is external but Src is not:
755d12b4a33SRafael Espindola     LinkFromSrc = true;
756d12b4a33SRafael Espindola     return false;
757d12b4a33SRafael Espindola   }
758dbb0bd1aSRafael Espindola 
7590910605aSRafael Espindola   if (Src.hasCommonLinkage()) {
760d12b4a33SRafael Espindola     if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
761d12b4a33SRafael Espindola       LinkFromSrc = true;
7620910605aSRafael Espindola       return false;
763d12b4a33SRafael Espindola     }
764d12b4a33SRafael Espindola 
765d12b4a33SRafael Espindola     if (!Dest.hasCommonLinkage()) {
766d12b4a33SRafael Espindola       LinkFromSrc = false;
767d12b4a33SRafael Espindola       return false;
768d12b4a33SRafael Espindola     }
7690910605aSRafael Espindola 
7700ae225b6SRafael Espindola     // FIXME: Make datalayout mandatory and just use getDataLayout().
7710ae225b6SRafael Espindola     DataLayout DL(Dest.getParent());
7720ae225b6SRafael Espindola 
7730910605aSRafael Espindola     uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
7740910605aSRafael Espindola     uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
775d12b4a33SRafael Espindola     LinkFromSrc = SrcSize > DestSize;
776d12b4a33SRafael Espindola     return false;
7770910605aSRafael Espindola   }
7780910605aSRafael Espindola 
779dbb0bd1aSRafael Espindola   if (Src.isWeakForLinker()) {
780dbb0bd1aSRafael Espindola     assert(!Dest.hasExternalWeakLinkage());
781dbb0bd1aSRafael Espindola     assert(!Dest.hasAvailableExternallyLinkage());
7820910605aSRafael Espindola 
783d12b4a33SRafael Espindola     if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
784d12b4a33SRafael Espindola       LinkFromSrc = true;
785d12b4a33SRafael Espindola       return false;
786d12b4a33SRafael Espindola     }
787dbb0bd1aSRafael Espindola 
788d12b4a33SRafael Espindola     LinkFromSrc = false;
7890910605aSRafael Espindola     return false;
790dbb0bd1aSRafael Espindola   }
791dbb0bd1aSRafael Espindola 
792dbb0bd1aSRafael Espindola   if (Dest.isWeakForLinker()) {
793dbb0bd1aSRafael Espindola     assert(Src.hasExternalLinkage());
794d12b4a33SRafael Espindola     LinkFromSrc = true;
795d12b4a33SRafael Espindola     return false;
796dbb0bd1aSRafael Espindola   }
797dbb0bd1aSRafael Espindola 
798dbb0bd1aSRafael Espindola   assert(!Src.hasExternalWeakLinkage());
799dbb0bd1aSRafael Espindola   assert(!Dest.hasExternalWeakLinkage());
800dbb0bd1aSRafael Espindola   assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
801dbb0bd1aSRafael Espindola          "Unexpected linkage type!");
802dbb0bd1aSRafael Espindola   return emitError("Linking globals named '" + Src.getName() +
803dbb0bd1aSRafael Espindola                    "': symbol multiply defined!");
804dbb0bd1aSRafael Espindola }
805dbb0bd1aSRafael Espindola 
80618c89411SRafael Espindola /// Loop over all of the linked values to compute type mappings.  For example,
80718c89411SRafael Espindola /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
80818c89411SRafael Espindola /// types 'Foo' but one got renamed when the module was loaded into the same
80918c89411SRafael Espindola /// LLVMContext.
810b1ed91f3SChris Lattner void ModuleLinker::computeTypeMapping() {
811c8a476eeSRafael Espindola   for (GlobalValue &SGV : SrcM->globals()) {
812c8a476eeSRafael Espindola     GlobalValue *DGV = getLinkedToGlobal(&SGV);
813c8a476eeSRafael Espindola     if (!DGV)
814c8a476eeSRafael Espindola       continue;
815b1ed91f3SChris Lattner 
816c8a476eeSRafael Espindola     if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
817c8a476eeSRafael Espindola       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
818b1ed91f3SChris Lattner       continue;
8195c310be0SDevang Patel     }
8205c310be0SDevang Patel 
821b1ed91f3SChris Lattner     // Unify the element type of appending arrays.
822b1ed91f3SChris Lattner     ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
823c8a476eeSRafael Espindola     ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
824b1ed91f3SChris Lattner     TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
825b1ed91f3SChris Lattner   }
82634fc5a0eSChris Lattner 
827c8a476eeSRafael Espindola   for (GlobalValue &SGV : *SrcM) {
828c8a476eeSRafael Espindola     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
829c8a476eeSRafael Espindola       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
830b1ed91f3SChris Lattner   }
831e79f4c77SAnton Korobeynikov 
832e96d7eb8SRafael Espindola   for (GlobalValue &SGV : SrcM->aliases()) {
833e96d7eb8SRafael Espindola     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
834e96d7eb8SRafael Espindola       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
835e96d7eb8SRafael Espindola   }
836e96d7eb8SRafael Espindola 
837d48b7783SBill Wendling   // Incorporate types by name, scanning all the types in the source module.
838d48b7783SBill Wendling   // At this point, the destination module may have a type "%foo = { i32 }" for
8392b3f61afSBill Wendling   // example.  When the source module got loaded into the same LLVMContext, if
8402b3f61afSBill Wendling   // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
8412fa1e43aSRafael Espindola   std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
8422fa1e43aSRafael Espindola   for (StructType *ST : Types) {
8434d4c9387SRafael Espindola     if (!ST->hasName())
8444d4c9387SRafael Espindola       continue;
8452b3f61afSBill Wendling 
8462b3f61afSBill Wendling     // Check to see if there is a dot in the name followed by a digit.
847d48b7783SBill Wendling     size_t DotPos = ST->getName().rfind('.');
848d48b7783SBill Wendling     if (DotPos == 0 || DotPos == StringRef::npos ||
84983c74e9fSGuy Benyei         ST->getName().back() == '.' ||
85083c74e9fSGuy Benyei         !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
851d48b7783SBill Wendling       continue;
8522b3f61afSBill Wendling 
8532b3f61afSBill Wendling     // Check to see if the destination module has a struct with the prefix name.
854973b3612SRafael Espindola     StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos));
855973b3612SRafael Espindola     if (!DST)
856973b3612SRafael Espindola       continue;
857973b3612SRafael Espindola 
8582b3f61afSBill Wendling     // Don't use it if this actually came from the source module. They're in
8598737480dSBill Wendling     // the same LLVMContext after all. Also don't use it unless the type is
8608737480dSBill Wendling     // actually used in the destination module. This can happen in situations
8618737480dSBill Wendling     // like this:
8628737480dSBill Wendling     //
8638737480dSBill Wendling     //      Module A                         Module B
8648737480dSBill Wendling     //      --------                         --------
8658737480dSBill Wendling     //   %Z = type { %A }                %B = type { %C.1 }
8668737480dSBill Wendling     //   %A = type { %B.1, [7 x i8] }    %C.1 = type { i8* }
8678737480dSBill Wendling     //   %B.1 = type { %C }              %A.2 = type { %B.3, [5 x i8] }
8688737480dSBill Wendling     //   %C = type { i8* }               %B.3 = type { %C.1 }
8698737480dSBill Wendling     //
8708737480dSBill Wendling     // When we link Module B with Module A, the '%B' in Module B is
8718737480dSBill Wendling     // used. However, that would then use '%C.1'. But when we process '%C.1',
8728737480dSBill Wendling     // we prefer to take the '%C' version. So we are then left with both
8738737480dSBill Wendling     // '%C.1' and '%C' being used for the same types. This leads to some
8748737480dSBill Wendling     // variables using one type and some using the other.
87531ad468dSRafael Espindola     if (TypeMap.DstStructTypesSet.hasType(DST))
8762b3f61afSBill Wendling       TypeMap.addTypeMapping(DST, ST);
8772b3f61afSBill Wendling   }
8782b3f61afSBill Wendling 
879b1ed91f3SChris Lattner   // Now that we have discovered all of the type equivalences, get a body for
880b1ed91f3SChris Lattner   // any 'opaque' types in the dest module that are now resolved.
881b1ed91f3SChris Lattner   TypeMap.linkDefinedTypeBodies();
882b1ed91f3SChris Lattner }
883c08e7a00SChris Lattner 
88409d84addSDuncan P. N. Exon Smith static void upgradeGlobalArray(GlobalVariable *GV) {
88509d84addSDuncan P. N. Exon Smith   ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
88609d84addSDuncan P. N. Exon Smith   StructType *OldTy = cast<StructType>(ATy->getElementType());
88709d84addSDuncan P. N. Exon Smith   assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
88809d84addSDuncan P. N. Exon Smith 
88909d84addSDuncan P. N. Exon Smith   // Get the upgraded 3 element type.
89009d84addSDuncan P. N. Exon Smith   PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
89109d84addSDuncan P. N. Exon Smith   Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
89209d84addSDuncan P. N. Exon Smith                   VoidPtrTy};
89309d84addSDuncan P. N. Exon Smith   StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
89409d84addSDuncan P. N. Exon Smith 
89509d84addSDuncan P. N. Exon Smith   // Build new constants with a null third field filled in.
89609d84addSDuncan P. N. Exon Smith   Constant *OldInitC = GV->getInitializer();
89709d84addSDuncan P. N. Exon Smith   ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
89809d84addSDuncan P. N. Exon Smith   if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
89909d84addSDuncan P. N. Exon Smith     // Invalid initializer; give up.
90009d84addSDuncan P. N. Exon Smith     return;
90109d84addSDuncan P. N. Exon Smith   std::vector<Constant *> Initializers;
90209d84addSDuncan P. N. Exon Smith   if (OldInit && OldInit->getNumOperands()) {
90309d84addSDuncan P. N. Exon Smith     Value *Null = Constant::getNullValue(VoidPtrTy);
90409d84addSDuncan P. N. Exon Smith     for (Use &U : OldInit->operands()) {
90509d84addSDuncan P. N. Exon Smith       ConstantStruct *Init = cast<ConstantStruct>(U.get());
90609d84addSDuncan P. N. Exon Smith       Initializers.push_back(ConstantStruct::get(
90709d84addSDuncan P. N. Exon Smith           NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
90809d84addSDuncan P. N. Exon Smith     }
90909d84addSDuncan P. N. Exon Smith   }
91009d84addSDuncan P. N. Exon Smith   assert(Initializers.size() == ATy->getNumElements() &&
91109d84addSDuncan P. N. Exon Smith          "Failed to copy all array elements");
91209d84addSDuncan P. N. Exon Smith 
91309d84addSDuncan P. N. Exon Smith   // Replace the old GV with a new one.
91409d84addSDuncan P. N. Exon Smith   ATy = ArrayType::get(NewTy, Initializers.size());
91509d84addSDuncan P. N. Exon Smith   Constant *NewInit = ConstantArray::get(ATy, Initializers);
91609d84addSDuncan P. N. Exon Smith   GlobalVariable *NewGV = new GlobalVariable(
91709d84addSDuncan P. N. Exon Smith       *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
91809d84addSDuncan P. N. Exon Smith       GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
91909d84addSDuncan P. N. Exon Smith       GV->isExternallyInitialized());
92009d84addSDuncan P. N. Exon Smith   NewGV->copyAttributesFrom(GV);
92109d84addSDuncan P. N. Exon Smith   NewGV->takeName(GV);
92209d84addSDuncan P. N. Exon Smith   assert(GV->use_empty() && "program cannot use initializer list");
92309d84addSDuncan P. N. Exon Smith   GV->eraseFromParent();
92409d84addSDuncan P. N. Exon Smith }
92509d84addSDuncan P. N. Exon Smith 
92609d84addSDuncan P. N. Exon Smith void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
92709d84addSDuncan P. N. Exon Smith   // Look for the global arrays.
92809d84addSDuncan P. N. Exon Smith   auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name));
92909d84addSDuncan P. N. Exon Smith   if (!DstGV)
93009d84addSDuncan P. N. Exon Smith     return;
93109d84addSDuncan P. N. Exon Smith   auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name));
93209d84addSDuncan P. N. Exon Smith   if (!SrcGV)
93309d84addSDuncan P. N. Exon Smith     return;
93409d84addSDuncan P. N. Exon Smith 
93509d84addSDuncan P. N. Exon Smith   // Check if the types already match.
93609d84addSDuncan P. N. Exon Smith   auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
93709d84addSDuncan P. N. Exon Smith   auto *SrcTy =
93809d84addSDuncan P. N. Exon Smith       cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
93909d84addSDuncan P. N. Exon Smith   if (DstTy == SrcTy)
94009d84addSDuncan P. N. Exon Smith     return;
94109d84addSDuncan P. N. Exon Smith 
94209d84addSDuncan P. N. Exon Smith   // Grab the element types.  We can only upgrade an array of a two-field
94309d84addSDuncan P. N. Exon Smith   // struct.  Only bother if the other one has three-fields.
94409d84addSDuncan P. N. Exon Smith   auto *DstEltTy = cast<StructType>(DstTy->getElementType());
94509d84addSDuncan P. N. Exon Smith   auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
94609d84addSDuncan P. N. Exon Smith   if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
94709d84addSDuncan P. N. Exon Smith     upgradeGlobalArray(DstGV);
94809d84addSDuncan P. N. Exon Smith     return;
94909d84addSDuncan P. N. Exon Smith   }
95009d84addSDuncan P. N. Exon Smith   if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
95109d84addSDuncan P. N. Exon Smith     upgradeGlobalArray(SrcGV);
95209d84addSDuncan P. N. Exon Smith 
95309d84addSDuncan P. N. Exon Smith   // We can't upgrade any other differences.
95409d84addSDuncan P. N. Exon Smith }
95509d84addSDuncan P. N. Exon Smith 
95609d84addSDuncan P. N. Exon Smith void ModuleLinker::upgradeMismatchedGlobals() {
95709d84addSDuncan P. N. Exon Smith   upgradeMismatchedGlobalArray("llvm.global_ctors");
95809d84addSDuncan P. N. Exon Smith   upgradeMismatchedGlobalArray("llvm.global_dtors");
95909d84addSDuncan P. N. Exon Smith }
96009d84addSDuncan P. N. Exon Smith 
96118c89411SRafael Espindola /// If there were any appending global variables, link them together now.
96218c89411SRafael Espindola /// Return true on error.
963b1ed91f3SChris Lattner bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
9643e8bc6a8SRafael Espindola                                          const GlobalVariable *SrcGV) {
965d48b7783SBill Wendling 
966b1ed91f3SChris Lattner   if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
967b1ed91f3SChris Lattner     return emitError("Linking globals named '" + SrcGV->getName() +
968b1ed91f3SChris Lattner            "': can only link appending global with another appending global!");
969361e513dSReid Spencer 
970b1ed91f3SChris Lattner   ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
971b1ed91f3SChris Lattner   ArrayType *SrcTy =
972b1ed91f3SChris Lattner     cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
973b1ed91f3SChris Lattner   Type *EltTy = DstTy->getElementType();
974b1ed91f3SChris Lattner 
975b1ed91f3SChris Lattner   // Check to see that they two arrays agree on type.
976b1ed91f3SChris Lattner   if (EltTy != SrcTy->getElementType())
977b1ed91f3SChris Lattner     return emitError("Appending variables with different element types!");
978b1ed91f3SChris Lattner   if (DstGV->isConstant() != SrcGV->isConstant())
979b1ed91f3SChris Lattner     return emitError("Appending variables linked with different const'ness!");
980b1ed91f3SChris Lattner 
981b1ed91f3SChris Lattner   if (DstGV->getAlignment() != SrcGV->getAlignment())
982b1ed91f3SChris Lattner     return emitError(
983b1ed91f3SChris Lattner              "Appending variables with different alignment need to be linked!");
984b1ed91f3SChris Lattner 
985b1ed91f3SChris Lattner   if (DstGV->getVisibility() != SrcGV->getVisibility())
986b1ed91f3SChris Lattner     return emitError(
987b1ed91f3SChris Lattner             "Appending variables with different visibility need to be linked!");
988b1ed91f3SChris Lattner 
989fac3a018SRafael Espindola   if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
990fac3a018SRafael Espindola     return emitError(
991fac3a018SRafael Espindola         "Appending variables with different unnamed_addr need to be linked!");
992fac3a018SRafael Espindola 
99364c1e180SRafael Espindola   if (StringRef(DstGV->getSection()) != SrcGV->getSection())
994b1ed91f3SChris Lattner     return emitError(
995b1ed91f3SChris Lattner           "Appending variables with different section name need to be linked!");
996b1ed91f3SChris Lattner 
997b1ed91f3SChris Lattner   uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
998b1ed91f3SChris Lattner   ArrayType *NewType = ArrayType::get(EltTy, NewSize);
999b1ed91f3SChris Lattner 
1000b1ed91f3SChris Lattner   // Create the new global variable.
1001b1ed91f3SChris Lattner   GlobalVariable *NG =
1002b1ed91f3SChris Lattner     new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
10032617dcceSCraig Topper                        DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
1004cbe34b4cSHans Wennborg                        DstGV->getThreadLocalMode(),
1005b1ed91f3SChris Lattner                        DstGV->getType()->getAddressSpace());
1006b1ed91f3SChris Lattner 
1007b1ed91f3SChris Lattner   // Propagate alignment, visibility and section info.
1008b6af2f36SBill Wendling   copyGVAttributes(NG, DstGV);
1009b1ed91f3SChris Lattner 
1010b1ed91f3SChris Lattner   AppendingVarInfo AVI;
1011b1ed91f3SChris Lattner   AVI.NewGV = NG;
1012b1ed91f3SChris Lattner   AVI.DstInit = DstGV->getInitializer();
1013b1ed91f3SChris Lattner   AVI.SrcInit = SrcGV->getInitializer();
1014b1ed91f3SChris Lattner   AppendingVars.push_back(AVI);
1015b1ed91f3SChris Lattner 
1016b1ed91f3SChris Lattner   // Replace any uses of the two global variables with uses of the new
1017b1ed91f3SChris Lattner   // global.
1018b1ed91f3SChris Lattner   ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
1019b1ed91f3SChris Lattner 
1020b1ed91f3SChris Lattner   DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
1021b1ed91f3SChris Lattner   DstGV->eraseFromParent();
1022b1ed91f3SChris Lattner 
1023cbb91408STanya Lattner   // Track the source variable so we don't try to link it.
1024cbb91408STanya Lattner   DoNotLinkFromSource.insert(SrcGV);
1025cbb91408STanya Lattner 
1026b1ed91f3SChris Lattner   return false;
1027b1ed91f3SChris Lattner }
1028b1ed91f3SChris Lattner 
1029778fcc77SRafael Espindola bool ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) {
1030b1ed91f3SChris Lattner   GlobalValue *DGV = getLinkedToGlobal(SGV);
1031b1ed91f3SChris Lattner 
1032778fcc77SRafael Espindola   // Handle the ultra special appending linkage case first.
1033778fcc77SRafael Espindola   if (DGV && DGV->hasAppendingLinkage())
1034778fcc77SRafael Espindola     return linkAppendingVarProto(cast<GlobalVariable>(DGV),
1035778fcc77SRafael Espindola                                  cast<GlobalVariable>(SGV));
1036778fcc77SRafael Espindola 
1037778fcc77SRafael Espindola   bool LinkFromSrc = true;
1038778fcc77SRafael Espindola   Comdat *C = nullptr;
1039778fcc77SRafael Espindola   GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
1040778fcc77SRafael Espindola   bool HasUnnamedAddr = SGV->hasUnnamedAddr();
1041778fcc77SRafael Espindola 
1042dad0a645SDavid Majnemer   if (const Comdat *SC = SGV->getComdat()) {
1043dad0a645SDavid Majnemer     Comdat::SelectionKind SK;
1044dad0a645SDavid Majnemer     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1045778fcc77SRafael Espindola     C = DstM->getOrInsertComdat(SC->getName());
1046778fcc77SRafael Espindola     C->setSelectionKind(SK);
1047778fcc77SRafael Espindola   } else if (DGV) {
1048778fcc77SRafael Espindola     if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
1049fc61de39SChris Lattner       return true;
1050dad0a645SDavid Majnemer   }
105134fc5a0eSChris Lattner 
1052dad0a645SDavid Majnemer   if (!LinkFromSrc) {
1053cbb91408STanya Lattner     // Track the source global so that we don't attempt to copy it over when
1054cbb91408STanya Lattner     // processing global initializers.
1055cbb91408STanya Lattner     DoNotLinkFromSource.insert(SGV);
1056cbb91408STanya Lattner 
1057778fcc77SRafael Espindola     if (DGV)
1058778fcc77SRafael Espindola       // Make sure to remember this mapping.
1059778fcc77SRafael Espindola       ValueMap[SGV] =
1060778fcc77SRafael Espindola           ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->getType()));
1061778fcc77SRafael Espindola   }
1062778fcc77SRafael Espindola 
1063778fcc77SRafael Espindola   if (DGV) {
1064778fcc77SRafael Espindola     Visibility = isLessConstraining(Visibility, DGV->getVisibility())
1065778fcc77SRafael Espindola                      ? DGV->getVisibility()
1066778fcc77SRafael Espindola                      : Visibility;
1067778fcc77SRafael Espindola     HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1068778fcc77SRafael Espindola   }
1069778fcc77SRafael Espindola 
1070778fcc77SRafael Espindola   if (!LinkFromSrc && !DGV)
1071dad0a645SDavid Majnemer     return false;
1072778fcc77SRafael Espindola 
1073778fcc77SRafael Espindola   GlobalValue *NewGV;
107426c29511SRafael Espindola   if (!LinkFromSrc) {
107526c29511SRafael Espindola     NewGV = DGV;
107626c29511SRafael Espindola   } else {
1077ef23711eSRafael Espindola     // If the GV is to be lazily linked, don't create it just yet.
1078ef23711eSRafael Espindola     // The ValueMaterializerTy will deal with creating it if it's used.
1079ef23711eSRafael Espindola     if (!DGV && (SGV->hasLocalLinkage() || SGV->hasLinkOnceLinkage() ||
1080ef23711eSRafael Espindola                  SGV->hasAvailableExternallyLinkage())) {
1081ef23711eSRafael Espindola       DoNotLinkFromSource.insert(SGV);
1082ef23711eSRafael Espindola       return false;
108326c29511SRafael Espindola     }
1084778fcc77SRafael Espindola 
1085ef23711eSRafael Espindola     NewGV = copyGlobalValueProto(TypeMap, *DstM, SGV);
1086fda0cee7SDuncan P. N. Exon Smith 
1087fda0cee7SDuncan P. N. Exon Smith     if (DGV && isa<Function>(DGV))
1088fda0cee7SDuncan P. N. Exon Smith       if (auto *NewF = dyn_cast<Function>(NewGV))
1089fda0cee7SDuncan P. N. Exon Smith         OverridingFunctions.insert(NewF);
1090ef23711eSRafael Espindola   }
1091778fcc77SRafael Espindola 
1092778fcc77SRafael Espindola   NewGV->setUnnamedAddr(HasUnnamedAddr);
1093778fcc77SRafael Espindola   NewGV->setVisibility(Visibility);
1094778fcc77SRafael Espindola 
1095778fcc77SRafael Espindola   if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
1096778fcc77SRafael Espindola     if (C)
1097778fcc77SRafael Espindola       NewGO->setComdat(C);
1098439835a6SRafael Espindola 
1099439835a6SRafael Espindola     if (DGV && DGV->hasCommonLinkage() && SGV->hasCommonLinkage())
1100439835a6SRafael Espindola       NewGO->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment()));
1101778fcc77SRafael Espindola   }
1102778fcc77SRafael Espindola 
1103879aeb77SRafael Espindola   if (auto *NewGVar = dyn_cast<GlobalVariable>(NewGV)) {
1104879aeb77SRafael Espindola     auto *DGVar = dyn_cast_or_null<GlobalVariable>(DGV);
1105879aeb77SRafael Espindola     auto *SGVar = dyn_cast<GlobalVariable>(SGV);
1106879aeb77SRafael Espindola     if (DGVar && SGVar && DGVar->isDeclaration() && SGVar->isDeclaration() &&
1107879aeb77SRafael Espindola         (!DGVar->isConstant() || !SGVar->isConstant()))
1108879aeb77SRafael Espindola       NewGVar->setConstant(false);
1109879aeb77SRafael Espindola   }
1110879aeb77SRafael Espindola 
1111778fcc77SRafael Espindola   // Make sure to remember this mapping.
1112778fcc77SRafael Espindola   if (NewGV != DGV) {
1113778fcc77SRafael Espindola     if (DGV) {
1114ad9d0ca8SRafael Espindola       DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
1115778fcc77SRafael Espindola       DGV->eraseFromParent();
1116778fcc77SRafael Espindola     }
1117778fcc77SRafael Espindola     ValueMap[SGV] = NewGV;
1118dad0a645SDavid Majnemer   }
11194e27567aSRafael Espindola 
1120fd38af2dSChandler Carruth   return false;
11214e27567aSRafael Espindola }
11224e27567aSRafael Espindola 
11233e8bc6a8SRafael Espindola static void getArrayElements(const Constant *C,
11243e8bc6a8SRafael Espindola                              SmallVectorImpl<Constant *> &Dest) {
11256705883aSChris Lattner   unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
112600245f42SChris Lattner 
11276705883aSChris Lattner   for (unsigned i = 0; i != NumElements; ++i)
11286705883aSChris Lattner     Dest.push_back(C->getAggregateElement(i));
112900245f42SChris Lattner }
113000245f42SChris Lattner 
1131b1ed91f3SChris Lattner void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
1132b1ed91f3SChris Lattner   // Merge the initializer.
1133d31dc048SRafael Espindola   SmallVector<Constant *, 16> DstElements;
1134d31dc048SRafael Espindola   getArrayElements(AVI.DstInit, DstElements);
1135b1ed91f3SChris Lattner 
1136d31dc048SRafael Espindola   SmallVector<Constant *, 16> SrcElements;
1137d31dc048SRafael Espindola   getArrayElements(AVI.SrcInit, SrcElements);
113800245f42SChris Lattner 
1139b1ed91f3SChris Lattner   ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
1140d31dc048SRafael Espindola 
1141d31dc048SRafael Espindola   StringRef Name = AVI.NewGV->getName();
1142d31dc048SRafael Espindola   bool IsNewStructor =
1143d31dc048SRafael Espindola       (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
1144d31dc048SRafael Espindola       cast<StructType>(NewType->getElementType())->getNumElements() == 3;
1145d31dc048SRafael Espindola 
1146d31dc048SRafael Espindola   for (auto *V : SrcElements) {
1147d31dc048SRafael Espindola     if (IsNewStructor) {
1148d31dc048SRafael Espindola       Constant *Key = V->getAggregateElement(2);
1149d31dc048SRafael Espindola       if (DoNotLinkFromSource.count(Key))
1150d31dc048SRafael Espindola         continue;
1151d31dc048SRafael Espindola     }
1152d31dc048SRafael Espindola     DstElements.push_back(
1153d31dc048SRafael Espindola         MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer));
1154d31dc048SRafael Espindola   }
1155d31dc048SRafael Espindola   if (IsNewStructor) {
1156d31dc048SRafael Espindola     NewType = ArrayType::get(NewType->getElementType(), DstElements.size());
1157d31dc048SRafael Espindola     AVI.NewGV->mutateType(PointerType::get(NewType, 0));
1158d31dc048SRafael Espindola   }
1159d31dc048SRafael Espindola 
1160d31dc048SRafael Espindola   AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements));
1161b1ed91f3SChris Lattner }
1162b1ed91f3SChris Lattner 
116318c89411SRafael Espindola /// Update the initializers in the Dest module now that all globals that may be
116418c89411SRafael Espindola /// referenced are in Dest.
1165ef23711eSRafael Espindola void ModuleLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) {
1166b1ed91f3SChris Lattner   // Figure out what the initializer looks like in the dest module.
1167ef23711eSRafael Espindola   Dst.setInitializer(MapValue(Src.getInitializer(), ValueMap, RF_None, &TypeMap,
1168ef23711eSRafael Espindola                               &ValMaterializer));
1169b1ed91f3SChris Lattner }
1170b1ed91f3SChris Lattner 
117118c89411SRafael Espindola /// Copy the source function over into the dest function and fix up references
117218c89411SRafael Espindola /// to values. At this point we know that Dest is an external function, and
117318c89411SRafael Espindola /// that Src is not.
1174ef23711eSRafael Espindola bool ModuleLinker::linkFunctionBody(Function &Dst, Function &Src) {
1175ef23711eSRafael Espindola   assert(Dst.isDeclaration() && !Src.isDeclaration());
1176361e513dSReid Spencer 
117740d7ebedSRafael Espindola   // Materialize if needed.
11783519da82SRafael Espindola   if (std::error_code EC = Src.materialize())
117940d7ebedSRafael Espindola     return emitError(EC.message());
118040d7ebedSRafael Espindola 
1181869d1ce8SRafael Espindola   // Link in the prefix data.
11823519da82SRafael Espindola   if (Src.hasPrefixData())
1183ef23711eSRafael Espindola     Dst.setPrefixData(MapValue(Src.getPrefixData(), ValueMap, RF_None, &TypeMap,
1184ef23711eSRafael Espindola                                &ValMaterializer));
1185869d1ce8SRafael Espindola 
1186869d1ce8SRafael Espindola   // Link in the prologue data.
11873519da82SRafael Espindola   if (Src.hasPrologueData())
1188ef23711eSRafael Espindola     Dst.setPrologueData(MapValue(Src.getPrologueData(), ValueMap, RF_None,
1189869d1ce8SRafael Espindola                                  &TypeMap, &ValMaterializer));
1190869d1ce8SRafael Espindola 
11917391dde1SChris Lattner   // Go through and convert function arguments over, remembering the mapping.
1192ef23711eSRafael Espindola   Function::arg_iterator DI = Dst.arg_begin();
11933519da82SRafael Espindola   for (Argument &Arg : Src.args()) {
1194a314d1acSRafael Espindola     DI->setName(Arg.getName());  // Copy the name over.
1195361e513dSReid Spencer 
1196b1ed91f3SChris Lattner     // Add a mapping to our mapping.
1197a314d1acSRafael Espindola     ValueMap[&Arg] = DI;
1198a314d1acSRafael Espindola     ++DI;
1199361e513dSReid Spencer   }
1200361e513dSReid Spencer 
12012f0557d0SChris Lattner   // Splice the body of the source function into the dest function.
1202ef23711eSRafael Espindola   Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
1203361e513dSReid Spencer 
1204361e513dSReid Spencer   // At this point, all of the instructions and values of the function are now
1205361e513dSReid Spencer   // copied over.  The only problem is that they are still referencing values in
1206361e513dSReid Spencer   // the Source function as operands.  Loop through all of the operands of the
120743f8d164SChris Lattner   // functions and patch them up to point to the local versions.
1208ef23711eSRafael Espindola   for (BasicBlock &BB : Dst)
1209a314d1acSRafael Espindola     for (Instruction &I : BB)
1210a314d1acSRafael Espindola       RemapInstruction(&I, ValueMap, RF_IgnoreMissingEntries, &TypeMap,
12119f8eff31SRafael Espindola                        &ValMaterializer);
1212cbb91408STanya Lattner 
12137391dde1SChris Lattner   // There is no need to map the arguments anymore.
12143519da82SRafael Espindola   for (Argument &Arg : Src.args())
1215a314d1acSRafael Espindola     ValueMap.erase(&Arg);
1216cbb91408STanya Lattner 
12173519da82SRafael Espindola   Src.Dematerialize();
121840d7ebedSRafael Espindola   return false;
1219361e513dSReid Spencer }
1220361e513dSReid Spencer 
1221ef23711eSRafael Espindola void ModuleLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
1222ef23711eSRafael Espindola   Constant *Aliasee = Src.getAliasee();
12236b238633SRafael Espindola   Constant *Val =
12246b238633SRafael Espindola       MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer);
1225ef23711eSRafael Espindola   Dst.setAliasee(Val);
12262c4a34aeSDavid Chisnall }
1227ef23711eSRafael Espindola 
1228ef23711eSRafael Espindola bool ModuleLinker::linkGlobalValueBody(GlobalValue &Src) {
1229ef23711eSRafael Espindola   Value *Dst = ValueMap[&Src];
1230ef23711eSRafael Espindola   assert(Dst);
1231ef23711eSRafael Espindola   if (auto *F = dyn_cast<Function>(&Src))
1232ef23711eSRafael Espindola     return linkFunctionBody(cast<Function>(*Dst), *F);
1233ef23711eSRafael Espindola   if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
1234ef23711eSRafael Espindola     linkGlobalInit(cast<GlobalVariable>(*Dst), *GVar);
1235ef23711eSRafael Espindola     return false;
1236b1ed91f3SChris Lattner   }
1237ef23711eSRafael Espindola   linkAliasBody(cast<GlobalAlias>(*Dst), cast<GlobalAlias>(Src));
1238ef23711eSRafael Espindola   return false;
1239cbb91408STanya Lattner }
1240b1ed91f3SChris Lattner 
124118c89411SRafael Espindola /// Insert all of the named MDNodes in Src into the Dest module.
1242b1ed91f3SChris Lattner void ModuleLinker::linkNamedMDNodes() {
124366f02413SBill Wendling   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1244b1ed91f3SChris Lattner   for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1245b1ed91f3SChris Lattner        E = SrcM->named_metadata_end(); I != E; ++I) {
124666f02413SBill Wendling     // Don't link module flags here. Do them separately.
124766f02413SBill Wendling     if (&*I == SrcModFlags) continue;
1248b1ed91f3SChris Lattner     NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1249b1ed91f3SChris Lattner     // Add Src elements into Dest node.
1250b1ed91f3SChris Lattner     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
125146d7af57SDuncan P. N. Exon Smith       DestNMD->addOperand(MapMetadata(I->getOperand(i), ValueMap, RF_None,
125246d7af57SDuncan P. N. Exon Smith                                       &TypeMap, &ValMaterializer));
1253b1ed91f3SChris Lattner   }
1254b1ed91f3SChris Lattner }
1255b1ed91f3SChris Lattner 
1256fda0cee7SDuncan P. N. Exon Smith /// Drop DISubprograms that have been superseded.
1257fda0cee7SDuncan P. N. Exon Smith ///
1258fda0cee7SDuncan P. N. Exon Smith /// FIXME: this creates an asymmetric result: we strip losing subprograms from
1259fda0cee7SDuncan P. N. Exon Smith /// DstM, but leave losing subprograms in SrcM.  Instead we should also strip
126046d7af57SDuncan P. N. Exon Smith /// losers from SrcM, but this requires extra plumbing in MapMetadata.
1261fda0cee7SDuncan P. N. Exon Smith void ModuleLinker::stripReplacedSubprograms() {
1262fda0cee7SDuncan P. N. Exon Smith   // Avoid quadratic runtime by returning early when there's nothing to do.
1263fda0cee7SDuncan P. N. Exon Smith   if (OverridingFunctions.empty())
1264fda0cee7SDuncan P. N. Exon Smith     return;
1265fda0cee7SDuncan P. N. Exon Smith 
1266fda0cee7SDuncan P. N. Exon Smith   // Move the functions now, so the set gets cleared even on early returns.
1267fda0cee7SDuncan P. N. Exon Smith   auto Functions = std::move(OverridingFunctions);
1268fda0cee7SDuncan P. N. Exon Smith   OverridingFunctions.clear();
1269fda0cee7SDuncan P. N. Exon Smith 
1270fda0cee7SDuncan P. N. Exon Smith   // Drop subprograms whose functions have been overridden by the new compile
1271fda0cee7SDuncan P. N. Exon Smith   // unit.
1272fda0cee7SDuncan P. N. Exon Smith   NamedMDNode *CompileUnits = DstM->getNamedMetadata("llvm.dbg.cu");
1273fda0cee7SDuncan P. N. Exon Smith   if (!CompileUnits)
1274fda0cee7SDuncan P. N. Exon Smith     return;
1275fda0cee7SDuncan P. N. Exon Smith   for (unsigned I = 0, E = CompileUnits->getNumOperands(); I != E; ++I) {
1276fda0cee7SDuncan P. N. Exon Smith     DICompileUnit CU(CompileUnits->getOperand(I));
1277fda0cee7SDuncan P. N. Exon Smith     assert(CU && "Expected valid compile unit");
1278fda0cee7SDuncan P. N. Exon Smith 
1279fda0cee7SDuncan P. N. Exon Smith     DITypedArray<DISubprogram> SPs(CU.getSubprograms());
1280fda0cee7SDuncan P. N. Exon Smith     assert(SPs && "Expected valid subprogram array");
1281fda0cee7SDuncan P. N. Exon Smith 
1282fda0cee7SDuncan P. N. Exon Smith     SmallVector<Metadata *, 16> NewSPs;
1283fda0cee7SDuncan P. N. Exon Smith     NewSPs.reserve(SPs.getNumElements());
1284fda0cee7SDuncan P. N. Exon Smith     for (unsigned S = 0, SE = SPs.getNumElements(); S != SE; ++S) {
1285fda0cee7SDuncan P. N. Exon Smith       DISubprogram SP = SPs.getElement(S);
1286fda0cee7SDuncan P. N. Exon Smith       if (SP && SP.getFunction() && Functions.count(SP.getFunction()))
1287fda0cee7SDuncan P. N. Exon Smith         continue;
1288fda0cee7SDuncan P. N. Exon Smith 
1289fda0cee7SDuncan P. N. Exon Smith       NewSPs.push_back(SP);
1290fda0cee7SDuncan P. N. Exon Smith     }
1291fda0cee7SDuncan P. N. Exon Smith 
1292fda0cee7SDuncan P. N. Exon Smith     // Redirect operand to the overriding subprogram.
1293fda0cee7SDuncan P. N. Exon Smith     if (NewSPs.size() != SPs.getNumElements())
1294fda0cee7SDuncan P. N. Exon Smith       CU.replaceSubprograms(DIArray(MDNode::get(DstM->getContext(), NewSPs)));
1295fda0cee7SDuncan P. N. Exon Smith   }
1296fda0cee7SDuncan P. N. Exon Smith }
1297fda0cee7SDuncan P. N. Exon Smith 
129818c89411SRafael Espindola /// Merge the linker flags in Src into the Dest module.
129966f02413SBill Wendling bool ModuleLinker::linkModuleFlagsMetadata() {
13000ec72bbcSDaniel Dunbar   // If the source module has no module flags, we are done.
130166f02413SBill Wendling   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
130266f02413SBill Wendling   if (!SrcModFlags) return false;
130366f02413SBill Wendling 
130466f02413SBill Wendling   // If the destination module doesn't have module flags yet, then just copy
130566f02413SBill Wendling   // over the source module's flags.
13060ec72bbcSDaniel Dunbar   NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
130766f02413SBill Wendling   if (DstModFlags->getNumOperands() == 0) {
130866f02413SBill Wendling     for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
130966f02413SBill Wendling       DstModFlags->addOperand(SrcModFlags->getOperand(I));
131066f02413SBill Wendling 
131166f02413SBill Wendling     return false;
131266f02413SBill Wendling   }
131366f02413SBill Wendling 
13140ec72bbcSDaniel Dunbar   // First build a map of the existing module flags and requirements.
1315df55d8baSDuncan P. N. Exon Smith   DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
13160ec72bbcSDaniel Dunbar   SmallSetVector<MDNode*, 16> Requirements;
13170ec72bbcSDaniel Dunbar   for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1318de36e804SDuncan P. N. Exon Smith     MDNode *Op = DstModFlags->getOperand(I);
13195bf8fef5SDuncan P. N. Exon Smith     ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
13200ec72bbcSDaniel Dunbar     MDString *ID = cast<MDString>(Op->getOperand(1));
13210ec72bbcSDaniel Dunbar 
13220ec72bbcSDaniel Dunbar     if (Behavior->getZExtValue() == Module::Require) {
13230ec72bbcSDaniel Dunbar       Requirements.insert(cast<MDNode>(Op->getOperand(2)));
13240ec72bbcSDaniel Dunbar     } else {
1325df55d8baSDuncan P. N. Exon Smith       Flags[ID] = std::make_pair(Op, I);
13260ec72bbcSDaniel Dunbar     }
13270ec72bbcSDaniel Dunbar   }
13280ec72bbcSDaniel Dunbar 
13290ec72bbcSDaniel Dunbar   // Merge in the flags from the source module, and also collect its set of
13300ec72bbcSDaniel Dunbar   // requirements.
133166f02413SBill Wendling   bool HasErr = false;
13320ec72bbcSDaniel Dunbar   for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1333de36e804SDuncan P. N. Exon Smith     MDNode *SrcOp = SrcModFlags->getOperand(I);
13345bf8fef5SDuncan P. N. Exon Smith     ConstantInt *SrcBehavior =
13355bf8fef5SDuncan P. N. Exon Smith         mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
13360ec72bbcSDaniel Dunbar     MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1337df55d8baSDuncan P. N. Exon Smith     MDNode *DstOp;
1338df55d8baSDuncan P. N. Exon Smith     unsigned DstIndex;
1339df55d8baSDuncan P. N. Exon Smith     std::tie(DstOp, DstIndex) = Flags.lookup(ID);
13400ec72bbcSDaniel Dunbar     unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
134166f02413SBill Wendling 
13420ec72bbcSDaniel Dunbar     // If this is a requirement, add it and continue.
13430ec72bbcSDaniel Dunbar     if (SrcBehaviorValue == Module::Require) {
13440ec72bbcSDaniel Dunbar       // If the destination module does not already have this requirement, add
13450ec72bbcSDaniel Dunbar       // it.
13460ec72bbcSDaniel Dunbar       if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
13470ec72bbcSDaniel Dunbar         DstModFlags->addOperand(SrcOp);
13480ec72bbcSDaniel Dunbar       }
13490ec72bbcSDaniel Dunbar       continue;
13500ec72bbcSDaniel Dunbar     }
135166f02413SBill Wendling 
13520ec72bbcSDaniel Dunbar     // If there is no existing flag with this ID, just add it.
13530ec72bbcSDaniel Dunbar     if (!DstOp) {
1354df55d8baSDuncan P. N. Exon Smith       Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
13550ec72bbcSDaniel Dunbar       DstModFlags->addOperand(SrcOp);
13560ec72bbcSDaniel Dunbar       continue;
13570ec72bbcSDaniel Dunbar     }
135866f02413SBill Wendling 
13590ec72bbcSDaniel Dunbar     // Otherwise, perform a merge.
13605bf8fef5SDuncan P. N. Exon Smith     ConstantInt *DstBehavior =
13615bf8fef5SDuncan P. N. Exon Smith         mdconst::extract<ConstantInt>(DstOp->getOperand(0));
13620ec72bbcSDaniel Dunbar     unsigned DstBehaviorValue = DstBehavior->getZExtValue();
13630ec72bbcSDaniel Dunbar 
13640ec72bbcSDaniel Dunbar     // If either flag has override behavior, handle it first.
13650ec72bbcSDaniel Dunbar     if (DstBehaviorValue == Module::Override) {
13660ec72bbcSDaniel Dunbar       // Diagnose inconsistent flags which both have override behavior.
13670ec72bbcSDaniel Dunbar       if (SrcBehaviorValue == Module::Override &&
13680ec72bbcSDaniel Dunbar           SrcOp->getOperand(2) != DstOp->getOperand(2)) {
13690ec72bbcSDaniel Dunbar         HasErr |= emitError("linking module flags '" + ID->getString() +
13700ec72bbcSDaniel Dunbar                             "': IDs have conflicting override values");
13710ec72bbcSDaniel Dunbar       }
13720ec72bbcSDaniel Dunbar       continue;
13730ec72bbcSDaniel Dunbar     } else if (SrcBehaviorValue == Module::Override) {
13740ec72bbcSDaniel Dunbar       // Update the destination flag to that of the source.
1375df55d8baSDuncan P. N. Exon Smith       DstModFlags->setOperand(DstIndex, SrcOp);
1376df55d8baSDuncan P. N. Exon Smith       Flags[ID].first = SrcOp;
13770ec72bbcSDaniel Dunbar       continue;
13780ec72bbcSDaniel Dunbar     }
13790ec72bbcSDaniel Dunbar 
13800ec72bbcSDaniel Dunbar     // Diagnose inconsistent merge behavior types.
13810ec72bbcSDaniel Dunbar     if (SrcBehaviorValue != DstBehaviorValue) {
13820ec72bbcSDaniel Dunbar       HasErr |= emitError("linking module flags '" + ID->getString() +
138366f02413SBill Wendling                           "': IDs have conflicting behaviors");
13840ec72bbcSDaniel Dunbar       continue;
138566f02413SBill Wendling     }
138666f02413SBill Wendling 
1387df55d8baSDuncan P. N. Exon Smith     auto replaceDstValue = [&](MDNode *New) {
1388df55d8baSDuncan P. N. Exon Smith       Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
1389df55d8baSDuncan P. N. Exon Smith       MDNode *Flag = MDNode::get(DstM->getContext(), FlagOps);
1390df55d8baSDuncan P. N. Exon Smith       DstModFlags->setOperand(DstIndex, Flag);
1391df55d8baSDuncan P. N. Exon Smith       Flags[ID].first = Flag;
1392df55d8baSDuncan P. N. Exon Smith     };
1393df55d8baSDuncan P. N. Exon Smith 
13940ec72bbcSDaniel Dunbar     // Perform the merge for standard behavior types.
13950ec72bbcSDaniel Dunbar     switch (SrcBehaviorValue) {
13960ec72bbcSDaniel Dunbar     case Module::Require:
13972a30d788SCraig Topper     case Module::Override: llvm_unreachable("not possible");
13980ec72bbcSDaniel Dunbar     case Module::Error: {
13990ec72bbcSDaniel Dunbar       // Emit an error if the values differ.
14000ec72bbcSDaniel Dunbar       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
14010ec72bbcSDaniel Dunbar         HasErr |= emitError("linking module flags '" + ID->getString() +
14020ec72bbcSDaniel Dunbar                             "': IDs have conflicting values");
140366f02413SBill Wendling       }
14040ec72bbcSDaniel Dunbar       continue;
140566f02413SBill Wendling     }
14060ec72bbcSDaniel Dunbar     case Module::Warning: {
14070ec72bbcSDaniel Dunbar       // Emit a warning if the values differ.
14080ec72bbcSDaniel Dunbar       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1409d12b4a33SRafael Espindola         emitWarning("linking module flags '" + ID->getString() +
1410d12b4a33SRafael Espindola                     "': IDs have conflicting values");
1411e17f3708SEli Bendersky       }
14120ec72bbcSDaniel Dunbar       continue;
14130ec72bbcSDaniel Dunbar     }
1414d77d9fb0SDaniel Dunbar     case Module::Append: {
1415d77d9fb0SDaniel Dunbar       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1416d77d9fb0SDaniel Dunbar       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
14175bf8fef5SDuncan P. N. Exon Smith       SmallVector<Metadata *, 8> MDs;
14185bf8fef5SDuncan P. N. Exon Smith       MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
14195bf8fef5SDuncan P. N. Exon Smith       for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
14205bf8fef5SDuncan P. N. Exon Smith         MDs.push_back(DstValue->getOperand(i));
14215bf8fef5SDuncan P. N. Exon Smith       for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
14225bf8fef5SDuncan P. N. Exon Smith         MDs.push_back(SrcValue->getOperand(i));
1423df55d8baSDuncan P. N. Exon Smith 
1424df55d8baSDuncan P. N. Exon Smith       replaceDstValue(MDNode::get(DstM->getContext(), MDs));
1425d77d9fb0SDaniel Dunbar       break;
1426d77d9fb0SDaniel Dunbar     }
1427d77d9fb0SDaniel Dunbar     case Module::AppendUnique: {
14285bf8fef5SDuncan P. N. Exon Smith       SmallSetVector<Metadata *, 16> Elts;
1429d77d9fb0SDaniel Dunbar       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1430d77d9fb0SDaniel Dunbar       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1431d77d9fb0SDaniel Dunbar       for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1432d77d9fb0SDaniel Dunbar         Elts.insert(DstValue->getOperand(i));
1433d77d9fb0SDaniel Dunbar       for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1434d77d9fb0SDaniel Dunbar         Elts.insert(SrcValue->getOperand(i));
1435df55d8baSDuncan P. N. Exon Smith 
1436df55d8baSDuncan P. N. Exon Smith       replaceDstValue(MDNode::get(DstM->getContext(),
14375bf8fef5SDuncan P. N. Exon Smith                                   makeArrayRef(Elts.begin(), Elts.end())));
1438d77d9fb0SDaniel Dunbar       break;
1439d77d9fb0SDaniel Dunbar     }
144066f02413SBill Wendling     }
144166f02413SBill Wendling   }
144266f02413SBill Wendling 
14430ec72bbcSDaniel Dunbar   // Check all of the requirements.
14440ec72bbcSDaniel Dunbar   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
14450ec72bbcSDaniel Dunbar     MDNode *Requirement = Requirements[I];
14460ec72bbcSDaniel Dunbar     MDString *Flag = cast<MDString>(Requirement->getOperand(0));
14475bf8fef5SDuncan P. N. Exon Smith     Metadata *ReqValue = Requirement->getOperand(1);
14480ec72bbcSDaniel Dunbar 
1449df55d8baSDuncan P. N. Exon Smith     MDNode *Op = Flags[Flag].first;
14500ec72bbcSDaniel Dunbar     if (!Op || Op->getOperand(2) != ReqValue) {
14510ec72bbcSDaniel Dunbar       HasErr |= emitError("linking module flags '" + Flag->getString() +
14529273b539SBill Wendling                           "': does not have the required value");
14530ec72bbcSDaniel Dunbar       continue;
145466f02413SBill Wendling     }
145566f02413SBill Wendling   }
145666f02413SBill Wendling 
145766f02413SBill Wendling   return HasErr;
145866f02413SBill Wendling }
145966f02413SBill Wendling 
1460b1ed91f3SChris Lattner bool ModuleLinker::run() {
146166f02413SBill Wendling   assert(DstM && "Null destination module");
146266f02413SBill Wendling   assert(SrcM && "Null source module");
1463b1ed91f3SChris Lattner 
1464b1ed91f3SChris Lattner   // Inherit the target data from the source module if the destination module
1465b1ed91f3SChris Lattner   // doesn't have one already.
1466f863ee29SRafael Espindola   if (!DstM->getDataLayout() && SrcM->getDataLayout())
1467b1ed91f3SChris Lattner     DstM->setDataLayout(SrcM->getDataLayout());
1468b1ed91f3SChris Lattner 
1469b1ed91f3SChris Lattner   // Copy the target triple from the source to dest if the dest's is empty.
1470b1ed91f3SChris Lattner   if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1471b1ed91f3SChris Lattner     DstM->setTargetTriple(SrcM->getTargetTriple());
1472b1ed91f3SChris Lattner 
1473f863ee29SRafael Espindola   if (SrcM->getDataLayout() && DstM->getDataLayout() &&
1474ae593f15SRafael Espindola       *SrcM->getDataLayout() != *DstM->getDataLayout()) {
1475d12b4a33SRafael Espindola     emitWarning("Linking two modules of different data layouts: '" +
1476d12b4a33SRafael Espindola                 SrcM->getModuleIdentifier() + "' is '" +
1477d12b4a33SRafael Espindola                 SrcM->getDataLayoutStr() + "' whereas '" +
1478d12b4a33SRafael Espindola                 DstM->getModuleIdentifier() + "' is '" +
1479d12b4a33SRafael Espindola                 DstM->getDataLayoutStr() + "'\n");
1480e17f3708SEli Bendersky   }
1481b1ed91f3SChris Lattner   if (!SrcM->getTargetTriple().empty() &&
1482b1ed91f3SChris Lattner       DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1483d12b4a33SRafael Espindola     emitWarning("Linking two modules of different target triples: " +
1484d12b4a33SRafael Espindola                 SrcM->getModuleIdentifier() + "' is '" +
1485d12b4a33SRafael Espindola                 SrcM->getTargetTriple() + "' whereas '" +
1486d12b4a33SRafael Espindola                 DstM->getModuleIdentifier() + "' is '" +
1487d12b4a33SRafael Espindola                 DstM->getTargetTriple() + "'\n");
1488e17f3708SEli Bendersky   }
1489b1ed91f3SChris Lattner 
1490b1ed91f3SChris Lattner   // Append the module inline asm string.
1491b1ed91f3SChris Lattner   if (!SrcM->getModuleInlineAsm().empty()) {
1492b1ed91f3SChris Lattner     if (DstM->getModuleInlineAsm().empty())
1493b1ed91f3SChris Lattner       DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1494b1ed91f3SChris Lattner     else
1495b1ed91f3SChris Lattner       DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1496b1ed91f3SChris Lattner                                SrcM->getModuleInlineAsm());
1497b1ed91f3SChris Lattner   }
1498b1ed91f3SChris Lattner 
1499b1ed91f3SChris Lattner   // Loop over all of the linked values to compute type mappings.
1500b1ed91f3SChris Lattner   computeTypeMapping();
1501b1ed91f3SChris Lattner 
1502dad0a645SDavid Majnemer   ComdatsChosen.clear();
15035106ce78SDavid Blaikie   for (const auto &SMEC : SrcM->getComdatSymbolTable()) {
1504dad0a645SDavid Majnemer     const Comdat &C = SMEC.getValue();
1505dad0a645SDavid Majnemer     if (ComdatsChosen.count(&C))
1506dad0a645SDavid Majnemer       continue;
1507dad0a645SDavid Majnemer     Comdat::SelectionKind SK;
1508dad0a645SDavid Majnemer     bool LinkFromSrc;
1509dad0a645SDavid Majnemer     if (getComdatResult(&C, SK, LinkFromSrc))
1510dad0a645SDavid Majnemer       return true;
1511dad0a645SDavid Majnemer     ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1512dad0a645SDavid Majnemer   }
1513dad0a645SDavid Majnemer 
151409d84addSDuncan P. N. Exon Smith   // Upgrade mismatched global arrays.
151509d84addSDuncan P. N. Exon Smith   upgradeMismatchedGlobals();
151609d84addSDuncan P. N. Exon Smith 
1517b1ed91f3SChris Lattner   // Insert all of the globals in src into the DstM module... without linking
1518b1ed91f3SChris Lattner   // initializers (which could refer to functions not yet mapped over).
1519b1ed91f3SChris Lattner   for (Module::global_iterator I = SrcM->global_begin(),
1520b1ed91f3SChris Lattner        E = SrcM->global_end(); I != E; ++I)
1521778fcc77SRafael Espindola     if (linkGlobalValueProto(I))
1522b1ed91f3SChris Lattner       return true;
1523b1ed91f3SChris Lattner 
1524b1ed91f3SChris Lattner   // Link the functions together between the two modules, without doing function
1525b1ed91f3SChris Lattner   // bodies... this just adds external function prototypes to the DstM
1526b1ed91f3SChris Lattner   // function...  We do this so that when we begin processing function bodies,
1527b1ed91f3SChris Lattner   // all of the global values that may be referenced are available in our
1528b1ed91f3SChris Lattner   // ValueMap.
1529b1ed91f3SChris Lattner   for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1530778fcc77SRafael Espindola     if (linkGlobalValueProto(I))
1531b1ed91f3SChris Lattner       return true;
1532b1ed91f3SChris Lattner 
1533b1ed91f3SChris Lattner   // If there were any aliases, link them now.
1534b1ed91f3SChris Lattner   for (Module::alias_iterator I = SrcM->alias_begin(),
1535b1ed91f3SChris Lattner        E = SrcM->alias_end(); I != E; ++I)
1536778fcc77SRafael Espindola     if (linkGlobalValueProto(I))
1537b1ed91f3SChris Lattner       return true;
1538b1ed91f3SChris Lattner 
1539b1ed91f3SChris Lattner   for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1540b1ed91f3SChris Lattner     linkAppendingVarInit(AppendingVars[i]);
1541b1ed91f3SChris Lattner 
1542beadd56aSRafael Espindola   for (const auto &Entry : DstM->getComdatSymbolTable()) {
1543beadd56aSRafael Espindola     const Comdat &C = Entry.getValue();
1544beadd56aSRafael Espindola     if (C.getSelectionKind() == Comdat::Any)
1545beadd56aSRafael Espindola       continue;
1546beadd56aSRafael Espindola     const GlobalValue *GV = SrcM->getNamedValue(C.getName());
1547beadd56aSRafael Espindola     assert(GV);
1548beadd56aSRafael Espindola     MapValue(GV, ValueMap, RF_None, &TypeMap, &ValMaterializer);
1549beadd56aSRafael Espindola   }
1550beadd56aSRafael Espindola 
1551b1ed91f3SChris Lattner   // Link in the function bodies that are defined in the source module into
1552b1ed91f3SChris Lattner   // DstM.
1553f97d0cbeSRafael Espindola   for (Function &SF : *SrcM) {
1554d4bcefc7SRafael Espindola     // Skip if no body (function is external).
1555f97d0cbeSRafael Espindola     if (SF.isDeclaration())
1556d4bcefc7SRafael Espindola       continue;
1557d4bcefc7SRafael Espindola 
1558f97d0cbeSRafael Espindola     // Skip if not linking from source.
1559f97d0cbeSRafael Espindola     if (DoNotLinkFromSource.count(&SF))
1560f97d0cbeSRafael Espindola       continue;
1561f97d0cbeSRafael Espindola 
1562ef23711eSRafael Espindola     if (linkGlobalValueBody(SF))
156340d7ebedSRafael Espindola       return true;
1564b1ed91f3SChris Lattner   }
1565b1ed91f3SChris Lattner 
1566b1ed91f3SChris Lattner   // Resolve all uses of aliases with aliasees.
1567ef23711eSRafael Espindola   for (GlobalAlias &Src : SrcM->aliases()) {
1568ef23711eSRafael Espindola     if (DoNotLinkFromSource.count(&Src))
1569ef23711eSRafael Espindola       continue;
1570ef23711eSRafael Espindola     linkGlobalValueBody(Src);
1571ef23711eSRafael Espindola   }
1572b1ed91f3SChris Lattner 
1573fda0cee7SDuncan P. N. Exon Smith   // Strip replaced subprograms before linking together compile units.
1574fda0cee7SDuncan P. N. Exon Smith   stripReplacedSubprograms();
1575fda0cee7SDuncan P. N. Exon Smith 
157666f02413SBill Wendling   // Remap all of the named MDNodes in Src into the DstM module. We do this
15776ddbb2e2SDevang Patel   // after linking GlobalValues so that MDNodes that reference GlobalValues
15786ddbb2e2SDevang Patel   // are properly remapped.
15796ddbb2e2SDevang Patel   linkNamedMDNodes();
15806ddbb2e2SDevang Patel 
158166f02413SBill Wendling   // Merge the module flags into the DstM module.
158266f02413SBill Wendling   if (linkModuleFlagsMetadata())
158366f02413SBill Wendling     return true;
158466f02413SBill Wendling 
158591686d6dSBill Wendling   // Update the initializers in the DstM module now that all globals that may
158691686d6dSBill Wendling   // be referenced are in DstM.
1587ef23711eSRafael Espindola   for (GlobalVariable &Src : SrcM->globals()) {
1588ef23711eSRafael Espindola     // Only process initialized GV's or ones not already in dest.
1589ef23711eSRafael Espindola     if (!Src.hasInitializer() || DoNotLinkFromSource.count(&Src))
1590ef23711eSRafael Espindola       continue;
1591ef23711eSRafael Espindola     linkGlobalValueBody(Src);
1592ef23711eSRafael Espindola   }
159391686d6dSBill Wendling 
15940a48b877STanya Lattner   // Process vector of lazily linked in functions.
1595ef23711eSRafael Espindola   while (!LazilyLinkGlobalValues.empty()) {
1596ef23711eSRafael Espindola     GlobalValue *SGV = LazilyLinkGlobalValues.back();
1597ef23711eSRafael Espindola     LazilyLinkGlobalValues.pop_back();
15980a48b877STanya Lattner 
15999573a9cfSRafael Espindola     assert(!SGV->isDeclaration() && "users should not pass down decls");
1600ef23711eSRafael Espindola     if (linkGlobalValueBody(*SGV))
160140d7ebedSRafael Espindola       return true;
16020a48b877STanya Lattner   }
16030a48b877STanya Lattner 
16042609888fSAnton Korobeynikov   return false;
16052609888fSAnton Korobeynikov }
1606361e513dSReid Spencer 
160731ad468dSRafael Espindola Linker::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
160831ad468dSRafael Espindola     : ETypes(E), IsPacked(P) {}
160931ad468dSRafael Espindola 
161031ad468dSRafael Espindola Linker::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
161131ad468dSRafael Espindola     : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
161231ad468dSRafael Espindola 
161331ad468dSRafael Espindola bool Linker::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
161431ad468dSRafael Espindola   if (IsPacked != That.IsPacked)
161531ad468dSRafael Espindola     return false;
161631ad468dSRafael Espindola   if (ETypes != That.ETypes)
161731ad468dSRafael Espindola     return false;
161831ad468dSRafael Espindola   return true;
161931ad468dSRafael Espindola }
162031ad468dSRafael Espindola 
162131ad468dSRafael Espindola bool Linker::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
162231ad468dSRafael Espindola   return !this->operator==(That);
162331ad468dSRafael Espindola }
162431ad468dSRafael Espindola 
162531ad468dSRafael Espindola StructType *Linker::StructTypeKeyInfo::getEmptyKey() {
162631ad468dSRafael Espindola   return DenseMapInfo<StructType *>::getEmptyKey();
162731ad468dSRafael Espindola }
162831ad468dSRafael Espindola 
162931ad468dSRafael Espindola StructType *Linker::StructTypeKeyInfo::getTombstoneKey() {
163031ad468dSRafael Espindola   return DenseMapInfo<StructType *>::getTombstoneKey();
163131ad468dSRafael Espindola }
163231ad468dSRafael Espindola 
163331ad468dSRafael Espindola unsigned Linker::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
163431ad468dSRafael Espindola   return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
163531ad468dSRafael Espindola                       Key.IsPacked);
163631ad468dSRafael Espindola }
163731ad468dSRafael Espindola 
163831ad468dSRafael Espindola unsigned Linker::StructTypeKeyInfo::getHashValue(const StructType *ST) {
163931ad468dSRafael Espindola   return getHashValue(KeyTy(ST));
164031ad468dSRafael Espindola }
164131ad468dSRafael Espindola 
164231ad468dSRafael Espindola bool Linker::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
164331ad468dSRafael Espindola                                         const StructType *RHS) {
164431ad468dSRafael Espindola   if (RHS == getEmptyKey() || RHS == getTombstoneKey())
164531ad468dSRafael Espindola     return false;
164631ad468dSRafael Espindola   return LHS == KeyTy(RHS);
164731ad468dSRafael Espindola }
164831ad468dSRafael Espindola 
164931ad468dSRafael Espindola bool Linker::StructTypeKeyInfo::isEqual(const StructType *LHS,
165031ad468dSRafael Espindola                                         const StructType *RHS) {
165131ad468dSRafael Espindola   if (RHS == getEmptyKey())
165231ad468dSRafael Espindola     return LHS == getEmptyKey();
165331ad468dSRafael Espindola 
165431ad468dSRafael Espindola   if (RHS == getTombstoneKey())
165531ad468dSRafael Espindola     return LHS == getTombstoneKey();
165631ad468dSRafael Espindola 
165731ad468dSRafael Espindola   return KeyTy(LHS) == KeyTy(RHS);
165831ad468dSRafael Espindola }
165931ad468dSRafael Espindola 
166031ad468dSRafael Espindola void Linker::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
166131ad468dSRafael Espindola   assert(!Ty->isOpaque());
16623280a5d9SBenjamin Kramer   NonOpaqueStructTypes.insert(Ty);
166331ad468dSRafael Espindola }
166431ad468dSRafael Espindola 
166531ad468dSRafael Espindola void Linker::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
166631ad468dSRafael Espindola   assert(Ty->isOpaque());
166731ad468dSRafael Espindola   OpaqueStructTypes.insert(Ty);
166831ad468dSRafael Espindola }
166931ad468dSRafael Espindola 
167031ad468dSRafael Espindola StructType *
167131ad468dSRafael Espindola Linker::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
167231ad468dSRafael Espindola                                                bool IsPacked) {
167331ad468dSRafael Espindola   Linker::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
167431ad468dSRafael Espindola   auto I = NonOpaqueStructTypes.find_as(Key);
167531ad468dSRafael Espindola   if (I == NonOpaqueStructTypes.end())
167631ad468dSRafael Espindola     return nullptr;
16773280a5d9SBenjamin Kramer   return *I;
167831ad468dSRafael Espindola }
167931ad468dSRafael Espindola 
168031ad468dSRafael Espindola bool Linker::IdentifiedStructTypeSet::hasType(StructType *Ty) {
168131ad468dSRafael Espindola   if (Ty->isOpaque())
168231ad468dSRafael Espindola     return OpaqueStructTypes.count(Ty);
168331ad468dSRafael Espindola   auto I = NonOpaqueStructTypes.find(Ty);
168431ad468dSRafael Espindola   if (I == NonOpaqueStructTypes.end())
168531ad468dSRafael Espindola     return false;
16863280a5d9SBenjamin Kramer   return *I == Ty;
168731ad468dSRafael Espindola }
168831ad468dSRafael Espindola 
16895cb9c82aSRafael Espindola void Linker::init(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
16905cb9c82aSRafael Espindola   this->Composite = M;
16915cb9c82aSRafael Espindola   this->DiagnosticHandler = DiagnosticHandler;
1692a4e85e3dSRafael Espindola 
1693a4e85e3dSRafael Espindola   TypeFinder StructTypes;
1694a4e85e3dSRafael Espindola   StructTypes.run(*M, true);
169531ad468dSRafael Espindola   for (StructType *Ty : StructTypes) {
169631ad468dSRafael Espindola     if (Ty->isOpaque())
169731ad468dSRafael Espindola       IdentifiedStructTypes.addOpaque(Ty);
169831ad468dSRafael Espindola     else
169931ad468dSRafael Espindola       IdentifiedStructTypes.addNonOpaque(Ty);
170031ad468dSRafael Espindola   }
1701aa9918aaSRafael Espindola }
17023df61b7bSRafael Espindola 
17035cb9c82aSRafael Espindola Linker::Linker(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
17045cb9c82aSRafael Espindola   init(M, DiagnosticHandler);
17055cb9c82aSRafael Espindola }
17065cb9c82aSRafael Espindola 
17075cb9c82aSRafael Espindola Linker::Linker(Module *M) {
17085cb9c82aSRafael Espindola   init(M, [this](const DiagnosticInfo &DI) {
17095cb9c82aSRafael Espindola     Composite->getContext().diagnose(DI);
17105cb9c82aSRafael Espindola   });
17115cb9c82aSRafael Espindola }
17125cb9c82aSRafael Espindola 
17133df61b7bSRafael Espindola Linker::~Linker() {
17143df61b7bSRafael Espindola }
17153df61b7bSRafael Espindola 
171691e6f6e1SBill Wendling void Linker::deleteModule() {
171791e6f6e1SBill Wendling   delete Composite;
17182617dcceSCraig Topper   Composite = nullptr;
171991e6f6e1SBill Wendling }
172091e6f6e1SBill Wendling 
17219f8eff31SRafael Espindola bool Linker::linkInModule(Module *Src) {
1722a4e85e3dSRafael Espindola   ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src,
1723a4e85e3dSRafael Espindola                          DiagnosticHandler);
1724*dab999d5SManman Ren   bool RetCode = TheLinker.run();
1725*dab999d5SManman Ren   Composite->dropTriviallyDeadConstantArrays();
1726*dab999d5SManman Ren   return RetCode;
17273df61b7bSRafael Espindola }
17283df61b7bSRafael Espindola 
1729b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
1730b1ed91f3SChris Lattner // LinkModules entrypoint.
1731b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
1732b1ed91f3SChris Lattner 
173318c89411SRafael Espindola /// This function links two modules together, with the resulting Dest module
173418c89411SRafael Espindola /// modified to be the composite of the two input modules. If an error occurs,
173518c89411SRafael Espindola /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
173618c89411SRafael Espindola /// Upon failure, the Dest module could be in a modified state, and shouldn't be
173718c89411SRafael Espindola /// relied on to be consistent.
17389f8eff31SRafael Espindola bool Linker::LinkModules(Module *Dest, Module *Src,
17394160f5d3SRafael Espindola                          DiagnosticHandlerFunction DiagnosticHandler) {
17404160f5d3SRafael Espindola   Linker L(Dest, DiagnosticHandler);
17419f8eff31SRafael Espindola   return L.linkInModule(Src);
17424160f5d3SRafael Espindola }
17434160f5d3SRafael Espindola 
17449f8eff31SRafael Espindola bool Linker::LinkModules(Module *Dest, Module *Src) {
1745287f18b4SRafael Espindola   Linker L(Dest);
17469f8eff31SRafael Espindola   return L.linkInModule(Src);
1747361e513dSReid Spencer }
1748a3aeb980SBill Wendling 
1749a3aeb980SBill Wendling //===----------------------------------------------------------------------===//
1750a3aeb980SBill Wendling // C API.
1751a3aeb980SBill Wendling //===----------------------------------------------------------------------===//
1752a3aeb980SBill Wendling 
1753a3aeb980SBill Wendling LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1754c6c58d5eSRafael Espindola                          unsigned Unused, char **OutMessages) {
175598ab63ceSRafael Espindola   Module *D = unwrap(Dest);
175698ab63ceSRafael Espindola   std::string Message;
17574160f5d3SRafael Espindola   raw_string_ostream Stream(Message);
17584160f5d3SRafael Espindola   DiagnosticPrinterRawOStream DP(Stream);
17594160f5d3SRafael Espindola 
17604160f5d3SRafael Espindola   LLVMBool Result = Linker::LinkModules(
17619f8eff31SRafael Espindola       D, unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
176298ab63ceSRafael Espindola 
176398ab63ceSRafael Espindola   if (OutMessages && Result)
176498ab63ceSRafael Espindola     *OutMessages = strdup(Message.c_str());
1765a3aeb980SBill Wendling   return Result;
1766a3aeb980SBill Wendling }
1767